@stacksjs/rpx 0.11.9 → 0.11.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +166 -162
- package/dist/chunk-00z9z9an.js +156 -0
- package/dist/chunk-747af2w4.js +1 -0
- package/dist/chunk-end75nnv.js +1 -0
- package/dist/{chunk-jpf41gb9.js → chunk-zs1tyy8z.js} +2 -2
- package/dist/daemon.d.ts +4 -0
- package/dist/dns-state.d.ts +27 -0
- package/dist/dns.d.ts +43 -0
- package/dist/hosts.d.ts +2 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +6 -156
- package/package.json +1 -1
- package/src/daemon.ts +41 -2
- package/src/dns-state.ts +116 -0
- package/src/dns.ts +252 -142
- package/src/hosts.ts +26 -5
- package/src/index.ts +29 -0
- package/src/start.ts +7 -9
- package/src/utils.ts +7 -1
- package/dist/chunk-6z1nzq0x.js +0 -1
- package/dist/chunk-qcdcnadb.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,158 +1,8 @@
|
|
|
1
|
-
import{a as G,b as Un,c as Fn,d as a,e as LS,f as ci,g as kS,h as X$,i as Ac,j as ya,k as wf,l as P$,m as VS,n as tw,o as v$}from"./chunk-jpf41gb9.js";import{execSync as za}from"node:child_process";import*as Bi from"node:http";import*as yw from"node:http2";import*as aw from"node:net";import*as D 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 Mn=(t,i)=>(n)=>`\x1B[${t}m${n}\x1B[${i}m`,dt={bold:Mn(1,22),dim:Mn(2,22),green:Mn(32,39),cyan:Mn(36,39)};import{homedir as se}from"node:os";import{join as ye,resolve as Zm}from"node:path";import{existsSync as Hc,statSync as Mc}from"fs";import{existsSync as Ew,mkdirSync as ga,readdirSync as ba,readFileSync as Tw,writeFileSync as Xa}from"fs";import{homedir as Ci}from"os";import{dirname as pa,resolve as Bt}from"path";import Ar from"process";import{existsSync as zc,statSync as Gc}from"fs";import{existsSync as kf,mkdirSync as Sw,readdirSync as Rw,writeFileSync as Bw}from"fs";import{homedir as Fi}from"os";import{dirname as Kc,resolve as ut}from"path";import Ai from"process";import{join as Cw,relative as Fw,resolve as qc}from"path";import nr from"process";import{existsSync as Cl,mkdirSync as hA,readdirSync as $A,writeFileSync as wA}from"fs";import{homedir as Jf}from"os";import{dirname as yA,resolve as wt}from"path";import wn from"process";import{join as Nw,relative as Jw,resolve as xc}from"path";import rr from"process";import{existsSync as Fl,mkdirSync as TA,readdirSync as SA,writeFileSync as RA}from"fs";import{dirname as CA,resolve as fr}from"path";import Vf from"process";import{Buffer as li}from"buffer";import{createCipheriv as _w,createDecipheriv as Uw,randomBytes as _f}from"crypto";import{closeSync as Uf,createReadStream as Oc,createWriteStream as dw,existsSync as df,fsyncSync as Dc,openSync as Lc,writeFileSync as jw}from"fs";import{access as Ww,constants as kc,mkdir as Yw,readdir as zn,rename as Vc,stat as Ni,unlink as Gn,writeFile as jf}from"fs/promises";import{join as Ji}from"path";import rt from"process";import{pipeline as Iw}from"stream/promises";import{createGzip as oc}from"zlib";import _i from"process";import Lt from"process";import{Buffer as xt}from"buffer";import{createCipheriv as Zw,createDecipheriv as Hw,randomBytes as Wf}from"crypto";import{closeSync as Yf,createReadStream as gc,createWriteStream as Mw,existsSync as Kn,fsyncSync as bc,openSync as Xc,writeFileSync as zw}from"fs";import{access as Gw,constants as Pc,mkdir as Kw,readdir as qn,rename as vc,stat as Ui,unlink as xn,writeFile as If}from"fs/promises";import{isAbsolute as qw,join as di,resolve as xw}from"path";import _ from"process";import{pipeline as Ow}from"stream/promises";import{createGzip as pc}from"zlib";import ji from"process";import kt from"process";import On from"process";import{existsSync as Dn}from"fs";import{resolve as Zf}from"path";import{existsSync as Dw}from"fs";import{existsSync as Lw,readdirSync as kw}from"fs";import{extname as Hf,resolve as Qc}from"path";import Vw from"process";import{join as ow,relative as gw,resolve as tl}from"path";import er from"process";import{Buffer as Ot}from"buffer";import{createCipheriv as bw,createDecipheriv as Xw,randomBytes as Mf}from"crypto";import{closeSync as zf,createReadStream as il,createWriteStream as Pw,existsSync as Ln,fsyncSync as nl,openSync as rl,writeFileSync as vw}from"fs";import{access as pw,constants as fl,mkdir as Qw,readdir as kn,rename as el,stat as Wi,unlink as Vn,writeFile as Gf}from"fs/promises";import{isAbsolute as tu,join as Yi,resolve as iu}from"path";import U from"process";import{pipeline as nu}from"stream/promises";import{createGzip as cl}from"zlib";import Ii from"process";import Vt from"process";import gn from"process";import{existsSync as bn}from"fs";import{resolve as Lf}from"path";import{existsSync as Cs}from"fs";class Rl{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(!Hc(t))return!0;return Mc(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=Hc(n)?Mc(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 Bl{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 ir=new Rl,ne=new Bl;var ru=Object.defineProperty,fu=(t)=>t;function eu(t,i){this[t]=fu.bind(null,i)}var cu=(t,i)=>{for(var n in i)ru(t,n,{get:i[n],enumerable:!0,configurable:!0,set:eu.bind(i,n)})},lu=(t,i)=>()=>(t&&(i=t(t=0)),i),Nl={};cu(Nl,{withErrorRecovery:()=>Ul,tryLoadConfig:()=>Wu,loadConfigWithResult:()=>du,loadConfig:()=>Il,isRetryableError:()=>Cu,isConfigNotFoundError:()=>Bu,isBunfigError:()=>dl,globalPerformanceMonitor:()=>yn,globalCache:()=>Zi,getEnvOrDefault:()=>Fu,generateConfigTypes:()=>Yu,defaultGeneratedDir:()=>xl,defaultConfigDir:()=>ql,deepMergeWithArrayStrategy:()=>le,deepMerge:()=>jl,createLibraryConfig:()=>Iu,config:()=>ju,bunfigPlugin:()=>Zu,applyEnvVarsToConfig:()=>$n,TypeGenerationError:()=>pf,SchemaValidationError:()=>sn,PluginError:()=>te,PerformanceMonitor:()=>fe,FileSystemError:()=>vf,ErrorFactory:()=>hi,EnvVarError:()=>ur,EnvProcessor:()=>mr,ConfigValidator:()=>he,ConfigValidationError:()=>Xf,ConfigNotFoundError:()=>wr,ConfigMergeError:()=>Pf,ConfigLoader:()=>$e,ConfigLoadError:()=>un,ConfigFileLoader:()=>Er,ConfigCache:()=>re,CacheUtils:()=>Hl,BunfigError:()=>Et,BrowserConfigError:()=>Qf,ArrayMergeStrategies:()=>Gl});class re{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(!zc(t))return!0;return Gc(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=zc(n)?Gc(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 fe{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 hu(t,i={}){let r=Object.keys(i).sort().map((f)=>`${f}:${i[f]}`).join("|");return r?`${t}:${r}`:t}function $u(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function wu(t){return t.getStats().size*2}function ee(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)=>cr(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]=ee(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((l)=>x(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(x(c)&&"path"in c){if(!e.find((l)=>x(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((h)=>cr(h,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 cr(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(!cr(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(!cr(t[f],i[f]))return!1}return!0}return!1}function x(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function uu(t,i){if(!Fl(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 ee(i,r)}catch{return null}}catch{return null}}async function su({name:t="",cwd:i,defaultConfig:n}){let r=i||Vf.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let h of f){let l=fr(r,`${c}${h}`),$=await uu(l,n);if($!==null)return $}try{let c=fr(r,"package.json");if(Fl(c)){let l=(await import(c))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return ee(n,l)}catch{}}}catch{}return n}function yu(t,i={}){let n=rr.cwd();while(n.includes("storage"))n=xc(n,"..");let r=xc(n,t||"");if(i?.relative)return Jw(rr.cwd(),r);return r}async function au(){try{let t=await su({name:"clarity",defaultConfig:vn,cwd:rr.cwd(),endpoint:"",headers:{}});return{...vn,...t}}catch{return vn}}function L(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Au(){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 Jl{async format(t){let i=await Au(),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:_i.pid,hostname:i(),environment:_i.env.NODE_ENV||"development",platform:_i.platform,version:_i.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_i.env.NODE_ENV||_i.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class lr{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={...gf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Jl,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{...pn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...pn};return{...pn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:gf.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,h=1000;while(e<c)try{try{try{await Ww(this.config.logDirectory,kc.F_OK|kc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Yw(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:li.from(t);try{if(!df(this.currentLogFile))await jf(this.currentLogFile,"",{mode:420});if(f=Lc(this.currentLogFile,"a",420),jw(f,l,{flag:"a"}),Dc(f),f!==void 0)Uf(f),f=void 0;if((await Ni(this.currentLogFile)).size===0){if(await jf(this.currentLogFile,l,{flag:"w",mode:420}),(await Ni(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let w=$;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(e<c-1){let s=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,s);let y=h*2**e;await new Promise((u)=>setTimeout(u,y)),e++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(f!==void 0)try{Uf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(l){if(e===c-1){let w=l,s=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}e++;let $=h*2**(e-1);await new Promise((w)=>setTimeout(w,$))}})();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(([,h],[,l])=>l.createdAt.getTime()-h.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[h]of f.slice(c))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return _f(16).toString("hex")}generateKey(){return _f(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=_f(16),r=_w("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=oc(),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(L())return;let t=await Ni(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await zn(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Ni(n).catch(()=>null))try{if(await Vc(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Gn(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await jf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ni(n).catch(()=>null))await Vc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await zn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,h)=>h.localeCompare(c));for(let c of e.slice(i.maxFiles))await Gn(Ji(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=Oc(t),r=dw(i),f=oc();await Iw(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()})),df(this.currentLogFile))try{let t=Lc(this.currentLogFile,"r+");Dc(t),Uf(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 zn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Gn(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,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=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 w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 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,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!L()){let $=Ml[t],w=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",s;switch(t){case"debug":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:K.gray(c),level:t}),console.error(s);break;case"info":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s);break;case"success":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:K.green(c),level:t}),console.error(s);break;case"warning":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.warn(s);break;case"error":if(s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s),h){let y=h.split(`
|
|
2
|
-
`);for(let u of y)if(u.trim()&&!u.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:K.gray(` ${u}`),level:t,showTimestamp:!1}))}break}}else if(!L()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let l=`${e} ${this.environment}.${t.toUpperCase()}: ${c}
|
|
3
|
-
`;if(h)l+=`${h}
|
|
4
|
-
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}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,h=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 w=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:K.green("✓"),tag:w,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 lr(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(!df(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Oc(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),h=Uw("aes-256-gcm",n,f);return h.setAuthTag(e),li.concat([h.update(c),h.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((w)=>w.length))+2,h=`┌${"─".repeat(c)}┐`,l=`└${"─".repeat(c)}┘`,$=e.map((w)=>{let s=" ".repeat(c-w.length-2);return`│ ${w}${s} │`});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(h)})),$.forEach((w)=>console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(w),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(l),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,h=0;if(n=t.replace(c,(l,$)=>{if($==="%")return"%";if(h>=i.length)return l;let w=i[h++];switch($){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return l}}),h<i.length)n+=` ${i.slice(h).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!L()){let c=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",h=K.blue("◐");console.error(`${h} ${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,h)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,c)),h!==void 0)this.activeProgressBar.message=h;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},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,h="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;rt.stdout.write(`${"\r".padEnd(rt.stdout.columns||80)}\r`),this.log(h,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)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=i||n===100?K.green("✓"):K.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=rt.stdout.columns||80,m=" ".repeat(Math.max(0,u-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 zn(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 Ni(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 Gn(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 Pn(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)=>hr(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]=Pn(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((h)=>hr(h,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 ce(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:Pn(t,i);if(Array.isArray(t))return n==="replace"?i:Pn(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]=Pn(c,e);else if(Z(e)&&Z(c))r[f]=ce(c,e,n);else r[f]=e}return r}function hr(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(!hr(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(!hr(t[f],i[f]))return!1}return!0}return!1}function Z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function on(t,i,n="replace"){if(!Cl(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 ce(i,f,n)}catch{return null}}catch{return null}}function mu(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${r}_${s.map(y).join("_")}`,m=`${r}_${s.map((A)=>A.toUpperCase()).join("_")}`;if(n)et.info(`Checking environment variable ${u} for config ${t}.${s.join(".")}`);if(typeof w==="object"&&w!==null&&!Array.isArray(w))l[$]=e(w,s);else{let A=wn.env[u]||wn.env[m];if(A!==void 0){if(n)et.info(`Using environment variable ${A?u:m} for config ${t}.${s.join(".")}`);if(typeof w==="number")l[$]=Number(A);else if(typeof w==="boolean")l[$]=A.toLowerCase()==="true";else if(Array.isArray(w))try{let T=JSON.parse(A);if(Array.isArray(T))l[$]=T;else l[$]=A.split(",").map((E)=>E.trim())}catch{l[$]=A.split(",").map((T)=>T.trim())}else l[$]=A}}}return l}return e(f)}async function Eu({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:h="replace"}){let l=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?mu(t,f,e):f,$=n||wn.cwd(),w=[".ts",".js",".mjs",".cjs",".json"];if(e)et.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${$}`);let s=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),u=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([$,wt($,"config"),wt($,".config"),r?wt($,r):void 0].filter(Boolean)));for(let T of A){if(e)et.info(`Searching for configuration in: ${T}`);let R=[wt($,"config"),wt($,".config")].concat(r?[wt($,r)]:[]).includes(T)?[...s,...y,...u,...m]:[...y,...s,...m,...u];for(let N of R)for(let J of w){let d=wt(T,`${N}${J}`),B=await on(d,l,h);if(B!==null){if(e)et.success(`Configuration loaded from: ${d}`);return B}}}if(t){let T=wt(Jf(),".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 N of w){let J=wt(T,`${R}${N}`),d=await on(J,l,h);if(d!==null){if(e)et.success(`Configuration loaded from user config directory: ${J}`);return d}}}if(t){let T=wt(Jf(),".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 N of w){let J=wt(T,`${R}${N}`),d=await on(J,l,h);if(d!==null){if(e)et.success(`Configuration loaded from user config directory dotfile: ${J}`);return d}}}if(t){let T=Jf(),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 N of w){let J=wt(T,`${R}${N}`),d=await on(J,l,h);if(d!==null){if(e)et.success(`Configuration loaded from user home directory: ${J}`);return d}}}try{let T=wt($,"package.json");if(Cl(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 ce(l,R,h)}catch(N){if(e)et.warn("Failed to merge package.json config:",N)}}}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 l}function Tu(t,i={}){let n=nr.cwd();while(n.includes("storage"))n=qc(n,"..");let r=qc(n,t||"");if(i?.relative)return Fw(nr.cwd(),r);return r}async function Su(){try{let t=await Eu({name:"clarity",alias:"logging",defaultConfig:Qn,cwd:nr.cwd()});return{...Qn,...t||{}}}catch{return Qn}}function g(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ru(){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 _l{async format(t){let i=await Ru(),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 $r{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={...bf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new _l,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{...tr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...tr};return{...tr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:bf.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,h=1000;while(e<c)try{try{try{await Gw(this.config.logDirectory,Pc.F_OK|Pc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Kw(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:xt.from(t);try{if(!Kn(this.currentLogFile))await If(this.currentLogFile,"",{mode:420});if(f=Xc(this.currentLogFile,"a",420),zw(f,l,{flag:"a"}),bc(f),f!==void 0)Yf(f),f=void 0;if((await Ui(this.currentLogFile)).size===0){if(await If(this.currentLogFile,l,{flag:"w",mode:420}),(await Ui(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let w=$;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(e<c-1){let s=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,s);let y=h*2**e;await new Promise((u)=>setTimeout(u,y)),e++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(f!==void 0)try{Yf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(l){if(e===c-1){let w=l,s=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}e++;let $=h*2**(e-1);await new Promise((w)=>setTimeout(w,$))}})();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 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(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(([,h],[,l])=>l.createdAt.getTime()-h.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[h]of f.slice(c))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return Wf(16).toString("hex")}generateKey(){return Wf(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=Wf(16),r=Zw("aes-256-gcm",i,n),f=xt.isBuffer(t)?t:xt.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=xt.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=pc(),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 Ui(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 qn(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Ui(n).catch(()=>null))try{if(await vc(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await xn(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await If(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ui(n).catch(()=>null))await vc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await qn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,h)=>h.localeCompare(c));for(let c of e.slice(i.maxFiles))await xn(di(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=gc(t),r=Mw(i),f=pc();await Ow(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()})),Kn(this.currentLogFile))try{let t=Xc(this.currentLogFile,"r+");bc(t),Yf(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 qn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await xn(di(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()?j.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,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=_.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${j.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 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=j.underline(j.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\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)=>j.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>j.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>j.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>j.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>j.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(qw(i)||i.startsWith("./")||i.startsWith("../"))i=xw(i);else return null;return Kn(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,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":zl[t],y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:j.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:j.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
10
|
-
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:j.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!g()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
11
|
-
`;if(h)w+=`${h}
|
|
12
|
-
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(t,i=""){let n={update:(h,l)=>{},finish:(h)=>{},interrupt:(h,l)=>{}};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:(h,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,l="info")=>{if(!g()&&_.stdout.isTTY)_.stdout.write(`
|
|
13
|
-
`);if(this[l==="warning"?"warn":l](h),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?j.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":j.blue("◐"),tag:n,message:`${j.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,h=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
|
|
14
|
-
`,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":j.green("✓"),tag:w,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 $r(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(!Kn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return gc(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),h=Hw("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=xt.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.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 h=f.split(`
|
|
15
|
-
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:j.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:j.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:j.cyan(w),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(`${j.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 l=/%([sdijfo%])/g,$=0;if(n=t.replace(l,(w,s)=>{if(s==="%")return"%";if($>=i.length)return w;let y=i[$++];switch(s){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 w}}),$<i.length)n+=` ${i.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${j.blue("◐")} `;console.error(`${$}${l} ${j.cyan(r)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}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=j.green("━".repeat(r)),c=j.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?j.green("✓"):j.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=_.stdout.columns||80,m=" ".repeat(Math.max(0,u-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 qn(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=di(this.config.logDirectory,r);if(t.before)try{if((await Ui(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 xn(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 Ul(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===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 Et}function Bu(t){return t instanceof wr}function Cu(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((n)=>t.message.toLowerCase().includes(n.toLowerCase()))}class mr{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:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return yn.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],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=On.env[l]||($?On.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=On.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof ur)throw s;throw hi.envVar(l,w,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(On.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],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,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 Fu(t,i){let n=Zl("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function jl(t,i,n={}){return Wl(t,i,n,new WeakMap)}function Wl(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 h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return Yl(t,i,f,r);if(!Ct(i)||!Ct(t))return i;return Uu(t,i,n,r)}function Yl(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 Nu(t,i);case"smart":return Ju(t,i,r);default:return i}return i}function Nu(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>of(f,r)))n.push(r);return n}function Ju(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ct(i[0])&&Ct(t[0]))return _u(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 _u(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 h of e)if(h in f){if(r.find(($)=>Ct($)&&(h in $)&&$[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function Uu(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 h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(Ct(h)&&Ct(l))e[c]=Wl(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=Yl(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function le(t,i,n="replace"){return jl(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(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(!of(t[f],i[f]))return!1}return!0}return!1}function Ct(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Er{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:h=!1}=n;if(f){let $=Zi.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!Dn(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new un(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new un(t,Error("Configuration must export a valid object"),"unknown");let T={config:le(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Zi.setWithFileCheck("file",T,t,e);return T}catch($){throw $ instanceof Error?hi.configLoad(t,$):hi.configLoad(t,Error(String($)))}};if(c)return yn.track("loadFromPath",l,{path:t});return l()}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(Zf(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 Ul(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 h=Zf(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=Zf(t,c);if(await this.checkFileAccess(h))r.push(h)}}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}}class he{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};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(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await yn.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Dw(i))throw new sn(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 sn(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,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.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 h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,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 h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' 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),h=this.validateWithRule(c,e,e.path);if(r.push(...h),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:Kl},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class $e{fileLoader=new Er;envProcessor=new mr;validator=new he;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...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(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...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(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)jt.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){let l=Date.now()-i;throw jt.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||Ai.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(ut(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw hi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),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,h,l){let $=h?$n(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)jt.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)jt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?$n(t,n,f):n,h=[ut(Fi(),".config",t),ut(Fi(),".config"),Fi()];for(let l of h){if(f)jt.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)jt.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?$n(t,r,e):r;try{let l=ut(n,"package.json");if(!kf(l))return null;let $=await import(l),w=$[t],s=t;if(!w&&i)w=$[i],s=i;if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)jt.success(`Configuration loaded from package.json: ${s}`);return{config:le(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)jt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}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:$n(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 Zi.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Zi.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,ut(t,"config"),ut(t,".config"),i?ut(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(ut(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=[ut(Fi(),".config",t),ut(Fi(),".config"),Fi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function ll(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 du(t){return ot.loadConfig({...t,__strictErrorHandling:!0})}async function Il(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)jt.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let h=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(h.name||"",i,!0,h.verbose||!1))?.config??i;return i}}async function ju(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"&&ll(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"&&ll(i)))return(await ot.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function Wu(t,i,n="replace"){let r=new Er;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function $n(t,i,n=!1){let r=new mr,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=Ai.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}function Yu(t){let i=ut(Ai.cwd(),t.configDir),n=ut(Ai.cwd(),t.generatedDir),r=ut(n,"config-types.ts");if(!kf(Kc(r)))Sw(Kc(r),{recursive:!0,mode:511});let f=kf(i)?Rw(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${cs}
|
|
31
|
-
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
32
|
-
`;Bw(r,e,{mode:438})}function Iu(t){let i=null,n=null,r=()=>{if(!n)n=Il(t).then((e)=>{return i=e,e},(e)=>{let c="defaultConfig"in t?t.defaultConfig:{};if(i=c,"verbose"in t&&t.verbose)jt.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 h=f[c];return r(),h},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,h){if(!i)i={...f};return i[c]=h,!0}})}function Zu(t){let i=Qc(Vw.cwd(),t?.configDir||"./config");function n(){if(!Lw(i))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),e=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=kw(i).filter((l)=>f.has(Hf(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),h=new Map;for(let{base:l,file:$}of c){let w=Hf($).toLowerCase(),s=h.get(l);if(!s){h.set(l,$);continue}let y=Hf(s).toLowerCase();if(e.indexOf(w)<e.indexOf(y))h.set(l,$)}return Array.from(h.entries()).map(([l,$])=>({base:l,file:$})).sort((l,$)=>l.base.localeCompare($.base))}function r(){let f=n(),e=f.map(($)=>$.base),c=e.length?e.map(($)=>`'${$}'`).join(" | "):"string",h=f.length?`{
|
|
33
|
-
${f.map(($)=>{let w=Qc(i,$.file).replace(/\\/g,"/");return` '${$.base}': typeof import('${w}').default`}).join(`,
|
|
34
|
-
`)}
|
|
35
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
36
|
-
export type ConfigByName = ${h}
|
|
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 Zl,Zi,yn,Hl,Hu,Mu,hl,vn,gf,ft,K,zu,$l,Gu,wl,Ku,qu,Kf,xu,ul,sl,qf,Ou,Du,Lu,ku,pn,Ml,Vu,et,ou,gu,yl,Qn,bf,b,j,bu,al,Xu,Al,Pu,vu,xf,pu,ml,El,Qu,Of,ts,is,ns,rs,fs,tr,zl,es,cs="0.15.6",Et,wr,un,Xf,Pf,ur,vf,pf,sn,Qf,te,hi,Gl,Kl,jt,ot,ql,xl,ls=lu(async()=>{Zl=import.meta.require,Zi=new re,yn=new fe,Hl={createKey:hu,isEquivalent:$u,estimateMemoryUsage:wu},Hu=fr(Vf.cwd(),"config"),Mu=fr(Vf.cwd(),"src/generated"),hl=rr.env.CLARITY_LOG_DIR||Nw(yu(),"logs"),vn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:hl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},gf=await au(),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,zu=ft.red,$l=ft.green,Gu=ft.yellow,wl=ft.blue,Ku=ft.magenta,qu=ft.cyan,Kf=ft.white,xu=ft.gray,ul=ft.bgRed,sl=ft.bgYellow,qf=ft.bold,Ou=ft.dim,Du=ft.italic,Lu=ft.underline,ku=ft.reset,pn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ml={debug:"\uD83D\uDD0D",info:wl("ℹ"),success:$l("✓"),warning:sl(Kf(qf(" WARN "))),error:ul(Kf(qf(" ERROR ")))},Vu=new lr("stacks"),et=new lr("bunfig",{showTags:!0}),ou=wt(wn.cwd(),"config"),gu=wt(wn.cwd(),"src/generated"),yl=nr.env.CLARITY_LOG_DIR||Cw(Tu(),"logs"),Qn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bf=await Su(),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"},j=b,bu=b.red,al=b.green,Xu=b.yellow,Al=b.blue,Pu=b.magenta,vu=b.cyan,xf=b.white,pu=b.gray,ml=b.bgRed,El=b.bgYellow,Qu=b.bgGray,Of=b.bold,ts=b.dim,is=b.italic,ns=b.underline,rs=b.strikethrough,fs=b.reset,tr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},zl={debug:"\uD83D\uDD0D",info:Al("ℹ"),success:al("✓"),warning:El(xf(Of(" WARN "))),error:ml(xf(Of(" ERROR ")))},es=new $r("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}`}},wr=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})}},un=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}},Xf=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})}},Pf=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}},ur=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})}},vf=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}},pf=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}},sn=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})}},Qf=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})}},te=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 wr(t,i,n)},configLoad(t,i,n){return new un(t,i,n)},configValidation(t,i,n){return new Xf(t,i,n)},configMerge(t,i,n,r){return new Pf(t,i,n,r)},envVar(t,i,n,r){return new ur(t,i,n,r)},fileSystem(t,i,n){return new vf(t,i,n)},typeGeneration(t,i,n){return new pf(t,i,n)},schemaValidation(t,i,n){return new sn(t,i,n)},browserConfig(t,i,n,r){return new Qf(t,i,n,r)},plugin(t,i,n){return new te(t,i,n)}},Gl={replace:"replace",concat:"concat",smart:"smart"},Kl=/^https?:\/\//,jt=new $r("bunfig",{showTags:!0}),ot=new $e,ql=ut(Ai.cwd(),"config"),xl=ut(Ai.cwd(),"src/generated")});function hs(t,i={}){let n=er.cwd();while(n.includes("storage"))n=tl(n,"..");let r=tl(n,t||"");if(i?.relative)return gw(er.cwd(),r);return r}var $s=er.env.CLARITY_LOG_DIR||ow(hs(),"logs"),Ol={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$s,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},sr={...Ol},$m=(async()=>{try{let{loadConfig:t}=await ls().then(()=>Nl),i=await t({name:"clarity",alias:"logging",defaultConfig:Ol,cwd:er.cwd()});if(i)Object.assign(sr,i)}catch{}return sr})();function X(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ws(){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 Dl{async format(t){let i=await ws(),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:Ii.pid,hostname:i(),environment:Ii.env.NODE_ENV||"development",platform:Ii.platform,version:Ii.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ii.env.NODE_ENV||Ii.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}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"},Y=tt,wm=tt.red,us=tt.green,um=tt.yellow,ss=tt.blue,sm=tt.magenta,ym=tt.cyan,Tl=tt.white,am=tt.gray,ys=tt.bgRed,as=tt.bgYellow,Am=tt.bgGray,Sl=tt.bold,mm=tt.dim,Em=tt.italic,Tm=tt.underline,Sm=tt.strikethrough,Rm=tt.reset,Df={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},As={debug:"\uD83D\uDD0D",info:ss("ℹ"),success:us("✓"),warning:as(Tl(Sl(" WARN "))),error:ys(Tl(Sl(" ERROR ")))};class Tr{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={...sr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Dl,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{...Df,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Df};return{...Df,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:sr.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,h=1000;while(e<c)try{try{try{await pw(this.config.logDirectory,fl.F_OK|fl.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Qw(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Ot.from(t);try{if(!Ln(this.currentLogFile))await Gf(this.currentLogFile,"",{mode:420});if(f=rl(this.currentLogFile,"a",420),vw(f,l,{flag:"a"}),nl(f),f!==void 0)zf(f),f=void 0;if((await Wi(this.currentLogFile)).size===0){if(await Gf(this.currentLogFile,l,{flag:"w",mode:420}),(await Wi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let w=$;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(e<c-1){let s=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,s);let y=h*2**e;await new Promise((u)=>setTimeout(u,y)),e++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(f!==void 0)try{zf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(l){if(e===c-1){let w=l,s=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}e++;let $=h*2**(e-1);await new Promise((w)=>setTimeout(w,$))}})();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(([,h],[,l])=>l.createdAt.getTime()-h.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[h]of f.slice(c))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return Mf(16).toString("hex")}generateKey(){return Mf(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=Mf(16),r=bw("aes-256-gcm",i,n),f=Ot.isBuffer(t)?t:Ot.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=Ot.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=cl(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(Ot.from(Ot.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 kn(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Wi(n).catch(()=>null))try{if(await el(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Vn(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Gf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Wi(n).catch(()=>null))await el(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await kn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,h)=>h.localeCompare(c));for(let c of e.slice(i.maxFiles))await Vn(Yi(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=il(t),r=Pw(i),f=cl();await nu(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()})),Ln(this.currentLogFile))try{let t=rl(this.currentLogFile,"r+");nl(t),zf(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 kn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Vn(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()?Y.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,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=U.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 w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 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 h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\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(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(tu(i)||i.startsWith("./")||i.startsWith("../"))i=iu(i);else return null;return Ln(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,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":As[t],y=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:Y.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:Y.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
40
|
-
`);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(!X()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
41
|
-
`;if(h)w+=`${h}
|
|
42
|
-
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(t,i=""){let n={update:(h,l)=>{},finish:(h)=>{},interrupt:(h,l)=>{}};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:(h,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,l="info")=>{if(!X()&&U.stdout.isTTY)U.stdout.write(`
|
|
43
|
-
`);if(this[l==="warning"?"warn":l](h),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?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,h=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
|
|
44
|
-
`,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":Y.green("✓"),tag:w,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 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(X())throw Error("createReadStream is not supported in browser environments");if(!Ln(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return il(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=Ot.isBuffer(t)?t:Ot.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),h=Xw("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=Ot.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.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 h=f.split(`
|
|
45
|
-
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:Y.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:Y.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:Y.cyan(w),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(`${Y.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 l=/%([sdijfo%])/g,$=0;if(n=t.replace(l,(w,s)=>{if(s==="%")return"%";if($>=i.length)return w;let y=i[$++];switch(s){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 w}}),$<i.length)n+=` ${i.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${Y.blue("◐")} `;console.error(`${$}${l} ${Y.cyan(r)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}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=Y.green("━".repeat(r)),c=Y.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?Y.green("✓"):Y.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${Y.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=U.stdout.columns||80,m=" ".repeat(Math.max(0,u-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 kn(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 Vn(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 Bm=new Tr("stacks");class Wt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class Ll extends Wt{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 yr extends Wt{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 kl extends Wt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class Vl extends Wt{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 we extends Wt{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 ol extends Wt{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 gl extends Wt{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 ar extends Wt{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 bl extends Wt{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 Xl extends Wt{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 Hi={configNotFound(t,i,n){return new Ll(t,i,n)},configLoad(t,i,n){return new yr(t,i,n)},configValidation(t,i,n){return new kl(t,i,n)},configMerge(t,i,n,r){return new Vl(t,i,n,r)},envVar(t,i,n,r){return new we(t,i,n,r)},fileSystem(t,i,n){return new ol(t,i,n)},typeGeneration(t,i,n){return new gl(t,i,n)},schemaValidation(t,i,n){return new ar(t,i,n)},browserConfig(t,i,n,r){return new bl(t,i,n,r)},plugin(t,i,n){return new Xl(t,i,n)}};async function ms(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===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 ue{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:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return ne.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],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=gn.env[l]||($?gn.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=gn.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof we)throw s;throw Hi.envVar(l,w,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(gn.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],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,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 Es(t,i,n={}){return Pl(t,i,n,new WeakMap)}function Pl(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 h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return vl(t,i,f,r);if(!Ft(i)||!Ft(t))return i;return Bs(t,i,n,r)}function vl(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 Ts(t,i);case"smart":return Ss(t,i,r);default:return i}return i}function Ts(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>ie(f,r)))n.push(r);return n}function Ss(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ft(i[0])&&Ft(t[0]))return Rs(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 Rs(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 h of e)if(h in f){if(r.find(($)=>Ft($)&&(h in $)&&$[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function Bs(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 h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(Ft(h)&&Ft(l))e[c]=Pl(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=vl(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function pl(t,i,n="replace"){return Es(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function ie(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(!ie(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(!ie(t[f],i[f]))return!1}return!0}return!1}function Ft(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Ql{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:h=!1}=n;if(f){let $=ir.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!bn(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new yr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new yr(t,Error("Configuration must export a valid object"),"unknown");let T={config:pl(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)ir.setWithFileCheck("file",T,t,e);return T}catch($){throw $ instanceof Error?Hi.configLoad(t,$):Hi.configLoad(t,Error(String($)))}};if(c)return ne.track("loadFromPath",l,{path:t});return l()}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(Lf(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 ms(async()=>{return bn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!bn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=Lf(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=Lf(t,c);if(await this.checkFileAccess(h))r.push(h)}}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(!bn(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 Fs=/^https?:\/\//;class th{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};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(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await ne.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Cs(i))throw new ar(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 ar(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,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.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 h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,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 h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' 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),h=this.validateWithRule(c,e,e.path);if(r.push(...h),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:Fs},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Dt=new Tr("bunfig",{showTags:!0});function Ns(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 ih{fileLoader=new Ql;envProcessor=new ue;validator=new th;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...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(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...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(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)Dt.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){if(h instanceof Error&&h.name==="ConfigNotFoundError")throw h;let l=Date.now()-i;throw Dt.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||Ar.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(Bt(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw Hi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),warnings:[`No configuration file found for "${r}"${Ns(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,h,l){let $=h?Xn(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)Dt.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)Dt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?Xn(t,n,f):n,h=[Bt(Ci(),".config",t),Bt(Ci(),".config"),Ci()];for(let l of h){if(f)Dt.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)Dt.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?Xn(t,r,e):r;try{let l=Bt(n,"package.json");if(!Ew(l))return null;let $={};try{$=JSON.parse(Tw(l,"utf8"))}catch(y){if(e)Dt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let w=$[t],s=t;if(!w&&i){let y=Array.isArray(i)?i:[i];for(let u of y){if(!u)continue;if($[u]){w=$[u],s=u;break}}}if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)Dt.success(`Configuration loaded from package.json: ${s}`);return{config:pl(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)Dt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}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:Xn(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 ir.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);ir.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(Ci(),".config",t),Bt(Ci(),".config"),Ci()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var _m=new ih;function Xn(t,i,n=!1){let r=new ue,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=Ar.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}var Um=Bt(Ar.cwd(),"config"),dm=Bt(Ar.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Js={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:ye(se(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:ye(se(),".stacks","ssl","stacks.localhost.crt"),keyPath:ye(se(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Mi=Js;import*as cw from"node:fs";import*as lw from"node:path";import*as qt from"node:process";import{spawn as Na}from"node:child_process";import*as Kt from"node:fs/promises";import{homedir as rw}from"node:os";import*as Gt from"node:path";import*as nt from"node:process";import{execSync as tn}from"node:child_process";import o from"node:fs/promises";import*as ac from"node:os";import{homedir as uf}from"node:os";import{join as Q}from"node:path";import*as zt from"node:process";import{createRequire as _s}from"node:module";import ae from"node:os";import Ae from"node:path";import{existsSync as nh,statSync as rh}from"fs";import{existsSync as Us,mkdirSync as Dm,readdirSync as Lm,readFileSync as ds,writeFileSync as km}from"fs";import{homedir as zi}from"os";import{dirname as gm,resolve as Nt}from"path";import tf from"process";import{existsSync as fh,statSync as eh}from"fs";import{existsSync as Me,mkdirSync as js,readdirSync as Ws,writeFileSync as Ys}from"fs";import{homedir as Gi}from"os";import{dirname as ch,resolve as yt}from"path";import mi from"process";import{join as Is,relative as Zs,resolve as lh}from"path";import Kr from"process";import{existsSync as bh,mkdirSync as r1,readdirSync as f1,writeFileSync as e1}from"fs";import{homedir as me}from"os";import{dirname as h1,resolve as st}from"path";import En from"process";import{join as Hs,relative as Ms,resolve as hh}from"path";import qr from"process";import{existsSync as Xh,mkdirSync as y1,readdirSync as a1,writeFileSync as A1}from"fs";import{dirname as E1,resolve as xr}from"path";import ze from"process";import{Buffer as $i}from"buffer";import{createCipheriv as zs,createDecipheriv as Gs,randomBytes as Ee}from"crypto";import{closeSync as Te,createReadStream as $h,createWriteStream as Ks,existsSync as Se,fsyncSync as wh,openSync as uh,writeFileSync as qs}from"fs";import{access as xs,constants as sh,mkdir as Os,readdir as Sr,rename as yh,stat as Ki,unlink as Rr,writeFile as Re}from"fs/promises";import{join as qi}from"path";import ct from"process";import{pipeline as Ds}from"stream/promises";import{createGzip as ah}from"zlib";import xi from"process";import Pt from"process";import{Buffer as gt}from"buffer";import{createCipheriv as Ls,createDecipheriv as ks,randomBytes as Be}from"crypto";import{closeSync as Ce,createReadStream as Ah,createWriteStream as Vs,existsSync as Br,fsyncSync as mh,openSync as Eh,writeFileSync as os}from"fs";import{access as gs,constants as Th,mkdir as bs,readdir as Cr,rename as Sh,stat as Oi,unlink as Fr,writeFile as Fe}from"fs/promises";import{isAbsolute as Xs,join as Di,resolve as Ps}from"path";import H from"process";import{pipeline as vs}from"stream/promises";import{createGzip as Rh}from"zlib";import Li from"process";import vt from"process";import Nr from"process";import{existsSync as Jr}from"fs";import{resolve as Ne}from"path";import{existsSync as ps}from"fs";import{existsSync as Qs,readdirSync as t0}from"fs";import{extname as Je,resolve as Bh}from"path";import i0 from"process";import{join as n0,relative as r0,resolve as Ch}from"path";import Or from"process";import{Buffer as bt}from"buffer";import{createCipheriv as f0,createDecipheriv as e0,randomBytes as _e}from"crypto";import{closeSync as Ue,createReadStream as Fh,createWriteStream as c0,existsSync as _r,fsyncSync as Nh,openSync as Jh,writeFileSync as l0}from"fs";import{access as h0,constants as _h,mkdir as $0,readdir as Ur,rename as Uh,stat as ki,unlink as dr,writeFile as de}from"fs/promises";import{isAbsolute as w0,join as Vi,resolve as u0}from"path";import M from"process";import{pipeline as s0}from"stream/promises";import{createGzip as dh}from"zlib";import oi from"process";import pt from"process";import jr from"process";import{existsSync as Wr}from"fs";import{resolve as je}from"path";import{existsSync as y0}from"fs";import{exec as My}from"node:child_process";import Dh from"node:fs";import zy from"node:os";import Yt from"node:path";import Y$ from"node:process";import{promisify as Gy}from"node:util";import Pi from"node:crypto";import Qt from"node:fs";import Xe from"node:path";import{execSync as gh}from"node:child_process";import Qr from"node:os";var Gm=_s(import.meta.url);class Ph{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(!nh(t))return!0;return rh(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=nh(n)?rh(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 vh{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 Dr=new Ph,Pe=new vh,a0=Object.defineProperty,A0=(t)=>t;function m0(t,i){this[t]=A0.bind(null,i)}var E0=(t,i)=>{for(var n in i)a0(t,n,{get:i[n],enumerable:!0,configurable:!0,set:m0.bind(i,n)})},T0=(t,i)=>()=>(t&&(i=t(t=0)),i),ph={};E0(ph,{withErrorRecovery:()=>i$,tryLoadConfig:()=>O0,loadConfigWithResult:()=>q0,loadConfig:()=>c$,isRetryableError:()=>Z0,isConfigNotFoundError:()=>I0,isBunfigError:()=>n$,globalPerformanceMonitor:()=>Bn,globalCache:()=>bi,getEnvOrDefault:()=>H0,generateConfigTypes:()=>D0,defaultGeneratedDir:()=>a$,defaultConfigDir:()=>y$,deepMergeWithArrayStrategy:()=>ic,deepMerge:()=>r$,createLibraryConfig:()=>L0,config:()=>x0,bunfigPlugin:()=>k0,applyEnvVarsToConfig:()=>An,TypeGenerationError:()=>Le,SchemaValidationError:()=>Sn,PluginError:()=>Ve,PerformanceMonitor:()=>pe,FileSystemError:()=>De,ErrorFactory:()=>ui,EnvVarError:()=>br,EnvProcessor:()=>nf,ConfigValidator:()=>nc,ConfigValidationError:()=>xe,ConfigNotFoundError:()=>gr,ConfigMergeError:()=>Oe,ConfigLoader:()=>rc,ConfigLoadError:()=>Tn,ConfigFileLoader:()=>rf,ConfigCache:()=>ve,CacheUtils:()=>h$,BunfigError:()=>Tt,BrowserConfigError:()=>ke,ArrayMergeStrategies:()=>u$});class ve{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(!fh(t))return!0;return eh(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=fh(n)?eh(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 pe{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 S0(t,i={}){let n=Object.keys(i).sort().map((r)=>`${r}:${i[r]}`).join("|");return n?`${t}:${n}`:t}function R0(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function B0(t){return t.getStats().size*2}function Qe(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&O(i[0])&&"id"in i[0]&&i[0].id===3&&O(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(O(i)&&O(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(O(t)&&"arr"in t&&Array.isArray(t.arr)&&O(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&O(i[0])&&O(t[0])){let r=[...i];for(let f of t)if(O(f)&&"name"in f){if(!r.find((e)=>O(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(O(f)&&"path"in f){if(!r.find((e)=>O(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>Lr(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(!O(i)||!O(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(O(f)&&O(n[r]))n[r]=Qe(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&O(f[0])&&O(n[r][0])){let e=[...f];for(let c of n[r])if(O(c)&&"name"in c){if(!e.find((h)=>O(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(O(c)&&"path"in c){if(!e.find((h)=>O(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((h)=>Lr(h,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 Lr(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(!Lr(t[n],i[n]))return!1;return!0}if(O(t)&&O(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(!Lr(t[f],i[f]))return!1}return!0}return!1}function O(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function C0(t,i){if(!Xh(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 Qe(i,r)}catch{return null}}catch{return null}}async function F0({name:t="",cwd:i,defaultConfig:n}){let r=i||ze.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let h of f){let l=xr(r,`${c}${h}`),$=await C0(l,n);if($!==null)return $}try{let c=xr(r,"package.json");if(Xh(c)){let h=(await import(c))[t];if(h&&typeof h==="object"&&!Array.isArray(h))try{return Qe(n,h)}catch{}}}catch{}return n}function N0(t,i={}){let n=qr.cwd();while(n.includes("storage"))n=hh(n,"..");let r=hh(n,t||"");if(i?.relative)return Ms(qr.cwd(),r);return r}async function J0(){try{let t=await F0({name:"clarity",defaultConfig:Hr,cwd:qr.cwd(),endpoint:"",headers:{}});return{...Hr,...t}}catch{return Hr}}function k(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _0(){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 Qh{async format(t){let i=await _0(),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:xi.pid,hostname:i(),environment:xi.env.NODE_ENV||"development",platform:xi.platform,version:xi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xi.env.NODE_ENV||xi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class kr{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={...Ke},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Qh,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{...Mr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Mr};return{...Mr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ke.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 xs(this.config.logDirectory,sh.F_OK|sh.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Os(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:$i.from(t);try{if(!Se(this.currentLogFile))await Re(this.currentLogFile,"",{mode:420});if(r=uh(this.currentLogFile,"a",420),qs(r,h,{flag:"a"}),wh(r),r!==void 0)Te(r),r=void 0;if((await Ki(this.currentLogFile)).size===0){if(await Re(this.currentLogFile,h,{flag:"w",mode:420}),(await Ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let $=l;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,w);let s=c*2**f;await new Promise((y)=>setTimeout(y,s)),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{Te(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(h){if(f===e-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}f++;let l=c*2**(f-1);await new Promise(($)=>setTimeout($,l))}})();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 qi(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 qi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return qi(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],[,h])=>h.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 Ee(16).toString("hex")}generateKey(){return Ee(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=Ee(16),r=zs("aes-256-gcm",i,n),f=$i.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:$i.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=ah(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i($i.from($i.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 Ki(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 Sr(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Ki(n).catch(()=>null))try{if(await yh(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Rr(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Re(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ki(n).catch(()=>null))await yh(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Sr(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await Rr(qi(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=$h(t),r=Ks(i),f=ah();await Ds(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()})),Se(this.currentLogFile))try{let t=uh(this.currentLogFile,"r+");wh(t),Te(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 Sr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Rr(qi(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,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=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 w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 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,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!k()){let $=$$[t],w=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",s;switch(t){case"debug":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:q.gray(c),level:t}),console.error(s);break;case"info":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s);break;case"success":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:q.green(c),level:t}),console.error(s);break;case"warning":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.warn(s);break;case"error":if(s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s),h){let y=h.split(`
|
|
61
|
-
`);for(let u of y)if(u.trim()&&!u.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:q.gray(` ${u}`),level:t,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let l=`${e} ${this.environment}.${t.toUpperCase()}: ${c}
|
|
62
|
-
`;if(h)l+=`${h}
|
|
63
|
-
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}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,h=this.formatConsoleTimestamp(c),l=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
|
|
64
|
-
`,l=l.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:h,icon:q.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!k())console.error(l.trim());await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new kr(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(!Se(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $h(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=$i.isBuffer(t)?t:$i.from(t,"base64"),f=r.slice(0,16),e=r.slice(-16),c=r.slice(16,-16),h=Gs("aes-256-gcm",n,f);return h.setAuthTag(e),$i.concat([h.update(c),h.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((w)=>w.length))+2,h=`┌${"─".repeat(c)}┐`,l=`└${"─".repeat(c)}┘`,$=e.map((w)=>{let s=" ".repeat(c-w.length-2);return`│ ${w}${s} │`});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(h)})),$.forEach((w)=>console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(w),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(l),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,h)=>{if(h==="%")return"%";if(e>=i.length)return c;let l=i[e++];switch(h){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 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)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=i||n===100?q.green("✓"):q.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${q.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=ct.stdout.columns||80,m=" ".repeat(Math.max(0,u-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 Sr(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=qi(this.config.logDirectory,r);if(t.before)try{if((await Ki(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 Rr(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 Zr(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)=>Vr(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]=Zr(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((h)=>Vr(h,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 tc(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:Zr(t,i);if(Array.isArray(t))return n==="replace"?i:Zr(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]=Zr(c,e);else if(z(e)&&z(c))r[f]=tc(c,e,n);else r[f]=e}return r}function Vr(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(!Vr(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(!Vr(t[f],i[f]))return!1}return!0}return!1}function z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Yr(t,i,n="replace"){if(!bh(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 tc(i,f,n)}catch{return null}}catch{return null}}function U0(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${r}_${s.map(y).join("_")}`,m=`${r}_${s.map((A)=>A.toUpperCase()).join("_")}`;if(n)ht.info(`Checking environment variable ${u} for config ${t}.${s.join(".")}`);if(typeof w==="object"&&w!==null&&!Array.isArray(w))l[$]=e(w,s);else{let A=En.env[u]||En.env[m];if(A!==void 0){if(n)ht.info(`Using environment variable ${A?u:m} for config ${t}.${s.join(".")}`);if(typeof w==="number")l[$]=Number(A);else if(typeof w==="boolean")l[$]=A.toLowerCase()==="true";else if(Array.isArray(w))try{let T=JSON.parse(A);if(Array.isArray(T))l[$]=T;else l[$]=A.split(",").map((E)=>E.trim())}catch{l[$]=A.split(",").map((T)=>T.trim())}else l[$]=A}}}return l}return e(f)}async function d0({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:h="replace"}){let l=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?U0(t,f,e):f,$=n||En.cwd(),w=[".ts",".js",".mjs",".cjs",".json"];if(e)ht.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${$}`);let s=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),u=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)ht.info(`Searching for configuration in: ${T}`);let E=[st($,"config"),st($,".config")].concat(r?[st($,r)]:[]).includes(T)?[...s,...y,...u,...m]:[...y,...s,...m,...u];for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from: ${J}`);return d}}}if(t){let T=st(me(),".config",t),E=["config",`${t}.config`];if(i)E.push(`${i}.config`);if(e)ht.info(`Checking user config directory: ${T}`);for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from user config directory: ${J}`);return d}}}if(t){let T=st(me(),".config"),E=[`.${t}.config`];if(i)E.push(`.${i}.config`);if(e)ht.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from user config directory dotfile: ${J}`);return d}}}if(t){let T=me(),E=[`.${t}.config`,`.${t}`];if(i)E.push(`.${i}.config`),E.push(`.${i}`);if(e)ht.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from user home directory: ${J}`);return d}}}try{let T=st($,"package.json");if(bh(T)){let E=await import(T),R=E[t];if(!R&&i){if(R=E[i],R&&e)ht.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)ht.success(`Configuration loaded from package.json: ${R===E[t]?t:i}`);return tc(l,R,h)}catch(N){if(e)ht.warn("Failed to merge package.json config:",N)}}}catch(T){if(e)ht.warn("Failed to load package.json:",T)}if(e)ht.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function j0(t,i={}){let n=Kr.cwd();while(n.includes("storage"))n=lh(n,"..");let r=lh(n,t||"");if(i?.relative)return Zs(Kr.cwd(),r);return r}async function W0(){try{let t=await d0({name:"clarity",alias:"logging",defaultConfig:zr,cwd:Kr.cwd()});return{...zr,...t||{}}}catch{return zr}}function P(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Y0(){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 t${async format(t){let i=await Y0(),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:Li.pid,hostname:i(),environment:Li.env.NODE_ENV||"development",platform:Li.platform,version:Li.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Li.env.NODE_ENV||Li.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class or{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={...qe},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new t$,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{...Gr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Gr};return{...Gr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:qe.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 gs(this.config.logDirectory,Th.F_OK|Th.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await bs(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:gt.from(t);try{if(!Br(this.currentLogFile))await Fe(this.currentLogFile,"",{mode:420});if(r=Eh(this.currentLogFile,"a",420),os(r,h,{flag:"a"}),mh(r),r!==void 0)Ce(r),r=void 0;if((await Oi(this.currentLogFile)).size===0){if(await Fe(this.currentLogFile,h,{flag:"w",mode:420}),(await Oi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let $=l;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,w);let s=c*2**f;await new Promise((y)=>setTimeout(y,s)),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{Ce(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(h){if(f===e-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}f++;let l=c*2**(f-1);await new Promise(($)=>setTimeout($,l))}})();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],[,h])=>h.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 Be(16).toString("hex")}generateKey(){return Be(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Be(16),r=Ls("aes-256-gcm",i,n),f=gt.isBuffer(t)?t:gt.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=gt.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Rh(),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 Oi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Cr(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Oi(n).catch(()=>null))try{if(await Sh(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Fr(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Fe(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Oi(n).catch(()=>null))await Sh(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Cr(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await Fr(Di(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=Ah(t),r=Vs(i),f=Rh();await vs(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()})),Br(this.currentLogFile))try{let t=Eh(this.currentLogFile,"r+");mh(t),Ce(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Cr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Fr(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()?W.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,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=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 w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 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 h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\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(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(Xs(i)||i.startsWith("./")||i.startsWith("../"))i=Ps(i);else return null;return Br(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,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":w$[t],y=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:W.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:W.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
69
|
-
`);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(!P()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
70
|
-
`;if(h)w+=`${h}
|
|
71
|
-
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}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?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,h=this.formatConsoleTimestamp(c),l=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
|
|
73
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":W.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!P())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new or(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(!Br(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ah(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),h=ks("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=gt.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.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 h=f.split(`
|
|
74
|
-
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:W.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:W.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:W.cyan(w),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(`${W.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,h=0;if(n=t.replace(c,(l,$)=>{if($==="%")return"%";if(h>=i.length)return l;let w=i[h++];switch($){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return l}}),h<i.length)n+=` ${i.slice(h).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${W.blue("◐")} `;console.error(`${h}${c} ${W.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=W.green("━".repeat(r)),c=W.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?W.green("✓"):W.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${W.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=H.stdout.columns||80,m=" ".repeat(Math.max(0,u-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 Cr(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 Oi(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 Fr(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 i$(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===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 n$(t){return t instanceof Tt}function I0(t){return t instanceof gr}function Z0(t){if(n$(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 nf{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:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Bn.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],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=Nr.env[l]||($?Nr.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=Nr.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof br)throw s;throw ui.envVar(l,w,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 ui.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],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,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 H0(t,i){let n=l$("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function r$(t,i,n={}){return f$(t,i,n,new WeakMap)}function f$(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 h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return e$(t,i,f,r);if(!Jt(i)||!Jt(t))return i;return K0(t,i,n,r)}function e$(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 M0(t,i);case"smart":return z0(t,i,r);default:return i}return i}function M0(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Ge(f,r)))n.push(r);return n}function z0(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Jt(i[0])&&Jt(t[0]))return G0(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 G0(t,i,n){let r=[...i];for(let f of t){if(!Jt(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let h of e)if(h in f){if(r.find((l)=>Jt(l)&&(h in l)&&l[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function K0(t,i,n,r){let f=i;if(Jt(f)&&r.has(f))return r.get(f);let e={...t};if(Jt(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(Jt(h)&&Jt(l))e[c]=f$(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=e$(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function ic(t,i,n="replace"){return r$(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Ge(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(!Ge(t[n],i[n]))return!1;return!0}if(Jt(t)&&Jt(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(!Ge(t[f],i[f]))return!1}return!0}return!1}function Jt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class rf{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:h=!1}=n;if(f){let $=bi.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!Jr(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new Tn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new Tn(t,Error("Configuration must export a valid object"),"unknown");let m={config:ic(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)bi.setWithFileCheck("file",m,t,e);return m}catch($){throw $ instanceof Error?ui.configLoad(t,$):ui.configLoad(t,Error(String($)))}};if(c)return Bn.track("loadFromPath",l,{path:t});return l()}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(Ne(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 i$(async()=>{return Jr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Jr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=Ne(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=Ne(t,c);if(await this.checkFileAccess(h))r.push(h)}}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(!Jr(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 nc{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};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(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await Bn.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!ps(i))throw new Sn(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 Sn(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,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.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 h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,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 h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' 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),h=this.validateWithRule(c,e,e.path);if(r.push(...h),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:s$},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class rc{fileLoader=new rf;envProcessor=new nf;validator=new nc;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...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(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...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(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)It.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){let l=Date.now()-i;throw It.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||mi.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(yt(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw ui.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),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,h,l){let $=h?An(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)It.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)It.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?An(t,n,f):n,h=[yt(Gi(),".config",t),yt(Gi(),".config"),Gi()];for(let l of h){if(f)It.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)It.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?An(t,r,e):r;try{let l=yt(n,"package.json");if(!Me(l))return null;let $=await import(l),w=$[t],s=t;if(!w&&i)w=$[i],s=i;if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)It.success(`Configuration loaded from package.json: ${s}`);return{config:ic(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)It.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}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:An(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 ui.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return bi.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);bi.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(Gi(),".config",t),yt(Gi(),".config"),Gi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function jh(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 q0(t){return ti.loadConfig({...t,__strictErrorHandling:!0})}async function c$(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 x0(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"&&jh(n)))return(await ti.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await ti.loadConfig({...t,cwd:t.cwd||mi.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&jh(i)))return(await ti.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function O0(t,i,n="replace"){let r=new rf;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function An(t,i,n=!1){let r=new nf,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=mi.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}function D0(t){let i=yt(mi.cwd(),t.configDir),n=yt(mi.cwd(),t.generatedDir),r=yt(n,"config-types.ts");if(!Me(ch(r)))js(ch(r),{recursive:!0,mode:511});let f=Me(i)?Ws(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${Ey}
|
|
90
|
-
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
91
|
-
`;Ys(r,e,{mode:438})}function L0(t){let i=null,n=null,r=()=>{if(!n)n=c$(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 h=f[c];return r(),h},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,h){if(!i)i={...f};return i[c]=h,!0}})}function k0(t){let i=Bh(i0.cwd(),t?.configDir||"./config");function n(){if(!Qs(i))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),e=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=t0(i).filter((l)=>f.has(Je(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),h=new Map;for(let{base:l,file:$}of c){let w=Je($).toLowerCase(),s=h.get(l);if(!s){h.set(l,$);continue}let y=Je(s).toLowerCase();if(e.indexOf(w)<e.indexOf(y))h.set(l,$)}return Array.from(h.entries()).map(([l,$])=>({base:l,file:$})).sort((l,$)=>l.base.localeCompare($.base))}function r(){let f=n(),e=f.map((l)=>l.base),c=e.length?e.map((l)=>`'${l}'`).join(" | "):"string",h=f.length?`{
|
|
92
|
-
${f.map((l)=>{let $=Bh(i,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${$}').default`}).join(`,
|
|
93
|
-
`)}
|
|
94
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
95
|
-
export type ConfigByName = ${h}
|
|
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 l$,bi,Bn,h$,V0,o0,Wh,Hr,Ke,lt,q,g0,Yh,b0,Ih,X0,P0,We,v0,Zh,Hh,Ye,p0,Q0,ty,iy,Mr,$$,ny,ht,ry,fy,Mh,zr,qe,v,W,ey,zh,cy,Gh,ly,hy,Ie,$y,Kh,qh,wy,Ze,uy,sy,yy,ay,Ay,Gr,w$,my,Ey="0.15.6",Tt,gr,Tn,xe,Oe,br,De,Le,Sn,ke,Ve,ui,u$,s$,It,ti,y$,a$,Ty=T0(async()=>{l$=import.meta.require,bi=new ve,Bn=new pe,h$={createKey:S0,isEquivalent:R0,estimateMemoryUsage:B0},V0=xr(ze.cwd(),"config"),o0=xr(ze.cwd(),"src/generated"),Wh=qr.env.CLARITY_LOG_DIR||Hs(N0(),"logs"),Hr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Wh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ke=await J0(),lt={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=lt,g0=lt.red,Yh=lt.green,b0=lt.yellow,Ih=lt.blue,X0=lt.magenta,P0=lt.cyan,We=lt.white,v0=lt.gray,Zh=lt.bgRed,Hh=lt.bgYellow,Ye=lt.bold,p0=lt.dim,Q0=lt.italic,ty=lt.underline,iy=lt.reset,Mr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$$={debug:"\uD83D\uDD0D",info:Ih("ℹ"),success:Yh("✓"),warning:Hh(We(Ye(" WARN "))),error:Zh(We(Ye(" ERROR ")))},ny=new kr("stacks"),ht=new kr("bunfig",{showTags:!0}),ry=st(En.cwd(),"config"),fy=st(En.cwd(),"src/generated"),Mh=Kr.env.CLARITY_LOG_DIR||Is(j0(),"logs"),zr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},qe=await W0(),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"},W=v,ey=v.red,zh=v.green,cy=v.yellow,Gh=v.blue,ly=v.magenta,hy=v.cyan,Ie=v.white,$y=v.gray,Kh=v.bgRed,qh=v.bgYellow,wy=v.bgGray,Ze=v.bold,uy=v.dim,sy=v.italic,yy=v.underline,ay=v.strikethrough,Ay=v.reset,Gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},w$={debug:"\uD83D\uDD0D",info:Gh("ℹ"),success:zh("✓"),warning:qh(Ie(Ze(" WARN "))),error:Kh(Ie(Ze(" ERROR ")))},my=new or("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}`}},gr=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})}},Tn=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}},xe=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})}},Oe=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}},br=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})}},De=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}},Le=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}},Sn=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})}},ke=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})}},Ve=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}},ui={configNotFound(t,i,n){return new gr(t,i,n)},configLoad(t,i,n){return new Tn(t,i,n)},configValidation(t,i,n){return new xe(t,i,n)},configMerge(t,i,n,r){return new Oe(t,i,n,r)},envVar(t,i,n,r){return new br(t,i,n,r)},fileSystem(t,i,n){return new De(t,i,n)},typeGeneration(t,i,n){return new Le(t,i,n)},schemaValidation(t,i,n){return new Sn(t,i,n)},browserConfig(t,i,n,r){return new ke(t,i,n,r)},plugin(t,i,n){return new Ve(t,i,n)}},u$={replace:"replace",concat:"concat",smart:"smart"},s$=/^https?:\/\//,It=new or("bunfig",{showTags:!0}),ti=new rc,y$=yt(mi.cwd(),"config"),a$=yt(mi.cwd(),"src/generated")});function Sy(t,i={}){let n=Or.cwd();while(n.includes("storage"))n=Ch(n,"..");let r=Ch(n,t||"");if(i?.relative)return r0(Or.cwd(),r);return r}var Ry=Or.env.CLARITY_LOG_DIR||n0(Sy(),"logs"),A$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ry,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Xr={...A$},hE=(async()=>{try{let{loadConfig:t}=await Ty().then(()=>ph),i=await t({name:"clarity",alias:"logging",defaultConfig:A$,cwd:Or.cwd()});if(i)Object.assign(Xr,i)}catch{}return Xr})();function p(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function By(){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 m${async format(t){let i=await By(),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}}}var it={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},I=it,$E=it.red,Cy=it.green,wE=it.yellow,Fy=it.blue,uE=it.magenta,sE=it.cyan,xh=it.white,yE=it.gray,Ny=it.bgRed,Jy=it.bgYellow,aE=it.bgGray,Oh=it.bold,AE=it.dim,mE=it.italic,EE=it.underline,TE=it.strikethrough,SE=it.reset,He={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_y={debug:"\uD83D\uDD0D",info:Fy("ℹ"),success:Cy("✓"),warning:Jy(xh(Oh(" WARN "))),error:Ny(xh(Oh(" ERROR ")))};class ff{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={...Xr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new m$,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{...He,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...He};return{...He,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Xr.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 h0(this.config.logDirectory,_h.F_OK|_h.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await $0(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:bt.from(t);try{if(!_r(this.currentLogFile))await de(this.currentLogFile,"",{mode:420});if(r=Jh(this.currentLogFile,"a",420),l0(r,h,{flag:"a"}),Nh(r),r!==void 0)Ue(r),r=void 0;if((await ki(this.currentLogFile)).size===0){if(await de(this.currentLogFile,h,{flag:"w",mode:420}),(await ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let $=l;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,w);let s=c*2**f;await new Promise((y)=>setTimeout(y,s)),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{Ue(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(h){if(f===e-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}f++;let l=c*2**(f-1);await new Promise(($)=>setTimeout($,l))}})();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 Vi(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 Vi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Vi(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],[,h])=>h.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 _e(16).toString("hex")}generateKey(){return _e(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=_e(16),r=f0("aes-256-gcm",i,n),f=bt.isBuffer(t)?t:bt.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=bt.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=dh(),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 ki(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((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await ki(n).catch(()=>null))try{if(await Uh(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await dr(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await de(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await ki(n).catch(()=>null))await Uh(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 dr(Vi(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=Fh(t),r=c0(i),f=dh();await s0(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()})),_r(this.currentLogFile))try{let t=Jh(this.currentLogFile,"r+");Nh(t),Ue(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 Ur(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await dr(Vi(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,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=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 w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){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 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 h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\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(w0(i)||i.startsWith("./")||i.startsWith("../"))i=u0(i);else return null;return _r(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,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":_y[t],y=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:I.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:I.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.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}`),h)console.error(h)}let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
100
|
-
`;if(h)w+=`${h}
|
|
101
|
-
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}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,h=this.formatConsoleTimestamp(c),l=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
|
|
103
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":I.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!p())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new ff(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(!_r(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Fh(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),h=e0("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=bt.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.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 h=f.split(`
|
|
104
|
-
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:I.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:I.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:I.cyan(w),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,h=0;if(n=t.replace(c,(l,$)=>{if($==="%")return"%";if(h>=i.length)return l;let w=i[h++];switch($){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return l}}),h<i.length)n+=` ${i.slice(h).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).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)):"",h=this.options.showIcons===!1?"":`${I.blue("◐")} `;console.error(`${h}${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)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?I.green("✓"):I.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=M.stdout.columns||80,m=" ".repeat(Math.max(0,u-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 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=Vi(this.config.logDirectory,r);if(t.before)try{if((await ki(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 dr(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 RE=new ff("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 E$ 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 Pr 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 T$ 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 S$ 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 fc 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 R$ 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 B$ 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 vr 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 C$ 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 F$ 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 Xi={configNotFound(t,i,n){return new E$(t,i,n)},configLoad(t,i,n){return new Pr(t,i,n)},configValidation(t,i,n){return new T$(t,i,n)},configMerge(t,i,n,r){return new S$(t,i,n,r)},envVar(t,i,n,r){return new fc(t,i,n,r)},fileSystem(t,i,n){return new R$(t,i,n)},typeGeneration(t,i,n){return new B$(t,i,n)},schemaValidation(t,i,n){return new vr(t,i,n)},browserConfig(t,i,n,r){return new C$(t,i,n,r)},plugin(t,i,n){return new F$(t,i,n)}};async function Uy(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===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 ec{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:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Pe.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],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=jr.env[l]||($?jr.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=jr.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof fc)throw s;throw Xi.envVar(l,w,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 Xi.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(jr.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],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,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 dy(t,i,n={}){return N$(t,i,n,new WeakMap)}function N$(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 h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return J$(t,i,f,r);if(!_t(i)||!_t(t))return i;return Iy(t,i,n,r)}function J$(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 jy(t,i);case"smart":return Wy(t,i,r);default:return i}return i}function jy(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>oe(f,r)))n.push(r);return n}function Wy(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(_t(i[0])&&_t(t[0]))return Yy(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 Yy(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 h of e)if(h in f){if(r.find((l)=>_t(l)&&(h in l)&&l[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function Iy(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 h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(_t(h)&&_t(l))e[c]=N$(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=J$(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function _$(t,i,n="replace"){return dy(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function oe(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(!oe(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(!oe(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:h=!1}=n;if(f){let $=Dr.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!Wr(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new Pr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new Pr(t,Error("Configuration must export a valid object"),"unknown");let m={config:_$(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Dr.setWithFileCheck("file",m,t,e);return m}catch($){throw $ instanceof Error?Xi.configLoad(t,$):Xi.configLoad(t,Error(String($)))}};if(c)return Pe.track("loadFromPath",l,{path:t});return l()}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(je(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 Uy(async()=>{return Wr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Wr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=je(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=je(t,c);if(await this.checkFileAccess(h))r.push(h)}}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(!Wr(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 Zy=/^https?:\/\//;class d${async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};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(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await Pe.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!y0(i))throw new vr(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 vr(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,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.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 h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,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 h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' 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),h=this.validateWithRule(c,e,e.path);if(r.push(...h),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:Zy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Xt=new ff("bunfig",{showTags:!0});function Hy(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`}class j${fileLoader=new U$;envProcessor=new ec;validator=new d$;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...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(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...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(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)Xt.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){if(h instanceof Error&&h.name==="ConfigNotFoundError")throw h;let l=Date.now()-i;throw Xt.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||tf.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(Nt(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw Xi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),warnings:[`No configuration file found for "${r}"${Hy(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,h,l){let $=h?Ir(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)Xt.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)Xt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?Ir(t,n,f):n,h=[Nt(zi(),".config",t),Nt(zi(),".config"),zi()];for(let l of h){if(f)Xt.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)Xt.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?Ir(t,r,e):r;try{let l=Nt(n,"package.json");if(!Us(l))return null;let $={};try{$=JSON.parse(ds(l,"utf8"))}catch(y){if(e)Xt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let w=$[t],s=t;if(!w&&i){let y=Array.isArray(i)?i:[i];for(let u of y){if(!u)continue;if($[u]){w=$[u],s=u;break}}}if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)Xt.success(`Configuration loaded from package.json: ${s}`);return{config:_$(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)Xt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}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:Ir(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 Xi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Dr.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Dr.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,Nt(t,"config"),Nt(t,".config"),i?Nt(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(Nt(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=[Nt(zi(),".config",t),Nt(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)}}var BE=new j$;function Ir(t,i,n=!1){let r=new ec,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=tf.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}var CE=Nt(tf.cwd(),"config"),FE=Nt(tf.cwd(),"src/generated"),W$={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:Ae.join(ae.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:Ae.join(ae.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:Ae.join(ae.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},V=W$,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"},gi={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 ge(t,i){let n=[];function r(f){let e;try{e=Dh.readdirSync(f)}catch{return}for(let c of e){let h=Yt.join(f,c);try{if(Dh.statSync(h).isDirectory())r(h);else if(c===i)n.push(f)}catch{continue}}}return r(t),n}function C(t,i,n){if(n||V.verbose)console.debug(`[tlsx:${t}] ${i}`)}var Ky=Gy(My);function I$(){return Y$.env.SUDO_PASSWORD}var Lh="[redacted]",qy=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),xy=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function Oy(t){let i=t.toLowerCase();return qy.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function pr(t){if(Array.isArray(t))return t.map((n)=>pr(n));if(typeof t==="string")return xy.test(t)?Lh:t;if(!t||typeof t!=="object")return t;let i={};for(let[n,r]of Object.entries(t)){if(Oy(n)){i[n]=Lh;continue}i[n]=pr(r)}return i}function ef(t){return JSON.stringify(pr(t))}function Dy(t){let i=I$();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 wi(t,i={}){let n=Dy(t);try{let{stdout:r,stderr:f}=await Ky(n,{cwd:i.cwd||Y$.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 Z$(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 cc(t){let i=Yt.join(zy.homedir(),".stacks","ssl"),n=t.basePath&&t.basePath.trim()!==""?t.basePath:V.basePath&&V.basePath.trim()!==""?V.basePath:i,r=t.certPath?Yt.isAbsolute(t.certPath)?t.certPath:Yt.join(n,t.certPath):Yt.join(n,V.certPath),f=t.keyPath?Yt.isAbsolute(t.keyPath)?t.keyPath:Yt.join(n,t.keyPath):Yt.join(n,V.keyPath),e=t.caCertPath?Yt.isAbsolute(t.caCertPath)?t.caCertPath:Yt.join(n,t.caCertPath):Yt.join(n,V.caCertPath);return{certPath:r,keyPath:f,caCertPath:e,basePath:n}}function H$(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 C(F.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function lc(t){let i=t.notBeforeDays??Zt.DEFAULT_NOT_BEFORE_DAYS,n=t.validityDays??(t.validityYears?t.validityYears*365:Zt.DEFAULT_VALIDITY_DAYS);C(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),C(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 mn(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=mn(i.length);return Buffer.concat([Buffer.from([t]),n,i])}function Rn(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 be(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 M$(t,i=0){return Rt(Ht.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function z$(t){return Rt(Ht.OCTET_STRING,t)}function St(...t){return Rt(Ht.SEQUENCE,Buffer.concat(t))}function Ly(...t){return Rt(Ht.SET,Buffer.concat(t))}function ky(t){return Rt(Ht.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function Vy(t){return Rt(Ht.UTF8_STRING,Buffer.from(t,"utf8"))}function oy(){return Buffer.from([Ht.NULL,0])}function kh(t,i,n=!0){let r=160|t|(n?0:0),f=mn(i.length);return Buffer.concat([Buffer.from([r]),f,i])}function Vh(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"),h=t.getUTCSeconds().toString().padStart(2,"0"),l=`${n}${r}${f}${e}${c}${h}Z`;return Rt(Ht.UTC_TIME,Buffer.from(l,"ascii"))}}function gy(t,i){return St(Vh(t),Vh(i))}function oh(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"?ky(n.value):Vy(n.value),e=St(Rn(r),f);i.push(Ly(e))}return St(...i)}function G$(t){return St(Rn(t),oy())}function by(t){return t.export({type:"spki",format:"der"})}function Xy(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(":"):[],h=8-e.length-c.length,l=Array.from({length:h},()=>"0");i=[...e,...l,...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 Py(t){let i=[];for(let n of t)if(n.type===2&&n.value){let r=mn(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=Xy(n.ip),f=mn(r.length);i.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=mn(n.value.length);i.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return St(...i)}function vy(t,i){if(t){if(i!==void 0)return St(Rt(1,Buffer.from([255])),be(i));return St(Rt(1,Buffer.from([255])))}return St()}function py(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 M$(Buffer.from([i]),n)}function Qy(t){let i=[];if(t.serverAuth)i.push(Rn(at.SERVER_AUTH));if(t.clientAuth)i.push(Rn(at.CLIENT_AUTH));return St(...i)}function an(t,i,n){let r=[Rn(t)];if(i)r.push(Rt(1,Buffer.from([255])));return r.push(z$(n)),St(...r)}function ta(t){let i=[];if(i.push(kh(0,be(2))),i.push(be(t.serialNumber)),i.push(G$(at.SHA256_WITH_RSA)),i.push(oh(t.issuer)),i.push(gy(t.notBefore,t.notAfter)),i.push(oh(t.subject)),i.push(by(t.publicKey)),t.extensions){let n=[];if(t.extensions.basicConstraints)n.push(an(at.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,vy(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)n.push(an(at.KEY_USAGE,t.extensions.keyUsage.critical??!0,py(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)n.push(an(at.EXTENDED_KEY_USAGE,!1,Qy(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)n.push(an(at.SUBJECT_ALT_NAME,!1,Py(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)n.push(an(at.SUBJECT_KEY_IDENTIFIER,!1,z$(t.extensions.subjectKeyIdentifier)));if(n.length>0)i.push(kh(3,St(...n)))}return St(...i)}function ia(t,i){let n=Pi.createSign("SHA256");n.update(t);let r=n.sign(i);return St(t,G$(at.SHA256_WITH_RSA),M$(r))}function na(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 hc(){return Pi.randomBytes(20)}function K$(t=2048){let{privateKey:i,publicKey:n}=Pi.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:n}}function ra(t){let i=t.export({type:"spki",format:"der"});return Pi.createHash("sha1").update(i).digest()}function q$(t){let i={serialNumber:t.serialNumber||hc(),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:ra(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=ta(i),r=ia(n,t.signingKey);return{certificate:na(r,"CERTIFICATE"),certificateDer:r}}function x$(t){return t.export({type:"pkcs8",format:"pem"})}function fa(t){return Pi.createPrivateKey(t)}function ea(t){let i=new Pi.X509Certificate(t),n=i.publicKey,r=[],f=i.subject.split(`
|
|
125
|
-
`);for(let e of f){let[c,...h]=e.split("="),l=h.join("=");if(c&&l)r.push({shortName:c.trim(),value:l.trim()})}return{publicKey:n,subject:r}}async function $c(t={}){C("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||Zt.DEFAULT_KEY_SIZE;C("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:n,publicKey:r}=K$(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}=lc({validityYears:t.validityYears||Zt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:h}=q$({serialNumber:hc(),notBefore:e,notAfter:c,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:h,privateKey:x$(n),notBefore:e,notAfter:c}}async function wc(t){if(C("ca","Generating new certificate",t.verbose),C("ca",`Options: ${ef(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}=ea(t.rootCA.certificate),n=fa(t.rootCA.privateKey);C("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}=K$(r),c=t.commonName||Z$(t),h=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:l,notAfter:$}=lc({validityDays:t.validityDays||Zt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),w=H$(t),s=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},y=t.extKeyUsage||{serverAuth:!0},{certificate:u}=q$({serialNumber:hc(),notBefore:l,notAfter:$,subject:h,issuer:i,publicKey:e,signingKey:n,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:s,extendedKeyUsage:y,subjectAltName:w});return{certificate:u,privateKey:x$(f),notBefore:l,notAfter:$}}function O$(t,i){C(F.STORAGE,`Storing certificate and private key with options: ${ef(i)}`,i?.verbose);let{certPath:n,keyPath:r}=cc({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});C(F.STORAGE,`Certificate path: ${n}`,i?.verbose),C(F.STORAGE,`Private key path: ${r}`,i?.verbose);let f=Xe.dirname(n);if(!Qt.existsSync(f))C(F.STORAGE,`Creating certificate directory: ${f}`,i?.verbose),Qt.mkdirSync(f,{recursive:!0});C(F.STORAGE,"Writing certificate file",i?.verbose),Qt.writeFileSync(n,t.certificate);let e=Xe.dirname(r);if(!Qt.existsSync(e))C(F.STORAGE,`Creating private key directory: ${e}`,i?.verbose),Qt.mkdirSync(e,{recursive:!0});return C(F.STORAGE,"Writing private key file",i?.verbose),Qt.writeFileSync(r,t.privateKey),C(F.STORAGE,"Certificate and private key stored successfully",i?.verbose),n}function D$(t,i){C(F.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:n}=cc({basePath:i?.basePath,caCertPath:i?.caCertPath});C(F.STORAGE,`CA certificate path: ${n}`,i?.verbose);let r=Xe.dirname(n);if(!Qt.existsSync(r))C(F.STORAGE,`Creating CA certificate directory: ${r}`,i?.verbose),Qt.mkdirSync(r,{recursive:!0});return C(F.STORAGE,"Writing CA certificate file",i?.verbose),Qt.writeFileSync(n,t),C(F.STORAGE,"CA certificate stored successfully",i?.verbose),n}async function ca(t,i){if(Qr.platform()!=="darwin")return!1;try{let n=gh(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!n)return C(F.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(gh("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(n))return C(F.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return C(F.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(n){return C(F.TRUST,`Error checking certificate trust: ${n}`,i),!1}}var la={platform:"darwin",async addCertificate(t,i){if(await ca(t,i?.verbose)){C(F.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),gi.success("Certificate is already trusted in system keychain");return}C(F.TRUST,"Adding certificate to macOS keychain",i?.verbose),await wi(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,n){let r=n||V.commonName;C(F.TRUST,`Removing certificate ${r} from macOS keychain`,i?.verbose);try{await wi(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),C(F.TRUST,`Removed certificate ${r} from macOS keychain`,i?.verbose)}catch(f){throw C(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},ha={platform:"win32",async addCertificate(t,i){C(F.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await wi(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,n){let r=n||V.commonName;C(F.TRUST,`Removing certificate ${r} from Windows certificate store`,i?.verbose);try{await wi(`certutil -delstore -enterprise Root "${r}"`),C(F.TRUST,`Removed certificate ${r} from Windows certificate store`,i?.verbose)}catch(f){throw C(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},$a={platform:"linux",async addCertificate(t,i){C(F.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let n=Qr.homedir(),r=Zt.LINUX_CERT_DB_FILENAME,f=Zt.LINUX_TRUST_ARGS;C(F.TRUST,`Searching for certificate databases in ${n}`,i?.verbose);let e=ge(n,r);if(e.length===0){gi.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of e){C(F.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{C(F.TRUST,`Attempting to delete existing cert for ${V.commonName}`,i?.verbose),await wi(`certutil -d sql:${c} -D -n ${V.commonName}`)}catch(h){C(F.TRUST,`Warning: Error deleting existing cert: ${h}`,i?.verbose),console.warn(`Error deleting existing cert: ${h}`)}C(F.TRUST,`Adding new certificate to ${c}`,i?.verbose),await wi(`certutil -d sql:${c} -A -t ${f} -n ${V.commonName} -i ${t}`),gi.info(`Cert added to ${c}`)}},async removeCertificate(t,i,n){let r=n||V.commonName;C(F.TRUST,`Removing certificate ${r} from Linux certificate store`,i?.verbose);let f=Qr.homedir(),e=Zt.LINUX_CERT_DB_FILENAME;C(F.TRUST,`Searching for certificate databases in ${f}`,i?.verbose);let c=ge(f,e);if(c.length===0){gi.warn("No certificate databases found. Cannot remove certificate.");return}for(let h of c){C(F.TRUST,`Processing certificate database in ${h}`,i?.verbose);try{await wi(`certutil -d sql:${h} -D -n "${r}"`),gi.info(`Cert removed from ${h}`)}catch(l){C(F.TRUST,`Error removing cert from ${h}: ${l}`,i?.verbose),console.warn(`Error removing cert from ${h}: ${l}`)}}}},wa={darwin:la,win32:ha,linux:$a};async function uc(t,i,n){C(F.TRUST,`Adding certificate to system trust store with options: ${ef(n)}`,n?.verbose),C(F.TRUST,"Storing certificate and private key",n?.verbose);let r=O$(t,n);C(F.TRUST,"Storing CA certificate",n?.verbose);let f=D$(i,n),e=Qr.platform();C(F.TRUST,`Detected platform: ${e}`,n?.verbose);let c=wa[e];if(!c){let h=`Unsupported platform: ${e}`;throw C(F.TRUST,`Error: ${h}`,n?.verbose),Error(h)}return await c.addCertificate(f,n),C(F.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{execSync as Nn}from"node:child_process";import{homedir as ua}from"node:os";import{join as sa}from"node:path";import{execSync as cf}from"node:child_process";function sc(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Cn(t){try{let i=cf(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`,{encoding:"utf8"});return sc(i)}catch{return null}}function L$(t){try{return cf(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function k$(t,i){try{let n=cf(`openssl x509 -in "${t}" -noout -text`,{encoding:"utf8"});return i.every((r)=>n.includes(`DNS:${r}`))}catch{return!1}}function V$(t,i,n=443){try{return cf(`echo | openssl s_client -connect ${t}:${n} -servername ${t} -CAfile "${i}" 2>/dev/null | grep "Verify return code"`,{encoding:"utf8",timeout:4000}).includes(": 0 (ok)")}catch{return!1}}function o$(t){let i=[];for(let n of t.split(`
|
|
126
|
-
`)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)i.push(r[1].toUpperCase())}return i}var ii="-d -r trustRoot -p ssl -p basic",si="/Library/Keychains/System.keychain",lf="rpx.localhost";function vi(){return sa(ua(),"Library/Keychains/login.keychain-db")}function hf(){return[si,vi()]}function yc(t,i=lf){let n=Nn(`security find-certificate -a -c "${i}" -Z "${t}" 2>/dev/null || true`,{encoding:"utf8"}),r=[];for(let f of n.split(`
|
|
127
|
-
`)){let e=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(e)r.push(e[1].toUpperCase())}return r}function Jn(t){if(process.platform!=="darwin")return;let i=Cn(t.caPath);if(!i)return;let n=t.commonName??lf,r=t.keychains??hf();for(let f of r)for(let e of yc(f,n)){if(e===i)continue;try{if(f.startsWith("/Library"))Fn(`security delete-certificate -Z ${e} "${f}"`);else Nn(`security delete-certificate -Z ${e} "${f}"`,{stdio:"ignore"});a("ssl",`Removed stale Root CA ${e} from ${f}`,t.verbose)}catch{}}}function pi(t,i,n){if(process.platform!=="darwin")return Qi(t,n);try{let f=Nn(`security verify-cert -c "${t}" -s "${i}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return a("ssl",`verify-cert ${i}: ${f?"trusted":"not trusted"}`,n?.verbose),f}catch{return!1}}function Qi(t,i){let n=Cn(t);if(!n)return!1;for(let r of hf())try{let f=Nn(`security find-certificate -a -Z "${r}" 2>/dev/null || true`,{encoding:"utf8"});for(let e of f.split(`
|
|
128
|
-
`))if(e.toUpperCase().includes("SHA-256")){if(e.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===n)return a("ssl",`Root CA fingerprint found in ${r}`,i?.verbose),!0}}catch{}return!1}function $f(t,i){if(process.platform!=="darwin")return!1;let n=i.serverName;Jn({caPath:t,commonName:i.commonName,verbose:i.verbose});let r=vi();try{Nn(`security add-trusted-cert ${ii} -k "${r}" "${t}"`,{stdio:"ignore"})}catch{}try{Fn(`security add-trusted-cert ${ii} -k ${si} "${t}"`)}catch{return!1}return pi(t,n,{verbose:i.verbose})||Qi(t,{verbose:i.verbose})}var yi=null,aa="rpx-root-ca.crt",Aa="rpx-root-ca.key";function sf(t){return{caCertPath:Q(t,aa),caKeyPath:Q(t,Aa)}}function ma(t){return{certPath:Q(t,"rpx.localhost.crt"),keyPath:Q(t,"rpx.localhost.key"),caCertPath:Q(t,"rpx.localhost.ca.crt"),rootCA:sf(t)}}async function Ea(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 g$(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 p$(t){let n=Ac(t).replace(/\*/g,"wildcard"),r=Q(uf(),".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||Q(f,`${n}.ca.crt`),certPath:t.https.certPath||Q(f,`${n}.crt`),keyPath:t.https.keyPath||Q(f,`${n}.key`)};return{caCertPath:Q(f,`${n}.ca.crt`),certPath:Q(f,`${n}.crt`),keyPath:Q(f,`${n}.key`)}}function b$(t){let i=new Set;if(wf(t))t.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";g$(r).forEach((f)=>i.add(f))});else if(P$(t)){let n=t.to||"rpx.localhost";g$(n).forEach((r)=>i.add(r))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function Ta(t){a("ssl","Loading SSL configuration",t.verbose);let i={...Mi,...t};if(t.https=Ei(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 Sa(t,i){if(zt.platform==="darwin")return Ra(t,i);if(zt.platform==="linux")try{let{exec:n}=await import("node:child_process");return await new Promise((r)=>{n(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)r(!0);else n(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(e)=>{r(!e)})})})}catch{return!1}return!1}async function Ra(t,i){if(zt.platform!=="darwin")return!1;let n=i?.serverName??"rpx.localhost",r=i?.verbose??!1;try{if(pi(t,n,{verbose:r}))return a("ssl","Root CA already trusted for SSL, skipping trust operation",r),!0;return a("ssl","Trusting Root CA for browsers (login + system keychains)",r),$f(t,{serverName:n,verbose:r})}catch{return!1}}async function nn(t){if(yi&&!t.forceRegenerate){a("ssl","Using cached SSL configuration",t.verbose);return}Q$();let i=wf(t)?t.proxies.map((w)=>w.to):[t.to];a("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let n=Ei(t,t.verbose),r=n.basePath||Q(uf(),".stacks","ssl");await o.mkdir(r,{recursive:!0});let f=sf(r),e=await Ea(f,t.verbose),c=!1;if(!e){if(t.verbose)S.info("Generating Root CA certificate (one-time)...");e=await $c(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(w){throw a("ssl",`Error saving Root CA files: ${w}`,t.verbose),Error(`Failed to save Root CA files: ${w}`)}}else a("ssl",`Reusing existing Root CA from ${f.caCertPath}`,t.verbose);if(t.verbose)S.info(`Generating host certificate for: ${i.join(", ")}`);let h=await wc({...n,rootCA:{certificate:e.certificate,privateKey:e.privateKey}});try{await Promise.all([o.writeFile(n.certPath,h.certificate),o.writeFile(n.keyPath,h.privateKey),o.writeFile(n.caCertPath,e.certificate)]),a("ssl","Certificate files saved successfully",t.verbose)}catch(w){throw a("ssl",`Error saving certificate files: ${w}`,t.verbose),Error(`Failed to save certificate files: ${w}`)}if(c?!1:await Ec(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(yi={key:h.privateKey,cert:h.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{Jn({caPath:f.caCertPath,verbose:t.verbose});let w=vi();try{tn(`security add-trusted-cert ${ii} -k "${w}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Fn(`security add-trusted-cert ${ii} -k ${si} "${f.caCertPath}"`),t.verbose)S.success("Successfully added Root CA to system trust store");$=!0;let s=Q(r,"trust-rpx-cert.sh"),y=`#!/bin/bash
|
|
129
|
-
echo "Trusting RPX Root CA"
|
|
130
|
-
sudo security add-trusted-cert ${ii} -k ${si} "${f.caCertPath}"
|
|
131
|
-
echo "Root CA trusted! Please restart your browser."
|
|
132
|
-
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
133
|
-
`;await o.writeFile(s,y,{mode:493})}catch(w){if(t.verbose)S.warn(`Could not add Root CA to trust store automatically: ${w}`);let s=Q(r,"trust-rpx-cert.sh"),y=`#!/bin/bash
|
|
134
|
-
echo "Trusting RPX Root CA"
|
|
135
|
-
sudo security add-trusted-cert ${ii} -k ${si} "${f.caCertPath}"
|
|
136
|
-
echo "Root CA trusted! Please restart your browser."
|
|
137
|
-
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
138
|
-
`;if(await o.writeFile(s,y,{mode:493}),t.verbose)S.info(`Created a trust helper script at: ${s}`),S.info(`If you're still having certificate issues, run: sh ${s}`)}else if(zt.platform==="linux")try{let{exec:w}=await import("node:child_process"),s="/usr/local/share/ca-certificates/rpx",y=`
|
|
139
|
-
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
140
|
-
cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
141
|
-
update-ca-certificates
|
|
142
|
-
echo "RPX Root CA installed. Please restart your browser."
|
|
143
|
-
`,u=Q(ac.tmpdir(),`rpx-trust-${Date.now()}.sh`);await o.writeFile(u,y,{mode:493}),await new Promise((m)=>{w(`sudo bash "${u}"`,(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(u).catch(()=>{}),$=!0}catch(w){if(t.verbose)S.warn(`Failed to trust certificates: ${w}`)}else if(zt.platform==="win32")try{let w=`
|
|
144
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
|
|
145
|
-
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
146
|
-
$store.Open("ReadWrite")
|
|
147
|
-
$store.Add($cert)
|
|
148
|
-
$store.Close()
|
|
149
|
-
Write-Host "Root CA trusted successfully!"
|
|
150
|
-
`,s=Q(ac.tmpdir(),"rpx-trust.ps1");if(await o.writeFile(s,w),tn(`powershell -ExecutionPolicy Bypass -File "${s}"`),t.verbose)S.success("Successfully added certificate to Windows trust store");$=!0}catch(w){if(t.verbose)S.warn(`Could not trust certificate: ${w}`)}else try{await uc(h,e.certificate,n),$=!0}catch(w){if(t.verbose)S.warn(`Could not add certificate to trust store: ${w}`)}if(yi={key:h.privateKey,cert:h.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 Q$(){yi=null}async function ni(t){if(!t)return null;if(yi)return yi;let i=Ei(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,h=e?c!==!1:!0;a("ssl",`Trust check: hasFlag=${e}, flagValue=${c}, shouldCheckTrust=${h}`,t.verbose);let l=i.basePath||Q(uf(),".stacks","ssl"),$=sf(l);if(!(h?await Ec($.caCertPath,t):!0))return a("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[s,y,u]=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(u&&!u.includes("-----BEGIN CERTIFICATE-----"))return a("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(wf(t))try{let{X509Certificate:m}=await import("node:crypto"),T=new m(y).subjectAltName||"",R=t.proxies.map((N)=>N.to).filter((N)=>!T.includes(`DNS:${N}`));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),yi={key:s,cert:y,ca:u},yi}catch(n){return a("ssl",`Error checking existing certificates: ${n}`,t.verbose),null}}function Ei(t,i){let n=Ac(t);a("ssl",`Primary domain: ${n}`,i);let r=p$(t),f=Q(uf(),".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(b$(t)).map((h)=>({type:2,value:h}))};if(X$(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(b$(t)).map((e)=>({type:2,value:e}))}}async function mc(t,i){let n=p$({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)=>v$(f,i)))}async function Ec(t,i){try{if(a("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),zt.platform==="darwin"){if(i?.serverName)return pi(t,i.serverName,{verbose:i.verbose});return Qi(t,{verbose:i.verbose})}else if(zt.platform==="win32")try{let r=tn(`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(tn(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=tn(`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(tn(`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 _n(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 h=c.sourceHost,l=r.pathname,$=tw(r.pathname,c.pathRewrites);if($)h=$.targetHost,l=$.targetPath,a("request",`Path rewrite: ${r.pathname} → ${h}${l}`,i);let w=`http://${h}${l}${r.search}`;try{let s=new Headers(n.headers);if(s.set("host",h),c.changeOrigin)s.set("origin",`http://${c.sourceHost}`);s.set("x-forwarded-for","127.0.0.1"),s.set("x-forwarded-proto","https"),s.set("x-forwarded-host",e);let y=await fetch(w,{method:n.method,headers:s,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 u=new Headers(y.headers);return new Response(y.body,{status:y.status,statusText:y.statusText,headers:u})}catch(s){return a("request",`Proxy error for ${e}: ${s}`,i),new Response(`Proxy Error: ${s}`,{status:502})}}}import*as yf from"node:fs";import*as At from"node:fs/promises";import{homedir as Ba}from"node:os";import*as Tc from"node:path";import*as af from"node:process";var Ca=/^[a-zA-Z0-9._-]+$/;function ri(){return Tc.join(Ba(),".stacks","rpx","registry.d")}function rn(t){return typeof t==="string"&&t.length>0&&t.length<=128&&Ca.test(t)}function Sc(t,i){if(!rn(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return Tc.join(t,`${i}.json`)}function fi(t){if(!Number.isInteger(t)||t<=0)return!1;try{return af.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function iw(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"&&rn(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 Fa(t){await At.mkdir(t,{recursive:!0})}async function Rc(t,i=ri(),n){if(!iw(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await Fa(i);let r=Sc(i,t.id),f=`${r}.tmp.${af.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 Af(t,i=ri(),n){let r=Sc(i,t);try{await At.unlink(r),a("registry",`removed entry ${t}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function nw(t,i=ri(),n){let r=Sc(i,t);try{let f=await At.readFile(r,"utf8"),e=JSON.parse(f);if(!iw(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 Ti(t=ri(),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(!rn(e))continue;let c=await nw(e,t,i);if(c)r.push(c)}return r}async function mf(t=ri(),i){let n=await Ti(t,i),r=0;for(let f of n){if(f.pid===void 0)continue;if(!fi(f.pid))a("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,i),await Af(f.id,t,i).catch(()=>{}),r++}return r}function Bc(t,i={}){let n=i.dir??ri(),r=i.debounceMs??100,f=i.pollMs??Math.max(r*2,250),e=i.verbose;yf.mkdirSync(n,{recursive:!0});let c=null,h=!1,l=null,$=!1,w=(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)))},s=()=>{if(c=null,h)return;Ti(n,e).then((T)=>{return l=w(T),t(T)}).catch((T)=>{a("registry",`watcher onChange failed: ${T}`,e)})},y=()=>{if(h)return;if(c)clearTimeout(c);c=setTimeout(s,r)},m=setInterval(()=>{if(h||$)return;$=!0,Ti(n,e).then((T)=>{if(w(T)!==l)y()}).catch((T)=>{a("registry",`watcher poll failed: ${T}`,e)}).finally(()=>{$=!1})},f),A=yf.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(h=!0,c)clearTimeout(c);clearInterval(m),A.close()}}}var Ja=5000;function ei(){return Gt.join(rw(),".stacks","rpx")}function Ef(t=ei()){return Gt.join(t,"daemon.pid")}async function en(t=ei()){try{let i=await Kt.readFile(Ef(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 _a(t=ei()){let i=await en(t);return i!==null&&fi(i)}async function fw(t=ei()){await Kt.mkdir(t,{recursive:!0});let i=Ef(t);while(!0){try{let r=await Kt.open(i,"wx");try{await r.write(`${nt.pid}
|
|
151
|
-
`)}finally{await r.close()}return i}catch(r){if(r.code!=="EEXIST")throw r}let n=await en(t);if(n!==null&&fi(n))throw Error(`rpx daemon already running (pid=${n})`);await Kt.unlink(i).catch(()=>{})}}async function fn(t=ei()){await Kt.unlink(Ef(t)).catch(()=>{})}function Ua(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 da(t){return t.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??t[0]??"rpx.localhost"}async function ja(t,i){let n=await Ti(i,t.verbose),r=[...new Set(n.map((w)=>w.to))],f=da(r),e=[...new Set([f,...r,"rpx.localhost"])],c=Gt.join(rw(),".stacks","ssl"),h=Gt.join(c,"rpx.localhost.crt"),l={https:typeof t.https==="object"?{...t.https,certPath:h,keyPath:Gt.join(c,"rpx.localhost.key"),commonName:f}:{certPath:h,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((w)=>({from:"localhost:1",to:w}))}:{to:f,from:"localhost:1"}},$=await ni(l);if(!$)a("daemon","no usable cert on disk, generating one",t.verbose),await nn(l),$=await ni(l);if(!$)throw Error("failed to bootstrap TLS for rpx daemon");return $}async function Wa(t={}){let i=t.verbose??!1,n=t.rpxDir??ei(),r=t.registryDir??Gt.join(n,"registry.d"),f=t.httpsPort??443,e=t.httpPort??80,c=t.hostname??"0.0.0.0",h=t.gcIntervalMs??Ja,l=await fw(n),$=new Map,w=(B)=>$.get(B);function s(B){let $t=new Map;for(let mt of B)$t.set(mt.to,Ua(mt));$=$t,a("daemon",`routing table now covers ${$t.size} host(s): ${Array.from($t.keys()).join(", ")||"<empty>"}`,i)}await mf(r,i).catch((B)=>{a("daemon",`initial gc failed: ${B}`,i)}),s(await Ti(r,i));let y=await ja(t,r),u=Bun.serve({port:f,hostname:c,tls:{key:y.key,cert:y.cert,ca:y.ca,requestCert:!1,rejectUnauthorized:!1},fetch:_n(w,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: ${l}`),S.info(`registry: ${r}`);let A=Bc((B)=>{s(B)},{dir:r,verbose:i}),T=setInterval(()=>{mf(r,i).then((B)=>{if(B>0)a("daemon",`gc reaped ${B} stale entries`,i)}).catch((B)=>{a("daemon",`periodic gc failed: ${B}`,i)})},h);if(typeof T.unref==="function")T.unref();let E=!1,R,N=new Promise((B)=>{R=B});async function J(){if(E)return N;if(E=!0,clearInterval(T),A.close(),u.stop(!1),m?.stop(!1),await fn(n),i)S.info("rpx daemon stopped");return R(),N}let d=(B)=>{a("daemon",`received ${B}, shutting down`,i),J().catch(()=>{})};return nt.once("SIGINT",d),nt.once("SIGTERM",d),{stop:J,done:N,httpsPort:typeof u.port==="number"?u.port:f,httpPort:m&&typeof m.port==="number"?m.port:e,pidPath:l}}function ew(){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 Cc(t={}){let i=t.rpxDir??ei(),n=t.verbose??!1,r=await en(i);if(r!==null&&fi(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 fn(i);await Kt.mkdir(i,{recursive:!0});let f=t.spawnCommand??ew();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");a("daemon",`spawning daemon: ${f.join(" ")}`,n);let e=Na(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",(w)=>{c=w});let h=t.startupTimeoutMs??5000,l=t.pollIntervalMs??50,$=Date.now()+h;while(Date.now()<$){if(c)throw c;let w=await en(i);if(w!==null&&fi(w))return a("daemon",`daemon registered with pid=${w}`,n),{pid:w,spawned:!0};await new Promise((s)=>setTimeout(s,l))}if(c)throw c;throw Error(`rpx daemon failed to start within ${h}ms (rpxDir=${i})`)}async function Ya(t={}){let i=t.rpxDir??ei(),n=t.verbose??!1,r=t.timeoutMs??5000,f=t.pollIntervalMs??50,e=t.forceAfterTimeout??!0,c=await en(i);if(c===null||!fi(c)){if(c!==null)await fn(i);return{stopped:!1,pid:c,forced:!1}}try{nt.kill(c,"SIGTERM")}catch(l){if(l.code==="ESRCH")return await fn(i),{stopped:!1,pid:c,forced:!1};throw l}let h=Date.now()+r;while(Date.now()<h){if(!fi(c))return a("daemon",`daemon pid=${c} stopped cleanly`,n),{stopped:!0,pid:c,forced:!1};await new Promise((l)=>setTimeout(l,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(l){if(l.code!=="ESRCH")throw l}return await fn(i),{stopped:!0,pid:c,forced:!0}}function hw(t){let i=t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return i.length>0?i:"rpx"}async function Tf(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 u=y.id??hw(y.to);if(!rn(u))throw Error(`invalid registry id "${u}" derived from to="${y.to}"`);if(r.has(u))throw Error(`duplicate registry id "${u}" — set an explicit \`id\` on one of the proxies`);return r.add(u),{...y,id:u}}),e=new Date().toISOString();for(let y of f)await Rc({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 Cc({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 h=!1,l=n??ri(),$=f.map((y)=>y.id),w=async()=>{if(h)return;h=!0;for(let y of $)await Af(y,n,i).catch((u)=>{a("runner",`removeEntry(${y}) failed: ${u}`,i)})},s=(y)=>{a("runner",`received ${y}, unregistering ${$.length} entries`,i),w().finally(()=>qt.exit(0))};qt.once("SIGINT",s),qt.once("SIGTERM",s),qt.once("exit",()=>{if(h)return;for(let y of $)try{cw.unlinkSync(lw.join(l,`${y}.json`))}catch{}}),await new Promise(()=>{})}import{exec as Ia}from"node:child_process";import Si from"node:fs";import $w from"node:os";import Nc from"node:path";import*as dn from"node:process";import{promisify as Za}from"node:util";var Sf=Za(Ia),Ut=dn.platform==="win32"?Nc.join(dn.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",Fc=!1;async function Rf(t){if(dn.platform==="win32")throw Error("Administrator privileges required on Windows");let i=Un(),n=t.replace(/'/g,"'\\''");try{if(i){let{stdout:f}=await Sf(`echo '${i}' | sudo -S sh -c '${n}' 2>/dev/null`);return Fc=!0,f}if(Fc)try{let{stdout:f}=await Sf(`sudo -n sh -c '${n}'`);return f}catch(f){a("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:r}=await Sf(`sudo sh -c '${n}'`);return Fc=!0,r}catch(r){throw Error(`Failed to execute sudo command: ${r.message}`)}}async function cn(t,i){a("hosts",`Adding hosts: ${t.join(", ")}`,i),a("hosts",`Using hosts file at: ${Ut}`,i);try{let n;try{n=await Si.promises.readFile(Ut,"utf-8")}catch{a("hosts","Reading hosts file requires elevated permissions, using sudo",i);try{n=await Rf(`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 h=`127.0.0.1 ${c}`,l=`::1 ${c}`;return!n.includes(h)&&!n.includes(l)});if(r.length===0){a("hosts","All hosts already exist in hosts file",i);return}let f=r.map((c)=>`
|
|
1
|
+
import{$ as L2,A as z_,B as V2,C as M_,D as Y_,E as $_,F as R2,G as G_,H as W_,I as E2,J as z2,K as M2,L as S2,M as T2,N as F2,O as I2,P as w2,Q as j2,R as H2,S as k2,T as C2,U as q2,V as x2,W as U2,X as f2,Y as y2,Z as O2,_ as P2,a as J,aa as h2,b as B_,ba as c2,c as i_,ca as u2,d as n_,da as m2,e as t_,ea as v2,f as r_,fa as b2,g as s_,ga as l2,h as o_,ha as a2,i as e_,ia as d2,j as _2,ja as p2,k as D2,ka as g2,l as B2,la as i2,m as K2,ma as X_,n as N2,na as n2,o as Y2,oa as t2,p as $2,q as G2,r as W2,s as X2,t as J2,u as Q2,v as Z2,w as K_,x as A2,y as c,z as N_}from"./chunk-00z9z9an.js";import{Aa as NB,Ba as YB,Ca as $B,Da as GB,pa as E_,qa as m,ra as sD,sa as K,ta as oD,ua as C,va as eD,wa as _B,xa as DB,ya as BB,za as KB}from"./chunk-zs1tyy8z.js";import{execSync as v_}from"node:child_process";import*as O from"node:http";import*as y_ from"node:http2";import*as O_ from"node:net";import*as F from"node:process";var n=(D,_)=>(B)=>`\x1B[${D}m${B}\x1B[${_}m`,H={bold:n(1,22),dim:n(2,22),green:n(32,39),cyan:n(36,39)};import*as j_ from"node:fs";import*as H_ from"node:path";import*as k from"node:process";function k_(D){let _=D.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return _.length>0?_:"rpx"}async function t(D){if(D.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let _=D.verbose??!1,B=D.registryDir,N=new Set,Y=D.proxies.map((R)=>{let $=R.id??k_(R.to);if(!$_($))throw Error(`invalid registry id "${$}" derived from to="${R.to}"`);if(N.has($))throw Error(`duplicate registry id "${$}" — set an explicit \`id\` on one of the proxies`);return N.add($),{...R,id:$}}),W=new Date().toISOString();for(let R of Y)await G_({id:R.id,from:R.from,to:R.to,pid:D.persistent?void 0:k.pid,cwd:k.cwd(),createdAt:W,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,pathRewrites:R.pathRewrites},B,_);let G=await X_({rpxDir:D.rpxDir,verbose:_,spawnCommand:D.spawnCommand,startupTimeoutMs:D.startupTimeoutMs,spawnEnv:D.spawnEnv});for(let R of Y)J.success(`https://${R.to} → ${R.from}`);if(J.info(`(via rpx daemon pid=${G.pid}; \`rpx daemon:status\` to inspect)`),D.detached)return;let V=!1,X=B??Y_(),A=Y.map((R)=>R.id),T=async()=>{if(V)return;V=!0;for(let R of A)await W_(R,B,_).catch(($)=>{K("runner",`removeEntry(${R}) failed: ${$}`,_)})},I=(R)=>{K("runner",`received ${R}, unregistering ${A.length} entries`,_),T().finally(()=>k.exit(0))};k.once("SIGINT",I),k.once("SIGTERM",I),k.once("exit",()=>{if(V)return;for(let R of A)try{j_.unlinkSync(H_.join(X,`${R}.json`))}catch{}}),await new Promise(()=>{})}import{exec as h_}from"node:child_process";import f from"node:fs";import q_ from"node:os";import Q_ from"node:path";import*as v from"node:process";import{promisify as c_}from"node:util";var r=c_(h_);function C_(D){let _=D.trim().toLowerCase();return _==="localhost"||_.endsWith(".localhost")||_.endsWith(".localhost.")}var j=v.platform==="win32"?Q_.join(v.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",J_=!1;async function s(D){if(v.platform==="win32")throw Error("Administrator privileges required on Windows");let _=m(),B=D.replace(/'/g,"'\\''");try{if(_){let{stdout:N}=await r(`echo '${_}' | sudo -S sh -c '${B}' 2>/dev/null`);return J_=!0,N}if(J_)try{let{stdout:N}=await r(`sudo -n sh -c '${B}'`);return N}catch(N){K("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:N}=await r(`sudo -n sh -c '${B}'`);return J_=!0,N}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(N){throw Error(`Failed to execute sudo command: ${N.message}`)}}async function L(D,_){let B=D.filter((Y)=>!C_(Y)),N=D.filter((Y)=>C_(Y));if(N.length>0)K("hosts",`Skipping /etc/hosts for loopback dev names: ${N.join(", ")}`,_);if(B.length===0)return;K("hosts",`Adding hosts: ${B.join(", ")}`,_),K("hosts",`Using hosts file at: ${j}`,_);try{let Y;try{Y=await f.promises.readFile(j,"utf-8")}catch{K("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{Y=await s(`cat "${j}"`)}catch(X){throw console.log(" Could not read hosts file — skipping hosts setup"),K("hosts",`sudo read also failed: ${X}`,_),Error(`Cannot read hosts file: ${X}`)}}let W=B.filter((X)=>{let A=`127.0.0.1 ${X}`,T=`::1 ${X}`;return!Y.includes(A)&&!Y.includes(T)});if(W.length===0){K("hosts","All hosts already exist in hosts file",_);return}let G=W.map((X)=>`
|
|
152
2
|
# Added by rpx
|
|
153
|
-
127.0.0.1 ${
|
|
154
|
-
::1 ${
|
|
155
|
-
`),
|
|
156
|
-
`),
|
|
3
|
+
127.0.0.1 ${X}
|
|
4
|
+
::1 ${X}`).join(`
|
|
5
|
+
`),V=Q_.join(q_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await f.promises.writeFile(V,Y+G,"utf8"),await s(`cat "${V}" | tee "${j}" > /dev/null`),console.log(` Hosts updated: ${W.join(", ")}`)}catch(X){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),W.forEach((A)=>{console.log(` 127.0.0.1 ${A}`),console.log(` ::1 ${A}`)}),console.log(` Or run: sudo nano ${j}`)}finally{try{await f.promises.unlink(V)}catch{}}}catch(Y){K("hosts",`Failed to manage hosts file: ${Y.message}`,_)}}async function Z_(D,_){K("hosts",`Removing hosts: ${D.join(", ")}`,_);try{let B;try{B=await f.promises.readFile(j,"utf-8")}catch{K("hosts","Reading hosts file requires elevated permissions, using sudo",_);try{B=await s(`cat "${j}"`)}catch(X){throw K("hosts",`sudo read also failed: ${X}`,_),Error(`Cannot read hosts file: ${X}`)}}let N=B.split(`
|
|
6
|
+
`),Y=!1,W=N.filter((X)=>{if(D.some((T)=>X.includes(` ${T}`)&&(X.includes("127.0.0.1")||X.includes("::1"))))return Y=!0,!1;if(X.trim()==="# Added by rpx")return Y=!0,!1;return!0});if(!Y){K("hosts","No matching hosts found to remove",_);return}while(W[W.length-1]?.trim()==="")W.pop();let G=`${W.join(`
|
|
157
7
|
`)}
|
|
158
|
-
`,h=Nc.join($w.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Si.promises.writeFile(h,c,"utf8"),await Rf(`cat "${h}" | tee "${Ut}" > /dev/null`),a("hosts","Hosts removed successfully",i)}catch(l){a("hosts","Could not clean up hosts file automatically",i)}finally{try{await Si.promises.unlink(h)}catch(l){a("hosts",`Failed to remove temporary file: ${l}`,i)}}}catch(n){a("hosts",`Failed to clean up hosts file: ${n.message}`,i)}}async function ln(t,i){a("hosts",`Checking hosts: ${t}`,i);let n;try{n=await Si.promises.readFile(Ut,"utf-8")}catch(r){a("hosts",`Error reading hosts file: ${r}`,i);try{let f=Un(),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 Sf(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 Bf from"node:net";function ai(t,i,n){return a("port",`Checking if port ${t} is in use on ${i}`,n),new Promise((r)=>{let f=Bf.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 uw(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 ai(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 ww(t,i,n=5000,r){return a("port",`Testing connection to ${i}:${t}`,r),new Promise((f)=>{let e=Bf.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 jn{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 ai(t,this.hostname,this.verbose))return this.findNextAvailablePort(t+1,i);if(i){if(!await ww(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 uw(t,this.hostname,this.verbose,this.maxRetries);if(i){if(!await ww(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 Ha=new jn;import{spawn as Ma}from"node:child_process";import*as Ri from"node:process";class Cf{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||Ri.cwd();a("start",`Starting process ${t}:`,n),a("start",` Command: ${r} ${f.join(" ")}`,n),a("start",` Working directory: ${e}`,n),a("start",` Environment variables: ${ci(i.env)}`,n);let c=Ma(r,f,{cwd:e,env:{...Ri.env,...i.env},shell:!0,stdio:"inherit"});return this.processes.set(t,{command:i.command,cwd:e,process:c,env:i.env}),new Promise((h,l)=>{if(c.on("error",($)=>{if(!this.isShuttingDown)a("start",`Process ${t} failed to start: ${$}`,n),this.processes.delete(t),l($),Ri.emit("SIGINT")}),c.on("exit",($)=>{if(!this.isShuttingDown&&$!==null&&$!==0)a("start",`Process ${t} exited with code ${$}`,n),this.processes.delete(t),l(Error(`Process ${t} exited with code ${$}`)),Ri.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),l(Error(`Process ${t} was killed during startup`));else a("start",`Process ${t} started successfully`,n),h()},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 hS=new Cf;var Nf=new Cf,Ga="0.12.0",Ka=new jn("0.0.0.0"),Wn=new Set,_c=!1,Ff=null,Uc=null;async function In(t){if(_c)return a("cleanup","Cleanup already in progress, skipping",t?.verbose),Uc||Promise.resolve();_c=!0,a("cleanup","Starting cleanup process",t?.verbose),Uc=new Promise((i)=>{Ff=i});try{await Nf.stopAll(t?.verbose),S.info("Shutting down proxy servers...");let i=[],n=Array.from(Wn).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(Jc(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 mc(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(Ff)Ff();Ff=null,_c=!1;let i=t&&"vitePluginUsage"in t&&t.vitePluginUsage===!0;if(D.env.NODE_ENV!=="test"&&D.env.BUN_ENV!=="test"&&!i)D.exit(0)}return Uc}var dc=!1;function jc(t){if(dc){a("signal",`Received second ${t} signal, forcing exit`,!0),D.exit(1);return}dc=!0,a("signal",`Received ${t} signal, initiating cleanup`,!0),In().catch((i)=>{a("signal",`Cleanup failed after ${t}: ${i}`,!0),D.exit(1)}).finally(()=>{dc=!1})}D.once("SIGINT",()=>jc("SIGINT"));D.once("SIGTERM",()=>jc("SIGTERM"));D.on("uncaughtException",(t)=>{a("process",`Uncaught exception: ${t}`,!0),S.error("Uncaught exception:",t),jc("uncaughtException")});async function Yn(t,i,n,r=5){a("connection",`Testing connection to ${t}:${i} (retries left: ${r})`,n);let f=15000,e=Date.now();if(D.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((h,l)=>{let $=aw.connect({host:t,port:i,timeout:3000});$.once("connect",()=>{a("connection",`Successfully connected to ${t}:${i}`,n),$.end(),h()}),$.once("timeout",()=>{a("connection",`Connection to ${t}:${i} timed out`,n),$.destroy(),l(Error("Connection timed out"))}),$.once("error",(w)=>{a("connection",`Failed to connect to ${t}:${i}: ${w}`,n),$.destroy(),l(w)})});try{await c()}catch(h){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(h.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)),Yn(t,i,n,r-1);if(r>0)try{a("connection",`Trying HTTP request to ${t}:${i}`,n),await new Promise(($,w)=>{let s=Bi.request({hostname:t,port:i,path:"/",method:"HEAD",timeout:5000},(y)=>{a("connection",`Received HTTP response with status: ${y.statusCode}`,n),$()});s.on("error",(y)=>w(y)),s.on("timeout",()=>{s.destroy(),w(Error("HTTP request timed out"))}),s.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((w)=>setTimeout(w,2000)),Yn(t,i,n,r-1)}let l=`Failed to connect to ${t}:${i} after ${5-r} attempts: ${h.message}`;a("connection",`${l}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,n),S.warn(l),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 Wc(t){a("server",`Starting server with options: ${ci(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 ln(f,t.verbose))[0]){S.info(`Adding ${n.hostname} to hosts file...`),S.info("This may require sudo/administrator privileges");try{await cn(f,t.verbose)}catch(h){if(S.error("Failed to add hosts entry:",h.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}`),D.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 Yn(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=Ei({...t,to:n.hostname});if(e=await ni({...t,to:n.hostname,https:t.https}),!e){if(a("ssl",`Generating new certificates for ${n.hostname}`,t.verbose),await nn({...t,from:i.toString(),to:n.hostname,https:t.https}),e=await ni({...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 xa({...t,from:t.from||"localhost:5173",to:n.hostname,fromPort:r,sourceUrl:{hostname:i.hostname,host:i.host},ssl:e})}async function qa(t,i,n,r,f,e,c,h,l,$,w){a("proxy",`Creating proxy server ${t} -> ${i} with cleanUrls: ${$}`,l);function s(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}`,l);let E=A.url||"/",R=A.method||"GET";if(A instanceof yw.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 N=s(A.headers);if(w)N.host=`${e.hostname}:${n}`,a("request",`Changed origin: setting host header to ${N.host}`,l);let J={hostname:e.hostname,port:n,path:E,method:R,headers:N};a("request",`Proxy request options: ${ci(J)}`,l);let d=Bi.request(J,(B)=>{if(a("response",`Proxy response received with status ${B.statusCode}`,l),$&&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(", ")}`,l);let hn=(Zn)=>{if(Zn.length===0){T.writeHead(B.statusCode||404,B.headers),B.pipe(T);return}let Ic=Zn[0],mw={...J,path:Ic},Zc=Bi.request(mw,(Hn)=>{if(Hn.statusCode===200)a("cleanUrls",`Found matching path: ${Ic}`,l),T.writeHead(Hn.statusCode,Hn.headers),Hn.pipe(T);else hn(Zn.slice(1))});Zc.on("error",()=>hn(Zn.slice(1))),Zc.end()};hn(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)});d.on("error",(B)=>{a("request",`Proxy request failed: ${B}`,l),S.error("Proxy request failed:",B),T.writeHead(502),T.end(`Proxy Error: ${B.message}`)}),A.pipe(d)};if(a("server",`Creating server with SSL config: ${!!c}`,l),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 N=new URL(R.url);a("request",`Bun.serve received: ${R.method} ${N.pathname}`,l);let J=`http://${e.host}`,d=new URL(N.pathname+N.search,J);try{let B=new Headers(R.headers);if(B.set("host",e.host),w)B.set("origin",J);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(d.toString(),{method:R.method,headers:B,body:R.body,redirect:"manual"}),mt=new Headers($t.headers);if($&&N.pathname.endsWith(".html")){let hn=N.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:hn}})}return new Response($t.body,{status:$t.status,statusText:$t.statusText,headers:mt})}catch(B){return a("request",`Proxy error: ${B}`,l),new Response(`Proxy Error: ${B}`,{status:502})}},error(R){return a("server",`Bun.serve error: ${R}`,l),new Response(`Server Error: ${R.message}`,{status:500})}});Wn.add(E),sw({from:t,to:i,vitePluginUsage:h,listenPort:r,ssl:!0,cleanUrls:$,verbose:l}),A()}catch(E){T(E)}});let u=Bi.createServer(y);function m(A){return Wn.add(A),new Promise((T,E)=>{A.listen(r,f,()=>{a("server",`Server listening on port ${r}`,l),sw({from:t,to:i,vitePluginUsage:h,listenPort:r,ssl:!!c,cleanUrls:$,verbose:l}),T()}),A.on("error",(R)=>{a("server",`Server error: ${R}`,l),E(R)})})}return m(u)}async function xa(t){a("setup",`Setting up reverse proxy: ${ci(t)}`,t.verbose);let{from:i,to:n,fromPort:r,sourceUrl:f,ssl:e,verbose:c,cleanup:h,vitePluginUsage:l,changeOrigin:$,cleanUrls:w}=t,s=80,y=443,u="0.0.0.0",m=t.portManager||Ka;try{if(n&&!n.includes("localhost")&&!n.includes("127.0.0.1")){if(!(await ln([n],c))[0]){S.warn(`The hostname ${n} isn't in your hosts file. Adding it now...`);try{await cn([n],c),S.success(`Added ${n} to your hosts file.`)}catch(N){S.error(`Failed to add ${n} to your hosts file: ${N}`),S.info(`You may need to manually add '127.0.0.1 ${n}' to your /etc/hosts file.`)}}}else if(D.platform!=="darwin"&&n&&n.includes("localhost")&&!n.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await ln([n],c))[0]){a("hosts",`${n} not found in hosts file, adding...`,c);try{await cn([n],c)}catch(N){a("hosts",`Failed to add ${n} to hosts file: ${N}`,c)}}}if(e&&!m.usedPorts.has(s)){if(!await ai(s,u,c))a("setup","Starting HTTP redirect server",c),Aw(c),m.usedPorts.add(s);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:s,T=await ai(A,u,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 qa(i,n,r,E,u,f,e,l,c,w,$)}catch(A){a("setup",`Setup failed: ${A}`,c),S.error(`Failed to setup reverse proxy: ${A.message}`),In({domains:[n],hosts:typeof h==="boolean"?h:h?.hosts,certs:typeof h==="boolean"?h:h?.certs,verbose:c,vitePluginUsage:l})}}function Aw(t){a("redirect","Starting HTTP redirect server",t);let i=Bi.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);Wn.add(i),a("redirect","HTTP redirect server started",t)}function Oa(t){let i={...Mi,...t};if(a("proxy",`Starting proxy with options: ${ci(i)}`,i?.verbose),i.viaDaemon){if(!i.from||!i.to){S.error("viaDaemon mode requires both `from` and `to`");return}Tf({proxies:[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}],verbose:i.verbose}).catch((l)=>{S.error(`Failed to register with rpx daemon: ${l.message}`),D.exit(1)});return}let n=i.to||"",r=n.split(".").pop()?.toLowerCase()||"",f=D.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:l,setupResolver:$})=>{l([n],i.verbose).then((w)=>{if(w)$(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((l)=>{a("dns",`Failed to start DNS server: ${l}`,i.verbose)});let h={from:i.from,to:i.to,cleanUrls:i.cleanUrls,https:Ei(i),cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,changeOrigin:i.changeOrigin,verbose:i.verbose,regenerateUntrustedCerts:i.regenerateUntrustedCerts};a("proxy",`Server options: ${ci(h)}`,i.verbose),Wc(h).catch((l)=>{a("proxy",`Failed to start proxy: ${l}`,i.verbose),S.error(`Failed to start proxy: ${l.message}`),In({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 Da(t){return t?.verbose||!1}async function Yc(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=Da(i);if(a("config",`Starting with config: ${ci(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 Tf({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 u of i.proxies)if(u.start){let m=`${u.from}-${u.to}`;try{a("watch",`Starting command for ${m} with command: ${u.start.command}`,n),S.info(`Starting command for ${m}...`),await Nf.startProcess(m,u.start,n);let A=new URL(u.from.startsWith("http")?u.from:`http://${u.from}`),T=A.hostname||"localhost",E=Number(A.port)||80;try{await Yn(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 ${u.from} -> ${u.to}`,n)}else if("start"in i&&i.start){a("watch","Found start command in single proxy config",n);let u=`${i.from}-${i.to}`;try{if(i.start)a("watch",`Starting command: ${i.start.command}`,n),await Nf.startProcess(u,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 Yn(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(D.platform!=="win32"&&(i.https||i.cleanup?.hosts!==!1)){if(!Un())try{a("sudo","Pre-acquiring sudo credentials for privileged operations",n),za("sudo -v",{stdio:"inherit"})}catch{a("sudo","Could not pre-acquire sudo credentials",n)}}if(i.https){let u=await ni(i);if(!u){if(a("ssl",`No valid or trusted certificates found for ${r}, generating new ones`,i.verbose),await nn(i),u=await ni(i),!u)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=u}let f="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((u)=>({...u,https:i.https,cleanup:i.cleanup,cleanUrls:u.cleanUrls??("cleanUrls"in i?i.cleanUrls:!1),vitePluginUsage:i.vitePluginUsage,changeOrigin:u.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((u)=>u.to||"rpx.localhost"),c=i._cachedSSLConfig,h=e.filter((u)=>u&&!u.includes("localhost")&&!u.includes("127.0.0.1")),l=["dev","app","page","new","day","foo"],$=["test","localhost","local","example","invalid"],w=[...new Set(h.map((u)=>u.split(".").pop()?.toLowerCase()))],s=w.filter((u)=>!!u&&l.includes(u));if(s.length>0&&n)S.warn(`The following TLDs may not work reliably for local development: ${s.map((u)=>`.${u}`).join(", ")}`),S.info(" These TLDs have HSTS preloading which can bypass local DNS"),S.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(D.platform==="darwin"&&h.length>0){let{startDnsServer:u,setupResolver:m}=await import("./chunk-6z1nzq0x.js");if(await u(h,n)){if(await m(n,h),n)if(w.every((E)=>!!E&&$.includes(E)))S.success(`DNS server started for ${w.map((E)=>`.${E}`).join(", ")} domains`);else S.success(`DNS server started for ${w.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:u,removeResolver:m}=await import("./chunk-6z1nzq0x.js");u(i.verbose),await m(i.verbose)}catch(u){a("cleanup",`Error stopping DNS server: ${u}`,i.verbose)}try{await Nf.stopAll(i.verbose)}catch(u){a("cleanup",`Error stopping processes: ${u}`,i.verbose)}await In({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(D.on("SIGINT",y),D.on("SIGTERM",y),D.on("uncaughtException",(u)=>{a("process",`Uncaught exception: ${u}`,!0),console.error("Uncaught exception:",u),y()}),c&&f.length>1){a("proxies",`Creating shared HTTPS server for ${f.length} domains`,n);let u=new Map;for(let E of f){let R=E.to||"rpx.localhost",N=new URL(E.from?.startsWith("http")?E.from:`http://${E.from}`);if(u.set(R,{sourceHost:N.host,cleanUrls:E.cleanUrls||!1,changeOrigin:E.changeOrigin||!1,pathRewrites:E.pathRewrites}),a("proxies",`Route: ${R} → ${N.host}`,n),!R.includes("localhost")&&!R.includes("127.0.0.1"))try{if(!(await ln([R],n))[0])await cn([R],n)}catch{a("hosts",`Could not add hosts entry for ${R}`,n)}}if(!await ai(80,"0.0.0.0",n))Aw(n);let A=443;if(await ai(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:_n((R)=>u.get(R),n),error(R){return a("server",`Shared proxy server error: ${R}`,n),new Response(`Server Error: ${R.message}`,{status:500})}});Wn.add(E),a("proxies",`Shared HTTPS proxy listening on port ${A} for ${u.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 u of f)try{let m=u.to||"rpx.localhost";a("proxy",`Starting proxy for ${m} with SSL config: ${!!c}`,u.verbose),await Wc({from:u.from||"localhost:5173",to:m,cleanUrls:u.cleanUrls||!1,https:u.https||!1,cleanup:u.cleanup||!1,vitePluginUsage:u.vitePluginUsage||!1,verbose:u.verbose||!1,_cachedSSLConfig:c,changeOrigin:u.changeOrigin||!1})}catch(m){a("proxies",`Failed to start proxy for ${u.to}: ${m}`,u.verbose),console.error(`Failed to start proxy for ${u.to}:`,m),y()}}function sw(t){if(t?.vitePluginUsage||!t?.verbose)return;if(console.log(""),console.log(` ${dt.green(dt.bold("rpx"))} ${dt.green(`v${Ga}`)}`),console.log(` ${dt.green("➜")} ${dt.dim(t?.from??"")} ${dt.dim("➜")} ${dt.cyan(t?.ssl?`https://${t?.to}`:`http://${t?.to}`)}`),t?.listenPort!==(t?.ssl?443:80))console.log(` ${dt.green("➜")} Listening on port ${t?.listenPort}`);if(t?.cleanUrls)console.log(` ${dt.green("➜")} Clean URLs enabled`)}var DS=Yc;export{Rc as writeEntry,Bc as watchRegistry,V$ as verifyHttpsChain,$f as trustRootCaForBrowsers,Ya as stopDaemon,Wc as startServer,Oa as startProxy,Yc as startProxies,ci as safeStringify,v$ as safeDeleteFile,Tf as runViaDaemon,Wa as runDaemon,tw as resolvePathRewrite,Jc as removeHosts,Af as removeEntry,fn as releaseDaemonLock,LS as redactSensitive,nw as readEntry,en as readDaemonPid,Cn as readCertSha256Fingerprint,L$ as readCertCommonName,Ti as readAll,Jn as pruneStaleRootCas,Ha as portManager,o$ as parseSha256HashesFromSecurityListing,sc as normalizeSha256Fingerprint,Ta as loadSSLConfig,yc as listCertSha256HashesByCommonName,X$ as isValidRootCA,rn as isValidId,P$ as isSingleProxyOptions,VS as isSingleProxyConfig,pi as isRootCaTrustedForSsl,Qi as isRootCaFingerprintInKeychains,ai as isPortInUse,fi as isPidAlive,wf as isMultiProxyOptions,ya as isMultiProxyConfig,_a as isDaemonRunning,Ec as isCertTrusted,Ei as httpsConfig,Un as getSudoPassword,ma as getSharedDaemonCertPaths,sf as getRootCAPaths,ri as getRegistryDir,Ac as getPrimaryDomain,hf as getMacosTrustKeychains,vi as getMacosLoginKeychainPath,ei as getDaemonRpxDir,Ef as getDaemonPidPath,nn as generateCertificate,mf as gcStaleEntries,Sa as forceTrustCertificate,uw as findAvailablePort,kS as extractHostname,Fn as execSudoSync,Cc as ensureDaemonRunning,hw as deriveIdFromTarget,ew as defaultDaemonSpawnCommand,Mi as defaultConfig,DS as default,a as debugLog,_n as createProxyFetchHandler,Mi as config,dt as colors,Q$ as clearSslConfigCache,mc as cleanupCertificates,In as cleanup,ln as checkHosts,ni as checkExistingCertificates,k$ as certIncludesSanHostnames,cn as addHosts,fw as acquireDaemonLock,lf as RPX_ROOT_CA_COMMON_NAME,si as MACOS_SYSTEM_KEYCHAIN,ii as MACOS_CA_TRUST_FLAGS,jn as DefaultPortManager};
|
|
8
|
+
`,V=Q_.join(q_.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await f.promises.writeFile(V,G,"utf8"),await s(`cat "${V}" | tee "${j}" > /dev/null`),K("hosts","Hosts removed successfully",_)}catch(X){K("hosts","Could not clean up hosts file automatically",_)}finally{try{await f.promises.unlink(V)}catch(X){K("hosts",`Failed to remove temporary file: ${X}`,_)}}}catch(B){K("hosts",`Failed to clean up hosts file: ${B.message}`,_)}}async function h(D,_){K("hosts",`Checking hosts: ${D}`,_);let B;try{B=await f.promises.readFile(j,"utf-8")}catch(N){K("hosts",`Error reading hosts file: ${N}`,_);try{let Y=m(),W;if(Y)W=`echo '${Y}' | sudo -S cat "${j}" 2>/dev/null`;else W=`sudo -n cat "${j}" 2>/dev/null || cat "${j}" 2>/dev/null || echo ""`;let{stdout:G}=await r(W);B=G}catch(Y){return K("hosts",`Cannot read hosts file, assuming entries don't exist: ${Y}`,_),D.map(()=>!1)}}return D.map((N)=>{let Y=`127.0.0.1 ${N}`,W=`::1 ${N}`;return B.includes(Y)||B.includes(W)})}import*as o from"node:net";function x(D,_,B){return K("port",`Checking if port ${D} is in use on ${_}`,B),new Promise((N)=>{let Y=o.createServer(),W=setTimeout(()=>{K("port",`Checking port ${D} timed out, assuming it's in use`,B),Y.close(),N(!0)},3000);Y.once("error",(G)=>{if(clearTimeout(W),G.code==="EADDRINUSE")K("port",`Port ${D} is in use`,B),N(!0);else K("port",`Error checking port ${D}: ${G.message}`,B),N(!0)}),Y.once("listening",()=>{clearTimeout(W),K("port",`Port ${D} is available`,B),Y.close(),N(!1)});try{Y.listen(D,_)}catch(G){clearTimeout(W),K("port",`Exception checking port ${D}: ${G}`,B),N(!0)}})}async function U_(D,_,B,N=50){K("port",`Finding available port starting from ${D} (max attempts: ${N})`,B);let Y=D,W=0;while(W<N){if(W++,!await x(Y,_,B))return K("port",`Found available port: ${Y} after ${W} attempts`,B),Y;K("port",`Port ${Y} is in use, trying ${Y+1} (attempt ${W}/${N})`,B),Y++}throw Error(`Unable to find available port after ${N} attempts starting from ${D}`)}function x_(D,_,B=5000,N){return K("port",`Testing connection to ${_}:${D}`,N),new Promise((Y)=>{let W=o.connect({host:_,port:D,timeout:B});W.once("connect",()=>{K("port",`Successfully connected to ${_}:${D}`,N),W.end(),Y(!0)}),W.once("timeout",()=>{K("port",`Connection to ${_}:${D} timed out`,N),W.destroy(),Y(!1)}),W.once("error",(G)=>{K("port",`Failed to connect to ${_}:${D}: ${G.message}`,N),W.destroy(),Y(!1)})})}class b{usedPorts=new Set;hostname;verbose;maxRetries;constructor(D="0.0.0.0",_,B=50){this.hostname=D,this.verbose=_,this.maxRetries=B}async getNextAvailablePort(D,_=!1){if(this.usedPorts.has(D))return this.findNextAvailablePort(D+1,_);if(await x(D,this.hostname,this.verbose))return this.findNextAvailablePort(D+1,_);if(_){if(!await x_(D,this.hostname,3000,this.verbose))return K("port",`Port ${D} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(D+1,_)}return this.usedPorts.add(D),D}async findNextAvailablePort(D,_=!1){let B=await U_(D,this.hostname,this.verbose,this.maxRetries);if(_){if(!await x_(B,this.hostname,3000,this.verbose))if(B<D+this.maxRetries)return this.findNextAvailablePort(B+1,_);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(B),B}releasePort(D){K("port",`Releasing port ${D}`,this.verbose),this.usedPorts.delete(D)}}var u_=new b;import{spawn as m_}from"node:child_process";import*as y from"node:process";class e{processes=new Map;isShuttingDown=!1;async startProcess(D,_,B){if(this.processes.has(D)){K("start",`Process ${D} is already running`,B);return}let[N,...Y]=_.command.split(" "),W=_.cwd||y.cwd();K("start",`Starting process ${D}:`,B),K("start",` Command: ${N} ${Y.join(" ")}`,B),K("start",` Working directory: ${W}`,B),K("start",` Environment variables: ${C(_.env)}`,B);let G=m_(N,Y,{cwd:W,env:{...y.env,..._.env},shell:!0,stdio:"inherit"});return this.processes.set(D,{command:_.command,cwd:W,process:G,env:_.env}),new Promise((V,X)=>{if(G.on("error",(A)=>{if(!this.isShuttingDown)K("start",`Process ${D} failed to start: ${A}`,B),this.processes.delete(D),X(A),y.emit("SIGINT")}),G.on("exit",(A)=>{if(!this.isShuttingDown&&A!==null&&A!==0)K("start",`Process ${D} exited with code ${A}`,B),this.processes.delete(D),X(Error(`Process ${D} exited with code ${A}`)),y.emit("SIGINT")}),B)G.stdout?.on("data",(A)=>{K("process",`[${D}] ${A.toString().trim()}`,!0)}),G.stderr?.on("data",(A)=>{K("process",`[${D}] ERR: ${A.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&G.killed)this.processes.delete(D),X(Error(`Process ${D} was killed during startup`));else K("start",`Process ${D} started successfully`,B),V()},1000)})}async stopProcess(D,_){let B=this.processes.get(D);if(!B?.process){K("start",`No process found for ${D}`,_);return}return K("start",`Stopping process ${D}`,_),new Promise((N)=>{if(!B.process){N();return}B.process.once("exit",()=>{this.processes.delete(D),K("start",`Process ${D} stopped`,_),N()});try{B.process.kill("SIGTERM"),setTimeout(()=>{if(B.process){K("start",`Force killing process ${D}`,_);try{B.process.kill("SIGKILL")}catch(Y){}}},3000)}catch(Y){K("start",`Error stopping process ${D}: ${Y}`,_),this.processes.delete(D),N()}})}async stopAll(D){if(this.isShuttingDown){K("start","Already shutting down, skipping duplicate stopAll call",D);return}this.isShuttingDown=!0,K("start","Stopping all processes",D);let _=Array.from(this.processes.keys()).map((B)=>this.stopProcess(B,D).catch((N)=>{J.error(`Failed to stop process ${B}:`,N)}));await Promise.allSettled(_),this.processes.clear(),this.isShuttingDown=!1}isRunning(D){let _=this.processes.get(D);return!!_?.process&&!_.process.killed}}var VD=new e;var D_=new e,b_="0.12.0",l_=new b("0.0.0.0"),l=new Set,A_=!1,__=null,V_=null;async function d(D){if(A_)return K("cleanup","Cleanup already in progress, skipping",D?.verbose),V_||Promise.resolve();A_=!0,K("cleanup","Starting cleanup process",D?.verbose),V_=new Promise((_)=>{__=_});try{await D_.stopAll(D?.verbose),J.info("Shutting down proxy servers...");let _=[],B=Array.from(l).map((N)=>new Promise((Y)=>{N.close(()=>{K("cleanup","Server closed successfully",D?.verbose),Y()})}));if(_.push(...B),D?.hosts&&D.domains?.length){K("cleanup","Cleaning up hosts file entries",D?.verbose),K("cleanup",`Original domains for cleanup: ${JSON.stringify(D.domains)}`,D?.verbose);let N=D.domains.filter((Y)=>{if(Y==="test.local")return!0;return Y!=="localhost"&&!Y.startsWith("localhost.")&&Y!=="127.0.0.1"});if(K("cleanup",`Filtered domains for cleanup: ${JSON.stringify(N)}`,D?.verbose),N.length>0)J.info("Cleaning up hosts file entries..."),_.push(Z_(N,D?.verbose).then(()=>{K("cleanup",`Removed hosts entries for ${N.join(", ")}`,D?.verbose)}).catch((Y)=>{K("cleanup",`Failed to remove hosts entries: ${Y}`,D?.verbose),J.warn(`Failed to clean up hosts file entries for ${N.join(", ")}:`,Y)}))}if(D?.certs&&D.domains?.length){K("cleanup","Cleaning up SSL certificates",D?.verbose),J.info("Cleaning up SSL certificates...");let N=D.domains.map(async(Y)=>{try{await z_(Y,D?.verbose),K("cleanup",`Removed certificates for ${Y}`,D?.verbose)}catch(W){K("cleanup",`Failed to remove certificates for ${Y}: ${W}`,D?.verbose),J.warn(`Failed to clean up certificates for ${Y}:`,W)}});_.push(...N)}await Promise.allSettled(_),K("cleanup","All cleanup tasks completed successfully",D?.verbose),J.success("All cleanup tasks completed successfully")}catch(_){K("cleanup",`Error during cleanup: ${_}`,D?.verbose),J.error("Error during cleanup:",_)}finally{if(__)__();__=null,A_=!1;let _=D&&"vitePluginUsage"in D&&D.vitePluginUsage===!0;if(F.env.NODE_ENV!=="test"&&F.env.BUN_ENV!=="test"&&!_)F.exit(0)}return V_}var R_=!1;function S_(D){if(R_){K("signal",`Received second ${D} signal, forcing exit`,!0),F.exit(1);return}R_=!0,K("signal",`Received ${D} signal, initiating cleanup`,!0),d().catch((_)=>{K("signal",`Cleanup failed after ${D}: ${_}`,!0),F.exit(1)}).finally(()=>{R_=!1})}F.once("SIGINT",()=>S_("SIGINT"));F.once("SIGTERM",()=>S_("SIGTERM"));F.on("uncaughtException",(D)=>{K("process",`Uncaught exception: ${D}`,!0),J.error("Uncaught exception:",D),S_("uncaughtException")});async function a(D,_,B,N=5){K("connection",`Testing connection to ${D}:${_} (retries left: ${N})`,B);let Y=15000,W=Date.now();if(F.env.RPX_BYPASS_CONNECTION_TEST==="true"){K("connection",`Bypassing connection test for ${D}:${_} due to RPX_BYPASS_CONNECTION_TEST flag`,B);return}let G=()=>new Promise((V,X)=>{let A=O_.connect({host:D,port:_,timeout:3000});A.once("connect",()=>{K("connection",`Successfully connected to ${D}:${_}`,B),A.end(),V()}),A.once("timeout",()=>{K("connection",`Connection to ${D}:${_} timed out`,B),A.destroy(),X(Error("Connection timed out"))}),A.once("error",(T)=>{K("connection",`Failed to connect to ${D}:${_}: ${T}`,B),A.destroy(),X(T)})});try{await G()}catch(V){if(Date.now()-W>Y){K("connection",`Connection test timed out after ${Y}ms, but continuing anyway`,B),J.warn(`Connection test to ${D}:${_} timed out, but RPX will try to proceed anyway.`);return}if(V.code==="ECONNREFUSED"&&N>0)return K("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${N} retries left)`,B),await new Promise((A)=>setTimeout(A,2000)),a(D,_,B,N-1);if(N>0)try{K("connection",`Trying HTTP request to ${D}:${_}`,B),await new Promise((A,T)=>{let I=O.request({hostname:D,port:_,path:"/",method:"HEAD",timeout:5000},(R)=>{K("connection",`Received HTTP response with status: ${R.statusCode}`,B),A()});I.on("error",(R)=>T(R)),I.on("timeout",()=>{I.destroy(),T(Error("HTTP request timed out"))}),I.end()}),K("connection",`HTTP request to ${D}:${_} succeeded`,B);return}catch(A){return K("connection",`HTTP request to ${D}:${_} failed: ${A}`,B),K("connection",`Retrying socket connection in 2 seconds... (${N} retries left)`,B),await new Promise((T)=>setTimeout(T,2000)),a(D,_,B,N-1)}let X=`Failed to connect to ${D}:${_} after ${5-N} attempts: ${V.message}`;K("connection",`${X}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,B),J.warn(X),J.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 T_(D){K("server",`Starting server with options: ${C(D)}`,D.verbose);let _=new URL((D.from?.startsWith("http")?D.from:`http://${D.from}`)||"localhost:5173"),B=new URL((D.to?.startsWith("http")?D.to:`http://${D.to}`)||"rpx.localhost"),N=Number.parseInt(_.port)||(_.protocol.includes("https:")?443:80),Y=[B.hostname];if(!B.hostname.includes("localhost")&&!B.hostname.includes("127.0.0.1")){K("hosts",`Checking if hosts file entry exists for: ${B.hostname}`,D?.verbose);try{if(!(await h(Y,D.verbose))[0]){J.info(`Adding ${B.hostname} to hosts file...`),J.info("This may require sudo/administrator privileges");try{await L(Y,D.verbose)}catch(V){if(J.error("Failed to add hosts entry:",V.message),J.warn("You can manually add this entry to your hosts file:"),J.warn(`127.0.0.1 ${B.hostname}`),J.warn(`::1 ${B.hostname}`),F.platform==="win32")J.warn("On Windows:"),J.warn("1. Run notepad as administrator"),J.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else J.warn("On Unix systems:"),J.warn("sudo nano /etc/hosts")}}else K("hosts",`Host entry already exists for ${B.hostname}`,D.verbose)}catch(G){J.error("Failed to check hosts file:",G.message)}}try{await a(_.hostname,N,D.verbose)}catch(G){K("server",`Connection test failed: ${G}`,D.verbose),J.error(G.message),J.warn("Continuing with proxy setup despite connection test failure..."),J.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let W=D._cachedSSLConfig||null;if(D.https)try{if(D.https===!0)D.https=N_({...D,to:B.hostname});if(W=await c({...D,to:B.hostname,https:D.https}),!W){if(K("ssl",`Generating new certificates for ${B.hostname}`,D.verbose),await K_({...D,from:_.toString(),to:B.hostname,https:D.https}),W=await c({...D,to:B.hostname,https:D.https}),!W)throw Error(`Failed to load SSL configuration after generating certificates for ${B.hostname}`)}}catch(G){throw K("server",`SSL setup failed: ${G}`,D.verbose),G}K("server",`Setting up reverse proxy with SSL config for ${B.hostname}`,D.verbose),await d_({...D,from:D.from||"localhost:5173",to:B.hostname,fromPort:N,sourceUrl:{hostname:_.hostname,host:_.host},ssl:W})}async function a_(D,_,B,N,Y,W,G,V,X,A,T){K("proxy",`Creating proxy server ${D} -> ${_} with cleanUrls: ${A}`,X);function I(Z){let z={};for(let[Q,E]of Object.entries(Z))if(!Q.startsWith(":"))z[Q]=E;return z}let R=(Z,z)=>{K("request",`Incoming request: ${Z.method} ${Z.url}`,X);let Q=Z.url||"/",E=Z.method||"GET";if(Z instanceof y_.Http2ServerRequest){let S=Z.headers;E=S[":method"]||E,Q=S[":path"]||Q}if(A){if(!Q.match(/\.[a-z0-9]+$/i))if(Q.endsWith("/"))Q=`${Q}index.html`;else Q=`${Q}.html`}let w=I(Z.headers);if(T)w.host=`${W.hostname}:${B}`,K("request",`Changed origin: setting host header to ${w.host}`,X);let U={hostname:W.hostname,port:B,path:Q,method:E,headers:w};K("request",`Proxy request options: ${C(U)}`,X);let p=O.request(U,(S)=>{if(K("response",`Proxy response received with status ${S.statusCode}`,X),A&&S.statusCode===404){let q=[];if(Q.endsWith(".html"))q.push(Q.slice(0,-5));else if(!Q.match(/\.[a-z0-9]+$/i))q.push(`${Q}.html`);if(!Q.endsWith("/"))q.push(`${Q}/index.html`);if(q.length>0){K("cleanUrls",`Trying alternative paths: ${q.join(", ")}`,X);let u=(g)=>{if(g.length===0){z.writeHead(S.statusCode||404,S.headers),S.pipe(z);return}let I_=g[0],L_={...U,path:I_},w_=O.request(L_,(i)=>{if(i.statusCode===200)K("cleanUrls",`Found matching path: ${I_}`,X),z.writeHead(i.statusCode,i.headers),i.pipe(z);else u(g.slice(1))});w_.on("error",()=>u(g.slice(1))),w_.end()};u(q);return}}let P={...S.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};z.writeHead(S.statusCode||500,P),S.pipe(z)});p.on("error",(S)=>{K("request",`Proxy request failed: ${S}`,X),J.error("Proxy request failed:",S),z.writeHead(502),z.end(`Proxy Error: ${S.message}`)}),Z.pipe(p)};if(K("server",`Creating server with SSL config: ${!!G}`,X),G)return new Promise((Z,z)=>{try{let Q=Bun.serve({port:N,hostname:Y,tls:{key:G.key,cert:G.cert,ca:G.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(E){let w=new URL(E.url);K("request",`Bun.serve received: ${E.method} ${w.pathname}`,X);let U=`http://${W.host}`,p=new URL(w.pathname+w.search,U);try{let S=new Headers(E.headers);if(S.set("host",W.host),T)S.set("origin",U);S.set("x-forwarded-for","127.0.0.1"),S.set("x-forwarded-proto","https"),S.set("x-forwarded-host",_);let P=await fetch(p.toString(),{method:E.method,headers:S,body:E.body,redirect:"manual"}),q=new Headers(P.headers);if(A&&w.pathname.endsWith(".html")){let u=w.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:u}})}return new Response(P.body,{status:P.status,statusText:P.statusText,headers:q})}catch(S){return K("request",`Proxy error: ${S}`,X),new Response(`Proxy Error: ${S}`,{status:502})}},error(E){return K("server",`Bun.serve error: ${E}`,X),new Response(`Server Error: ${E.message}`,{status:500})}});l.add(Q),f_({from:D,to:_,vitePluginUsage:V,listenPort:N,ssl:!0,cleanUrls:A,verbose:X}),Z()}catch(Q){z(Q)}});let $=O.createServer(R);function M(Z){return l.add(Z),new Promise((z,Q)=>{Z.listen(N,Y,()=>{K("server",`Server listening on port ${N}`,X),f_({from:D,to:_,vitePluginUsage:V,listenPort:N,ssl:!!G,cleanUrls:A,verbose:X}),z()}),Z.on("error",(E)=>{K("server",`Server error: ${E}`,X),Q(E)})})}return M($)}async function d_(D){K("setup",`Setting up reverse proxy: ${C(D)}`,D.verbose);let{from:_,to:B,fromPort:N,sourceUrl:Y,ssl:W,verbose:G,cleanup:V,vitePluginUsage:X,changeOrigin:A,cleanUrls:T}=D,I=80,R=443,$="0.0.0.0",M=D.portManager||l_;try{if(B&&!B.includes("localhost")&&!B.includes("127.0.0.1")){if(!(await h([B],G))[0]){J.warn(`The hostname ${B} isn't in your hosts file. Adding it now...`);try{await L([B],G),J.success(`Added ${B} to your hosts file.`)}catch(w){J.error(`Failed to add ${B} to your hosts file: ${w}`),J.info(`You may need to manually add '127.0.0.1 ${B}' to your /etc/hosts file.`)}}}else if(F.platform!=="darwin"&&B&&B.includes("localhost")&&!B.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await h([B],G))[0]){K("hosts",`${B} not found in hosts file, adding...`,G);try{await L([B],G)}catch(w){K("hosts",`Failed to add ${B} to hosts file: ${w}`,G)}}}if(W&&!M.usedPorts.has(I)){if(!await x(I,$,G))K("setup","Starting HTTP redirect server",G),P_(G),M.usedPorts.add(I);else if(K("setup","Port 80 is in use, skipping HTTP redirect",G),G)J.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let Z=W?R:I,z=await x(Z,$,G),Q;if(z){if(K("setup",`Port ${Z} is already in use`,G),G)J.warn(`Port ${Z} is already in use. This may be another instance of rpx or another service.`);if(Z===443){if(Q=await M.getNextAvailablePort(3443,!0),K("setup",`Using port ${Q} instead of ${Z}`,G),G)J.info(`Using port ${Q} instead. Access your site at https://${B}:${Q}`)}else if(Q=await M.getNextAvailablePort(Z+1000,!0),K("setup",`Using port ${Q} instead of ${Z}`,G),G)J.info(`Using port ${Q} instead. Access your site at http://${B}:${Q}`)}else Q=Z,M.usedPorts.add(Q),K("setup",`Using standard ${Z===443?"HTTPS":"HTTP"} port ${Z} for ${B}`,G);await a_(_,B,N,Q,$,Y,W,X,G,T,A)}catch(Z){K("setup",`Setup failed: ${Z}`,G),J.error(`Failed to setup reverse proxy: ${Z.message}`),d({domains:[B],hosts:typeof V==="boolean"?V:V?.hosts,certs:typeof V==="boolean"?V:V?.certs,verbose:G,vitePluginUsage:X})}}function P_(D){K("redirect","Starting HTTP redirect server",D);let _=O.createServer((B,N)=>{let Y=B.headers.host||"";K("redirect",`Redirecting request from ${Y}${B.url} to HTTPS`,D),N.writeHead(301,{Location:`https://${Y}${B.url}`}),N.end()}).listen(80);l.add(_),K("redirect","HTTP redirect server started",D)}function p_(D){let _={...B_,...D};if(K("proxy",`Starting proxy with options: ${C(_)}`,_?.verbose),_.viaDaemon){if(!_.from||!_.to){J.error("viaDaemon mode requires both `from` and `to`");return}t({proxies:[{id:_.id,from:_.from,to:_.to,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}],verbose:_.verbose}).catch((X)=>{J.error(`Failed to register with rpx daemon: ${X.message}`),F.exit(1)});return}let B=_.to||"",N=B.split(".").pop()?.toLowerCase()||"",Y=F.platform==="darwin"&&B&&!B.includes("localhost")&&!B.includes("127.0.0.1"),W=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"];if(Y&&W.includes(N)&&_?.verbose)J.warn(`The .${N} TLD may not work reliably for local development`),J.info(` Google owns .${N} with HSTS preloading, which can bypass local DNS`),J.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(Y)import("./chunk-end75nnv.js").then(({setupDevelopmentDns:X})=>{X({domains:[B],verbose:_.verbose}).then((A)=>{if(A)Promise.resolve().then(()=>{if(_.verbose)if(G.includes(N))J.success(`DNS server started for .${N} domains`);else J.success(`DNS server started for .${N} domains (hosts file entry also added)`)});else K("dns",`Could not start DNS server - ${B} may not resolve in browser`,_.verbose)})}).catch((X)=>{K("dns",`Failed to start DNS server: ${X}`,_.verbose)});let V={from:_.from,to:_.to,cleanUrls:_.cleanUrls,https:N_(_),cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,changeOrigin:_.changeOrigin,verbose:_.verbose,regenerateUntrustedCerts:_.regenerateUntrustedCerts};K("proxy",`Server options: ${C(V)}`,_.verbose),T_(V).catch((X)=>{K("proxy",`Failed to start proxy: ${X}`,_.verbose),J.error(`Failed to start proxy: ${X.message}`),d({domains:[_.to],hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose})})}function g_(D){return D?.verbose||!1}async function F_(D){let _={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(D)_={..._,...D};let B=g_(_);if(K("config",`Starting with config: ${C(_,2)}`,B),K("config",`Is multi-proxy? ${"proxies"in _}`,B),_.viaDaemon){let M="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map((Z)=>({id:Z.id,from:Z.from,to:Z.to,cleanUrls:Z.cleanUrls??_.cleanUrls,changeOrigin:Z.changeOrigin??_.changeOrigin,pathRewrites:Z.pathRewrites})):[{id:_.id,from:_.from,to:_.to,cleanUrls:_.cleanUrls,changeOrigin:_.changeOrigin,pathRewrites:_.pathRewrites}];await t({proxies:M,verbose:B});return}if("proxies"in _&&Array.isArray(_.proxies)){K("servers",`Found ${_.proxies.length} proxies in config`,B);for(let $ of _.proxies)if($.start){let M=`${$.from}-${$.to}`;try{K("watch",`Starting command for ${M} with command: ${$.start.command}`,B),J.info(`Starting command for ${M}...`),await D_.startProcess(M,$.start,B);let Z=new URL($.from.startsWith("http")?$.from:`http://${$.from}`),z=Z.hostname||"localhost",Q=Number(Z.port)||80;try{await a(z,Q,B),K("watch",`Dev server is ready at ${z}:${Q}`,B)}catch(E){K("watch",`Connection check failed, but continuing with proxy setup: ${E}`,B),J.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(Z){throw K("watch",`Failed to start command for ${M}: ${Z}`,B),Error(`Failed to start command for ${M}: ${Z}`)}}else K("watch",`No start command for proxy ${$.from} -> ${$.to}`,B)}else if("start"in _&&_.start){K("watch","Found start command in single proxy config",B);let $=`${_.from}-${_.to}`;try{if(_.start)K("watch",`Starting command: ${_.start.command}`,B),await D_.startProcess($,_.start,B);let M=new URL(_.from?.startsWith("http")?_.from:`http://${_.from}`),Z=M.hostname||"localhost",z=Number(M.port)||80;try{await a(Z,z,B),K("watch",`Dev server is ready at ${Z}:${z}`,B)}catch(Q){K("watch",`Connection check failed, but continuing with proxy setup: ${Q}`,B),J.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw K("watch",`Failed to run start command: ${M}`,B),Error(`Failed to run start command: ${M}`)}}else K("watch","No start command found in config",B);let N="proxies"in _&&Array.isArray(_.proxies)?_.proxies[0]?.to:("to"in _)?_.to:"rpx.localhost";if(F.platform!=="win32"&&(_.https||_.cleanup?.hosts!==!1)){if(!m())try{K("sudo","Pre-acquiring sudo credentials for privileged operations",B),v_("sudo -v",{stdio:"inherit"})}catch{K("sudo","Could not pre-acquire sudo credentials",B)}}if(_.https){let $=await c(_);if(!$){if(K("ssl",`No valid or trusted certificates found for ${N}, generating new ones`,_.verbose),await K_(_),$=await c(_),!$)throw Error(`Failed to load SSL certificates after generation for ${N}`)}else K("ssl",`Using existing and trusted certificates for ${N}`,_.verbose);_._cachedSSLConfig=$}let Y="proxies"in _&&Array.isArray(_.proxies)?_.proxies.map(($)=>({...$,https:_.https,cleanup:_.cleanup,cleanUrls:$.cleanUrls??("cleanUrls"in _?_.cleanUrls:!1),vitePluginUsage:_.vitePluginUsage,changeOrigin:$.changeOrigin??_.changeOrigin,verbose:B,_cachedSSLConfig:_._cachedSSLConfig})):[{from:"from"in _?_.from:"localhost:5173",to:"to"in _?_.to:"rpx.localhost",cleanUrls:"cleanUrls"in _?_.cleanUrls:!1,https:_.https,cleanup:_.cleanup,vitePluginUsage:_.vitePluginUsage,start:"start"in _?_.start:void 0,changeOrigin:_.changeOrigin,verbose:B,_cachedSSLConfig:_._cachedSSLConfig}],W=Y.map(($)=>$.to||"rpx.localhost"),G=_._cachedSSLConfig,V=W.filter(($)=>$&&!$.includes("localhost")&&!$.includes("127.0.0.1")),X=["dev","app","page","new","day","foo"],A=["test","localhost","local","example","invalid"],T=[...new Set(V.map(($)=>$.split(".").pop()?.toLowerCase()))],I=T.filter(($)=>!!$&&X.includes($));if(I.length>0&&B)J.warn(`The following TLDs may not work reliably for local development: ${I.map(($)=>`.${$}`).join(", ")}`),J.info(" These TLDs have HSTS preloading which can bypass local DNS"),J.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(F.platform==="darwin"&&V.length>0){let{setupDevelopmentDns:$}=await import("./chunk-end75nnv.js");if(await $({domains:V,verbose:B})){if(B)if(T.every((z)=>!!z&&A.includes(z)))J.success(`DNS server started for ${T.map((z)=>`.${z}`).join(", ")} domains`);else J.success(`DNS server started for ${T.map((z)=>`.${z}`).join(", ")} domains (hosts file entries also added)`)}else K("dns","Could not start DNS server - custom domains may not resolve",B)}let R=async()=>{K("cleanup","Starting cleanup handler",_.verbose);try{let{tearDownDevelopmentDns:$}=await import("./chunk-end75nnv.js");await $({verbose:_.verbose})}catch($){K("cleanup",`Error stopping DNS server: ${$}`,_.verbose)}try{await D_.stopAll(_.verbose)}catch($){K("cleanup",`Error stopping processes: ${$}`,_.verbose)}await d({domains:W,hosts:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.hosts,certs:typeof _.cleanup==="boolean"?_.cleanup:_.cleanup?.certs,verbose:_.verbose||!1})};if(F.on("SIGINT",R),F.on("SIGTERM",R),F.on("uncaughtException",($)=>{K("process",`Uncaught exception: ${$}`,!0),console.error("Uncaught exception:",$),R()}),G&&Y.length>1){K("proxies",`Creating shared HTTPS server for ${Y.length} domains`,B);let $=new Map;for(let Q of Y){let E=Q.to||"rpx.localhost",w=new URL(Q.from?.startsWith("http")?Q.from:`http://${Q.from}`);if($.set(E,{sourceHost:w.host,cleanUrls:Q.cleanUrls||!1,changeOrigin:Q.changeOrigin||!1,pathRewrites:Q.pathRewrites}),K("proxies",`Route: ${E} → ${w.host}`,B),!E.includes("localhost")&&!E.includes("127.0.0.1"))try{if(!(await h([E],B))[0])await L([E],B)}catch{K("hosts",`Could not add hosts entry for ${E}`,B)}}if(!await x(80,"0.0.0.0",B))P_(B);let Z=443;if(await x(Z,"0.0.0.0",B)){if(K("proxies",`Port ${Z} is already in use, cannot start shared proxy`,B),B)J.warn(`Port ${Z} is in use. Shared HTTPS proxy cannot start.`);return}try{let Q=Bun.serve({port:Z,hostname:"0.0.0.0",tls:{key:G.key,cert:G.cert,ca:G.ca,requestCert:!1,rejectUnauthorized:!1},fetch:M_((E)=>$.get(E),B),error(E){return K("server",`Shared proxy server error: ${E}`,B),new Response(`Server Error: ${E.message}`,{status:500})}});l.add(Q),K("proxies",`Shared HTTPS proxy listening on port ${Z} for ${$.size} domains`,B)}catch(Q){K("proxies",`Failed to start shared proxy: ${Q}`,B),console.error("Failed to start shared HTTPS proxy:",Q),R()}}else for(let $ of Y)try{let M=$.to||"rpx.localhost";K("proxy",`Starting proxy for ${M} with SSL config: ${!!G}`,$.verbose),await T_({from:$.from||"localhost:5173",to:M,cleanUrls:$.cleanUrls||!1,https:$.https||!1,cleanup:$.cleanup||!1,vitePluginUsage:$.vitePluginUsage||!1,verbose:$.verbose||!1,_cachedSSLConfig:G,changeOrigin:$.changeOrigin||!1})}catch(M){K("proxies",`Failed to start proxy for ${$.to}: ${M}`,$.verbose),console.error(`Failed to start proxy for ${$.to}:`,M),R()}}function f_(D){if(D?.vitePluginUsage||!D?.verbose)return;if(console.log(""),console.log(` ${H.green(H.bold("rpx"))} ${H.green(`v${b_}`)}`),console.log(` ${H.green("➜")} ${H.dim(D?.from??"")} ${H.dim("➜")} ${H.cyan(D?.ssl?`https://${D?.to}`:`http://${D?.to}`)}`),D?.listenPort!==(D?.ssl?443:80))console.log(` ${H.green("➜")} Listening on port ${D?.listenPort}`);if(D?.cleanUrls)console.log(` ${H.green("➜")} Clean URLs enabled`)}var rD=F_;export{G_ as writeEntry,S2 as watchRegistry,s_ as verifyHttpsChain,W2 as trustRootCaForBrowsers,c2 as tearDownDevelopmentDns,h2 as syncDevelopmentDnsFromRegistry,x2 as stopDnsServer,n2 as stopDaemon,T_ as startServer,p_ as startProxy,F_ as startProxies,q2 as startDnsServer,O2 as setupResolver,L2 as setupDevelopmentDns,C as safeStringify,GB as safeDeleteFile,t as runViaDaemon,g2 as runDaemon,f2 as resolverFilePath,j2 as resolverBasenamesForDomains,w2 as resolverBasenameForDomain,$B as resolvePathRewrite,u2 as removeResolver,P2 as removeLegacyTldResolvers,Z_ as removeHosts,W_ as removeEntry,p2 as releaseDaemonLock,oD as redactSensitive,m2 as reconcileStaleDevelopmentDns,t2 as reconcileDevelopmentDnsOnIdle,E2 as readEntry,l2 as readDaemonPid,n_ as readCertSha256Fingerprint,t_ as readCertCommonName,z2 as readAll,Y2 as pruneStaleRootCas,u_ as portManager,o_ as parseSha256HashesFromSecurityListing,i_ as normalizeSha256Fingerprint,I2 as normalizeDevDomain,Q2 as loadSSLConfig,N2 as listCertSha256HashesByCommonName,_B as isValidRootCA,$_ as isValidId,NB as isSingleProxyOptions,YB as isSingleProxyConfig,$2 as isRootCaTrustedForSsl,G2 as isRootCaFingerprintInKeychains,x as isPortInUse,R2 as isPidAlive,KB as isMultiProxyOptions,BB as isMultiProxyConfig,U2 as isDnsServerRunning,a2 as isDaemonRunning,V2 as isCertTrusted,N_ as httpsConfig,m as getSudoPassword,J2 as getSharedDaemonCertPaths,X2 as getRootCAPaths,Y_ as getRegistryDir,DB as getPrimaryDomain,K2 as getMacosTrustKeychains,B2 as getMacosLoginKeychainPath,v2 as getDaemonRpxDir,b2 as getDaemonPidPath,K_ as generateCertificate,M2 as gcStaleEntries,Z2 as forceTrustCertificate,U_ as findAvailablePort,eD as extractHostname,sD as execSudoSync,X_ as ensureDaemonRunning,H2 as devDomainsFromHosts,k_ as deriveIdFromTarget,i2 as defaultDaemonSpawnCommand,B_ as defaultConfig,rD as default,K as debugLog,M_ as createProxyFetchHandler,y2 as contentLooksLikeRpxResolver,B_ as config,H as colors,A2 as clearSslConfigCache,z_ as cleanupCertificates,d as cleanup,h as checkHosts,c as checkExistingCertificates,r_ as certIncludesSanHostnames,L as addHosts,d2 as acquireDaemonLock,D2 as RPX_ROOT_CA_COMMON_NAME,C2 as RPX_RESOLVER_MARKER,_2 as MACOS_SYSTEM_KEYCHAIN,e_ as MACOS_CA_TRUST_FLAGS,F2 as LEGACY_TLD_RESOLVER_LABELS,b as DefaultPortManager,T2 as DNS_STATE_VERSION,k2 as DNS_PORT};
|