@stacksjs/rpx 0.11.5 → 0.11.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,156 @@
1
+ import{a as G,b as Rn,c as tc,d as a,e as $S,f as ei,g as sS,h as Y$,i as ic,j as g0,k as pr,l as d$,m as wS,n as z$,o as I$}from"./chunk-jpf41gb9.js";import{execSync as Aa}from"node:child_process";import*as Ri from"node:http";import*as X$ from"node:http2";import*as P$ from"node:net";import*as O from"node:process";var S={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)};var jn=(t,i)=>(n)=>`\x1B[${t}m${n}\x1B[${i}m`,jt={bold:jn(1,22),dim:jn(2,22),green:jn(32,39),cyan:jn(36,39)};import{homedir as Qf}from"node:os";import{join as te,resolve as um}from"node:path";import{existsSync as Sc,statSync as Rc}from"fs";import{existsSync as Q$,mkdirSync as _a,readdirSync as Ua,readFileSync as ts,writeFileSync as ja}from"fs";import{homedir as Bi}from"os";import{dirname as da,resolve as Bt}from"path";import lr from"process";import{existsSync as Bc,statSync as Nc}from"fs";import{existsSync as df,mkdirSync as is,readdirSync as ns,writeFileSync as rs}from"fs";import{homedir as Ni}from"os";import{dirname as Fc,resolve as wt}from"path";import ai from"process";import{join as fs,relative as es,resolve as Jc}from"path";import Xn from"process";import{existsSync as hh,mkdirSync as Da,readdirSync as Oa,writeFileSync as La}from"fs";import{homedir as uf}from"os";import{dirname as oa,resolve as st}from"path";import hn from"process";import{join as cs,relative as hs,resolve as Cc}from"path";import Pn from"process";import{existsSync as lh,mkdirSync as va,readdirSync as pa,writeFileSync as Qa}from"fs";import{dirname as iA,resolve as vn}from"path";import If from"process";import{Buffer as ci}from"buffer";import{createCipheriv as ls,createDecipheriv as $s,randomBytes as yf}from"crypto";import{closeSync as af,createReadStream as _c,createWriteStream as ss,existsSync as Af,fsyncSync as Uc,openSync as jc,writeFileSync as ws}from"fs";import{access as us,constants as Wc,mkdir as ys,readdir as Wn,rename as Yc,stat as Fi,unlink as Yn,writeFile as mf}from"fs/promises";import{join as Ji}from"path";import rt from"process";import{pipeline as as}from"stream/promises";import{createGzip as dc}from"zlib";import Ci from"process";import Lt from"process";import{Buffer as xt}from"buffer";import{createCipheriv as As,createDecipheriv as ms,randomBytes as Ef}from"crypto";import{closeSync as Tf,createReadStream as Ic,createWriteStream as Es,existsSync as dn,fsyncSync as Zc,openSync as Hc,writeFileSync as Ts}from"fs";import{access as Ss,constants as Mc,mkdir as Rs,readdir as In,rename as zc,stat as _i,unlink as Zn,writeFile as Sf}from"fs/promises";import{isAbsolute as Bs,join as Ui,resolve as Ns}from"path";import _ from"process";import{pipeline as Fs}from"stream/promises";import{createGzip as Gc}from"zlib";import ji from"process";import kt from"process";import Hn from"process";import{existsSync as Mn}from"fs";import{resolve as Rf}from"path";import{existsSync as Js}from"fs";import{existsSync as Cs,readdirSync as _s}from"fs";import{extname as Bf,resolve as Kc}from"path";import Us from"process";import{join as js,relative as Ws,resolve as qc}from"path";import pn from"process";import{Buffer as Dt}from"buffer";import{createCipheriv as Ys,createDecipheriv as ds,randomBytes as Nf}from"crypto";import{closeSync as Ff,createReadStream as xc,createWriteStream as Is,existsSync as zn,fsyncSync as Dc,openSync as Oc,writeFileSync as Zs}from"fs";import{access as Hs,constants as Lc,mkdir as Ms,readdir as Gn,rename as kc,stat as Wi,unlink as Kn,writeFile as Jf}from"fs/promises";import{isAbsolute as zs,join as Yi,resolve as Gs}from"path";import U from"process";import{pipeline as Ks}from"stream/promises";import{createGzip as Vc}from"zlib";import di from"process";import Vt from"process";import xn from"process";import{existsSync as Dn}from"fs";import{resolve as Yf}from"path";import{existsSync as fu}from"fs";class eh{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 n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}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(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Sc(t))return!0;return Rc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Sc(n)?Rc(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class ch{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}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((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var bn=new eh,Lf=new ch;var qs=Object.defineProperty,xs=(t)=>t;function Ds(t,i){this[t]=xs.bind(null,i)}var Os=(t,i)=>{for(var n in i)qs(t,n,{get:i[n],enumerable:!0,configurable:!0,set:Ds.bind(i,n)})},Ls=(t,i)=>()=>(t&&(i=t(t=0)),i),$h={};Os($h,{withErrorRecovery:()=>uh,tryLoadConfig:()=>uw,loadConfigWithResult:()=>sw,loadConfig:()=>Eh,isRetryableError:()=>fw,isConfigNotFoundError:()=>rw,isBunfigError:()=>yh,globalPerformanceMonitor:()=>sn,globalCache:()=>Ii,getEnvOrDefault:()=>ew,generateConfigTypes:()=>yw,defaultGeneratedDir:()=>Ch,defaultConfigDir:()=>Jh,deepMergeWithArrayStrategy:()=>bf,deepMerge:()=>ah,createLibraryConfig:()=>aw,config:()=>ww,bunfigPlugin:()=>Aw,applyEnvVarsToConfig:()=>cn,TypeGenerationError:()=>qf,SchemaValidationError:()=>$n,PluginError:()=>Df,PerformanceMonitor:()=>Vf,FileSystemError:()=>Kf,ErrorFactory:()=>hi,EnvVarError:()=>fr,EnvProcessor:()=>$r,ConfigValidator:()=>Xf,ConfigValidationError:()=>zf,ConfigNotFoundError:()=>rr,ConfigMergeError:()=>Gf,ConfigLoader:()=>Pf,ConfigLoadError:()=>ln,ConfigFileLoader:()=>sr,ConfigCache:()=>kf,CacheUtils:()=>Sh,BunfigError:()=>Et,BrowserConfigError:()=>xf,ArrayMergeStrategies:()=>Nh});class kf{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 n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}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(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Bc(t))return!0;return Nc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Bc(n)?Nc(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Vf{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}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((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function ks(t,i={}){let r=Object.keys(i).sort().map((f)=>`${f}:${i[f]}`).join("|");return r?`${t}:${r}`:t}function Vs(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function os(t){return t.getStats().size*2}function of(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&x(i[0])&&"id"in i[0]&&i[0].id===3&&x(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(x(i)&&x(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(x(t)&&"arr"in t&&Array.isArray(t.arr)&&x(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&x(i[0])&&x(t[0])){let r=[...i];for(let f of t)if(x(f)&&"name"in f){if(!r.find((c)=>x(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(x(f)&&"path"in f){if(!r.find((c)=>x(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((e)=>Qn(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!x(i)||!x(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(x(f)&&x(n[r]))n[r]=of(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&x(f[0])&&x(n[r][0])){let e=[...f];for(let c of n[r])if(x(c)&&"name"in c){if(!e.find((h)=>x(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(x(c)&&"path"in c){if(!e.find((h)=>x(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((l)=>Qn(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function Qn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Qn(t[n],i[n]))return!1;return!0}if(x(t)&&x(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Qn(t[f],i[f]))return!1}return!0}return!1}function x(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function gs(t,i){if(!lh(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return of(i,r)}catch{return null}}catch{return null}}async function bs({name:t="",cwd:i,defaultConfig:n}){let r=i||If.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let l of f){let h=vn(r,`${c}${l}`),$=await gs(h,n);if($!==null)return $}try{let c=vn(r,"package.json");if(lh(c)){let h=(await import(c))[t];if(h&&typeof h==="object"&&!Array.isArray(h))try{return of(n,h)}catch{}}}catch{}return n}function Xs(t,i={}){let n=Pn.cwd();while(n.includes("storage"))n=Cc(n,"..");let r=Cc(n,t||"");if(i?.relative)return hs(Pn.cwd(),r);return r}async function Ps(){try{let t=await bs({name:"clarity",defaultConfig:kn,cwd:Pn.cwd(),endpoint:"",headers:{}});return{...kn,...t}}catch{return kn}}function L(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vs(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Lt<"u"){let t=Lt.type;if(t==="renderer"||t==="worker")return!1;return!!(Lt.versions&&(Lt.versions.node||Lt.versions.bun))}return!1}class sh{async format(t){let i=await vs(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ci.pid,hostname:i(),environment:Ci.env.NODE_ENV||"development",platform:Ci.platform,version:Ci.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ci.env.NODE_ENV||Ci.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class tr{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={...Hf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new sh,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 n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Vn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Vn};return{...Vn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Hf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,l=1000;while(e<c)try{try{try{await us(this.config.logDirectory,Wc.F_OK|Wc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await ys(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ci.from(t);try{if(!Af(this.currentLogFile))await mf(this.currentLogFile,"",{mode:420});if(f=jc(this.currentLogFile,"a",420),ws(f,h,{flag:"a"}),Uc(f),f!==void 0)af(f),f=void 0;if((await Fi(this.currentLogFile)).size===0){if(await mf(this.currentLogFile,h,{flag:"w",mode:420}),(await Fi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let s=$;if(s.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(s.code)){if(e<c-1){let u=typeof s.message==="string"?s.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,u);let y=l*2**e;await new Promise((w)=>setTimeout(w,y)),e++;continue}}if(s?.code&&["ENOSPC","EDQUOT"].includes(s.code))throw Error(`Disk quota exceeded or no space left on device: ${s.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",s),s}finally{if(f!==void 0)try{af(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(h){if(e===c-1){let s=h,u=typeof s.message==="string"?s.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),h}e++;let $=l*2**(e-1);await new Promise((s)=>setTimeout(s,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 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(L())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 n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,h])=>h.createdAt.getTime()-l.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return yf(16).toString("hex")}generateKey(){return yf(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(),n=yf(16),r=ls("aes-256-gcm",i,n),f=ci.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:ci.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=dc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(ci.from(ci.concat(f)))),r.on("error",n),r.write(t),r.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(L())return;let t=await Fi(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 n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Wn(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Fi(n).catch(()=>null))try{if(await Yc(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await Yn(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await mf(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Fi(n).catch(()=>null))await Yc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await Wn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of e.slice(i.maxFiles))await Yn(Ji(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=_c(t),r=ss(i),f=dc();await as(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}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 n={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(n)}}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()})),Af(this.currentLogFile))try{let t=jc(this.currentLogFile,"r+");Uc(t),af(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(!L()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Wn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Yn(Ji(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,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?K.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=rt.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${K.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!L()){let $=Rh[t],s=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:K.gray(c),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:K.green(c),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.error(u),l){let y=l.split(`
2
+ `);for(let w of y)if(w.trim()&&!w.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:K.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!L()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(t))return;let h=`${e} ${this.environment}.${t.toUpperCase()}: ${c}
3
+ `;if(l)h+=`${l}
4
+ `;h=h.replace(this.ANSI_PATTERN,""),await this.writeToFile(h)}time(t){let i=performance.now();if(this.fancy&&!L()){let n=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:K.blue("◐"),tag:n,message:`${K.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
5
+ `,$=$.replace(this.ANSI_PATTERN,""),this.fancy&&!L()){let s=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:K.green("✓"),tag:s,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!L())console.error($.trim());await this.writeToFile($)}}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}`,n=new tr(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(n),n}createReadStream(){if(L())throw Error("createReadStream is not supported in browser environments");if(!Af(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return _c(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 n=this.keys.get(this.currentKeyId);try{let r=ci.isBuffer(t)?t:ci.from(t,"base64"),f=r.slice(0,16),e=r.slice(-16),c=r.slice(16,-16),l=$s("aes-256-gcm",n,f);return l.setAuthTag(e),ci.concat([l.update(c),l.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return L()}isServerMode(){return!L()}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,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i);if(this.fancy&&!L()){let e=t.split(`
6
+ `),c=Math.max(...e.map((s)=>s.length))+2,l=`┌${"─".repeat(c)}┐`,h=`└${"─".repeat(c)}┘`,$=e.map((s)=>{let u=" ".repeat(c-s.length-2);return`│ ${s}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:K.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(l)})),$.forEach((s)=>console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(s),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(h),showTimestamp:!1}))}else if(!L())console.error(`${r} ${this.environment}.INFO: [BOX] ${t}`);let f=`${r} ${this.environment}.INFO: [BOX] ${t}
7
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(t){if(L())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${K.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();rt.stdin.removeListener("data",n);try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!1)}catch{}rt.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!0)}catch{}rt.stdin.resume(),rt.stdin.once("data",n)})}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 n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,l=0;if(n=t.replace(c,(h,$)=>{if($==="%")return"%";if(l>=i.length)return h;let s=i[l++];switch($){case"s":return String(s);case"d":case"i":return Number(s).toString();case"j":case"o":return JSON.stringify(s,null,2);default:return h}}),l<i.length)n+=` ${i.slice(l).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}if(this.fancy&&!L()){let c=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",l=K.blue("◐");console.error(`${l} ${c} ${K.cyan(n)}`)}let e=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}progress(t,i=""){if(!this.enabled||!this.fancy||L()||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 n=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(c,l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,c)),l!==void 0)this.activeProgressBar.message=l;let h=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,h)},finish:(c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;if(this.activeProgressBar.current=this.activeProgressBar.total,c!==void 0)this.activeProgressBar.message=c;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(c,l="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;rt.stdout.write(`${"\r".padEnd(rt.stdout.columns||80)}\r`),this.log(l,c),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||L()||!rt.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=K.green("━".repeat(r)),c=K.gray("━".repeat(f)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",s=i||n===100?K.green("✓"):K.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",y=`\r${s}${u} ${l} ${h}${$}`,w=rt.stdout.columns||80,m=" ".repeat(Math.max(0,w-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,rt.stdout.write(t.lastRenderedLine),i)rt.stdout.write(`
9
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||L()||!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(L()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Wn(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=Ji(this.config.logDirectory,r);if(t.before)try{if((await Fi(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Yn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Ln(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 r=[...i];for(let f of t)if(Z(f)&&"name"in f){if(!r.find((c)=>Z(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(Z(f)&&"path"in f){if(!r.find((c)=>Z(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((e)=>ir(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!Z(i)||!Z(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(Z(f)&&Z(n[r]))n[r]=Ln(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&Z(f[0])&&Z(n[r][0])){let e=[...f];for(let c of n[r])if(Z(c)&&"name"in c){if(!e.find((h)=>Z(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(Z(c)&&"path"in c){if(!e.find((h)=>Z(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((l)=>ir(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function gf(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:Ln(t,i);if(Array.isArray(t))return n==="replace"?i:Ln(t,i);if(!Z(i)||!Z(t))return i;let r={...t};for(let f of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let e=i[f],c=r[f];if(e===null||e===void 0)continue;if(Array.isArray(e)||Array.isArray(c))if(n==="replace")r[f]=e;else r[f]=Ln(c,e);else if(Z(e)&&Z(c))r[f]=gf(c,e,n);else r[f]=e}return r}function ir(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!ir(t[n],i[n]))return!1;return!0}if(Z(t)&&Z(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!ir(t[f],i[f]))return!1}return!0}return!1}function Z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function qn(t,i,n="replace"){if(!hh(t))return null;try{let r=await import(t),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return gf(i,f,n)}catch{return null}}catch{return null}}function ps(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),w=`${r}_${u.map(y).join("_")}`,m=`${r}_${u.map((A)=>A.toUpperCase()).join("_")}`;if(n)et.info(`Checking environment variable ${w} for config ${t}.${u.join(".")}`);if(typeof s==="object"&&s!==null&&!Array.isArray(s))h[$]=e(s,u);else{let A=hn.env[w]||hn.env[m];if(A!==void 0){if(n)et.info(`Using environment variable ${A?w:m} for config ${t}.${u.join(".")}`);if(typeof s==="number")h[$]=Number(A);else if(typeof s==="boolean")h[$]=A.toLowerCase()==="true";else if(Array.isArray(s))try{let T=JSON.parse(A);if(Array.isArray(T))h[$]=T;else h[$]=A.split(",").map((E)=>E.trim())}catch{h[$]=A.split(",").map((T)=>T.trim())}else h[$]=A}}}return h}return e(f)}async function Qs({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:l="replace"}){let h=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?ps(t,f,e):f,$=n||hn.cwd(),s=[".ts",".js",".mjs",".cjs",".json"];if(e)et.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${$}`);let u=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),w=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([$,st($,"config"),st($,".config"),r?st($,r):void 0].filter(Boolean)));for(let T of A){if(e)et.info(`Searching for configuration in: ${T}`);let R=[st($,"config"),st($,".config")].concat(r?[st($,r)]:[]).includes(T)?[...u,...y,...w,...m]:[...y,...u,...m,...w];for(let J of R)for(let C of s){let j=st(T,`${J}${C}`),B=await qn(j,h,l);if(B!==null){if(e)et.success(`Configuration loaded from: ${j}`);return B}}}if(t){let T=st(uf(),".config",t),E=["config",`${t}.config`];if(i)E.push(`${i}.config`);if(e)et.info(`Checking user config directory: ${T}`);for(let R of E)for(let J of s){let C=st(T,`${R}${J}`),j=await qn(C,h,l);if(j!==null){if(e)et.success(`Configuration loaded from user config directory: ${C}`);return j}}}if(t){let T=st(uf(),".config"),E=[`.${t}.config`];if(i)E.push(`.${i}.config`);if(e)et.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of E)for(let J of s){let C=st(T,`${R}${J}`),j=await qn(C,h,l);if(j!==null){if(e)et.success(`Configuration loaded from user config directory dotfile: ${C}`);return j}}}if(t){let T=uf(),E=[`.${t}.config`,`.${t}`];if(i)E.push(`.${i}.config`),E.push(`.${i}`);if(e)et.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of E)for(let J of s){let C=st(T,`${R}${J}`),j=await qn(C,h,l);if(j!==null){if(e)et.success(`Configuration loaded from user home directory: ${C}`);return j}}}try{let T=st($,"package.json");if(hh(T)){let E=await import(T),R=E[t];if(!R&&i){if(R=E[i],R&&e)et.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)et.success(`Configuration loaded from package.json: ${R===E[t]?t:i}`);return gf(h,R,l)}catch(J){if(e)et.warn("Failed to merge package.json config:",J)}}}catch(T){if(e)et.warn("Failed to load package.json:",T)}if(e)et.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return h}function tw(t,i={}){let n=Xn.cwd();while(n.includes("storage"))n=Jc(n,"..");let r=Jc(n,t||"");if(i?.relative)return es(Xn.cwd(),r);return r}async function iw(){try{let t=await Qs({name:"clarity",alias:"logging",defaultConfig:on,cwd:Xn.cwd()});return{...on,...t||{}}}catch{return on}}function g(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nw(){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 wh{async format(t){let i=await nw(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}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 nr{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 wh,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 n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...gn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...gn};return{...gn,...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},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!g()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,l=1000;while(e<c)try{try{try{await Ss(this.config.logDirectory,Mc.F_OK|Mc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Rs(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:xt.from(t);try{if(!dn(this.currentLogFile))await Sf(this.currentLogFile,"",{mode:420});if(f=Hc(this.currentLogFile,"a",420),Ts(f,h,{flag:"a"}),Zc(f),f!==void 0)Tf(f),f=void 0;if((await _i(this.currentLogFile)).size===0){if(await Sf(this.currentLogFile,h,{flag:"w",mode:420}),(await _i(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let s=$;if(s.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(s.code)){if(e<c-1){let u=typeof s.message==="string"?s.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,u);let y=l*2**e;await new Promise((w)=>setTimeout(w,y)),e++;continue}}if(s?.code&&["ENOSPC","EDQUOT"].includes(s.code))throw Error(`Disk quota exceeded or no space left on device: ${s.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",s),s}finally{if(f!==void 0)try{Tf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(h){if(e===c-1){let s=h,u=typeof s.message==="string"?s.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),h}e++;let $=l*2**(e-1);await new Promise((s)=>setTimeout(s,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 Ui(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 Ui(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ui(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(g())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 n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,h])=>h.createdAt.getTime()-l.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}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(),n=Ef(16),r=As("aes-256-gcm",i,n),f=xt.isBuffer(t)?t:xt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),$=xt.allocUnsafe(16+l+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),h.copy($,16+l),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Gc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(xt.from(xt.concat(f)))),r.on("error",n),r.write(t),r.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(g())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 n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await In(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await _i(n).catch(()=>null))try{if(await zc(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await Zn(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await Sf(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await _i(n).catch(()=>null))await zc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await In(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of e.slice(i.maxFiles))await Zn(Ui(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=Ic(t),r=Es(i),f=Gc();await Fs(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),dn(this.currentLogFile))try{let t=Hc(this.currentLogFile,"r+");Zc(t),Tf(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(!g()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await In(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Zn(Ui(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,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()?W.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||g())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:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=_.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${W.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=W.underline(W.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>W.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>W.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>W.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>W.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>W.strikethrough(r)),i}supportsHyperlinks(){if(g())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 n=_.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(Bs(i)||i.startsWith("./")||i.startsWith("../"))i=Ns(i);else return null;return dn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Bh[t],y=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",w;switch(t){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:W.gray(h),level:t}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:W.green(h),level:t}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.error(w),l){let m=l.split(`
10
+ `);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:W.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!g()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(t))return;let s=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
11
+ `;if(l)s+=`${l}
12
+ `;if(s=s.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(s)}progress(t,i=""){let n={update:(l,h)=>{},finish:(l)=>{},interrupt:(l,h)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,h)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),h!==void 0)this.activeProgressBar.message=h;if(this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,h="info")=>{if(!g()&&_.stdout.isTTY)_.stdout.write(`
13
+ `);if(this[h==="warning"?"warn":h](l),this.activeProgressBar&&this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":W.blue("◐"),tag:n,message:`${W.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
14
+ `,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":W.green("✓"),tag:s,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!g())console.error($.trim());if(this.shouldWriteToFile())await this.writeToFile($)}}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}`,n=new nr(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(n),n}createReadStream(){if(g())throw Error("createReadStream is not supported in browser environments");if(!dn(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 n=this.keys.get(this.currentKeyId);try{let r=xt.isBuffer(t)?t:xt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=ms("aes-256-gcm",n,f);l.setAuthTag(e);let h=l.update(c),$=l.final(),s=h.length+$.length,u=xt.allocUnsafe(s);return h.copy(u,0),$.copy(u,h.length),u.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return g()}isServerMode(){return!g()}setTestEncryptionKey(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,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let l=f.split(`
15
+ `),h=Math.max(...l.map((y)=>y.length))+2,$=`┌${"─".repeat(h)}┐`,s=`└${"─".repeat(h)}┘`,u=l.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:W.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:W.cyan($),showTimestamp:!1})),u.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:W.cyan(s),showTimestamp:!1}))}else if(!g())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
16
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(g())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${W.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();_.stdin.removeListener("data",n);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",n)})}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 n=t;if(i&&i.length>0){let h=/%([sdijfo%])/g,$=0;if(n=t.replace(h,(s,u)=>{if(u==="%")return"%";if($>=i.length)return s;let y=i[$++];switch(u){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return s}}),$<i.length)n+=` ${i.slice($).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${W.blue("◐")} `;console.error(`${$}${h} ${W.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=W.green("━".repeat(r)),c=W.gray("━".repeat(f)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",s=this.options.showIcons===!1?"":i||n===100?W.green("✓"):W.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${W.gray(this.formatTag(this.name))}`:"",y=`\r${s}${u} ${l} ${h}${$}`,w=_.stdout.columns||80,m=" ".repeat(Math.max(0,w-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,_.stdout.write(t.lastRenderedLine),i)_.stdout.write(`
18
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||g()||!_.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(g()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await In(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=Ui(this.config.logDirectory,r);if(t.before)try{if((await _i(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Zn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function uh(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(h){if(c=h instanceof Error?h:Error(String(h)),l===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function yh(t){return t instanceof Et}function rw(t){return t instanceof rr}function fw(t){if(yh(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>t.message.toLowerCase().includes(n.toLowerCase()))}class $r{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:l=!1,trackPerformance:h=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let s=r||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],s,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:l,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(h)return sn.track("applyEnvironmentVariables",$,{configName:t});return $()}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,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],l=c.map((s)=>this.formatEnvKey(s,r.useCamelCase)),h=`${n}_${l.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((s)=>s.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let s=Hn.env[h]||($?Hn.env[$]:void 0);if(s!==void 0){if(r.verbose){let u=Hn.env[h]?h:$}try{t[f]=this.parseEnvironmentValue(s,typeof e,h,r.customParsers,r.configName)}catch(u){if(u instanceof fr)throw u;throw hi.envVar(h,s,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw hi.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(Hn.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],l=`${n}_${c.map((h)=>this.formatEnvKey(h,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:l,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}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 n=`Environment Variables for ${i}:
19
+
20
+ `;for(let r of t)n+=`${r.key}
21
+ `,n+=` Type: ${r.type}
22
+ `,n+=` Description: ${r.description}
23
+ `,n+=` Example: ${r.example}
24
+
25
+ `;return n}formatAsMarkdown(t,i){let n=`# Environment Variables for ${i}
26
+
27
+ `;n+=`| Variable | Type | Description | Example |
28
+ `,n+=`|----------|------|-------------|----------|
29
+ `;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
30
+ `;return n}}function ew(t,i){let n=Th("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function ah(t,i,n={}){return Ah(t,i,n,new WeakMap)}function Ah(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return mh(t,i,f,r);if(!Nt(i)||!Nt(t))return i;return $w(t,i,n,r)}function mh(t,i,n,r){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(n){case"replace":return i;case"concat":return cw(t,i);case"smart":return hw(t,i,r);default:return i}return i}function cw(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Zf(f,r)))n.push(r);return n}function hw(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Nt(i[0])&&Nt(t[0]))return lw(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function lw(t,i,n){let r=[...i];for(let f of t){if(!Nt(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find(($)=>Nt($)&&(l in $)&&$[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function $w(t,i,n,r){let f=i;if(Nt(f)&&r.has(f))return r.get(f);let e={...t};if(Nt(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(Nt(l)&&Nt(h))e[c]=Ah(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=mh(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function bf(t,i,n="replace"){return ah(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Zf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Zf(t[n],i[n]))return!1;return!0}if(Nt(t)&&Nt(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Zf(t[f],i[f]))return!1}return!0}return!1}function Nt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class sr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let $=Ii.getWithFileCheck("file",t);if($){if(l)console.log(`Configuration loaded from cache: ${t}`);return $}}let h=async()=>{if(!Mn(t))return null;try{let $=`?t=${Date.now()}`,s=await import(t+$),u=s.default||s,y="default"in s,w=Object.keys(s).length>0;if(!y&&!w)throw new ln(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new ln(t,Error("Configuration must export a valid object"),"unknown");let T={config:bf(i,u,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Ii.setWithFileCheck("file",T,t,e);return T}catch($){throw $ instanceof Error?hi.configLoad(t,$):hi.configLoad(t,Error(String($)))}};if(c)return sn.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Rf(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(n.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)n.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return n.filter(Boolean)}checkFileAccess(t){return uh(async()=>{return Mn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Mn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=Rf(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=Rf(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}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((n)=>n.test(t))}async validateConfigFile(t){let i=[];try{if(!Mn(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class Xf{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,$=async()=>{let s=[],u=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(w){return s.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:s,warnings:u}}};if(l)return await sn.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Js(i))throw new $n(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new $n(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let $=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,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))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}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:Fh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Pf{fileLoader=new sr;envProcessor=new $r;validator=new Xf;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let $=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if($)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let s=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),u=!s&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),y=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if($&&(y||s))throw h;if(u&&(!$||!y))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)Wt.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){let h=Date.now()-i;throw Wt.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:$="replace",verbose:s=!1}=t,u=e||ai.cwd(),y=[],w=await this.loadLocalConfiguration(r,f,u,c,l,$,s,h,n);if(w)return y.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(w,y,h,r,s);let m=await this.loadHomeConfiguration(r,f,l,$,s,h);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,h,r,s);let A=await this.loadPackageJsonConfiguration(r,f,u,l,$,s,h);if(A)return y.push(wt(u,"package.json")),this.finalizeResult(A,y,h,r,s);if(y.push(...this.getAllSearchPaths(r,f,u,c)),i)throw hi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,l,h,s),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let $=l?cn(t,f,c):f,s=this.getLocalDirectories(n,r);for(let u of s){if(c)Wt.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),w=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(w){if(c)Wt.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?cn(t,n,f):n,l=[wt(Ni(),".config",t),wt(Ni(),".config"),Ni()];for(let h of l){if(f)Wt.info(`Checking home directory: ${h}`);let $=this.fileLoader.generateConfigPaths(t,h,i),s=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(s){if(f)Wt.success(`Configuration loaded from home directory: ${s.source.path}`);return s}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?cn(t,r,e):r;try{let h=wt(n,"package.json");if(!df(h))return null;let $=await import(h),s=$[t],u=t;if(!s&&i)s=$[i],u=i;if(s&&typeof s==="object"&&!Array.isArray(s)){if(e)Wt.success(`Configuration loaded from package.json: ${u}`);return{config:bf(l,s,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)Wt.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:cn(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw hi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Ii.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Ii.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias)n.push(`alias:${i.alias}`);if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,wt(t,"config"),wt(t,".config"),i?wt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(wt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[wt(Ni(),".config",t),wt(Ni(),".config"),Ni()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function oc(t){let n=!(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 n||r}async function sw(t){return ot.loadConfig({...t,__strictErrorHandling:!0})}async function Eh(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await ot.loadConfig(t);else r=await ot.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let f=r instanceof Error?r.name:"UnknownError",e=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||e.includes("config"))&&t.verbose)Wt.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ot.applyEnvironmentVariables(l.name||"",i,!0,l.verbose||!1))?.config??i;return i}}async function ww(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ot.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&oc(n)))return(await ot.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await ot.loadConfig({...t,cwd:t.cwd||ai.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&oc(i)))return(await ot.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function uw(t,i,n="replace"){let r=new sr;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function cn(t,i,n=!1){let r=new $r,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((A)=>A.toUpperCase()).join("")}`,`${f}_${u.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,m;for(let A of y)if(w=ai.env[A],w!==void 0){m=A;break}if(w!==void 0&&m)if(typeof s==="boolean")h[$]=["true","1","yes"].includes(w.toLowerCase());else if(typeof s==="number"){let A=Number(w);if(!Number.isNaN(A))h[$]=A}else if(Array.isArray(s))try{h[$]=JSON.parse(w)}catch{h[$]=w.split(",").map((A)=>A.trim())}else h[$]=w;else if(s&&typeof s==="object"&&!Array.isArray(s))h[$]=e(s,u)}return h}return e(i)}function yw(t){let i=wt(ai.cwd(),t.configDir),n=wt(ai.cwd(),t.generatedDir),r=wt(n,"config-types.ts");if(!df(Fc(r)))is(Fc(r),{recursive:!0,mode:511});let f=df(i)?ns(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${Ow}
31
+ export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
32
+ `;rs(r,e,{mode:438})}function aw(t){let i=null,n=null,r=()=>{if(!n)n=Eh(t).then((e)=>{return i=e,e},(e)=>{let c="defaultConfig"in t?t.defaultConfig:{};if(i=c,"verbose"in t&&t.verbose)Wt.warn("Config loading failed, using defaults:",[e instanceof Error?e:Error(String(e))]);return c});return n},f="defaultConfig"in t?t.defaultConfig:{};return i=f,r(),new Proxy({},{get(e,c){if(i)return i[c];let l=f[c];return r(),l},has(e,c){return c in(i||f)},ownKeys(){return Object.keys(i||f)},getOwnPropertyDescriptor(e,c){return Object.getOwnPropertyDescriptor(i||f,c)},set(e,c,l){if(!i)i={...f};return i[c]=l,!0}})}function Aw(t){let i=Kc(Us.cwd(),t?.configDir||"./config");function n(){if(!Cs(i))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),e=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=_s(i).filter((h)=>f.has(Bf(h))).map((h)=>({base:h.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:h})),l=new Map;for(let{base:h,file:$}of c){let s=Bf($).toLowerCase(),u=l.get(h);if(!u){l.set(h,$);continue}let y=Bf(u).toLowerCase();if(e.indexOf(s)<e.indexOf(y))l.set(h,$)}return Array.from(l.entries()).map(([h,$])=>({base:h,file:$})).sort((h,$)=>h.base.localeCompare($.base))}function r(){let f=n(),e=f.map(($)=>$.base),c=e.length?e.map(($)=>`'${$}'`).join(" | "):"string",l=f.length?`{
33
+ ${f.map(($)=>{let s=Kc(i,$.file).replace(/\\/g,"/");return` '${$.base}': typeof import('${s}').default`}).join(`,
34
+ `)}
35
+ }`:"Record<string, any>";return`export type ConfigNames = ${c}
36
+ export type ConfigByName = ${l}
37
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
38
+ export type ConfigOf = Config
39
+ `}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(e)=>{return{path:e.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Th,Ii,sn,Sh,mw,Ew,gc,kn,Hf,ft,K,Tw,bc,Sw,Xc,Rw,Bw,Cf,Nw,Pc,vc,_f,Fw,Jw,Cw,_w,Vn,Rh,Uw,et,jw,Ww,pc,on,Mf,b,W,Yw,Qc,dw,th,Iw,Zw,Uf,Hw,ih,nh,Mw,jf,zw,Gw,Kw,qw,xw,gn,Bh,Dw,Ow="0.15.6",Et,rr,ln,zf,Gf,fr,Kf,qf,$n,xf,Df,hi,Nh,Fh,Wt,ot,Jh,Ch,Lw=Ls(async()=>{Th=import.meta.require,Ii=new kf,sn=new Vf,Sh={createKey:ks,isEquivalent:Vs,estimateMemoryUsage:os},mw=vn(If.cwd(),"config"),Ew=vn(If.cwd(),"src/generated"),gc=Pn.env.CLARITY_LOG_DIR||cs(Xs(),"logs"),kn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Hf=await Ps(),ft={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"},K=ft,Tw=ft.red,bc=ft.green,Sw=ft.yellow,Xc=ft.blue,Rw=ft.magenta,Bw=ft.cyan,Cf=ft.white,Nw=ft.gray,Pc=ft.bgRed,vc=ft.bgYellow,_f=ft.bold,Fw=ft.dim,Jw=ft.italic,Cw=ft.underline,_w=ft.reset,Vn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Rh={debug:"\uD83D\uDD0D",info:Xc("ℹ"),success:bc("✓"),warning:vc(Cf(_f(" WARN "))),error:Pc(Cf(_f(" ERROR ")))},Uw=new tr("stacks"),et=new tr("bunfig",{showTags:!0}),jw=st(hn.cwd(),"config"),Ww=st(hn.cwd(),"src/generated"),pc=Xn.env.CLARITY_LOG_DIR||fs(tw(),"logs"),on={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:pc,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 iw(),b={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"},W=b,Yw=b.red,Qc=b.green,dw=b.yellow,th=b.blue,Iw=b.magenta,Zw=b.cyan,Uf=b.white,Hw=b.gray,ih=b.bgRed,nh=b.bgYellow,Mw=b.bgGray,jf=b.bold,zw=b.dim,Gw=b.italic,Kw=b.underline,qw=b.strikethrough,xw=b.reset,gn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Bh={debug:"\uD83D\uDD0D",info:th("ℹ"),success:Qc("✓"),warning:nh(Uf(jf(" WARN "))),error:ih(Uf(jf(" ERROR ")))},Dw=new nr("stacks"),Et=class extends Error{timestamp;context;constructor(i,n={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,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(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},rr=class extends Et{code="CONFIG_NOT_FOUND";constructor(i,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:n,searchPathCount:n.length})}},ln=class extends Et{code="CONFIG_LOAD_ERROR";constructor(i,n,r){super(`Failed to load configuration from "${i}": ${n.message}`,{configPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},zf=class extends Et{code="CONFIG_VALIDATION_ERROR";constructor(i,n,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:n,errorCount:n.length})}},Gf=class extends Et{code="CONFIG_MERGE_ERROR";constructor(i,n,r,f){super(`Failed to merge configuration from "${i}" with "${n}": ${r.message}`,{sourcePath:i,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},fr=class extends Et{code="ENV_VAR_ERROR";constructor(i,n,r,f){super(`Failed to parse environment variable "${i}" with value "${n}" as ${r}`,{envKey:i,envValue:n,expectedType:r,configName:f})}},Kf=class extends Et{code="FILE_SYSTEM_ERROR";constructor(i,n,r){super(`File system ${i} failed for "${n}": ${r.message}`,{operation:i,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},qf=class extends Et{code="TYPE_GENERATION_ERROR";constructor(i,n,r){super(`Failed to generate types from "${i}" to "${n}": ${r.message}`,{configDir:i,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},$n=class extends Et{code="SCHEMA_VALIDATION_ERROR";constructor(i,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:n,errorCount:n.length})}},xf=class extends Et{code="BROWSER_CONFIG_ERROR";constructor(i,n,r,f){super(`Failed to fetch configuration from "${i}": ${n} ${r}`,{endpoint:i,status:n,statusText:r,configName:f})}},Df=class extends Et{code="PLUGIN_ERROR";constructor(i,n,r){super(`Plugin "${i}" failed during ${n}: ${r.message}`,{pluginName:i,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},hi={configNotFound(t,i,n){return new rr(t,i,n)},configLoad(t,i,n){return new ln(t,i,n)},configValidation(t,i,n){return new zf(t,i,n)},configMerge(t,i,n,r){return new Gf(t,i,n,r)},envVar(t,i,n,r){return new fr(t,i,n,r)},fileSystem(t,i,n){return new Kf(t,i,n)},typeGeneration(t,i,n){return new qf(t,i,n)},schemaValidation(t,i,n){return new $n(t,i,n)},browserConfig(t,i,n,r){return new xf(t,i,n,r)},plugin(t,i,n){return new Df(t,i,n)}},Nh={replace:"replace",concat:"concat",smart:"smart"},Fh=/^https?:\/\//,Wt=new nr("bunfig",{showTags:!0}),ot=new Pf,Jh=wt(ai.cwd(),"config"),Ch=wt(ai.cwd(),"src/generated")});function kw(t,i={}){let n=pn.cwd();while(n.includes("storage"))n=qc(n,"..");let r=qc(n,t||"");if(i?.relative)return Ws(pn.cwd(),r);return r}var Vw=pn.env.CLARITY_LOG_DIR||js(kw(),"logs"),_h={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Vw,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},er={..._h},OA=(async()=>{try{let{loadConfig:t}=await Lw().then(()=>$h),i=await t({name:"clarity",alias:"logging",defaultConfig:_h,cwd:pn.cwd()});if(i)Object.assign(er,i)}catch{}return er})();function X(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ow(){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 Uh{async format(t){let i=await ow(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:di.pid,hostname:i(),environment:di.env.NODE_ENV||"development",platform:di.platform,version:di.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:di.env.NODE_ENV||di.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var Q={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"},d=Q,LA=Q.red,gw=Q.green,kA=Q.yellow,bw=Q.blue,VA=Q.magenta,oA=Q.cyan,rh=Q.white,gA=Q.gray,Xw=Q.bgRed,Pw=Q.bgYellow,bA=Q.bgGray,fh=Q.bold,XA=Q.dim,PA=Q.italic,vA=Q.underline,pA=Q.strikethrough,QA=Q.reset,Wf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},vw={debug:"\uD83D\uDD0D",info:bw("ℹ"),success:gw("✓"),warning:Pw(rh(fh(" WARN "))),error:Xw(rh(fh(" ERROR ")))};class wr{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={...er},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Uh,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??U.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Wf,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Wf};return{...Wf,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:er.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!X()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,l=1000;while(e<c)try{try{try{await Hs(this.config.logDirectory,Lc.F_OK|Lc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Ms(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Dt.from(t);try{if(!zn(this.currentLogFile))await Jf(this.currentLogFile,"",{mode:420});if(f=Oc(this.currentLogFile,"a",420),Zs(f,h,{flag:"a"}),Dc(f),f!==void 0)Ff(f),f=void 0;if((await Wi(this.currentLogFile)).size===0){if(await Jf(this.currentLogFile,h,{flag:"w",mode:420}),(await Wi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let s=$;if(s.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(s.code)){if(e<c-1){let u=typeof s.message==="string"?s.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,u);let y=l*2**e;await new Promise((w)=>setTimeout(w,y)),e++;continue}}if(s?.code&&["ENOSPC","EDQUOT"].includes(s.code))throw Error(`Disk quota exceeded or no space left on device: ${s.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",s),s}finally{if(f!==void 0)try{Ff(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(h){if(e===c-1){let s=h,u=typeof s.message==="string"?s.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),h}e++;let $=l*2**(e-1);await new Promise((s)=>setTimeout(s,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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(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 n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,h])=>h.createdAt.getTime()-l.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}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(),n=Nf(16),r=Ys("aes-256-gcm",i,n),f=Dt.isBuffer(t)?t:Dt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),$=Dt.allocUnsafe(16+l+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),h.copy($,16+l),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Vc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(Dt.from(Dt.concat(f)))),r.on("error",n),r.write(t),r.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 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 n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Gn(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Wi(n).catch(()=>null))try{if(await kc(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await Kn(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await Jf(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Wi(n).catch(()=>null))await kc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await Gn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of e.slice(i.maxFiles))await Kn(Yi(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=xc(t),r=Is(i),f=Vc();await Ks(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),zn(this.currentLogFile))try{let t=Oc(this.currentLogFile,"r+");Dc(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 Gn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Kn(Yi(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,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()?d.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||X())return!1;let t=typeof U.env.NO_COLOR<"u",i=U.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof U.stderr<"u"&&U.stderr.isTTY||typeof U.stdout<"u"&&U.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=U.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${d.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=d.underline(d.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>d.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>d.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>d.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>d.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>d.strikethrough(r)),i}supportsHyperlinks(){if(X())return!1;let t=U.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 n=U.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(zs(i)||i.startsWith("./")||i.startsWith("../"))i=Gs(i);else return null;return zn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){if(!this.shouldLog(t))return;let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":vw[t],y=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",w;switch(t){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:d.gray(h),level:t}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:d.green(h),level:t}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.error(w),l){let m=l.split(`
40
+ `);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:d.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!X()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),l)console.error(l)}let s=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
41
+ `;if(l)s+=`${l}
42
+ `;if(s=s.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(s)}progress(t,i=""){let n={update:(l,h)=>{},finish:(l)=>{},interrupt:(l,h)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,h)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),h!==void 0)this.activeProgressBar.message=h;if(this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,h="info")=>{if(!X()&&U.stdout.isTTY)U.stdout.write(`
43
+ `);if(this[h==="warning"?"warn":h](l),this.activeProgressBar&&this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":d.blue("◐"),tag:n,message:`${d.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
44
+ `,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":d.green("✓"),tag:s,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!X())console.error($.trim());if(this.shouldWriteToFile())await this.writeToFile($)}}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}`,n=new wr(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(n),n}createReadStream(){if(X())throw Error("createReadStream is not supported in browser environments");if(!zn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return xc(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 n=this.keys.get(this.currentKeyId);try{let r=Dt.isBuffer(t)?t:Dt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=ds("aes-256-gcm",n,f);l.setAuthTag(e);let h=l.update(c),$=l.final(),s=h.length+$.length,u=Dt.allocUnsafe(s);return h.copy(u,0),$.copy(u,h.length),u.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}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,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let l=f.split(`
45
+ `),h=Math.max(...l.map((y)=>y.length))+2,$=`┌${"─".repeat(h)}┐`,s=`└${"─".repeat(h)}┘`,u=l.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:d.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:d.cyan($),showTimestamp:!1})),u.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:d.cyan(s),showTimestamp:!1}))}else if(!X())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
46
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(X())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${d.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();U.stdin.removeListener("data",n);try{if(typeof U.stdin.setRawMode==="function")U.stdin.setRawMode(!1)}catch{}U.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof U.stdin.setRawMode==="function")U.stdin.setRawMode(!0)}catch{}U.stdin.resume(),U.stdin.once("data",n)})}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 n=t;if(i&&i.length>0){let h=/%([sdijfo%])/g,$=0;if(n=t.replace(h,(s,u)=>{if(u==="%")return"%";if($>=i.length)return s;let y=i[$++];switch(u){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return s}}),$<i.length)n+=` ${i.slice($).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${d.blue("◐")} `;console.error(`${$}${h} ${d.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!U.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=d.green("━".repeat(r)),c=d.gray("━".repeat(f)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",s=this.options.showIcons===!1?"":i||n===100?d.green("✓"):d.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${d.gray(this.formatTag(this.name))}`:"",y=`\r${s}${u} ${l} ${h}${$}`,w=U.stdout.columns||80,m=" ".repeat(Math.max(0,w-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,U.stdout.write(t.lastRenderedLine),i)U.stdout.write(`
48
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||X()||!U.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 Gn(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=Yi(this.config.logDirectory,r);if(t.before)try{if((await Wi(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Kn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var tm=new wr("stacks");class Yt 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,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class jh extends Yt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((e)=>`"${e}"`).join(", ")}`;super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}}class cr extends Yt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}}class Wh extends Yt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class Yh extends Yt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class vf extends Yt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}}class dh extends Yt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class Ih extends Yt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class hr extends Yt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class Zh extends Yt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}}class Hh extends Yt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}}var Zi={configNotFound(t,i,n){return new jh(t,i,n)},configLoad(t,i,n){return new cr(t,i,n)},configValidation(t,i,n){return new Wh(t,i,n)},configMerge(t,i,n,r){return new Yh(t,i,n,r)},envVar(t,i,n,r){return new vf(t,i,n,r)},fileSystem(t,i,n){return new dh(t,i,n)},typeGeneration(t,i,n){return new Ih(t,i,n)},schemaValidation(t,i,n){return new hr(t,i,n)},browserConfig(t,i,n,r){return new Zh(t,i,n,r)},plugin(t,i,n){return new Hh(t,i,n)}};async function pw(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(h){if(c=h instanceof Error?h:Error(String(h)),l===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class pf{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:l=!1,trackPerformance:h=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let s=r||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],s,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:l,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(h)return Lf.track("applyEnvironmentVariables",$,{configName:t});return $()}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,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],l=c.map((s)=>this.formatEnvKey(s,r.useCamelCase)),h=`${n}_${l.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((s)=>s.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let s=xn.env[h]||($?xn.env[$]:void 0);if(s!==void 0){if(r.verbose){let u=xn.env[h]?h:$}try{t[f]=this.parseEnvironmentValue(s,typeof e,h,r.customParsers,r.configName)}catch(u){if(u instanceof vf)throw u;throw Zi.envVar(h,s,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw Zi.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(xn.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],l=`${n}_${c.map((h)=>this.formatEnvKey(h,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:l,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}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 n=`Environment Variables for ${i}:
49
+
50
+ `;for(let r of t)n+=`${r.key}
51
+ `,n+=` Type: ${r.type}
52
+ `,n+=` Description: ${r.description}
53
+ `,n+=` Example: ${r.example}
54
+
55
+ `;return n}formatAsMarkdown(t,i){let n=`# Environment Variables for ${i}
56
+
57
+ `;n+=`| Variable | Type | Description | Example |
58
+ `,n+=`|----------|------|-------------|----------|
59
+ `;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
60
+ `;return n}}function Qw(t,i,n={}){return Mh(t,i,n,new WeakMap)}function Mh(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return zh(t,i,f,r);if(!Ft(i)||!Ft(t))return i;return ru(t,i,n,r)}function zh(t,i,n,r){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(n){case"replace":return i;case"concat":return tu(t,i);case"smart":return iu(t,i,r);default:return i}return i}function tu(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Of(f,r)))n.push(r);return n}function iu(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ft(i[0])&&Ft(t[0]))return nu(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function nu(t,i,n){let r=[...i];for(let f of t){if(!Ft(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find(($)=>Ft($)&&(l in $)&&$[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function ru(t,i,n,r){let f=i;if(Ft(f)&&r.has(f))return r.get(f);let e={...t};if(Ft(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(Ft(l)&&Ft(h))e[c]=Mh(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=zh(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function Gh(t,i,n="replace"){return Qw(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Of(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Of(t[n],i[n]))return!1;return!0}if(Ft(t)&&Ft(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Of(t[f],i[f]))return!1}return!0}return!1}function Ft(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Kh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let $=bn.getWithFileCheck("file",t);if($){if(l)console.log(`Configuration loaded from cache: ${t}`);return $}}let h=async()=>{if(!Dn(t))return null;try{let $=`?t=${Date.now()}`,s=await import(t+$),u=s.default||s,y="default"in s,w=Object.keys(s).length>0;if(!y&&!w)throw new cr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new cr(t,Error("Configuration must export a valid object"),"unknown");let T={config:Gh(i,u,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)bn.setWithFileCheck("file",T,t,e);return T}catch($){throw $ instanceof Error?Zi.configLoad(t,$):Zi.configLoad(t,Error(String($)))}};if(c)return Lf.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Yf(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=i===void 0?[]:Array.isArray(i)?i:[i];for(let e of r){if(!e)continue;if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}let f=new Set;return n.filter((e)=>{if(!e||f.has(e))return!1;return f.add(e),!0})}checkFileAccess(t){return pw(async()=>{return Dn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Dn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=Yf(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=Yf(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}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((n)=>n.test(t))}async validateConfigFile(t){let i=[];try{if(!Dn(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var eu=/^https?:\/\//;class qh{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,$=async()=>{let s=[],u=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(w){return s.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:s,warnings:u}}};if(l)return await Lf.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!fu(i))throw new hr(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new hr(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let $=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,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))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}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:eu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Ot=new wr("bunfig",{showTags:!0});function cu(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((n)=>`"${n}"`).join(", ")}`}class xh{fileLoader=new Kh;envProcessor=new pf;validator=new qh;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let $=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if($)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let s=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),u=!s&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),y=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if($&&(y||s))throw h;if(u&&(!$||!y))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)Ot.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let h=Date.now()-i;throw Ot.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:$="replace",verbose:s=!1}=t,u=e||lr.cwd(),y=[],w=await this.loadLocalConfiguration(r,f,u,c,l,$,s,h,n);if(w)return y.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(w,y,h,r,s);let m=await this.loadHomeConfiguration(r,f,l,$,s,h);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,h,r,s);let A=await this.loadPackageJsonConfiguration(r,f,u,l,$,s,h);if(A)return y.push(Bt(u,"package.json")),this.finalizeResult(A,y,h,r,s);if(y.push(...this.getAllSearchPaths(r,f,u,c)),i)throw Zi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,l,h,s),warnings:[`No configuration file found for "${r}"${cu(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let $=l?On(t,f,c):f,s=this.getLocalDirectories(n,r);for(let u of s){if(c)Ot.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),w=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(w){if(c)Ot.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?On(t,n,f):n,l=[Bt(Bi(),".config",t),Bt(Bi(),".config"),Bi()];for(let h of l){if(f)Ot.info(`Checking home directory: ${h}`);let $=this.fileLoader.generateConfigPaths(t,h,i),s=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(s){if(f)Ot.success(`Configuration loaded from home directory: ${s.source.path}`);return s}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?On(t,r,e):r;try{let h=Bt(n,"package.json");if(!Q$(h))return null;let $={};try{$=JSON.parse(ts(h,"utf8"))}catch(y){if(e)Ot.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let s=$[t],u=t;if(!s&&i){let y=Array.isArray(i)?i:[i];for(let w of y){if(!w)continue;if($[w]){s=$[w],u=w;break}}}if(s&&typeof s==="object"&&!Array.isArray(s)){if(e)Ot.success(`Configuration loaded from package.json: ${u}`);return{config:Gh(l,s,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)Ot.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:On(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Zi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return bn.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);bn.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias){let r=Array.isArray(i.alias)?i.alias.join(","):i.alias;n.push(`alias:${r}`)}if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Bt(t,"config"),Bt(t,".config"),i?Bt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(Bt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[Bt(Bi(),".config",t),Bt(Bi(),".config"),Bi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var em=new xh;function On(t,i,n=!1){let r=new pf,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((A)=>A.toUpperCase()).join("")}`,`${f}_${u.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,m;for(let A of y)if(w=lr.env[A],w!==void 0){m=A;break}if(w!==void 0&&m)if(typeof s==="boolean")h[$]=["true","1","yes"].includes(w.toLowerCase());else if(typeof s==="number"){let A=Number(w);if(!Number.isNaN(A))h[$]=A}else if(Array.isArray(s))try{h[$]=JSON.parse(w)}catch{h[$]=w.split(",").map((A)=>A.trim())}else h[$]=w;else if(s&&typeof s==="object"&&!Array.isArray(s))h[$]=e(s,u)}return h}return e(i)}var cm=Bt(lr.cwd(),"config"),hm=Bt(lr.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",hu={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:te(Qf(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:te(Qf(),".stacks","ssl","stacks.localhost.crt"),keyPath:te(Qf(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Hi=hu;import*as O$ from"node:fs";import*as L$ from"node:path";import*as qt from"node:process";import{spawn as ra}from"node:child_process";import*as Kt from"node:fs/promises";import{homedir as q$}from"node:os";import*as Gt from"node:path";import*as nt from"node:process";import{execSync as wi}from"node:child_process";import o from"node:fs/promises";import*as Qe from"node:os";import{homedir as vi}from"node:os";import{join as it}from"node:path";import*as zt from"node:process";import{createRequire as lu}from"node:module";import ie from"node:os";import ne from"node:path";import{existsSync as Dh,statSync as Oh}from"fs";import{existsSync as $u,mkdirSync as Bm,readdirSync as Nm,readFileSync as su,writeFileSync as Fm}from"fs";import{homedir as Mi}from"os";import{dirname as _m,resolve as Jt}from"path";import gr from"process";import{existsSync as Lh,statSync as kh}from"fs";import{existsSync as Ne,mkdirSync as wu,readdirSync as uu,writeFileSync as yu}from"fs";import{homedir as zi}from"os";import{dirname as Vh,resolve as yt}from"path";import Ai from"process";import{join as au,relative as Au,resolve as oh}from"path";import dr from"process";import{existsSync as Zl,mkdirSync as zm,readdirSync as Gm,writeFileSync as Km}from"fs";import{homedir as re}from"os";import{dirname as Dm,resolve as ut}from"path";import an from"process";import{join as mu,relative as Eu,resolve as gh}from"path";import Ir from"process";import{existsSync as Hl,mkdirSync as om,readdirSync as gm,writeFileSync as bm}from"fs";import{dirname as Pm,resolve as Zr}from"path";import Fe from"process";import{Buffer as li}from"buffer";import{createCipheriv as Tu,createDecipheriv as Su,randomBytes as fe}from"crypto";import{closeSync as ee,createReadStream as bh,createWriteStream as Ru,existsSync as ce,fsyncSync as Xh,openSync as Ph,writeFileSync as Bu}from"fs";import{access as Nu,constants as vh,mkdir as Fu,readdir as ur,rename as ph,stat as Gi,unlink as yr,writeFile as he}from"fs/promises";import{join as Ki}from"path";import ct from"process";import{pipeline as Ju}from"stream/promises";import{createGzip as Qh}from"zlib";import qi from"process";import Pt from"process";import{Buffer as gt}from"buffer";import{createCipheriv as Cu,createDecipheriv as _u,randomBytes as le}from"crypto";import{closeSync as $e,createReadStream as tl,createWriteStream as Uu,existsSync as ar,fsyncSync as il,openSync as nl,writeFileSync as ju}from"fs";import{access as Wu,constants as rl,mkdir as Yu,readdir as Ar,rename as fl,stat as xi,unlink as mr,writeFile as se}from"fs/promises";import{isAbsolute as du,join as Di,resolve as Iu}from"path";import H from"process";import{pipeline as Zu}from"stream/promises";import{createGzip as el}from"zlib";import Oi from"process";import vt from"process";import Er from"process";import{existsSync as Tr}from"fs";import{resolve as we}from"path";import{existsSync as Hu}from"fs";import{existsSync as Mu,readdirSync as zu}from"fs";import{extname as ue,resolve as cl}from"path";import Gu from"process";import{join as Ku,relative as qu,resolve as hl}from"path";import Hr from"process";import{Buffer as bt}from"buffer";import{createCipheriv as xu,createDecipheriv as Du,randomBytes as ye}from"crypto";import{closeSync as ae,createReadStream as ll,createWriteStream as Ou,existsSync as Sr,fsyncSync as $l,openSync as sl,writeFileSync as Lu}from"fs";import{access as ku,constants as wl,mkdir as Vu,readdir as Rr,rename as ul,stat as Li,unlink as Br,writeFile as Ae}from"fs/promises";import{isAbsolute as ou,join as ki,resolve as gu}from"path";import M from"process";import{pipeline as bu}from"stream/promises";import{createGzip as yl}from"zlib";import Vi from"process";import pt from"process";import Nr from"process";import{existsSync as Fr}from"fs";import{resolve as me}from"path";import{existsSync as Xu}from"fs";import{exec as E0}from"node:child_process";import Ul from"node:fs";import T0 from"node:os";import dt from"node:path";import m$ from"node:process";import{promisify as S0}from"node:util";import Xi from"node:crypto";import Qt from"node:fs";import ze from"node:path";import{execSync as Il}from"node:child_process";import or from"node:os";var mm=lu(import.meta.url);class Ml{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 n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}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(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Dh(t))return!0;return Oh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Dh(n)?Oh(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class zl{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}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((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Mr=new Ml,Ge=new zl,Pu=Object.defineProperty,vu=(t)=>t;function pu(t,i){this[t]=vu.bind(null,i)}var Qu=(t,i)=>{for(var n in i)Pu(t,n,{get:i[n],enumerable:!0,configurable:!0,set:pu.bind(i,n)})},ty=(t,i)=>()=>(t&&(i=t(t=0)),i),Gl={};Qu(Gl,{withErrorRecovery:()=>xl,tryLoadConfig:()=>Fy,loadConfigWithResult:()=>By,loadConfig:()=>Vl,isRetryableError:()=>Ay,isConfigNotFoundError:()=>ay,isBunfigError:()=>Dl,globalPerformanceMonitor:()=>Tn,globalCache:()=>gi,getEnvOrDefault:()=>my,generateConfigTypes:()=>Jy,defaultGeneratedDir:()=>Ql,defaultConfigDir:()=>pl,deepMergeWithArrayStrategy:()=>Oe,deepMerge:()=>Ol,createLibraryConfig:()=>Cy,config:()=>Ny,bunfigPlugin:()=>_y,applyEnvVarsToConfig:()=>un,TypeGenerationError:()=>Ye,SchemaValidationError:()=>mn,PluginError:()=>Ie,PerformanceMonitor:()=>qe,FileSystemError:()=>We,ErrorFactory:()=>si,EnvVarError:()=>Dr,EnvProcessor:()=>br,ConfigValidator:()=>Le,ConfigValidationError:()=>Ue,ConfigNotFoundError:()=>xr,ConfigMergeError:()=>je,ConfigLoader:()=>ke,ConfigLoadError:()=>An,ConfigFileLoader:()=>Xr,ConfigCache:()=>Ke,CacheUtils:()=>gl,BunfigError:()=>Tt,BrowserConfigError:()=>de,ArrayMergeStrategies:()=>Pl});class Ke{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 n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}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(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Lh(t))return!0;return kh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Lh(n)?kh(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class qe{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}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((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function iy(t,i={}){let n=Object.keys(i).sort().map((r)=>`${r}:${i[r]}`).join("|");return n?`${t}:${n}`:t}function ny(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function ry(t){return t.getStats().size*2}function xe(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&D(i[0])&&"id"in i[0]&&i[0].id===3&&D(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(D(i)&&D(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(D(t)&&"arr"in t&&Array.isArray(t.arr)&&D(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&D(i[0])&&D(t[0])){let r=[...i];for(let f of t)if(D(f)&&"name"in f){if(!r.find((e)=>D(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(D(f)&&"path"in f){if(!r.find((e)=>D(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>zr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!D(i)||!D(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(D(f)&&D(n[r]))n[r]=xe(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&D(f[0])&&D(n[r][0])){let e=[...f];for(let c of n[r])if(D(c)&&"name"in c){if(!e.find((l)=>D(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(D(c)&&"path"in c){if(!e.find((l)=>D(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((l)=>zr(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function zr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!zr(t[n],i[n]))return!1;return!0}if(D(t)&&D(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!zr(t[f],i[f]))return!1}return!0}return!1}function D(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function fy(t,i){if(!Hl(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return xe(i,r)}catch{return null}}catch{return null}}async function ey({name:t="",cwd:i,defaultConfig:n}){let r=i||Fe.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let l of f){let h=Zr(r,`${c}${l}`),$=await fy(h,n);if($!==null)return $}try{let c=Zr(r,"package.json");if(Hl(c)){let l=(await import(c))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return xe(n,l)}catch{}}}catch{}return n}function cy(t,i={}){let n=Ir.cwd();while(n.includes("storage"))n=gh(n,"..");let r=gh(n,t||"");if(i?.relative)return Eu(Ir.cwd(),r);return r}async function hy(){try{let t=await ey({name:"clarity",defaultConfig:Ur,cwd:Ir.cwd(),endpoint:"",headers:{}});return{...Ur,...t}}catch{return Ur}}function k(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ly(){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 Kl{async format(t){let i=await ly(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:qi.pid,hostname:i(),environment:qi.env.NODE_ENV||"development",platform:qi.platform,version:qi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qi.env.NODE_ENV||qi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Gr{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={...Ce},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Kl,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??ct.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...jr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...jr};return{...jr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ce.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await Nu(this.config.logDirectory,vh.F_OK|vh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Fu(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:li.from(t);try{if(!ce(this.currentLogFile))await he(this.currentLogFile,"",{mode:420});if(r=Ph(this.currentLogFile,"a",420),Bu(r,l,{flag:"a"}),Xh(r),r!==void 0)ee(r),r=void 0;if((await Gi(this.currentLogFile)).size===0){if(await he(this.currentLogFile,l,{flag:"w",mode:420}),(await Gi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let $=h;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let s=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,s);let u=c*2**f;await new Promise((y)=>setTimeout(y,u)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{ee(r)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===e-1){let $=l,s=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}f++;let h=c*2**(f-1);await new Promise(($)=>setTimeout($,h))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}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 Ki(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 Ki(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ki(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,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return fe(16).toString("hex")}generateKey(){return fe(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(),n=fe(16),r=Tu("aes-256-gcm",i,n),f=li.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:li.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Qh(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(li.from(li.concat(f)))),r.on("error",n),r.write(t),r.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 Gi(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 n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await ur(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Gi(n).catch(()=>null))try{if(await ph(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await yr(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await he(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Gi(n).catch(()=>null))await ph(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await ur(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await yr(Ki(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=bh(t),r=Ru(i),f=Qh();await Ju(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}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 n={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(n)}}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()})),ce(this.currentLogFile))try{let t=Ph(this.currentLogFile,"r+");Xh(t),ee(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 ur(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await yr(Ki(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,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?q.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=ct.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${q.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!k()){let $=bl[t],s=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:q.gray(c),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:q.green(c),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.error(u),l){let y=l.split(`
61
+ `);for(let w of y)if(w.trim()&&!w.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:q.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(t))return;let h=`${e} ${this.environment}.${t.toUpperCase()}: ${c}
62
+ `;if(l)h+=`${l}
63
+ `;h=h.replace(this.ANSI_PATTERN,""),await this.writeToFile(h)}time(t){let i=performance.now();if(this.fancy&&!k()){let n=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:q.blue("◐"),tag:n,message:`${q.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
64
+ `,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!k()){let $=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:q.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=new Gr(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(n),n}createReadStream(){if(k())throw Error("createReadStream is not supported in browser environments");if(!ce(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return bh(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 n=this.keys.get(this.currentKeyId);try{let r=li.isBuffer(t)?t:li.from(t,"base64"),f=r.slice(0,16),e=r.slice(-16),c=r.slice(16,-16),l=Su("aes-256-gcm",n,f);return l.setAuthTag(e),li.concat([l.update(c),l.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}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,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i);if(this.fancy&&!k()){let e=t.split(`
65
+ `),c=Math.max(...e.map((s)=>s.length))+2,l=`┌${"─".repeat(c)}┐`,h=`└${"─".repeat(c)}┘`,$=e.map((s)=>{let u=" ".repeat(c-s.length-2);return`│ ${s}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:q.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(l)})),$.forEach((s)=>console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(s),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(h),showTimestamp:!1}))}else if(!k())console.error(`${r} ${this.environment}.INFO: [BOX] ${t}`);let f=`${r} ${this.environment}.INFO: [BOX] ${t}
66
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(t){if(k())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${q.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();ct.stdin.removeListener("data",n);try{if(typeof ct.stdin.setRawMode==="function")ct.stdin.setRawMode(!1)}catch{}ct.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof ct.stdin.setRawMode==="function")ct.stdin.setRawMode(!0)}catch{}ct.stdin.resume(),ct.stdin.once("data",n)})}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 n=t;if(i&&i.length>0){let f=/%([sdijfo%])/g,e=0;if(n=t.replace(f,(c,l)=>{if(l==="%")return"%";if(e>=i.length)return c;let h=i[e++];switch(l){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return c}}),e<i.length)n+=` ${i.slice(e).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!k()){let f=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",e=q.blue("◐");console.error(`${e} ${f} ${q.cyan(n)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
67
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}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 n=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,r)),f!==void 0)this.activeProgressBar.message=f;let e=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,e)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;ct.stdout.write(`${"\r".padEnd(ct.stdout.columns||80)}\r`),this.log(f,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||k()||!ct.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=q.green("━".repeat(r)),c=q.gray("━".repeat(f)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",s=i||n===100?q.green("✓"):q.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${q.gray(this.formatTag(this.name))}`:"",y=`\r${s}${u} ${l} ${h}${$}`,w=ct.stdout.columns||80,m=" ".repeat(Math.max(0,w-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,ct.stdout.write(t.lastRenderedLine),i)ct.stdout.write(`
68
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||k()||!ct.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 ur(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Ki(this.config.logDirectory,r);if(t.before)try{if((await Gi(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await yr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function _r(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 r=[...i];for(let f of t)if(z(f)&&"name"in f){if(!r.find((e)=>z(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(z(f)&&"path"in f){if(!r.find((e)=>z(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>Kr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!z(i)||!z(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(z(f)&&z(n[r]))n[r]=_r(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&z(f[0])&&z(n[r][0])){let e=[...f];for(let c of n[r])if(z(c)&&"name"in c){if(!e.find((l)=>z(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(z(c)&&"path"in c){if(!e.find((l)=>z(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((l)=>Kr(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function De(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:_r(t,i);if(Array.isArray(t))return n==="replace"?i:_r(t,i);if(!z(i)||!z(t))return i;let r={...t};for(let f of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let e=i[f],c=r[f];if(e===null||e===void 0)continue;if(Array.isArray(e)||Array.isArray(c))if(n==="replace")r[f]=e;else r[f]=_r(c,e);else if(z(e)&&z(c))r[f]=De(c,e,n);else r[f]=e}return r}function Kr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Kr(t[n],i[n]))return!1;return!0}if(z(t)&&z(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Kr(t[f],i[f]))return!1}return!0}return!1}function z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Jr(t,i,n="replace"){if(!Zl(t))return null;try{let r=await import(t),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return De(i,f,n)}catch{return null}}catch{return null}}function $y(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),w=`${r}_${u.map(y).join("_")}`,m=`${r}_${u.map((A)=>A.toUpperCase()).join("_")}`;if(n)lt.info(`Checking environment variable ${w} for config ${t}.${u.join(".")}`);if(typeof s==="object"&&s!==null&&!Array.isArray(s))h[$]=e(s,u);else{let A=an.env[w]||an.env[m];if(A!==void 0){if(n)lt.info(`Using environment variable ${A?w:m} for config ${t}.${u.join(".")}`);if(typeof s==="number")h[$]=Number(A);else if(typeof s==="boolean")h[$]=A.toLowerCase()==="true";else if(Array.isArray(s))try{let T=JSON.parse(A);if(Array.isArray(T))h[$]=T;else h[$]=A.split(",").map((E)=>E.trim())}catch{h[$]=A.split(",").map((T)=>T.trim())}else h[$]=A}}}return h}return e(f)}async function sy({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:l="replace"}){let h=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?$y(t,f,e):f,$=n||an.cwd(),s=[".ts",".js",".mjs",".cjs",".json"];if(e)lt.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${$}`);let u=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),w=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([$,ut($,"config"),ut($,".config"),r?ut($,r):void 0].filter(Boolean)));for(let T of A){if(e)lt.info(`Searching for configuration in: ${T}`);let E=[ut($,"config"),ut($,".config")].concat(r?[ut($,r)]:[]).includes(T)?[...u,...y,...w,...m]:[...y,...u,...m,...w];for(let R of E)for(let J of s){let C=ut(T,`${R}${J}`),j=await Jr(C,h,l);if(j!==null){if(e)lt.success(`Configuration loaded from: ${C}`);return j}}}if(t){let T=ut(re(),".config",t),E=["config",`${t}.config`];if(i)E.push(`${i}.config`);if(e)lt.info(`Checking user config directory: ${T}`);for(let R of E)for(let J of s){let C=ut(T,`${R}${J}`),j=await Jr(C,h,l);if(j!==null){if(e)lt.success(`Configuration loaded from user config directory: ${C}`);return j}}}if(t){let T=ut(re(),".config"),E=[`.${t}.config`];if(i)E.push(`.${i}.config`);if(e)lt.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of E)for(let J of s){let C=ut(T,`${R}${J}`),j=await Jr(C,h,l);if(j!==null){if(e)lt.success(`Configuration loaded from user config directory dotfile: ${C}`);return j}}}if(t){let T=re(),E=[`.${t}.config`,`.${t}`];if(i)E.push(`.${i}.config`),E.push(`.${i}`);if(e)lt.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of E)for(let J of s){let C=ut(T,`${R}${J}`),j=await Jr(C,h,l);if(j!==null){if(e)lt.success(`Configuration loaded from user home directory: ${C}`);return j}}}try{let T=ut($,"package.json");if(Zl(T)){let E=await import(T),R=E[t];if(!R&&i){if(R=E[i],R&&e)lt.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)lt.success(`Configuration loaded from package.json: ${R===E[t]?t:i}`);return De(h,R,l)}catch(J){if(e)lt.warn("Failed to merge package.json config:",J)}}}catch(T){if(e)lt.warn("Failed to load package.json:",T)}if(e)lt.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return h}function wy(t,i={}){let n=dr.cwd();while(n.includes("storage"))n=oh(n,"..");let r=oh(n,t||"");if(i?.relative)return Au(dr.cwd(),r);return r}async function uy(){try{let t=await sy({name:"clarity",alias:"logging",defaultConfig:Wr,cwd:dr.cwd()});return{...Wr,...t||{}}}catch{return Wr}}function P(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function yy(){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 ql{async format(t){let i=await yy(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Oi.pid,hostname:i(),environment:Oi.env.NODE_ENV||"development",platform:Oi.platform,version:Oi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Oi.env.NODE_ENV||Oi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qr{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={..._e},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new ql,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??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Yr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Yr};return{...Yr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:_e.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await Wu(this.config.logDirectory,rl.F_OK|rl.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Yu(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:gt.from(t);try{if(!ar(this.currentLogFile))await se(this.currentLogFile,"",{mode:420});if(r=nl(this.currentLogFile,"a",420),ju(r,l,{flag:"a"}),il(r),r!==void 0)$e(r),r=void 0;if((await xi(this.currentLogFile)).size===0){if(await se(this.currentLogFile,l,{flag:"w",mode:420}),(await xi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let $=h;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let s=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,s);let u=c*2**f;await new Promise((y)=>setTimeout(y,u)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{$e(r)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===e-1){let $=l,s=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}f++;let h=c*2**(f-1);await new Promise(($)=>setTimeout($,h))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}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 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(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,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}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(),n=le(16),r=Cu("aes-256-gcm",i,n),f=gt.isBuffer(t)?t:gt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),$=gt.allocUnsafe(16+l+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),h.copy($,16+l),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=el(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(gt.from(gt.concat(f)))),r.on("error",n),r.write(t),r.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 xi(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 n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ar(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await xi(n).catch(()=>null))try{if(await fl(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await mr(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await se(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await xi(n).catch(()=>null))await fl(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Ar(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await mr(Di(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=tl(t),r=Uu(i),f=el();await Zu(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),ar(this.currentLogFile))try{let t=nl(this.currentLogFile,"r+");il(t),$e(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 Ar(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await mr(Di(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,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()?Y.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof H.env.NO_COLOR<"u",i=H.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=H.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${Y.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=Y.underline(Y.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>Y.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Y.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Y.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Y.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>Y.strikethrough(r)),i}supportsHyperlinks(){if(P())return!1;let t=H.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 n=H.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(du(i)||i.startsWith("./")||i.startsWith("../"))i=Iu(i);else return null;return ar(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Xl[t],y=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",w;switch(t){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:Y.gray(h),level:t}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:Y.green(h),level:t}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.error(w),l){let m=l.split(`
69
+ `);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:Y.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),l)console.error(l)}if(!this.shouldLog(t))return;let s=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
70
+ `;if(l)s+=`${l}
71
+ `;if(s=s.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(s)}progress(t,i=""){let n={update:(f,e)=>{},finish:(f)=>{},interrupt:(f,e)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,e)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),e!==void 0)this.activeProgressBar.message=e;if(this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,e="info")=>{if(!P()&&H.stdout.isTTY)H.stdout.write(`
72
+ `);if(this[e==="warning"?"warn":e](f),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":Y.blue("◐"),tag:n,message:`${Y.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
73
+ `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":Y.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=new qr(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(n),n}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!ar(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return tl(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 n=this.keys.get(this.currentKeyId);try{let r=gt.isBuffer(t)?t:gt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=_u("aes-256-gcm",n,f);l.setAuthTag(e);let h=l.update(c),$=l.final(),s=h.length+$.length,u=gt.allocUnsafe(s);return h.copy(u,0),$.copy(u,h.length),u.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}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,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let l=f.split(`
74
+ `),h=Math.max(...l.map((y)=>y.length))+2,$=`┌${"─".repeat(h)}┐`,s=`└${"─".repeat(h)}┘`,u=l.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:Y.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:Y.cyan($),showTimestamp:!1})),u.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:Y.cyan(s),showTimestamp:!1}))}else if(!P())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
75
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${Y.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();H.stdin.removeListener("data",n);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",n)})}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 n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,l=0;if(n=t.replace(c,(h,$)=>{if($==="%")return"%";if(l>=i.length)return h;let s=i[l++];switch($){case"s":return String(s);case"d":case"i":return Number(s).toString();case"j":case"o":return JSON.stringify(s,null,2);default:return h}}),l<i.length)n+=` ${i.slice(l).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${Y.blue("◐")} `;console.error(`${l}${c} ${Y.cyan(r)}`)}let e=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
76
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(e)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=Y.green("━".repeat(r)),c=Y.gray("━".repeat(f)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",s=this.options.showIcons===!1?"":i||n===100?Y.green("✓"):Y.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${Y.gray(this.formatTag(this.name))}`:"",y=`\r${s}${u} ${l} ${h}${$}`,w=H.stdout.columns||80,m=" ".repeat(Math.max(0,w-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,H.stdout.write(t.lastRenderedLine),i)H.stdout.write(`
77
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!H.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 Ar(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Di(this.config.logDirectory,r);if(t.before)try{if((await xi(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await mr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function xl(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(h){if(c=h instanceof Error?h:Error(String(h)),l===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function Dl(t){return t instanceof Tt}function ay(t){return t instanceof xr}function Ay(t){if(Dl(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 br{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:l=!1,trackPerformance:h=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let s=r||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],s,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:l,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(h)return Tn.track("applyEnvironmentVariables",$,{configName:t});return $()}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,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],l=c.map((s)=>this.formatEnvKey(s,r.useCamelCase)),h=`${n}_${l.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((s)=>s.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let s=Er.env[h]||($?Er.env[$]:void 0);if(s!==void 0){if(r.verbose){let u=Er.env[h]?h:$}try{t[f]=this.parseEnvironmentValue(s,typeof e,h,r.customParsers,r.configName)}catch(u){if(u instanceof Dr)throw u;throw si.envVar(h,s,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw si.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(Er.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],l=`${n}_${c.map((h)=>this.formatEnvKey(h,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:l,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}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 n=`Environment Variables for ${i}:
78
+
79
+ `;for(let r of t)n+=`${r.key}
80
+ `,n+=` Type: ${r.type}
81
+ `,n+=` Description: ${r.description}
82
+ `,n+=` Example: ${r.example}
83
+
84
+ `;return n}formatAsMarkdown(t,i){let n=`# Environment Variables for ${i}
85
+
86
+ `;n+=`| Variable | Type | Description | Example |
87
+ `,n+=`|----------|------|-------------|----------|
88
+ `;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
89
+ `;return n}}function my(t,i){let n=ol("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function Ol(t,i,n={}){return Ll(t,i,n,new WeakMap)}function Ll(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return kl(t,i,f,r);if(!Ct(i)||!Ct(t))return i;return Ry(t,i,n,r)}function kl(t,i,n,r){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(n){case"replace":return i;case"concat":return Ey(t,i);case"smart":return Ty(t,i,r);default:return i}return i}function Ey(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Je(f,r)))n.push(r);return n}function Ty(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ct(i[0])&&Ct(t[0]))return Sy(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function Sy(t,i,n){let r=[...i];for(let f of t){if(!Ct(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find((h)=>Ct(h)&&(l in h)&&h[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function Ry(t,i,n,r){let f=i;if(Ct(f)&&r.has(f))return r.get(f);let e={...t};if(Ct(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(Ct(l)&&Ct(h))e[c]=Ll(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=kl(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function Oe(t,i,n="replace"){return Ol(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Je(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Je(t[n],i[n]))return!1;return!0}if(Ct(t)&&Ct(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Je(t[f],i[f]))return!1}return!0}return!1}function Ct(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Xr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let $=gi.getWithFileCheck("file",t);if($){if(l)console.log(`Configuration loaded from cache: ${t}`);return $}}let h=async()=>{if(!Tr(t))return null;try{let $=`?t=${Date.now()}`,s=await import(t+$),u=s.default||s,y="default"in s,w=Object.keys(s).length>0;if(!y&&!w)throw new An(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new An(t,Error("Configuration must export a valid object"),"unknown");let m={config:Oe(i,u,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)gi.setWithFileCheck("file",m,t,e);return m}catch($){throw $ instanceof Error?si.configLoad(t,$):si.configLoad(t,Error(String($)))}};if(c)return Tn.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(we(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(n.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)n.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return n.filter(Boolean)}checkFileAccess(t){return xl(async()=>{return Tr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Tr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=we(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=we(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}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(!Tr(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class Le{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,$=async()=>{let s=[],u=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(w){return s.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:s,warnings:u}}};if(l)return await Tn.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Hu(i))throw new mn(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new mn(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let $=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,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))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}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:vl},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ke{fileLoader=new Xr;envProcessor=new br;validator=new Le;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let $=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if($)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let s=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),u=!s&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),y=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if($&&(y||s))throw h;if(u&&(!$||!y))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)It.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){let h=Date.now()-i;throw It.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:$="replace",verbose:s=!1}=t,u=e||Ai.cwd(),y=[],w=await this.loadLocalConfiguration(r,f,u,c,l,$,s,h,n);if(w)return y.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(w,y,h,r,s);let m=await this.loadHomeConfiguration(r,f,l,$,s,h);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,h,r,s);let A=await this.loadPackageJsonConfiguration(r,f,u,l,$,s,h);if(A)return y.push(yt(u,"package.json")),this.finalizeResult(A,y,h,r,s);if(y.push(...this.getAllSearchPaths(r,f,u,c)),i)throw si.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,l,h,s),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let $=l?un(t,f,c):f,s=this.getLocalDirectories(n,r);for(let u of s){if(c)It.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),w=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(w){if(c)It.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?un(t,n,f):n,l=[yt(zi(),".config",t),yt(zi(),".config"),zi()];for(let h of l){if(f)It.info(`Checking home directory: ${h}`);let $=this.fileLoader.generateConfigPaths(t,h,i),s=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(s){if(f)It.success(`Configuration loaded from home directory: ${s.source.path}`);return s}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?un(t,r,e):r;try{let h=yt(n,"package.json");if(!Ne(h))return null;let $=await import(h),s=$[t],u=t;if(!s&&i)s=$[i],u=i;if(s&&typeof s==="object"&&!Array.isArray(s)){if(e)It.success(`Configuration loaded from package.json: ${u}`);return{config:Oe(l,s,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)It.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:un(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw si.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return gi.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);gi.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias)n.push(`alias:${i.alias}`);if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,yt(t,"config"),yt(t,".config"),i?yt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(yt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[yt(zi(),".config",t),yt(zi(),".config"),zi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function al(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")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||n}async function By(t){return ti.loadConfig({...t,__strictErrorHandling:!0})}async function Vl(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await ti.loadConfig(t);else r=await ti.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let f=r instanceof Error?r.name:"UnknownError",e=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||e.includes("config"))&&t.verbose)It.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let c=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ti.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function Ny(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ti.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&al(n)))return(await ti.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await ti.loadConfig({...t,cwd:t.cwd||Ai.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&al(i)))return(await ti.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function Fy(t,i,n="replace"){let r=new Xr;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function un(t,i,n=!1){let r=new br,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((A)=>A.toUpperCase()).join("")}`,`${f}_${u.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,m;for(let A of y)if(w=Ai.env[A],w!==void 0){m=A;break}if(w!==void 0&&m)if(typeof s==="boolean")h[$]=["true","1","yes"].includes(w.toLowerCase());else if(typeof s==="number"){let A=Number(w);if(!Number.isNaN(A))h[$]=A}else if(Array.isArray(s))try{h[$]=JSON.parse(w)}catch{h[$]=w.split(",").map((A)=>A.trim())}else h[$]=w;else if(s&&typeof s==="object"&&!Array.isArray(s))h[$]=e(s,u)}return h}return e(i)}function Jy(t){let i=yt(Ai.cwd(),t.configDir),n=yt(Ai.cwd(),t.generatedDir),r=yt(n,"config-types.ts");if(!Ne(Vh(r)))wu(Vh(r),{recursive:!0,mode:511});let f=Ne(i)?uu(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${Qy}
90
+ export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
91
+ `;yu(r,e,{mode:438})}function Cy(t){let i=null,n=null,r=()=>{if(!n)n=Vl(t).then((e)=>{return i=e,e},(e)=>{let c="defaultConfig"in t?t.defaultConfig:{};if(i=c,"verbose"in t&&t.verbose)It.warn("Config loading failed, using defaults:",[e instanceof Error?e:Error(String(e))]);return c});return n},f="defaultConfig"in t?t.defaultConfig:{};return i=f,r(),new Proxy({},{get(e,c){if(i)return i[c];let l=f[c];return r(),l},has(e,c){return c in(i||f)},ownKeys(){return Object.keys(i||f)},getOwnPropertyDescriptor(e,c){return Object.getOwnPropertyDescriptor(i||f,c)},set(e,c,l){if(!i)i={...f};return i[c]=l,!0}})}function _y(t){let i=cl(Gu.cwd(),t?.configDir||"./config");function n(){if(!Mu(i))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),e=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=zu(i).filter((h)=>f.has(ue(h))).map((h)=>({base:h.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:h})),l=new Map;for(let{base:h,file:$}of c){let s=ue($).toLowerCase(),u=l.get(h);if(!u){l.set(h,$);continue}let y=ue(u).toLowerCase();if(e.indexOf(s)<e.indexOf(y))l.set(h,$)}return Array.from(l.entries()).map(([h,$])=>({base:h,file:$})).sort((h,$)=>h.base.localeCompare($.base))}function r(){let f=n(),e=f.map((h)=>h.base),c=e.length?e.map((h)=>`'${h}'`).join(" | "):"string",l=f.length?`{
92
+ ${f.map((h)=>{let $=cl(i,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${$}').default`}).join(`,
93
+ `)}
94
+ }`:"Record<string, any>";return`export type ConfigNames = ${c}
95
+ export type ConfigByName = ${l}
96
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
97
+ export type ConfigOf = Config
98
+ `}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(e)=>{return{path:e.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var ol,gi,Tn,gl,Uy,jy,Al,Ur,Ce,ht,q,Wy,ml,Yy,El,dy,Iy,Ee,Zy,Tl,Sl,Te,Hy,My,zy,Gy,jr,bl,Ky,lt,qy,xy,Rl,Wr,_e,v,Y,Dy,Bl,Oy,Nl,Ly,ky,Se,Vy,Fl,Jl,oy,Re,gy,by,Xy,Py,vy,Yr,Xl,py,Qy="0.15.6",Tt,xr,An,Ue,je,Dr,We,Ye,mn,de,Ie,si,Pl,vl,It,ti,pl,Ql,t0=ty(async()=>{ol=import.meta.require,gi=new Ke,Tn=new qe,gl={createKey:iy,isEquivalent:ny,estimateMemoryUsage:ry},Uy=Zr(Fe.cwd(),"config"),jy=Zr(Fe.cwd(),"src/generated"),Al=Ir.env.CLARITY_LOG_DIR||mu(cy(),"logs"),Ur={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Al,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ce=await hy(),ht={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"},q=ht,Wy=ht.red,ml=ht.green,Yy=ht.yellow,El=ht.blue,dy=ht.magenta,Iy=ht.cyan,Ee=ht.white,Zy=ht.gray,Tl=ht.bgRed,Sl=ht.bgYellow,Te=ht.bold,Hy=ht.dim,My=ht.italic,zy=ht.underline,Gy=ht.reset,jr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bl={debug:"\uD83D\uDD0D",info:El("ℹ"),success:ml("✓"),warning:Sl(Ee(Te(" WARN "))),error:Tl(Ee(Te(" ERROR ")))},Ky=new Gr("stacks"),lt=new Gr("bunfig",{showTags:!0}),qy=ut(an.cwd(),"config"),xy=ut(an.cwd(),"src/generated"),Rl=dr.env.CLARITY_LOG_DIR||au(wy(),"logs"),Wr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},_e=await uy(),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"},Y=v,Dy=v.red,Bl=v.green,Oy=v.yellow,Nl=v.blue,Ly=v.magenta,ky=v.cyan,Se=v.white,Vy=v.gray,Fl=v.bgRed,Jl=v.bgYellow,oy=v.bgGray,Re=v.bold,gy=v.dim,by=v.italic,Xy=v.underline,Py=v.strikethrough,vy=v.reset,Yr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Xl={debug:"\uD83D\uDD0D",info:Nl("ℹ"),success:Bl("✓"),warning:Jl(Se(Re(" WARN "))),error:Fl(Se(Re(" ERROR ")))},py=new qr("stacks"),Tt=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,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},xr=class extends Tt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${t}"${r} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}},An=class extends Tt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Ue=class extends Tt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}},je=class extends Tt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Dr=class extends Tt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}},We=class extends Tt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Ye=class extends Tt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}},mn=class extends Tt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}},de=class extends Tt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}},Ie=class extends Tt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}},si={configNotFound(t,i,n){return new xr(t,i,n)},configLoad(t,i,n){return new An(t,i,n)},configValidation(t,i,n){return new Ue(t,i,n)},configMerge(t,i,n,r){return new je(t,i,n,r)},envVar(t,i,n,r){return new Dr(t,i,n,r)},fileSystem(t,i,n){return new We(t,i,n)},typeGeneration(t,i,n){return new Ye(t,i,n)},schemaValidation(t,i,n){return new mn(t,i,n)},browserConfig(t,i,n,r){return new de(t,i,n,r)},plugin(t,i,n){return new Ie(t,i,n)}},Pl={replace:"replace",concat:"concat",smart:"smart"},vl=/^https?:\/\//,It=new qr("bunfig",{showTags:!0}),ti=new ke,pl=yt(Ai.cwd(),"config"),Ql=yt(Ai.cwd(),"src/generated")});function i0(t,i={}){let n=Hr.cwd();while(n.includes("storage"))n=hl(n,"..");let r=hl(n,t||"");if(i?.relative)return qu(Hr.cwd(),r);return r}var n0=Hr.env.CLARITY_LOG_DIR||Ku(i0(),"logs"),t$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:n0,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Or={...t$},D1=(async()=>{try{let{loadConfig:t}=await t0().then(()=>Gl),i=await t({name:"clarity",alias:"logging",defaultConfig:t$,cwd:Hr.cwd()});if(i)Object.assign(Or,i)}catch{}return Or})();function p(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function r0(){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 i${async format(t){let i=await r0(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Vi.pid,hostname:i(),environment:Vi.env.NODE_ENV||"development",platform:Vi.platform,version:Vi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Vi.env.NODE_ENV||Vi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}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"},I=tt,O1=tt.red,f0=tt.green,L1=tt.yellow,e0=tt.blue,k1=tt.magenta,V1=tt.cyan,Cl=tt.white,o1=tt.gray,c0=tt.bgRed,h0=tt.bgYellow,g1=tt.bgGray,_l=tt.bold,b1=tt.dim,X1=tt.italic,P1=tt.underline,v1=tt.strikethrough,p1=tt.reset,Be={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},l0={debug:"\uD83D\uDD0D",info:e0("ℹ"),success:f0("✓"),warning:h0(Cl(_l(" WARN "))),error:c0(Cl(_l(" ERROR ")))};class Pr{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={...Or},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new i$,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??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Be,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Be};return{...Be,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Or.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await ku(this.config.logDirectory,wl.F_OK|wl.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Vu(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(!Sr(this.currentLogFile))await Ae(this.currentLogFile,"",{mode:420});if(r=sl(this.currentLogFile,"a",420),Lu(r,l,{flag:"a"}),$l(r),r!==void 0)ae(r),r=void 0;if((await Li(this.currentLogFile)).size===0){if(await Ae(this.currentLogFile,l,{flag:"w",mode:420}),(await Li(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let $=h;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let s=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,s);let u=c*2**f;await new Promise((y)=>setTimeout(y,u)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{ae(r)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===e-1){let $=l,s=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}f++;let h=c*2**(f-1);await new Promise(($)=>setTimeout($,h))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}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 ki(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 ki(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return ki(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,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ye(16).toString("hex")}generateKey(){return ye(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(),n=ye(16),r=xu("aes-256-gcm",i,n),f=bt.isBuffer(t)?t:bt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),$=bt.allocUnsafe(16+l+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),h.copy($,16+l),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=yl(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(bt.from(bt.concat(f)))),r.on("error",n),r.write(t),r.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 Li(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 n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Rr(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Li(n).catch(()=>null))try{if(await ul(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await Br(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await Ae(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Li(n).catch(()=>null))await ul(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Rr(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await Br(ki(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=ll(t),r=Ou(i),f=yl();await bu(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),Sr(this.currentLogFile))try{let t=sl(this.currentLogFile,"r+");$l(t),ae(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 Rr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Br(ki(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,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()?I.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof M.env.NO_COLOR<"u",i=M.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=M.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${I.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];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 e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=I.underline(I.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>I.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>I.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>I.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>I.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>I.strikethrough(r)),i}supportsHyperlinks(){if(p())return!1;let t=M.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 n=M.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(ou(i)||i.startsWith("./")||i.startsWith("../"))i=gu(i);else return null;return Sr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){if(!this.shouldLog(t))return;let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":l0[t],y=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",w;switch(t){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:I.gray(h),level:t}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:I.green(h),level:t}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.error(w),l){let m=l.split(`
99
+ `);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:I.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),l)console.error(l)}let s=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
100
+ `;if(l)s+=`${l}
101
+ `;if(s=s.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(s)}progress(t,i=""){let n={update:(f,e)=>{},finish:(f)=>{},interrupt:(f,e)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,e)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),e!==void 0)this.activeProgressBar.message=e;if(this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,e="info")=>{if(!p()&&M.stdout.isTTY)M.stdout.write(`
102
+ `);if(this[e==="warning"?"warn":e](f),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":I.blue("◐"),tag:n,message:`${I.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,l=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
103
+ `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":I.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}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}`,n=new Pr(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(n),n}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!Sr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ll(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 n=this.keys.get(this.currentKeyId);try{let r=bt.isBuffer(t)?t:bt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),l=Du("aes-256-gcm",n,f);l.setAuthTag(e);let h=l.update(c),$=l.final(),s=h.length+$.length,u=bt.allocUnsafe(s);return h.copy(u,0),$.copy(u,h.length),u.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}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,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let l=f.split(`
104
+ `),h=Math.max(...l.map((y)=>y.length))+2,$=`┌${"─".repeat(h)}┐`,s=`└${"─".repeat(h)}┘`,u=l.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:I.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:I.cyan($),showTimestamp:!1})),u.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:I.cyan(s),showTimestamp:!1}))}else if(!p())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
105
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(p())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${I.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();M.stdin.removeListener("data",n);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",n)})}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 n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,l=0;if(n=t.replace(c,(h,$)=>{if($==="%")return"%";if(l>=i.length)return h;let s=i[l++];switch($){case"s":return String(s);case"d":case"i":return Number(s).toString();case"j":case"o":return JSON.stringify(s,null,2);default:return h}}),l<i.length)n+=` ${i.slice(l).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${I.blue("◐")} `;console.error(`${l}${c} ${I.cyan(r)}`)}let e=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
106
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(e)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=I.green("━".repeat(r)),c=I.gray("━".repeat(f)),l=`[${e}${c}]`,h=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",s=this.options.showIcons===!1?"":i||n===100?I.green("✓"):I.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",y=`\r${s}${u} ${l} ${h}${$}`,w=M.stdout.columns||80,m=" ".repeat(Math.max(0,w-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,M.stdout.write(t.lastRenderedLine),i)M.stdout.write(`
107
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!M.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 Rr(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=ki(this.config.logDirectory,r);if(t.before)try{if((await Li(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Br(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var Q1=new Pr("stacks");class Mt 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,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class n$ extends Mt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((e)=>`"${e}"`).join(", ")}`;super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}}class Lr extends Mt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}}class r$ extends Mt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class f$ extends Mt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class Ve extends Mt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}}class e$ extends Mt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class c$ extends Mt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class kr extends Mt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class h$ extends Mt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}}class l$ extends Mt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}}var bi={configNotFound(t,i,n){return new n$(t,i,n)},configLoad(t,i,n){return new Lr(t,i,n)},configValidation(t,i,n){return new r$(t,i,n)},configMerge(t,i,n,r){return new f$(t,i,n,r)},envVar(t,i,n,r){return new Ve(t,i,n,r)},fileSystem(t,i,n){return new e$(t,i,n)},typeGeneration(t,i,n){return new c$(t,i,n)},schemaValidation(t,i,n){return new kr(t,i,n)},browserConfig(t,i,n,r){return new h$(t,i,n,r)},plugin(t,i,n){return new l$(t,i,n)}};async function $0(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(h){if(c=h instanceof Error?h:Error(String(h)),l===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class oe{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,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:l=!1,trackPerformance:h=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let s=r||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],s,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:l,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(h)return Ge.track("applyEnvironmentVariables",$,{configName:t});return $()}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,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],l=c.map((s)=>this.formatEnvKey(s,r.useCamelCase)),h=`${n}_${l.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((s)=>s.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let s=Nr.env[h]||($?Nr.env[$]:void 0);if(s!==void 0){if(r.verbose){let u=Nr.env[h]?h:$}try{t[f]=this.parseEnvironmentValue(s,typeof e,h,r.customParsers,r.configName)}catch(u){if(u instanceof Ve)throw u;throw bi.envVar(h,s,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw bi.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(Nr.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],l=`${n}_${c.map((h)=>this.formatEnvKey(h,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:l,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}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 n=`Environment Variables for ${i}:
108
+
109
+ `;for(let r of t)n+=`${r.key}
110
+ `,n+=` Type: ${r.type}
111
+ `,n+=` Description: ${r.description}
112
+ `,n+=` Example: ${r.example}
113
+
114
+ `;return n}formatAsMarkdown(t,i){let n=`# Environment Variables for ${i}
115
+
116
+ `;n+=`| Variable | Type | Description | Example |
117
+ `,n+=`|----------|------|-------------|----------|
118
+ `;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
119
+ `;return n}}function s0(t,i,n={}){return $$(t,i,n,new WeakMap)}function $$(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return s$(t,i,f,r);if(!_t(i)||!_t(t))return i;return a0(t,i,n,r)}function s$(t,i,n,r){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(n){case"replace":return i;case"concat":return w0(t,i);case"smart":return u0(t,i,r);default:return i}return i}function w0(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Ze(f,r)))n.push(r);return n}function u0(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(_t(i[0])&&_t(t[0]))return y0(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function y0(t,i,n){let r=[...i];for(let f of t){if(!_t(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find((h)=>_t(h)&&(l in h)&&h[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function a0(t,i,n,r){let f=i;if(_t(f)&&r.has(f))return r.get(f);let e={...t};if(_t(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(_t(l)&&_t(h))e[c]=$$(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=s$(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function w$(t,i,n="replace"){return s0(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Ze(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Ze(t[n],i[n]))return!1;return!0}if(_t(t)&&_t(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Ze(t[f],i[f]))return!1}return!0}return!1}function _t(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class u${extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let $=Mr.getWithFileCheck("file",t);if($){if(l)console.log(`Configuration loaded from cache: ${t}`);return $}}let h=async()=>{if(!Fr(t))return null;try{let $=`?t=${Date.now()}`,s=await import(t+$),u=s.default||s,y="default"in s,w=Object.keys(s).length>0;if(!y&&!w)throw new Lr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Lr(t,Error("Configuration must export a valid object"),"unknown");let m={config:w$(i,u,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Mr.setWithFileCheck("file",m,t,e);return m}catch($){throw $ instanceof Error?bi.configLoad(t,$):bi.configLoad(t,Error(String($)))}};if(c)return Ge.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(me(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=i===void 0?[]:Array.isArray(i)?i:[i];for(let e of r){if(!e)continue;if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}let f=new Set;return n.filter((e)=>{if(!e||f.has(e))return!1;return f.add(e),!0})}checkFileAccess(t){return $0(async()=>{return Fr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Fr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=me(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=me(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}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(!Fr(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var A0=/^https?:\/\//;class y${async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,$=async()=>{let s=[],u=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(w){return s.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:s,warnings:u}}};if(l)return await Ge.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Xu(i))throw new kr(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new kr(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,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)r.push({path:n,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))r.push({path:n,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)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let $=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,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))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}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:A0},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Xt=new Pr("bunfig",{showTags:!0});function m0(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((n)=>`"${n}"`).join(", ")}`}class a${fileLoader=new u$;envProcessor=new oe;validator=new y$;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let $=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if($)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let s=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),u=!s&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),y=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if($&&(y||s))throw h;if(u&&(!$||!y))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)Xt.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let h=Date.now()-i;throw Xt.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:$="replace",verbose:s=!1}=t,u=e||gr.cwd(),y=[],w=await this.loadLocalConfiguration(r,f,u,c,l,$,s,h,n);if(w)return y.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(w,y,h,r,s);let m=await this.loadHomeConfiguration(r,f,l,$,s,h);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,h,r,s);let A=await this.loadPackageJsonConfiguration(r,f,u,l,$,s,h);if(A)return y.push(Jt(u,"package.json")),this.finalizeResult(A,y,h,r,s);if(y.push(...this.getAllSearchPaths(r,f,u,c)),i)throw bi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,l,h,s),warnings:[`No configuration file found for "${r}"${m0(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let $=l?Cr(t,f,c):f,s=this.getLocalDirectories(n,r);for(let u of s){if(c)Xt.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),w=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(w){if(c)Xt.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?Cr(t,n,f):n,l=[Jt(Mi(),".config",t),Jt(Mi(),".config"),Mi()];for(let h of l){if(f)Xt.info(`Checking home directory: ${h}`);let $=this.fileLoader.generateConfigPaths(t,h,i),s=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(s){if(f)Xt.success(`Configuration loaded from home directory: ${s.source.path}`);return s}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?Cr(t,r,e):r;try{let h=Jt(n,"package.json");if(!$u(h))return null;let $={};try{$=JSON.parse(su(h,"utf8"))}catch(y){if(e)Xt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let s=$[t],u=t;if(!s&&i){let y=Array.isArray(i)?i:[i];for(let w of y){if(!w)continue;if($[w]){s=$[w],u=w;break}}}if(s&&typeof s==="object"&&!Array.isArray(s)){if(e)Xt.success(`Configuration loaded from package.json: ${u}`);return{config:w$(l,s,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)Xt.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Cr(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw bi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Mr.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Mr.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias){let r=Array.isArray(i.alias)?i.alias.join(","):i.alias;n.push(`alias:${r}`)}if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Jt(t,"config"),Jt(t,".config"),i?Jt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(Jt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[Jt(Mi(),".config",t),Jt(Mi(),".config"),Mi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var tE=new a$;function Cr(t,i,n=!1){let r=new oe,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((A)=>A.toUpperCase()).join("")}`,`${f}_${u.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,m;for(let A of y)if(w=gr.env[A],w!==void 0){m=A;break}if(w!==void 0&&m)if(typeof s==="boolean")h[$]=["true","1","yes"].includes(w.toLowerCase());else if(typeof s==="number"){let A=Number(w);if(!Number.isNaN(A))h[$]=A}else if(Array.isArray(s))try{h[$]=JSON.parse(w)}catch{h[$]=w.split(",").map((A)=>A.trim())}else h[$]=w;else if(s&&typeof s==="object"&&!Array.isArray(s))h[$]=e(s,u)}return h}return e(i)}var iE=Jt(gr.cwd(),"config"),nE=Jt(gr.cwd(),"src/generated"),A$={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:ne.join(ie.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:ne.join(ie.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:ne.join(ie.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},V=A$,Zt={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 F={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},oi={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 He(t,i){let n=[];function r(f){let e;try{e=Ul.readdirSync(f)}catch{return}for(let c of e){let l=dt.join(f,c);try{if(Ul.statSync(l).isDirectory())r(l);else if(c===i)n.push(f)}catch{continue}}}return r(t),n}function N(t,i,n){if(n||V.verbose)console.debug(`[tlsx:${t}] ${i}`)}var R0=S0(E0);function E$(){return m$.env.SUDO_PASSWORD}var jl="[redacted]",B0=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),N0=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function F0(t){let i=t.toLowerCase();return B0.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function Vr(t){if(Array.isArray(t))return t.map((n)=>Vr(n));if(typeof t==="string")return N0.test(t)?jl:t;if(!t||typeof t!=="object")return t;let i={};for(let[n,r]of Object.entries(t)){if(F0(n)){i[n]=jl;continue}i[n]=Vr(r)}return i}function vr(t){return JSON.stringify(Vr(t))}function J0(t){let i=E$();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let n=i.replace(/'/g,"'\\''"),r=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function $i(t,i={}){let n=J0(t);try{let{stdout:r,stderr:f}=await R0(n,{cwd:i.cwd||m$.cwd(),timeout:i.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${t}
120
+ Error: ${r.message}`);throw f.stack=r.stack,f}}function T$(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=dt.join(T0.homedir(),".stacks","ssl"),n=t.basePath&&t.basePath.trim()!==""?t.basePath:V.basePath&&V.basePath.trim()!==""?V.basePath:i,r=t.certPath?dt.isAbsolute(t.certPath)?t.certPath:dt.join(n,t.certPath):dt.join(n,V.certPath),f=t.keyPath?dt.isAbsolute(t.keyPath)?t.keyPath:dt.join(n,t.keyPath):dt.join(n,V.keyPath),e=t.caCertPath?dt.isAbsolute(t.caCertPath)?t.caCertPath:dt.join(n,t.caCertPath):dt.join(n,V.caCertPath);return{certPath:r,keyPath:f,caCertPath:e,basePath:n}}function S$(t){let i=[],n=new Set;if(t.domain)n.add(t.domain);if(t.domains?.length)t.domains.forEach((r)=>n.add(r));for(let r of n)i.push({type:2,value:r});if(t.altNameIPs?.length)for(let r of t.altNameIPs)i.push({type:7,ip:r});if(t.altNameURIs?.length)for(let r of t.altNameURIs)i.push({type:6,value:r});if(t.subjectAltNames?.length)i.push(...t.subjectAltNames);return N(F.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function be(t){let i=t.notBeforeDays??Zt.DEFAULT_NOT_BEFORE_DAYS,n=t.validityDays??(t.validityYears?t.validityYears*365:Zt.DEFAULT_VALIDITY_DAYS);N(F.CERT,"Calculating certificate validity dates",t.verbose);let r=new Date(Date.now()-86400*i*1000),f=new Date(r.getTime()+n*24*60*60*1000);return r.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),N(F.CERT,`Validity period: ${r.toISOString()} to ${f.toISOString()}`,t.verbose),{notBefore:r,notAfter:f}}var Ht={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},at={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 yn(t){if(t<128)return Buffer.from([t]);let i=[],n=t;while(n>0)i.unshift(n&255),n>>=8;return Buffer.from([128|i.length,...i])}function Rt(t,i){let n=yn(i.length);return Buffer.concat([Buffer.from([t]),n,i])}function En(t){let i=t.split(".").map(Number),n=[];n.push(40*i[0]+i[1]);for(let r=2;r<i.length;r++){let f=i[r],e=[];e.unshift(f&127),f>>=7;while(f>0)e.unshift(f&127|128),f>>=7;n.push(...e)}return Rt(Ht.OID,Buffer.from(n))}function Me(t){let i;if(typeof t==="bigint"){let n=t.toString(16).padStart(2,"0");i=Buffer.from(n.length%2?`0${n}`:n,"hex")}else if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let n=t.toString(16).padStart(2,"0");i=Buffer.from(n.length%2?`0${n}`:n,"hex")}else i=t;if(i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return Rt(Ht.INTEGER,i)}function R$(t,i=0){return Rt(Ht.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function B$(t){return Rt(Ht.OCTET_STRING,t)}function St(...t){return Rt(Ht.SEQUENCE,Buffer.concat(t))}function C0(...t){return Rt(Ht.SET,Buffer.concat(t))}function _0(t){return Rt(Ht.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function U0(t){return Rt(Ht.UTF8_STRING,Buffer.from(t,"utf8"))}function j0(){return Buffer.from([Ht.NULL,0])}function Wl(t,i,n=!0){let r=160|t|(n?0:0),f=yn(i.length);return Buffer.concat([Buffer.from([r]),f,i])}function Yl(t){let i=t.getUTCFullYear();if(i>=2050){let n=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Rt(Ht.GENERALIZED_TIME,Buffer.from(n,"ascii"))}else{let n=(i%100).toString().padStart(2,"0"),r=(t.getUTCMonth()+1).toString().padStart(2,"0"),f=t.getUTCDate().toString().padStart(2,"0"),e=t.getUTCHours().toString().padStart(2,"0"),c=t.getUTCMinutes().toString().padStart(2,"0"),l=t.getUTCSeconds().toString().padStart(2,"0"),h=`${n}${r}${f}${e}${c}${l}Z`;return Rt(Ht.UTC_TIME,Buffer.from(h,"ascii"))}}function W0(t,i){return St(Yl(t),Yl(i))}function dl(t){let i=[];for(let n of t){let r;switch(n.shortName){case"CN":r=at.COMMON_NAME;break;case"C":r=at.COUNTRY;break;case"L":r=at.LOCALITY;break;case"ST":r=at.STATE;break;case"O":r=at.ORGANIZATION;break;case"OU":r=at.ORGANIZATIONAL_UNIT;break;default:continue}let f=n.shortName==="C"?_0(n.value):U0(n.value),e=St(En(r),f);i.push(C0(e))}return St(...i)}function N$(t){return St(En(t),j0())}function Y0(t){return t.export({type:"spki",format:"der"})}function d0(t){if(t.includes(":")){let i=t;if(t.includes("::")){let f=t.split("::"),e=f[0]?f[0].split(":"):[],c=f[1]?f[1].split(":"):[],l=8-e.length-c.length,h=Array.from({length:l},()=>"0");i=[...e,...h,...c].join(":")}let n=i.split(":"),r=Buffer.alloc(16);for(let f=0;f<8;f++){let e=Number.parseInt(n[f]||"0",16);r.writeUInt16BE(e,f*2)}return r}else{let i=t.split(".").map((n)=>Number.parseInt(n,10));return Buffer.from(i)}}function I0(t){let i=[];for(let n of t)if(n.type===2&&n.value){let r=yn(n.value.length);i.push(Buffer.concat([Buffer.from([130]),r,Buffer.from(n.value,"ascii")]))}else if(n.type===7&&n.ip){let r=d0(n.ip),f=yn(r.length);i.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=yn(n.value.length);i.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return St(...i)}function Z0(t,i){if(t){if(i!==void 0)return St(Rt(1,Buffer.from([255])),Me(i));return St(Rt(1,Buffer.from([255])))}return St()}function H0(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 n=0,r=i;while(r>0&&(r&1)===0)n++,r>>=1;if(i===0)n=7;return R$(Buffer.from([i]),n)}function M0(t){let i=[];if(t.serverAuth)i.push(En(at.SERVER_AUTH));if(t.clientAuth)i.push(En(at.CLIENT_AUTH));return St(...i)}function wn(t,i,n){let r=[En(t)];if(i)r.push(Rt(1,Buffer.from([255])));return r.push(B$(n)),St(...r)}function z0(t){let i=[];if(i.push(Wl(0,Me(2))),i.push(Me(t.serialNumber)),i.push(N$(at.SHA256_WITH_RSA)),i.push(dl(t.issuer)),i.push(W0(t.notBefore,t.notAfter)),i.push(dl(t.subject)),i.push(Y0(t.publicKey)),t.extensions){let n=[];if(t.extensions.basicConstraints)n.push(wn(at.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,Z0(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)n.push(wn(at.KEY_USAGE,t.extensions.keyUsage.critical??!0,H0(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)n.push(wn(at.EXTENDED_KEY_USAGE,!1,M0(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)n.push(wn(at.SUBJECT_ALT_NAME,!1,I0(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)n.push(wn(at.SUBJECT_KEY_IDENTIFIER,!1,B$(t.extensions.subjectKeyIdentifier)));if(n.length>0)i.push(Wl(3,St(...n)))}return St(...i)}function G0(t,i){let n=Xi.createSign("SHA256");n.update(t);let r=n.sign(i);return St(t,N$(at.SHA256_WITH_RSA),R$(r))}function K0(t,i){let n=t.toString("base64"),r=[];for(let f=0;f<n.length;f+=64)r.push(n.slice(f,f+64));return`-----BEGIN ${i}-----
121
+ ${r.join(`
122
+ `)}
123
+ -----END ${i}-----
124
+ `}function Xe(){return Xi.randomBytes(20)}function F$(t=2048){let{privateKey:i,publicKey:n}=Xi.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:n}}function q0(t){let i=t.export({type:"spki",format:"der"});return Xi.createHash("sha1").update(i).digest()}function J$(t){let i={serialNumber:t.serialNumber||Xe(),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:q0(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 n=z0(i),r=G0(n,t.signingKey);return{certificate:K0(r,"CERTIFICATE"),certificateDer:r}}function C$(t){return t.export({type:"pkcs8",format:"pem"})}function x0(t){return Xi.createPrivateKey(t)}function D0(t){let i=new Xi.X509Certificate(t),n=i.publicKey,r=[],f=i.subject.split(`
125
+ `);for(let e of f){let[c,...l]=e.split("="),h=l.join("=");if(c&&h)r.push({shortName:c.trim(),value:h.trim()})}return{publicKey:n,subject:r}}async function Pe(t={}){N("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||Zt.DEFAULT_KEY_SIZE;N("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:n,publicKey:r}=F$(i),f=[{shortName:"C",value:t.countryName||V.countryName},{shortName:"ST",value:t.stateName||V.stateName},{shortName:"L",value:t.localityName||V.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:e,notAfter:c}=be({validityYears:t.validityYears||Zt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:l}=J$({serialNumber:Xe(),notBefore:e,notAfter:c,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:l,privateKey:C$(n),notBefore:e,notAfter:c}}async function ve(t){if(N("ca","Generating new certificate",t.verbose),N("ca",`Options: ${vr(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}=D0(t.rootCA.certificate),n=x0(t.rootCA.privateKey);N("ca",`Generating ${Zt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let r=Zt.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:e}=F$(r),c=t.commonName||T$(t),l=t.certificateAttributes||[{shortName:"C",value:t.countryName||V.countryName},{shortName:"ST",value:t.stateName||V.stateName},{shortName:"L",value:t.localityName||V.localityName},{shortName:"O",value:t.organizationName||V.organizationName},{shortName:"CN",value:c}],{notBefore:h,notAfter:$}=be({validityDays:t.validityDays||Zt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),s=S$(t),u=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},y=t.extKeyUsage||{serverAuth:!0},{certificate:w}=J$({serialNumber:Xe(),notBefore:h,notAfter:$,subject:l,issuer:i,publicKey:e,signingKey:n,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:u,extendedKeyUsage:y,subjectAltName:s});return{certificate:w,privateKey:C$(f),notBefore:h,notAfter:$}}function _$(t,i){N(F.STORAGE,`Storing certificate and private key with options: ${vr(i)}`,i?.verbose);let{certPath:n,keyPath:r}=ge({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});N(F.STORAGE,`Certificate path: ${n}`,i?.verbose),N(F.STORAGE,`Private key path: ${r}`,i?.verbose);let f=ze.dirname(n);if(!Qt.existsSync(f))N(F.STORAGE,`Creating certificate directory: ${f}`,i?.verbose),Qt.mkdirSync(f,{recursive:!0});N(F.STORAGE,"Writing certificate file",i?.verbose),Qt.writeFileSync(n,t.certificate);let e=ze.dirname(r);if(!Qt.existsSync(e))N(F.STORAGE,`Creating private key directory: ${e}`,i?.verbose),Qt.mkdirSync(e,{recursive:!0});return N(F.STORAGE,"Writing private key file",i?.verbose),Qt.writeFileSync(r,t.privateKey),N(F.STORAGE,"Certificate and private key stored successfully",i?.verbose),n}function U$(t,i){N(F.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:n}=ge({basePath:i?.basePath,caCertPath:i?.caCertPath});N(F.STORAGE,`CA certificate path: ${n}`,i?.verbose);let r=ze.dirname(n);if(!Qt.existsSync(r))N(F.STORAGE,`Creating CA certificate directory: ${r}`,i?.verbose),Qt.mkdirSync(r,{recursive:!0});return N(F.STORAGE,"Writing CA certificate file",i?.verbose),Qt.writeFileSync(n,t),N(F.STORAGE,"CA certificate stored successfully",i?.verbose),n}async function O0(t,i){if(or.platform()!=="darwin")return!1;try{let n=Il(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!n)return N(F.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(Il("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(n))return N(F.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return N(F.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(n){return N(F.TRUST,`Error checking certificate trust: ${n}`,i),!1}}var L0={platform:"darwin",async addCertificate(t,i){if(await O0(t,i?.verbose)){N(F.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),oi.success("Certificate is already trusted in system keychain");return}N(F.TRUST,"Adding certificate to macOS keychain",i?.verbose),await $i(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,n){let r=n||V.commonName;N(F.TRUST,`Removing certificate ${r} from macOS keychain`,i?.verbose);try{await $i(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),N(F.TRUST,`Removed certificate ${r} from macOS keychain`,i?.verbose)}catch(f){throw N(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},k0={platform:"win32",async addCertificate(t,i){N(F.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await $i(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,n){let r=n||V.commonName;N(F.TRUST,`Removing certificate ${r} from Windows certificate store`,i?.verbose);try{await $i(`certutil -delstore -enterprise Root "${r}"`),N(F.TRUST,`Removed certificate ${r} from Windows certificate store`,i?.verbose)}catch(f){throw N(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},V0={platform:"linux",async addCertificate(t,i){N(F.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let n=or.homedir(),r=Zt.LINUX_CERT_DB_FILENAME,f=Zt.LINUX_TRUST_ARGS;N(F.TRUST,`Searching for certificate databases in ${n}`,i?.verbose);let e=He(n,r);if(e.length===0){oi.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of e){N(F.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{N(F.TRUST,`Attempting to delete existing cert for ${V.commonName}`,i?.verbose),await $i(`certutil -d sql:${c} -D -n ${V.commonName}`)}catch(l){N(F.TRUST,`Warning: Error deleting existing cert: ${l}`,i?.verbose),console.warn(`Error deleting existing cert: ${l}`)}N(F.TRUST,`Adding new certificate to ${c}`,i?.verbose),await $i(`certutil -d sql:${c} -A -t ${f} -n ${V.commonName} -i ${t}`),oi.info(`Cert added to ${c}`)}},async removeCertificate(t,i,n){let r=n||V.commonName;N(F.TRUST,`Removing certificate ${r} from Linux certificate store`,i?.verbose);let f=or.homedir(),e=Zt.LINUX_CERT_DB_FILENAME;N(F.TRUST,`Searching for certificate databases in ${f}`,i?.verbose);let c=He(f,e);if(c.length===0){oi.warn("No certificate databases found. Cannot remove certificate.");return}for(let l of c){N(F.TRUST,`Processing certificate database in ${l}`,i?.verbose);try{await $i(`certutil -d sql:${l} -D -n "${r}"`),oi.info(`Cert removed from ${l}`)}catch(h){N(F.TRUST,`Error removing cert from ${l}: ${h}`,i?.verbose),console.warn(`Error removing cert from ${l}: ${h}`)}}}},o0={darwin:L0,win32:k0,linux:V0};async function pe(t,i,n){N(F.TRUST,`Adding certificate to system trust store with options: ${vr(n)}`,n?.verbose),N(F.TRUST,"Storing certificate and private key",n?.verbose);let r=_$(t,n);N(F.TRUST,"Storing CA certificate",n?.verbose);let f=U$(i,n),e=or.platform();N(F.TRUST,`Detected platform: ${e}`,n?.verbose);let c=o0[e];if(!c){let l=`Unsupported platform: ${e}`;throw N(F.TRUST,`Error: ${l}`,n?.verbose),Error(l)}return await c.addCertificate(f,n),N(F.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}var ui=null,b0="rpx-root-ca.crt",X0="rpx-root-ca.key";function Z$(t){return{caCertPath:it(t,b0),caKeyPath:it(t,X0)}}async function P0(t,i){try{let[n,r]=await Promise.all([o.readFile(t.caCertPath,"utf8"),o.readFile(t.caKeyPath,"utf8")]);if(!n.includes("-----BEGIN CERTIFICATE-----")||!r.includes("PRIVATE KEY-----"))return a("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:n,privateKey:r}}catch(n){return a("ssl",`No existing Root CA at ${t.caCertPath} (${n.code||n}), will create one`,i),null}}function j$(t){let i=new Set;i.add(t);let n=t.split(".");if(n.length>=2)i.add(`*.${n.slice(1).join(".")}`);return Array.from(i)}function H$(t){let n=ic(t).replace(/\*/g,"wildcard"),r=it(vi(),".stacks","ssl"),f=r;if(typeof t?.https==="object")return f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:r,{caCertPath:t.https.caCertPath||it(f,`${n}.ca.crt`),certPath:t.https.certPath||it(f,`${n}.crt`),keyPath:t.https.keyPath||it(f,`${n}.key`)};return{caCertPath:it(f,`${n}.ca.crt`),certPath:it(f,`${n}.crt`),keyPath:it(f,`${n}.key`)}}function W$(t){let i=new Set;if(pr(t))t.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";j$(r).forEach((f)=>i.add(f))});else if(d$(t)){let n=t.to||"rpx.localhost";j$(n).forEach((r)=>i.add(r))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function v0(t){a("ssl","Loading SSL configuration",t.verbose);let i={...Hi,...t};if(t.https=mi(i),!t.https?.keyPath&&!t.https?.certPath)return a("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let n=!t.https?.keyPath?"keyPath":"certPath";throw a("ssl",`Invalid SSL configuration - missing ${n}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${n}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{a("ssl","Reading SSL certificate files",t.verbose);let n=await o.readFile(t.https?.keyPath,"utf8"),r=await o.readFile(t.https?.certPath,"utf8");return a("ssl","SSL configuration loaded successfully",t.verbose),{key:n,cert:r}}catch(n){return a("ssl",`Failed to read certificates: ${n}`,t.verbose),null}}catch(n){throw a("ssl",`SSL configuration error: ${n}`,t.verbose),n}}async function p0(t){if(zt.platform==="darwin")return Q0(t);if(zt.platform==="linux")try{let{exec:i}=await import("node:child_process");return await new Promise((n)=>{i(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(r)=>{if(!r)n(!0);else i(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(f)=>{n(!f)})})})}catch{return!1}return!1}async function Q0(t){if(zt.platform!=="darwin")return!1;try{if(await Pi(t,{verbose:!1,regenerateUntrustedCerts:!0}))return a("ssl","Certificate is already trusted, skipping trust operation",!1),!0;a("ssl","Trusting certificate via macOS security command",!1);let n=it(vi(),"Library/Keychains/login.keychain-db");try{if(wi(`security add-trusted-cert -d -r trustRoot -p ssl -p basic -k "${n}" "${t}"`,{stdio:"ignore"}),await Pi(t,{verbose:!1,regenerateUntrustedCerts:!0}))return!0}catch{}try{return tc(`security add-trusted-cert -d -r trustRoot -p ssl -p basic -k /Library/Keychains/System.keychain "${t}"`),await Pi(t,{verbose:!1,regenerateUntrustedCerts:!0})}catch{return!1}}catch{return!1}}async function pi(t){if(ui&&!t.forceRegenerate){a("ssl","Using cached SSL configuration",t.verbose);return}M$();let i=pr(t)?t.proxies.map((s)=>s.to):[t.to];a("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let n=mi(t,t.verbose),r=n.basePath||it(vi(),".stacks","ssl");await o.mkdir(r,{recursive:!0});let f=Z$(r),e=await P0(f,t.verbose),c=!1;if(!e){if(t.verbose)S.info("Generating Root CA certificate (one-time)...");e=await Pe(n);try{await Promise.all([o.writeFile(f.caCertPath,e.certificate),o.writeFile(f.caKeyPath,e.privateKey,{mode:384})]),c=!0,a("ssl",`Persisted Root CA at ${f.caCertPath}`,t.verbose)}catch(s){throw a("ssl",`Error saving Root CA files: ${s}`,t.verbose),Error(`Failed to save Root CA files: ${s}`)}}else a("ssl",`Reusing existing Root CA from ${f.caCertPath}`,t.verbose);if(t.verbose)S.info(`Generating host certificate for: ${i.join(", ")}`);let l=await ve({...n,rootCA:{certificate:e.certificate,privateKey:e.privateKey}});try{await Promise.all([o.writeFile(n.certPath,l.certificate),o.writeFile(n.keyPath,l.privateKey),o.writeFile(n.caCertPath,e.certificate)]),a("ssl","Certificate files saved successfully",t.verbose)}catch(s){throw a("ssl",`Error saving certificate files: ${s}`,t.verbose),Error(`Failed to save certificate files: ${s}`)}if(c?!1:await Pi(f.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(a("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)S.success("Root CA is already trusted in system trust store");if(ui={key:l.privateKey,cert:l.certificate,ca:e.certificate},t.verbose)S.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)S.info("Adding certificate to system trust store (may require sudo permission)...");let $=!1;if(zt.platform==="darwin")try{if(tc(`security add-trusted-cert -d -r trustRoot -p ssl -p basic -k /Library/Keychains/System.keychain "${f.caCertPath}"`),t.verbose)S.success("Successfully added Root CA to system trust store");$=!0;let s=it(r,"trust-rpx-cert.sh"),u=`#!/bin/bash
126
+ echo "Trusting RPX Root CA"
127
+ sudo security add-trusted-cert -d -r trustRoot -p ssl -p basic -k /Library/Keychains/System.keychain "${f.caCertPath}"
128
+ echo "Root CA trusted! Please restart your browser."
129
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
130
+ `;await o.writeFile(s,u,{mode:493})}catch(s){if(t.verbose)S.warn(`Could not add Root CA to trust store automatically: ${s}`);let u=it(r,"trust-rpx-cert.sh"),y=`#!/bin/bash
131
+ echo "Trusting RPX Root CA"
132
+ sudo security add-trusted-cert -d -r trustRoot -p ssl -p basic -k /Library/Keychains/System.keychain "${f.caCertPath}"
133
+ echo "Root CA trusted! Please restart your browser."
134
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
135
+ `;if(await o.writeFile(u,y,{mode:493}),t.verbose)S.info(`Created a trust helper script at: ${u}`),S.info(`If you're still having certificate issues, run: sh ${u}`)}else if(zt.platform==="linux")try{let{exec:s}=await import("node:child_process"),u="/usr/local/share/ca-certificates/rpx",y=`
136
+ mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
137
+ cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
138
+ update-ca-certificates
139
+ echo "RPX Root CA installed. Please restart your browser."
140
+ `,w=it(Qe.tmpdir(),`rpx-trust-${Date.now()}.sh`);await o.writeFile(w,y,{mode:493}),await new Promise((m)=>{s(`sudo bash "${w}"`,(A)=>{if(A){if(t.verbose)S.warn(`Could not trust certificates: ${A}`);m(!1)}else{if(t.verbose)S.success("Successfully added certificates to system trust store");m(!0)}})}),await o.unlink(w).catch(()=>{}),$=!0}catch(s){if(t.verbose)S.warn(`Failed to trust certificates: ${s}`)}else if(zt.platform==="win32")try{let s=`
141
+ $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
142
+ $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
143
+ $store.Open("ReadWrite")
144
+ $store.Add($cert)
145
+ $store.Close()
146
+ Write-Host "Root CA trusted successfully!"
147
+ `,u=it(Qe.tmpdir(),"rpx-trust.ps1");if(await o.writeFile(u,s),wi(`powershell -ExecutionPolicy Bypass -File "${u}"`),t.verbose)S.success("Successfully added certificate to Windows trust store");$=!0}catch(s){if(t.verbose)S.warn(`Could not trust certificate: ${s}`)}else try{await pe(l,e.certificate,n),$=!0}catch(s){if(t.verbose)S.warn(`Could not add certificate to trust store: ${s}`)}if(ui={key:l.privateKey,cert:l.certificate,ca:e.certificate},t.verbose)S.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!$&&t.verbose)S.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),S.warn("This will bypass the warning and you should only need to do it once")}function M$(){ui=null}async function ii(t){if(!t)return null;if(ui)return ui;let i=mi(t);try{let[n,r,f]=await Promise.all([o.access(i.keyPath).then(()=>!0).catch(()=>!1),o.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?o.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!n||!r)return a("ssl",`Certificate files don't exist: key=${n}, cert=${r}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let e="regenerateUntrustedCerts"in t,c=t.regenerateUntrustedCerts,l=e?c!==!1:!0;a("ssl",`Trust check: hasFlag=${e}, flagValue=${c}, shouldCheckTrust=${l}`,t.verbose);let h=i.basePath||it(vi(),".stacks","ssl"),$=Z$(h);if(!(l?await Pi($.caCertPath,t):!0))return a("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[u,y,w]=await Promise.all([o.readFile(i.keyPath,"utf8"),o.readFile(i.certPath,"utf8"),f&&i.caCertPath?o.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(w&&!w.includes("-----BEGIN CERTIFICATE-----"))return a("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(pr(t))try{let{X509Certificate:m}=await import("node:crypto"),T=new m(y).subjectAltName||"",R=t.proxies.map((J)=>J.to).filter((J)=>!T.includes(`DNS:${J}`));if(R.length>0)return a("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,t.verbose),null}catch(m){a("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return a("ssl","Successfully loaded existing certificates",t.verbose),ui={key:u,cert:y,ca:w},ui}catch(n){return a("ssl",`Error checking existing certificates: ${n}`,t.verbose),null}}function mi(t,i){let n=ic(t);a("ssl",`Primary domain: ${n}`,i);let r=H$(t),f=it(vi(),".stacks","ssl");if(typeof t.https==="object"){let e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:f,c={domain:n,hostCertCN:n,basePath:e,caCertPath:t.https.caCertPath||r.caCertPath,certPath:t.https.certPath||r.certPath,keyPath:t.https.keyPath||r.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||n,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(W$(t)).map((l)=>({type:2,value:l}))};if(Y$(t.https.rootCA))c.rootCA=t.https.rootCA;return c}return{domain:n,hostCertCN:n,basePath:f,...r,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:n,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(W$(t)).map((e)=>({type:2,value:e}))}}async function nc(t,i){let n=H$({to:t,verbose:i}),r=[n.caCertPath,n.certPath,n.keyPath];a("certificates","Attempting to clean up relating certificates",i),await Promise.all(r.map((f)=>I$(f,i)))}async function Pi(t,i){try{if(a("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),zt.platform==="darwin")try{let n=wi(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim(),r=(c)=>c.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase(),f=r(n);if(!f)return a("ssl","Could not extract certificate fingerprint",i?.verbose),!1;let e=["/Library/Keychains/System.keychain",it(vi(),"Library/Keychains/login.keychain-db")];for(let c of e)try{let l=wi(`security find-certificate -a -Z "${c}" 2>/dev/null || true`).toString();for(let h of l.split(`
148
+ `))if(h.toUpperCase().includes("SHA-256")&&r(h)===f)return a("ssl",`Certificate fingerprint found in ${c}`,i?.verbose),!0}catch{}return a("ssl","Certificate fingerprint not found in system keychains",i?.verbose),!1}catch(n){return a("ssl",`Error checking certificate trust: ${n}`,i?.verbose),!1}else if(zt.platform==="win32")try{let r=wi(`openssl x509 -noout -subject -in "${t}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!r)return a("ssl","Could not extract certificate subject",i?.verbose),!1;let f=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(wi(f).toString().includes(r))return a("ssl","Certificate found in trusted root store",i?.verbose),!0;return a("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(n){return a("ssl",`Error checking certificate trust on Windows: ${n}`,i?.verbose),!1}else if(zt.platform==="linux")try{let r=wi(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"",f=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let e of f)try{if(wi(`find ${e} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${r}"`).toString().includes(r))return a("ssl",`Certificate fingerprint found in ${e}`,i?.verbose),!0}catch{}return a("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(n){return a("ssl",`Error checking certificate trust on Linux: ${n}`,i?.verbose),!1}return a("ssl",`Platform ${zt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(n){return a("ssl",`Error checking if certificate is trusted: ${n}`,i?.verbose),!1}}function Sn(t,i){return async(n)=>{let r=new URL(n.url),e=(n.headers.get("host")||"").split(":")[0],c=t(e);if(!c)return a("request",`No route found for host: ${e}`,i),new Response(`No proxy configured for ${e}`,{status:404});let l=c.sourceHost,h=r.pathname,$=z$(r.pathname,c.pathRewrites);if($)l=$.targetHost,h=$.targetPath,a("request",`Path rewrite: ${r.pathname} → ${l}${h}`,i);let s=`http://${l}${h}${r.search}`;try{let u=new Headers(n.headers);if(u.set("host",l),c.changeOrigin)u.set("origin",`http://${c.sourceHost}`);u.set("x-forwarded-for","127.0.0.1"),u.set("x-forwarded-proto","https"),u.set("x-forwarded-host",e);let y=await fetch(s,{method:n.method,headers:u,body:n.body,redirect:"manual"});if(c.cleanUrls&&r.pathname.endsWith(".html")){let m=r.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let w=new Headers(y.headers);return new Response(y.body,{status:y.status,statusText:y.statusText,headers:w})}catch(u){return a("request",`Proxy error for ${e}: ${u}`,i),new Response(`Proxy Error: ${u}`,{status:502})}}}import*as Qr from"node:fs";import*as At from"node:fs/promises";import{homedir as ta}from"node:os";import*as rc from"node:path";import*as tf from"node:process";var ia=/^[a-zA-Z0-9._-]+$/;function ni(){return rc.join(ta(),".stacks","rpx","registry.d")}function Qi(t){return typeof t==="string"&&t.length>0&&t.length<=128&&ia.test(t)}function fc(t,i){if(!Qi(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return rc.join(t,`${i}.json`)}function ri(t){if(!Number.isInteger(t)||t<=0)return!1;try{return tf.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function G$(t){if(!t||typeof t!=="object")return!1;let i=t,n=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0;return typeof i.id==="string"&&Qi(i.id)&&typeof i.from==="string"&&i.from.length>0&&typeof i.to==="string"&&i.to.length>0&&n&&typeof i.createdAt==="string"}async function na(t){await At.mkdir(t,{recursive:!0})}async function ec(t,i=ni(),n){if(!G$(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await na(i);let r=fc(i,t.id),f=`${r}.tmp.${tf.pid}.${Date.now()}`,e=JSON.stringify(t,null,2);try{await At.writeFile(f,e,{encoding:"utf8",mode:420}),await At.rename(f,r),a("registry",`wrote entry ${t.id} → ${r}`,n)}catch(c){throw await At.unlink(f).catch(()=>{}),c}}async function nf(t,i=ni(),n){let r=fc(i,t);try{await At.unlink(r),a("registry",`removed entry ${t}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function K$(t,i=ni(),n){let r=fc(i,t);try{let f=await At.readFile(r,"utf8"),e=JSON.parse(f);if(!G$(e))return a("registry",`entry ${t} failed validation, removing`,n),await At.unlink(r).catch(()=>{}),null;return e}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return a("registry",`entry ${t} has invalid JSON, removing`,n),await At.unlink(r).catch(()=>{}),null;throw f}}async function Ei(t=ni(),i){let n;try{n=await At.readdir(t)}catch(f){if(f.code==="ENOENT")return[];throw f}let r=[];for(let f of n){if(!f.endsWith(".json"))continue;let e=f.slice(0,-5);if(!Qi(e))continue;let c=await K$(e,t,i);if(c)r.push(c)}return r}async function rf(t=ni(),i){let n=await Ei(t,i),r=0;for(let f of n){if(f.pid===void 0)continue;if(!ri(f.pid))a("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,i),await nf(f.id,t,i).catch(()=>{}),r++}return r}function cc(t,i={}){let n=i.dir??ni(),r=i.debounceMs??100,f=i.pollMs??Math.max(r*2,250),e=i.verbose;Qr.mkdirSync(n,{recursive:!0});let c=null,l=!1,h=null,$=!1,s=(T)=>{return JSON.stringify(T.map((E)=>({id:E.id,from:E.from,to:E.to,pid:E.pid,pathRewrites:E.pathRewrites,cleanUrls:E.cleanUrls,changeOrigin:E.changeOrigin})).sort((E,R)=>E.id.localeCompare(R.id)))},u=()=>{if(c=null,l)return;Ei(n,e).then((T)=>{return h=s(T),t(T)}).catch((T)=>{a("registry",`watcher onChange failed: ${T}`,e)})},y=()=>{if(l)return;if(c)clearTimeout(c);c=setTimeout(u,r)},m=setInterval(()=>{if(l||$)return;$=!0,Ei(n,e).then((T)=>{if(s(T)!==h)y()}).catch((T)=>{a("registry",`watcher poll failed: ${T}`,e)}).finally(()=>{$=!1})},f),A=Qr.watch(n,{persistent:!0},(T,E)=>{if(E&&/\.tmp\.\d+\.\d+$/.test(E))return;y()});return A.on("error",(T)=>{a("registry",`watcher error: ${T}`,e)}),y(),{close:()=>{if(l=!0,c)clearTimeout(c);clearInterval(m),A.close()}}}var fa=5000;function fi(){return Gt.join(q$(),".stacks","rpx")}function ff(t=fi()){return Gt.join(t,"daemon.pid")}async function nn(t=fi()){try{let i=await Kt.readFile(ff(t),"utf8"),n=Number.parseInt(i.trim(),10);if(!Number.isFinite(n)||n<=0)return null;return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ea(t=fi()){let i=await nn(t);return i!==null&&ri(i)}async function x$(t=fi()){await Kt.mkdir(t,{recursive:!0});let i=ff(t);while(!0){try{let r=await Kt.open(i,"wx");try{await r.write(`${nt.pid}
149
+ `)}finally{await r.close()}return i}catch(r){if(r.code!=="EEXIST")throw r}let n=await nn(t);if(n!==null&&ri(n))throw Error(`rpx daemon already running (pid=${n})`);await Kt.unlink(i).catch(()=>{})}}async function tn(t=fi()){await Kt.unlink(ff(t)).catch(()=>{})}function ca(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 ha(t){return t.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??t[0]??"rpx.localhost"}async function la(t,i){let n=await Ei(i,t.verbose),r=[...new Set(n.map((s)=>s.to))],f=ha(r),e=[...new Set([f,...r,"rpx.localhost"])],c=Gt.join(q$(),".stacks","ssl"),l=Gt.join(c,"rpx.localhost.crt"),h={https:typeof t.https==="object"?{...t.https,certPath:l,keyPath:Gt.join(c,"rpx.localhost.key"),commonName:f}:{certPath:l,keyPath:Gt.join(c,"rpx.localhost.key"),caCertPath:Gt.join(c,"rpx.localhost.ca.crt"),commonName:f},verbose:t.verbose,regenerateUntrustedCerts:!0,...e.length>1?{proxies:e.map((s)=>({from:"localhost:1",to:s}))}:{to:f,from:"localhost:1"}},$=await ii(h);if(!$)a("daemon","no usable cert on disk, generating one",t.verbose),await pi(h),$=await ii(h);if(!$)throw Error("failed to bootstrap TLS for rpx daemon");return $}async function $a(t={}){let i=t.verbose??!1,n=t.rpxDir??fi(),r=t.registryDir??Gt.join(n,"registry.d"),f=t.httpsPort??443,e=t.httpPort??80,c=t.hostname??"0.0.0.0",l=t.gcIntervalMs??fa,h=await x$(n),$=new Map,s=(B)=>$.get(B);function u(B){let $t=new Map;for(let mt of B)$t.set(mt.to,ca(mt));$=$t,a("daemon",`routing table now covers ${$t.size} host(s): ${Array.from($t.keys()).join(", ")||"<empty>"}`,i)}await rf(r,i).catch((B)=>{a("daemon",`initial gc failed: ${B}`,i)}),u(await Ei(r,i));let y=await la(t,r),w=Bun.serve({port:f,hostname:c,tls:{key:y.key,cert:y.cert,ca:y.ca,requestCert:!1,rejectUnauthorized:!1},fetch:Sn(s,i),error(B){return a("daemon",`https server error: ${B}`,i),new Response(`Server Error: ${B.message}`,{status:500})}}),m=null;if(e>0)m=Bun.serve({port:e,hostname:c,fetch(B){let $t=new URL(B.url),mt=(B.headers.get("host")??$t.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${mt}${$t.pathname}${$t.search}`}})}});if(i)S.success(`rpx daemon listening on https://${c}:${f}${m?` (http→https on :${e})`:""}`),S.info(`pid file: ${h}`),S.info(`registry: ${r}`);let A=cc((B)=>{u(B)},{dir:r,verbose:i}),T=setInterval(()=>{rf(r,i).then((B)=>{if(B>0)a("daemon",`gc reaped ${B} stale entries`,i)}).catch((B)=>{a("daemon",`periodic gc failed: ${B}`,i)})},l);if(typeof T.unref==="function")T.unref();let E=!1,R,J=new Promise((B)=>{R=B});async function C(){if(E)return J;if(E=!0,clearInterval(T),A.close(),w.stop(!1),m?.stop(!1),await tn(n),i)S.info("rpx daemon stopped");return R(),J}let j=(B)=>{a("daemon",`received ${B}, shutting down`,i),C().catch(()=>{})};return nt.once("SIGINT",j),nt.once("SIGTERM",j),{stop:C,done:J,httpsPort:typeof w.port==="number"?w.port:f,httpPort:m&&typeof m.port==="number"?m.port:e,pidPath:h}}function D$(){let t=nt.execPath,i=Gt.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&nt.argv[1])return[t,nt.argv[1],"daemon:start"];return[t,"daemon:start"]}async function hc(t={}){let i=t.rpxDir??fi(),n=t.verbose??!1,r=await nn(i);if(r!==null&&ri(r))return a("daemon",`ensureDaemonRunning: already running pid=${r}`,n),{pid:r,spawned:!1};if(r!==null)a("daemon",`ensureDaemonRunning: clearing stale pid=${r}`,n),await tn(i);await Kt.mkdir(i,{recursive:!0});let f=t.spawnCommand??D$();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");a("daemon",`spawning daemon: ${f.join(" ")}`,n);let e=ra(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??nt.cwd(),env:t.spawnEnv?{...nt.env,...t.spawnEnv}:nt.env});e.unref();let c=null;e.once("error",(s)=>{c=s});let l=t.startupTimeoutMs??5000,h=t.pollIntervalMs??50,$=Date.now()+l;while(Date.now()<$){if(c)throw c;let s=await nn(i);if(s!==null&&ri(s))return a("daemon",`daemon registered with pid=${s}`,n),{pid:s,spawned:!0};await new Promise((u)=>setTimeout(u,h))}if(c)throw c;throw Error(`rpx daemon failed to start within ${l}ms (rpxDir=${i})`)}async function sa(t={}){let i=t.rpxDir??fi(),n=t.verbose??!1,r=t.timeoutMs??5000,f=t.pollIntervalMs??50,e=t.forceAfterTimeout??!0,c=await nn(i);if(c===null||!ri(c)){if(c!==null)await tn(i);return{stopped:!1,pid:c,forced:!1}}try{nt.kill(c,"SIGTERM")}catch(h){if(h.code==="ESRCH")return await tn(i),{stopped:!1,pid:c,forced:!1};throw h}let l=Date.now()+r;while(Date.now()<l){if(!ri(c))return a("daemon",`daemon pid=${c} stopped cleanly`,n),{stopped:!0,pid:c,forced:!1};await new Promise((h)=>setTimeout(h,f))}if(!e)throw Error(`rpx daemon (pid=${c}) did not exit within ${r}ms`);a("daemon",`daemon pid=${c} did not exit, escalating to SIGKILL`,n);try{nt.kill(c,"SIGKILL")}catch(h){if(h.code!=="ESRCH")throw h}return await tn(i),{stopped:!0,pid:c,forced:!0}}function k$(t){let i=t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return i.length>0?i:"rpx"}async function ef(t){if(t.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let i=t.verbose??!1,n=t.registryDir,r=new Set,f=t.proxies.map((y)=>{let w=y.id??k$(y.to);if(!Qi(w))throw Error(`invalid registry id "${w}" derived from to="${y.to}"`);if(r.has(w))throw Error(`duplicate registry id "${w}" — set an explicit \`id\` on one of the proxies`);return r.add(w),{...y,id:w}}),e=new Date().toISOString();for(let y of f)await ec({id:y.id,from:y.from,to:y.to,pid:t.persistent?void 0:qt.pid,cwd:qt.cwd(),createdAt:e,cleanUrls:y.cleanUrls,changeOrigin:y.changeOrigin,pathRewrites:y.pathRewrites},n,i);let c=await hc({rpxDir:t.rpxDir,verbose:i,spawnCommand:t.spawnCommand,startupTimeoutMs:t.startupTimeoutMs,spawnEnv:t.spawnEnv});for(let y of f)S.success(`https://${y.to} → ${y.from}`);if(S.info(`(via rpx daemon pid=${c.pid}; \`rpx daemon:status\` to inspect)`),t.detached)return;let l=!1,h=n??ni(),$=f.map((y)=>y.id),s=async()=>{if(l)return;l=!0;for(let y of $)await nf(y,n,i).catch((w)=>{a("runner",`removeEntry(${y}) failed: ${w}`,i)})},u=(y)=>{a("runner",`received ${y}, unregistering ${$.length} entries`,i),s().finally(()=>qt.exit(0))};qt.once("SIGINT",u),qt.once("SIGTERM",u),qt.once("exit",()=>{if(l)return;for(let y of $)try{O$.unlinkSync(L$.join(h,`${y}.json`))}catch{}}),await new Promise(()=>{})}import{exec as wa}from"node:child_process";import Ti from"node:fs";import V$ from"node:os";import $c from"node:path";import*as Bn from"node:process";import{promisify as ua}from"node:util";var cf=ua(wa),Ut=Bn.platform==="win32"?$c.join(Bn.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",lc=!1;async function hf(t){if(Bn.platform==="win32")throw Error("Administrator privileges required on Windows");let i=Rn(),n=t.replace(/'/g,"'\\''");try{if(i){let{stdout:f}=await cf(`echo '${i}' | sudo -S sh -c '${n}' 2>/dev/null`);return lc=!0,f}if(lc)try{let{stdout:f}=await cf(`sudo -n sh -c '${n}'`);return f}catch(f){a("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:r}=await cf(`sudo sh -c '${n}'`);return lc=!0,r}catch(r){throw Error(`Failed to execute sudo command: ${r.message}`)}}async function rn(t,i){a("hosts",`Adding hosts: ${t.join(", ")}`,i),a("hosts",`Using hosts file at: ${Ut}`,i);try{let n;try{n=await Ti.promises.readFile(Ut,"utf-8")}catch{a("hosts","Reading hosts file requires elevated permissions, using sudo",i);try{n=await hf(`cat "${Ut}"`)}catch(c){throw console.log(" Could not read hosts file — skipping hosts setup"),a("hosts",`sudo read also failed: ${c}`,i),Error(`Cannot read hosts file: ${c}`)}}let r=t.filter((c)=>{let l=`127.0.0.1 ${c}`,h=`::1 ${c}`;return!n.includes(l)&&!n.includes(h)});if(r.length===0){a("hosts","All hosts already exist in hosts file",i);return}let f=r.map((c)=>`
150
+ # Added by rpx
151
+ 127.0.0.1 ${c}
152
+ ::1 ${c}`).join(`
153
+ `),e=$c.join(V$.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Ti.promises.writeFile(e,n+f,"utf8"),await hf(`cat "${e}" | tee "${Ut}" > /dev/null`),console.log(` Hosts updated: ${r.join(", ")}`)}catch(c){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),r.forEach((l)=>{console.log(` 127.0.0.1 ${l}`),console.log(` ::1 ${l}`)}),console.log(` Or run: sudo nano ${Ut}`)}finally{try{await Ti.promises.unlink(e)}catch{}}}catch(n){a("hosts",`Failed to manage hosts file: ${n.message}`,i)}}async function sc(t,i){a("hosts",`Removing hosts: ${t.join(", ")}`,i);try{let n;try{n=await Ti.promises.readFile(Ut,"utf-8")}catch{a("hosts","Reading hosts file requires elevated permissions, using sudo",i);try{n=await hf(`cat "${Ut}"`)}catch(h){throw a("hosts",`sudo read also failed: ${h}`,i),Error(`Cannot read hosts file: ${h}`)}}let r=n.split(`
154
+ `),f=!1,e=r.filter((h)=>{if(t.some((s)=>h.includes(` ${s}`)&&(h.includes("127.0.0.1")||h.includes("::1"))))return f=!0,!1;if(h.trim()==="# Added by rpx")return f=!0,!1;return!0});if(!f){a("hosts","No matching hosts found to remove",i);return}while(e[e.length-1]?.trim()==="")e.pop();let c=`${e.join(`
155
+ `)}
156
+ `,l=$c.join(V$.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Ti.promises.writeFile(l,c,"utf8"),await hf(`cat "${l}" | tee "${Ut}" > /dev/null`),a("hosts","Hosts removed successfully",i)}catch(h){a("hosts","Could not clean up hosts file automatically",i)}finally{try{await Ti.promises.unlink(l)}catch(h){a("hosts",`Failed to remove temporary file: ${h}`,i)}}}catch(n){a("hosts",`Failed to clean up hosts file: ${n.message}`,i)}}async function fn(t,i){a("hosts",`Checking hosts: ${t}`,i);let n;try{n=await Ti.promises.readFile(Ut,"utf-8")}catch(r){a("hosts",`Error reading hosts file: ${r}`,i);try{let f=Rn(),e;if(f)e=`echo '${f}' | sudo -S cat "${Ut}" 2>/dev/null`;else e=`sudo -n cat "${Ut}" 2>/dev/null || cat "${Ut}" 2>/dev/null || echo ""`;let{stdout:c}=await cf(e);n=c}catch(f){return a("hosts",`Cannot read hosts file, assuming entries don't exist: ${f}`,i),t.map(()=>!1)}}return t.map((r)=>{let f=`127.0.0.1 ${r}`,e=`::1 ${r}`;return n.includes(f)||n.includes(e)})}import*as lf from"node:net";function yi(t,i,n){return a("port",`Checking if port ${t} is in use on ${i}`,n),new Promise((r)=>{let f=lf.createServer(),e=setTimeout(()=>{a("port",`Checking port ${t} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(c)=>{if(clearTimeout(e),c.code==="EADDRINUSE")a("port",`Port ${t} is in use`,n),r(!0);else a("port",`Error checking port ${t}: ${c.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout(e),a("port",`Port ${t} is available`,n),f.close(),r(!1)});try{f.listen(t,i)}catch(c){clearTimeout(e),a("port",`Exception checking port ${t}: ${c}`,n),r(!0)}})}async function g$(t,i,n,r=50){a("port",`Finding available port starting from ${t} (max attempts: ${r})`,n);let f=t,e=0;while(e<r){if(e++,!await yi(f,i,n))return a("port",`Found available port: ${f} after ${e} attempts`,n),f;a("port",`Port ${f} is in use, trying ${f+1} (attempt ${e}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${t}`)}function o$(t,i,n=5000,r){return a("port",`Testing connection to ${i}:${t}`,r),new Promise((f)=>{let e=lf.connect({host:i,port:t,timeout:n});e.once("connect",()=>{a("port",`Successfully connected to ${i}:${t}`,r),e.end(),f(!0)}),e.once("timeout",()=>{a("port",`Connection to ${i}:${t} timed out`,r),e.destroy(),f(!1)}),e.once("error",(c)=>{a("port",`Failed to connect to ${i}:${t}: ${c.message}`,r),e.destroy(),f(!1)})})}class Nn{usedPorts=new Set;hostname;verbose;maxRetries;constructor(t="0.0.0.0",i,n=50){this.hostname=t,this.verbose=i,this.maxRetries=n}async getNextAvailablePort(t,i=!1){if(this.usedPorts.has(t))return this.findNextAvailablePort(t+1,i);if(await yi(t,this.hostname,this.verbose))return this.findNextAvailablePort(t+1,i);if(i){if(!await o$(t,this.hostname,3000,this.verbose))return a("port",`Port ${t} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(t+1,i)}return this.usedPorts.add(t),t}async findNextAvailablePort(t,i=!1){let n=await g$(t,this.hostname,this.verbose,this.maxRetries);if(i){if(!await o$(n,this.hostname,3000,this.verbose))if(n<t+this.maxRetries)return this.findNextAvailablePort(n+1,i);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(t){a("port",`Releasing port ${t}`,this.verbose),this.usedPorts.delete(t)}}var ya=new Nn;import{spawn as aa}from"node:child_process";import*as Si from"node:process";class $f{processes=new Map;isShuttingDown=!1;async startProcess(t,i,n){if(this.processes.has(t)){a("start",`Process ${t} is already running`,n);return}let[r,...f]=i.command.split(" "),e=i.cwd||Si.cwd();a("start",`Starting process ${t}:`,n),a("start",` Command: ${r} ${f.join(" ")}`,n),a("start",` Working directory: ${e}`,n),a("start",` Environment variables: ${ei(i.env)}`,n);let c=aa(r,f,{cwd:e,env:{...Si.env,...i.env},shell:!0,stdio:"inherit"});return this.processes.set(t,{command:i.command,cwd:e,process:c,env:i.env}),new Promise((l,h)=>{if(c.on("error",($)=>{if(!this.isShuttingDown)a("start",`Process ${t} failed to start: ${$}`,n),this.processes.delete(t),h($),Si.emit("SIGINT")}),c.on("exit",($)=>{if(!this.isShuttingDown&&$!==null&&$!==0)a("start",`Process ${t} exited with code ${$}`,n),this.processes.delete(t),h(Error(`Process ${t} exited with code ${$}`)),Si.emit("SIGINT")}),n)c.stdout?.on("data",($)=>{a("process",`[${t}] ${$.toString().trim()}`,!0)}),c.stderr?.on("data",($)=>{a("process",`[${t}] ERR: ${$.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&c.killed)this.processes.delete(t),h(Error(`Process ${t} was killed during startup`));else a("start",`Process ${t} started successfully`,n),l()},1000)})}async stopProcess(t,i){let n=this.processes.get(t);if(!n?.process){a("start",`No process found for ${t}`,i);return}return a("start",`Stopping process ${t}`,i),new Promise((r)=>{if(!n.process){r();return}n.process.once("exit",()=>{this.processes.delete(t),a("start",`Process ${t} stopped`,i),r()});try{n.process.kill("SIGTERM"),setTimeout(()=>{if(n.process){a("start",`Force killing process ${t}`,i);try{n.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){a("start",`Error stopping process ${t}: ${f}`,i),this.processes.delete(t),r()}})}async stopAll(t){if(this.isShuttingDown){a("start","Already shutting down, skipping duplicate stopAll call",t);return}this.isShuttingDown=!0,a("start","Stopping all processes",t);let i=Array.from(this.processes.keys()).map((n)=>this.stopProcess(n,t).catch((r)=>{S.error(`Failed to stop process ${n}:`,r)}));await Promise.allSettled(i),this.processes.clear(),this.isShuttingDown=!1}isRunning(t){let i=this.processes.get(t);return!!i?.process&&!i.process.killed}}var YT=new $f;var wf=new $f,ma="0.12.0",Ea=new Nn("0.0.0.0"),Fn=new Set,wc=!1,sf=null,uc=null;async function Cn(t){if(wc)return a("cleanup","Cleanup already in progress, skipping",t?.verbose),uc||Promise.resolve();wc=!0,a("cleanup","Starting cleanup process",t?.verbose),uc=new Promise((i)=>{sf=i});try{await wf.stopAll(t?.verbose),S.info("Shutting down proxy servers...");let i=[],n=Array.from(Fn).map((r)=>new Promise((f)=>{r.close(()=>{a("cleanup","Server closed successfully",t?.verbose),f()})}));if(i.push(...n),t?.hosts&&t.domains?.length){a("cleanup","Cleaning up hosts file entries",t?.verbose),a("cleanup",`Original domains for cleanup: ${JSON.stringify(t.domains)}`,t?.verbose);let r=t.domains.filter((f)=>{if(f==="test.local")return!0;return f!=="localhost"&&!f.startsWith("localhost.")&&f!=="127.0.0.1"});if(a("cleanup",`Filtered domains for cleanup: ${JSON.stringify(r)}`,t?.verbose),r.length>0)S.info("Cleaning up hosts file entries..."),i.push(sc(r,t?.verbose).then(()=>{a("cleanup",`Removed hosts entries for ${r.join(", ")}`,t?.verbose)}).catch((f)=>{a("cleanup",`Failed to remove hosts entries: ${f}`,t?.verbose),S.warn(`Failed to clean up hosts file entries for ${r.join(", ")}:`,f)}))}if(t?.certs&&t.domains?.length){a("cleanup","Cleaning up SSL certificates",t?.verbose),S.info("Cleaning up SSL certificates...");let r=t.domains.map(async(f)=>{try{await nc(f,t?.verbose),a("cleanup",`Removed certificates for ${f}`,t?.verbose)}catch(e){a("cleanup",`Failed to remove certificates for ${f}: ${e}`,t?.verbose),S.warn(`Failed to clean up certificates for ${f}:`,e)}});i.push(...r)}await Promise.allSettled(i),a("cleanup","All cleanup tasks completed successfully",t?.verbose),S.success("All cleanup tasks completed successfully")}catch(i){a("cleanup",`Error during cleanup: ${i}`,t?.verbose),S.error("Error during cleanup:",i)}finally{if(sf)sf();sf=null,wc=!1;let i=t&&"vitePluginUsage"in t&&t.vitePluginUsage===!0;if(O.env.NODE_ENV!=="test"&&O.env.BUN_ENV!=="test"&&!i)O.exit(0)}return uc}var yc=!1;function ac(t){if(yc){a("signal",`Received second ${t} signal, forcing exit`,!0),O.exit(1);return}yc=!0,a("signal",`Received ${t} signal, initiating cleanup`,!0),Cn().catch((i)=>{a("signal",`Cleanup failed after ${t}: ${i}`,!0),O.exit(1)}).finally(()=>{yc=!1})}O.once("SIGINT",()=>ac("SIGINT"));O.once("SIGTERM",()=>ac("SIGTERM"));O.on("uncaughtException",(t)=>{a("process",`Uncaught exception: ${t}`,!0),S.error("Uncaught exception:",t),ac("uncaughtException")});async function Jn(t,i,n,r=5){a("connection",`Testing connection to ${t}:${i} (retries left: ${r})`,n);let f=15000,e=Date.now();if(O.env.RPX_BYPASS_CONNECTION_TEST==="true"){a("connection",`Bypassing connection test for ${t}:${i} due to RPX_BYPASS_CONNECTION_TEST flag`,n);return}let c=()=>new Promise((l,h)=>{let $=P$.connect({host:t,port:i,timeout:3000});$.once("connect",()=>{a("connection",`Successfully connected to ${t}:${i}`,n),$.end(),l()}),$.once("timeout",()=>{a("connection",`Connection to ${t}:${i} timed out`,n),$.destroy(),h(Error("Connection timed out"))}),$.once("error",(s)=>{a("connection",`Failed to connect to ${t}:${i}: ${s}`,n),$.destroy(),h(s)})});try{await c()}catch(l){if(Date.now()-e>f){a("connection",`Connection test timed out after ${f}ms, but continuing anyway`,n),S.warn(`Connection test to ${t}:${i} timed out, but RPX will try to proceed anyway.`);return}if(l.code==="ECONNREFUSED"&&r>0)return a("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${r} retries left)`,n),await new Promise(($)=>setTimeout($,2000)),Jn(t,i,n,r-1);if(r>0)try{a("connection",`Trying HTTP request to ${t}:${i}`,n),await new Promise(($,s)=>{let u=Ri.request({hostname:t,port:i,path:"/",method:"HEAD",timeout:5000},(y)=>{a("connection",`Received HTTP response with status: ${y.statusCode}`,n),$()});u.on("error",(y)=>s(y)),u.on("timeout",()=>{u.destroy(),s(Error("HTTP request timed out"))}),u.end()}),a("connection",`HTTP request to ${t}:${i} succeeded`,n);return}catch($){return a("connection",`HTTP request to ${t}:${i} failed: ${$}`,n),a("connection",`Retrying socket connection in 2 seconds... (${r} retries left)`,n),await new Promise((s)=>setTimeout(s,2000)),Jn(t,i,n,r-1)}let h=`Failed to connect to ${t}:${i} after ${5-r} attempts: ${l.message}`;a("connection",`${h}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,n),S.warn(h),S.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function Ac(t){a("server",`Starting server with options: ${ei(t)}`,t.verbose);let i=new URL((t.from?.startsWith("http")?t.from:`http://${t.from}`)||"localhost:5173"),n=new URL((t.to?.startsWith("http")?t.to:`http://${t.to}`)||"rpx.localhost"),r=Number.parseInt(i.port)||(i.protocol.includes("https:")?443:80),f=[n.hostname];if(!n.hostname.includes("localhost")&&!n.hostname.includes("127.0.0.1")){a("hosts",`Checking if hosts file entry exists for: ${n.hostname}`,t?.verbose);try{if(!(await fn(f,t.verbose))[0]){S.info(`Adding ${n.hostname} to hosts file...`),S.info("This may require sudo/administrator privileges");try{await rn(f,t.verbose)}catch(l){if(S.error("Failed to add hosts entry:",l.message),S.warn("You can manually add this entry to your hosts file:"),S.warn(`127.0.0.1 ${n.hostname}`),S.warn(`::1 ${n.hostname}`),O.platform==="win32")S.warn("On Windows:"),S.warn("1. Run notepad as administrator"),S.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else S.warn("On Unix systems:"),S.warn("sudo nano /etc/hosts")}}else a("hosts",`Host entry already exists for ${n.hostname}`,t.verbose)}catch(c){S.error("Failed to check hosts file:",c.message)}}try{await Jn(i.hostname,r,t.verbose)}catch(c){a("server",`Connection test failed: ${c}`,t.verbose),S.error(c.message),S.warn("Continuing with proxy setup despite connection test failure..."),S.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let e=t._cachedSSLConfig||null;if(t.https)try{if(t.https===!0)t.https=mi({...t,to:n.hostname});if(e=await ii({...t,to:n.hostname,https:t.https}),!e){if(a("ssl",`Generating new certificates for ${n.hostname}`,t.verbose),await pi({...t,from:i.toString(),to:n.hostname,https:t.https}),e=await ii({...t,to:n.hostname,https:t.https}),!e)throw Error(`Failed to load SSL configuration after generating certificates for ${n.hostname}`)}}catch(c){throw a("server",`SSL setup failed: ${c}`,t.verbose),c}a("server",`Setting up reverse proxy with SSL config for ${n.hostname}`,t.verbose),await Sa({...t,from:t.from||"localhost:5173",to:n.hostname,fromPort:r,sourceUrl:{hostname:i.hostname,host:i.host},ssl:e})}async function Ta(t,i,n,r,f,e,c,l,h,$,s){a("proxy",`Creating proxy server ${t} -> ${i} with cleanUrls: ${$}`,h);function u(A){let T={};for(let[E,R]of Object.entries(A))if(!E.startsWith(":"))T[E]=R;return T}let y=(A,T)=>{a("request",`Incoming request: ${A.method} ${A.url}`,h);let E=A.url||"/",R=A.method||"GET";if(A instanceof X$.Http2ServerRequest){let B=A.headers;R=B[":method"]||R,E=B[":path"]||E}if($){if(!E.match(/\.[a-z0-9]+$/i))if(E.endsWith("/"))E=`${E}index.html`;else E=`${E}.html`}let J=u(A.headers);if(s)J.host=`${e.hostname}:${n}`,a("request",`Changed origin: setting host header to ${J.host}`,h);let C={hostname:e.hostname,port:n,path:E,method:R,headers:J};a("request",`Proxy request options: ${ei(C)}`,h);let j=Ri.request(C,(B)=>{if(a("response",`Proxy response received with status ${B.statusCode}`,h),$&&B.statusCode===404){let mt=[];if(E.endsWith(".html"))mt.push(E.slice(0,-5));else if(!E.match(/\.[a-z0-9]+$/i))mt.push(`${E}.html`);if(!E.endsWith("/"))mt.push(`${E}/index.html`);if(mt.length>0){a("cleanUrls",`Trying alternative paths: ${mt.join(", ")}`,h);let en=(_n)=>{if(_n.length===0){T.writeHead(B.statusCode||404,B.headers),B.pipe(T);return}let Ec=_n[0],p$={...C,path:Ec},Tc=Ri.request(p$,(Un)=>{if(Un.statusCode===200)a("cleanUrls",`Found matching path: ${Ec}`,h),T.writeHead(Un.statusCode,Un.headers),Un.pipe(T);else en(_n.slice(1))});Tc.on("error",()=>en(_n.slice(1))),Tc.end()};en(mt);return}}let $t={...B.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};T.writeHead(B.statusCode||500,$t),B.pipe(T)});j.on("error",(B)=>{a("request",`Proxy request failed: ${B}`,h),S.error("Proxy request failed:",B),T.writeHead(502),T.end(`Proxy Error: ${B.message}`)}),A.pipe(j)};if(a("server",`Creating server with SSL config: ${!!c}`,h),c)return new Promise((A,T)=>{try{let E=Bun.serve({port:r,hostname:f,tls:{key:c.key,cert:c.cert,ca:c.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let J=new URL(R.url);a("request",`Bun.serve received: ${R.method} ${J.pathname}`,h);let C=`http://${e.host}`,j=new URL(J.pathname+J.search,C);try{let B=new Headers(R.headers);if(B.set("host",e.host),s)B.set("origin",C);B.set("x-forwarded-for","127.0.0.1"),B.set("x-forwarded-proto","https"),B.set("x-forwarded-host",i);let $t=await fetch(j.toString(),{method:R.method,headers:B,body:R.body,redirect:"manual"}),mt=new Headers($t.headers);if($&&J.pathname.endsWith(".html")){let en=J.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:en}})}return new Response($t.body,{status:$t.status,statusText:$t.statusText,headers:mt})}catch(B){return a("request",`Proxy error: ${B}`,h),new Response(`Proxy Error: ${B}`,{status:502})}},error(R){return a("server",`Bun.serve error: ${R}`,h),new Response(`Server Error: ${R.message}`,{status:500})}});Fn.add(E),b$({from:t,to:i,vitePluginUsage:l,listenPort:r,ssl:!0,cleanUrls:$,verbose:h}),A()}catch(E){T(E)}});let w=Ri.createServer(y);function m(A){return Fn.add(A),new Promise((T,E)=>{A.listen(r,f,()=>{a("server",`Server listening on port ${r}`,h),b$({from:t,to:i,vitePluginUsage:l,listenPort:r,ssl:!!c,cleanUrls:$,verbose:h}),T()}),A.on("error",(R)=>{a("server",`Server error: ${R}`,h),E(R)})})}return m(w)}async function Sa(t){a("setup",`Setting up reverse proxy: ${ei(t)}`,t.verbose);let{from:i,to:n,fromPort:r,sourceUrl:f,ssl:e,verbose:c,cleanup:l,vitePluginUsage:h,changeOrigin:$,cleanUrls:s}=t,u=80,y=443,w="0.0.0.0",m=t.portManager||Ea;try{if(n&&!n.includes("localhost")&&!n.includes("127.0.0.1")){if(!(await fn([n],c))[0]){S.warn(`The hostname ${n} isn't in your hosts file. Adding it now...`);try{await rn([n],c),S.success(`Added ${n} to your hosts file.`)}catch(J){S.error(`Failed to add ${n} to your hosts file: ${J}`),S.info(`You may need to manually add '127.0.0.1 ${n}' to your /etc/hosts file.`)}}}else if(O.platform!=="darwin"&&n&&n.includes("localhost")&&!n.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await fn([n],c))[0]){a("hosts",`${n} not found in hosts file, adding...`,c);try{await rn([n],c)}catch(J){a("hosts",`Failed to add ${n} to hosts file: ${J}`,c)}}}if(e&&!m.usedPorts.has(u)){if(!await yi(u,w,c))a("setup","Starting HTTP redirect server",c),v$(c),m.usedPorts.add(u);else if(a("setup","Port 80 is in use, skipping HTTP redirect",c),c)S.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let A=e?y:u,T=await yi(A,w,c),E;if(T){if(a("setup",`Port ${A} is already in use`,c),c)S.warn(`Port ${A} is already in use. This may be another instance of rpx or another service.`);if(A===443){if(E=await m.getNextAvailablePort(3443,!0),a("setup",`Using port ${E} instead of ${A}`,c),c)S.info(`Using port ${E} instead. Access your site at https://${n}:${E}`)}else if(E=await m.getNextAvailablePort(A+1000,!0),a("setup",`Using port ${E} instead of ${A}`,c),c)S.info(`Using port ${E} instead. Access your site at http://${n}:${E}`)}else E=A,m.usedPorts.add(E),a("setup",`Using standard ${A===443?"HTTPS":"HTTP"} port ${A} for ${n}`,c);await Ta(i,n,r,E,w,f,e,h,c,s,$)}catch(A){a("setup",`Setup failed: ${A}`,c),S.error(`Failed to setup reverse proxy: ${A.message}`),Cn({domains:[n],hosts:typeof l==="boolean"?l:l?.hosts,certs:typeof l==="boolean"?l:l?.certs,verbose:c,vitePluginUsage:h})}}function v$(t){a("redirect","Starting HTTP redirect server",t);let i=Ri.createServer((n,r)=>{let f=n.headers.host||"";a("redirect",`Redirecting request from ${f}${n.url} to HTTPS`,t),r.writeHead(301,{Location:`https://${f}${n.url}`}),r.end()}).listen(80);Fn.add(i),a("redirect","HTTP redirect server started",t)}function Ra(t){let i={...Hi,...t};if(a("proxy",`Starting proxy with options: ${ei(i)}`,i?.verbose),i.viaDaemon){if(!i.from||!i.to){S.error("viaDaemon mode requires both `from` and `to`");return}ef({proxies:[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}],verbose:i.verbose}).catch((h)=>{S.error(`Failed to register with rpx daemon: ${h.message}`),O.exit(1)});return}let n=i.to||"",r=n.split(".").pop()?.toLowerCase()||"",f=O.platform==="darwin"&&n&&!n.includes("localhost")&&!n.includes("127.0.0.1"),e=["dev","app","page","new","day","foo"],c=["test","localhost","local","example","invalid"];if(f&&e.includes(r)&&i?.verbose)S.warn(`The .${r} TLD may not work reliably for local development`),S.info(` Google owns .${r} with HSTS preloading, which can bypass local DNS`),S.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(f)import("./chunk-6z1nzq0x.js").then(({startDnsServer:h,setupResolver:$})=>{h([n],i.verbose).then((s)=>{if(s)$(i.verbose,[n]).then(()=>{if(i.verbose)if(c.includes(r))S.success(`DNS server started for .${r} domains`);else S.success(`DNS server started for .${r} domains (hosts file entry also added)`)});else a("dns",`Could not start DNS server - ${n} may not resolve in browser`,i.verbose)})}).catch((h)=>{a("dns",`Failed to start DNS server: ${h}`,i.verbose)});let l={from:i.from,to:i.to,cleanUrls:i.cleanUrls,https:mi(i),cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,changeOrigin:i.changeOrigin,verbose:i.verbose,regenerateUntrustedCerts:i.regenerateUntrustedCerts};a("proxy",`Server options: ${ei(l)}`,i.verbose),Ac(l).catch((h)=>{a("proxy",`Failed to start proxy: ${h}`,i.verbose),S.error(`Failed to start proxy: ${h.message}`),Cn({domains:[i.to],hosts:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.hosts,certs:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.certs,verbose:i.verbose})})}function Ba(t){return t?.verbose||!1}async function mc(t){let i={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(t)i={...i,...t};let n=Ba(i);if(a("config",`Starting with config: ${ei(i,2)}`,n),a("config",`Is multi-proxy? ${"proxies"in i}`,n),i.viaDaemon){let m="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((A)=>({id:A.id,from:A.from,to:A.to,cleanUrls:A.cleanUrls??i.cleanUrls,changeOrigin:A.changeOrigin??i.changeOrigin,pathRewrites:A.pathRewrites})):[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}];await ef({proxies:m,verbose:n});return}if("proxies"in i&&Array.isArray(i.proxies)){a("servers",`Found ${i.proxies.length} proxies in config`,n);for(let w of i.proxies)if(w.start){let m=`${w.from}-${w.to}`;try{a("watch",`Starting command for ${m} with command: ${w.start.command}`,n),S.info(`Starting command for ${m}...`),await wf.startProcess(m,w.start,n);let A=new URL(w.from.startsWith("http")?w.from:`http://${w.from}`),T=A.hostname||"localhost",E=Number(A.port)||80;try{await Jn(T,E,n),a("watch",`Dev server is ready at ${T}:${E}`,n)}catch(R){a("watch",`Connection check failed, but continuing with proxy setup: ${R}`,n),S.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(A){throw a("watch",`Failed to start command for ${m}: ${A}`,n),Error(`Failed to start command for ${m}: ${A}`)}}else a("watch",`No start command for proxy ${w.from} -> ${w.to}`,n)}else if("start"in i&&i.start){a("watch","Found start command in single proxy config",n);let w=`${i.from}-${i.to}`;try{if(i.start)a("watch",`Starting command: ${i.start.command}`,n),await wf.startProcess(w,i.start,n);let m=new URL(i.from?.startsWith("http")?i.from:`http://${i.from}`),A=m.hostname||"localhost",T=Number(m.port)||80;try{await Jn(A,T,n),a("watch",`Dev server is ready at ${A}:${T}`,n)}catch(E){a("watch",`Connection check failed, but continuing with proxy setup: ${E}`,n),S.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(m){throw a("watch",`Failed to run start command: ${m}`,n),Error(`Failed to run start command: ${m}`)}}else a("watch","No start command found in config",n);let r="proxies"in i&&Array.isArray(i.proxies)?i.proxies[0]?.to:("to"in i)?i.to:"rpx.localhost";if(O.platform!=="win32"&&(i.https||i.cleanup?.hosts!==!1)){if(!Rn())try{a("sudo","Pre-acquiring sudo credentials for privileged operations",n),Aa("sudo -v",{stdio:"inherit"})}catch{a("sudo","Could not pre-acquire sudo credentials",n)}}if(i.https){let w=await ii(i);if(!w){if(a("ssl",`No valid or trusted certificates found for ${r}, generating new ones`,i.verbose),await pi(i),w=await ii(i),!w)throw Error(`Failed to load SSL certificates after generation for ${r}`)}else a("ssl",`Using existing and trusted certificates for ${r}`,i.verbose);i._cachedSSLConfig=w}let f="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((w)=>({...w,https:i.https,cleanup:i.cleanup,cleanUrls:w.cleanUrls??("cleanUrls"in i?i.cleanUrls:!1),vitePluginUsage:i.vitePluginUsage,changeOrigin:w.changeOrigin??i.changeOrigin,verbose:n,_cachedSSLConfig:i._cachedSSLConfig})):[{from:"from"in i?i.from:"localhost:5173",to:"to"in i?i.to:"rpx.localhost",cleanUrls:"cleanUrls"in i?i.cleanUrls:!1,https:i.https,cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,start:"start"in i?i.start:void 0,changeOrigin:i.changeOrigin,verbose:n,_cachedSSLConfig:i._cachedSSLConfig}],e=f.map((w)=>w.to||"rpx.localhost"),c=i._cachedSSLConfig,l=e.filter((w)=>w&&!w.includes("localhost")&&!w.includes("127.0.0.1")),h=["dev","app","page","new","day","foo"],$=["test","localhost","local","example","invalid"],s=[...new Set(l.map((w)=>w.split(".").pop()?.toLowerCase()))],u=s.filter((w)=>!!w&&h.includes(w));if(u.length>0&&n)S.warn(`The following TLDs may not work reliably for local development: ${u.map((w)=>`.${w}`).join(", ")}`),S.info(" These TLDs have HSTS preloading which can bypass local DNS"),S.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(O.platform==="darwin"&&l.length>0){let{startDnsServer:w,setupResolver:m}=await import("./chunk-6z1nzq0x.js");if(await w(l,n)){if(await m(n,l),n)if(s.every((E)=>!!E&&$.includes(E)))S.success(`DNS server started for ${s.map((E)=>`.${E}`).join(", ")} domains`);else S.success(`DNS server started for ${s.map((E)=>`.${E}`).join(", ")} domains (hosts file entries also added)`)}else a("dns","Could not start DNS server - custom domains may not resolve",n)}let y=async()=>{a("cleanup","Starting cleanup handler",i.verbose);try{let{stopDnsServer:w,removeResolver:m}=await import("./chunk-6z1nzq0x.js");w(i.verbose),await m(i.verbose)}catch(w){a("cleanup",`Error stopping DNS server: ${w}`,i.verbose)}try{await wf.stopAll(i.verbose)}catch(w){a("cleanup",`Error stopping processes: ${w}`,i.verbose)}await Cn({domains:e,hosts:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.hosts,certs:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.certs,verbose:i.verbose||!1})};if(O.on("SIGINT",y),O.on("SIGTERM",y),O.on("uncaughtException",(w)=>{a("process",`Uncaught exception: ${w}`,!0),console.error("Uncaught exception:",w),y()}),c&&f.length>1){a("proxies",`Creating shared HTTPS server for ${f.length} domains`,n);let w=new Map;for(let E of f){let R=E.to||"rpx.localhost",J=new URL(E.from?.startsWith("http")?E.from:`http://${E.from}`);if(w.set(R,{sourceHost:J.host,cleanUrls:E.cleanUrls||!1,changeOrigin:E.changeOrigin||!1,pathRewrites:E.pathRewrites}),a("proxies",`Route: ${R} → ${J.host}`,n),!R.includes("localhost")&&!R.includes("127.0.0.1"))try{if(!(await fn([R],n))[0])await rn([R],n)}catch{a("hosts",`Could not add hosts entry for ${R}`,n)}}if(!await yi(80,"0.0.0.0",n))v$(n);let A=443;if(await yi(A,"0.0.0.0",n)){if(a("proxies",`Port ${A} is already in use, cannot start shared proxy`,n),n)S.warn(`Port ${A} is in use. Shared HTTPS proxy cannot start.`);return}try{let E=Bun.serve({port:A,hostname:"0.0.0.0",tls:{key:c.key,cert:c.cert,ca:c.ca,requestCert:!1,rejectUnauthorized:!1},fetch:Sn((R)=>w.get(R),n),error(R){return a("server",`Shared proxy server error: ${R}`,n),new Response(`Server Error: ${R.message}`,{status:500})}});Fn.add(E),a("proxies",`Shared HTTPS proxy listening on port ${A} for ${w.size} domains`,n)}catch(E){a("proxies",`Failed to start shared proxy: ${E}`,n),console.error("Failed to start shared HTTPS proxy:",E),y()}}else for(let w of f)try{let m=w.to||"rpx.localhost";a("proxy",`Starting proxy for ${m} with SSL config: ${!!c}`,w.verbose),await Ac({from:w.from||"localhost:5173",to:m,cleanUrls:w.cleanUrls||!1,https:w.https||!1,cleanup:w.cleanup||!1,vitePluginUsage:w.vitePluginUsage||!1,verbose:w.verbose||!1,_cachedSSLConfig:c,changeOrigin:w.changeOrigin||!1})}catch(m){a("proxies",`Failed to start proxy for ${w.to}: ${m}`,w.verbose),console.error(`Failed to start proxy for ${w.to}:`,m),y()}}function b$(t){if(t?.vitePluginUsage||!t?.verbose)return;if(console.log(""),console.log(` ${jt.green(jt.bold("rpx"))} ${jt.green(`v${ma}`)}`),console.log(` ${jt.green("➜")} ${jt.dim(t?.from??"")} ${jt.dim("➜")} ${jt.cyan(t?.ssl?`https://${t?.to}`:`http://${t?.to}`)}`),t?.listenPort!==(t?.ssl?443:80))console.log(` ${jt.green("➜")} Listening on port ${t?.listenPort}`);if(t?.cleanUrls)console.log(` ${jt.green("➜")} Clean URLs enabled`)}var lS=mc;export{ec as writeEntry,cc as watchRegistry,sa as stopDaemon,Ac as startServer,Ra as startProxy,mc as startProxies,ei as safeStringify,I$ as safeDeleteFile,ef as runViaDaemon,$a as runDaemon,z$ as resolvePathRewrite,sc as removeHosts,nf as removeEntry,tn as releaseDaemonLock,$S as redactSensitive,K$ as readEntry,nn as readDaemonPid,Ei as readAll,ya as portManager,v0 as loadSSLConfig,Y$ as isValidRootCA,Qi as isValidId,d$ as isSingleProxyOptions,wS as isSingleProxyConfig,yi as isPortInUse,ri as isPidAlive,pr as isMultiProxyOptions,g0 as isMultiProxyConfig,ea as isDaemonRunning,Pi as isCertTrusted,mi as httpsConfig,Rn as getSudoPassword,ni as getRegistryDir,ic as getPrimaryDomain,fi as getDaemonRpxDir,ff as getDaemonPidPath,pi as generateCertificate,rf as gcStaleEntries,p0 as forceTrustCertificate,g$ as findAvailablePort,sS as extractHostname,tc as execSudoSync,hc as ensureDaemonRunning,k$ as deriveIdFromTarget,D$ as defaultDaemonSpawnCommand,Hi as defaultConfig,lS as default,a as debugLog,Sn as createProxyFetchHandler,Hi as config,jt as colors,M$ as clearSslConfigCache,nc as cleanupCertificates,Cn as cleanup,fn as checkHosts,ii as checkExistingCertificates,rn as addHosts,x$ as acquireDaemonLock,Nn as DefaultPortManager};