@stacksjs/rpx 0.11.46 → 0.11.48
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 +239 -181
- package/dist/chunk-3tg7caak.js +311 -0
- package/dist/{chunk-t3s94va5.js → chunk-er1mtkha.js} +1 -1
- package/dist/{chunk-086aa2f7.js → chunk-handw2xw.js} +1 -1
- package/dist/{chunk-nnnptjfw.js → chunk-pcyc92vj.js} +11 -11
- package/dist/daemon.d.ts +4 -2
- package/dist/gateway.d.ts +65 -0
- package/dist/https.d.ts +8 -0
- package/dist/index.d.ts +26 -2
- package/dist/index.js +2 -2
- package/dist/local-ca.d.ts +77 -0
- package/dist/sni.d.ts +37 -0
- package/dist/start.d.ts +9 -1
- package/dist/types.d.ts +23 -0
- package/package.json +2 -2
- package/dist/chunk-z0swphpg.js +0 -253
package/dist/bin/cli.js
CHANGED
|
@@ -1,257 +1,315 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import{createRequire as Kw}from"node:module";var jw=Object.defineProperty;var Uw=(e)=>e;function Ww(e,t){this[e]=Uw.bind(null,t)}var Qf=(e,t)=>{for(var r in t)jw(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ww.bind(t,r)})};var Q=(e,t)=>()=>(e&&(t=e(e=0)),t);var I=Kw(import.meta.url);import{existsSync as fh,statSync as hh}from"fs";import{existsSync as Iv,mkdirSync as AA,readdirSync as kA,readFileSync as _v,writeFileSync as OA}from"fs";import{homedir as Gr}from"os";import{dirname as FA,resolve as lt}from"path";import Ns from"process";import{existsSync as dh,statSync as mh}from"fs";import{existsSync as Nc,mkdirSync as jv,readdirSync as Uv,writeFileSync as Wv}from"fs";import{homedir as qr}from"os";import{dirname as gh,resolve as He}from"path";import Ar from"process";import{join as Kv,relative as Hv,resolve as ph}from"path";import vs from"process";import{existsSync as Zh,mkdirSync as HA,readdirSync as VA,writeFileSync as YA}from"fs";import{homedir as hc}from"os";import{dirname as qA,resolve as Ke}from"path";import Xi from"process";import{join as Vv,relative as Yv,resolve as yh}from"path";import bs from"process";import{existsSync as ed,mkdirSync as e1,readdirSync as t1,writeFileSync as r1}from"fs";import{dirname as n1,resolve as $s}from"path";import Dc from"process";import{Buffer as cr}from"buffer";import{createCipheriv as zv,createDecipheriv as Gv,randomBytes as dc}from"crypto";import{closeSync as mc,createReadStream as wh,createWriteStream as qv,existsSync as gc,fsyncSync as vh,openSync as bh,writeFileSync as Jv}from"fs";import{access as Xv,constants as $h,mkdir as Qv,readdir as Zn,rename as xh,stat as Jr,unlink as es,writeFile as pc}from"fs/promises";import{join as Xr}from"path";import Re from"process";import{pipeline as Zv}from"stream/promises";import{createGzip as Ch}from"zlib";import Qr from"process";import Lt from"process";import{Buffer as Ft}from"buffer";import{createCipheriv as eb,createDecipheriv as tb,randomBytes as yc}from"crypto";import{closeSync as wc,createReadStream as Sh,createWriteStream as rb,existsSync as ts,fsyncSync as Eh,openSync as Th,writeFileSync as ib}from"fs";import{access as nb,constants as Ph,mkdir as sb,readdir as rs,rename as Rh,stat as Zr,unlink as is,writeFile as vc}from"fs/promises";import{isAbsolute as ob,join as ei,resolve as ab}from"path";import F from"process";import{pipeline as cb}from"stream/promises";import{createGzip as Ah}from"zlib";import ti from"process";import Mt from"process";import ns from"process";import{existsSync as ss}from"fs";import{resolve as bc}from"path";import{existsSync as lb}from"fs";import{existsSync as ub,readdirSync as fb}from"fs";import{extname as $c,resolve as kh}from"path";import hb from"process";import{join as db,relative as mb,resolve as Oh}from"path";import xs from"process";import{Buffer as Bt}from"buffer";import{createCipheriv as gb,createDecipheriv as pb,randomBytes as xc}from"crypto";import{closeSync as Cc,createReadStream as Nh,createWriteStream as yb,existsSync as os,fsyncSync as Dh,openSync as Fh,writeFileSync as wb}from"fs";import{access as vb,constants as Bh,mkdir as bb,readdir as as,rename as Lh,stat as ri,unlink as cs,writeFile as Sc}from"fs/promises";import{isAbsolute as $b,join as ii,resolve as xb}from"path";import B from"process";import{pipeline as Cb}from"stream/promises";import{createGzip as Mh}from"zlib";import ni from"process";import It from"process";import us from"process";import{existsSync as fs}from"fs";import{resolve as kc}from"path";import{existsSync as K$}from"fs";class Xh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!fh(e))return!0;return hh(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=fh(r)?hh(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Qh{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Tb(e,t){this[e]=Eb.bind(null,t)}class Vc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!dh(e))return!0;return mh(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=dh(r)?mh(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Yc{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Ab(e,t={}){let i=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return i?`${e}:${i}`:e}function kb(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Ob(e){return e.getStats().size*2}function zc(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ie(t[0])&&"id"in t[0]&&t[0].id===3&&ie(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ie(t)&&ie(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(ie(e)&&"arr"in e&&Array.isArray(e.arr)&&ie(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ie(t[0])&&ie(e[0])){let i=[...t];for(let n of e)if(ie(n)&&"name"in n){if(!i.find((o)=>ie(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(ie(n)&&"path"in n){if(!i.find((o)=>ie(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>Cs(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!ie(t)||!ie(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(ie(n)&&ie(r[i]))r[i]=zc(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&ie(n[0])&&ie(r[i][0])){let s=[...n];for(let o of r[i])if(ie(o)&&"name"in o){if(!s.find((a)=>ie(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(ie(o)&&"path"in o){if(!s.find((a)=>ie(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Cs(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function Cs(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Cs(e[r],t[r]))return!1;return!0}if(ie(e)&&ie(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Cs(e[n],t[n]))return!1}return!0}return!1}function ie(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Nb(e,t){if(!ed(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return zc(t,i)}catch{return null}}catch{return null}}async function Db({name:e="",cwd:t,defaultConfig:r}){let i=t||Dc.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of n){let a=$s(i,`${o}${c}`),l=await Nb(a,r);if(l!==null)return l}try{let o=$s(i,"package.json");if(ed(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return zc(r,a)}catch{}}}catch{}return r}function Fb(e,t={}){let r=bs.cwd();while(r.includes("storage"))r=yh(r,"..");let i=yh(r,e||"");if(t?.relative)return Yv(bs.cwd(),i);return i}async function Bb(){try{let e=await Db({name:"clarity",defaultConfig:ms,cwd:bs.cwd(),endpoint:"",headers:{}});return{...ms,...e}}catch{return ms}}function ae(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Lb(){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 e=Lt.type;if(e==="renderer"||e==="worker")return!1;return!!(Lt.versions&&(Lt.versions.node||Lt.versions.bun))}return!1}class rd{async format(e){let t=await Lb(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Qr.pid,hostname:t(),environment:Qr.env.NODE_ENV||"development",platform:Qr.platform,version:Qr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qr.env.NODE_ENV||Qr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ss{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(e,t={}){this.name=e,this.config={...Bc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new rd,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Re.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...gs,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...gs};return{...gs,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Bc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await Xv(this.config.logDirectory,$h.F_OK|$h.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Qv(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:cr.from(e);try{if(!gc(this.currentLogFile))await pc(this.currentLogFile,"",{mode:420});if(n=bh(this.currentLogFile,"a",420),Jv(n,a,{flag:"a"}),vh(n),n!==void 0)mc(n),n=void 0;if((await Jr(this.currentLogFile)).size===0){if(await pc(this.currentLogFile,a,{flag:"w",mode:420}),(await Jr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{mc(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 Xr(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 Xr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Xr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ae())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return dc(16).toString("hex")}generateKey(){return dc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=dc(16),i=zv("aes-256-gcm",t,r),n=cr.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:cr.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Ch(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(cr.from(cr.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ae())return;let e=await Jr(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Zn(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Jr(r).catch(()=>null))try{if(await xh(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await es(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await pc(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Jr(r).catch(()=>null))await xh(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await Zn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await es(Xr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=wh(e),i=qv(t),n=Ch();await Zv(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),gc(this.currentLogFile))try{let e=bh(this.currentLogFile,"r+");vh(e),mc(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ae()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Zn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await es(Xr(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Z.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=Re.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${Z.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!ae()){let l=hd[e],u=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:Z.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:Z.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
|
|
3
|
-
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:
|
|
2
|
+
import{createRequire as Pb}from"node:module";var Sb=Object.defineProperty;var Eb=(e)=>e;function Tb(e,t){this[e]=Eb.bind(null,t)}var nl=(e,t)=>{for(var r in t)Sb(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Tb.bind(t,r)})};var te=(e,t)=>()=>(e&&(t=e(e=0)),t);var U=Pb(import.meta.url);import{existsSync as _d,statSync as jd}from"fs";import{existsSync as C$,mkdirSync as I1,readdirSync as M1,readFileSync as x$,writeFileSync as _1}from"fs";import{homedir as nn}from"os";import{dirname as K1,resolve as gt}from"path";import wo from"process";import{existsSync as Ud,statSync as Kd}from"fs";import{existsSync as Nl,mkdirSync as S$,readdirSync as E$,writeFileSync as T$}from"fs";import{homedir as sn}from"os";import{dirname as Wd,resolve as Ye}from"path";import _r from"process";import{join as P$,relative as A$,resolve as Vd}from"path";import io from"process";import{existsSync as Pm,mkdirSync as Z1,readdirSync as Q1,writeFileSync as eO}from"fs";import{homedir as hl}from"os";import{dirname as nO,resolve as qe}from"path";import wi from"process";import{join as R$,relative as k$,resolve as Hd}from"path";import so from"process";import{existsSync as Am,mkdirSync as cO,readdirSync as lO,writeFileSync as uO}from"fs";import{dirname as hO,resolve as oo}from"path";import Dl from"process";import{Buffer as wr}from"buffer";import{createCipheriv as O$,createDecipheriv as N$,randomBytes as dl}from"crypto";import{closeSync as ml,createReadStream as zd,createWriteStream as D$,existsSync as gl,fsyncSync as Gd,openSync as qd,writeFileSync as F$}from"fs";import{access as L$,constants as Yd,mkdir as B$,readdir as Ms,rename as Jd,stat as on,unlink as _s,writeFile as pl}from"fs/promises";import{join as an}from"path";import Be from"process";import{pipeline as I$}from"stream/promises";import{createGzip as Xd}from"zlib";import cn from"process";import Wt from"process";import{Buffer as Ut}from"buffer";import{createCipheriv as M$,createDecipheriv as _$,randomBytes as yl}from"crypto";import{closeSync as wl,createReadStream as Zd,createWriteStream as j$,existsSync as js,fsyncSync as Qd,openSync as em,writeFileSync as U$}from"fs";import{access as K$,constants as tm,mkdir as W$,readdir as Us,rename as rm,stat as ln,unlink as Ks,writeFile as vl}from"fs/promises";import{isAbsolute as V$,join as un,resolve as H$}from"path";import I from"process";import{pipeline as z$}from"stream/promises";import{createGzip as nm}from"zlib";import fn from"process";import Vt from"process";import Ws from"process";import{existsSync as Vs}from"fs";import{resolve as bl}from"path";import{existsSync as G$}from"fs";import{existsSync as q$,readdirSync as Y$}from"fs";import{extname as $l,resolve as im}from"path";import J$ from"process";import{join as X$,relative as Z$,resolve as sm}from"path";import ao from"process";import{Buffer as Kt}from"buffer";import{createCipheriv as Q$,createDecipheriv as eC,randomBytes as Cl}from"crypto";import{closeSync as xl,createReadStream as om,createWriteStream as tC,existsSync as Hs,fsyncSync as am,openSync as cm,writeFileSync as rC}from"fs";import{access as nC,constants as lm,mkdir as iC,readdir as zs,rename as um,stat as hn,unlink as Gs,writeFile as Sl}from"fs/promises";import{isAbsolute as sC,join as dn,resolve as oC}from"path";import M from"process";import{pipeline as aC}from"stream/promises";import{createGzip as fm}from"zlib";import mn from"process";import Ht from"process";import Ys from"process";import{existsSync as Js}from"fs";import{resolve as kl}from"path";import{existsSync as Px}from"fs";class Em{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!_d(e))return!0;return jd(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=_d(r)?jd(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Tm{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function uC(e,t){this[e]=lC.bind(null,t)}class Hl{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Ud(e))return!0;return Kd(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Ud(r)?Kd(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class zl{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function dC(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function mC(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function gC(e){return e.getStats().size*2}function Gl(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ae(t[0])&&"id"in t[0]&&t[0].id===3&&ae(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ae(t)&&ae(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(ae(e)&&"arr"in e&&Array.isArray(e.arr)&&ae(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ae(t[0])&&ae(e[0])){let n=[...t];for(let i of e)if(ae(i)&&"name"in i){if(!n.find((o)=>ae(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(ae(i)&&"path"in i){if(!n.find((o)=>ae(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>co(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!ae(t)||!ae(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(ae(i)&&ae(r[n]))r[n]=Gl(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&ae(i[0])&&ae(r[n][0])){let s=[...i];for(let o of r[n])if(ae(o)&&"name"in o){if(!s.find((a)=>ae(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(ae(o)&&"path"in o){if(!s.find((a)=>ae(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>co(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function co(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!co(e[r],t[r]))return!1;return!0}if(ae(e)&&ae(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!co(e[i],t[i]))return!1}return!0}return!1}function ae(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function pC(e,t){if(!Am(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Gl(t,n)}catch{return null}}catch{return null}}async function yC({name:e="",cwd:t,defaultConfig:r}){let n=t||Dl.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=oo(n,`${o}${c}`),l=await pC(a,r);if(l!==null)return l}try{let o=oo(n,"package.json");if(Am(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Gl(r,a)}catch{}}}catch{}return r}function wC(e,t={}){let r=so.cwd();while(r.includes("storage"))r=Hd(r,"..");let n=Hd(r,e||"");if(t?.relative)return k$(so.cwd(),n);return n}async function vC(){try{let e=await yC({name:"clarity",defaultConfig:Qs,cwd:so.cwd(),endpoint:"",headers:{}});return{...Qs,...e}}catch{return Qs}}function he(){if(Wt.env.NODE_ENV==="test"||Wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bC(){if(Wt.env.NODE_ENV==="test"||Wt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Wt<"u"){let e=Wt.type;if(e==="renderer"||e==="worker")return!1;return!!(Wt.versions&&(Wt.versions.node||Wt.versions.bun))}return!1}class km{async format(e){let t=await bC(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:cn.pid,hostname:t(),environment:cn.env.NODE_ENV||"development",platform:cn.platform,version:cn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:cn.env.NODE_ENV||cn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class lo{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(e,t={}){this.name=e,this.config={...Ll},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new km,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Be.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...eo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...eo};return{...eo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ll.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await L$(this.config.logDirectory,Yd.F_OK|Yd.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await B$(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:wr.from(e);try{if(!gl(this.currentLogFile))await pl(this.currentLogFile,"",{mode:420});if(i=qd(this.currentLogFile,"a",420),F$(i,a,{flag:"a"}),Gd(i),i!==void 0)ml(i),i=void 0;if((await on(this.currentLogFile)).size===0){if(await pl(this.currentLogFile,a,{flag:"w",mode:420}),(await on(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{ml(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 an(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 an(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return an(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(he())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return dl(16).toString("hex")}generateKey(){return dl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=dl(16),n=O$("aes-256-gcm",t,r),i=wr.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:wr.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Xd(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(wr.from(wr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(he())return;let e=await on(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Ms(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await on(r).catch(()=>null))try{if(await Jd(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await _s(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await pl(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await on(r).catch(()=>null))await Jd(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Ms(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await _s(an(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=zd(e),n=D$(t),i=Xd();await I$(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),gl(this.currentLogFile))try{let e=qd(this.currentLogFile,"r+");Gd(e),ml(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!he()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ms(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await _s(an(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?re.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=Be.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${re.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!he()){let l=jm[e],u=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:re.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:re.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
|
|
3
|
+
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:re.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!he()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
4
4
|
`;if(c)a+=`${c}
|
|
5
|
-
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!
|
|
6
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
7
|
-
`),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:
|
|
8
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
9
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||
|
|
10
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ae()||!Re.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ae()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Zn(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=Xr(this.config.logDirectory,i);if(e.before)try{if((await Jr(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await es(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ds(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&z(t[0])&&"id"in t[0]&&t[0].id===3&&z(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(z(t)&&z(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(z(e)&&"arr"in e&&Array.isArray(e.arr)&&z(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&z(t[0])&&z(e[0])){let i=[...t];for(let n of e)if(z(n)&&"name"in n){if(!i.find((o)=>z(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(z(n)&&"path"in n){if(!i.find((o)=>z(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>Es(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!z(t)||!z(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(z(n)&&z(r[i]))r[i]=ds(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&z(n[0])&&z(r[i][0])){let s=[...n];for(let o of r[i])if(z(o)&&"name"in o){if(!s.find((a)=>z(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(z(o)&&"path"in o){if(!s.find((a)=>z(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Es(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function Gc(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ds(e,t);if(Array.isArray(e))return r==="replace"?t:ds(e,t);if(!z(t)||!z(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=ds(o,s);else if(z(s)&&z(o))i[n]=Gc(o,s,r);else i[n]=s}return i}function Es(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Es(e[r],t[r]))return!1;return!0}if(z(e)&&z(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Es(e[n],t[n]))return!1}return!0}return!1}function z(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ls(e,t,r="replace"){if(!Zh(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Gc(t,n,r)}catch{return null}}catch{return null}}function Mb(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${f.map(h).join("_")}`,y=`${i}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)ke.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=Xi.env[d]||Xi.env[y];if(g!==void 0){if(r)ke.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(n)}async function Ib({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?Mb(e,n,s):n,l=r||Xi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)ke.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Ke(l,"config"),Ke(l,".config"),i?Ke(l,i):void 0].filter(Boolean)));for(let p of g){if(s)ke.info(`Searching for configuration in: ${p}`);let b=[Ke(l,"config"),Ke(l,".config")].concat(i?[Ke(l,i)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let P of b)for(let R of u){let v=Ke(p,`${P}${R}`),T=await ls(v,a,c);if(T!==null){if(s)ke.success(`Configuration loaded from: ${v}`);return T}}}if(e){let p=Ke(hc(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)ke.info(`Checking user config directory: ${p}`);for(let b of w)for(let P of u){let R=Ke(p,`${b}${P}`),v=await ls(R,a,c);if(v!==null){if(s)ke.success(`Configuration loaded from user config directory: ${R}`);return v}}}if(e){let p=Ke(hc(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)ke.info(`Checking user config directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ke(p,`${b}${P}`),v=await ls(R,a,c);if(v!==null){if(s)ke.success(`Configuration loaded from user config directory dotfile: ${R}`);return v}}}if(e){let p=hc(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)ke.info(`Checking user home directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ke(p,`${b}${P}`),v=await ls(R,a,c);if(v!==null){if(s)ke.success(`Configuration loaded from user home directory: ${R}`);return v}}}try{let p=Ke(l,"package.json");if(Zh(p)){let w=await import(p),b=w[e];if(!b&&t){if(b=w[t],b&&s)ke.success(`Using alias "${t}" configuration from package.json`)}if(b&&typeof b==="object"&&!Array.isArray(b))try{if(s)ke.success(`Configuration loaded from package.json: ${b===w[e]?e:t}`);return Gc(a,b,c)}catch(P){if(s)ke.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)ke.warn("Failed to load package.json:",p)}if(s)ke.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function _b(e,t={}){let r=vs.cwd();while(r.includes("storage"))r=ph(r,"..");let i=ph(r,e||"");if(t?.relative)return Hv(vs.cwd(),i);return i}async function jb(){try{let e=await Ib({name:"clarity",alias:"logging",defaultConfig:ps,cwd:vs.cwd()});return{...ps,...e||{}}}catch{return ps}}function ge(){if(Mt.env.NODE_ENV==="test"||Mt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ub(){if(Mt.env.NODE_ENV==="test"||Mt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Mt<"u"){let e=Mt.type;if(e==="renderer"||e==="worker")return!1;return!!(Mt.versions&&(Mt.versions.node||Mt.versions.bun))}return!1}class id{async format(e){let t=await Ub(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ti.pid,hostname:t(),environment:ti.env.NODE_ENV||"development",platform:ti.platform,version:ti.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ti.env.NODE_ENV||ti.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ts{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(e,t={}){this.name=e,this.config={...Lc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new id,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??F.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ys,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ys};return{...ys,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Lc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ge()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await nb(this.config.logDirectory,Ph.F_OK|Ph.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await sb(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ft.from(e);try{if(!ts(this.currentLogFile))await vc(this.currentLogFile,"",{mode:420});if(n=Th(this.currentLogFile,"a",420),ib(n,a,{flag:"a"}),Eh(n),n!==void 0)wc(n),n=void 0;if((await Zr(this.currentLogFile)).size===0){if(await vc(this.currentLogFile,a,{flag:"w",mode:420}),(await Zr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{wc(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 ei(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 ei(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ei(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ge())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return yc(16).toString("hex")}generateKey(){return yc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=yc(16),i=eb("aes-256-gcm",t,r),n=Ft.isBuffer(e)?e:Ft.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=Ft.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Ah(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Ft.from(Ft.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ge())return;if(!this.shouldWriteToFile())return;let e=await Zr(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await rs(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Zr(r).catch(()=>null))try{if(await Rh(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await is(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await vc(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Zr(r).catch(()=>null))await Rh(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await rs(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await is(ei(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Sh(e),i=rb(t),n=Ah();await cb(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ts(this.currentLogFile))try{let e=Th(this.currentLogFile,"r+");Eh(e),wc(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ge()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await rs(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await is(ei(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?_.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ge())return!1;let e=typeof F.env.NO_COLOR<"u",t=F.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof F.stderr<"u"&&F.stderr.isTTY||typeof F.stdout<"u"&&F.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=F.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${_.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=_.underline(_.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>_.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>_.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>_.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>_.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>_.strikethrough(i)),t}supportsHyperlinks(){if(ge())return!1;let e=F.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=F.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ob(t)||t.startsWith("./")||t.startsWith("../"))t=ab(t);else return null;return ts(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":dd[e],h=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:_.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:_.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
11
|
-
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:
|
|
5
|
+
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!he()){let r=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:re.blue("◐"),tag:r,message:`${re.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
6
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!he()){let u=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:re.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!he())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new lo(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(he())throw Error("createReadStream is not supported in browser environments");if(!gl(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return zd(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=wr.isBuffer(e)?e:wr.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=N$("aes-256-gcm",r,i);return c.setAuthTag(s),wr.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return he()}isServerMode(){return!he()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!he()){let s=e.split(`
|
|
7
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:re.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:re.cyan(c)})),l.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:re.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:re.cyan(a),showTimestamp:!1}))}else if(!he())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(he())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${re.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Be.stdin.removeListener("data",r);try{if(typeof Be.stdin.setRawMode==="function")Be.stdin.setRawMode(!1)}catch{}Be.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Be.stdin.setRawMode==="function")Be.stdin.setRawMode(!0)}catch{}Be.stdin.resume(),Be.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!he()){let o=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",c=re.blue("◐");console.error(`${c} ${o} ${re.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
9
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||he()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||he())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||he())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||he())return;Be.stdout.write(`${"\r".padEnd(Be.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||he()||!Be.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=re.green("━".repeat(n)),o=re.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=t||r===100?re.green("✓"):re.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${re.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=Be.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,Be.stdout.write(e.lastRenderedLine),t)Be.stdout.write(`
|
|
10
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||he()||!Be.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(he()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ms(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=an(this.config.logDirectory,n);if(e.before)try{if((await on(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await _s(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Zs(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Y(t[0])&&"id"in t[0]&&t[0].id===3&&Y(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Y(t)&&Y(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Y(e)&&"arr"in e&&Array.isArray(e.arr)&&Y(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Y(t[0])&&Y(e[0])){let n=[...t];for(let i of e)if(Y(i)&&"name"in i){if(!n.find((o)=>Y(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(Y(i)&&"path"in i){if(!n.find((o)=>Y(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>uo(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Y(t)||!Y(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Y(i)&&Y(r[n]))r[n]=Zs(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Y(i[0])&&Y(r[n][0])){let s=[...i];for(let o of r[n])if(Y(o)&&"name"in o){if(!s.find((a)=>Y(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(Y(o)&&"path"in o){if(!s.find((a)=>Y(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>uo(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function ql(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Zs(e,t);if(Array.isArray(e))return r==="replace"?t:Zs(e,t);if(!Y(t)||!Y(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=Zs(o,s);else if(Y(s)&&Y(o))n[i]=ql(o,s,r);else n[i]=s}return n}function uo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!uo(e[r],t[r]))return!1;return!0}if(Y(e)&&Y(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!uo(e[i],t[i]))return!1}return!0}return!1}function Y(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function qs(e,t,r="replace"){if(!Pm(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return ql(t,i,r)}catch{return null}}catch{return null}}function $C(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${n}_${f.map(h).join("_")}`,y=`${n}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)Me.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=wi.env[d]||wi.env[y];if(g!==void 0){if(r)Me.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(i)}async function CC({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?$C(e,i,s):i,l=r||wi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Me.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,qe(l,"config"),qe(l,".config"),n?qe(l,n):void 0].filter(Boolean)));for(let p of g){if(s)Me.info(`Searching for configuration in: ${p}`);let v=[qe(l,"config"),qe(l,".config")].concat(n?[qe(l,n)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let P of v)for(let A of u){let R=qe(p,`${P}${A}`),D=await qs(R,a,c);if(D!==null){if(s)Me.success(`Configuration loaded from: ${R}`);return D}}}if(e){let p=qe(hl(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)Me.info(`Checking user config directory: ${p}`);for(let v of w)for(let P of u){let A=qe(p,`${v}${P}`),R=await qs(A,a,c);if(R!==null){if(s)Me.success(`Configuration loaded from user config directory: ${A}`);return R}}}if(e){let p=qe(hl(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)Me.info(`Checking user config directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=qe(p,`${v}${P}`),R=await qs(A,a,c);if(R!==null){if(s)Me.success(`Configuration loaded from user config directory dotfile: ${A}`);return R}}}if(e){let p=hl(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)Me.info(`Checking user home directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=qe(p,`${v}${P}`),R=await qs(A,a,c);if(R!==null){if(s)Me.success(`Configuration loaded from user home directory: ${A}`);return R}}}try{let p=qe(l,"package.json");if(Pm(p)){let w=await import(p),v=w[e];if(!v&&t){if(v=w[t],v&&s)Me.success(`Using alias "${t}" configuration from package.json`)}if(v&&typeof v==="object"&&!Array.isArray(v))try{if(s)Me.success(`Configuration loaded from package.json: ${v===w[e]?e:t}`);return ql(a,v,c)}catch(P){if(s)Me.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)Me.warn("Failed to load package.json:",p)}if(s)Me.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function xC(e,t={}){let r=io.cwd();while(r.includes("storage"))r=Vd(r,"..");let n=Vd(r,e||"");if(t?.relative)return A$(io.cwd(),n);return n}async function SC(){try{let e=await CC({name:"clarity",alias:"logging",defaultConfig:to,cwd:io.cwd()});return{...to,...e||{}}}catch{return to}}function be(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function EC(){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 e=Vt.type;if(e==="renderer"||e==="worker")return!1;return!!(Vt.versions&&(Vt.versions.node||Vt.versions.bun))}return!1}class Om{async format(e){let t=await EC(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:fn.pid,hostname:t(),environment:fn.env.NODE_ENV||"development",platform:fn.platform,version:fn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:fn.env.NODE_ENV||fn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class fo{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(e,t={}){this.name=e,this.config={...Bl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Om,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ro,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ro};return{...ro,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Bl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!be()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await K$(this.config.logDirectory,tm.F_OK|tm.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await W$(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ut.from(e);try{if(!js(this.currentLogFile))await vl(this.currentLogFile,"",{mode:420});if(i=em(this.currentLogFile,"a",420),U$(i,a,{flag:"a"}),Qd(i),i!==void 0)wl(i),i=void 0;if((await ln(this.currentLogFile)).size===0){if(await vl(this.currentLogFile,a,{flag:"w",mode:420}),(await ln(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{wl(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 un(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 un(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return un(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(be())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return yl(16).toString("hex")}generateKey(){return yl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=yl(16),n=M$("aes-256-gcm",t,r),i=Ut.isBuffer(e)?e:Ut.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=Ut.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=nm(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Ut.from(Ut.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(be())return;if(!this.shouldWriteToFile())return;let e=await ln(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Us(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ln(r).catch(()=>null))try{if(await rm(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ks(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await vl(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ln(r).catch(()=>null))await rm(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Us(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Ks(un(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Zd(e),n=j$(t),i=nm();await z$(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),js(this.currentLogFile))try{let e=em(this.currentLogFile,"r+");Qd(e),wl(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!be()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Us(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ks(un(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?K.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||be())return!1;let e=typeof I.env.NO_COLOR<"u",t=I.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=I.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${K.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=K.underline(K.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>K.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>K.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>K.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>K.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>K.strikethrough(n)),t}supportsHyperlinks(){if(be())return!1;let e=I.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=I.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(V$(t)||t.startsWith("./")||t.startsWith("../"))t=H$(t);else return null;return js(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Um[e],h=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:K.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:K.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
11
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:K.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!be()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
12
12
|
`;if(c)u+=`${c}
|
|
13
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let
|
|
14
|
-
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
15
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?
|
|
16
|
-
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(
|
|
18
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
19
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
13
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!be()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!be()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!be()&&I.stdout.isTTY)I.stdout.write(`
|
|
14
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!be()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":K.blue("◐"),tag:r,message:`${K.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
15
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":K.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!be())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new fo(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(be())throw Error("createReadStream is not supported in browser environments");if(!js(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Zd(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Ut.isBuffer(e)?e:Ut.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=_$("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Ut.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return be()}isServerMode(){return!be()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
16
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:K.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(u),showTimestamp:!1}))}else if(!be())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(be())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${K.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();I.stdin.removeListener("data",r);try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!1)}catch{}I.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!0)}catch{}I.stdin.resume(),I.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){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 u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${l}${a} ${K.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
18
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!I.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=K.green("━".repeat(n)),o=K.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?K.green("✓"):K.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=I.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,I.stdout.write(e.lastRenderedLine),t)I.stdout.write(`
|
|
19
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||be()||!I.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(be()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Us(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=un(this.config.logDirectory,n);if(e.before)try{if((await ln(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ks(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Nm(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Dm(e){return e instanceof ot}function TC(e){return e instanceof ho}function PC(e){if(Dm(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class vo{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return $i.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Ws.env[a]||(l?Ws.env[l]:void 0);if(u!==void 0){if(n.verbose){let f=Ws.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(u,typeof s,a,n.customParsers,n.configName)}catch(f){if(f instanceof mo)throw f;throw vr.envVar(a,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw vr.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Ws.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
20
20
|
|
|
21
|
-
`;for(let
|
|
22
|
-
`,r+=` Type: ${
|
|
23
|
-
`,r+=` Description: ${
|
|
24
|
-
`,r+=` Example: ${
|
|
21
|
+
`;for(let n of e)r+=`${n.key}
|
|
22
|
+
`,r+=` Type: ${n.type}
|
|
23
|
+
`,r+=` Description: ${n.description}
|
|
24
|
+
`,r+=` Example: ${n.example}
|
|
25
25
|
|
|
26
26
|
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
27
27
|
|
|
28
28
|
`;r+=`| Variable | Type | Description | Example |
|
|
29
29
|
`,r+=`|----------|------|-------------|----------|
|
|
30
|
-
`;for(let
|
|
31
|
-
`;return r}}function Hb(e,t){let r=ud("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function od(e,t,r={}){return ad(e,t,r,new WeakMap)}function ad(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return cd(e,t,n,i);if(!ut(t)||!ut(e))return t;return Gb(e,t,r,i)}function cd(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Vb(e,t);case"smart":return Yb(e,t,i);default:return t}return t}function Vb(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Fc(n,i)))r.push(i);return r}function Yb(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(ut(t[0])&&ut(e[0]))return zb(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function zb(e,t,r){let i=[...t];for(let n of e){if(!ut(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in n){if(i.find((l)=>ut(l)&&(c in l)&&l[c]===n[c])){o=!0;break}}if(!o)i.push(n)}return i}function Gb(e,t,r,i){let n=t;if(ut(n)&&i.has(n))return i.get(n);let s={...e};if(ut(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(ut(c)&&ut(a))s[o]=ad(a,c,r,i);else if(Array.isArray(c)||Array.isArray(a))s[o]=cd(a,c,r.arrayMergeMode||"smart",i);else s[o]=c}return s}function qc(e,t,r="replace"){return od(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Fc(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Fc(e[r],t[r]))return!1;return!0}if(ut(e)&&ut(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Fc(e[n],t[n]))return!1}return!0}return!1}function ut(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Fs{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=si.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!ss(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new Qi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Qi(e,Error("Configuration must export a valid object"),"unknown");let p={config:qc(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)si.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?lr.configLoad(e,l):lr.configLoad(e,Error(String(l)))}};if(o)return en.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(bc(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return nd(async()=>ss(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!ss(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let c=bc(e,`${s}${o}`);if(await this.checkFileAccess(c))i.push(c)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=bc(e,o);if(await this.checkFileAccess(c))i.push(c)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!ss(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Jc{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await en.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!lb(t))throw new Zi(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new Zi(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(i.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(i.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(i.push(...c),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:gd},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Xc{fileLoader=new Fs;envProcessor=new Ds;validator=new Jc;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||s)await this.validateConfiguration(c.config,n,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(i?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(a);if(i.slowThreshold&&a.duration>i.slowThreshold)vt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw vt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Ar.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,o)),this.finalizeResult(d,h,a,i,u);let y=await this.loadHomeConfiguration(i,n,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,a,i,u);let g=await this.loadPackageJsonConfiguration(i,n,f,c,l,u,a);if(g)return h.push(He(f,"package.json")),this.finalizeResult(g,h,a,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,o)),t)throw lr.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,c,a,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,c,a){let l=c?Ji(e,n,o):n,u=this.getLocalDirectories(r,i);for(let f of u){if(o)vt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)vt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?Ji(e,r,n):r,c=[He(qr(),".config",e),He(qr(),".config"),qr()];for(let a of c){if(n)vt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(u){if(n)vt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let c=o?Ji(e,i,s):i;try{let a=He(r,"package.json");if(!Nc(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)vt.success(`Configuration loaded from package.json: ${f}`);return{config:qc(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)vt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ji(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw lr.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return si.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);si.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,He(e,"config"),He(e,".config"),t?He(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(He(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[He(qr(),".config",e),He(qr(),".config"),qr()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Ih(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),i=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||i}async function qb(e){return _t.loadConfig({...e,__strictErrorHandling:!0})}async function ld(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await _t.loadConfig(e);else i=await _t.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)vt.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await _t.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Jb(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await _t.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Ih(r)))return(await _t.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await _t.loadConfig({...e,cwd:e.cwd||Ar.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Ih(t)))return(await _t.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Xb(e,t,r="replace"){let i=new Fs;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Ji(e,t,r=!1){let i=new Ds,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((g)=>g.toUpperCase()).join("")}`,`${n}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Ar.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function Qb(e){let t=He(Ar.cwd(),e.configDir),r=He(Ar.cwd(),e.generatedDir),i=He(r,"config-types.ts");if(!Nc(gh(i)))jv(gh(i),{recursive:!0,mode:511});let n=Nc(t)?Uv(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${P$}
|
|
32
|
-
export type ConfigNames = ${
|
|
33
|
-
`;
|
|
34
|
-
${
|
|
30
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
31
|
+
`;return r}}function AC(e,t){let r=Mm("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Fm(e,t,r={}){return Lm(e,t,r,new WeakMap)}function Lm(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Bm(e,t,i,n);if(!pt(t)||!pt(e))return t;return NC(e,t,r,n)}function Bm(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return RC(e,t);case"smart":return kC(e,t,n);default:return t}return t}function RC(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Fl(i,n)))r.push(n);return r}function kC(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(pt(t[0])&&pt(e[0]))return OC(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function OC(e,t,r){let n=[...t];for(let i of e){if(!pt(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>pt(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function NC(e,t,r,n){let i=t;if(pt(i)&&n.has(i))return n.get(i);let s={...e};if(pt(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(pt(c)&&pt(a))s[o]=Lm(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=Bm(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function Yl(e,t,r="replace"){return Fm(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Fl(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Fl(e[r],t[r]))return!1;return!0}if(pt(e)&&pt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Fl(e[i],t[i]))return!1}return!0}return!1}function pt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class bo{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=gn.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Vs(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new vi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new vi(e,Error("Configuration must export a valid object"),"unknown");let p={config:Yl(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)gn.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?vr.configLoad(e,l):vr.configLoad(e,Error(String(l)))}};if(o)return $i.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(bl(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Nm(async()=>Vs(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Vs(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=bl(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=bl(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Vs(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Jl{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await $i.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!G$(t))throw new bi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new bi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Wm},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Xl{fileLoader=new bo;envProcessor=new vo;validator=new Jl;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)Et.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw Et.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||_r.cwd(),h=[],d=await this.loadLocalConfiguration(n,i,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(n,i,f,o)),this.finalizeResult(d,h,a,n,u);let y=await this.loadHomeConfiguration(n,i,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(y,h,a,n,u);let g=await this.loadPackageJsonConfiguration(n,i,f,c,l,u,a);if(g)return h.push(Ye(f,"package.json")),this.finalizeResult(g,h,a,n,u);if(h.push(...this.getAllSearchPaths(n,i,f,o)),t)throw vr.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?yi(e,i,o):i,u=this.getLocalDirectories(r,n);for(let f of u){if(o)Et.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Et.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?yi(e,r,i):r,c=[Ye(sn(),".config",e),Ye(sn(),".config"),sn()];for(let a of c){if(i)Et.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(u){if(i)Et.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?yi(e,n,s):n;try{let a=Ye(r,"package.json");if(!Nl(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Et.success(`Configuration loaded from package.json: ${f}`);return{config:Yl(c,u,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Et.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:yi(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw vr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return gn.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);gn.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ye(e,"config"),Ye(e,".config"),t?Ye(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Ye(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ye(sn(),".config",e),Ye(sn(),".config"),sn()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function hm(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function DC(e){return zt.loadConfig({...e,__strictErrorHandling:!0})}async function Im(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await zt.loadConfig(e);else n=await zt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)Et.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await zt.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function FC(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await zt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&hm(r)))return(await zt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await zt.loadConfig({...e,cwd:e.cwd||_r.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&hm(t)))return(await zt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function LC(e,t,r="replace"){let n=new bo;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function yi(e,t,r=!1){let n=new vo,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((g)=>g.toUpperCase()).join("")}`,`${i}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=_r.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function BC(e){let t=Ye(_r.cwd(),e.configDir),r=Ye(_r.cwd(),e.generatedDir),n=Ye(r,"config-types.ts");if(!Nl(Wd(n)))S$(Wd(n),{recursive:!0,mode:511});let i=Nl(t)?E$(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${fx}
|
|
32
|
+
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
33
|
+
`;T$(n,s,{mode:438})}function IC(e){let t=null,r=null,n=()=>{if(!r)r=Im(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)Et.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function MC(e){let t=im(J$.cwd(),e?.configDir||"./config");function r(){if(!q$(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Y$(t).filter((a)=>i.has($l(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=$l(l).toLowerCase(),f=c.get(a);if(!f){c.set(a,l);continue}let h=$l(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=i.length?`{
|
|
34
|
+
${i.map((l)=>{let u=im(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${u}').default`}).join(`,
|
|
35
35
|
`)}
|
|
36
36
|
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
37
37
|
export type ConfigByName = ${c}
|
|
38
38
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
39
|
export type ConfigOf = Config
|
|
40
|
-
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}function A$(e,t={}){let r=xs.cwd();while(r.includes("storage"))r=Oh(r,"..");let i=Oh(r,e||"");if(t?.relative)return mb(xs.cwd(),i);return i}function ye(){if(It.env.NODE_ENV==="test"||It.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function O$(){if(It.env.NODE_ENV==="test"||It.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof It<"u"){let e=It.type;if(e==="renderer"||e==="worker")return!1;return!!(It.versions&&(It.versions.node||It.versions.bun))}return!1}class vd{async format(e){let t=await O$(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ni.pid,hostname:t(),environment:ni.env.NODE_ENV||"development",platform:ni.platform,version:ni.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ni.env.NODE_ENV||ni.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Bs{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(e,t={}){this.name=e,this.config={...As},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new vd,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??B.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ac,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ac};return{...Ac,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:As.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ye()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await vb(this.config.logDirectory,Bh.F_OK|Bh.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await bb(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Bt.from(e);try{if(!os(this.currentLogFile))await Sc(this.currentLogFile,"",{mode:420});if(n=Fh(this.currentLogFile,"a",420),wb(n,a,{flag:"a"}),Dh(n),n!==void 0)Cc(n),n=void 0;if((await ri(this.currentLogFile)).size===0){if(await Sc(this.currentLogFile,a,{flag:"w",mode:420}),(await ri(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{Cc(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 ii(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 ii(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ii(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ye())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return xc(16).toString("hex")}generateKey(){return xc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=xc(16),i=gb("aes-256-gcm",t,r),n=Bt.isBuffer(e)?e:Bt.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=Bt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Mh(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Bt.from(Bt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ye())return;if(!this.shouldWriteToFile())return;let e=await ri(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await as(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ri(r).catch(()=>null))try{if(await Lh(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await cs(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Sc(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await ri(r).catch(()=>null))await Lh(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await as(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await cs(ii(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Nh(e),i=yb(t),n=Mh();await Cb(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),os(this.currentLogFile))try{let e=Fh(this.currentLogFile,"r+");Dh(e),Cc(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ye()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await as(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await cs(ii(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?K.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ye())return!1;let e=typeof B.env.NO_COLOR<"u",t=B.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof B.stderr<"u"&&B.stderr.isTTY||typeof B.stdout<"u"&&B.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=B.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${K.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=K.underline(K.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>K.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>K.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>K.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>K.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>K.strikethrough(i)),t}supportsHyperlinks(){if(ye())return!1;let e=B.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=B.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if($b(t)||t.startsWith("./")||t.startsWith("../"))t=xb(t);else return null;return os(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":L$[e],h=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:K.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:K.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
41
|
-
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:
|
|
40
|
+
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function dx(e,t={}){let r=ao.cwd();while(r.includes("storage"))r=sm(r,"..");let n=sm(r,e||"");if(t?.relative)return Z$(ao.cwd(),n);return n}function Ce(){if(Ht.env.NODE_ENV==="test"||Ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gx(){if(Ht.env.NODE_ENV==="test"||Ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ht<"u"){let e=Ht.type;if(e==="renderer"||e==="worker")return!1;return!!(Ht.versions&&(Ht.versions.node||Ht.versions.bun))}return!1}class Gm{async format(e){let t=await gx(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:mn.pid,hostname:t(),environment:mn.env.NODE_ENV||"development",platform:mn.platform,version:mn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:mn.env.NODE_ENV||mn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $o{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(e,t={}){this.name=e,this.config={...go},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Gm,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Rl,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Rl};return{...Rl,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:go.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ce()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await nC(this.config.logDirectory,lm.F_OK|lm.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await iC(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Kt.from(e);try{if(!Hs(this.currentLogFile))await Sl(this.currentLogFile,"",{mode:420});if(i=cm(this.currentLogFile,"a",420),rC(i,a,{flag:"a"}),am(i),i!==void 0)xl(i),i=void 0;if((await hn(this.currentLogFile)).size===0){if(await Sl(this.currentLogFile,a,{flag:"w",mode:420}),(await hn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{xl(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 dn(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 dn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return dn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ce())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Cl(16).toString("hex")}generateKey(){return Cl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Cl(16),n=Q$("aes-256-gcm",t,r),i=Kt.isBuffer(e)?e:Kt.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=Kt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=fm(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Kt.from(Kt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ce())return;if(!this.shouldWriteToFile())return;let e=await hn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await zs(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await hn(r).catch(()=>null))try{if(await um(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Gs(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Sl(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await hn(r).catch(()=>null))await um(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await zs(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Gs(dn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=om(e),n=tC(t),i=fm();await aC(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Hs(this.currentLogFile))try{let e=cm(this.currentLogFile,"r+");am(e),xl(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ce()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await zs(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Gs(dn(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?H.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ce())return!1;let e=typeof M.env.NO_COLOR<"u",t=M.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=M.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${H.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=H.underline(H.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>H.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>H.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>H.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>H.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>H.strikethrough(n)),t}supportsHyperlinks(){if(Ce())return!1;let e=M.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=M.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(sC(t)||t.startsWith("./")||t.startsWith("../"))t=oC(t);else return null;return Hs(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":bx[e],h=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:H.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:H.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
41
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:H.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!Ce()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
42
42
|
`;if(c)u+=`${c}
|
|
43
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let
|
|
44
|
-
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
45
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?
|
|
46
|
-
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(
|
|
48
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
49
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
43
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ce()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!Ce()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!Ce()&&M.stdout.isTTY)M.stdout.write(`
|
|
44
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!Ce()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":H.blue("◐"),tag:r,message:`${H.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
45
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":H.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ce())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new $o(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Ce())throw Error("createReadStream is not supported in browser environments");if(!Hs(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return om(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Kt.isBuffer(e)?e:Kt.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=eC("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Kt.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ce()}isServerMode(){return!Ce()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
46
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:H.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(u),showTimestamp:!1}))}else if(!Ce())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Ce())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${H.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();M.stdin.removeListener("data",r);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){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 u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${H.blue("◐")} `;console.error(`${l}${a} ${H.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
48
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=H.green("━".repeat(n)),o=H.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?H.green("✓"):H.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${H.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=M.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,M.stdout.write(e.lastRenderedLine),t)M.stdout.write(`
|
|
49
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ce()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ce()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await zs(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=dn(this.config.logDirectory,n);if(e.before)try{if((await hn(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Gs(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function $x(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class Ql{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Vl.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Ys.env[a]||(l?Ys.env[l]:void 0);if(u!==void 0){if(n.verbose){let f=Ys.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(u,typeof s,a,n.customParsers,n.configName)}catch(f){if(f instanceof Zl)throw f;throw pn.envVar(a,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw pn.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Ys.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
50
50
|
|
|
51
|
-
`;for(let
|
|
52
|
-
`,r+=` Type: ${
|
|
53
|
-
`,r+=` Description: ${
|
|
54
|
-
`,r+=` Example: ${
|
|
51
|
+
`;for(let n of e)r+=`${n.key}
|
|
52
|
+
`,r+=` Type: ${n.type}
|
|
53
|
+
`,r+=` Description: ${n.description}
|
|
54
|
+
`,r+=` Example: ${n.example}
|
|
55
55
|
|
|
56
56
|
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
57
57
|
|
|
58
58
|
`;r+=`| Variable | Type | Description | Example |
|
|
59
59
|
`,r+=`|----------|------|-------------|----------|
|
|
60
|
-
`;for(let
|
|
61
|
-
`;return r}}function I$(e,t,r={}){return Pd(e,t,r,new WeakMap)}function Pd(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Rd(e,t,n,i);if(!ft(t)||!ft(e))return t;return W$(e,t,r,i)}function Rd(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return _$(e,t);case"smart":return j$(e,t,i);default:return t}return t}function _$(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Kc(n,i)))r.push(i);return r}function j$(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(ft(t[0])&&ft(e[0]))return U$(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function U$(e,t,r){let i=[...t];for(let n of e){if(!ft(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in n){if(i.find((l)=>ft(l)&&(c in l)&&l[c]===n[c])){o=!0;break}}if(!o)i.push(n)}return i}function W$(e,t,r,i){let n=t;if(ft(n)&&i.has(n))return i.get(n);let s={...e};if(ft(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(ft(c)&&ft(a))s[o]=Pd(a,c,r,i);else if(Array.isArray(c)||Array.isArray(a))s[o]=Rd(a,c,r.arrayMergeMode||"smart",i);else s[o]=c}return s}function Ad(e,t,r="replace"){return I$(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Kc(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Kc(e[r],t[r]))return!1;return!0}if(ft(e)&&ft(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Kc(e[n],t[n]))return!1}return!0}return!1}function ft(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class kd{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=ws.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!fs(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new ks(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new ks(e,Error("Configuration must export a valid object"),"unknown");let p={config:Ad(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)ws.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?oi.configLoad(e,l):oi.configLoad(e,Error(String(l)))}};if(o)return Hc.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(kc(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return M$(async()=>fs(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!fs(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let c=kc(e,`${s}${o}`);if(await this.checkFileAccess(c))i.push(c)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=kc(e,o);if(await this.checkFileAccess(c))i.push(c)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!fs(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Od{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await Hc.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!K$(t))throw new Os(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new Os(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(i.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(i.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(i.push(...c),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:H$},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function V$(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Nd{fileLoader=new kd;envProcessor=new Zc;validator=new Od;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||s)await this.validateConfiguration(c.config,n,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(i?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(a);if(i.slowThreshold&&a.duration>i.slowThreshold)kt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw kt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Ns.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,o)),this.finalizeResult(d,h,a,i,u);let y=await this.loadHomeConfiguration(i,n,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,a,i,u);let g=await this.loadPackageJsonConfiguration(i,n,f,c,l,u,a);if(g)return h.push(lt(f,"package.json")),this.finalizeResult(g,h,a,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,o)),t)throw oi.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,c,a,u),warnings:[`No configuration file found for "${i}"${V$(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,c,a){let l=c?hs(e,n,o):n,u=this.getLocalDirectories(r,i);for(let f of u){if(o)kt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)kt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?hs(e,r,n):r,c=[lt(Gr(),".config",e),lt(Gr(),".config"),Gr()];for(let a of c){if(n)kt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(u){if(n)kt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let c=o?hs(e,i,s):i;try{let a=lt(r,"package.json");if(!Iv(a))return null;let l={};try{l=JSON.parse(_v(a,"utf8"))}catch(h){if(s)kt.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=l[e],f=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){u=l[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)kt.success(`Configuration loaded from package.json: ${f}`);return{config:Ad(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)kt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:hs(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw oi.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ws.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);ws.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,lt(e,"config"),lt(e,".config"),t?lt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(lt(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[lt(Gr(),".config",e),lt(Gr(),".config"),Gr()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}async function Dd(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await Oc.loadConfig(e);else i=await Oc.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)kt.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Oc.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function hs(e,t,r=!1){let i=new Zc,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((g)=>g.toUpperCase()).join("")}`,`${n}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Ns.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}var ws,Hc,Sb,Eb=(e)=>e,Pb=(e,t)=>{for(var r in t)Sb(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Tb.bind(t,r)})},Rb=(e,t)=>()=>(e&&(t=e(e=0)),t),td,ud,si,en,fd,t$,r$,_h,ms,Bc,Ae,Z,i$,jh,n$,Uh,s$,o$,Ec,a$,Wh,Kh,Tc,c$,l$,u$,f$,gs,hd,h$,ke,d$,m$,Hh,ps,Lc,pe,_,g$,Vh,p$,Yh,y$,w$,Pc,v$,zh,Gh,b$,Rc,$$,x$,C$,S$,E$,ys,dd,T$,P$="0.15.6",et,Ps,Qi,Mc,Ic,Rs,_c,jc,Zi,Uc,Wc,lr,md,gd,vt,_t,pd,yd,R$,k$,wd,As,V1,Se,K,Y1,N$,z1,D$,G1,q1,qh,J1,F$,B$,X1,Jh,Q1,Z1,ek,tk,rk,Ac,L$,ik,bt,bd,ks,$d,xd,Qc,Cd,Sd,Os,Ed,Td,oi,H$,kt,Oc,ck,lk;var Fd=Q(()=>{ws=new Xh,Hc=new Qh,Sb=Object.defineProperty;td={};Pb(td,{withErrorRecovery:()=>nd,tryLoadConfig:()=>Xb,loadConfigWithResult:()=>qb,loadConfig:()=>ld,isRetryableError:()=>Kb,isConfigNotFoundError:()=>Wb,isBunfigError:()=>sd,globalPerformanceMonitor:()=>en,globalCache:()=>si,getEnvOrDefault:()=>Hb,generateConfigTypes:()=>Qb,defaultGeneratedDir:()=>yd,defaultConfigDir:()=>pd,deepMergeWithArrayStrategy:()=>qc,deepMerge:()=>od,createLibraryConfig:()=>Zb,config:()=>Jb,bunfigPlugin:()=>e$,applyEnvVarsToConfig:()=>Ji,TypeGenerationError:()=>jc,SchemaValidationError:()=>Zi,PluginError:()=>Wc,PerformanceMonitor:()=>Yc,FileSystemError:()=>_c,ErrorFactory:()=>lr,EnvVarError:()=>Rs,EnvProcessor:()=>Ds,ConfigValidator:()=>Jc,ConfigValidationError:()=>Mc,ConfigNotFoundError:()=>Ps,ConfigMergeError:()=>Ic,ConfigLoader:()=>Xc,ConfigLoadError:()=>Qi,ConfigFileLoader:()=>Fs,ConfigCache:()=>Vc,CacheUtils:()=>fd,BunfigError:()=>et,BrowserConfigError:()=>Uc,ArrayMergeStrategies:()=>md});R$=Rb(async()=>{ud=import.meta.require,si=new Vc,en=new Yc,fd={createKey:Ab,isEquivalent:kb,estimateMemoryUsage:Ob},t$=$s(Dc.cwd(),"config"),r$=$s(Dc.cwd(),"src/generated"),_h=bs.env.CLARITY_LOG_DIR||Vv(Fb(),"logs"),ms={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_h,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Bc=await Bb(),Ae={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},Z=Ae,i$=Ae.red,jh=Ae.green,n$=Ae.yellow,Uh=Ae.blue,s$=Ae.magenta,o$=Ae.cyan,Ec=Ae.white,a$=Ae.gray,Wh=Ae.bgRed,Kh=Ae.bgYellow,Tc=Ae.bold,c$=Ae.dim,l$=Ae.italic,u$=Ae.underline,f$=Ae.reset,gs={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},hd={debug:"\uD83D\uDD0D",info:Uh("ℹ"),success:jh("✓"),warning:Kh(Ec(Tc(" WARN "))),error:Wh(Ec(Tc(" ERROR ")))},h$=new Ss("stacks"),ke=new Ss("bunfig",{showTags:!0}),d$=Ke(Xi.cwd(),"config"),m$=Ke(Xi.cwd(),"src/generated"),Hh=vs.env.CLARITY_LOG_DIR||Kv(_b(),"logs"),ps={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Hh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lc=await jb(),pe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},_=pe,g$=pe.red,Vh=pe.green,p$=pe.yellow,Yh=pe.blue,y$=pe.magenta,w$=pe.cyan,Pc=pe.white,v$=pe.gray,zh=pe.bgRed,Gh=pe.bgYellow,b$=pe.bgGray,Rc=pe.bold,$$=pe.dim,x$=pe.italic,C$=pe.underline,S$=pe.strikethrough,E$=pe.reset,ys={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},dd={debug:"\uD83D\uDD0D",info:Yh("ℹ"),success:Vh("✓"),warning:Gh(Pc(Rc(" WARN "))),error:zh(Pc(Rc(" ERROR ")))},T$=new Ts("stacks"),et=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,i])=>`${r}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Ps=class extends et{code="CONFIG_NOT_FOUND";constructor(t,r,i){let n=i?` or alias "${i}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:i,searchPaths:r,searchPathCount:r.length})}},Qi=class extends et{code="CONFIG_LOAD_ERROR";constructor(t,r,i){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Mc=class extends et{code="CONFIG_VALIDATION_ERROR";constructor(t,r,i){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:i,validationErrors:r,errorCount:r.length})}},Ic=class extends et{code="CONFIG_MERGE_ERROR";constructor(t,r,i,n){super(`Failed to merge configuration from "${t}" with "${r}": ${i.message}`,{sourcePath:t,targetPath:r,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Rs=class extends et{code="ENV_VAR_ERROR";constructor(t,r,i,n){super(`Failed to parse environment variable "${t}" with value "${r}" as ${i}`,{envKey:t,envValue:r,expectedType:i,configName:n})}},_c=class extends et{code="FILE_SYSTEM_ERROR";constructor(t,r,i){super(`File system ${t} failed for "${r}": ${i.message}`,{operation:t,path:r,originalError:i.name,originalMessage:i.message});this.cause=i}},jc=class extends et{code="TYPE_GENERATION_ERROR";constructor(t,r,i){super(`Failed to generate types from "${t}" to "${r}": ${i.message}`,{configDir:t,outputPath:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Zi=class extends et{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:t,configName:i,validationErrors:r,errorCount:r.length})}},Uc=class extends et{code="BROWSER_CONFIG_ERROR";constructor(t,r,i,n){super(`Failed to fetch configuration from "${t}": ${r} ${i}`,{endpoint:t,status:r,statusText:i,configName:n})}},Wc=class extends et{code="PLUGIN_ERROR";constructor(t,r,i){super(`Plugin "${t}" failed during ${r}: ${i.message}`,{pluginName:t,operation:r,originalError:i.name,originalMessage:i.message});this.cause=i}},lr={configNotFound(e,t,r){return new Ps(e,t,r)},configLoad(e,t,r){return new Qi(e,t,r)},configValidation(e,t,r){return new Mc(e,t,r)},configMerge(e,t,r,i){return new Ic(e,t,r,i)},envVar(e,t,r,i){return new Rs(e,t,r,i)},fileSystem(e,t,r){return new _c(e,t,r)},typeGeneration(e,t,r){return new jc(e,t,r)},schemaValidation(e,t,r){return new Zi(e,t,r)},browserConfig(e,t,r,i){return new Uc(e,t,r,i)},plugin(e,t,r){return new Wc(e,t,r)}},md={replace:"replace",concat:"concat",smart:"smart"},gd=/^https?:\/\//,vt=new Ts("bunfig",{showTags:!0}),_t=new Xc,pd=He(Ar.cwd(),"config"),yd=He(Ar.cwd(),"src/generated")});k$=xs.env.CLARITY_LOG_DIR||db(A$(),"logs"),wd={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:k$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},As={...wd},V1=(async()=>{try{let{loadConfig:e}=await R$().then(()=>td),t=await e({name:"clarity",alias:"logging",defaultConfig:wd,cwd:xs.cwd()});if(t)Object.assign(As,t)}catch{}return As})();Se={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},K=Se,Y1=Se.red,N$=Se.green,z1=Se.yellow,D$=Se.blue,G1=Se.magenta,q1=Se.cyan,qh=Se.white,J1=Se.gray,F$=Se.bgRed,B$=Se.bgYellow,X1=Se.bgGray,Jh=Se.bold,Q1=Se.dim,Z1=Se.italic,ek=Se.underline,tk=Se.strikethrough,rk=Se.reset,Ac={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},L$={debug:"\uD83D\uDD0D",info:D$("ℹ"),success:N$("✓"),warning:B$(qh(Jh(" WARN "))),error:F$(qh(Jh(" ERROR ")))};ik=new Bs("stacks");bt=class bt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};bd=class bd extends bt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};ks=class ks extends bt{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};$d=class $d extends bt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};xd=class xd extends bt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}};Qc=class Qc extends bt{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}};Cd=class Cd extends bt{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Sd=class Sd extends bt{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Os=class Os extends bt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Ed=class Ed extends bt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}};Td=class Td extends bt{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};oi={configNotFound(e,t,r){return new bd(e,t,r)},configLoad(e,t,r){return new ks(e,t,r)},configValidation(e,t,r){return new $d(e,t,r)},configMerge(e,t,r,i){return new xd(e,t,r,i)},envVar(e,t,r,i){return new Qc(e,t,r,i)},fileSystem(e,t,r){return new Cd(e,t,r)},typeGeneration(e,t,r){return new Sd(e,t,r)},schemaValidation(e,t,r){return new Os(e,t,r)},browserConfig(e,t,r,i){return new Ed(e,t,r,i)},plugin(e,t,r){return new Td(e,t,r)}};H$=/^https?:\/\//;kt=new Bs("bunfig",{showTags:!0});Oc=new Nd;ck=lt(Ns.cwd(),"config"),lk=lt(Ns.cwd(),"src/generated")});import{homedir as el}from"node:os";import{join as tl,resolve as Y$}from"node:path";async function Ld(){if(!rl)rl=await Dd({name:"rpx",cwd:Y$(__dirname,".."),defaultConfig:Bd});return rl}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Bd,rl=null,jt;var Ls=Q(()=>{Fd();Bd={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:tl(el(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:tl(el(),".stacks","ssl","stacks.localhost.crt"),keyPath:tl(el(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};jt=Bd});function ai(e){return e.startsWith("*.")}function Or(e,t){if(!ai(t))return!1;let r=t.slice(1);return e.length>r.length&&e.endsWith(r)}function Md(e,t){let r=e.get(t);if(r!==void 0)return r;let i,n=-1;for(let[s,o]of e){if(!ai(s))continue;if(Or(t,s)){let c=s.length-1;if(c>n)n=c,i=o}}return i}import{existsSync as z$,readdirSync as G$,readFileSync as q$,statSync as J$}from"node:fs";import{homedir as _d}from"node:os";import{isAbsolute as X$,join as ci}from"node:path";function nl(e,t){if(e==="~")return t;if(e.startsWith("~/"))return ci(t,e.slice(2));return e}function Z$(e){let t=e.indexOf(":");return(t===-1?e:e.slice(0,t)).toLowerCase()}function Ms(e){return e.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function ex(e,t){for(let r of t){let i=`.${r}`;if(e.endsWith(i)){let n=e.slice(0,-i.length);if(n.length>0&&!n.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(n))return n}}return null}function tx(e,t){let r=t.readText(ci(e,"rpx.site.json"));if(r)try{let n=JSON.parse(r);if(n&&typeof n==="object")return n}catch{}let i=t.readText(ci(e,"package.json"));if(i)try{let n=JSON.parse(i);if(n.rpx&&typeof n.rpx==="object")return n.rpx}catch{}return null}function rx(e){let t=e.selfRegisters??!1;return{command:e.command,env:e.env,urlEnv:e.urlEnv,selfRegisters:t,routes:e.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function ix(e,t){let r=tx(e,t);if(r?.command)return rx(r);let i=t.fileExists(ci(e,"buddy")),n=t.readText(ci(e,"package.json")),s=null;if(n)try{s=JSON.parse(n)}catch{s=null}let o={...s?.dependencies??{},...s?.devDependencies??{}};if(i||Object.keys(o).some((a)=>a==="stacks"||a.startsWith("@stacksjs/")))return{command:i?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(s?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function sl(e,t={}){let r={dirExists:t.dirExists??il.dirExists,fileExists:t.fileExists??il.fileExists,readText:t.readText??il.readText},i=t.detect??ix,n=t.homeDir??_d(),s=e.tlds??Ud,o=(e.roots??jd).map((h)=>nl(h,n)),c=e.idleTimeoutMs??Q$,a=new Map;for(let h of e.sites??[])a.set(h.to,h);let l=(h)=>h.idleTimeoutMs??c;function u(h){let d=Md(a,h);if(!d)return null;let y=X$(d.dir)?d.dir:nl(d.dir,n),g=d.selfRegisters??!1,p=d.routes??[];if(!g&&p.length===0)p=i(y,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let w=Id({...d.env??{}},void 0,h);return{host:h,id:Ms(h),dir:y,command:d.command,env:w,routes:p,selfRegisters:g,idleTimeoutMs:l(d),source:"config"}}function f(h){let d=ex(h,s);if(!d)return null;for(let y of o){let g=ci(y,d);if(!r.dirExists(g))continue;let p=i(g,r);if(!p)continue;let w=p.selfRegisters??!1;return{host:h,id:Ms(h),dir:g,command:p.command,env:Id({...p.env??{}},p.urlEnv,h),routes:w?[]:p.routes??[],selfRegisters:w,idleTimeoutMs:c,source:"discovered"}}return null}return{resolve(h){let d=Z$(h);if(!d)return null;return u(d)??f(d)}}}function nx(e){try{return G$(e,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function Wd(e,t={}){let r=t.homeDir??_d(),i=e.tlds??Ud,n=(e.roots??jd).map((f)=>nl(f,r)),s=t.readdir??nx,o=sl(e,t),c=[],a=new Set,l=(f)=>{if(f&&!a.has(f.host))a.add(f.host),c.push(f)};for(let f of e.sites??[])if(!f.to.includes("*"))l(o.resolve(f.to));let u=i[0]??"localhost";for(let f of n)for(let h of s(f))l(o.resolve(`${h}.${u}`));return c}function Id(e,t,r){if(!t)return e;let i=`https://${r}`;for(let n of t)if(e[n]===void 0)e[n]=i;return e}var jd,Ud,Q$=1800000,il;var ol=Q(()=>{jd=["~/Code"],Ud=["localhost","test"],il={dirExists:(e)=>{try{return J$(e).isDirectory()}catch{return!1}},fileExists:(e)=>{try{return z$(e)}catch{return!1}},readText:(e)=>{try{return q$(e,"utf8")}catch{return null}}}});var x;var Nr=Q(()=>{x={info:(...e)=>console.log("[info]",...e),success:(...e)=>console.log("[success]",...e),warn:(...e)=>console.warn("[warn]",...e),error:(...e)=>console.error("[error]",...e),debug:(...e)=>console.debug("[debug]",...e),log:(...e)=>console.log(...e),start:(...e)=>console.log("[start]",...e),box:(...e)=>console.log("[box]",...e)}});import{createRequire as sx}from"node:module";import{Resolver as al}from"node:dns/promises";import{createHash as ax,sign as cx}from"node:crypto";import{createHash as lx}from"node:crypto";import{sign as ux}from"node:crypto";import{generateKeyPairSync as Gm,X509Certificate as vx}from"node:crypto";import cl from"node:os";import ll from"node:path";import{existsSync as Hd,statSync as Vd}from"fs";import{existsSync as $x,mkdirSync as Nk,readdirSync as Dk,readFileSync as xx,writeFileSync as Fk}from"fs";import{homedir as li}from"os";import{dirname as Mk,resolve as dt}from"path";import Eo from"process";import{existsSync as Yd,statSync as zd}from"fs";import{existsSync as Dl,mkdirSync as Cx,readdirSync as Sx,writeFileSync as Ex}from"fs";import{homedir as ui}from"os";import{dirname as Gd,resolve as Ye}from"path";import Fr from"process";import{join as Tx,relative as Px,resolve as qd}from"path";import ao from"process";import{existsSync as qm,mkdirSync as zk,readdirSync as Gk,writeFileSync as qk}from"fs";import{homedir as ul}from"os";import{dirname as Qk,resolve as Ve}from"path";import on from"process";import{join as Rx,relative as Ax,resolve as Jd}from"path";import co from"process";import{existsSync as Jm,mkdirSync as iO,readdirSync as nO,writeFileSync as sO}from"fs";import{dirname as aO,resolve as lo}from"path";import Fl from"process";import{Buffer as ur}from"buffer";import{createCipheriv as kx,createDecipheriv as Ox,randomBytes as fl}from"crypto";import{closeSync as hl,createReadStream as Xd,createWriteStream as Nx,existsSync as dl,fsyncSync as Qd,openSync as Zd,writeFileSync as Dx}from"fs";import{access as Fx,constants as em,mkdir as Bx,readdir as Is,rename as tm,stat as fi,unlink as _s,writeFile as ml}from"fs/promises";import{join as hi}from"path";import Oe from"process";import{pipeline as Lx}from"stream/promises";import{createGzip as rm}from"zlib";import di from"process";import Ht from"process";import{Buffer as Ut}from"buffer";import{createCipheriv as Mx,createDecipheriv as Ix,randomBytes as gl}from"crypto";import{closeSync as pl,createReadStream as im,createWriteStream as _x,existsSync as js,fsyncSync as nm,openSync as sm,writeFileSync as jx}from"fs";import{access as Ux,constants as om,mkdir as Wx,readdir as Us,rename as am,stat as mi,unlink as Ws,writeFile as yl}from"fs/promises";import{isAbsolute as Kx,join as gi,resolve as Hx}from"path";import G from"process";import{pipeline as Vx}from"stream/promises";import{createGzip as cm}from"zlib";import pi from"process";import Vt from"process";import Ks from"process";import{existsSync as Hs}from"fs";import{resolve as wl}from"path";import{existsSync as Yx}from"fs";import{existsSync as zx,readdirSync as Gx}from"fs";import{extname as vl,resolve as lm}from"path";import qx from"process";import{join as Jx,relative as Xx,resolve as um}from"path";import uo from"process";import{Buffer as Wt}from"buffer";import{createCipheriv as Qx,createDecipheriv as Zx,randomBytes as bl}from"crypto";import{closeSync as $l,createReadStream as fm,createWriteStream as eC,existsSync as Vs,fsyncSync as hm,openSync as dm,writeFileSync as tC}from"fs";import{access as rC,constants as mm,mkdir as iC,readdir as Ys,rename as gm,stat as yi,unlink as zs,writeFile as xl}from"fs/promises";import{isAbsolute as nC,join as wi,resolve as sC}from"path";import q from"process";import{pipeline as oC}from"stream/promises";import{createGzip as pm}from"zlib";import vi from"process";import Yt from"process";import Gs from"process";import{existsSync as qs}from"fs";import{resolve as Cl}from"path";import{existsSync as aC}from"fs";import{exec as AS}from"node:child_process";import Vl from"node:fs";import kS from"node:os";import $t from"node:path";import Ng from"node:process";import{promisify as OS}from"node:util";import Ci from"node:crypto";import zt from"node:fs";import Gl from"node:path";import e0 from"node:crypto";import{execSync as i0}from"node:child_process";import Co from"node:os";async function Qs(e,t={},r=30000){try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(i){if(i&&typeof i==="object"&&i.name==="TimeoutError"){let n=Error(`ACME HTTP request to ${e} timed out after ${r}ms`);throw n.name="AcmeRequestTimeoutError",n}throw i}}async function Bm(e,t,r={}){let i=r.timeoutMs??120000,n=r.intervalMs??3000,s=e.split(".").slice(-2).join("."),o;try{let l=new al,u=await l.resolveNs(s),f=(await Promise.all(u.map((h)=>l.resolve4(h).catch(()=>[])))).flat();if(f.length>0)o=new al,o.setServers(f)}catch{}let c=Date.now()+i,a=o??new al;for(;;){try{if((await a.resolveTxt(e)).some((l)=>l.join("")===t))return!0}catch{}if(Date.now()>=c)return!1;await new Promise((l)=>setTimeout(l,n))}}class sn{tokens=new Map;add(e,t){this.tokens.set(e,t)}get(e){return this.tokens.get(e)}remove(e){this.tokens.delete(e)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(e){let t=e.indexOf(sn.PATH_PREFIX);if(t===-1)return;let r=e.slice(t+sn.PATH_PREFIX.length);return this.get(r)}}function Zs(e){return(typeof e==="string"?Buffer.from(e,"utf8"):Buffer.from(e)).toString("base64url")}function Al(e){return Buffer.from(e,"base64url")}function Lm(e){let t=e.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function Mm(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}","y":"${e.y}"}`;return ax("sha256").update(t).digest("base64url")}function Im(e){let{protectedHeader:t,payload:r,privateKey:i}=e,n=Zs(JSON.stringify(t)),s=r===""?"":Zs(JSON.stringify(r)),o=`${n}.${s}`,c=cx("sha256",Buffer.from(o),{key:i,dsaEncoding:"ieee-p1363"});return{protected:n,payload:s,signature:Zs(c)}}class oo{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(e){this.directoryUrl=e.directoryUrl,this.accountKey=e.accountKey,this.jwk=Lm(e.accountPublicKey),this.thumbprint=Mm(this.jwk),this.requestTimeoutMs=e.requestTimeoutMs??Fm}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let e=await Qs(this.directoryUrl,{},this.requestTimeoutMs);if(!e.ok)throw Error(`Failed to fetch ACME directory: HTTP ${e.status}`);return this.directoryCache=await e.json(),this.directoryCache}async newNonce(){let e=await this.directory(),t=(await Qs(e.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let e=this.nonce;return this.nonce=void 0,e}return this.newNonce()}async signedPost(e){let{url:t,payload:r,useJwk:i}=e,n={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(i)n.jwk=this.jwk;else n.kid=this.requireKid();let s=Im({protectedHeader:n,payload:r,privateKey:this.accountKey}),o=await Qs(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(s)},this.requestTimeoutMs),c=o.headers.get("replay-nonce");if(c)this.nonce=c;let a=o.headers.get("content-type")??"",l;if(a.includes("application/pem-certificate-chain")||a.startsWith("text/"))l=await o.text();else{let u=await o.text();l=u?JSON.parse(u):{}}if(o.status>=400){let u=l??{};throw new so(`ACME request to ${t} failed (HTTP ${o.status}): ${u.type??""} ${u.detail??""}`.trim(),u,o.status)}return{status:o.status,headers:o.headers,body:l,location:o.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(e={}){let t=await this.directory(),r={termsOfServiceAgreed:!0};if(e.email)r.contact=[`mailto:${e.email}`];let i=await this.signedPost({url:t.newAccount,payload:r,useJwk:!0});if(!i.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=i.location,this.accountKid}async newOrder(e){let t=await this.directory(),r={identifiers:e.map((n)=>({type:"dns",value:n}))},i=await this.signedPost({url:t.newOrder,payload:r});if(!i.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:i.body,orderUrl:i.location}}async getAuthorization(e){return(await this.signedPost({url:e,payload:""})).body}keyAuthorization(e){return`${e}.${this.thumbprint}`}dns01TxtValue(e){return lx("sha256").update(this.keyAuthorization(e)).digest("base64url")}async notifyChallengeReady(e){await this.signedPost({url:e,payload:{}})}async pollAuthorization(e,t={}){let r=t.timeoutMs??60000,i=t.intervalMs??2000,n=Date.now()+r;while(Date.now()<n){let s=await this.getAuthorization(e);if(s.status==="valid")return;if(s.status==="invalid"){let o=s.challenges.find((c)=>c.status==="invalid");throw new so(`Authorization for ${s.identifier.value} became invalid: ${o?.error?.detail??"unknown reason"}`,o?.error??{},0)}await Kd(i),i=Math.min(i*1.5,1e4)}throw Error(`Timed out waiting for authorization ${e} to become valid`)}async finalizeOrder(e,t){return(await this.signedPost({url:e,payload:{csr:t}})).body}async getOrder(e){return(await this.signedPost({url:e,payload:""})).body}async pollOrder(e,t={}){let r=t.timeoutMs??60000,i=t.intervalMs??2000,n=Date.now()+r;while(Date.now()<n){let s=await this.getOrder(e);if(s.status==="valid"){if(!s.certificate)throw Error("ACME order is valid but has no certificate URL");return s.certificate}if(s.status==="invalid")throw Error(`ACME order ${e} became invalid`);await Kd(i),i=Math.min(i*1.5,1e4)}throw Error(`Timed out waiting for order ${e} to become valid`)}async downloadCertificate(e){let t=await this.signedPost({url:e,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(e,t){let r=e.challenges.find((i)=>i.type===t);if(!r)throw Error(`No ${t} challenge available for ${e.identifier.value}`);return r}}function Um(e){let t=e.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${e.trim()}
|
|
62
|
-
`,chainPem:""};let
|
|
63
|
-
`,
|
|
64
|
-
`);return{certPem:
|
|
65
|
-
`:""}}function Wm(e){return`_acme-challenge.${e.startsWith("*.")?e.slice(2):e}`}function Kd(e){return new Promise((t)=>setTimeout(t,e))}function fx(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function dr(e,t){return Buffer.concat([Buffer.from([e]),fx(t.length),t])}function Km(e){let t;if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=[],i=e;while(i>0)r.unshift(i&255),i>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=e.length===0?Buffer.from([0]):e,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return dr(2,t)}function Dr(e){let t=e.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${e}`);let r=[40*t[0]+t[1]];for(let i=2;i<t.length;i++){let n=t[i],s=[n&127];n=Math.floor(n/128);while(n>0)s.unshift(n&127|128),n=Math.floor(n/128);r.push(...s)}return dr(6,Buffer.from(r))}function ht(...e){return dr(48,Buffer.concat(e))}function kl(...e){return dr(49,Buffer.concat(e))}function Ol(e){return dr(3,Buffer.concat([Buffer.from([0]),e]))}function Hm(e){return dr(4,e)}function Vm(e){return dr(12,Buffer.from(e,"utf8"))}function Nl(e,t,r){let i=128|(r?32:0)|e;return dr(i,t)}function wx(e){let t=e.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=Al(t.x),i=Al(t.y);if(r.length!==32||i.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${i.length}`);return Buffer.concat([Buffer.from([4]),r,i])}function Ym(e){let{domains:t,publicKey:r,privateKey:i}=e;if(t.length===0)throw Error("At least one domain is required to build a CSR");let n=ht(kl(ht(Dr(gx),Vm(t[0])))),s=ht(ht(Dr(hx),Dr(dx)),Ol(wx(r))),o=t.map((g)=>Nl(2,Buffer.from(g,"ascii"),!1)),c=ht(...o),a=ht(Dr(yx),Hm(c)),l=ht(a),u=ht(Dr(px),kl(l)),f=Nl(0,u,!0),h=ht(Km(0),n,s,f),d=ux("sha256",h,i),y=ht(Dr(mx));return ht(h,y,Ol(d))}function zm(e){return Ym(e).toString("base64url")}function bx(e){if(e){let{createPrivateKey:n,createPublicKey:s}=ox("node:crypto"),o=n(e),c=s(o.export({format:"pem",type:"pkcs8"}));return{privateKey:o,publicKey:c,pem:e}}let{privateKey:t,publicKey:r}=Gm("ec",{namedCurve:"P-256"}),i=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:i}}async function ql(e){let{domains:t,method:r}=e;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!e.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((f)=>f.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let i=e.directoryUrl??(e.staging===!1?jm:_m),n=bx(e.accountKeyPem),s=new oo({directoryUrl:i,accountKey:n.privateKey,accountPublicKey:n.publicKey,requestTimeoutMs:e.requestTimeoutMs});await s.newAccount({email:e.email});let{order:o,orderUrl:c}=await s.newOrder(t),a=e.http01Store??So,l=[],u=[];try{for(let v of o.authorizations){let T=await s.getAuthorization(v);if(T.status==="valid")continue;let S=oo.selectChallenge(T,r);if(r==="dns-01"){let D=Wm(T.identifier.value),W=s.dns01TxtValue(S.token);await e.dnsProvider.setTxt(D,W),l.push({name:D,value:W}),await Bm(D,W,{timeoutMs:e.dnsPropagationTimeoutMs??120000})}else a.add(S.token,s.keyAuthorization(S.token)),u.push(S.token);await s.notifyChallengeReady(S.url),await s.pollAuthorization(v,{timeoutMs:e.timeoutMs})}let{privateKey:f,publicKey:h}=Gm("ec",{namedCurve:"P-256"}),d=zm({domains:t,publicKey:h,privateKey:f});await s.finalizeOrder(o.finalize,d);let y=await s.pollOrder(c,{timeoutMs:e.timeoutMs}),g=await s.downloadCertificate(y),{certPem:p,chainPem:w}=Um(g),b=w?`${p}${w}`:p,P=f.export({format:"pem",type:"pkcs8"}).toString(),R=new Date(new vx(p).validTo);return{certPem:p,keyPem:P,chainPem:w,fullChainPem:b,accountKeyPem:n.pem,notAfter:R}}finally{for(let{name:f,value:h}of l)await e.dnsProvider?.removeTxt(f,h).catch(()=>{});for(let f of u)a.remove(f)}}class Xm{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Hd(e))return!0;return Vd(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=Hd(r)?Vd(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Qm{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function uC(e,t){this[e]=lC.bind(null,t)}class Xl{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Yd(e))return!0;return zd(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=Yd(r)?zd(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Ql{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function dC(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function mC(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function gC(e){return e.getStats().size*2}function Zl(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ne(t[0])&&"id"in t[0]&&t[0].id===3&&ne(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ne(t)&&ne(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(ne(e)&&"arr"in e&&Array.isArray(e.arr)&&ne(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ne(t[0])&&ne(e[0])){let i=[...t];for(let n of e)if(ne(n)&&"name"in n){if(!i.find((s)=>ne(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(ne(n)&&"path"in n){if(!i.find((s)=>ne(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>ho(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!ne(t)||!ne(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(ne(n)&&ne(r[i]))r[i]=Zl(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&ne(n[0])&&ne(r[i][0])){let s=[...n];for(let o of r[i])if(ne(o)&&"name"in o){if(!s.find((c)=>ne(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(ne(o)&&"path"in o){if(!s.find((c)=>ne(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((c)=>ho(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function ho(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ho(e[r],t[r]))return!1;return!0}if(ne(e)&&ne(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ho(e[n],t[n]))return!1}return!0}return!1}function ne(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function pC(e,t){if(!Jm(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Zl(t,i)}catch{return null}}catch{return null}}async function yC({name:e="",cwd:t,defaultConfig:r}){let i=t||Fl.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of n){let a=lo(i,`${o}${c}`),l=await pC(a,r);if(l!==null)return l}try{let o=lo(i,"package.json");if(Jm(o)){let c=(await import(o))[e];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Zl(r,c)}catch{}}}catch{}return r}function wC(e,t={}){let r=co.cwd();while(r.includes("storage"))r=Jd(r,"..");let i=Jd(r,e||"");if(t?.relative)return Ax(co.cwd(),i);return i}async function vC(){try{let e=await yC({name:"clarity",defaultConfig:to,cwd:co.cwd(),endpoint:"",headers:{}});return{...to,...e}}catch{return to}}function ce(){if(Ht.env.NODE_ENV==="test"||Ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bC(){if(Ht.env.NODE_ENV==="test"||Ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ht<"u"){let e=Ht.type;if(e==="renderer"||e==="worker")return!1;return!!(Ht.versions&&(Ht.versions.node||Ht.versions.bun))}return!1}class eg{async format(e){let t=await bC(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:di.pid,hostname:t(),environment:di.env.NODE_ENV||"development",platform:di.platform,version:di.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:di.env.NODE_ENV||di.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class mo{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(e,t={}){this.name=e,this.config={...Ll},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new eg,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Oe.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ro,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ro};return{...ro,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ll.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await Fx(this.config.logDirectory,em.F_OK|em.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await Bx(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ur.from(e);try{if(!dl(this.currentLogFile))await ml(this.currentLogFile,"",{mode:420});if(i=Zd(this.currentLogFile,"a",420),Dx(i,c,{flag:"a"}),Qd(i),i!==void 0)hl(i),i=void 0;if((await fi(this.currentLogFile)).size===0){if(await ml(this.currentLogFile,c,{flag:"w",mode:420}),(await fi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=o*2**n;await new Promise((h)=>setTimeout(h,f)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{hl(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(n===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}n++;let a=o*2**(n-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 hi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return hi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return hi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ce())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return fl(16).toString("hex")}generateKey(){return fl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=fl(16),i=kx("aes-256-gcm",t,r),n=ur.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:ur.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=rm(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(ur.from(ur.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ce())return;let e=await fi(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Is(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await fi(r).catch(()=>null))try{if(await tm(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await _s(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ml(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await fi(r).catch(()=>null))await tm(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Is(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await _s(hi(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Xd(e),i=Nx(t),n=rm();await Lx(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),dl(this.currentLogFile))try{let e=Zd(this.currentLogFile,"r+");Qd(e),hl(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ce()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Is(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await _s(hi(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=Oe.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${ee.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!ce()){let l=ug[e],u=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:ee.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:ee.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
|
|
66
|
-
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:
|
|
60
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
61
|
+
`;return r}}function Cx(e,t,r={}){return tg(e,t,r,new WeakMap)}function tg(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return rg(e,t,i,n);if(!yt(t)||!yt(e))return t;return Tx(e,t,r,n)}function rg(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return xx(e,t);case"smart":return Sx(e,t,n);default:return t}return t}function xx(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Wl(i,n)))r.push(n);return r}function Sx(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(yt(t[0])&&yt(e[0]))return Ex(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Ex(e,t,r){let n=[...t];for(let i of e){if(!yt(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>yt(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function Tx(e,t,r,n){let i=t;if(yt(i)&&n.has(i))return n.get(i);let s={...e};if(yt(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(yt(c)&&yt(a))s[o]=tg(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=rg(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function ng(e,t,r="replace"){return Cx(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Wl(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Wl(e[r],t[r]))return!1;return!0}if(yt(e)&&yt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Wl(e[i],t[i]))return!1}return!0}return!1}function yt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ig{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=no.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Js(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new po(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new po(e,Error("Configuration must export a valid object"),"unknown");let p={config:ng(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)no.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?pn.configLoad(e,l):pn.configLoad(e,Error(String(l)))}};if(o)return Vl.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(kl(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of n){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let i=new Set;return r.filter((s)=>{if(!s||i.has(s))return!1;return i.add(s),!0})}checkFileAccess(e){return $x(async()=>Js(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Js(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=kl(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=kl(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Js(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class sg{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await Vl.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Px(t))throw new yo(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new yo(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Ax},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Rx(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class og{fileLoader=new ig;envProcessor=new Ql;validator=new sg;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)Dt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw Dt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||wo.cwd(),h=[],d=await this.loadLocalConfiguration(n,i,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(n,i,f,o)),this.finalizeResult(d,h,a,n,u);let y=await this.loadHomeConfiguration(n,i,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(y,h,a,n,u);let g=await this.loadPackageJsonConfiguration(n,i,f,c,l,u,a);if(g)return h.push(gt(f,"package.json")),this.finalizeResult(g,h,a,n,u);if(h.push(...this.getAllSearchPaths(n,i,f,o)),t)throw pn.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,u),warnings:[`No configuration file found for "${n}"${Rx(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?Xs(e,i,o):i,u=this.getLocalDirectories(r,n);for(let f of u){if(o)Dt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Dt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?Xs(e,r,i):r,c=[gt(nn(),".config",e),gt(nn(),".config"),nn()];for(let a of c){if(i)Dt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(u){if(i)Dt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?Xs(e,n,s):n;try{let a=gt(r,"package.json");if(!C$(a))return null;let l={};try{l=JSON.parse(x$(a,"utf8"))}catch(h){if(s)Dt.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=l[e],f=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){u=l[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Dt.success(`Configuration loaded from package.json: ${f}`);return{config:ng(c,u,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Dt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Xs(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw pn.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return no.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);no.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,gt(e,"config"),gt(e,".config"),t?gt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(gt(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[gt(nn(),".config",e),gt(nn(),".config"),nn()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}async function ag(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Ol.loadConfig(e);else n=await Ol.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)Dt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Ol.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function Xs(e,t,r=!1){let n=new Ql,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((g)=>g.toUpperCase()).join("")}`,`${i}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=wo.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}var no,Vl,cC,lC=(e)=>e,fC=(e,t)=>{for(var r in t)cC(e,r,{get:t[r],enumerable:!0,configurable:!0,set:uC.bind(t,r)})},hC=(e,t)=>()=>(e&&(t=e(e=0)),t),Rm,Mm,gn,$i,_m,_C,jC,dm,Qs,Ll,Ie,re,UC,mm,KC,gm,WC,VC,El,HC,pm,ym,Tl,zC,GC,qC,YC,eo,jm,JC,Me,XC,ZC,wm,to,Bl,$e,K,QC,vm,ex,bm,tx,rx,Pl,nx,$m,Cm,ix,Al,sx,ox,ax,cx,lx,ro,Um,ux,fx="0.15.6",ot,ho,vi,Il,Ml,mo,_l,jl,bi,Ul,Kl,vr,Km,Wm,Et,zt,Vm,Hm,hx,mx,zm,go,QO,ke,H,eN,px,tN,yx,rN,nN,xm,iN,wx,vx,sN,Sm,oN,aN,cN,lN,uN,Rl,bx,fN,Tt,qm,po,Ym,Jm,Zl,Xm,Zm,yo,Qm,eg,pn,Ax,Dt,Ol,pN,yN;var cg=te(()=>{no=new Em,Vl=new Tm,cC=Object.defineProperty;Rm={};fC(Rm,{withErrorRecovery:()=>Nm,tryLoadConfig:()=>LC,loadConfigWithResult:()=>DC,loadConfig:()=>Im,isRetryableError:()=>PC,isConfigNotFoundError:()=>TC,isBunfigError:()=>Dm,globalPerformanceMonitor:()=>$i,globalCache:()=>gn,getEnvOrDefault:()=>AC,generateConfigTypes:()=>BC,defaultGeneratedDir:()=>Hm,defaultConfigDir:()=>Vm,deepMergeWithArrayStrategy:()=>Yl,deepMerge:()=>Fm,createLibraryConfig:()=>IC,config:()=>FC,bunfigPlugin:()=>MC,applyEnvVarsToConfig:()=>yi,TypeGenerationError:()=>jl,SchemaValidationError:()=>bi,PluginError:()=>Kl,PerformanceMonitor:()=>zl,FileSystemError:()=>_l,ErrorFactory:()=>vr,EnvVarError:()=>mo,EnvProcessor:()=>vo,ConfigValidator:()=>Jl,ConfigValidationError:()=>Il,ConfigNotFoundError:()=>ho,ConfigMergeError:()=>Ml,ConfigLoader:()=>Xl,ConfigLoadError:()=>vi,ConfigFileLoader:()=>bo,ConfigCache:()=>Hl,CacheUtils:()=>_m,BunfigError:()=>ot,BrowserConfigError:()=>Ul,ArrayMergeStrategies:()=>Km});hx=hC(async()=>{Mm=import.meta.require,gn=new Hl,$i=new zl,_m={createKey:dC,isEquivalent:mC,estimateMemoryUsage:gC},_C=oo(Dl.cwd(),"config"),jC=oo(Dl.cwd(),"src/generated"),dm=so.env.CLARITY_LOG_DIR||R$(wC(),"logs"),Qs={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:dm,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ll=await vC(),Ie={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},re=Ie,UC=Ie.red,mm=Ie.green,KC=Ie.yellow,gm=Ie.blue,WC=Ie.magenta,VC=Ie.cyan,El=Ie.white,HC=Ie.gray,pm=Ie.bgRed,ym=Ie.bgYellow,Tl=Ie.bold,zC=Ie.dim,GC=Ie.italic,qC=Ie.underline,YC=Ie.reset,eo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jm={debug:"\uD83D\uDD0D",info:gm("ℹ"),success:mm("✓"),warning:ym(El(Tl(" WARN "))),error:pm(El(Tl(" ERROR ")))},JC=new lo("stacks"),Me=new lo("bunfig",{showTags:!0}),XC=qe(wi.cwd(),"config"),ZC=qe(wi.cwd(),"src/generated"),wm=io.env.CLARITY_LOG_DIR||P$(xC(),"logs"),to={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wm,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Bl=await SC(),$e={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},K=$e,QC=$e.red,vm=$e.green,ex=$e.yellow,bm=$e.blue,tx=$e.magenta,rx=$e.cyan,Pl=$e.white,nx=$e.gray,$m=$e.bgRed,Cm=$e.bgYellow,ix=$e.bgGray,Al=$e.bold,sx=$e.dim,ox=$e.italic,ax=$e.underline,cx=$e.strikethrough,lx=$e.reset,ro={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Um={debug:"\uD83D\uDD0D",info:bm("ℹ"),success:vm("✓"),warning:Cm(Pl(Al(" WARN "))),error:$m(Pl(Al(" ERROR ")))},ux=new fo("stacks"),ot=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},ho=class extends ot{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},vi=class extends ot{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Il=class extends ot{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Ml=class extends ot{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},mo=class extends ot{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},_l=class extends ot{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},jl=class extends ot{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},bi=class extends ot{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Ul=class extends ot{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},Kl=class extends ot{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},vr={configNotFound(e,t,r){return new ho(e,t,r)},configLoad(e,t,r){return new vi(e,t,r)},configValidation(e,t,r){return new Il(e,t,r)},configMerge(e,t,r,n){return new Ml(e,t,r,n)},envVar(e,t,r,n){return new mo(e,t,r,n)},fileSystem(e,t,r){return new _l(e,t,r)},typeGeneration(e,t,r){return new jl(e,t,r)},schemaValidation(e,t,r){return new bi(e,t,r)},browserConfig(e,t,r,n){return new Ul(e,t,r,n)},plugin(e,t,r){return new Kl(e,t,r)}},Km={replace:"replace",concat:"concat",smart:"smart"},Wm=/^https?:\/\//,Et=new fo("bunfig",{showTags:!0}),zt=new Xl,Vm=Ye(_r.cwd(),"config"),Hm=Ye(_r.cwd(),"src/generated")});mx=ao.env.CLARITY_LOG_DIR||X$(dx(),"logs"),zm={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:mx,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},go={...zm},QO=(async()=>{try{let{loadConfig:e}=await hx().then(()=>Rm),t=await e({name:"clarity",alias:"logging",defaultConfig:zm,cwd:ao.cwd()});if(t)Object.assign(go,t)}catch{}return go})();ke={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},H=ke,eN=ke.red,px=ke.green,tN=ke.yellow,yx=ke.blue,rN=ke.magenta,nN=ke.cyan,xm=ke.white,iN=ke.gray,wx=ke.bgRed,vx=ke.bgYellow,sN=ke.bgGray,Sm=ke.bold,oN=ke.dim,aN=ke.italic,cN=ke.underline,lN=ke.strikethrough,uN=ke.reset,Rl={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bx={debug:"\uD83D\uDD0D",info:yx("ℹ"),success:px("✓"),warning:vx(xm(Sm(" WARN "))),error:wx(xm(Sm(" ERROR ")))};fN=new $o("stacks");Tt=class Tt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};qm=class qm extends Tt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};po=class po extends Tt{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};Ym=class Ym extends Tt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Jm=class Jm extends Tt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};Zl=class Zl extends Tt{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};Xm=class Xm extends Tt{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Zm=class Zm extends Tt{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};yo=class yo extends Tt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Qm=class Qm extends Tt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};eg=class eg extends Tt{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};pn={configNotFound(e,t,r){return new qm(e,t,r)},configLoad(e,t,r){return new po(e,t,r)},configValidation(e,t,r){return new Ym(e,t,r)},configMerge(e,t,r,n){return new Jm(e,t,r,n)},envVar(e,t,r,n){return new Zl(e,t,r,n)},fileSystem(e,t,r){return new Xm(e,t,r)},typeGeneration(e,t,r){return new Zm(e,t,r)},schemaValidation(e,t,r){return new yo(e,t,r)},browserConfig(e,t,r,n){return new Qm(e,t,r,n)},plugin(e,t,r){return new eg(e,t,r)}};Ax=/^https?:\/\//;Dt=new $o("bunfig",{showTags:!0});Ol=new og;pN=gt(wo.cwd(),"config"),yN=gt(wo.cwd(),"src/generated")});import{homedir as eu}from"node:os";import{join as tu,resolve as kx}from"node:path";async function ug(){if(!ru)ru=await ag({name:"rpx",cwd:kx(__dirname,".."),defaultConfig:lg});return ru}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",lg,ru=null,Gt;var Co=te(()=>{cg();lg={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:tu(eu(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:tu(eu(),".stacks","ssl","stacks.localhost.crt"),keyPath:tu(eu(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};Gt=lg});function yn(e){return e.startsWith("*.")}function Ur(e,t){if(!yn(t))return!1;let r=t.slice(1);return e.length>r.length&&e.endsWith(r)}function fg(e,t){let r=e.get(t);if(r!==void 0)return r;let n,i=-1;for(let[s,o]of e){if(!yn(s))continue;if(Ur(t,s)){let c=s.length-1;if(c>i)i=c,n=o}}return n}import{existsSync as Ox,readdirSync as Nx,readFileSync as Dx,statSync as Fx}from"node:fs";import{homedir as dg}from"node:os";import{isAbsolute as Lx,join as wn}from"node:path";function iu(e,t){if(e==="~")return t;if(e.startsWith("~/"))return wn(t,e.slice(2));return e}function Ix(e){let t=e.indexOf(":");return(t===-1?e:e.slice(0,t)).toLowerCase()}function xo(e){return e.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function Mx(e,t){for(let r of t){let n=`.${r}`;if(e.endsWith(n)){let i=e.slice(0,-n.length);if(i.length>0&&!i.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(i))return i}}return null}function _x(e,t){let r=t.readText(wn(e,"rpx.site.json"));if(r)try{let i=JSON.parse(r);if(i&&typeof i==="object")return i}catch{}let n=t.readText(wn(e,"package.json"));if(n)try{let i=JSON.parse(n);if(i.rpx&&typeof i.rpx==="object")return i.rpx}catch{}return null}function jx(e){let t=e.selfRegisters??!1;return{command:e.command,env:e.env,urlEnv:e.urlEnv,selfRegisters:t,routes:e.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function Ux(e,t){let r=_x(e,t);if(r?.command)return jx(r);let n=t.fileExists(wn(e,"buddy")),i=t.readText(wn(e,"package.json")),s=null;if(i)try{s=JSON.parse(i)}catch{s=null}let o={...s?.dependencies??{},...s?.devDependencies??{}};if(n||Object.keys(o).some((a)=>a==="stacks"||a.startsWith("@stacksjs/")))return{command:n?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(s?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function su(e,t={}){let r={dirExists:t.dirExists??nu.dirExists,fileExists:t.fileExists??nu.fileExists,readText:t.readText??nu.readText},n=t.detect??Ux,i=t.homeDir??dg(),s=e.tlds??gg,o=(e.roots??mg).map((h)=>iu(h,i)),c=e.idleTimeoutMs??Bx,a=new Map;for(let h of e.sites??[])a.set(h.to,h);let l=(h)=>h.idleTimeoutMs??c;function u(h){let d=fg(a,h);if(!d)return null;let y=Lx(d.dir)?d.dir:iu(d.dir,i),g=d.selfRegisters??!1,p=d.routes??[];if(!g&&p.length===0)p=n(y,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let w=hg({...d.env??{}},void 0,h);return{host:h,id:xo(h),dir:y,command:d.command,env:w,routes:p,selfRegisters:g,idleTimeoutMs:l(d),source:"config"}}function f(h){let d=Mx(h,s);if(!d)return null;for(let y of o){let g=wn(y,d);if(!r.dirExists(g))continue;let p=n(g,r);if(!p)continue;let w=p.selfRegisters??!1;return{host:h,id:xo(h),dir:g,command:p.command,env:hg({...p.env??{}},p.urlEnv,h),routes:w?[]:p.routes??[],selfRegisters:w,idleTimeoutMs:c,source:"discovered"}}return null}return{resolve(h){let d=Ix(h);if(!d)return null;return u(d)??f(d)}}}function Kx(e){try{return Nx(e,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function pg(e,t={}){let r=t.homeDir??dg(),n=e.tlds??gg,i=(e.roots??mg).map((f)=>iu(f,r)),s=t.readdir??Kx,o=su(e,t),c=[],a=new Set,l=(f)=>{if(f&&!a.has(f.host))a.add(f.host),c.push(f)};for(let f of e.sites??[])if(!f.to.includes("*"))l(o.resolve(f.to));let u=n[0]??"localhost";for(let f of i)for(let h of s(f))l(o.resolve(`${h}.${u}`));return c}function hg(e,t,r){if(!t)return e;let n=`https://${r}`;for(let i of t)if(e[i]===void 0)e[i]=n;return e}var mg,gg,Bx=1800000,nu;var ou=te(()=>{mg=["~/Code"],gg=["localhost","test"],nu={dirExists:(e)=>{try{return Fx(e).isDirectory()}catch{return!1}},fileExists:(e)=>{try{return Ox(e)}catch{return!1}},readText:(e)=>{try{return Dx(e,"utf8")}catch{return null}}}});var b;var qt=te(()=>{b={info:(...e)=>console.log("[info]",...e),success:(...e)=>console.log("[success]",...e),warn:(...e)=>console.warn("[warn]",...e),error:(...e)=>console.error("[error]",...e),debug:(...e)=>console.debug("[debug]",...e),log:(...e)=>console.log(...e),start:(...e)=>console.log("[start]",...e),box:(...e)=>console.log("[box]",...e)}});import{createRequire as Wx}from"node:module";import{Resolver as au}from"node:dns/promises";import yg from"node:process";import{createHash as Vx,sign as Hx}from"node:crypto";import{createHash as zx}from"node:crypto";import{sign as Gx}from"node:crypto";import{generateKeyPairSync as dp,X509Certificate as rS}from"node:crypto";import cu from"node:os";import lu from"node:path";import{existsSync as vg,statSync as bg}from"fs";import{existsSync as iS,mkdirSync as UN,readdirSync as KN,readFileSync as sS,writeFileSync as WN}from"fs";import{homedir as vn}from"os";import{dirname as zN,resolve as wt}from"path";import ua from"process";import{existsSync as $g,statSync as Cg}from"fs";import{existsSync as Ou,mkdirSync as oS,readdirSync as aS,writeFileSync as cS}from"fs";import{homedir as bn}from"os";import{dirname as xg,resolve as Xe}from"path";import Vr from"process";import{join as lS,relative as uS,resolve as Sg}from"path";import qo from"process";import{existsSync as gp,mkdirSync as rD,readdirSync as nD,writeFileSync as iD}from"fs";import{homedir as uu}from"os";import{dirname as aD,resolve as Je}from"path";import Ni from"process";import{join as fS,relative as hS,resolve as Eg}from"path";import Yo from"process";import{existsSync as pp,mkdirSync as hD,readdirSync as dD,writeFileSync as mD}from"fs";import{dirname as pD,resolve as Jo}from"path";import Nu from"process";import{Buffer as br}from"buffer";import{createCipheriv as dS,createDecipheriv as mS,randomBytes as fu}from"crypto";import{closeSync as hu,createReadStream as Tg,createWriteStream as gS,existsSync as du,fsyncSync as Pg,openSync as Ag,writeFileSync as pS}from"fs";import{access as yS,constants as Rg,mkdir as wS,readdir as So,rename as kg,stat as $n,unlink as Eo,writeFile as mu}from"fs/promises";import{join as Cn}from"path";import _e from"process";import{pipeline as vS}from"stream/promises";import{createGzip as Og}from"zlib";import xn from"process";import Xt from"process";import{Buffer as Yt}from"buffer";import{createCipheriv as bS,createDecipheriv as $S,randomBytes as gu}from"crypto";import{closeSync as pu,createReadStream as Ng,createWriteStream as CS,existsSync as To,fsyncSync as Dg,openSync as Fg,writeFileSync as xS}from"fs";import{access as SS,constants as Lg,mkdir as ES,readdir as Po,rename as Bg,stat as Sn,unlink as Ao,writeFile as yu}from"fs/promises";import{isAbsolute as TS,join as En,resolve as PS}from"path";import J from"process";import{pipeline as AS}from"stream/promises";import{createGzip as Ig}from"zlib";import Tn from"process";import Zt from"process";import Ro from"process";import{existsSync as ko}from"fs";import{resolve as wu}from"path";import{existsSync as RS}from"fs";import{existsSync as kS,readdirSync as OS}from"fs";import{extname as vu,resolve as Mg}from"path";import NS from"process";import{join as DS,relative as FS,resolve as _g}from"path";import Xo from"process";import{Buffer as Jt}from"buffer";import{createCipheriv as LS,createDecipheriv as BS,randomBytes as bu}from"crypto";import{closeSync as $u,createReadStream as jg,createWriteStream as IS,existsSync as Oo,fsyncSync as Ug,openSync as Kg,writeFileSync as MS}from"fs";import{access as _S,constants as Wg,mkdir as jS,readdir as No,rename as Vg,stat as Pn,unlink as Do,writeFile as Cu}from"fs/promises";import{isAbsolute as US,join as An,resolve as KS}from"path";import X from"process";import{pipeline as WS}from"stream/promises";import{createGzip as Hg}from"zlib";import Rn from"process";import Qt from"process";import Fo from"process";import{existsSync as Lo}from"fs";import{resolve as xu}from"path";import{existsSync as VS}from"fs";import{exec as d0}from"node:child_process";import On from"node:fs";import Wu from"node:os";import nt from"node:path";import Zp from"node:process";import{promisify as m0}from"node:util";import Ii from"node:crypto";import Kr from"node:fs";import b0 from"node:tls";import C0 from"node:crypto";import x0 from"node:fs";import A0 from"node:crypto";import jn from"node:crypto";import Lt from"node:fs";import Ln from"node:path";import z0 from"node:process";import er from"node:fs";import zu from"node:path";import{execSync as X0}from"node:child_process";import Nn from"node:fs";import Bt from"node:os";async function kn(e,t={},r=30000){try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(n){if(n&&typeof n==="object"&&n.name==="TimeoutError"){let i=Error(`ACME HTTP request to ${e} timed out after ${r}ms`);throw i.name="AcmeRequestTimeoutError",i}throw n}}async function Gu(e,t,r={}){let n=r.timeoutMs??120000,i=r.intervalMs??3000,s=e.split(".").slice(-2).join("."),o;try{let l=new au,u=await l.resolveNs(s),f=(await Promise.all(u.map((h)=>l.resolve4(h).catch(()=>[])))).flat();if(f.length>0)o=new au,o.setServers(f)}catch{}let c=Date.now()+n,a=o??new au;for(;;){try{if((await a.resolveTxt(e)).some((l)=>l.join("")===t))return!0}catch{}if(Date.now()>=c)return!1;await new Promise((l)=>setTimeout(l,i))}}function Vo(e){let t=e.split(".");if(t.length<=2)return{apex:e,subdomain:""};let r=t.slice(-2).join("."),n=t.slice(0,-2).join(".");return{apex:r,subdomain:n}}class qu{apiKey;secretApiKey;baseUrl;requestTimeoutMs;constructor(e){let t=e?.apiKey??yg.env.PORKBUN_API_KEY,r=e?.secretApiKey??yg.env.PORKBUN_SECRET_KEY;if(!t||!r)throw Error("Porkbun credentials missing: set PORKBUN_API_KEY and PORKBUN_SECRET_KEY (or pass them in)");this.apiKey=t,this.secretApiKey=r,this.baseUrl=e?.baseUrl??"https://api.porkbun.com/api/json/v3",this.requestTimeoutMs=e?.requestTimeoutMs??ca}async post(e,t){let r=await kn(`${this.baseUrl}${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretApiKey,...t})},this.requestTimeoutMs),n=await r.json().catch(()=>({}));if(!r.ok||n.status!=="SUCCESS")throw Error(`Porkbun API ${e} failed: ${n.message??`HTTP ${r.status}`}`);return n}async setTxt(e,t){let{apex:r,subdomain:n}=Vo(e);await this.post(`/dns/create/${r}`,{type:"TXT",name:n,content:t,ttl:"600"})}async removeTxt(e,t){let{apex:r,subdomain:n}=Vo(e),i=n?`${n}.${r}`:r,s=(await this.post(`/dns/retrieveByNameType/${r}/TXT/${n}`,{}).catch(()=>null))?.records??[];for(let o of s)if(o.content===t&&(o.name===i||o.name===r))await this.post(`/dns/delete/${r}/${o.id}`,{}).catch(()=>{})}}class Wr{tokens=new Map;add(e,t){this.tokens.set(e,t)}get(e){return this.tokens.get(e)}remove(e){this.tokens.delete(e)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(e){let t=e.indexOf(Wr.PATH_PREFIX);if(t===-1)return;let r=e.slice(t+Wr.PATH_PREFIX.length);return this.get(r)}}function Pi(e){return(typeof e==="string"?Buffer.from(e,"utf8"):Buffer.from(e)).toString("base64url")}function Ri(e){return Buffer.from(e,"base64url")}function up(e){return Ri(e).toString("utf8")}function Ju(e){let t=e.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function Xu(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}","y":"${e.y}"}`;return Vx("sha256").update(t).digest("base64url")}function Zu(e){let{protectedHeader:t,payload:r,privateKey:n}=e,i=Pi(JSON.stringify(t)),s=r===""?"":Pi(JSON.stringify(r)),o=`${i}.${s}`,c=Hx("sha256",Buffer.from(o),{key:n,dsaEncoding:"ieee-p1363"});return{protected:i,payload:s,signature:Pi(c)}}class Oi{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(e){this.directoryUrl=e.directoryUrl,this.accountKey=e.accountKey,this.jwk=Ju(e.accountPublicKey),this.thumbprint=Xu(this.jwk),this.requestTimeoutMs=e.requestTimeoutMs??ca}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let e=await kn(this.directoryUrl,{},this.requestTimeoutMs);if(!e.ok)throw Error(`Failed to fetch ACME directory: HTTP ${e.status}`);return this.directoryCache=await e.json(),this.directoryCache}async newNonce(){let e=await this.directory(),t=(await kn(e.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let e=this.nonce;return this.nonce=void 0,e}return this.newNonce()}async signedPost(e){let{url:t,payload:r,useJwk:n}=e,i={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(n)i.jwk=this.jwk;else i.kid=this.requireKid();let s=Zu({protectedHeader:i,payload:r,privateKey:this.accountKey}),o=await kn(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(s)},this.requestTimeoutMs),c=o.headers.get("replay-nonce");if(c)this.nonce=c;let a=o.headers.get("content-type")??"",l;if(a.includes("application/pem-certificate-chain")||a.startsWith("text/"))l=await o.text();else{let u=await o.text();l=u?JSON.parse(u):{}}if(o.status>=400){let u=l??{};throw new ki(`ACME request to ${t} failed (HTTP ${o.status}): ${u.type??""} ${u.detail??""}`.trim(),u,o.status)}return{status:o.status,headers:o.headers,body:l,location:o.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(e={}){let t=await this.directory(),r={termsOfServiceAgreed:!0};if(e.email)r.contact=[`mailto:${e.email}`];let n=await this.signedPost({url:t.newAccount,payload:r,useJwk:!0});if(!n.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=n.location,this.accountKid}async newOrder(e){let t=await this.directory(),r={identifiers:e.map((i)=>({type:"dns",value:i}))},n=await this.signedPost({url:t.newOrder,payload:r});if(!n.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:n.body,orderUrl:n.location}}async getAuthorization(e){return(await this.signedPost({url:e,payload:""})).body}keyAuthorization(e){return`${e}.${this.thumbprint}`}dns01TxtValue(e){return zx("sha256").update(this.keyAuthorization(e)).digest("base64url")}async notifyChallengeReady(e){await this.signedPost({url:e,payload:{}})}async pollAuthorization(e,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,i=Date.now()+r;while(Date.now()<i){let s=await this.getAuthorization(e);if(s.status==="valid")return;if(s.status==="invalid"){let o=s.challenges.find((c)=>c.status==="invalid");throw new ki(`Authorization for ${s.identifier.value} became invalid: ${o?.error?.detail??"unknown reason"}`,o?.error??{},0)}await wg(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for authorization ${e} to become valid`)}async finalizeOrder(e,t){return(await this.signedPost({url:e,payload:{csr:t}})).body}async getOrder(e){return(await this.signedPost({url:e,payload:""})).body}async pollOrder(e,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,i=Date.now()+r;while(Date.now()<i){let s=await this.getOrder(e);if(s.status==="valid"){if(!s.certificate)throw Error("ACME order is valid but has no certificate URL");return s.certificate}if(s.status==="invalid")throw Error(`ACME order ${e} became invalid`);await wg(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for order ${e} to become valid`)}async downloadCertificate(e){let t=await this.signedPost({url:e,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(e,t){let r=e.challenges.find((n)=>n.type===t);if(!r)throw Error(`No ${t} challenge available for ${e.identifier.value}`);return r}}function tf(e){let t=e.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${e.trim()}
|
|
62
|
+
`,chainPem:""};let n=`${r.trim()}
|
|
63
|
+
`,i=t.slice(1).map((s)=>s.trim()).join(`
|
|
64
|
+
`);return{certPem:n,chainPem:i?`${i}
|
|
65
|
+
`:""}}function rf(e){return`_acme-challenge.${e.startsWith("*.")?e.slice(2):e}`}function wg(e){return new Promise((t)=>setTimeout(t,e))}function qx(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function rr(e,t){return Buffer.concat([Buffer.from([e]),qx(t.length),t])}function nf(e){let t;if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=[],n=e;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=e.length===0?Buffer.from([0]):e,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return rr(2,t)}function $r(e){let t=e.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${e}`);let r=[40*t[0]+t[1]];for(let n=2;n<t.length;n++){let i=t[n],s=[i&127];i=Math.floor(i/128);while(i>0)s.unshift(i&127|128),i=Math.floor(i/128);r.push(...s)}return rr(6,Buffer.from(r))}function fp(){return Buffer.from([5,0])}function at(...e){return rr(48,Buffer.concat(e))}function Ho(...e){return rr(49,Buffer.concat(e))}function zo(e){return rr(3,Buffer.concat([Buffer.from([0]),e]))}function sf(e){return rr(4,e)}function hp(e){return rr(19,Buffer.from(e,"ascii"))}function of(e){return rr(12,Buffer.from(e,"utf8"))}function Go(e,t,r){let n=128|(r?32:0)|e;return rr(n,t)}function tS(e){let t=e.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=Ri(t.x),n=Ri(t.y);if(r.length!==32||n.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${n.length}`);return Buffer.concat([Buffer.from([4]),r,n])}function af(e){let{domains:t,publicKey:r,privateKey:n}=e;if(t.length===0)throw Error("At least one domain is required to build a CSR");let i=at(Ho(at($r(Zx),of(t[0])))),s=at(at($r(Yx),$r(Jx)),zo(tS(r))),o=t.map((g)=>Go(2,Buffer.from(g,"ascii"),!1)),c=at(...o),a=at($r(eS),sf(c)),l=at(a),u=at($r(Qx),Ho(l)),f=Go(0,u,!0),h=at(nf(0),i,s,f),d=Gx("sha256",h,n),y=at($r(Xx));return at(h,y,zo(d))}function cf(e){return af(e).toString("base64url")}function nS(e){if(e){let{createPrivateKey:i,createPublicKey:s}=xi("node:crypto"),o=i(e),c=s(o.export({format:"pem",type:"pkcs8"}));return{privateKey:o,publicKey:c,pem:e}}let{privateKey:t,publicKey:r}=dp("ec",{namedCurve:"P-256"}),n=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:n}}async function la(e){let{domains:t,method:r}=e;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!e.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((f)=>f.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=e.directoryUrl??(e.staging===!1?ef:Qu),i=nS(e.accountKeyPem),s=new Oi({directoryUrl:n,accountKey:i.privateKey,accountPublicKey:i.publicKey,requestTimeoutMs:e.requestTimeoutMs});await s.newAccount({email:e.email});let{order:o,orderUrl:c}=await s.newOrder(t),a=e.http01Store??Ui,l=[],u=[];try{for(let R of o.authorizations){let D=await s.getAuthorization(R);if(D.status==="valid")continue;let F=Oi.selectChallenge(D,r);if(r==="dns-01"){let x=rf(D.identifier.value),k=s.dns01TxtValue(F.token);await e.dnsProvider.setTxt(x,k),l.push({name:x,value:k}),await Gu(x,k,{timeoutMs:e.dnsPropagationTimeoutMs??120000})}else a.add(F.token,s.keyAuthorization(F.token)),u.push(F.token);await s.notifyChallengeReady(F.url),await s.pollAuthorization(R,{timeoutMs:e.timeoutMs})}let{privateKey:f,publicKey:h}=dp("ec",{namedCurve:"P-256"}),d=cf({domains:t,publicKey:h,privateKey:f});await s.finalizeOrder(o.finalize,d);let y=await s.pollOrder(c,{timeoutMs:e.timeoutMs}),g=await s.downloadCertificate(y),{certPem:p,chainPem:w}=tf(g),v=w?`${p}${w}`:p,P=f.export({format:"pem",type:"pkcs8"}).toString(),A=new Date(new rS(p).validTo);return{certPem:p,keyPem:P,chainPem:w,fullChainPem:v,accountKeyPem:i.pem,notAfter:A}}finally{for(let{name:f,value:h}of l)await e.dnsProvider?.removeTxt(f,h).catch(()=>{});for(let f of u)a.remove(f)}}class yp{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!vg(e))return!0;return bg(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=vg(r)?bg(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class wp{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function GS(e,t){this[e]=zS.bind(null,t)}class uf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!$g(e))return!0;return Cg(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=$g(r)?Cg(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ff{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function JS(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function XS(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function ZS(e){return e.getStats().size*2}function hf(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ce(t[0])&&"id"in t[0]&&t[0].id===3&&ce(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ce(t)&&ce(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(ce(e)&&"arr"in e&&Array.isArray(e.arr)&&ce(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ce(t[0])&&ce(e[0])){let n=[...t];for(let i of e)if(ce(i)&&"name"in i){if(!n.find((s)=>ce(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(ce(i)&&"path"in i){if(!n.find((s)=>ce(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>Qo(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!ce(t)||!ce(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(ce(i)&&ce(r[n]))r[n]=hf(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&ce(i[0])&&ce(r[n][0])){let s=[...i];for(let o of r[n])if(ce(o)&&"name"in o){if(!s.find((c)=>ce(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(ce(o)&&"path"in o){if(!s.find((c)=>ce(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((c)=>Qo(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function Qo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Qo(e[r],t[r]))return!1;return!0}if(ce(e)&&ce(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Qo(e[i],t[i]))return!1}return!0}return!1}function ce(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function QS(e,t){if(!pp(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return hf(t,n)}catch{return null}}catch{return null}}async function eE({name:e="",cwd:t,defaultConfig:r}){let n=t||Nu.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=Jo(n,`${o}${c}`),l=await QS(a,r);if(l!==null)return l}try{let o=Jo(n,"package.json");if(pp(o)){let c=(await import(o))[e];if(c&&typeof c==="object"&&!Array.isArray(c))try{return hf(r,c)}catch{}}}catch{}return r}function tE(e,t={}){let r=Yo.cwd();while(r.includes("storage"))r=Eg(r,"..");let n=Eg(r,e||"");if(t?.relative)return hS(Yo.cwd(),n);return n}async function rE(){try{let e=await eE({name:"clarity",defaultConfig:jo,cwd:Yo.cwd(),endpoint:"",headers:{}});return{...jo,...e}}catch{return jo}}function de(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nE(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Xt<"u"){let e=Xt.type;if(e==="renderer"||e==="worker")return!1;return!!(Xt.versions&&(Xt.versions.node||Xt.versions.bun))}return!1}class bp{async format(e){let t=await nE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:xn.pid,hostname:t(),environment:xn.env.NODE_ENV||"development",platform:xn.platform,version:xn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xn.env.NODE_ENV||xn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ea{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(e,t={}){this.name=e,this.config={...Fu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new bp,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_e.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Uo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Uo};return{...Uo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Fu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await yS(this.config.logDirectory,Rg.F_OK|Rg.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await wS(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:br.from(e);try{if(!du(this.currentLogFile))await mu(this.currentLogFile,"",{mode:420});if(n=Ag(this.currentLogFile,"a",420),pS(n,c,{flag:"a"}),Pg(n),n!==void 0)hu(n),n=void 0;if((await $n(this.currentLogFile)).size===0){if(await mu(this.currentLogFile,c,{flag:"w",mode:420}),(await $n(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(i<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let f=o*2**i;await new Promise((h)=>setTimeout(h,f)),i++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(n!==void 0)try{hu(n)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(i===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}i++;let a=o*2**(i-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Cn(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 Cn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Cn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(de())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return fu(16).toString("hex")}generateKey(){return fu(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=fu(16),n=dS("aes-256-gcm",t,r),i=br.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:br.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Og(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(br.from(br.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(de())return;let e=await $n(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await So(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await $n(r).catch(()=>null))try{if(await kg(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Eo(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await mu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await $n(r).catch(()=>null))await kg(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await So(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Eo(Cn(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Tg(e),n=gS(t),i=Og();await vS(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),du(this.currentLogFile))try{let e=Ag(this.currentLogFile,"r+");Pg(e),hu(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!de()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await So(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Eo(Cn(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?ne.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=_e.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${ne.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!de()){let l=kp[e],u=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:ne.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:ne.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
|
|
66
|
+
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:ne.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!de()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
67
67
|
`;if(c)a+=`${c}
|
|
68
|
-
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!
|
|
69
|
-
`,a=a.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
70
|
-
`),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:
|
|
71
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
72
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
73
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ce()||!Oe.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ce()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Is(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=hi(this.config.logDirectory,i);if(e.before)try{if((await fi(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await _s(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function eo(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&J(t[0])&&"id"in t[0]&&t[0].id===3&&J(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(J(t)&&J(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(J(e)&&"arr"in e&&Array.isArray(e.arr)&&J(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&J(t[0])&&J(e[0])){let i=[...t];for(let n of e)if(J(n)&&"name"in n){if(!i.find((s)=>J(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(J(n)&&"path"in n){if(!i.find((s)=>J(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>go(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!J(t)||!J(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(J(n)&&J(r[i]))r[i]=eo(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&J(n[0])&&J(r[i][0])){let s=[...n];for(let o of r[i])if(J(o)&&"name"in o){if(!s.find((c)=>J(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(J(o)&&"path"in o){if(!s.find((c)=>J(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((c)=>go(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function eu(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:eo(e,t);if(Array.isArray(e))return r==="replace"?t:eo(e,t);if(!J(t)||!J(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=eo(o,s);else if(J(s)&&J(o))i[n]=eu(o,s,r);else i[n]=s}return i}function go(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!go(e[r],t[r]))return!1;return!0}if(J(e)&&J(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!go(e[n],t[n]))return!1}return!0}return!1}function J(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Js(e,t,r="replace"){if(!qm(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return eu(t,n,r)}catch{return null}}catch{return null}}function $C(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${f.map(h).join("_")}`,y=`${i}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)De.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=on.env[d]||on.env[y];if(g!==void 0){if(r)De.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(n)}async function xC({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?$C(e,n,s):n,l=r||on.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)De.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Ve(l,"config"),Ve(l,".config"),i?Ve(l,i):void 0].filter(Boolean)));for(let p of g){if(s)De.info(`Searching for configuration in: ${p}`);let w=[Ve(l,"config"),Ve(l,".config")].concat(i?[Ve(l,i)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let b of w)for(let P of u){let R=Ve(p,`${b}${P}`),v=await Js(R,a,c);if(v!==null){if(s)De.success(`Configuration loaded from: ${R}`);return v}}}if(e){let p=Ve(ul(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)De.info(`Checking user config directory: ${p}`);for(let b of w)for(let P of u){let R=Ve(p,`${b}${P}`),v=await Js(R,a,c);if(v!==null){if(s)De.success(`Configuration loaded from user config directory: ${R}`);return v}}}if(e){let p=Ve(ul(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)De.info(`Checking user config directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ve(p,`${b}${P}`),v=await Js(R,a,c);if(v!==null){if(s)De.success(`Configuration loaded from user config directory dotfile: ${R}`);return v}}}if(e){let p=ul(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)De.info(`Checking user home directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ve(p,`${b}${P}`),v=await Js(R,a,c);if(v!==null){if(s)De.success(`Configuration loaded from user home directory: ${R}`);return v}}}try{let p=Ve(l,"package.json");if(qm(p)){let w=await import(p),b=w[e];if(!b&&t){if(b=w[t],b&&s)De.success(`Using alias "${t}" configuration from package.json`)}if(b&&typeof b==="object"&&!Array.isArray(b))try{if(s)De.success(`Configuration loaded from package.json: ${b===w[e]?e:t}`);return eu(a,b,c)}catch(P){if(s)De.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)De.warn("Failed to load package.json:",p)}if(s)De.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function CC(e,t={}){let r=ao.cwd();while(r.includes("storage"))r=qd(r,"..");let i=qd(r,e||"");if(t?.relative)return Px(ao.cwd(),i);return i}async function SC(){try{let e=await xC({name:"clarity",alias:"logging",defaultConfig:io,cwd:ao.cwd()});return{...io,...e||{}}}catch{return io}}function we(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function EC(){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 e=Vt.type;if(e==="renderer"||e==="worker")return!1;return!!(Vt.versions&&(Vt.versions.node||Vt.versions.bun))}return!1}class tg{async format(e){let t=await EC(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:pi.pid,hostname:t(),environment:pi.env.NODE_ENV||"development",platform:pi.platform,version:pi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pi.env.NODE_ENV||pi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class po{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(e,t={}){this.name=e,this.config={...Ml},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new tg,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??G.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...no,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...no};return{...no,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ml.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!we()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await Ux(this.config.logDirectory,om.F_OK|om.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await Wx(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ut.from(e);try{if(!js(this.currentLogFile))await yl(this.currentLogFile,"",{mode:420});if(i=sm(this.currentLogFile,"a",420),jx(i,c,{flag:"a"}),nm(i),i!==void 0)pl(i),i=void 0;if((await mi(this.currentLogFile)).size===0){if(await yl(this.currentLogFile,c,{flag:"w",mode:420}),(await mi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=o*2**n;await new Promise((h)=>setTimeout(h,f)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{pl(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(n===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}n++;let a=o*2**(n-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return gi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return gi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return gi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(we())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return gl(16).toString("hex")}generateKey(){return gl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=gl(16),i=Mx("aes-256-gcm",t,r),n=Ut.isBuffer(e)?e:Ut.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=Ut.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=cm(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Ut.from(Ut.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(we())return;if(!this.shouldWriteToFile())return;let e=await mi(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Us(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await mi(r).catch(()=>null))try{if(await am(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ws(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await yl(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await mi(r).catch(()=>null))await am(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Us(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await Ws(gi(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=im(e),i=_x(t),n=cm();await Vx(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),js(this.currentLogFile))try{let e=sm(this.currentLogFile,"r+");nm(e),pl(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!we()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Us(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ws(gi(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?j.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||we())return!1;let e=typeof G.env.NO_COLOR<"u",t=G.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof G.stderr<"u"&&G.stderr.isTTY||typeof G.stdout<"u"&&G.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=G.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${j.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=j.underline(j.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>j.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>j.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>j.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>j.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>j.strikethrough(i)),t}supportsHyperlinks(){if(we())return!1;let e=G.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=G.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Kx(t)||t.startsWith("./")||t.startsWith("../"))t=Hx(t);else return null;return js(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":fg[e],h=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:j.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:j.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
74
|
-
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:
|
|
68
|
+
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!de()){let r=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:ne.blue("◐"),tag:r,message:`${ne.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),a=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
69
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.fancy&&!de()){let l=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:ne.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!de())console.error(a.trim());await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ea(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(de())throw Error("createReadStream is not supported in browser environments");if(!du(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Tg(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=br.isBuffer(e)?e:br.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=mS("aes-256-gcm",r,i);return c.setAuthTag(s),br.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return de()}isServerMode(){return!de()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!de()){let s=e.split(`
|
|
70
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:ne.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ne.cyan(c)})),l.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:ne.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:ne.cyan(a),showTimestamp:!1}))}else if(!de())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
71
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(de())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ne.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();_e.stdin.removeListener("data",r);try{if(typeof _e.stdin.setRawMode==="function")_e.stdin.setRawMode(!1)}catch{}_e.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof _e.stdin.setRawMode==="function")_e.stdin.setRawMode(!0)}catch{}_e.stdin.resume(),_e.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let i=/%([sdijfo%])/g,s=0;if(r=e.replace(i,(o,c)=>{if(c==="%")return"%";if(s>=t.length)return o;let a=t[s++];switch(c){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!de()){let i=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"",s=ne.blue("◐");console.error(`${s} ${i} ${ne.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
72
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||de()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||de())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,n)),i!==void 0)this.activeProgressBar.message=i;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||de())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,i="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||de())return;_e.stdout.write(`${"\r".padEnd(_e.stdout.columns||80)}\r`),this.log(i,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||de()||!_e.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=ne.green("━".repeat(n)),o=ne.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=t||r===100?ne.green("✓"):ne.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${ne.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=_e.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,_e.stdout.write(e.lastRenderedLine),t)_e.stdout.write(`
|
|
73
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||de()||!_e.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(de()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await So(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=Cn(this.config.logDirectory,n);if(e.before)try{if((await $n(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Eo(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function _o(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Z(t[0])&&"id"in t[0]&&t[0].id===3&&Z(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Z(t)&&Z(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Z(e)&&"arr"in e&&Array.isArray(e.arr)&&Z(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Z(t[0])&&Z(e[0])){let n=[...t];for(let i of e)if(Z(i)&&"name"in i){if(!n.find((s)=>Z(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Z(i)&&"path"in i){if(!n.find((s)=>Z(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>ta(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Z(t)||!Z(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Z(i)&&Z(r[n]))r[n]=_o(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Z(i[0])&&Z(r[n][0])){let s=[...i];for(let o of r[n])if(Z(o)&&"name"in o){if(!s.find((c)=>Z(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(Z(o)&&"path"in o){if(!s.find((c)=>Z(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((c)=>ta(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function df(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:_o(e,t);if(Array.isArray(e))return r==="replace"?t:_o(e,t);if(!Z(t)||!Z(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=_o(o,s);else if(Z(s)&&Z(o))n[i]=df(o,s,r);else n[i]=s}return n}function ta(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ta(e[r],t[r]))return!1;return!0}if(Z(e)&&Z(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ta(e[i],t[i]))return!1}return!0}return!1}function Z(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Bo(e,t,r="replace"){if(!gp(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return df(t,i,r)}catch{return null}}catch{return null}}function iE(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${n}_${f.map(h).join("_")}`,y=`${n}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)Ue.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=Ni.env[d]||Ni.env[y];if(g!==void 0){if(r)Ue.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(i)}async function sE({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?iE(e,i,s):i,l=r||Ni.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Ue.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Je(l,"config"),Je(l,".config"),n?Je(l,n):void 0].filter(Boolean)));for(let p of g){if(s)Ue.info(`Searching for configuration in: ${p}`);let w=[Je(l,"config"),Je(l,".config")].concat(n?[Je(l,n)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let v of w)for(let P of u){let A=Je(p,`${v}${P}`),R=await Bo(A,a,c);if(R!==null){if(s)Ue.success(`Configuration loaded from: ${A}`);return R}}}if(e){let p=Je(uu(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)Ue.info(`Checking user config directory: ${p}`);for(let v of w)for(let P of u){let A=Je(p,`${v}${P}`),R=await Bo(A,a,c);if(R!==null){if(s)Ue.success(`Configuration loaded from user config directory: ${A}`);return R}}}if(e){let p=Je(uu(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)Ue.info(`Checking user config directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=Je(p,`${v}${P}`),R=await Bo(A,a,c);if(R!==null){if(s)Ue.success(`Configuration loaded from user config directory dotfile: ${A}`);return R}}}if(e){let p=uu(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)Ue.info(`Checking user home directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=Je(p,`${v}${P}`),R=await Bo(A,a,c);if(R!==null){if(s)Ue.success(`Configuration loaded from user home directory: ${A}`);return R}}}try{let p=Je(l,"package.json");if(gp(p)){let w=await import(p),v=w[e];if(!v&&t){if(v=w[t],v&&s)Ue.success(`Using alias "${t}" configuration from package.json`)}if(v&&typeof v==="object"&&!Array.isArray(v))try{if(s)Ue.success(`Configuration loaded from package.json: ${v===w[e]?e:t}`);return df(a,v,c)}catch(P){if(s)Ue.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)Ue.warn("Failed to load package.json:",p)}if(s)Ue.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function oE(e,t={}){let r=qo.cwd();while(r.includes("storage"))r=Sg(r,"..");let n=Sg(r,e||"");if(t?.relative)return uS(qo.cwd(),n);return n}async function aE(){try{let e=await sE({name:"clarity",alias:"logging",defaultConfig:Ko,cwd:qo.cwd()});return{...Ko,...e||{}}}catch{return Ko}}function xe(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cE(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Zt<"u"){let e=Zt.type;if(e==="renderer"||e==="worker")return!1;return!!(Zt.versions&&(Zt.versions.node||Zt.versions.bun))}return!1}class $p{async format(e){let t=await cE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Tn.pid,hostname:t(),environment:Tn.env.NODE_ENV||"development",platform:Tn.platform,version:Tn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Tn.env.NODE_ENV||Tn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ra{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(e,t={}){this.name=e,this.config={...Lu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new $p,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??J.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Wo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Wo};return{...Wo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Lu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!xe()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await SS(this.config.logDirectory,Lg.F_OK|Lg.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await ES(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Yt.from(e);try{if(!To(this.currentLogFile))await yu(this.currentLogFile,"",{mode:420});if(n=Fg(this.currentLogFile,"a",420),xS(n,c,{flag:"a"}),Dg(n),n!==void 0)pu(n),n=void 0;if((await Sn(this.currentLogFile)).size===0){if(await yu(this.currentLogFile,c,{flag:"w",mode:420}),(await Sn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(i<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let f=o*2**i;await new Promise((h)=>setTimeout(h,f)),i++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(n!==void 0)try{pu(n)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(i===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}i++;let a=o*2**(i-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return En(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 En(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return En(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(xe())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return gu(16).toString("hex")}generateKey(){return gu(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=gu(16),n=bS("aes-256-gcm",t,r),i=Yt.isBuffer(e)?e:Yt.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=Yt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Ig(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Yt.from(Yt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(xe())return;if(!this.shouldWriteToFile())return;let e=await Sn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Po(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Sn(r).catch(()=>null))try{if(await Bg(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ao(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await yu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Sn(r).catch(()=>null))await Bg(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Po(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Ao(En(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Ng(e),n=CS(t),i=Ig();await AS(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),To(this.currentLogFile))try{let e=Fg(this.currentLogFile,"r+");Dg(e),pu(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!xe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Po(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ao(En(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?W.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||xe())return!1;let e=typeof J.env.NO_COLOR<"u",t=J.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof J.stderr<"u"&&J.stderr.isTTY||typeof J.stdout<"u"&&J.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=J.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${W.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=W.underline(W.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>W.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>W.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>W.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>W.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>W.strikethrough(n)),t}supportsHyperlinks(){if(xe())return!1;let e=J.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=J.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(TS(t)||t.startsWith("./")||t.startsWith("../"))t=PS(t);else return null;return To(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Op[e],h=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:W.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:W.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
74
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:W.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!xe()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
75
75
|
`;if(c)u+=`${c}
|
|
76
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(
|
|
77
|
-
`);if(this[s==="warning"?"warn":s](
|
|
78
|
-
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?
|
|
79
|
-
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:
|
|
80
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(
|
|
81
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
82
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
76
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!xe()&&J.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!xe()&&J.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!xe()&&J.stdout.isTTY)J.stdout.write(`
|
|
77
|
+
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!xe()&&J.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":W.blue("◐"),tag:r,message:`${W.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),a=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
78
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":W.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!xe())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ra(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(xe())throw Error("createReadStream is not supported in browser environments");if(!To(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ng(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Yt.isBuffer(e)?e:Yt.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=$S("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Yt.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return xe()}isServerMode(){return!xe()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
79
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:W.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:W.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:W.cyan(u),showTimestamp:!1}))}else if(!xe())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
80
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(xe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${W.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();J.stdin.removeListener("data",r);try{if(typeof J.stdin.setRawMode==="function")J.stdin.setRawMode(!1)}catch{}J.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof J.stdin.setRawMode==="function")J.stdin.setRawMode(!0)}catch{}J.stdin.resume(),J.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${W.blue("◐")} `;console.error(`${c}${o} ${W.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
81
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!J.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=W.green("━".repeat(n)),o=W.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?W.green("✓"):W.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${W.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=J.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,J.stdout.write(e.lastRenderedLine),t)J.stdout.write(`
|
|
82
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||xe()||!J.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(xe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Po(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=En(this.config.logDirectory,n);if(e.before)try{if((await Sn(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ao(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Cp(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function xp(e){return e instanceof ct}function lE(e){return e instanceof na}function uE(e){if(xp(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class fa{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Ki.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Ro.env[a]||(l?Ro.env[l]:void 0);if(u!==void 0){if(n.verbose){let f=Ro.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(u,typeof s,a,n.customParsers,n.configName)}catch(f){if(f instanceof ia)throw f;throw Cr.envVar(a,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Cr.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Ro.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
83
83
|
|
|
84
|
-
`;for(let
|
|
85
|
-
`,r+=` Type: ${
|
|
86
|
-
`,r+=` Description: ${
|
|
87
|
-
`,r+=` Example: ${
|
|
84
|
+
`;for(let n of e)r+=`${n.key}
|
|
85
|
+
`,r+=` Type: ${n.type}
|
|
86
|
+
`,r+=` Description: ${n.description}
|
|
87
|
+
`,r+=` Example: ${n.example}
|
|
88
88
|
|
|
89
89
|
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
90
90
|
|
|
91
91
|
`;r+=`| Variable | Type | Description | Example |
|
|
92
92
|
`,r+=`|----------|------|-------------|----------|
|
|
93
|
-
`;for(let
|
|
94
|
-
`;return r}}function RC(e,t){let r=cg("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function ng(e,t,r={}){return sg(e,t,r,new WeakMap)}function sg(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return og(e,t,n,i);if(!mt(t)||!mt(e))return t;return NC(e,t,r,i)}function og(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return AC(e,t);case"smart":return kC(e,t,i);default:return t}return t}function AC(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Bl(n,i)))r.push(i);return r}function kC(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(mt(t[0])&&mt(e[0]))return OC(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function OC(e,t,r){let i=[...t];for(let n of e){if(!mt(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in n){if(i.find((a)=>mt(a)&&(c in a)&&a[c]===n[c])){o=!0;break}}if(!o)i.push(n)}return i}function NC(e,t,r,i){let n=t;if(mt(n)&&i.has(n))return i.get(n);let s={...e};if(mt(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(mt(c)&&mt(a))s[o]=sg(a,c,r,i);else if(Array.isArray(c)||Array.isArray(a))s[o]=og(a,c,r.arrayMergeMode||"smart",i);else s[o]=c}return s}function tu(e,t,r="replace"){return ng(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Bl(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Bl(e[r],t[r]))return!1;return!0}if(mt(e)&&mt(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Bl(e[n],t[n]))return!1}return!0}return!1}function mt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Po{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=$i.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Hs(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new an(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new an(e,Error("Configuration must export a valid object"),"unknown");let y={config:tu(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)$i.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?hr.configLoad(e,l):hr.configLoad(e,Error(String(l)))}};if(o)return un.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(wl(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return rg(async()=>Hs(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Hs(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let c=wl(e,`${s}${o}`);if(await this.checkFileAccess(c))i.push(c)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=wl(e,o);if(await this.checkFileAccess(c))i.push(c)}}catch{return[]}return i}looksLikeConfigFile(e){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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Hs(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class ru{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await un.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Yx(t))throw new cn(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new cn(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(i.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(i.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(i.push(...c),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:dg},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class iu{fileLoader=new Po;envProcessor=new To;validator=new ru;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||s)await this.validateConfiguration(c.config,n,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(i?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(a);if(i.slowThreshold&&a.duration>i.slowThreshold)xt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw xt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Fr.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,o)),this.finalizeResult(d,h,a,i,u);let y=await this.loadHomeConfiguration(i,n,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,a,i,u);let g=await this.loadPackageJsonConfiguration(i,n,f,c,l,u,a);if(g)return h.push(Ye(f,"package.json")),this.finalizeResult(g,h,a,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,o)),t)throw hr.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,c,a,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,c,a){let l=c?rn(e,n,o):n,u=this.getLocalDirectories(r,i);for(let f of u){if(o)xt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)xt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?rn(e,r,n):r,c=[Ye(ui(),".config",e),Ye(ui(),".config"),ui()];for(let a of c){if(n)xt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(u){if(n)xt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let c=o?rn(e,i,s):i;try{let a=Ye(r,"package.json");if(!Dl(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)xt.success(`Configuration loaded from package.json: ${f}`);return{config:tu(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)xt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:rn(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw hr.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return $i.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);$i.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ye(e,"config"),Ye(e,".config"),t?Ye(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Ye(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ye(ui(),".config",e),Ye(ui(),".config"),ui()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function ym(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function DC(e){return Gt.loadConfig({...e,__strictErrorHandling:!0})}async function ag(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await Gt.loadConfig(e);else i=await Gt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)xt.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Gt.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function FC(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Gt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&ym(r)))return(await Gt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Gt.loadConfig({...e,cwd:e.cwd||Fr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ym(t)))return(await Gt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function BC(e,t,r="replace"){let i=new Po;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function rn(e,t,r=!1){let i=new To,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((g)=>g.toUpperCase()).join("")}`,`${n}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Fr.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function LC(e){let t=Ye(Fr.cwd(),e.configDir),r=Ye(Fr.cwd(),e.generatedDir),i=Ye(r,"config-types.ts");if(!Dl(Gd(i)))Cx(Gd(i),{recursive:!0,mode:511});let n=Dl(t)?Sx(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${fS}
|
|
95
|
-
export type ConfigNames = ${
|
|
96
|
-
`;
|
|
97
|
-
${
|
|
93
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
94
|
+
`;return r}}function fE(e,t){let r=Ap("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Sp(e,t,r={}){return Ep(e,t,r,new WeakMap)}function Ep(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Tp(e,t,i,n);if(!vt(t)||!vt(e))return t;return gE(e,t,r,n)}function Tp(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return hE(e,t);case"smart":return dE(e,t,n);default:return t}return t}function hE(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Du(i,n)))r.push(n);return r}function dE(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(vt(t[0])&&vt(e[0]))return mE(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function mE(e,t,r){let n=[...t];for(let i of e){if(!vt(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((a)=>vt(a)&&(c in a)&&a[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function gE(e,t,r,n){let i=t;if(vt(i)&&n.has(i))return n.get(i);let s={...e};if(vt(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(vt(c)&&vt(a))s[o]=Ep(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=Tp(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function mf(e,t,r="replace"){return Sp(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Du(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Du(e[r],t[r]))return!1;return!0}if(vt(e)&&vt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Du(e[i],t[i]))return!1}return!0}return!1}function vt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ha{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=Dn.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!ko(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new Di(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Di(e,Error("Configuration must export a valid object"),"unknown");let y={config:mf(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Dn.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?Cr.configLoad(e,l):Cr.configLoad(e,Error(String(l)))}};if(o)return Ki.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(wu(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Cp(async()=>ko(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ko(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=wu(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=wu(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ko(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class gf{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await Ki.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!RS(t))throw new Fi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Fi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Dp},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class pf{fileLoader=new ha;envProcessor=new fa;validator=new gf;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)Pt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw Pt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Vr.cwd(),h=[],d=await this.loadLocalConfiguration(n,i,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(n,i,f,o)),this.finalizeResult(d,h,a,n,u);let y=await this.loadHomeConfiguration(n,i,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(y,h,a,n,u);let g=await this.loadPackageJsonConfiguration(n,i,f,c,l,u,a);if(g)return h.push(Xe(f,"package.json")),this.finalizeResult(g,h,a,n,u);if(h.push(...this.getAllSearchPaths(n,i,f,o)),t)throw Cr.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?Si(e,i,o):i,u=this.getLocalDirectories(r,n);for(let f of u){if(o)Pt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Pt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?Si(e,r,i):r,c=[Xe(bn(),".config",e),Xe(bn(),".config"),bn()];for(let a of c){if(i)Pt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(u){if(i)Pt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?Si(e,n,s):n;try{let a=Xe(r,"package.json");if(!Ou(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Pt.success(`Configuration loaded from package.json: ${f}`);return{config:mf(c,u,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Pt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Si(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw Cr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Dn.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Dn.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Xe(e,"config"),Xe(e,".config"),t?Xe(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Xe(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Xe(bn(),".config",e),Xe(bn(),".config"),bn()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function zg(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function pE(e){return tr.loadConfig({...e,__strictErrorHandling:!0})}async function Pp(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await tr.loadConfig(e);else n=await tr.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)Pt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await tr.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function yE(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await tr.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&zg(r)))return(await tr.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await tr.loadConfig({...e,cwd:e.cwd||Vr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&zg(t)))return(await tr.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function wE(e,t,r="replace"){let n=new ha;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Si(e,t,r=!1){let n=new fa,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((g)=>g.toUpperCase()).join("")}`,`${i}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Vr.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function vE(e){let t=Xe(Vr.cwd(),e.configDir),r=Xe(Vr.cwd(),e.generatedDir),n=Xe(r,"config-types.ts");if(!Ou(xg(n)))oS(xg(n),{recursive:!0,mode:511});let i=Ou(t)?aS(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${qE}
|
|
95
|
+
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
96
|
+
`;cS(n,s,{mode:438})}function bE(e){let t=null,r=null,n=()=>{if(!r)r=Pp(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)Pt.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function $E(e){let t=Mg(NS.cwd(),e?.configDir||"./config");function r(){if(!kS(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=OS(t).filter((a)=>i.has(vu(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=vu(l).toLowerCase(),f=c.get(a);if(!f){c.set(a,l);continue}let h=vu(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((a)=>a.base),o=s.length?s.map((a)=>`'${a}'`).join(" | "):"string",c=i.length?`{
|
|
97
|
+
${i.map((a)=>{let l=Mg(t,a.file).replace(/\\/g,"/");return` '${a.base}': typeof import('${l}').default`}).join(`,
|
|
98
98
|
`)}
|
|
99
99
|
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
100
100
|
export type ConfigByName = ${c}
|
|
101
101
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
102
102
|
export type ConfigOf = Config
|
|
103
|
-
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}function dS(e,t={}){let r=uo.cwd();while(r.includes("storage"))r=um(r,"..");let i=um(r,e||"");if(t?.relative)return Xx(uo.cwd(),i);return i}function be(){if(Yt.env.NODE_ENV==="test"||Yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gS(){if(Yt.env.NODE_ENV==="test"||Yt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Yt<"u"){let e=Yt.type;if(e==="renderer"||e==="worker")return!1;return!!(Yt.versions&&(Yt.versions.node||Yt.versions.bun))}return!1}class yg{async format(e){let t=await gS(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:vi.pid,hostname:t(),environment:vi.env.NODE_ENV||"development",platform:vi.platform,version:vi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:vi.env.NODE_ENV||vi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ro{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(e,t={}){this.name=e,this.config={...vo},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new yg,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Rl,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Rl};return{...Rl,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:vo.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!be()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await rC(this.config.logDirectory,mm.F_OK|mm.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await iC(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Wt.from(e);try{if(!Vs(this.currentLogFile))await xl(this.currentLogFile,"",{mode:420});if(i=dm(this.currentLogFile,"a",420),tC(i,c,{flag:"a"}),hm(i),i!==void 0)$l(i),i=void 0;if((await yi(this.currentLogFile)).size===0){if(await xl(this.currentLogFile,c,{flag:"w",mode:420}),(await yi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=o*2**n;await new Promise((h)=>setTimeout(h,f)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{$l(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(n===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}n++;let a=o*2**(n-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return wi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return wi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return wi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(be())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return bl(16).toString("hex")}generateKey(){return bl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=bl(16),i=Qx("aes-256-gcm",t,r),n=Wt.isBuffer(e)?e:Wt.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=Wt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=pm(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Wt.from(Wt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(be())return;if(!this.shouldWriteToFile())return;let e=await yi(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Ys(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await yi(r).catch(()=>null))try{if(await gm(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await zs(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await xl(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await yi(r).catch(()=>null))await gm(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Ys(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await zs(wi(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=fm(e),i=eC(t),n=pm();await oC(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Vs(this.currentLogFile))try{let e=dm(this.currentLogFile,"r+");hm(e),$l(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!be()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ys(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await zs(wi(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?H.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||be())return!1;let e=typeof q.env.NO_COLOR<"u",t=q.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof q.stderr<"u"&&q.stderr.isTTY||typeof q.stdout<"u"&&q.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=q.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${H.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=H.underline(H.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>H.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>H.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>H.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>H.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>H.strikethrough(i)),t}supportsHyperlinks(){if(be())return!1;let e=q.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=q.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(nC(t)||t.startsWith("./")||t.startsWith("../"))t=sC(t);else return null;return Vs(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":bS[e],h=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:H.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:H.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
104
|
-
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:
|
|
103
|
+
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function JE(e,t={}){let r=Xo.cwd();while(r.includes("storage"))r=_g(r,"..");let n=_g(r,e||"");if(t?.relative)return FS(Xo.cwd(),n);return n}function Ee(){if(Qt.env.NODE_ENV==="test"||Qt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ZE(){if(Qt.env.NODE_ENV==="test"||Qt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Qt<"u"){let e=Qt.type;if(e==="renderer"||e==="worker")return!1;return!!(Qt.versions&&(Qt.versions.node||Qt.versions.bun))}return!1}class Ip{async format(e){let t=await ZE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Rn.pid,hostname:t(),environment:Rn.env.NODE_ENV||"development",platform:Rn.platform,version:Rn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Rn.env.NODE_ENV||Rn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class da{name;fileLocks=new Map;currentKeyId=null;keys=new Map;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(e,t={}){this.name=e,this.config={...sa},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ip,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??X.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Au,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Au};return{...Au,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:sa.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ee()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await _S(this.config.logDirectory,Wg.F_OK|Wg.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await jS(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Jt.from(e);try{if(!Oo(this.currentLogFile))await Cu(this.currentLogFile,"",{mode:420});if(n=Kg(this.currentLogFile,"a",420),MS(n,c,{flag:"a"}),Ug(n),n!==void 0)$u(n),n=void 0;if((await Pn(this.currentLogFile)).size===0){if(await Cu(this.currentLogFile,c,{flag:"w",mode:420}),(await Pn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(i<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let f=o*2**i;await new Promise((h)=>setTimeout(h,f)),i++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(n!==void 0)try{$u(n)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(i===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}i++;let a=o*2**(i-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return An(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 An(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return An(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ee())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return bu(16).toString("hex")}generateKey(){return bu(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=bu(16),n=LS("aes-256-gcm",t,r),i=Jt.isBuffer(e)?e:Jt.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=Jt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Hg(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Jt.from(Jt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ee())return;if(!this.shouldWriteToFile())return;let e=await Pn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await No(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Pn(r).catch(()=>null))try{if(await Vg(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Do(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Cu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Pn(r).catch(()=>null))await Vg(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await No(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Do(An(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=jg(e),n=IS(t),i=Hg();await WS(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Oo(this.currentLogFile))try{let e=Kg(this.currentLogFile,"r+");Ug(e),$u(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ee()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await No(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Do(An(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?z.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ee())return!1;let e=typeof X.env.NO_COLOR<"u",t=X.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof X.stderr<"u"&&X.stderr.isTTY||typeof X.stdout<"u"&&X.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=X.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${z.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=z.underline(z.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>z.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>z.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>z.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>z.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>z.strikethrough(n)),t}supportsHyperlinks(){if(Ee())return!1;let e=X.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=X.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(US(t)||t.startsWith("./")||t.startsWith("../"))t=KS(t);else return null;return Oo(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":n0[e],h=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:z.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:z.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
104
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:z.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!Ee()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
105
105
|
`;if(c)u+=`${c}
|
|
106
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(
|
|
107
|
-
`);if(this[s==="warning"?"warn":s](
|
|
108
|
-
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?
|
|
109
|
-
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:
|
|
110
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(
|
|
111
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
112
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
106
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ee()&&X.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Ee()&&X.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Ee()&&X.stdout.isTTY)X.stdout.write(`
|
|
107
|
+
`);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Ee()&&X.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":z.blue("◐"),tag:r,message:`${z.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),a=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
108
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":z.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ee())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new da(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Ee())throw Error("createReadStream is not supported in browser environments");if(!Oo(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return jg(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Jt.isBuffer(e)?e:Jt.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=BS("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Jt.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ee()}isServerMode(){return!Ee()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
109
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:z.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(u),showTimestamp:!1}))}else if(!Ee())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
110
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Ee())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${z.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();X.stdin.removeListener("data",r);try{if(typeof X.stdin.setRawMode==="function")X.stdin.setRawMode(!1)}catch{}X.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof X.stdin.setRawMode==="function")X.stdin.setRawMode(!0)}catch{}X.stdin.resume(),X.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${z.blue("◐")} `;console.error(`${c}${o} ${z.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
111
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!X.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=z.green("━".repeat(n)),o=z.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?z.green("✓"):z.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=X.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,X.stdout.write(e.lastRenderedLine),t)X.stdout.write(`
|
|
112
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ee()||!X.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ee()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await No(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=An(this.config.logDirectory,n);if(e.before)try{if((await Pn(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Do(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function i0(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class wf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return lf.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Fo.env[a]||(l?Fo.env[l]:void 0);if(u!==void 0){if(n.verbose){let f=Fo.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(u,typeof s,a,n.customParsers,n.configName)}catch(f){if(f instanceof yf)throw f;throw Fn.envVar(a,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Fn.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Fo.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
113
113
|
|
|
114
|
-
`;for(let
|
|
115
|
-
`,r+=` Type: ${
|
|
116
|
-
`,r+=` Description: ${
|
|
117
|
-
`,r+=` Example: ${
|
|
114
|
+
`;for(let n of e)r+=`${n.key}
|
|
115
|
+
`,r+=` Type: ${n.type}
|
|
116
|
+
`,r+=` Description: ${n.description}
|
|
117
|
+
`,r+=` Example: ${n.example}
|
|
118
118
|
|
|
119
119
|
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
120
120
|
|
|
121
121
|
`;r+=`| Variable | Type | Description | Example |
|
|
122
122
|
`,r+=`|----------|------|-------------|----------|
|
|
123
|
-
`;for(let
|
|
124
|
-
`;return r}}function xS(e,t,r={}){return Eg(e,t,r,new WeakMap)}function Eg(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Tg(e,t,n,i);if(!gt(t)||!gt(e))return t;return TS(e,t,r,i)}function Tg(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return CS(e,t);case"smart":return SS(e,t,i);default:return t}return t}function CS(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Hl(n,i)))r.push(i);return r}function SS(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(gt(t[0])&>(e[0]))return ES(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function ES(e,t,r){let i=[...t];for(let n of e){if(!gt(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in n){if(i.find((a)=>gt(a)&&(c in a)&&a[c]===n[c])){o=!0;break}}if(!o)i.push(n)}return i}function TS(e,t,r,i){let n=t;if(gt(n)&&i.has(n))return i.get(n);let s={...e};if(gt(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(gt(c)&>(a))s[o]=Eg(a,c,r,i);else if(Array.isArray(c)||Array.isArray(a))s[o]=Tg(a,c,r.arrayMergeMode||"smart",i);else s[o]=c}return s}function Pg(e,t,r="replace"){return xS(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Hl(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Hl(e[r],t[r]))return!1;return!0}if(gt(e)&>(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Hl(e[n],t[n]))return!1}return!0}return!1}function gt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Rg{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=fo.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!qs(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new bo(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new bo(e,Error("Configuration must export a valid object"),"unknown");let y={config:Pg(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)fo.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?xi.configLoad(e,l):xi.configLoad(e,Error(String(l)))}};if(o)return Jl.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(Cl(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return $S(async()=>qs(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!qs(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let c=Cl(e,`${s}${o}`);if(await this.checkFileAccess(c))i.push(c)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=Cl(e,o);if(await this.checkFileAccess(c))i.push(c)}}catch{return[]}return i}looksLikeConfigFile(e){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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!qs(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Ag{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await Jl.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!aC(t))throw new $o(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new $o(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(i.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(i.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(i.push(...c),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:PS},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function RS(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class kg{fileLoader=new Rg;envProcessor=new su;validator=new Ag;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||s)await this.validateConfiguration(c.config,n,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(i?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(a);if(i.slowThreshold&&a.duration>i.slowThreshold)Kt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw Kt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Eo.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,o)),this.finalizeResult(d,h,a,i,u);let y=await this.loadHomeConfiguration(i,n,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,a,i,u);let g=await this.loadPackageJsonConfiguration(i,n,f,c,l,u,a);if(g)return h.push(dt(f,"package.json")),this.finalizeResult(g,h,a,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,o)),t)throw xi.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,c,a,u),warnings:[`No configuration file found for "${i}"${RS(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,c,a){let l=c?Xs(e,n,o):n,u=this.getLocalDirectories(r,i);for(let f of u){if(o)Kt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Kt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?Xs(e,r,n):r,c=[dt(li(),".config",e),dt(li(),".config"),li()];for(let a of c){if(n)Kt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(u){if(n)Kt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let c=o?Xs(e,i,s):i;try{let a=dt(r,"package.json");if(!$x(a))return null;let l={};try{l=JSON.parse(xx(a,"utf8"))}catch(h){if(s)Kt.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=l[e],f=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){u=l[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Kt.success(`Configuration loaded from package.json: ${f}`);return{config:Pg(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Kt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Xs(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw xi.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return fo.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);fo.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,dt(e,"config"),dt(e,".config"),t?dt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(dt(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[dt(li(),".config",e),dt(li(),".config"),li()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Xs(e,t,r=!1){let i=new su,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((g)=>g.toUpperCase()).join("")}`,`${n}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Eo.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function Dg(e){return Vl.readFileSync(e,"utf8")}function Yl(e,t){let r=[];function i(n){let s;try{s=Vl.readdirSync(n)}catch{return}for(let o of s){let c=$t.join(n,o);try{if(Vl.statSync(c).isDirectory())i(c);else if(o===t)r.push(n)}catch{continue}}}return i(e),r}function A(e,t,r){if(r||fe.verbose)console.debug(`[tlsx:${e}] ${t}`)}function Fg(){return Ng.env.SUDO_PASSWORD}function BS(e){let t=e.toLowerCase();return DS.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function xo(e){if(Array.isArray(e))return e.map((r)=>xo(r));if(typeof e==="string")return FS.test(e)?km:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,i]of Object.entries(e)){if(BS(r)){t[r]=km;continue}t[r]=xo(i)}return t}function Ao(e){return JSON.stringify(xo(e))}function LS(e){let t=Fg();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(e))return e;let r=t.replace(/'/g,"'\\''"),i=e.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${i}`}async function fr(e,t={}){let r=LS(e);try{let{stdout:i,stderr:n}=await NS(r,{cwd:t.cwd||Ng.cwd(),timeout:t.timeout||30000});return{stdout:i.trim(),stderr:n.trim()}}catch(i){let n=Error(`Failed to execute command: ${e}
|
|
125
|
-
Error: ${
|
|
126
|
-
|
|
123
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
124
|
+
`;return r}}function s0(e,t,r={}){return Hp(e,t,r,new WeakMap)}function Hp(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return zp(e,t,i,n);if(!bt(t)||!bt(e))return t;return l0(e,t,r,n)}function zp(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return o0(e,t);case"smart":return a0(e,t,n);default:return t}return t}function o0(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Ku(i,n)))r.push(n);return r}function a0(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(bt(t[0])&&bt(e[0]))return c0(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function c0(e,t,r){let n=[...t];for(let i of e){if(!bt(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((a)=>bt(a)&&(c in a)&&a[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function l0(e,t,r,n){let i=t;if(bt(i)&&n.has(i))return n.get(i);let s={...e};if(bt(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(bt(c)&&bt(a))s[o]=Hp(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=zp(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function Gp(e,t,r="replace"){return s0(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Ku(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ku(e[r],t[r]))return!1;return!0}if(bt(e)&&bt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Ku(e[i],t[i]))return!1}return!0}return!1}function bt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class qp{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=Zo.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Lo(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new oa(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new oa(e,Error("Configuration must export a valid object"),"unknown");let y={config:Gp(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Zo.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?Fn.configLoad(e,l):Fn.configLoad(e,Error(String(l)))}};if(o)return lf.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(xu(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of n){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let i=new Set;return r.filter((s)=>{if(!s||i.has(s))return!1;return i.add(s),!0})}checkFileAccess(e){return i0(async()=>Lo(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Lo(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=xu(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=xu(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Lo(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Yp{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await lf.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!VS(t))throw new aa(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new aa(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:u0},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function f0(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Jp{fileLoader=new qp;envProcessor=new wf;validator=new Yp;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)Ft.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw Ft.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||ua.cwd(),h=[],d=await this.loadLocalConfiguration(n,i,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(n,i,f,o)),this.finalizeResult(d,h,a,n,u);let y=await this.loadHomeConfiguration(n,i,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(y,h,a,n,u);let g=await this.loadPackageJsonConfiguration(n,i,f,c,l,u,a);if(g)return h.push(wt(f,"package.json")),this.finalizeResult(g,h,a,n,u);if(h.push(...this.getAllSearchPaths(n,i,f,o)),t)throw Fn.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,u),warnings:[`No configuration file found for "${n}"${f0(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?Io(e,i,o):i,u=this.getLocalDirectories(r,n);for(let f of u){if(o)Ft.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Ft.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?Io(e,r,i):r,c=[wt(vn(),".config",e),wt(vn(),".config"),vn()];for(let a of c){if(i)Ft.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(u){if(i)Ft.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?Io(e,n,s):n;try{let a=wt(r,"package.json");if(!iS(a))return null;let l={};try{l=JSON.parse(sS(a,"utf8"))}catch(h){if(s)Ft.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=l[e],f=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){u=l[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Ft.success(`Configuration loaded from package.json: ${f}`);return{config:Gp(c,u,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Ft.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Io(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw Fn.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Zo.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Zo.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,wt(e,"config"),wt(e,".config"),t?wt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(wt(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[wt(vn(),".config",e),wt(vn(),".config"),vn()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}async function h0(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Ru.loadConfig(e);else n=await Ru.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)Ft.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Ru.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}function Io(e,t,r=!1){let n=new wf,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((g)=>g.toUpperCase()).join("")}`,`${i}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=ua.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}async function Xp(){if(!ku)ku=await h0({name:"tlsx",alias:"tls",defaultConfig:ma});return ku}function vf(e){return On.readFileSync(e,"utf8")}function Qp(e){let t=Wu.platform(),r;if(!e)if(t==="darwin")r="/etc/ssl/certs";else if(t==="win32")r="C:\\Windows\\System32\\certsrv\\CertEnroll";else if(t==="linux")r="/etc/ssl/certs";else throw Error(`Unsupported platform: ${t}`);else r=e;let n=On.readdirSync(r).filter((s)=>s.endsWith(".crt")).map((s)=>nt.join(r,s)),i=nt.join(Wu.homedir(),".stacks","ssl");if(On.existsSync(i))n.push(...On.readdirSync(i).filter((s)=>s.endsWith(".crt")).map((s)=>nt.join(i,s)));return n}function bf(e){let t=Number.parseInt(e[0],16);if(t<8)return e;return t-=8,t.toString()+e.substring(1)}function Li(e,t){let r=[];function n(i){let s;try{s=On.readdirSync(i)}catch{return}for(let o of s){let c=nt.join(i,o);try{if(On.statSync(c).isDirectory())n(c);else if(o===t)r.push(i)}catch{continue}}}return n(e),r}function C(e,t,r){if(r||B.verbose)console.debug(`[tlsx:${e}] ${t}`)}function $f(){return Zp.env.SUDO_PASSWORD}function w0(e){let t=e.toLowerCase();return p0.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function Bi(e){if(Array.isArray(e))return e.map((r)=>Bi(r));if(typeof e==="string")return y0.test(e)?sp:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e)){if(w0(r)){t[r]=sp;continue}t[r]=Bi(n)}return t}function Wi(e){return JSON.stringify(Bi(e))}function v0(e){let t=$f();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(e))return e;let r=t.replace(/'/g,"'\\''"),n=e.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function it(e,t={}){let r=v0(e);try{let{stdout:n,stderr:i}=await g0(r,{cwd:t.cwd||Zp.cwd(),timeout:t.timeout||30000});return{stdout:n.trim(),stderr:i.trim()}}catch(n){let i=Error(`Failed to execute command: ${e}
|
|
125
|
+
Error: ${n.message}`);throw i.stack=n.stack,i}}function Cf(e){if(e.domain)return e.domain;if(e.domains?.length)return e.domains[0];throw Error("Either domain or domains must be specified")}function In(e){let t=nt.join(Wu.homedir(),".stacks","ssl"),r=e.basePath&&e.basePath.trim()!==""?e.basePath:B.basePath&&B.basePath.trim()!==""?B.basePath:t,n=e.certPath?nt.isAbsolute(e.certPath)?e.certPath:nt.join(r,e.certPath):nt.join(r,B.certPath),i=e.keyPath?nt.isAbsolute(e.keyPath)?e.keyPath:nt.join(r,e.keyPath):nt.join(r,B.keyPath),s=e.caCertPath?nt.isAbsolute(e.caCertPath)?e.caCertPath:nt.join(r,e.caCertPath):nt.join(r,B.caCertPath);return{certPath:n,keyPath:i,caCertPath:s,basePath:r}}function ey(e){return e.startsWith("*.")?`_wildcard.${e.slice(2)}`:e}function ty(e){return e.replace(/\.crt$/,"")}function nr(e){let t;if(e.startsWith("-----BEGIN CERTIFICATE-----"))t=e;else t=vf(e);return new Ii.X509Certificate(t)}function Mn(e){return nr(e).fingerprint256.replace(/:/g,"").toUpperCase()}function xf(e){return e.match($0)??[]}function ga(e){let t=e.replace(/-----BEGIN [A-Z ]+-----/,"").replace(/-----END [A-Z ]+-----[\s\S]*$/,"").replace(/\s+/g,"");return Buffer.from(t,"base64")}function pa(e){return Ii.createHash("sha256").update(e).digest("hex").toUpperCase()}function Sf(e,t){let r=t.replace(/:/g,"").toUpperCase();for(let n of xf(e))try{if(pa(ga(n))===r)return!0}catch{}return!1}function _n(e){return Mi(nr(e).subject)}function Ef(e,t,r=443,n=4000){let i;try{i=t.includes("-----BEGIN")?t:Kr.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((s)=>{let o=!1,c=(l)=>{if(o)return;o=!0,s(l)},a=b0.connect({host:e,port:r,servername:e,ca:i,rejectUnauthorized:!0},()=>{c(a.authorized),a.end()});a.setTimeout(n,()=>{a.destroy(),c(!1)}),a.on("error",()=>c(!1))})}function Vu(e){let t=[],r=e.split(`
|
|
126
|
+
`);for(let n of r){let[i,...s]=n.split("="),o=s.join("=");if(i&&o)t.push({shortName:i.trim(),value:o.trim()})}return t}function Mi(e){return Vu(e).find((t)=>t.shortName==="CN")?.value||""}function ry(e){let t=[],r=Mi(e.subject);if(r&&!/^\d+\.\d+\.\d+\.\d+$/.test(r))t.push(r);let n=e.subjectAltName;if(n){let i=n.split(", ");for(let s of i)if(s.startsWith("DNS:"))t.push(s.slice(4))}return[...new Set(t)]}function ya(e,t){let r=nr(e),n=ry(r);for(let i of n){if(i===t)return!0;if(i.startsWith("*.")){let s=i.slice(2);if(t.endsWith(s)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}function ny(e){let t=nr(e);return{subject:Vu(t.subject),issuer:Vu(t.issuer),validFrom:new Date(t.validFrom),validTo:new Date(t.validTo),serialNumber:t.serialNumber}}function iy(e){let t=nr(e);return new Date>new Date(t.validTo)}function sy(e,t=30){let r=nr(e),n=new Date;return(new Date(r.validTo).getTime()-n.getTime())/86400000<=t}function oy(e,t,r){C(S.CERT,`Validating certificate: ${e}`,r);try{if(!Kr.existsSync(e))return{valid:!1,expired:!1,notYetValid:!1,issuerValid:!1,domains:[],validFrom:new Date,validTo:new Date,issuer:"",subject:"",message:`Certificate file not found: ${e}`};let n=Kr.readFileSync(e,"utf8"),i=new Ii.X509Certificate(n),s=new Date,o=new Date(i.validFrom),c=new Date(i.validTo),a=s>c,l=s<o,u=Mi(i.subject),f=Mi(i.issuer),h=ry(i),d=!1;if(t)if(Kr.existsSync(t))try{let y=Kr.readFileSync(t,"utf8"),g=new Ii.X509Certificate(y);d=i.verify(g.publicKey)}catch(y){C(S.CERT,`Error validating CA certificate: ${y}`,r)}else C(S.CERT,`CA certificate file not found: ${t}`,r);return{valid:!a&&!l&&(t?d:!0),expired:a,notYetValid:l,issuerValid:d,domains:h,validFrom:o,validTo:c,issuer:f,subject:u}}catch(n){return C(S.CERT,`Error validating certificate: ${n}`,r),{valid:!1,expired:!1,notYetValid:!1,issuerValid:!1,domains:[],validFrom:new Date,validTo:new Date,issuer:"",subject:"",message:`Error validating certificate: ${n}`}}}function ay(e,t){C(S.CERT,`Validating browser compatibility: ${e}`,t);try{if(!Kr.existsSync(e))return{compatible:!1,issues:[`Certificate file not found: ${e}`]};let r=Kr.readFileSync(e,"utf8"),n=new Ii.X509Certificate(r),i=[],s=!1,o=!1;if(Mi(n.subject)==="localhost")s=!0;let c=n.subjectAltName;if(c){let h=c.split(", ");for(let d of h){if(d==="DNS:localhost")s=!0;if(d.includes("*"))o=!0}}if(!s)i.push('Certificate does not include "localhost" in Subject Alternative Names, which may cause issues with some browsers.');if(o)i.push("Certificate contains wildcard domains, which may not be fully supported in all browsers for localhost development.");let a=n.keyUsage,l=n.extKeyUsage||"";if(!(l.includes("TLS Web Server Authentication")||l.includes("1.3.6.1.5.5.7.3.1")))i.push("Certificate lacks Extended Key Usage for serverAuth, which is required by modern browsers.");let u=new Date(n.validFrom),f=(new Date(n.validTo).getTime()-u.getTime())/86400000;if(f>398)i.push(`Certificate validity period is ${Math.floor(f)} days, which exceeds the 398-day maximum supported by modern browsers.`);return{compatible:i.length===0,issues:i}}catch(r){return C(S.CERT,`Error validating browser compatibility: ${r}`,t),{compatible:!1,issues:[`Error validating browser compatibility: ${r}`]}}}function T0(e){return Buffer.from(e.replace(/-/g,""),"hex")}function _i(e,t=Af){let r=C0.createHash("sha1").update(Buffer.concat([T0(t),Buffer.from(e,"utf8")])).digest(),n=Buffer.from(r.subarray(0,16));n[6]=n[6]&15|80,n[8]=n[8]&63|128;let i=n.toString("hex").toUpperCase();return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function Mo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function cy(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"root-ca"}function op(e,t){for(let r of e.split(`
|
|
127
|
+
`)){let n=r.indexOf("=");if(n!==-1&&r.slice(0,n).trim()===t)return r.slice(n+1).trim()}return}function P0(e,t=64){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r.join(`
|
|
128
|
+
`)}function Rf(e){let t=e.fingerprint.replace(/:/g,"").toUpperCase(),r=_i(`${t}:profile`),n=_i(`${t}:root`),i=P0(Buffer.from(e.certificateDer).toString("base64")),s=Mo(e.displayName),o=Mo(e.organization),c=Mo(e.identifier);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
129
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
130
|
+
<plist version="1.0">
|
|
131
|
+
<dict>
|
|
132
|
+
<key>PayloadContent</key>
|
|
133
|
+
<array>
|
|
134
|
+
<dict>
|
|
135
|
+
<key>PayloadCertificateFileName</key>
|
|
136
|
+
<string>${Mo(`${cy(e.displayName)}.cer`)}</string>
|
|
137
|
+
<key>PayloadContent</key>
|
|
138
|
+
<data>
|
|
139
|
+
${i}
|
|
140
|
+
</data>
|
|
141
|
+
<key>PayloadDescription</key>
|
|
142
|
+
<string>Adds the ${s} root certificate</string>
|
|
143
|
+
<key>PayloadDisplayName</key>
|
|
144
|
+
<string>${s}</string>
|
|
145
|
+
<key>PayloadIdentifier</key>
|
|
146
|
+
<string>${c}.root</string>
|
|
147
|
+
<key>PayloadType</key>
|
|
148
|
+
<string>com.apple.security.root</string>
|
|
149
|
+
<key>PayloadUUID</key>
|
|
150
|
+
<string>${n}</string>
|
|
151
|
+
<key>PayloadVersion</key>
|
|
152
|
+
<integer>1</integer>
|
|
153
|
+
</dict>
|
|
154
|
+
</array>
|
|
155
|
+
<key>PayloadDescription</key>
|
|
156
|
+
<string>Trusts the ${s} certificate authority on this device (SHA-256 ${t.slice(0,16)})</string>
|
|
157
|
+
<key>PayloadDisplayName</key>
|
|
158
|
+
<string>${s}</string>
|
|
159
|
+
<key>PayloadIdentifier</key>
|
|
160
|
+
<string>${c}</string>
|
|
161
|
+
<key>PayloadOrganization</key>
|
|
162
|
+
<string>${o}</string>
|
|
163
|
+
<key>PayloadRemovalDisallowed</key>
|
|
164
|
+
<false/>
|
|
165
|
+
<key>PayloadType</key>
|
|
166
|
+
<string>Configuration</string>
|
|
167
|
+
<key>PayloadUUID</key>
|
|
168
|
+
<string>${r}</string>
|
|
169
|
+
<key>PayloadVersion</key>
|
|
170
|
+
<integer>1</integer>
|
|
171
|
+
</dict>
|
|
172
|
+
</plist>
|
|
173
|
+
`}async function ly(e){let t=e.caCertPath.startsWith("-----BEGIN")?e.caCertPath:x0.readFileSync(e.caCertPath,"utf8"),r=nr(t),n=ga(t),i=pa(n),s=e.name?.trim()||op(r.subject,"CN")||"tlsx Root CA",o=e.organization?.trim()||op(r.subject,"O")||"tlsx",c=e.identifier?.trim()||`${wa}.${i.slice(0,12).toLowerCase()}`,a=`${cy(s)}.${S0[e.format]}`,l=Pf[e.format];switch(e.format){case"pem":return{data:t.endsWith(`
|
|
174
|
+
`)?t:`${t}
|
|
175
|
+
`,filename:a,mime:l};case"der":return{data:new Uint8Array(n),filename:a,mime:l};case"mobileconfig":return{data:Rf({certificateDer:n,displayName:s,organization:o,identifier:c,fingerprint:i}),filename:a,mime:l};default:throw Error(`Unsupported export format: ${String(e.format)}`)}}function uy(e,t){switch(e){case"macos":return["macOS (system keychain, all users and browsers):",` sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`," Restart any open browser afterwards."].join(`
|
|
176
|
+
`);case"ios":return["iOS / iPadOS (configuration profile):",` 1. Export the profile if you have not yet: tlsx export-ca --format mobileconfig --out ${t}`,` 2. Send ${t} to the device (AirDrop, Mail, or a link) and open it.`," 3. Settings > Profile Downloaded > Install, and confirm with the passcode."," 4. Settings > General > About > Certificate Trust Settings, then enable full trust for the new root."," Without step 4 the profile is installed but Safari still rejects the certificate."].join(`
|
|
177
|
+
`);case"windows":return["Windows (Local Machine root store, run from an elevated prompt):",` certutil -addstore -f ROOT ${t}`," Or double-click the file, Install Certificate, Local Machine, Trusted Root Certification Authorities."].join(`
|
|
178
|
+
`);case"debian":return["Debian / Ubuntu / Raspberry Pi OS:",` sudo cp ${t} /usr/local/share/ca-certificates/tlsx-root-ca.crt`," sudo update-ca-certificates"," The file must end in .crt to be picked up. Browsers using NSS (Firefox, Chromium) keep their own store; see linux-nss."].join(`
|
|
179
|
+
`);case"rhel":return["RHEL / Fedora / Rocky / AlmaLinux:",` sudo cp ${t} /etc/pki/ca-trust/source/anchors/tlsx-root-ca.crt`," sudo update-ca-trust"].join(`
|
|
180
|
+
`);case"android":return["Android (user CA):",` 1. Copy ${t} to the device (it must be PEM or DER with a .crt or .cer extension).`," 2. Settings > Security > Encryption & credentials > Install a certificate > CA certificate."," Apps only trust user CAs when their network security config opts in (Android 7+); Chrome does, most apps do not."].join(`
|
|
181
|
+
`);case"linux-nss":return["Linux browser stores (Firefox, Chromium via NSS):",` certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n "tlsx Root CA" -i ${t}`," For Firefox, repeat with -d sql:$HOME/.mozilla/firefox/<profile>, or import via Settings > Privacy & Security > Certificates."," tlsx install does this for every cert9.db it finds under your home directory."].join(`
|
|
182
|
+
`);default:throw Error(`Unknown platform: ${String(e)}. Expected one of ${Tf.join(", ")}`)}}function va(e){let t=[],r=new Set;if(e.domain)r.add(e.domain);if(e.domains?.length)e.domains.forEach((n)=>r.add(n));for(let n of r)t.push({type:2,value:n});if(e.altNameIPs?.length)for(let n of e.altNameIPs)t.push({type:7,ip:n});if(e.altNameURIs?.length)for(let n of e.altNameURIs)t.push({type:6,value:n});if(e.subjectAltNames?.length)t.push(...e.subjectAltNames);return C(S.CERT,`Generated ${t.length} Subject Alternative Names`,e.verbose),t}function fy(e){C(S.CERT,"Generating random serial number",e);let t=A0.randomBytes(20),r=bf(t.toString("hex"));return C(S.CERT,`Generated serial number: ${r}`,e),r}function ba(e){let t=e.notBeforeDays??lt.DEFAULT_NOT_BEFORE_DAYS,r=e.validityDays??(e.validityYears?e.validityYears*365:lt.DEFAULT_VALIDITY_DAYS);C(S.CERT,"Calculating certificate validity dates",e.verbose);let n=new Date(Date.now()-86400*t*1000),i=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),i.setUTCHours(23,59,59,999),C(S.CERT,`Validity period: ${n.toISOString()} to ${i.toISOString()}`,e.verbose),{notBefore:n,notAfter:i}}function hy(e){let t=[];t.push({name:"basicConstraints",cA:e.isCA??!1,critical:!0,...e.basicConstraints||{}});let r=va(e);if(r.length>0)t.push({name:"subjectAltName",altNames:r});let n=e.keyUsage||{digitalSignature:!0,keyEncipherment:!0};t.push({name:"keyUsage",critical:!0,...n});let i=e.extKeyUsage||{serverAuth:!0};return t.push({name:"extKeyUsage",...i}),t}function Ai(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function ft(e,t){let r=Ai(t.length);return Buffer.concat([Buffer.from([e]),r,t])}function ji(e){let t=e.split(".").map(Number),r=[];r.push(40*t[0]+t[1]);for(let n=2;n<t.length;n++){let i=t[n],s=[];s.unshift(i&127),i>>=7;while(i>0)s.unshift(i&127|128),i>>=7;r.push(...s)}return ft(At.OID,Buffer.from(r))}function Hu(e){let t;if(typeof e==="bigint"){let r=e.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=e.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else t=e;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return ft(At.INTEGER,t)}function dy(e,t=0){return ft(At.BIT_STRING,Buffer.concat([Buffer.from([t]),e]))}function my(e){return ft(At.OCTET_STRING,e)}function ut(...e){return ft(At.SEQUENCE,Buffer.concat(e))}function R0(...e){return ft(At.SET,Buffer.concat(e))}function k0(e){return ft(At.PRINTABLE_STRING,Buffer.from(e,"ascii"))}function O0(e){return ft(At.UTF8_STRING,Buffer.from(e,"utf8"))}function N0(){return Buffer.from([At.NULL,0])}function ap(e,t,r=!0){let n=160|e|(r?0:0),i=Ai(t.length);return Buffer.concat([Buffer.from([n]),i,t])}function cp(e){let t=e.getUTCFullYear();if(t>=2050){let r=e.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return ft(At.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(t%100).toString().padStart(2,"0"),n=(e.getUTCMonth()+1).toString().padStart(2,"0"),i=e.getUTCDate().toString().padStart(2,"0"),s=e.getUTCHours().toString().padStart(2,"0"),o=e.getUTCMinutes().toString().padStart(2,"0"),c=e.getUTCSeconds().toString().padStart(2,"0"),a=`${r}${n}${i}${s}${o}${c}Z`;return ft(At.UTC_TIME,Buffer.from(a,"ascii"))}}function D0(e,t){return ut(cp(e),cp(t))}function lp(e){let t=[];for(let r of e){let n;switch(r.shortName){case"CN":n=Ze.COMMON_NAME;break;case"C":n=Ze.COUNTRY;break;case"L":n=Ze.LOCALITY;break;case"ST":n=Ze.STATE;break;case"O":n=Ze.ORGANIZATION;break;case"OU":n=Ze.ORGANIZATIONAL_UNIT;break;default:continue}let i=r.shortName==="C"?k0(r.value):O0(r.value),s=ut(ji(n),i);t.push(R0(s))}return ut(...t)}function gy(e){return ut(ji(e),N0())}function F0(e){return e.export({type:"spki",format:"der"})}function L0(e){if(e.includes(":")){let t=e;if(e.includes("::")){let i=e.split("::"),s=i[0]?i[0].split(":"):[],o=i[1]?i[1].split(":"):[],c=8-s.length-o.length,a=Array.from({length:c},()=>"0");t=[...s,...a,...o].join(":")}let r=t.split(":"),n=Buffer.alloc(16);for(let i=0;i<8;i++){let s=Number.parseInt(r[i]||"0",16);n.writeUInt16BE(s,i*2)}return n}else{let t=e.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(t)}}function B0(e){let t=[];for(let r of e)if(r.type===2&&r.value){let n=Ai(r.value.length);t.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=L0(r.ip),i=Ai(n.length);t.push(Buffer.concat([Buffer.from([135]),i,n]))}else if(r.type===6&&r.value){let n=Ai(r.value.length);t.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return ut(...t)}function I0(e,t){if(e){if(t!==void 0)return ut(ft(1,Buffer.from([255])),Hu(t));return ut(ft(1,Buffer.from([255])))}return ut()}function M0(e){let t=0;if(e.digitalSignature)t|=128;if(e.keyEncipherment)t|=32;if(e.keyCertSign)t|=4;if(e.cRLSign)t|=2;let r=0,n=t;while(n>0&&(n&1)===0)r++,n>>=1;if(t===0)r=7;return dy(Buffer.from([t]),r)}function _0(e){let t=[];if(e.serverAuth)t.push(ji(Ze.SERVER_AUTH));if(e.clientAuth)t.push(ji(Ze.CLIENT_AUTH));return ut(...t)}function Ci(e,t,r){let n=[ji(e)];if(t)n.push(ft(1,Buffer.from([255])));return n.push(my(r)),ut(...n)}function j0(e){let t=[];if(t.push(ap(0,Hu(2))),t.push(Hu(e.serialNumber)),t.push(gy(Ze.SHA256_WITH_RSA)),t.push(lp(e.issuer)),t.push(D0(e.notBefore,e.notAfter)),t.push(lp(e.subject)),t.push(F0(e.publicKey)),e.extensions){let r=[];if(e.extensions.basicConstraints)r.push(Ci(Ze.BASIC_CONSTRAINTS,e.extensions.basicConstraints.critical??!0,I0(e.extensions.basicConstraints.isCA,e.extensions.basicConstraints.pathLenConstraint)));if(e.extensions.keyUsage)r.push(Ci(Ze.KEY_USAGE,e.extensions.keyUsage.critical??!0,M0(e.extensions.keyUsage)));if(e.extensions.extendedKeyUsage)r.push(Ci(Ze.EXTENDED_KEY_USAGE,!1,_0(e.extensions.extendedKeyUsage)));if(e.extensions.subjectAltName?.length)r.push(Ci(Ze.SUBJECT_ALT_NAME,!1,B0(e.extensions.subjectAltName)));if(e.extensions.subjectKeyIdentifier)r.push(Ci(Ze.SUBJECT_KEY_IDENTIFIER,!1,my(e.extensions.subjectKeyIdentifier)));if(r.length>0)t.push(ap(3,ut(...r)))}return ut(...t)}function U0(e,t){let r=jn.createSign("SHA256");r.update(e);let n=r.sign(t);return ut(e,gy(Ze.SHA256_WITH_RSA),dy(n))}function K0(e,t){let r=e.toString("base64"),n=[];for(let i=0;i<r.length;i+=64)n.push(r.slice(i,i+64));return`-----BEGIN ${t}-----
|
|
183
|
+
${n.join(`
|
|
127
184
|
`)}
|
|
128
185
|
-----END ${t}-----
|
|
129
|
-
`}function
|
|
130
|
-
`);for(let s of
|
|
131
|
-
`);
|
|
132
|
-
`).some((i)=>{let n=i.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!n&&n[1].toUpperCase()===r}))return A(k.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return A(k.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(r){return A(k.TRUST,`Error checking certificate trust: ${r}`,t),!1}}async function du(e,t,r){A(k.TRUST,`Adding certificate to system trust store with options: ${Ao(r)}`,r?.verbose),A(k.TRUST,"Storing certificate and private key",r?.verbose);let i=Kg(e,r);A(k.TRUST,"Storing CA certificate",r?.verbose);let n=Hg(t,r),s=Co.platform();A(k.TRUST,`Detected platform: ${s}`,r?.verbose);let o=c0[s];if(!o){let c=`Unsupported platform: ${s}`;throw A(k.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await o.addCertificate(n,r),A(k.TRUST,"Certificate successfully added to system trust store",r?.verbose),i}var ox,Fm=30000,So,_m="https://acme-staging-v02.api.letsencrypt.org/directory",jm="https://acme-v02.api.letsencrypt.org/directory",so,hx="1.2.840.10045.2.1",dx="1.2.840.10045.3.1.7",mx="1.2.840.10045.4.3.2",gx="2.5.4.3",px="1.2.840.113549.1.9.14",yx="2.5.29.17",fo,Jl,cC,lC=(e)=>e,fC=(e,t)=>{for(var r in t)cC(e,r,{get:t[r],enumerable:!0,configurable:!0,set:uC.bind(t,r)})},hC=(e,t)=>()=>(e&&(t=e(e=0)),t),Zm,cg,$i,un,lg,_C,jC,wm,to,Ll,Ne,ee,UC,vm,WC,bm,KC,HC,Sl,VC,$m,xm,El,YC,zC,GC,qC,ro,ug,JC,De,XC,QC,Cm,io,Ml,ve,j,ZC,Sm,eS,Em,tS,rS,Tl,iS,Tm,Pm,nS,Pl,sS,oS,aS,cS,lS,no,fg,uS,fS="0.15.6",tt,yo,an,Il,_l,wo,jl,Ul,cn,Wl,Kl,hr,hg,dg,xt,Gt,mg,gg,hS,mS,pg,vo,QO,Ee,H,ZO,pS,eN,yS,tN,rN,Rm,iN,wS,vS,nN,Am,sN,oN,aN,cN,lN,Rl,bS,uN,Et,wg,bo,vg,bg,nu,$g,xg,$o,Cg,Sg,xi,PS,Kt,fN,hN,dN,Og,fe,Ct,k,bi,NS,km="[redacted]",DS,FS,St,ze,s0,o0,a0,c0;var Yg=Q(()=>{ox=sx(import.meta.url);So=new sn;so=class so extends Error{problem;httpStatus;constructor(e,t,r){super(e);this.name="AcmeError",this.problem=t,this.httpStatus=r}};fo=new Xm,Jl=new Qm,cC=Object.defineProperty;Zm={};fC(Zm,{withErrorRecovery:()=>rg,tryLoadConfig:()=>BC,loadConfigWithResult:()=>DC,loadConfig:()=>ag,isRetryableError:()=>PC,isConfigNotFoundError:()=>TC,isBunfigError:()=>ig,globalPerformanceMonitor:()=>un,globalCache:()=>$i,getEnvOrDefault:()=>RC,generateConfigTypes:()=>LC,defaultGeneratedDir:()=>gg,defaultConfigDir:()=>mg,deepMergeWithArrayStrategy:()=>tu,deepMerge:()=>ng,createLibraryConfig:()=>MC,config:()=>FC,bunfigPlugin:()=>IC,applyEnvVarsToConfig:()=>rn,TypeGenerationError:()=>Ul,SchemaValidationError:()=>cn,PluginError:()=>Kl,PerformanceMonitor:()=>Ql,FileSystemError:()=>jl,ErrorFactory:()=>hr,EnvVarError:()=>wo,EnvProcessor:()=>To,ConfigValidator:()=>ru,ConfigValidationError:()=>Il,ConfigNotFoundError:()=>yo,ConfigMergeError:()=>_l,ConfigLoader:()=>iu,ConfigLoadError:()=>an,ConfigFileLoader:()=>Po,ConfigCache:()=>Xl,CacheUtils:()=>lg,BunfigError:()=>tt,BrowserConfigError:()=>Wl,ArrayMergeStrategies:()=>hg});hS=hC(async()=>{cg=import.meta.require,$i=new Xl,un=new Ql,lg={createKey:dC,isEquivalent:mC,estimateMemoryUsage:gC},_C=lo(Fl.cwd(),"config"),jC=lo(Fl.cwd(),"src/generated"),wm=co.env.CLARITY_LOG_DIR||Rx(wC(),"logs"),to={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wm,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ll=await vC(),Ne={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},ee=Ne,UC=Ne.red,vm=Ne.green,WC=Ne.yellow,bm=Ne.blue,KC=Ne.magenta,HC=Ne.cyan,Sl=Ne.white,VC=Ne.gray,$m=Ne.bgRed,xm=Ne.bgYellow,El=Ne.bold,YC=Ne.dim,zC=Ne.italic,GC=Ne.underline,qC=Ne.reset,ro={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ug={debug:"\uD83D\uDD0D",info:bm("ℹ"),success:vm("✓"),warning:xm(Sl(El(" WARN "))),error:$m(Sl(El(" ERROR ")))},JC=new mo("stacks"),De=new mo("bunfig",{showTags:!0}),XC=Ve(on.cwd(),"config"),QC=Ve(on.cwd(),"src/generated"),Cm=ao.env.CLARITY_LOG_DIR||Tx(CC(),"logs"),io={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Cm,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ml=await SC(),ve={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},j=ve,ZC=ve.red,Sm=ve.green,eS=ve.yellow,Em=ve.blue,tS=ve.magenta,rS=ve.cyan,Tl=ve.white,iS=ve.gray,Tm=ve.bgRed,Pm=ve.bgYellow,nS=ve.bgGray,Pl=ve.bold,sS=ve.dim,oS=ve.italic,aS=ve.underline,cS=ve.strikethrough,lS=ve.reset,no={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fg={debug:"\uD83D\uDD0D",info:Em("ℹ"),success:Sm("✓"),warning:Pm(Tl(Pl(" WARN "))),error:Tm(Tl(Pl(" ERROR ")))},uS=new po("stacks"),tt=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},yo=class extends tt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},an=class extends tt{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Il=class extends tt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},_l=class extends tt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},wo=class extends tt{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},jl=class extends tt{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Ul=class extends tt{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},cn=class extends tt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Wl=class extends tt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},Kl=class extends tt{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},hr={configNotFound(e,t,r){return new yo(e,t,r)},configLoad(e,t,r){return new an(e,t,r)},configValidation(e,t,r){return new Il(e,t,r)},configMerge(e,t,r,i){return new _l(e,t,r,i)},envVar(e,t,r,i){return new wo(e,t,r,i)},fileSystem(e,t,r){return new jl(e,t,r)},typeGeneration(e,t,r){return new Ul(e,t,r)},schemaValidation(e,t,r){return new cn(e,t,r)},browserConfig(e,t,r,i){return new Wl(e,t,r,i)},plugin(e,t,r){return new Kl(e,t,r)}},hg={replace:"replace",concat:"concat",smart:"smart"},dg=/^https?:\/\//,xt=new po("bunfig",{showTags:!0}),Gt=new iu,mg=Ye(Fr.cwd(),"config"),gg=Ye(Fr.cwd(),"src/generated")});mS=uo.env.CLARITY_LOG_DIR||Jx(dS(),"logs"),pg={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:mS,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},vo={...pg},QO=(async()=>{try{let{loadConfig:e}=await hS().then(()=>Zm),t=await e({name:"clarity",alias:"logging",defaultConfig:pg,cwd:uo.cwd()});if(t)Object.assign(vo,t)}catch{}return vo})();Ee={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},H=Ee,ZO=Ee.red,pS=Ee.green,eN=Ee.yellow,yS=Ee.blue,tN=Ee.magenta,rN=Ee.cyan,Rm=Ee.white,iN=Ee.gray,wS=Ee.bgRed,vS=Ee.bgYellow,nN=Ee.bgGray,Am=Ee.bold,sN=Ee.dim,oN=Ee.italic,aN=Ee.underline,cN=Ee.strikethrough,lN=Ee.reset,Rl={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bS={debug:"\uD83D\uDD0D",info:yS("ℹ"),success:pS("✓"),warning:vS(Rm(Am(" WARN "))),error:wS(Rm(Am(" ERROR ")))};uN=new Ro("stacks");Et=class Et extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};wg=class wg extends Et{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};bo=class bo extends Et{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};vg=class vg extends Et{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};bg=class bg extends Et{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}};nu=class nu extends Et{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}};$g=class $g extends Et{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};xg=class xg extends Et{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};$o=class $o extends Et{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Cg=class Cg extends Et{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}};Sg=class Sg extends Et{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};xi={configNotFound(e,t,r){return new wg(e,t,r)},configLoad(e,t,r){return new bo(e,t,r)},configValidation(e,t,r){return new vg(e,t,r)},configMerge(e,t,r,i){return new bg(e,t,r,i)},envVar(e,t,r,i){return new nu(e,t,r,i)},fileSystem(e,t,r){return new $g(e,t,r)},typeGeneration(e,t,r){return new xg(e,t,r)},schemaValidation(e,t,r){return new $o(e,t,r)},browserConfig(e,t,r,i){return new Cg(e,t,r,i)},plugin(e,t,r){return new Sg(e,t,r)}};PS=/^https?:\/\//;Kt=new Ro("bunfig",{showTags:!0});fN=new kg;hN=dt(Eo.cwd(),"config"),dN=dt(Eo.cwd(),"src/generated"),Og={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:ll.join(cl.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:ll.join(cl.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:ll.join(cl.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},fe=Og,Ct={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"},k={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},bi={info:(...e)=>console.log(...e),warn:(...e)=>console.warn(...e),success:(...e)=>console.log(...e),error:(...e)=>console.error(...e),debug:(...e)=>console.debug(...e)};NS=OS(AS);DS=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),FS=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;St={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},ze={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"};s0={platform:"darwin",async addCertificate(e,t){if(await n0(e,t?.verbose)){A(k.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),bi.success("Certificate is already trusted in system keychain");return}A(k.TRUST,"Adding certificate to macOS keychain",t?.verbose),await fr(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${e}`)},async removeCertificate(e,t,r){let i=r||fe.commonName;A(k.TRUST,`Removing certificate ${i} from macOS keychain`,t?.verbose);try{await fr(`sudo security delete-certificate -c "${i}" /Library/Keychains/System.keychain`),A(k.TRUST,`Removed certificate ${i} from macOS keychain`,t?.verbose)}catch(n){throw A(k.TRUST,`Error removing certificate: ${n}`,t?.verbose),n}}},o0={platform:"win32",async addCertificate(e,t){A(k.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await fr(`certutil -f -v -addstore -enterprise Root ${e}`)},async removeCertificate(e,t,r){let i=r||fe.commonName;A(k.TRUST,`Removing certificate ${i} from Windows certificate store`,t?.verbose);try{await fr(`certutil -delstore -enterprise Root "${i}"`),A(k.TRUST,`Removed certificate ${i} from Windows certificate store`,t?.verbose)}catch(n){throw A(k.TRUST,`Error removing certificate: ${n}`,t?.verbose),n}}},a0={platform:"linux",async addCertificate(e,t){A(k.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let r=Co.homedir(),i=Ct.LINUX_CERT_DB_FILENAME,n=Ct.LINUX_TRUST_ARGS;A(k.TRUST,`Searching for certificate databases in ${r}`,t?.verbose);let s=Yl(r,i);if(s.length===0){bi.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let o of s){A(k.TRUST,`Processing certificate database in ${o}`,t?.verbose);try{A(k.TRUST,`Attempting to delete existing cert for ${fe.commonName}`,t?.verbose),await fr(`certutil -d sql:${o} -D -n ${fe.commonName}`)}catch(c){A(k.TRUST,`Warning: Error deleting existing cert: ${c}`,t?.verbose),console.warn(`Error deleting existing cert: ${c}`)}A(k.TRUST,`Adding new certificate to ${o}`,t?.verbose),await fr(`certutil -d sql:${o} -A -t ${n} -n ${fe.commonName} -i ${e}`),bi.info(`Cert added to ${o}`)}},async removeCertificate(e,t,r){let i=r||fe.commonName;A(k.TRUST,`Removing certificate ${i} from Linux certificate store`,t?.verbose);let n=Co.homedir(),s=Ct.LINUX_CERT_DB_FILENAME;A(k.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let o=Yl(n,s);if(o.length===0){bi.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of o){A(k.TRUST,`Processing certificate database in ${c}`,t?.verbose);try{await fr(`certutil -d sql:${c} -D -n "${i}"`),bi.info(`Cert removed from ${c}`)}catch(a){A(k.TRUST,`Error removing cert from ${c}: ${a}`,t?.verbose),console.warn(`Error removing cert from ${c}: ${a}`)}}}},c0={darwin:s0,win32:o0,linux:a0}});var No=Q(()=>{Yg()});function Br(e){try{return Oo(e)}catch{return null}}function mu(e){try{return fu(e)||null}catch{return null}}function gu(e,t){try{return t.every((r)=>hu(e,r))}catch{return!1}}var Do=Q(()=>{No()});import{existsSync as zg,statSync as Gg}from"fs";import{existsSync as Fu,mkdirSync as g0,readdirSync as p0,writeFileSync as y0}from"fs";import{homedir as Si}from"os";import{dirname as qg,resolve as qe}from"path";import Lr from"process";import{join as w0,relative as v0,resolve as Jg}from"path";import Jo from"process";import{existsSync as Np,mkdirSync as yD,readdirSync as wD,writeFileSync as vD}from"fs";import{homedir as pu}from"os";import{dirname as xD,resolve as Ge}from"path";import hn from"process";import{join as b0,relative as $0,resolve as Xg}from"path";import Xo from"process";import{existsSync as Dp,mkdirSync as PD,readdirSync as RD,writeFileSync as AD}from"fs";import{dirname as OD,resolve as Qo}from"path";import Bu from"process";import{Buffer as mr}from"buffer";import{createCipheriv as x0,createDecipheriv as C0,randomBytes as yu}from"crypto";import{closeSync as wu,createReadStream as Qg,createWriteStream as S0,existsSync as vu,fsyncSync as Zg,openSync as ep,writeFileSync as E0}from"fs";import{access as T0,constants as tp,mkdir as P0,readdir as Fo,rename as rp,stat as Ei,unlink as Bo,writeFile as bu}from"fs/promises";import{join as Ti}from"path";import Fe from"process";import{pipeline as R0}from"stream/promises";import{createGzip as ip}from"zlib";import Pi from"process";import Xt from"process";import{Buffer as qt}from"buffer";import{createCipheriv as A0,createDecipheriv as k0,randomBytes as $u}from"crypto";import{closeSync as xu,createReadStream as np,createWriteStream as O0,existsSync as Lo,fsyncSync as sp,openSync as op,writeFileSync as N0}from"fs";import{access as D0,constants as ap,mkdir as F0,readdir as Mo,rename as cp,stat as Ri,unlink as Io,writeFile as Cu}from"fs/promises";import{isAbsolute as B0,join as Ai,resolve as L0}from"path";import L from"process";import{pipeline as M0}from"stream/promises";import{createGzip as lp}from"zlib";import ki from"process";import Qt from"process";import _o from"process";import{existsSync as jo}from"fs";import{resolve as Su}from"path";import{existsSync as I0}from"fs";import{existsSync as _0,readdirSync as j0}from"fs";import{extname as Eu,resolve as up}from"path";import U0 from"process";import{join as WE,relative as KE,resolve as xp}from"path";import sa from"process";import{Buffer as Jt}from"buffer";import{createCipheriv as YE,createDecipheriv as zE,randomBytes as ku}from"crypto";import{closeSync as Ou,createReadStream as Cp,createWriteStream as GE,existsSync as Wo,fsyncSync as Sp,openSync as Ep,writeFileSync as qE}from"fs";import{access as JE,constants as Tp,mkdir as XE,readdir as Ko,rename as Pp,stat as Oi,unlink as Ho,writeFile as Nu}from"fs/promises";import{isAbsolute as QE,join as Ni,resolve as ZE}from"path";import M from"process";import{pipeline as eT}from"stream/promises";import{createGzip as Rp}from"zlib";import Di from"process";import Zt from"process";function h0(e,t){this[e]=f0.bind(null,t)}class Vu{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!zg(e))return!0;return Gg(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=zg(r)?Gg(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Yu{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function W0(e,t={}){let i=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return i?`${e}:${i}`:e}function K0(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function H0(e){return e.getStats().size*2}function zu(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&se(t[0])&&"id"in t[0]&&t[0].id===3&&se(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(se(t)&&se(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(se(e)&&"arr"in e&&Array.isArray(e.arr)&&se(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&se(t[0])&&se(e[0])){let i=[...t];for(let n of e)if(se(n)&&"name"in n){if(!i.find((o)=>se(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(se(n)&&"path"in n){if(!i.find((o)=>se(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>Zo(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!se(t)||!se(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(se(n)&&se(r[i]))r[i]=zu(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&se(n[0])&&se(r[i][0])){let s=[...n];for(let o of r[i])if(se(o)&&"name"in o){if(!s.find((a)=>se(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(se(o)&&"path"in o){if(!s.find((a)=>se(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Zo(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function Zo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Zo(e[r],t[r]))return!1;return!0}if(se(e)&&se(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Zo(e[n],t[n]))return!1}return!0}return!1}function se(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function V0(e,t){if(!Dp(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return zu(t,i)}catch{return null}}catch{return null}}async function Y0({name:e="",cwd:t,defaultConfig:r}){let i=t||Bu.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of n){let a=Qo(i,`${o}${c}`),l=await V0(a,r);if(l!==null)return l}try{let o=Qo(i,"package.json");if(Dp(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return zu(r,a)}catch{}}}catch{}return r}function z0(e,t={}){let r=Xo.cwd();while(r.includes("storage"))r=Xg(r,"..");let i=Xg(r,e||"");if(t?.relative)return $0(Xo.cwd(),i);return i}async function G0(){try{let e=await Y0({name:"clarity",defaultConfig:Yo,cwd:Xo.cwd(),endpoint:"",headers:{}});return{...Yo,...e}}catch{return Yo}}function le(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function q0(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Xt<"u"){let e=Xt.type;if(e==="renderer"||e==="worker")return!1;return!!(Xt.versions&&(Xt.versions.node||Xt.versions.bun))}return!1}class Fp{async format(e){let t=await q0(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Pi.pid,hostname:t(),environment:Pi.env.NODE_ENV||"development",platform:Pi.platform,version:Pi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Pi.env.NODE_ENV||Pi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ea{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(e,t={}){this.name=e,this.config={...Mu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Fp,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Fe.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...zo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...zo};return{...zo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Mu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await T0(this.config.logDirectory,tp.F_OK|tp.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await P0(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:mr.from(e);try{if(!vu(this.currentLogFile))await bu(this.currentLogFile,"",{mode:420});if(n=ep(this.currentLogFile,"a",420),E0(n,a,{flag:"a"}),Zg(n),n!==void 0)wu(n),n=void 0;if((await Ei(this.currentLogFile)).size===0){if(await bu(this.currentLogFile,a,{flag:"w",mode:420}),(await Ei(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{wu(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ti(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Ti(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ti(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(le())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return yu(16).toString("hex")}generateKey(){return yu(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=yu(16),i=x0("aes-256-gcm",t,r),n=mr.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:mr.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=ip(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(mr.from(mr.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(le())return;let e=await Ei(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Fo(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Ei(r).catch(()=>null))try{if(await rp(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Bo(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await bu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Ei(r).catch(()=>null))await rp(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await Fo(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Bo(Ti(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Qg(e),i=S0(t),n=ip();await R0(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),vu(this.currentLogFile))try{let e=ep(this.currentLogFile,"r+");Zg(e),wu(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!le()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Fo(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Bo(Ti(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?te.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=Fe.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${te.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!le()){let l=Hp[e],u=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:te.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:te.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
|
|
133
|
-
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:te.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!le()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
186
|
+
`}function kf(){let e=jn.randomBytes(20);return e[0]=e[0]&127||1,e}function py(e=2048){let{privateKey:t,publicKey:r}=jn.generateKeyPairSync("rsa",{modulusLength:e});return{privateKey:t,publicKey:r}}function W0(e){let t=e.export({type:"spki",format:"der"});return jn.createHash("sha1").update(t).digest()}function yy(e){let t={serialNumber:e.serialNumber||kf(),notBefore:e.notBefore,notAfter:e.notAfter,subject:e.subject,issuer:e.issuer||e.subject,publicKey:e.publicKey,extensions:{basicConstraints:{isCA:e.isCA??!1,critical:!0,pathLenConstraint:e.pathLenConstraint},subjectKeyIdentifier:W0(e.publicKey)}};if(e.keyUsage)t.extensions.keyUsage={...e.keyUsage,critical:!0};if(e.extendedKeyUsage)t.extensions.extendedKeyUsage=e.extendedKeyUsage;if(e.subjectAltName?.length)t.extensions.subjectAltName=e.subjectAltName;let r=j0(t),n=U0(r,e.signingKey);return{certificate:K0(n,"CERTIFICATE"),certificateDer:n}}function wy(e){return e.export({type:"pkcs8",format:"pem"})}function V0(e){return jn.createPrivateKey(e)}function H0(e){let t=new jn.X509Certificate(e),r=t.publicKey,n=[],i=t.subject.split(`
|
|
187
|
+
`);for(let s of i){let[o,...c]=s.split("="),a=c.join("=");if(o&&a)n.push({shortName:o.trim(),value:a.trim()})}return{publicKey:r,subject:n}}async function Vi(e={}){C("ca","Creating new Root CA Certificate",e.verbose);let t=e.keySize||lt.DEFAULT_KEY_SIZE;C("ca",`Generating ${t}-bit RSA key pair`,e.verbose);let{privateKey:r,publicKey:n}=py(t),i=[{shortName:"C",value:e.countryName||B.countryName},{shortName:"ST",value:e.stateName||B.stateName},{shortName:"L",value:e.localityName||B.localityName},{shortName:"O",value:e.organization||"Local Development CA"},{shortName:"OU",value:e.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:e.commonName||"Local Development Root CA"}],{notBefore:s,notAfter:o}=ba({validityYears:e.validityYears||lt.DEFAULT_CA_VALIDITY_YEARS,verbose:e.verbose}),{certificate:c}=yy({serialNumber:kf(),notBefore:s,notAfter:o,subject:i,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:wy(r),notBefore:s,notAfter:o}}async function Un(e){if(C("ca","Generating new certificate",e.verbose),C("ca",`Options: ${Wi(e)}`,e.verbose),!e.domain&&!e.domains?.length)throw Error("Either domain or domains must be specified");if(!e.rootCA?.certificate||!e.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=H0(e.rootCA.certificate),r=V0(e.rootCA.privateKey);C("ca",`Generating ${lt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,e.verbose);let n=lt.DEFAULT_KEY_SIZE,{privateKey:i,publicKey:s}=py(n),o=e.commonName||Cf(e),c=e.certificateAttributes||[{shortName:"C",value:e.countryName||B.countryName},{shortName:"ST",value:e.stateName||B.stateName},{shortName:"L",value:e.localityName||B.localityName},{shortName:"O",value:e.organizationName||B.organizationName},{shortName:"CN",value:o}],{notBefore:a,notAfter:l}=ba({validityDays:e.validityDays||lt.DEFAULT_VALIDITY_DAYS,verbose:e.verbose}),u=va(e),f=e.keyUsage||{digitalSignature:!0,keyEncipherment:!0},h=e.extKeyUsage||{serverAuth:!0},{certificate:d}=yy({serialNumber:kf(),notBefore:a,notAfter:l,subject:c,issuer:t,publicKey:s,signingKey:r,isCA:e.basicConstraints?.cA??!1,pathLenConstraint:e.basicConstraints?.pathLenConstraint,keyUsage:f,extendedKeyUsage:h,subjectAltName:u});return{certificate:d,privateKey:wy(i),notBefore:a,notAfter:l}}function Of(e){let t={};for(let r of e.split(`
|
|
188
|
+
`)){let n=r.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf("=");if(i===-1)continue;let s=n.slice(0,i).trim(),o=n.slice(i+1).trim();if(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))o=o.slice(1,-1);t[s]=o}return t}function Nf(e){let t=Of(e),r=[t.ID??"",...(t.ID_LIKE??"").split(/\s+/)].map((n)=>n.trim().toLowerCase()).filter(Boolean);for(let n of r){if(G0.has(n))return"debian";if(q0.has(n))return"rhel";if(Y0.has(n))return"arch"}return"unknown"}function $a(e="/"){for(let t of["/etc/os-release","/usr/lib/os-release"]){let r=Ln.join(e,t);if(!Lt.existsSync(r))continue;try{let n=Nf(Lt.readFileSync(r,"utf8"));if(n!=="unknown")return n}catch{}}for(let t of Object.values(Kn))if(Lt.existsSync(Ln.join(e,t.anchorDir)))return t.family;return"unknown"}function Ca(e){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tlsx-root-ca"}.crt`}function Df(e="/"){let t=new Set;for(let r of Object.values(Kn))for(let n of r.bundles){if(t.has(n))continue;t.add(n);let i=Ln.join(e,n);if(Lt.existsSync(i))return i}return}function xa(e,t="/"){let r=Df(t);if(!r)return!1;try{let n=Mn(e);return Sf(Lt.readFileSync(r,"utf8"),n)}catch{return!1}}function Ei(e){return`'${e.replace(/'/g,"'\\''")}'`}function vy(e){return{root:e.root??"/",exec:e.exec??((t)=>it(t)),isRoot:e.isRoot??z0.getuid?.()===0}}function J0(e){try{return _n(e)||B.commonName}catch{return B.commonName}}async function Ff(e,t={}){let{root:r,exec:n,isRoot:i}=vy(t),s=$a(r),o=[];if(C(S.TRUST,`Linux distro family: ${s} (root=${r}, isRoot=${i})`,t.verbose),s==="unknown")return{family:s,commands:o,status:"unsupported",error:"could not detect a supported distro family from /etc/os-release (debian, rhel or arch)"};let c=Kn[s],a=Ln.join(r,c.anchorDir),l=Ln.join(a,Ca(t.name??J0(e))),u={family:s,anchorPath:l,updateCommand:c.updateCommand,commands:o};if(xa(e,r))return C(S.TRUST,"CA already present in the system bundle, not rerunning the update",t.verbose),{...u,status:"already-trusted"};try{if(i)Lt.mkdirSync(a,{recursive:!0}),Lt.copyFileSync(e,l),Lt.chmodSync(l,420),o.push(c.updateCommand),C(S.TRUST,`Wrote ${l}; running ${c.updateCommand}`,t.verbose),await n(c.updateCommand);else{let f=[`sudo mkdir -p ${Ei(a)}`,`sudo cp ${Ei(e)} ${Ei(l)}`,`sudo chmod 644 ${Ei(l)}`,`sudo ${c.updateCommand}`].join(" && ");o.push(f),C(S.TRUST,`Running: ${f}`,t.verbose),await n(f)}return{...u,status:"installed"}}catch(f){return C(S.TRUST,`System trust store install failed: ${f}`,t.verbose),{...u,status:"failed",error:f instanceof Error?f.message:String(f)}}}async function Lf(e,t={}){let{root:r,exec:n,isRoot:i}=vy(t),s=$a(r),o=[];if(s==="unknown")return{family:s,commands:o,status:"unsupported",error:"could not detect a supported distro family"};let c=Kn[s],a=Ln.join(r,c.anchorDir,Ca(e)),l={family:s,anchorPath:a,updateCommand:c.updateCommand,commands:o};if(!Lt.existsSync(a))return{...l,status:"not-found"};try{if(i)Lt.unlinkSync(a),o.push(c.updateCommand),await n(c.updateCommand);else{let u=`sudo rm -f ${Ei(a)} && sudo ${c.updateCommand}`;o.push(u),await n(u)}return{...l,status:"removed"}}catch(u){return{...l,status:"failed",error:u instanceof Error?u.message:String(u)}}}function Bf(e,t){C(S.STORAGE,`Storing certificate and private key with options: ${Wi(t)}`,t?.verbose);let{certPath:r,keyPath:n}=In({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});C(S.STORAGE,`Certificate path: ${r}`,t?.verbose),C(S.STORAGE,`Private key path: ${n}`,t?.verbose);let i=zu.dirname(r);if(!er.existsSync(i))C(S.STORAGE,`Creating certificate directory: ${i}`,t?.verbose),er.mkdirSync(i,{recursive:!0});C(S.STORAGE,"Writing certificate file",t?.verbose),er.writeFileSync(r,e.certificate);let s=zu.dirname(n);if(!er.existsSync(s))C(S.STORAGE,`Creating private key directory: ${s}`,t?.verbose),er.mkdirSync(s,{recursive:!0});return C(S.STORAGE,"Writing private key file",t?.verbose),er.writeFileSync(n,e.privateKey),C(S.STORAGE,"Certificate and private key stored successfully",t?.verbose),r}function Sa(e,t){C(S.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:r}=In({basePath:t?.basePath,caCertPath:t?.caCertPath});C(S.STORAGE,`CA certificate path: ${r}`,t?.verbose);let n=zu.dirname(r);if(!er.existsSync(n))C(S.STORAGE,`Creating CA certificate directory: ${n}`,t?.verbose),er.mkdirSync(n,{recursive:!0});return C(S.STORAGE,"Writing CA certificate file",t?.verbose),er.writeFileSync(r,e),C(S.STORAGE,"CA certificate stored successfully",t?.verbose),r}function Bn(e,t){return{platform:e,stores:t,trusted:t.some((r)=>r.status==="installed"||r.status==="already-trusted")}}async function If(e,t,r){let n=Bt.platform();if(n==="linux"){let i=xa(e,r?.root);return C(S.TRUST,i?"Certificate found in the system CA bundle":"Certificate not in the system CA bundle",t),i}if(n!=="darwin")return!1;try{let i=Mn(e);if(!i)return C(S.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(X0("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
189
|
+
`).some((s)=>{let o=s.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!o&&o[1].toUpperCase()===i}))return C(S.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return C(S.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(i){return C(S.TRUST,`Error checking certificate trust: ${i}`,t),!1}}async function by(e,t){return If(e,t?.verbose,t?.linux)}async function Ea(e,t,r){C(S.TRUST,`Adding certificate to system trust store with options: ${Wi(r)}`,r?.verbose),C(S.TRUST,"Storing certificate and private key",r?.verbose);let n=Bf(e,r);C(S.TRUST,"Storing CA certificate",r?.verbose);let i=Sa(t,r),s=Bt.platform();C(S.TRUST,`Detected platform: ${s}`,r?.verbose);let o=Wn[s];if(!o){let c=`Unsupported platform: ${s}`;throw C(S.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await o.addCertificate(i,r),C(S.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}async function $y(e,t){let r=Bt.platform();C(S.TRUST,`Adding ${e} to the ${r} trust store`,t?.verbose);let n=Wn[r];if(!n)throw Error(`Unsupported platform: ${r}`);return n.addCertificate(e,t)}async function Cy(e,t,r){C(S.TRUST,`Removing certificate for ${e} from system trust store`,t?.verbose);let n=t?.caCertPath||B.caCertPath,i=r||B.commonName,s=Bt.platform();C(S.TRUST,`Detected platform: ${s}`,t?.verbose);let o=Wn[s];if(!o){let c=`Unsupported platform: ${s}`;throw C(S.TRUST,`Error: ${c}`,t?.verbose),Error(c)}if(!o.removeCertificate)throw Error(`Removing certificates is not supported on ${s}`);await o.removeCertificate(n,t,i),C(S.TRUST,`Certificate for ${e} successfully removed from system trust store`,t?.verbose)}async function xy(e,t){let r=e?.verbose||B.verbose;C(S.TRUST,"Cleaning up all TLSX certificates from system trust store",r);let n=Bt.platform();C(S.TRUST,`Detected platform: ${n}`,r);let i=Wn[n];if(!i){let s=`Unsupported platform: ${n}`;throw C(S.TRUST,`Error: ${s}`,r),Error(s)}if(!i.removeCertificate)throw Error(`Removing certificates is not supported on ${n}`);try{if(n==="darwin"){C(S.TRUST,"Removing all TLSX certificates from macOS keychain",r);let s=t||B.commonName;await it(`sudo security find-certificate -a -c "${s}" -Z /Library/Keychains/System.keychain | grep SHA-1 | awk '{print $3}' | xargs -I {} sudo security delete-certificate -Z {} /Library/Keychains/System.keychain`),ie.success(`All certificates matching "${s}" removed from macOS keychain`)}else if(n==="win32"){C(S.TRUST,"Removing all TLSX certificates from Windows certificate store",r);let s=t||B.organizationName;await it(`certutil -delstore -enterprise Root "${s}"`),ie.success(`All certificates matching "${s}" removed from Windows certificate store`)}else if(n==="linux"){C(S.TRUST,"Removing all TLSX certificates from Linux certificate stores",r);let s=Bt.homedir(),o=lt.LINUX_CERT_DB_FILENAME;C(S.TRUST,`Searching for certificate databases in ${s}`,r);let c=Li(s,o);if(c.length===0){ie.warn("No certificate databases found. Cannot clean up certificates.");return}for(let a of c){C(S.TRUST,`Processing certificate database in ${a}`,r);try{let{stdout:l}=await it(`certutil -d sql:${a} -L`),u=l.split(`
|
|
190
|
+
`);for(let f of u)if(t?f.toLowerCase().includes(t.toLowerCase()):f.includes(B.organizationName)||f.includes("tlsx")||f.includes("Local Development")){let h=f.split(/\s+/)[0].trim();if(h){C(S.TRUST,`Removing certificate: ${h}`,r);try{await it(`certutil -d sql:${a} -D -n "${h}"`),ie.info(`Removed certificate ${h} from ${a}`)}catch(d){C(S.TRUST,`Error removing cert ${h}: ${d}`,r)}}}}catch(l){C(S.TRUST,`Error processing database ${a}: ${l}`,r),console.warn(`Error processing database ${a}: ${l}`)}}ie.success("All matching certificates removed from Linux certificate stores")}C(S.TRUST,"Trust store cleanup completed successfully",r)}catch(s){throw C(S.TRUST,`Error cleaning up trust store: ${s}`,r),Error(`Failed to clean up trust store: ${s}`)}}async function Ta(e){let t=e?.verbose??B.verbose,{caCertPath:r,basePath:n}=In({basePath:e?.basePath,caCertPath:e?.caCertPath}),i=r.replace(/\.crt$/,".key");C(S.TRUST,`installCA: caCertPath=${r}`,t),C(S.TRUST,`installCA: basePath=${n}`,t);let s=!1;if(!(Nn.existsSync(r)&&Nn.existsSync(i))){C(S.TRUST,"No existing Root CA found, generating one",t);let l=await Vi({...e?.ca,verbose:t});Sa(l.certificate,{...e,basePath:n,caCertPath:r}),Nn.writeFileSync(i,l.privateKey,{mode:384}),s=!0,ie.success(`Generated new Root CA at ${r}`)}else C(S.TRUST,"Reusing existing Root CA on disk",t),ie.info(`Using existing Root CA at ${r}`);let o=Bt.platform(),c=Wn[o];if(!c)throw Error(`installCA: unsupported platform: ${o}`);if(await If(r,t,e?.linux)){ie.success("Root CA is already trusted in the system store");let l=Bn(o,[{store:o==="linux"?"linux-system":"macos-keychain",location:o==="linux"?"system CA bundle":Ti,status:"already-trusted"}]);return{caCertPath:r,caKeyPath:i,generated:s,trustInstalled:!1,alreadyTrusted:!0,report:l}}let a=await c.addCertificate(r,e);if(a.trusted)ie.success("Root CA installed in the system trust store");else ie.warn("Root CA was not installed into any trust store; see the report for details");return{caCertPath:r,caKeyPath:i,generated:s,trustInstalled:a.trusted,alreadyTrusted:!1,report:a}}async function Sy(e){let t=e?.verbose??B.verbose,{caCertPath:r}=In({basePath:e?.basePath,caCertPath:e?.caCertPath}),n=r.replace(/\.crt$/,".key"),i=e?.certName;if(!i&&Nn.existsSync(r))try{i=_n(r)||void 0,C(S.TRUST,`uninstallCA: extracted CN from cert: ${i}`,t)}catch(l){C(S.TRUST,`uninstallCA: CN extraction failed: ${l}`,t)}i=i??B.commonName;let s=Bt.platform(),o=Wn[s];if(!o?.removeCertificate)throw Error(`uninstallCA: removing certificates is not supported on ${s}`);let c=!1;try{await o.removeCertificate(r,e,i),c=!0,ie.success(`Root CA "${i}" removed from the system trust store`)}catch(l){C(S.TRUST,`uninstallCA: handler.removeCertificate failed: ${l}`,t),ie.warn(`Could not remove Root CA from trust store: ${l.message}`)}let a=!1;if(e?.deleteFiles){for(let l of[r,n])try{if(Nn.existsSync(l))Nn.unlinkSync(l),C(S.TRUST,`uninstallCA: deleted ${l}`,t),a=!0}catch(u){C(S.TRUST,`uninstallCA: failed to delete ${l}: ${u}`,t)}if(a)ie.success("Removed CA cert + key from disk")}return{removedFromTrustStore:c,filesDeleted:a,caCertPath:r,caKeyPath:n}}var xi,ca=30000,Ui,Yu,Qu="https://acme-staging-v02.api.letsencrypt.org/directory",ef="https://acme-v02.api.letsencrypt.org/directory",ki,Yx="1.2.840.10045.2.1",Jx="1.2.840.10045.3.1.7",Xx="1.2.840.10045.4.3.2",Zx="2.5.4.3",Qx="1.2.840.113549.1.9.14",eS="2.5.29.17",lt,mp,S,Zo,lf,HS,zS=(e)=>e,qS=(e,t)=>{for(var r in t)HS(e,r,{get:t[r],enumerable:!0,configurable:!0,set:GS.bind(t,r)})},YS=(e,t)=>()=>(e&&(t=e(e=0)),t),vp,Ap,Dn,Ki,Rp,CE,xE,Gg,jo,Fu,je,ne,SE,qg,EE,Yg,TE,PE,Su,AE,Jg,Xg,Eu,RE,kE,OE,NE,Uo,kp,DE,Ue,FE,LE,Zg,Ko,Lu,Se,W,BE,Qg,IE,ep,ME,_E,Tu,jE,tp,rp,UE,Pu,KE,WE,VE,HE,zE,Wo,Op,GE,qE="0.15.6",ct,na,Di,Bu,Iu,ia,Mu,_u,Fi,ju,Uu,Cr,Np,Dp,Pt,tr,Fp,Lp,YE,XE,Bp,sa,aF,Oe,z,cF,QE,lF,e0,uF,fF,np,hF,t0,r0,dF,ip,mF,gF,pF,yF,wF,Au,n0,vF,Rt,Mp,oa,_p,jp,yf,Up,Kp,aa,Wp,Vp,Fn,u0,Ft,Ru,bF,$F,ma,ku=null,B,ie,g0,sp="[redacted]",p0,y0,$0,Tf,Pf,S0,wa="dev.stacksjs.tlsx",E0="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Af,At,Ze,Kn,G0,q0,Y0,Ti="/Library/Keychains/System.keychain",Z0,Q0,eT,Wn;var Ey=te(()=>{xi=Wx(import.meta.url);Ui=new Wr;Yu=class Yu extends Wr{webroot;written=new Set;constructor(e){super();this.webroot=e,xi("node:fs").mkdirSync(this.webroot,{recursive:!0})}filePath(e){let t=xi("node:path");return t.join(this.webroot,t.basename(e))}add(e,t){super.add(e,t),xi("node:fs").writeFileSync(this.filePath(e),t,"utf8"),this.written.add(e)}remove(e){super.remove(e);let t=xi("node:fs");try{t.unlinkSync(this.filePath(e))}catch{}this.written.delete(e)}cleanup(){for(let e of[...this.written])this.remove(e)}};ki=class ki extends Error{problem;httpStatus;constructor(e,t,r){super(e);this.name="AcmeError",this.problem=t,this.httpStatus=r}};lt={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"},mp={DEFAULT_CERT_DIR:".stacks/ssl",CERT_EXTENSION:".crt",KEY_EXTENSION:".crt.key",CA_CERT_EXTENSION:".ca.crt"},S={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"};Zo=new yp,lf=new wp,HS=Object.defineProperty;vp={};qS(vp,{withErrorRecovery:()=>Cp,tryLoadConfig:()=>wE,loadConfigWithResult:()=>pE,loadConfig:()=>Pp,isRetryableError:()=>uE,isConfigNotFoundError:()=>lE,isBunfigError:()=>xp,globalPerformanceMonitor:()=>Ki,globalCache:()=>Dn,getEnvOrDefault:()=>fE,generateConfigTypes:()=>vE,defaultGeneratedDir:()=>Lp,defaultConfigDir:()=>Fp,deepMergeWithArrayStrategy:()=>mf,deepMerge:()=>Sp,createLibraryConfig:()=>bE,config:()=>yE,bunfigPlugin:()=>$E,applyEnvVarsToConfig:()=>Si,TypeGenerationError:()=>_u,SchemaValidationError:()=>Fi,PluginError:()=>Uu,PerformanceMonitor:()=>ff,FileSystemError:()=>Mu,ErrorFactory:()=>Cr,EnvVarError:()=>ia,EnvProcessor:()=>fa,ConfigValidator:()=>gf,ConfigValidationError:()=>Bu,ConfigNotFoundError:()=>na,ConfigMergeError:()=>Iu,ConfigLoader:()=>pf,ConfigLoadError:()=>Di,ConfigFileLoader:()=>ha,ConfigCache:()=>uf,CacheUtils:()=>Rp,BunfigError:()=>ct,BrowserConfigError:()=>ju,ArrayMergeStrategies:()=>Np});YE=YS(async()=>{Ap=import.meta.require,Dn=new uf,Ki=new ff,Rp={createKey:JS,isEquivalent:XS,estimateMemoryUsage:ZS},CE=Jo(Nu.cwd(),"config"),xE=Jo(Nu.cwd(),"src/generated"),Gg=Yo.env.CLARITY_LOG_DIR||fS(tE(),"logs"),jo={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Gg,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Fu=await rE(),je={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},ne=je,SE=je.red,qg=je.green,EE=je.yellow,Yg=je.blue,TE=je.magenta,PE=je.cyan,Su=je.white,AE=je.gray,Jg=je.bgRed,Xg=je.bgYellow,Eu=je.bold,RE=je.dim,kE=je.italic,OE=je.underline,NE=je.reset,Uo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},kp={debug:"\uD83D\uDD0D",info:Yg("ℹ"),success:qg("✓"),warning:Xg(Su(Eu(" WARN "))),error:Jg(Su(Eu(" ERROR ")))},DE=new ea("stacks"),Ue=new ea("bunfig",{showTags:!0}),FE=Je(Ni.cwd(),"config"),LE=Je(Ni.cwd(),"src/generated"),Zg=qo.env.CLARITY_LOG_DIR||lS(oE(),"logs"),Ko={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Zg,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lu=await aE(),Se={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},W=Se,BE=Se.red,Qg=Se.green,IE=Se.yellow,ep=Se.blue,ME=Se.magenta,_E=Se.cyan,Tu=Se.white,jE=Se.gray,tp=Se.bgRed,rp=Se.bgYellow,UE=Se.bgGray,Pu=Se.bold,KE=Se.dim,WE=Se.italic,VE=Se.underline,HE=Se.strikethrough,zE=Se.reset,Wo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Op={debug:"\uD83D\uDD0D",info:ep("ℹ"),success:Qg("✓"),warning:rp(Tu(Pu(" WARN "))),error:tp(Tu(Pu(" ERROR ")))},GE=new ra("stacks"),ct=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},na=class extends ct{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},Di=class extends ct{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Bu=class extends ct{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Iu=class extends ct{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},ia=class extends ct{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Mu=class extends ct{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},_u=class extends ct{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Fi=class extends ct{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},ju=class extends ct{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},Uu=class extends ct{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Cr={configNotFound(e,t,r){return new na(e,t,r)},configLoad(e,t,r){return new Di(e,t,r)},configValidation(e,t,r){return new Bu(e,t,r)},configMerge(e,t,r,n){return new Iu(e,t,r,n)},envVar(e,t,r,n){return new ia(e,t,r,n)},fileSystem(e,t,r){return new Mu(e,t,r)},typeGeneration(e,t,r){return new _u(e,t,r)},schemaValidation(e,t,r){return new Fi(e,t,r)},browserConfig(e,t,r,n){return new ju(e,t,r,n)},plugin(e,t,r){return new Uu(e,t,r)}},Np={replace:"replace",concat:"concat",smart:"smart"},Dp=/^https?:\/\//,Pt=new ra("bunfig",{showTags:!0}),tr=new pf,Fp=Xe(Vr.cwd(),"config"),Lp=Xe(Vr.cwd(),"src/generated")});XE=Xo.env.CLARITY_LOG_DIR||DS(JE(),"logs"),Bp={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:XE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},sa={...Bp},aF=(async()=>{try{let{loadConfig:e}=await YE().then(()=>vp),t=await e({name:"clarity",alias:"logging",defaultConfig:Bp,cwd:Xo.cwd()});if(t)Object.assign(sa,t)}catch{}return sa})();Oe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},z=Oe,cF=Oe.red,QE=Oe.green,lF=Oe.yellow,e0=Oe.blue,uF=Oe.magenta,fF=Oe.cyan,np=Oe.white,hF=Oe.gray,t0=Oe.bgRed,r0=Oe.bgYellow,dF=Oe.bgGray,ip=Oe.bold,mF=Oe.dim,gF=Oe.italic,pF=Oe.underline,yF=Oe.strikethrough,wF=Oe.reset,Au={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},n0={debug:"\uD83D\uDD0D",info:e0("ℹ"),success:QE("✓"),warning:r0(np(ip(" WARN "))),error:t0(np(ip(" ERROR ")))};vF=new da("stacks");Rt=class Rt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};Mp=class Mp extends Rt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};oa=class oa extends Rt{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};_p=class _p extends Rt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};jp=class jp extends Rt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};yf=class yf extends Rt{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};Up=class Up extends Rt{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Kp=class Kp extends Rt{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};aa=class aa extends Rt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Wp=class Wp extends Rt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};Vp=class Vp extends Rt{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Fn={configNotFound(e,t,r){return new Mp(e,t,r)},configLoad(e,t,r){return new oa(e,t,r)},configValidation(e,t,r){return new _p(e,t,r)},configMerge(e,t,r,n){return new jp(e,t,r,n)},envVar(e,t,r,n){return new yf(e,t,r,n)},fileSystem(e,t,r){return new Up(e,t,r)},typeGeneration(e,t,r){return new Kp(e,t,r)},schemaValidation(e,t,r){return new aa(e,t,r)},browserConfig(e,t,r,n){return new Wp(e,t,r,n)},plugin(e,t,r){return new Vp(e,t,r)}};u0=/^https?:\/\//;Ft=new da("bunfig",{showTags:!0});Ru=new Jp;bF=wt(ua.cwd(),"config"),$F=wt(ua.cwd(),"src/generated"),ma={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:lu.join(cu.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:lu.join(cu.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:lu.join(cu.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};B=ma,ie={info:(...e)=>console.log(...e),warn:(...e)=>console.warn(...e),success:(...e)=>console.log(...e),error:(...e)=>console.error(...e),debug:(...e)=>console.debug(...e)};g0=m0(d0);p0=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),y0=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;$0=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g;Tf=["macos","ios","windows","debian","rhel","android","linux-nss"],Pf={pem:"application/x-pem-file",der:"application/x-x509-ca-cert",mobileconfig:"application/x-apple-aspen-config"},S0={pem:"pem",der:"cer",mobileconfig:"mobileconfig"};Af=_i(wa,E0);At={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},Ze={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"};Kn={debian:{family:"debian",anchorDir:"/usr/local/share/ca-certificates",updateCommand:"update-ca-certificates",bundles:["/etc/ssl/certs/ca-certificates.crt"]},rhel:{family:"rhel",anchorDir:"/etc/pki/ca-trust/source/anchors",updateCommand:"update-ca-trust",bundles:["/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"]},arch:{family:"arch",anchorDir:"/etc/ca-certificates/trust-source/anchors",updateCommand:"trust extract-compat",bundles:["/etc/ca-certificates/extracted/tls-ca-bundle.pem","/etc/ssl/certs/ca-certificates.crt"]}},G0=new Set(["debian","ubuntu","raspbian","linuxmint","pop","elementary","kali","neon","zorin","alpine"]),q0=new Set(["rhel","fedora","centos","rocky","almalinux","ol","oracle","amzn"]),Y0=new Set(["arch","archarm","manjaro","endeavouros","garuda"]);Z0={platform:"darwin",async addCertificate(e,t){if(await If(e,t?.verbose))return C(S.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),ie.success("Certificate is already trusted in system keychain"),Bn("darwin",[{store:"macos-keychain",location:Ti,status:"already-trusted"}]);return C(S.TRUST,"Adding certificate to macOS keychain",t?.verbose),await it(`sudo security add-trusted-cert -d -r trustRoot -k ${Ti} ${e}`),Bn("darwin",[{store:"macos-keychain",location:Ti,status:"installed"}])},async removeCertificate(e,t,r){let n=r||B.commonName;C(S.TRUST,`Removing certificate ${n} from macOS keychain`,t?.verbose);try{await it(`sudo security delete-certificate -c "${n}" ${Ti}`),C(S.TRUST,`Removed certificate ${n} from macOS keychain`,t?.verbose)}catch(i){throw C(S.TRUST,`Error removing certificate: ${i}`,t?.verbose),i}}},Q0={platform:"win32",async addCertificate(e,t){return C(S.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await it(`certutil -f -v -addstore -enterprise Root ${e}`),Bn("win32",[{store:"windows-root",location:"LocalMachine\\Root",status:"installed"}])},async removeCertificate(e,t,r){let n=r||B.commonName;C(S.TRUST,`Removing certificate ${n} from Windows certificate store`,t?.verbose);try{await it(`certutil -delstore -enterprise Root "${n}"`),C(S.TRUST,`Removed certificate ${n} from Windows certificate store`,t?.verbose)}catch(i){throw C(S.TRUST,`Error removing certificate: ${i}`,t?.verbose),i}}},eT={platform:"linux",async addCertificate(e,t){let r=t?.verbose,n=[];C(S.TRUST,"Adding certificate to the Linux system trust store",r);let i=await Ff(e,{...t?.linux,verbose:r}),s=i.anchorPath??"(no supported anchor directory)";if(i.status==="installed")ie.success(`Root CA installed into the ${i.family} system trust store (${i.anchorPath})`),n.push({store:"linux-system",location:s,status:"installed"});else if(i.status==="already-trusted")ie.success("Root CA is already in the system CA bundle"),n.push({store:"linux-system",location:s,status:"already-trusted"});else if(i.status==="failed")ie.warn(`Could not update the ${i.family} system trust store: ${i.error}`),n.push({store:"linux-system",location:s,status:"failed",detail:i.error});else C(S.TRUST,`System trust store skipped: ${i.error}`,r),n.push({store:"linux-system",location:s,status:"skipped",detail:i.error});let o=i.status==="installed"||i.status==="already-trusted",c=Bt.homedir(),a=lt.LINUX_CERT_DB_FILENAME,l=lt.LINUX_TRUST_ARGS;C(S.TRUST,`Searching for certificate databases in ${c}`,r);let u=Li(c,a);if(u.length===0){if(o)C(S.TRUST,"No NSS certificate databases found; the system store covers this host",r);else ie.warn("No certificate databases found and the system trust store was not updated. Certificate may not be trusted by the system.");return Bn("linux",n)}for(let f of u){C(S.TRUST,`Processing certificate database in ${f}`,r);try{C(S.TRUST,`Attempting to delete existing cert for ${B.commonName}`,r),await it(`certutil -d sql:${f} -D -n ${B.commonName}`)}catch(h){C(S.TRUST,`Warning: Error deleting existing cert: ${h}`,r),console.warn(`Error deleting existing cert: ${h}`)}C(S.TRUST,`Adding new certificate to ${f}`,r);try{await it(`certutil -d sql:${f} -A -t ${l} -n ${B.commonName} -i ${e}`),ie.info(`Cert added to ${f}`),n.push({store:"linux-nss",location:f,status:"installed"})}catch(h){if(!o)throw h;C(S.TRUST,`certutil failed for ${f}: ${h}`,r),n.push({store:"linux-nss",location:f,status:"failed",detail:h instanceof Error?h.message:String(h)})}}return Bn("linux",n)},async removeCertificate(e,t,r){let n=r||B.commonName;C(S.TRUST,`Removing certificate ${n} from Linux certificate store`,t?.verbose);let i=await Lf(n,{...t?.linux,verbose:t?.verbose});if(i.status==="removed")ie.info(`Removed ${i.anchorPath} from the ${i.family} system trust store`);else if(i.status==="failed")ie.warn(`Could not remove the CA from the system trust store: ${i.error}`);else C(S.TRUST,`System trust store removal: ${i.status}`,t?.verbose);let s=Bt.homedir(),o=lt.LINUX_CERT_DB_FILENAME;C(S.TRUST,`Searching for certificate databases in ${s}`,t?.verbose);let c=Li(s,o);if(c.length===0){ie.warn("No certificate databases found. Cannot remove certificate.");return}for(let a of c){C(S.TRUST,`Processing certificate database in ${a}`,t?.verbose);try{await it(`certutil -d sql:${a} -D -n "${n}"`),ie.info(`Cert removed from ${a}`)}catch(l){C(S.TRUST,`Error removing cert from ${a}: ${l}`,t?.verbose),console.warn(`Error removing cert from ${a}: ${l}`)}}}},Wn={darwin:Z0,win32:Q0,linux:eT}});var Mf={};nl(Mf,{AcmeClient:()=>Oi,AcmeError:()=>ki,CERT_CONSTANTS:()=>lt,DEFAULT_PROFILE_IDENTIFIER_PREFIX:()=>wa,DEFAULT_REQUEST_TIMEOUT_MS:()=>ca,EXPORT_MIME_TYPES:()=>Pf,FileHttp01Store:()=>Yu,Http01Store:()=>Wr,LETS_ENCRYPT_PRODUCTION_DIRECTORY:()=>ef,LETS_ENCRYPT_STAGING_DIRECTORY:()=>Qu,LINUX_DISTRO_STORES:()=>Kn,LOG_CATEGORIES:()=>S,PATH_CONSTANTS:()=>mp,PorkbunDnsProvider:()=>qu,TLSX_UUID_NAMESPACE:()=>Af,TRUST_PLATFORMS:()=>Tf,addCertToSystemTrustStore:()=>$y,addCertToSystemTrustStoreAndSaveCert:()=>Ea,base64urlDecode:()=>Ri,base64urlDecodeToString:()=>up,base64urlEncode:()=>Pi,buildCsr:()=>af,buildCsrBase64url:()=>cf,buildMobileConfig:()=>Rf,calculateValidityDates:()=>ba,certFileBase:()=>ey,cleanupTrustStore:()=>xy,config:()=>B,createRootCA:()=>Vi,debugLog:()=>C,defaultConfig:()=>ma,defaultHttp01Store:()=>Ui,derBitString:()=>zo,derContext:()=>Go,derInteger:()=>nf,derNull:()=>fp,derOctetString:()=>sf,derOid:()=>$r,derPrintableString:()=>hp,derSequence:()=>at,derSet:()=>Ho,derUtf8String:()=>of,detectLinuxDistroFamily:()=>Nf,dns01RecordName:()=>rf,exportCA:()=>ly,fetchWithTimeout:()=>kn,findFoldersWithFile:()=>Li,findLinuxCaBundle:()=>Df,generateCertificate:()=>Un,generateCertificateExtensions:()=>hy,generateRandomSerial:()=>fy,generateSubjectAltNames:()=>va,getCertCommonName:()=>_n,getCertSha256Fingerprint:()=>Mn,getCertificateFromCertPemOrPath:()=>nr,getConfig:()=>Xp,getPrimaryDomain:()=>Cf,getSudoPassword:()=>$f,installCA:()=>Ta,installCAIntoLinuxSystemStore:()=>Ff,isCertExpired:()=>iy,isCertTrusted:()=>by,isCertTrustedOnLinux:()=>xa,isCertValidForDomain:()=>ya,jwkFromKey:()=>Ju,jwkThumbprint:()=>Xu,linuxAnchorFileName:()=>Ca,listCertsInDirectory:()=>Qp,log:()=>ie,makeNumberPositive:()=>bf,normalizeCertPaths:()=>In,obtainCertificate:()=>la,parseCertDetails:()=>ny,parseOsRelease:()=>Of,pemBundleHasFingerprint:()=>Sf,pemToDer:()=>ga,readCertFromFile:()=>vf,readLinuxDistroFamily:()=>$a,redactSensitive:()=>Bi,removeCAFromLinuxSystemStore:()=>Lf,removeCertFromSystemTrustStore:()=>Cy,renewalOutputBase:()=>ty,runCommand:()=>it,safeStringify:()=>Wi,sha256FingerprintOfDer:()=>pa,signJws:()=>Zu,splitApexAndSubdomain:()=>Vo,splitPemCertificates:()=>xf,splitPemChain:()=>tf,storeCACertificate:()=>Sa,storeCertificate:()=>Bf,trustInstructions:()=>uy,uninstallCA:()=>Sy,uuidV5:()=>_i,validateBrowserCompatibility:()=>ay,validateCertificate:()=>oy,verifyServerChain:()=>Ef,waitForTxtRecord:()=>Gu,willCertExpireSoon:()=>sy});var Hi=te(()=>{Ey()});function Hr(e){try{return Mn(e)}catch{return null}}function _f(e){try{return _n(e)||null}catch{return null}}function jf(e,t){try{return t.every((r)=>ya(e,r))}catch{return!1}}var Pa=te(()=>{Hi()});import{existsSync as Ty,statSync as Py}from"fs";import{existsSync as sh,mkdirSync as oT,readdirSync as aT,writeFileSync as cT}from"fs";import{homedir as Vn}from"os";import{dirname as Ay,resolve as et}from"path";import zr from"process";import{join as lT,relative as uT,resolve as Ry}from"path";import Va from"process";import{existsSync as fw,mkdirSync as hL,readdirSync as dL,writeFileSync as mL}from"fs";import{homedir as Uf}from"os";import{dirname as yL,resolve as Qe}from"path";import Gi from"process";import{join as fT,relative as hT,resolve as ky}from"path";import Ha from"process";import{existsSync as hw,mkdirSync as CL,readdirSync as xL,writeFileSync as SL}from"fs";import{dirname as TL,resolve as za}from"path";import oh from"process";import{Buffer as xr}from"buffer";import{createCipheriv as dT,createDecipheriv as mT,randomBytes as Kf}from"crypto";import{closeSync as Wf,createReadStream as Oy,createWriteStream as gT,existsSync as Vf,fsyncSync as Ny,openSync as Dy,writeFileSync as pT}from"fs";import{access as yT,constants as Fy,mkdir as wT,readdir as Aa,rename as Ly,stat as Hn,unlink as Ra,writeFile as Hf}from"fs/promises";import{join as zn}from"path";import Ke from"process";import{pipeline as vT}from"stream/promises";import{createGzip as By}from"zlib";import Gn from"process";import or from"process";import{Buffer as ir}from"buffer";import{createCipheriv as bT,createDecipheriv as $T,randomBytes as zf}from"crypto";import{closeSync as Gf,createReadStream as Iy,createWriteStream as CT,existsSync as ka,fsyncSync as My,openSync as _y,writeFileSync as xT}from"fs";import{access as ST,constants as jy,mkdir as ET,readdir as Oa,rename as Uy,stat as qn,unlink as Na,writeFile as qf}from"fs/promises";import{isAbsolute as TT,join as Yn,resolve as PT}from"path";import _ from"process";import{pipeline as AT}from"stream/promises";import{createGzip as Ky}from"zlib";import Jn from"process";import ar from"process";import Da from"process";import{existsSync as Fa}from"fs";import{resolve as Yf}from"path";import{existsSync as RT}from"fs";import{existsSync as kT,readdirSync as OT}from"fs";import{extname as Jf,resolve as Wy}from"path";import NT from"process";import{join as DP,relative as FP,resolve as tw}from"path";import Qa from"process";import{Buffer as sr}from"buffer";import{createCipheriv as IP,createDecipheriv as MP,randomBytes as th}from"crypto";import{closeSync as rh,createReadStream as rw,createWriteStream as _P,existsSync as Ba,fsyncSync as nw,openSync as iw,writeFileSync as jP}from"fs";import{access as UP,constants as sw,mkdir as KP,readdir as Ia,rename as ow,stat as Xn,unlink as Ma,writeFile as nh}from"fs/promises";import{isAbsolute as WP,join as Zn,resolve as VP}from"path";import j from"process";import{pipeline as HP}from"stream/promises";import{createGzip as aw}from"zlib";import Qn from"process";import cr from"process";function nT(e,t){this[e]=rT.bind(null,t)}class ph{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Ty(e))return!0;return Py(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Ty(r)?Py(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class yh{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function DT(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function FT(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function LT(e){return e.getStats().size*2}function wh(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&le(t[0])&&"id"in t[0]&&t[0].id===3&&le(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(le(t)&&le(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(le(e)&&"arr"in e&&Array.isArray(e.arr)&&le(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&le(t[0])&&le(e[0])){let n=[...t];for(let i of e)if(le(i)&&"name"in i){if(!n.find((o)=>le(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(le(i)&&"path"in i){if(!n.find((o)=>le(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>Ga(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!le(t)||!le(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(le(i)&&le(r[n]))r[n]=wh(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&le(i[0])&&le(r[n][0])){let s=[...i];for(let o of r[n])if(le(o)&&"name"in o){if(!s.find((a)=>le(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(le(o)&&"path"in o){if(!s.find((a)=>le(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Ga(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function Ga(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ga(e[r],t[r]))return!1;return!0}if(le(e)&&le(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Ga(e[i],t[i]))return!1}return!0}return!1}function le(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function BT(e,t){if(!hw(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return wh(t,n)}catch{return null}}catch{return null}}async function IT({name:e="",cwd:t,defaultConfig:r}){let n=t||oh.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=za(n,`${o}${c}`),l=await BT(a,r);if(l!==null)return l}try{let o=za(n,"package.json");if(hw(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return wh(r,a)}catch{}}}catch{}return r}function MT(e,t={}){let r=Ha.cwd();while(r.includes("storage"))r=ky(r,"..");let n=ky(r,e||"");if(t?.relative)return hT(Ha.cwd(),n);return n}async function _T(){try{let e=await IT({name:"clarity",defaultConfig:ja,cwd:Ha.cwd(),endpoint:"",headers:{}});return{...ja,...e}}catch{return ja}}function me(){if(or.env.NODE_ENV==="test"||or.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jT(){if(or.env.NODE_ENV==="test"||or.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof or<"u"){let e=or.type;if(e==="renderer"||e==="worker")return!1;return!!(or.versions&&(or.versions.node||or.versions.bun))}return!1}class dw{async format(e){let t=await jT(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Gn.pid,hostname:t(),environment:Gn.env.NODE_ENV||"development",platform:Gn.platform,version:Gn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Gn.env.NODE_ENV||Gn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qa{name;fileLocks=new Map;currentKeyId=null;keys=new Map;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(e,t={}){this.name=e,this.config={...ch},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new dw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Ke.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ua,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ua};return{...Ua,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ch.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await yT(this.config.logDirectory,Fy.F_OK|Fy.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await wT(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:xr.from(e);try{if(!Vf(this.currentLogFile))await Hf(this.currentLogFile,"",{mode:420});if(i=Dy(this.currentLogFile,"a",420),pT(i,a,{flag:"a"}),Ny(i),i!==void 0)Wf(i),i=void 0;if((await Hn(this.currentLogFile)).size===0){if(await Hf(this.currentLogFile,a,{flag:"w",mode:420}),(await Hn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{Wf(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 zn(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 zn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return zn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(me())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Kf(16).toString("hex")}generateKey(){return Kf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Kf(16),n=dT("aes-256-gcm",t,r),i=xr.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:xr.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=By(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(xr.from(xr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(me())return;let e=await Hn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Aa(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Hn(r).catch(()=>null))try{if(await Ly(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ra(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Hf(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Hn(r).catch(()=>null))await Ly(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Aa(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Ra(zn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Oy(e),n=gT(t),i=By();await vT(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Vf(this.currentLogFile))try{let e=Dy(this.currentLogFile,"r+");Ny(e),Wf(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!me()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Aa(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ra(zn(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?se.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=Ke.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${se.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!me()){let l=xw[e],u=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:se.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:se.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
|
|
191
|
+
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:se.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!me()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
134
192
|
`;if(c)a+=`${c}
|
|
135
|
-
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!
|
|
136
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
137
|
-
`),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:
|
|
138
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
139
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||
|
|
140
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||le()||!Fe.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(le()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Fo(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=Ti(this.config.logDirectory,i);if(e.before)try{if((await Ei(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Bo(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Vo(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&X(t[0])&&"id"in t[0]&&t[0].id===3&&X(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(X(t)&&X(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(X(e)&&"arr"in e&&Array.isArray(e.arr)&&X(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&X(t[0])&&X(e[0])){let i=[...t];for(let n of e)if(X(n)&&"name"in n){if(!i.find((o)=>X(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(X(n)&&"path"in n){if(!i.find((o)=>X(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>ta(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!X(t)||!X(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(X(n)&&X(r[i]))r[i]=Vo(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&X(n[0])&&X(r[i][0])){let s=[...n];for(let o of r[i])if(X(o)&&"name"in o){if(!s.find((a)=>X(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(X(o)&&"path"in o){if(!s.find((a)=>X(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>ta(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function Gu(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Vo(e,t);if(Array.isArray(e))return r==="replace"?t:Vo(e,t);if(!X(t)||!X(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=Vo(o,s);else if(X(s)&&X(o))i[n]=Gu(o,s,r);else i[n]=s}return i}function ta(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ta(e[r],t[r]))return!1;return!0}if(X(e)&&X(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ta(e[n],t[n]))return!1}return!0}return!1}function X(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Uo(e,t,r="replace"){if(!Np(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Gu(t,n,r)}catch{return null}}catch{return null}}function J0(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${f.map(h).join("_")}`,y=`${i}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)Le.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=hn.env[d]||hn.env[y];if(g!==void 0){if(r)Le.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(n)}async function X0({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?J0(e,n,s):n,l=r||hn.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Le.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Ge(l,"config"),Ge(l,".config"),i?Ge(l,i):void 0].filter(Boolean)));for(let p of g){if(s)Le.info(`Searching for configuration in: ${p}`);let b=[Ge(l,"config"),Ge(l,".config")].concat(i?[Ge(l,i)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let P of b)for(let R of u){let v=Ge(p,`${P}${R}`),T=await Uo(v,a,c);if(T!==null){if(s)Le.success(`Configuration loaded from: ${v}`);return T}}}if(e){let p=Ge(pu(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)Le.info(`Checking user config directory: ${p}`);for(let b of w)for(let P of u){let R=Ge(p,`${b}${P}`),v=await Uo(R,a,c);if(v!==null){if(s)Le.success(`Configuration loaded from user config directory: ${R}`);return v}}}if(e){let p=Ge(pu(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)Le.info(`Checking user config directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ge(p,`${b}${P}`),v=await Uo(R,a,c);if(v!==null){if(s)Le.success(`Configuration loaded from user config directory dotfile: ${R}`);return v}}}if(e){let p=pu(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)Le.info(`Checking user home directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ge(p,`${b}${P}`),v=await Uo(R,a,c);if(v!==null){if(s)Le.success(`Configuration loaded from user home directory: ${R}`);return v}}}try{let p=Ge(l,"package.json");if(Np(p)){let w=await import(p),b=w[e];if(!b&&t){if(b=w[t],b&&s)Le.success(`Using alias "${t}" configuration from package.json`)}if(b&&typeof b==="object"&&!Array.isArray(b))try{if(s)Le.success(`Configuration loaded from package.json: ${b===w[e]?e:t}`);return Gu(a,b,c)}catch(P){if(s)Le.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)Le.warn("Failed to load package.json:",p)}if(s)Le.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function Q0(e,t={}){let r=Jo.cwd();while(r.includes("storage"))r=Jg(r,"..");let i=Jg(r,e||"");if(t?.relative)return v0(Jo.cwd(),i);return i}async function Z0(){try{let e=await X0({name:"clarity",alias:"logging",defaultConfig:Go,cwd:Jo.cwd()});return{...Go,...e||{}}}catch{return Go}}function $e(){if(Qt.env.NODE_ENV==="test"||Qt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function eE(){if(Qt.env.NODE_ENV==="test"||Qt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Qt<"u"){let e=Qt.type;if(e==="renderer"||e==="worker")return!1;return!!(Qt.versions&&(Qt.versions.node||Qt.versions.bun))}return!1}class Bp{async format(e){let t=await eE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ki.pid,hostname:t(),environment:ki.env.NODE_ENV||"development",platform:ki.platform,version:ki.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ki.env.NODE_ENV||ki.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ra{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(e,t={}){this.name=e,this.config={...Iu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Bp,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??L.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...qo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...qo};return{...qo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Iu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!$e()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await D0(this.config.logDirectory,ap.F_OK|ap.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await F0(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:qt.from(e);try{if(!Lo(this.currentLogFile))await Cu(this.currentLogFile,"",{mode:420});if(n=op(this.currentLogFile,"a",420),N0(n,a,{flag:"a"}),sp(n),n!==void 0)xu(n),n=void 0;if((await Ri(this.currentLogFile)).size===0){if(await Cu(this.currentLogFile,a,{flag:"w",mode:420}),(await Ri(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{xu(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 Ai(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 Ai(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ai(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if($e())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return $u(16).toString("hex")}generateKey(){return $u(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=$u(16),i=A0("aes-256-gcm",t,r),n=qt.isBuffer(e)?e:qt.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=qt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=lp(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(qt.from(qt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if($e())return;if(!this.shouldWriteToFile())return;let e=await Ri(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Mo(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Ri(r).catch(()=>null))try{if(await cp(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Io(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Cu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Ri(r).catch(()=>null))await cp(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await Mo(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Io(Ai(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=np(e),i=O0(t),n=lp();await M0(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Lo(this.currentLogFile))try{let e=op(this.currentLogFile,"r+");sp(e),xu(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!$e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Mo(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Io(Ai(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?U.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||$e())return!1;let e=typeof L.env.NO_COLOR<"u",t=L.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=L.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${U.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=U.underline(U.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>U.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>U.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>U.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>U.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>U.strikethrough(i)),t}supportsHyperlinks(){if($e())return!1;let e=L.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=L.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(B0(t)||t.startsWith("./")||t.startsWith("../"))t=L0(t);else return null;return Lo(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Vp[e],h=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:U.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:U.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
141
|
-
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:
|
|
193
|
+
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!me()){let r=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:se.blue("◐"),tag:r,message:`${se.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
194
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!me()){let u=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:se.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!me())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new qa(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(me())throw Error("createReadStream is not supported in browser environments");if(!Vf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Oy(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=xr.isBuffer(e)?e:xr.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=mT("aes-256-gcm",r,i);return c.setAuthTag(s),xr.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return me()}isServerMode(){return!me()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!me()){let s=e.split(`
|
|
195
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:se.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:se.cyan(c)})),l.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:se.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:se.cyan(a),showTimestamp:!1}))}else if(!me())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
196
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(me())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${se.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Ke.stdin.removeListener("data",r);try{if(typeof Ke.stdin.setRawMode==="function")Ke.stdin.setRawMode(!1)}catch{}Ke.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Ke.stdin.setRawMode==="function")Ke.stdin.setRawMode(!0)}catch{}Ke.stdin.resume(),Ke.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!me()){let o=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",c=se.blue("◐");console.error(`${c} ${o} ${se.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
197
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||me()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||me())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||me())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||me())return;Ke.stdout.write(`${"\r".padEnd(Ke.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||me()||!Ke.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=se.green("━".repeat(n)),o=se.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=t||r===100?se.green("✓"):se.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${se.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=Ke.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,Ke.stdout.write(e.lastRenderedLine),t)Ke.stdout.write(`
|
|
198
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||me()||!Ke.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(me()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Aa(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=zn(this.config.logDirectory,n);if(e.before)try{if((await Hn(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ra(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function _a(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Q(t[0])&&"id"in t[0]&&t[0].id===3&&Q(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Q(t)&&Q(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Q(e)&&"arr"in e&&Array.isArray(e.arr)&&Q(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Q(t[0])&&Q(e[0])){let n=[...t];for(let i of e)if(Q(i)&&"name"in i){if(!n.find((o)=>Q(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(Q(i)&&"path"in i){if(!n.find((o)=>Q(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>Ya(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Q(t)||!Q(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Q(i)&&Q(r[n]))r[n]=_a(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Q(i[0])&&Q(r[n][0])){let s=[...i];for(let o of r[n])if(Q(o)&&"name"in o){if(!s.find((a)=>Q(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(Q(o)&&"path"in o){if(!s.find((a)=>Q(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Ya(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function vh(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:_a(e,t);if(Array.isArray(e))return r==="replace"?t:_a(e,t);if(!Q(t)||!Q(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=_a(o,s);else if(Q(s)&&Q(o))n[i]=vh(o,s,r);else n[i]=s}return n}function Ya(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ya(e[r],t[r]))return!1;return!0}if(Q(e)&&Q(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Ya(e[i],t[i]))return!1}return!0}return!1}function Q(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function La(e,t,r="replace"){if(!fw(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return vh(t,i,r)}catch{return null}}catch{return null}}function UT(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${n}_${f.map(h).join("_")}`,y=`${n}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)Ve.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=Gi.env[d]||Gi.env[y];if(g!==void 0){if(r)Ve.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(i)}async function KT({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?UT(e,i,s):i,l=r||Gi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Ve.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Qe(l,"config"),Qe(l,".config"),n?Qe(l,n):void 0].filter(Boolean)));for(let p of g){if(s)Ve.info(`Searching for configuration in: ${p}`);let v=[Qe(l,"config"),Qe(l,".config")].concat(n?[Qe(l,n)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let P of v)for(let A of u){let R=Qe(p,`${P}${A}`),D=await La(R,a,c);if(D!==null){if(s)Ve.success(`Configuration loaded from: ${R}`);return D}}}if(e){let p=Qe(Uf(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)Ve.info(`Checking user config directory: ${p}`);for(let v of w)for(let P of u){let A=Qe(p,`${v}${P}`),R=await La(A,a,c);if(R!==null){if(s)Ve.success(`Configuration loaded from user config directory: ${A}`);return R}}}if(e){let p=Qe(Uf(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)Ve.info(`Checking user config directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=Qe(p,`${v}${P}`),R=await La(A,a,c);if(R!==null){if(s)Ve.success(`Configuration loaded from user config directory dotfile: ${A}`);return R}}}if(e){let p=Uf(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)Ve.info(`Checking user home directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=Qe(p,`${v}${P}`),R=await La(A,a,c);if(R!==null){if(s)Ve.success(`Configuration loaded from user home directory: ${A}`);return R}}}try{let p=Qe(l,"package.json");if(fw(p)){let w=await import(p),v=w[e];if(!v&&t){if(v=w[t],v&&s)Ve.success(`Using alias "${t}" configuration from package.json`)}if(v&&typeof v==="object"&&!Array.isArray(v))try{if(s)Ve.success(`Configuration loaded from package.json: ${v===w[e]?e:t}`);return vh(a,v,c)}catch(P){if(s)Ve.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)Ve.warn("Failed to load package.json:",p)}if(s)Ve.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function WT(e,t={}){let r=Va.cwd();while(r.includes("storage"))r=Ry(r,"..");let n=Ry(r,e||"");if(t?.relative)return uT(Va.cwd(),n);return n}async function VT(){try{let e=await KT({name:"clarity",alias:"logging",defaultConfig:Ka,cwd:Va.cwd()});return{...Ka,...e||{}}}catch{return Ka}}function Te(){if(ar.env.NODE_ENV==="test"||ar.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function HT(){if(ar.env.NODE_ENV==="test"||ar.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ar<"u"){let e=ar.type;if(e==="renderer"||e==="worker")return!1;return!!(ar.versions&&(ar.versions.node||ar.versions.bun))}return!1}class mw{async format(e){let t=await HT(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Jn.pid,hostname:t(),environment:Jn.env.NODE_ENV||"development",platform:Jn.platform,version:Jn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Jn.env.NODE_ENV||Jn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ja{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(e,t={}){this.name=e,this.config={...lh},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new mw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Wa,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Wa};return{...Wa,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:lh.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Te()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await ST(this.config.logDirectory,jy.F_OK|jy.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await ET(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ir.from(e);try{if(!ka(this.currentLogFile))await qf(this.currentLogFile,"",{mode:420});if(i=_y(this.currentLogFile,"a",420),xT(i,a,{flag:"a"}),My(i),i!==void 0)Gf(i),i=void 0;if((await qn(this.currentLogFile)).size===0){if(await qf(this.currentLogFile,a,{flag:"w",mode:420}),(await qn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{Gf(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 Yn(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 Yn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Yn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Te())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return zf(16).toString("hex")}generateKey(){return zf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=zf(16),n=bT("aes-256-gcm",t,r),i=ir.isBuffer(e)?e:ir.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=ir.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Ky(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(ir.from(ir.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Te())return;if(!this.shouldWriteToFile())return;let e=await qn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Oa(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await qn(r).catch(()=>null))try{if(await Uy(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Na(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await qf(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await qn(r).catch(()=>null))await Uy(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Oa(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Na(Yn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Iy(e),n=CT(t),i=Ky();await AT(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ka(this.currentLogFile))try{let e=_y(this.currentLogFile,"r+");My(e),Gf(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Te()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Oa(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Na(Yn(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?V.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Te())return!1;let e=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=_.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${V.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=V.underline(V.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>V.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>V.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>V.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>V.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>V.strikethrough(n)),t}supportsHyperlinks(){if(Te())return!1;let e=_.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=_.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(TT(t)||t.startsWith("./")||t.startsWith("../"))t=PT(t);else return null;return ka(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Sw[e],h=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:V.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:V.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
199
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:V.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!Te()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
142
200
|
`;if(c)u+=`${c}
|
|
143
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let
|
|
144
|
-
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()
|
|
145
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?
|
|
146
|
-
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:
|
|
147
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(
|
|
148
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
149
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy
|
|
201
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Te()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!Te()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!Te()&&_.stdout.isTTY)_.stdout.write(`
|
|
202
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!Te()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":V.blue("◐"),tag:r,message:`${V.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
203
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":V.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Te())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ja(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Te())throw Error("createReadStream is not supported in browser environments");if(!ka(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Iy(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ir.isBuffer(e)?e:ir.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=$T("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=ir.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Te()}isServerMode(){return!Te()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
204
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:V.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:V.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:V.cyan(u),showTimestamp:!1}))}else if(!Te())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
205
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Te())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${V.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){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 u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${V.blue("◐")} `;console.error(`${l}${a} ${V.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
206
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=V.green("━".repeat(n)),o=V.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?V.green("✓"):V.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${V.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=_.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,_.stdout.write(e.lastRenderedLine),t)_.stdout.write(`
|
|
207
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Te()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Te()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Oa(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=Yn(this.config.logDirectory,n);if(e.before)try{if((await qn(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Na(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function gw(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function pw(e){return e instanceof ht}function zT(e){return e instanceof Xa}function GT(e){if(pw(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class tc{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Ji.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Da.env[a]||(l?Da.env[l]:void 0);if(u!==void 0){if(n.verbose){let f=Da.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(u,typeof s,a,n.customParsers,n.configName)}catch(f){if(f instanceof Za)throw f;throw Sr.envVar(a,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Sr.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Da.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
150
208
|
|
|
151
|
-
`;for(let
|
|
152
|
-
`,r+=` Type: ${
|
|
153
|
-
`,r+=` Description: ${
|
|
154
|
-
`,r+=` Example: ${
|
|
209
|
+
`;for(let n of e)r+=`${n.key}
|
|
210
|
+
`,r+=` Type: ${n.type}
|
|
211
|
+
`,r+=` Description: ${n.description}
|
|
212
|
+
`,r+=` Example: ${n.example}
|
|
155
213
|
|
|
156
214
|
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
157
215
|
|
|
158
216
|
`;r+=`| Variable | Type | Description | Example |
|
|
159
217
|
`,r+=`|----------|------|-------------|----------|
|
|
160
|
-
`;for(let
|
|
161
|
-
`;return r}}function iE(e,t){let r=Wp("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function Ip(e,t,r={}){return _p(e,t,r,new WeakMap)}function _p(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return jp(e,t,n,i);if(!pt(t)||!pt(e))return t;return aE(e,t,r,i)}function jp(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return nE(e,t);case"smart":return sE(e,t,i);default:return t}return t}function nE(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Lu(n,i)))r.push(i);return r}function sE(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(pt(t[0])&&pt(e[0]))return oE(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function oE(e,t,r){let i=[...t];for(let n of e){if(!pt(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in n){if(i.find((l)=>pt(l)&&(c in l)&&l[c]===n[c])){o=!0;break}}if(!o)i.push(n)}return i}function aE(e,t,r,i){let n=t;if(pt(n)&&i.has(n))return i.get(n);let s={...e};if(pt(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(pt(c)&&pt(a))s[o]=_p(a,c,r,i);else if(Array.isArray(c)||Array.isArray(a))s[o]=jp(a,c,r.arrayMergeMode||"smart",i);else s[o]=c}return s}function qu(e,t,r="replace"){return Ip(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Lu(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Lu(e[r],t[r]))return!1;return!0}if(pt(e)&&pt(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Lu(e[n],t[n]))return!1}return!0}return!1}function pt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ca{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=Fi.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!jo(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new dn(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new dn(e,Error("Configuration must export a valid object"),"unknown");let p={config:qu(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Fi.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?gr.configLoad(e,l):gr.configLoad(e,Error(String(l)))}};if(o)return gn.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(Su(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Lp(async()=>jo(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!jo(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let c=Su(e,`${s}${o}`);if(await this.checkFileAccess(c))i.push(c)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=Su(e,o);if(await this.checkFileAccess(c))i.push(c)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!jo(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Ju{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await gn.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!I0(t))throw new mn(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new mn(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(i.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(i.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(i.push(...c),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:zp},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Xu{fileLoader=new ca;envProcessor=new aa;validator=new Ju;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||s)await this.validateConfiguration(c.config,n,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(i?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(a);if(i.slowThreshold&&a.duration>i.slowThreshold)Tt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw Tt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Lr.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,o)),this.finalizeResult(d,h,a,i,u);let y=await this.loadHomeConfiguration(i,n,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,a,i,u);let g=await this.loadPackageJsonConfiguration(i,n,f,c,l,u,a);if(g)return h.push(qe(f,"package.json")),this.finalizeResult(g,h,a,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,o)),t)throw gr.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,c,a,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,c,a){let l=c?fn(e,n,o):n,u=this.getLocalDirectories(r,i);for(let f of u){if(o)Tt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Tt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?fn(e,r,n):r,c=[qe(Si(),".config",e),qe(Si(),".config"),Si()];for(let a of c){if(n)Tt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(u){if(n)Tt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let c=o?fn(e,i,s):i;try{let a=qe(r,"package.json");if(!Fu(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Tt.success(`Configuration loaded from package.json: ${f}`);return{config:qu(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Tt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:fn(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw gr.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Fi.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Fi.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,qe(e,"config"),qe(e,".config"),t?qe(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(qe(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[qe(Si(),".config",e),qe(Si(),".config"),Si()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function fp(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),i=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||i}async function cE(e){return er.loadConfig({...e,__strictErrorHandling:!0})}async function Up(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await er.loadConfig(e);else i=await er.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)Tt.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await er.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function lE(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await er.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&fp(r)))return(await er.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await er.loadConfig({...e,cwd:e.cwd||Lr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&fp(t)))return(await er.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function uE(e,t,r="replace"){let i=new ca;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function fn(e,t,r=!1){let i=new aa,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((g)=>g.toUpperCase()).join("")}`,`${n}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Lr.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function fE(e){let t=qe(Lr.cwd(),e.configDir),r=qe(Lr.cwd(),e.generatedDir),i=qe(r,"config-types.ts");if(!Fu(qg(i)))g0(qg(i),{recursive:!0,mode:511});let n=Fu(t)?p0(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${jE}
|
|
162
|
-
export type ConfigNames = ${
|
|
163
|
-
`;
|
|
164
|
-
${
|
|
218
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
219
|
+
`;return r}}function qT(e,t){let r=$w("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function yw(e,t,r={}){return ww(e,t,r,new WeakMap)}function ww(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return vw(e,t,i,n);if(!$t(t)||!$t(e))return t;return ZT(e,t,r,n)}function vw(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return YT(e,t);case"smart":return JT(e,t,n);default:return t}return t}function YT(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>ah(i,n)))r.push(n);return r}function JT(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if($t(t[0])&&$t(e[0]))return XT(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function XT(e,t,r){let n=[...t];for(let i of e){if(!$t(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>$t(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function ZT(e,t,r,n){let i=t;if($t(i)&&n.has(i))return n.get(i);let s={...e};if($t(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if($t(c)&&$t(a))s[o]=ww(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=vw(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function bh(e,t,r="replace"){return yw(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ah(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ah(e[r],t[r]))return!1;return!0}if($t(e)&&$t(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ah(e[i],t[i]))return!1}return!0}return!1}function $t(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class rc{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=ei.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Fa(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new qi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new qi(e,Error("Configuration must export a valid object"),"unknown");let p={config:bh(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)ei.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?Sr.configLoad(e,l):Sr.configLoad(e,Error(String(l)))}};if(o)return Ji.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(Yf(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return gw(async()=>Fa(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Fa(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=Yf(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=Yf(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Fa(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class $h{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await Ji.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!RT(t))throw new Yi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Yi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Tw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ch{fileLoader=new rc;envProcessor=new tc;validator=new $h;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)kt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw kt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||zr.cwd(),h=[],d=await this.loadLocalConfiguration(n,i,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(n,i,f,o)),this.finalizeResult(d,h,a,n,u);let y=await this.loadHomeConfiguration(n,i,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(y,h,a,n,u);let g=await this.loadPackageJsonConfiguration(n,i,f,c,l,u,a);if(g)return h.push(et(f,"package.json")),this.finalizeResult(g,h,a,n,u);if(h.push(...this.getAllSearchPaths(n,i,f,o)),t)throw Sr.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?zi(e,i,o):i,u=this.getLocalDirectories(r,n);for(let f of u){if(o)kt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)kt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?zi(e,r,i):r,c=[et(Vn(),".config",e),et(Vn(),".config"),Vn()];for(let a of c){if(i)kt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(u){if(i)kt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?zi(e,n,s):n;try{let a=et(r,"package.json");if(!sh(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)kt.success(`Configuration loaded from package.json: ${f}`);return{config:bh(c,u,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)kt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:zi(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw Sr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ei.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);ei.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,et(e,"config"),et(e,".config"),t?et(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(et(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[et(Vn(),".config",e),et(Vn(),".config"),Vn()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Vy(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function QT(e){return lr.loadConfig({...e,__strictErrorHandling:!0})}async function bw(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await lr.loadConfig(e);else n=await lr.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)kt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await lr.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function eP(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await lr.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Vy(r)))return(await lr.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await lr.loadConfig({...e,cwd:e.cwd||zr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Vy(t)))return(await lr.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function tP(e,t,r="replace"){let n=new rc;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function zi(e,t,r=!1){let n=new tc,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((g)=>g.toUpperCase()).join("")}`,`${i}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=zr.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function rP(e){let t=et(zr.cwd(),e.configDir),r=et(zr.cwd(),e.generatedDir),n=et(r,"config-types.ts");if(!sh(Ay(n)))oT(Ay(n),{recursive:!0,mode:511});let i=sh(t)?aT(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${OP}
|
|
220
|
+
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
221
|
+
`;cT(n,s,{mode:438})}function nP(e){let t=null,r=null,n=()=>{if(!r)r=bw(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)kt.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function iP(e){let t=Wy(NT.cwd(),e?.configDir||"./config");function r(){if(!kT(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=OT(t).filter((a)=>i.has(Jf(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=Jf(l).toLowerCase(),f=c.get(a);if(!f){c.set(a,l);continue}let h=Jf(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=i.length?`{
|
|
222
|
+
${i.map((l)=>{let u=Wy(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${u}').default`}).join(`,
|
|
165
223
|
`)}
|
|
166
224
|
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
167
225
|
export type ConfigByName = ${c}
|
|
168
226
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
169
227
|
export type ConfigOf = Config
|
|
170
|
-
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}function HE(e,t={}){let r=sa.cwd();while(r.includes("storage"))r=xp(r,"..");let i=xp(r,e||"");if(t?.relative)return KE(sa.cwd(),i);return i}function Ce(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function tT(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Zt<"u"){let e=Zt.type;if(e==="renderer"||e==="worker")return!1;return!!(Zt.versions&&(Zt.versions.node||Zt.versions.bun))}return!1}class Xp{async format(e){let t=await tT(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Di.pid,hostname:t(),environment:Di.env.NODE_ENV||"development",platform:Di.platform,version:Di.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Di.env.NODE_ENV||Di.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class pn{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(e,t={}){this.name=e,this.config={...oa},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Xp,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Du,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Du};return{...Du,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:oa.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ce()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await JE(this.config.logDirectory,Tp.F_OK|Tp.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await XE(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Jt.from(e);try{if(!Wo(this.currentLogFile))await Nu(this.currentLogFile,"",{mode:420});if(n=Ep(this.currentLogFile,"a",420),qE(n,a,{flag:"a"}),Sp(n),n!==void 0)Ou(n),n=void 0;if((await Oi(this.currentLogFile)).size===0){if(await Nu(this.currentLogFile,a,{flag:"w",mode:420}),(await Oi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{Ou(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ni(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Ni(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ni(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ce())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ku(16).toString("hex")}generateKey(){return ku(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=ku(16),i=YE("aes-256-gcm",t,r),n=Jt.isBuffer(e)?e:Jt.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=Jt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Rp(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Jt.from(Jt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ce())return;if(!this.shouldWriteToFile())return;let e=await Oi(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Ko(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Oi(r).catch(()=>null))try{if(await Pp(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ho(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Nu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Oi(r).catch(()=>null))await Pp(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await Ko(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Ho(Ni(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Cp(e),i=GE(t),n=Rp();await eT(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Wo(this.currentLogFile))try{let e=Ep(this.currentLogFile,"r+");Sp(e),Ou(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ce()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ko(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ho(Ni(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?V.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ce())return!1;let e=typeof M.env.NO_COLOR<"u",t=M.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=M.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${V.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=V.underline(V.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>V.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>V.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>V.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>V.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>V.strikethrough(i)),t}supportsHyperlinks(){if(Ce())return!1;let e=M.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=M.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(QE(t)||t.startsWith("./")||t.startsWith("../"))t=ZE(t);else return null;return Wo(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":oT[e],h=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:V.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:V.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
171
|
-
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:
|
|
228
|
+
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function LP(e,t={}){let r=Qa.cwd();while(r.includes("storage"))r=tw(r,"..");let n=tw(r,e||"");if(t?.relative)return FP(Qa.cwd(),n);return n}function Ae(){if(cr.env.NODE_ENV==="test"||cr.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zP(){if(cr.env.NODE_ENV==="test"||cr.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof cr<"u"){let e=cr.type;if(e==="renderer"||e==="worker")return!1;return!!(cr.versions&&(cr.versions.node||cr.versions.bun))}return!1}class kw{async format(e){let t=await zP(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Qn.pid,hostname:t(),environment:Qn.env.NODE_ENV||"development",platform:Qn.platform,version:Qn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qn.env.NODE_ENV||Qn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Xi{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(e,t={}){this.name=e,this.config={...ec},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new kw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??j.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ih,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ih};return{...ih,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ec.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ae()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await UP(this.config.logDirectory,sw.F_OK|sw.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await KP(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 a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:sr.from(e);try{if(!Ba(this.currentLogFile))await nh(this.currentLogFile,"",{mode:420});if(i=iw(this.currentLogFile,"a",420),jP(i,a,{flag:"a"}),nw(i),i!==void 0)rh(i),i=void 0;if((await Xn(this.currentLogFile)).size===0){if(await nh(this.currentLogFile,a,{flag:"w",mode:420}),(await Xn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{rh(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 Zn(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 Zn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Zn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ae())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}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 r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return th(16).toString("hex")}generateKey(){return th(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=th(16),n=IP("aes-256-gcm",t,r),i=sr.isBuffer(e)?e:sr.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=sr.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=aw(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(sr.from(sr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ae())return;if(!this.shouldWriteToFile())return;let e=await Xn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Ia(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Xn(r).catch(()=>null))try{if(await ow(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ma(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await nh(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Xn(r).catch(()=>null))await ow(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Ia(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Ma(Zn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=rw(e),n=_P(t),i=aw();await HP(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Ba(this.currentLogFile))try{let e=iw(this.currentLogFile,"r+");nw(e),rh(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ae()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ia(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ma(Zn(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?G.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ae())return!1;let e=typeof j.env.NO_COLOR<"u",t=j.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof j.stderr<"u"&&j.stderr.isTTY||typeof j.stdout<"u"&&j.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=j.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${G.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=G.underline(G.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>G.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>G.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>G.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>G.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>G.strikethrough(n)),t}supportsHyperlinks(){if(Ae())return!1;let e=j.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=j.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(WP(t)||t.startsWith("./")||t.startsWith("../"))t=VP(t);else return null;return Ba(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":XP[e],h=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:G.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:G.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
229
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:G.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!Ae()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
172
230
|
`;if(c)u+=`${c}
|
|
173
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let
|
|
174
|
-
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
175
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?
|
|
176
|
-
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:
|
|
177
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(
|
|
178
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
179
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ce()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ce()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ko(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=Ni(this.config.logDirectory,i);if(e.before)try{if((await Oi(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Ho(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var u0,f0=(e)=>e,d0=(e,t)=>{for(var r in t)u0(e,r,{get:t[r],enumerable:!0,configurable:!0,set:h0.bind(t,r)})},m0=(e,t)=>()=>(e&&(t=e(e=0)),t),Op,Wp,Fi,gn,Kp,mE,gE,hp,Yo,Mu,Be,te,pE,dp,yE,mp,wE,vE,Tu,bE,gp,pp,Pu,$E,xE,CE,SE,zo,Hp,EE,Le,TE,PE,yp,Go,Iu,xe,U,RE,wp,AE,vp,kE,OE,Ru,NE,bp,$p,DE,Au,FE,BE,LE,ME,IE,qo,Vp,_E,jE="0.15.6",nt,ia,dn,_u,ju,na,Uu,Wu,mn,Ku,Hu,gr,Yp,zp,Tt,er,Gp,qp,UE,VE,Jp,oa,cF,Te,V,vF,rT,bF,iT,$F,xF,Ap,CF,nT,sT,SF,kp,EF,TF,PF,RF,AF,Du,oT,kF;var Qp=Q(()=>{u0=Object.defineProperty;Op={};d0(Op,{withErrorRecovery:()=>Lp,tryLoadConfig:()=>uE,loadConfigWithResult:()=>cE,loadConfig:()=>Up,isRetryableError:()=>rE,isConfigNotFoundError:()=>tE,isBunfigError:()=>Mp,globalPerformanceMonitor:()=>gn,globalCache:()=>Fi,getEnvOrDefault:()=>iE,generateConfigTypes:()=>fE,defaultGeneratedDir:()=>qp,defaultConfigDir:()=>Gp,deepMergeWithArrayStrategy:()=>qu,deepMerge:()=>Ip,createLibraryConfig:()=>hE,config:()=>lE,bunfigPlugin:()=>dE,applyEnvVarsToConfig:()=>fn,TypeGenerationError:()=>Wu,SchemaValidationError:()=>mn,PluginError:()=>Hu,PerformanceMonitor:()=>Yu,FileSystemError:()=>Uu,ErrorFactory:()=>gr,EnvVarError:()=>na,EnvProcessor:()=>aa,ConfigValidator:()=>Ju,ConfigValidationError:()=>_u,ConfigNotFoundError:()=>ia,ConfigMergeError:()=>ju,ConfigLoader:()=>Xu,ConfigLoadError:()=>dn,ConfigFileLoader:()=>ca,ConfigCache:()=>Vu,CacheUtils:()=>Kp,BunfigError:()=>nt,BrowserConfigError:()=>Ku,ArrayMergeStrategies:()=>Yp});UE=m0(async()=>{Wp=import.meta.require,Fi=new Vu,gn=new Yu,Kp={createKey:W0,isEquivalent:K0,estimateMemoryUsage:H0},mE=Qo(Bu.cwd(),"config"),gE=Qo(Bu.cwd(),"src/generated"),hp=Xo.env.CLARITY_LOG_DIR||b0(z0(),"logs"),Yo={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:hp,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Mu=await G0(),Be={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},te=Be,pE=Be.red,dp=Be.green,yE=Be.yellow,mp=Be.blue,wE=Be.magenta,vE=Be.cyan,Tu=Be.white,bE=Be.gray,gp=Be.bgRed,pp=Be.bgYellow,Pu=Be.bold,$E=Be.dim,xE=Be.italic,CE=Be.underline,SE=Be.reset,zo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Hp={debug:"\uD83D\uDD0D",info:mp("ℹ"),success:dp("✓"),warning:pp(Tu(Pu(" WARN "))),error:gp(Tu(Pu(" ERROR ")))},EE=new ea("stacks"),Le=new ea("bunfig",{showTags:!0}),TE=Ge(hn.cwd(),"config"),PE=Ge(hn.cwd(),"src/generated"),yp=Jo.env.CLARITY_LOG_DIR||w0(Q0(),"logs"),Go={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yp,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Iu=await Z0(),xe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},U=xe,RE=xe.red,wp=xe.green,AE=xe.yellow,vp=xe.blue,kE=xe.magenta,OE=xe.cyan,Ru=xe.white,NE=xe.gray,bp=xe.bgRed,$p=xe.bgYellow,DE=xe.bgGray,Au=xe.bold,FE=xe.dim,BE=xe.italic,LE=xe.underline,ME=xe.strikethrough,IE=xe.reset,qo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Vp={debug:"\uD83D\uDD0D",info:vp("ℹ"),success:wp("✓"),warning:$p(Ru(Au(" WARN "))),error:bp(Ru(Au(" ERROR ")))},_E=new ra("stacks"),nt=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,i])=>`${r}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},ia=class extends nt{code="CONFIG_NOT_FOUND";constructor(t,r,i){let n=i?` or alias "${i}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:i,searchPaths:r,searchPathCount:r.length})}},dn=class extends nt{code="CONFIG_LOAD_ERROR";constructor(t,r,i){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},_u=class extends nt{code="CONFIG_VALIDATION_ERROR";constructor(t,r,i){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:i,validationErrors:r,errorCount:r.length})}},ju=class extends nt{code="CONFIG_MERGE_ERROR";constructor(t,r,i,n){super(`Failed to merge configuration from "${t}" with "${r}": ${i.message}`,{sourcePath:t,targetPath:r,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},na=class extends nt{code="ENV_VAR_ERROR";constructor(t,r,i,n){super(`Failed to parse environment variable "${t}" with value "${r}" as ${i}`,{envKey:t,envValue:r,expectedType:i,configName:n})}},Uu=class extends nt{code="FILE_SYSTEM_ERROR";constructor(t,r,i){super(`File system ${t} failed for "${r}": ${i.message}`,{operation:t,path:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Wu=class extends nt{code="TYPE_GENERATION_ERROR";constructor(t,r,i){super(`Failed to generate types from "${t}" to "${r}": ${i.message}`,{configDir:t,outputPath:r,originalError:i.name,originalMessage:i.message});this.cause=i}},mn=class extends nt{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:t,configName:i,validationErrors:r,errorCount:r.length})}},Ku=class extends nt{code="BROWSER_CONFIG_ERROR";constructor(t,r,i,n){super(`Failed to fetch configuration from "${t}": ${r} ${i}`,{endpoint:t,status:r,statusText:i,configName:n})}},Hu=class extends nt{code="PLUGIN_ERROR";constructor(t,r,i){super(`Plugin "${t}" failed during ${r}: ${i.message}`,{pluginName:t,operation:r,originalError:i.name,originalMessage:i.message});this.cause=i}},gr={configNotFound(e,t,r){return new ia(e,t,r)},configLoad(e,t,r){return new dn(e,t,r)},configValidation(e,t,r){return new _u(e,t,r)},configMerge(e,t,r,i){return new ju(e,t,r,i)},envVar(e,t,r,i){return new na(e,t,r,i)},fileSystem(e,t,r){return new Uu(e,t,r)},typeGeneration(e,t,r){return new Wu(e,t,r)},schemaValidation(e,t,r){return new mn(e,t,r)},browserConfig(e,t,r,i){return new Ku(e,t,r,i)},plugin(e,t,r){return new Hu(e,t,r)}},Yp={replace:"replace",concat:"concat",smart:"smart"},zp=/^https?:\/\//,Tt=new ra("bunfig",{showTags:!0}),er=new Xu,Gp=qe(Lr.cwd(),"config"),qp=qe(Lr.cwd(),"src/generated")});VE=sa.env.CLARITY_LOG_DIR||WE(HE(),"logs"),Jp={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:VE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},oa={...Jp},cF=(async()=>{try{let{loadConfig:e}=await UE().then(()=>Op),t=await e({name:"clarity",alias:"logging",defaultConfig:Jp,cwd:sa.cwd()});if(t)Object.assign(oa,t)}catch{}return oa})();Te={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},V=Te,vF=Te.red,rT=Te.green,bF=Te.yellow,iT=Te.blue,$F=Te.magenta,xF=Te.cyan,Ap=Te.white,CF=Te.gray,nT=Te.bgRed,sT=Te.bgYellow,SF=Te.bgGray,kp=Te.bold,EF=Te.dim,TF=Te.italic,PF=Te.underline,RF=Te.strikethrough,AF=Te.reset,Du={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oT={debug:"\uD83D\uDD0D",info:iT("ℹ"),success:rT("✓"),warning:sT(Ap(kp(" WARN "))),error:nT(Ap(kp(" ERROR ")))};kF=new pn("stacks")});var Bi={};Qf(Bi,{authorizeSystemAccess:()=>cT,debugLog:()=>m,execSudoSync:()=>yr,extractHostname:()=>hT,getPrimaryDomain:()=>fa,getSudoPassword:()=>pr,isMultiProxyConfig:()=>ha,isMultiProxyOptions:()=>Mr,isProcessElevated:()=>yn,isSingleProxyConfig:()=>dT,isSingleProxyOptions:()=>vn,isValidRootCA:()=>Qu,redactSensitive:()=>ua,resolvePathRewrite:()=>Zu,safeDeleteFile:()=>ef,safeStringify:()=>tr,shouldReusePort:()=>wn});import{execSync as la}from"node:child_process";import*as ey from"node:fs/promises";function pr(){return process.env.SUDO_PASSWORD}function yn(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function cT(e={}){if(process.platform==="win32")return!0;if(yn()||!!pr())return!0;let t=e.exec??la;try{return t("sudo -n true",{stdio:"ignore"}),!0}catch{if(!e.interactive)return!1}try{return t("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function yr(e){if(yn())return la(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let t=pr(),r=e.replace(/'/g,"'\\''");if(t)return la(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return la(`sudo -n sh -c '${r}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function m(e,t,r){if(r)aT.debug(`[rpx:${e}] ${t}`)}function wn(){let e=process.env.RPX_REUSE_PORT;return e==="1"||e==="true"}function fT(e){let t=e.toLowerCase();return lT.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function ua(e){if(Array.isArray(e))return e.map((r)=>ua(r));if(typeof e==="string")return uT.test(e)?Zp:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,i]of Object.entries(e)){if(fT(r)){t[r]=Zp;continue}t[r]=ua(i)}return t}function tr(e,t){return JSON.stringify(ua(e),null,t)}function hT(e){if(Mr(e))return e.proxies.map((t)=>{let r=t.to||"stacks.localhost";return r.startsWith("http")?new URL(r).hostname:r});if(vn(e)){let t=e.to||"stacks.localhost";return[t.startsWith("http")?new URL(t).hostname:t]}return["stacks.localhost"]}function Qu(e){return typeof e==="object"&&e!==null&&"certificate"in e&&"privateKey"in e&&typeof e.certificate==="string"&&typeof e.privateKey==="string"}function fa(e){if(!e)return"stacks.localhost";if(Mr(e)&&e.proxies.length>0)return e.proxies[0].to||"stacks.localhost";if(vn(e))return e.to||"stacks.localhost";return"stacks.localhost"}function ha(e){return!!(e&&("proxies"in e)&&Array.isArray(e.proxies))}function Mr(e){return"proxies"in e&&Array.isArray(e.proxies)}function vn(e){return"to"in e&&typeof e.to==="string"}function dT(e){return!!(e&&("to"in e)&&!("proxies"in e))}function Zu(e,t){if(!t||t.length===0)return null;for(let r of t)if(e===r.from||e.startsWith(`${r.from}/`)){let i=r.to.startsWith("http")?new URL(r.to).host:r.to,n=r.stripPrefix===!0?e.slice(r.from.length)||"/":e;return{targetHost:i,targetPath:n}}return null}async function ef(e,t){try{await ey.unlink(e),m("certificates",`Successfully deleted: ${e}`,t)}catch(r){if(r.code!=="ENOENT")m("certificates",`Warning: Could not delete ${e}: ${r}`,t)}}var aT,Zp="[redacted]",lT,uT;var he=Q(()=>{Qp();aT=new pn("rpx",{showTags:!1});lT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),uT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as da}from"node:child_process";import{homedir as mT}from"node:os";import{join as gT}from"node:path";function ma(){return gT(mT(),"Library/Keychains/login.keychain-db")}function rf(){return[vr,ma()]}function ty(e,t=tf){let r=da(`security find-certificate -a -c "${t}" -Z "${e}" 2>/dev/null || true`,{encoding:"utf8"}),i=[];for(let n of r.split(`
|
|
180
|
-
`)){let s=
|
|
181
|
-
`))if(s.toUpperCase().includes("SHA-256")){if(s.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return m("ssl",`Root CA fingerprint found in ${
|
|
231
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ae()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!Ae()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!Ae()&&j.stdout.isTTY)j.stdout.write(`
|
|
232
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!Ae()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":G.blue("◐"),tag:r,message:`${G.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
233
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":G.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ae())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Xi(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Ae())throw Error("createReadStream is not supported in browser environments");if(!Ba(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return rw(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=sr.isBuffer(e)?e:sr.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=MP("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=sr.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ae()}isServerMode(){return!Ae()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
234
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:G.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(u),showTimestamp:!1}))}else if(!Ae())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
235
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Ae())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${G.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();j.stdin.removeListener("data",r);try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!1)}catch{}j.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!0)}catch{}j.stdin.resume(),j.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){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 u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${G.blue("◐")} `;console.error(`${l}${a} ${G.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
236
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!j.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=G.green("━".repeat(n)),o=G.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?G.green("✓"):G.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=j.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,j.stdout.write(e.lastRenderedLine),t)j.stdout.write(`
|
|
237
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ae()||!j.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ae()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ia(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=Zn(this.config.logDirectory,n);if(e.before)try{if((await Xn(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ma(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var tT,rT=(e)=>e,iT=(e,t)=>{for(var r in t)tT(e,r,{get:t[r],enumerable:!0,configurable:!0,set:nT.bind(t,r)})},sT=(e,t)=>()=>(e&&(t=e(e=0)),t),uw,$w,ei,Ji,Cw,sP,oP,Hy,ja,ch,We,se,aP,zy,cP,Gy,lP,uP,Xf,fP,qy,Yy,Zf,hP,dP,mP,gP,Ua,xw,pP,Ve,yP,wP,Jy,Ka,lh,Pe,V,vP,Xy,bP,Zy,$P,CP,Qf,xP,Qy,ew,SP,eh,EP,TP,PP,AP,RP,Wa,Sw,kP,OP="0.15.6",ht,Xa,qi,uh,fh,Za,hh,dh,Yi,mh,gh,Sr,Ew,Tw,kt,lr,Pw,Aw,NP,BP,Rw,ec,nB,Ne,G,mB,GP,gB,qP,pB,yB,cw,wB,YP,JP,vB,lw,bB,$B,CB,xB,SB,ih,XP,EB;var Ow=te(()=>{tT=Object.defineProperty;uw={};iT(uw,{withErrorRecovery:()=>gw,tryLoadConfig:()=>tP,loadConfigWithResult:()=>QT,loadConfig:()=>bw,isRetryableError:()=>GT,isConfigNotFoundError:()=>zT,isBunfigError:()=>pw,globalPerformanceMonitor:()=>Ji,globalCache:()=>ei,getEnvOrDefault:()=>qT,generateConfigTypes:()=>rP,defaultGeneratedDir:()=>Aw,defaultConfigDir:()=>Pw,deepMergeWithArrayStrategy:()=>bh,deepMerge:()=>yw,createLibraryConfig:()=>nP,config:()=>eP,bunfigPlugin:()=>iP,applyEnvVarsToConfig:()=>zi,TypeGenerationError:()=>dh,SchemaValidationError:()=>Yi,PluginError:()=>gh,PerformanceMonitor:()=>yh,FileSystemError:()=>hh,ErrorFactory:()=>Sr,EnvVarError:()=>Za,EnvProcessor:()=>tc,ConfigValidator:()=>$h,ConfigValidationError:()=>uh,ConfigNotFoundError:()=>Xa,ConfigMergeError:()=>fh,ConfigLoader:()=>Ch,ConfigLoadError:()=>qi,ConfigFileLoader:()=>rc,ConfigCache:()=>ph,CacheUtils:()=>Cw,BunfigError:()=>ht,BrowserConfigError:()=>mh,ArrayMergeStrategies:()=>Ew});NP=sT(async()=>{$w=import.meta.require,ei=new ph,Ji=new yh,Cw={createKey:DT,isEquivalent:FT,estimateMemoryUsage:LT},sP=za(oh.cwd(),"config"),oP=za(oh.cwd(),"src/generated"),Hy=Ha.env.CLARITY_LOG_DIR||fT(MT(),"logs"),ja={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Hy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},ch=await _T(),We={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},se=We,aP=We.red,zy=We.green,cP=We.yellow,Gy=We.blue,lP=We.magenta,uP=We.cyan,Xf=We.white,fP=We.gray,qy=We.bgRed,Yy=We.bgYellow,Zf=We.bold,hP=We.dim,dP=We.italic,mP=We.underline,gP=We.reset,Ua={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xw={debug:"\uD83D\uDD0D",info:Gy("ℹ"),success:zy("✓"),warning:Yy(Xf(Zf(" WARN "))),error:qy(Xf(Zf(" ERROR ")))},pP=new qa("stacks"),Ve=new qa("bunfig",{showTags:!0}),yP=Qe(Gi.cwd(),"config"),wP=Qe(Gi.cwd(),"src/generated"),Jy=Va.env.CLARITY_LOG_DIR||lT(WT(),"logs"),Ka={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Jy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},lh=await VT(),Pe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},V=Pe,vP=Pe.red,Xy=Pe.green,bP=Pe.yellow,Zy=Pe.blue,$P=Pe.magenta,CP=Pe.cyan,Qf=Pe.white,xP=Pe.gray,Qy=Pe.bgRed,ew=Pe.bgYellow,SP=Pe.bgGray,eh=Pe.bold,EP=Pe.dim,TP=Pe.italic,PP=Pe.underline,AP=Pe.strikethrough,RP=Pe.reset,Wa={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Sw={debug:"\uD83D\uDD0D",info:Zy("ℹ"),success:Xy("✓"),warning:ew(Qf(eh(" WARN "))),error:Qy(Qf(eh(" ERROR ")))},kP=new Ja("stacks"),ht=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Xa=class extends ht{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},qi=class extends ht{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},uh=class extends ht{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},fh=class extends ht{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Za=class extends ht{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},hh=class extends ht{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},dh=class extends ht{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Yi=class extends ht{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},mh=class extends ht{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},gh=class extends ht{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Sr={configNotFound(e,t,r){return new Xa(e,t,r)},configLoad(e,t,r){return new qi(e,t,r)},configValidation(e,t,r){return new uh(e,t,r)},configMerge(e,t,r,n){return new fh(e,t,r,n)},envVar(e,t,r,n){return new Za(e,t,r,n)},fileSystem(e,t,r){return new hh(e,t,r)},typeGeneration(e,t,r){return new dh(e,t,r)},schemaValidation(e,t,r){return new Yi(e,t,r)},browserConfig(e,t,r,n){return new mh(e,t,r,n)},plugin(e,t,r){return new gh(e,t,r)}},Ew={replace:"replace",concat:"concat",smart:"smart"},Tw=/^https?:\/\//,kt=new Ja("bunfig",{showTags:!0}),lr=new Ch,Pw=et(zr.cwd(),"config"),Aw=et(zr.cwd(),"src/generated")});BP=Qa.env.CLARITY_LOG_DIR||DP(LP(),"logs"),Rw={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:BP,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ec={...Rw},nB=(async()=>{try{let{loadConfig:e}=await NP().then(()=>uw),t=await e({name:"clarity",alias:"logging",defaultConfig:Rw,cwd:Qa.cwd()});if(t)Object.assign(ec,t)}catch{}return ec})();Ne={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},G=Ne,mB=Ne.red,GP=Ne.green,gB=Ne.yellow,qP=Ne.blue,pB=Ne.magenta,yB=Ne.cyan,cw=Ne.white,wB=Ne.gray,YP=Ne.bgRed,JP=Ne.bgYellow,vB=Ne.bgGray,lw=Ne.bold,bB=Ne.dim,$B=Ne.italic,CB=Ne.underline,xB=Ne.strikethrough,SB=Ne.reset,ih={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},XP={debug:"\uD83D\uDD0D",info:qP("ℹ"),success:GP("✓"),warning:JP(cw(lw(" WARN "))),error:YP(cw(lw(" ERROR ")))};EB=new Xi("stacks")});var ri={};nl(ri,{authorizeSystemAccess:()=>QP,debugLog:()=>m,execSudoSync:()=>Tr,extractHostname:()=>nA,getPrimaryDomain:()=>sc,getSudoPassword:()=>Er,isMultiProxyConfig:()=>oc,isMultiProxyOptions:()=>Gr,isProcessElevated:()=>Zi,isSingleProxyConfig:()=>iA,isSingleProxyOptions:()=>Qi,isValidRootCA:()=>xh,redactSensitive:()=>ic,resolvePathRewrite:()=>Sh,safeDeleteFile:()=>Eh,safeStringify:()=>ur,shouldReusePort:()=>ti});import{execSync as nc}from"node:child_process";import*as Dw from"node:fs/promises";function Er(){return process.env.SUDO_PASSWORD}function Zi(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function QP(e={}){if(process.platform==="win32")return!0;if(Zi()||!!Er())return!0;let t=e.exec??nc;try{return t("sudo -n true",{stdio:"ignore"}),!0}catch{if(!e.interactive)return!1}try{return t("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function Tr(e){if(Zi())return nc(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let t=Er(),r=e.replace(/'/g,"'\\''");if(t)return nc(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return nc(`sudo -n sh -c '${r}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function m(e,t,r){if(r)ZP.debug(`[rpx:${e}] ${t}`)}function ti(){let e=process.env.RPX_REUSE_PORT;return e==="1"||e==="true"}function rA(e){let t=e.toLowerCase();return eA.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function ic(e){if(Array.isArray(e))return e.map((r)=>ic(r));if(typeof e==="string")return tA.test(e)?Nw:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e)){if(rA(r)){t[r]=Nw;continue}t[r]=ic(n)}return t}function ur(e,t){return JSON.stringify(ic(e),null,t)}function nA(e){if(Gr(e))return e.proxies.map((t)=>{let r=t.to||"stacks.localhost";return r.startsWith("http")?new URL(r).hostname:r});if(Qi(e)){let t=e.to||"stacks.localhost";return[t.startsWith("http")?new URL(t).hostname:t]}return["stacks.localhost"]}function xh(e){return typeof e==="object"&&e!==null&&"certificate"in e&&"privateKey"in e&&typeof e.certificate==="string"&&typeof e.privateKey==="string"}function sc(e){if(!e)return"stacks.localhost";if(Gr(e)&&e.proxies.length>0)return e.proxies[0].to||"stacks.localhost";if(Qi(e))return e.to||"stacks.localhost";return"stacks.localhost"}function oc(e){return!!(e&&("proxies"in e)&&Array.isArray(e.proxies))}function Gr(e){return"proxies"in e&&Array.isArray(e.proxies)}function Qi(e){return"to"in e&&typeof e.to==="string"}function iA(e){return!!(e&&("to"in e)&&!("proxies"in e))}function Sh(e,t){if(!t||t.length===0)return null;for(let r of t)if(e===r.from||e.startsWith(`${r.from}/`)){let n=r.to.startsWith("http")?new URL(r.to).host:r.to,i=r.stripPrefix===!0?e.slice(r.from.length)||"/":e;return{targetHost:n,targetPath:i}}return null}async function Eh(e,t){try{await Dw.unlink(e),m("certificates",`Successfully deleted: ${e}`,t)}catch(r){if(r.code!=="ENOENT")m("certificates",`Warning: Could not delete ${e}: ${r}`,t)}}var ZP,Nw="[redacted]",eA,tA;var fe=te(()=>{Ow();ZP=new Xi("rpx",{showTags:!1});eA=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),tA=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as ac}from"node:child_process";import{homedir as sA}from"node:os";import{join as oA}from"node:path";function cc(){return oA(sA(),"Library/Keychains/login.keychain-db")}function Ph(){return[Ar,cc()]}function Fw(e,t=Th){let r=ac(`security find-certificate -a -c "${t}" -Z "${e}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let i of r.split(`
|
|
238
|
+
`)){let s=i.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(s)n.push(s[1].toUpperCase())}return n}function Ah(e){if(process.platform!=="darwin")return;let t=Hr(e.caPath);if(!t)return;let r=e.commonName??Th,n=e.keychains??Ph();for(let i of n)for(let s of Fw(i,r)){if(s===t)continue;try{if(i.startsWith("/Library"))Tr(`security delete-certificate -Z ${s} "${i}"`);else ac(`security delete-certificate -Z ${s} "${i}"`,{stdio:"ignore"});m("ssl",`Removed stale Root CA ${s} from ${i}`,e.verbose)}catch{}}}function Rh(e,t,r){if(process.platform!=="darwin")return lc(e,r);try{let i=ac(`security verify-cert -c "${e}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return m("ssl",`verify-cert ${t}: ${i?"trusted":"not trusted"}`,r?.verbose),i}catch{return!1}}function lc(e,t){let r=Hr(e);if(!r)return!1;for(let n of Ph())try{let i=ac(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let s of i.split(`
|
|
239
|
+
`))if(s.toUpperCase().includes("SHA-256")){if(s.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return m("ssl",`Root CA fingerprint found in ${n}`,t?.verbose),!0}}catch{}return!1}var Pr="-d -r trustRoot -p ssl -p basic",Ar="/Library/Keychains/System.keychain",Th="rpx.localhost";var kh=te(()=>{Pa();fe()});import{execSync as Oh}from"node:child_process";import we from"node:fs/promises";import*as Nh from"node:os";import{homedir as ni}from"node:os";import*as Iw from"node:path";import{join as ve}from"node:path";import*as Rr from"node:process";function Mw(e,t){return[...new Set(e.filter(Boolean))].map((r)=>({serverName:r,cert:t.cert,key:t.key}))}function _w(e,t,r){let n=ve(ni(),".stacks","ssl"),i=[...new Set([t,...e,"rpx.localhost"])];return{https:{certPath:Dh,keyPath:ve(n,"rpx.localhost.key"),caCertPath:ve(n,"rpx.localhost.ca.crt"),commonName:t},verbose:r,regenerateUntrustedCerts:!0,proxies:i.map((s)=>({from:"localhost:1",to:s,cleanUrls:!1}))}}function uc(e){return{caCertPath:ve(e,cA),caKeyPath:ve(e,lA)}}async function uA(e,t){try{let[r,n]=await Promise.all([we.readFile(e.caCertPath,"utf8"),we.readFile(e.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return m("ssl",`Root CA files at ${e.caCertPath} look malformed, will regenerate`,t),null;return{certificate:r,privateKey:n}}catch(r){return m("ssl",`No existing Root CA at ${e.caCertPath} (${r.code||r}), will create one`,t),null}}async function Fh(e,t={}){await we.mkdir(e,{recursive:!0});let r=uc(e),n=await uA(r,t.verbose);if(n)return m("ssl",`Reusing existing Root CA from ${r.caCertPath}`,t.verbose),{...n,created:!1,paths:r};if(t.verbose)b.info("Generating Root CA certificate (one-time)...");let i=await Vi(t.caOptions??{});try{await Promise.all([we.writeFile(r.caCertPath,i.certificate),we.writeFile(r.caKeyPath,i.privateKey,{mode:384})]),m("ssl",`Persisted Root CA at ${r.caCertPath}`,t.verbose)}catch(s){throw m("ssl",`Error saving Root CA files: ${s}`,t.verbose),Error(`Failed to save Root CA files: ${s}`)}return{certificate:i.certificate,privateKey:i.privateKey,created:!0,paths:r}}function Lw(e){let t=new Set;t.add(e);let r=e.split(".");if(r.length>=3){let n=r[r.length-1],i=r[r.length-2],s=new Set(["co","com","org","net","ac","gov","edu"]);if(!(r.length===3&&n.length===2&&s.has(i)))t.add(`*.${r.slice(1).join(".")}`)}return Array.from(t)}function jw(e){let r=sc(e).replace(/\*/g,"wildcard"),n=ve(ni(),".stacks","ssl"),i=n;if(typeof e?.https==="object")return i=e.https.basePath&&e.https.basePath.trim()!==""?e.https.basePath:n,{caCertPath:e.https.caCertPath||ve(i,`${r}.ca.crt`),certPath:e.https.certPath||ve(i,`${r}.crt`),keyPath:e.https.keyPath||ve(i,`${r}.key`)};return{caCertPath:ve(i,`${r}.ca.crt`),certPath:ve(i,`${r}.crt`),keyPath:ve(i,`${r}.key`)}}function Bw(e){let t=new Set;if(Gr(e))e.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";Lw(n).forEach((i)=>t.add(i))});else if(Qi(e)){let r=e.to||"rpx.localhost";Lw(r).forEach((n)=>t.add(n))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function es(e){if(kr&&!e.forceRegenerate){m("ssl","Using cached SSL configuration",e.verbose);return}Lh();let t=Gr(e)?e.proxies.map((f)=>f.to):[e.to];m("ssl",`Generating certificate for domains: ${t.join(", ")}`,e.verbose);let r=ts(e,e.verbose),n=r.basePath||ve(ni(),".stacks","ssl"),i=await Fh(n,{caOptions:r,verbose:e.verbose}),s={certificate:i.certificate,privateKey:i.privateKey},o=i.created,c=i.paths;if(e.verbose)b.info(`Generating host certificate for: ${t.join(", ")}`);let a=await Un({...r,rootCA:{certificate:s.certificate,privateKey:s.privateKey}});try{await Promise.all([we.writeFile(r.certPath,a.certificate),we.writeFile(r.keyPath,a.privateKey),we.writeFile(r.caCertPath,s.certificate)]),m("ssl","Certificate files saved successfully",e.verbose)}catch(f){throw m("ssl",`Error saving certificate files: ${f}`,e.verbose),Error(`Failed to save certificate files: ${f}`)}if(o?!1:await fc(c.caCertPath,{verbose:e.verbose,regenerateUntrustedCerts:!0})){if(m("ssl","Root CA already trusted, skipping trust store update",e.verbose),e.verbose)b.success("Root CA is already trusted in system trust store");if(kr={key:a.privateKey,cert:a.certificate,ca:s.certificate},e.verbose)b.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(e.verbose)b.info("Adding certificate to system trust store (may require sudo permission)...");let u=!1;if(Rr.platform==="darwin")try{Ah({caPath:c.caCertPath,verbose:e.verbose});let f=cc();try{Oh(`security add-trusted-cert ${Pr} -k "${f}" "${c.caCertPath}"`,{stdio:"ignore"})}catch{}if(Tr(`security add-trusted-cert ${Pr} -k ${Ar} "${c.caCertPath}"`),e.verbose)b.success("Successfully added Root CA to system trust store");u=!0;let h=ve(n,"trust-rpx-cert.sh"),d=`#!/bin/bash
|
|
182
240
|
echo "Trusting RPX Root CA"
|
|
183
241
|
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
184
242
|
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
185
243
|
if [ -n "$SUDO_PASSWORD" ]
|
|
186
244
|
then
|
|
187
245
|
printf '%s
|
|
188
|
-
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${
|
|
246
|
+
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${Pr} -k ${Ar} "${c.caCertPath}"
|
|
189
247
|
else
|
|
190
|
-
sudo security add-trusted-cert ${
|
|
248
|
+
sudo security add-trusted-cert ${Pr} -k ${Ar} "${c.caCertPath}"
|
|
191
249
|
fi
|
|
192
250
|
echo "Root CA trusted! Please restart your browser."
|
|
193
251
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
194
|
-
`;await
|
|
252
|
+
`;await we.writeFile(h,d,{mode:493})}catch(f){if(e.verbose)b.warn(`Could not add Root CA to trust store automatically: ${f}`);let h=ve(n,"trust-rpx-cert.sh"),d=`#!/bin/bash
|
|
195
253
|
echo "Trusting RPX Root CA"
|
|
196
254
|
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
197
255
|
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
198
256
|
if [ -n "$SUDO_PASSWORD" ]
|
|
199
257
|
then
|
|
200
258
|
printf '%s
|
|
201
|
-
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${
|
|
259
|
+
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${Pr} -k ${Ar} "${c.caCertPath}"
|
|
202
260
|
else
|
|
203
|
-
sudo security add-trusted-cert ${
|
|
261
|
+
sudo security add-trusted-cert ${Pr} -k ${Ar} "${c.caCertPath}"
|
|
204
262
|
fi
|
|
205
263
|
echo "Root CA trusted! Please restart your browser."
|
|
206
264
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
207
|
-
`;if(await
|
|
265
|
+
`;if(await we.writeFile(h,d,{mode:493}),e.verbose)b.info(`Created a trust helper script at: ${h}`),b.info(`If you're still having certificate issues, run: sh ${h}`)}else if(Rr.platform==="linux")try{let{exec:f}=await import("node:child_process"),h="/usr/local/share/ca-certificates/rpx",d=`
|
|
208
266
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
209
|
-
cp "${
|
|
267
|
+
cp "${c.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
210
268
|
update-ca-certificates
|
|
211
269
|
echo "RPX Root CA installed. Please restart your browser."
|
|
212
|
-
`,
|
|
213
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${
|
|
270
|
+
`,y=ve(Nh.tmpdir(),`rpx-trust-${Date.now()}.sh`);await we.writeFile(y,d,{mode:493}),await new Promise((g)=>{f(`sudo bash "${y}"`,(p)=>{if(p){if(e.verbose)b.warn(`Could not trust certificates: ${p}`);g(!1)}else{if(e.verbose)b.success("Successfully added certificates to system trust store");g(!0)}})}),await we.unlink(y).catch(()=>{}),u=!0}catch(f){if(e.verbose)b.warn(`Failed to trust certificates: ${f}`)}else if(Rr.platform==="win32")try{let f=`
|
|
271
|
+
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${c.caCertPath.replace(/\//g,"\\")}")
|
|
214
272
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
215
273
|
$store.Open("ReadWrite")
|
|
216
274
|
$store.Add($cert)
|
|
217
275
|
$store.Close()
|
|
218
276
|
Write-Host "Root CA trusted successfully!"
|
|
219
|
-
`,
|
|
220
|
-
`)){let
|
|
221
|
-
`),s=
|
|
222
|
-
`,g);if(p===-1)p=
|
|
223
|
-
host: ${
|
|
277
|
+
`,h=ve(Nh.tmpdir(),"rpx-trust.ps1");if(await we.writeFile(h,f),Oh(`powershell -ExecutionPolicy Bypass -File "${h}"`),e.verbose)b.success("Successfully added certificate to Windows trust store");u=!0}catch(f){if(e.verbose)b.warn(`Could not trust certificate: ${f}`)}else try{await Ea(a,s.certificate,r),u=!0}catch(f){if(e.verbose)b.warn(`Could not add certificate to trust store: ${f}`)}if(kr={key:a.privateKey,cert:a.certificate,ca:s.certificate},e.verbose)b.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!u&&e.verbose)b.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),b.warn("This will bypass the warning and you should only need to do it once")}function Lh(){kr=null}async function Or(e){if(!e)return null;if(kr)return kr;let t=ts(e);try{let[r,n,i]=await Promise.all([we.access(t.keyPath).then(()=>!0).catch(()=>!1),we.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?we.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return m("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${t.keyPath}, ${t.certPath}`,e.verbose),null;let s="regenerateUntrustedCerts"in e,o=e.regenerateUntrustedCerts,c=s?o!==!1:!0;m("ssl",`Trust check: hasFlag=${s}, flagValue=${o}, shouldCheckTrust=${c}`,e.verbose);let a=t.basePath||ve(ni(),".stacks","ssl"),l=uc(a);if(!(c?await fc(l.caCertPath,e):!0))return m("ssl","Root CA exists but is not trusted, will regenerate",e.verbose),null;let[f,h,d]=await Promise.all([we.readFile(t.keyPath,"utf8"),we.readFile(t.certPath,"utf8"),i&&t.caCertPath?we.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(d&&!d.includes("-----BEGIN CERTIFICATE-----"))return m("ssl","Invalid root CA certificate content, will regenerate",e.verbose),null;if(Gr(e))try{let{X509Certificate:y}=await import("node:crypto"),p=new y(h).subjectAltName||"",v=e.proxies.map((P)=>P.to).filter((P)=>!p.includes(`DNS:${P}`));if(v.length>0)return m("ssl",`Certificate missing SANs for: ${v.join(", ")}, will regenerate`,e.verbose),null}catch(y){m("ssl",`Could not verify cert SANs: ${y}`,e.verbose)}return m("ssl","Successfully loaded existing certificates",e.verbose),kr={key:f,cert:h,ca:d},kr}catch(r){return m("ssl",`Error checking existing certificates: ${r}`,e.verbose),null}}function ts(e,t){let r=sc(e);m("ssl",`Primary domain: ${r}`,t);let n=jw(e),i=ve(ni(),".stacks","ssl");if(typeof e.https==="object"){let s=e.https.basePath&&e.https.basePath.trim()!==""?e.https.basePath:i,o=e.https.altNameIPs?.filter((a)=>typeof a==="string"&&a.length>0),c={domain:r,hostCertCN:r,basePath:s,caCertPath:e.https.caCertPath||n.caCertPath,certPath:e.https.certPath||n.certPath,keyPath:e.https.keyPath||n.keyPath,altNameIPs:o&&o.length>0?o:["127.0.0.1","::1"],altNameURIs:[],commonName:e.https.commonName||r,organizationName:e.https.organizationName||"Local Development",countryName:e.https.countryName||"US",stateName:e.https.stateName||"California",localityName:e.https.localityName||"Playa Vista",validityDays:e.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(Bw(e)).map((a)=>({type:2,value:a}))};if(xh(e.https.rootCA))c.rootCA=e.https.rootCA;return c}return{domain:r,hostCertCN:r,basePath:i,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(Bw(e)).map((s)=>({type:2,value:s}))}}async function Uw(e,t){let r=jw({to:e,verbose:t}),n=[r.caCertPath,r.certPath,r.keyPath];m("certificates","Attempting to clean up relating certificates",t),await Promise.all(n.map((i)=>Eh(i,t)))}async function fc(e,t){try{if(m("ssl",`Checking if certificate is trusted: ${e}`,t?.verbose),Rr.platform==="darwin"){if(t?.serverName)return Rh(e,t.serverName,{verbose:t?.verbose});return lc(e,{verbose:t?.verbose})}else if(Rr.platform==="win32")try{let r=_f(e)||"";if(!r)return m("ssl","Could not extract certificate subject",t?.verbose),!1;let n=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(Oh(n).toString().includes(r))return m("ssl","Certificate found in trusted root store",t?.verbose),!0;return m("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Windows: ${r}`,t?.verbose),!1}else if(Rr.platform==="linux")try{let r=Hr(e);if(!r)return m("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let n=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let i of n){let s;try{s=await we.readdir(i)}catch{continue}for(let o of s){let c=Hr(Iw.join(i,o));if(c&&c===r)return m("ssl",`Certificate fingerprint found in ${i}`,t?.verbose),!0}}return m("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Linux: ${r}`,t?.verbose),!1}return m("ssl",`Platform ${Rr.platform} not supported for certificate trust check`,t?.verbose),!1}catch(r){return m("ssl",`Error checking if certificate is trusted: ${r}`,t?.verbose),!1}}var kr=null,Dh,cA="rpx-root-ca.crt",lA="rpx-root-ca.key";var hc=te(()=>{Hi();qt();Co();kh();fe();kh();Pa();Pa();Dh=ve(ni(),".stacks","ssl","rpx.localhost.crt")});function fA(e){return{enabled:e?.enabled??!1,path:e?.path??"/",interval:e?.interval??1e4,timeout:e?.timeout??2000,healthyThreshold:e?.healthyThreshold??2,unhealthyThreshold:e?.unhealthyThreshold??3}}function hA(e){return(Array.isArray(e)?e:[e]).map((r)=>{let n=typeof r==="string"?{url:r}:r;return{url:n.url,weight:n.weight&&n.weight>0?n.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function Kw(e){return(Array.isArray(e)?e:[e]).map((r)=>typeof r==="string"?r:r.url)}function qr(e){if(!e)return"localhost:5173";let t=Array.isArray(e)?e[0]:e;if(!t)return"localhost:5173";return typeof t==="string"?t:t.url}function rs(e,t){return{upstreams:hA(e),strategy:t?.strategy??"round-robin",healthCheck:fA(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function dA(e){let t=e.upstreams.filter((r)=>r.healthy);if(t.length===0&&e.upstreams.length===1)return e.upstreams;return t}function mA(e,t){let r=e.cursor%t.length;return e.cursor=(e.cursor+1)%t.length,t[r]}function gA(e,t){if(e.wrrCurrentWeights.length!==t.length)e.wrrCurrentWeights=t.map(()=>0);let r=t.reduce((i,s)=>i+s.weight,0),n=0;for(let i=0;i<t.length;i++)if(e.wrrCurrentWeights[i]+=t[i].weight,e.wrrCurrentWeights[i]>e.wrrCurrentWeights[n])n=i;return e.wrrCurrentWeights[n]-=r,t[n]}function pA(e){let t=e[0];for(let r=1;r<e.length;r++)if(e[r].activeConnections<t.activeConnections)t=e[r];return t}function Ww(e){let t=dA(e);if(t.length===0)return;if(t.length===1)return t[0];switch(e.strategy){case"weighted-round-robin":return gA(e,t);case"least-connections":return pA(t);case"round-robin":default:return mA(e,t)}}function dc(e,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=e.healthCheck.healthyThreshold)t.healthy=!0}function ns(e,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=e.healthCheck.unhealthyThreshold)t.healthy=!1}function yA(e){let t=e.lastIndexOf(":");if(t===-1)return{hostname:e,port:80};let r=Number(e.slice(t+1));return{hostname:e.slice(0,t),port:Number.isFinite(r)?r:80}}async function wA(e,t){let{hostname:r,port:n}=yA(t.url),i=new AbortController,s=setTimeout(()=>i.abort(),e.healthCheck.timeout);try{(await fetch(`http://${r}:${n}${e.healthCheck.path}`,{signal:i.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),dc(e,t)}catch{ns(e,t)}finally{clearTimeout(s)}}function is(e){if(!e.healthCheck.enabled||e.healthCheckTimer||e.upstreams.length<2)return;let t=setInterval(()=>{for(let r of e.upstreams)wA(e,r)},e.healthCheck.interval);t.unref?.(),e.healthCheckTimer=t}function ii(e){if(e.healthCheckTimer)clearInterval(e.healthCheckTimer),e.healthCheckTimer=null}import{createHash as Hw,timingSafeEqual as Vw}from"node:crypto";import{readFileSync as vA}from"node:fs";function ss(e,t){let r=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8");if(r.length!==n.length)return Vw(r,r),!1;return Vw(r,n)}function $A(e,t){let r=(h)=>Hw("md5").update(h).digest(),n=Buffer.from(e,"utf8"),i=Buffer.from(t,"utf8"),s=r(Buffer.concat([n,i,n])),o=[n,Buffer.from("$apr1$","utf8"),i];for(let h=n.length;h>0;h-=16)o.push(s.subarray(0,Math.min(h,16)));for(let h=n.length;h>0;h>>=1)o.push(h&1?Buffer.from([0]):n.subarray(0,1));let c=r(Buffer.concat(o));for(let h=0;h<1000;h++){let d=[];if(d.push(h&1?n:c.subarray(0,16)),h%3)d.push(i);if(h%7)d.push(n);d.push(h&1?c.subarray(0,16):n),c=r(Buffer.concat(d))}let a="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",l=(h,d)=>{let y="",g=h;for(let p=0;p<d;p++)y+=a[g&63],g>>=6;return y},u=c,f="";return f+=l(u[0]<<16|u[6]<<8|u[12],4),f+=l(u[1]<<16|u[7]<<8|u[13],4),f+=l(u[2]<<16|u[8]<<8|u[14],4),f+=l(u[3]<<16|u[9]<<8|u[15],4),f+=l(u[4]<<16|u[10]<<8|u[5],4),f+=l(u[11],2),`$apr1$${t}$${f}`}function CA(e,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(e,t)}catch{return!1}if(t.startsWith("$apr1$")){let n=t.split("$")[2]??"";return ss($A(e,n),t)}if(t.startsWith("{SHA}")){let r=Hw("sha1").update(e,"utf8").digest("base64");return ss(`{SHA}${r}`,t)}return ss(e,t)}function xA(e){let t=new Map;for(let r of e.split(`
|
|
278
|
+
`)){let n=r.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf(":");if(i<=0)continue;t.set(n.slice(0,i),n.slice(i+1))}return t}function os(e){if(!e)return;let t=(e.realm??"").trim()||"Restricted",r=[];if(e.username)r.push({username:e.username,password:e.password??""});for(let s of e.users??[])if(s?.username)r.push({username:s.username,password:s.password??""});let n;if(e.htpasswdFile)try{n=xA(vA(e.htpasswdFile,"utf8"))}catch{n=void 0}if(r.length===0&&(!n||n.size===0))return;return{realm:t,verify:(s,o)=>{let c=!1;for(let a of r)if(ss(s,a.username)&&ss(o,a.password))c=!0;if(n){let a=n.get(s);if(a&&CA(o,a))c=!0}return c}}}function zw(e,t,r){if(t.startsWith(bA))return;let n=e.headers.get("authorization")??"",i=n.indexOf(" "),s=i===-1?n:n.slice(0,i),o=i===-1?"":n.slice(i+1).trim();if(s.toLowerCase()==="basic"&&o){let a="";try{a=Buffer.from(o,"base64").toString("utf8")}catch{a=""}let l=a.indexOf(":");if(l>=0&&r.verify(a.slice(0,l),a.slice(l+1)))return}let c=r.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${c}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var bA="/.well-known/acme-challenge/";var mc=()=>{};function TA(e){return EA.has(e.toUpperCase())}function PA(){let e=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(e)&&e>0?e:30000}function AA(e){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:e*8}function RA(){let e=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(e)&&e>0?e:0}function kA(){let e=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(e)&&e>0?e:0}function OA(){let e=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(e)&&e>0?e:256}class Xw{socket=null;buf=new Uint8Array(NA);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(e){let t=this.socket,r=t.write(e);while(r<e.length){if(this.closed)throw gc;await new Promise((n)=>{this.drainWaiter=n}),r+=t.write(e.subarray(r))}}wakeDrain(){let e=this.drainWaiter;if(e)this.drainWaiter=null,e()}push(e){if(this.bodyQueue){let t=e.length<=this.bodyRemaining?e.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(e.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<e.length)this.appendToBuf(e.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(e),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>DA)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=FA)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(e){let t=this.len+e.length;if(t>this.buf.length){let r=new Uint8Array(Math.max(this.buf.length*2,t));r.set(this.buf.subarray(0,this.len)),this.buf=r}this.buf.set(e,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let e=this.waiter;if(e)this.waiter=null,e()}waitForData(e){if(this.len>e||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((e)=>{this.waiter=e})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class Zw{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=PA();maxWaiters;checkoutIdleMs=RA();inUse=new Set;constructor(e,t,r,n=""){this.host=e;this.port=t;this.maxTotal=r;this.key=n;this.maxWaiters=AA(r)}trackCheckout(e){if(e.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(e),this.ensureSweeper()}dial(){let e=new Xw;return SA({hostname:this.host,port:this.port,socket:{data:(t,r)=>e.push(r),drain:()=>e.wakeDrain(),close:()=>e.markClosed(),end:()=>e.markClosed(),error:()=>e.markClosed(),connectError:()=>e.markClosed(),timeout:()=>e.markTimedOut()}}).then((t)=>{let r=t;r.setNoDelay?.(!0);let n=kA();if(n>0)r.timeout?.(n);return e.socket=t,e})}acquireIdleSync(){while(this.idle.length){let e=this.idle.pop();if(!e.closed)return e.socket?.ref(),e.pos=0,e.len=0,this.trackCheckout(e),e;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw Yr;let e=await this.waitForSlot();if(e===Yr)throw Yr;if(e)return e.pos=0,e.len=0,this.trackCheckout(e),e}this.open++;try{let e=await this.dial();return this.trackCheckout(e),e}catch(e){throw this.open--,this.wakeWaiter(),e}}waitForSlot(){return new Promise((e)=>{let t=!1,r=(s)=>{if(t)return;t=!0,clearTimeout(i),e(s)},n=(s)=>r(s),i=setTimeout(()=>{let s=this.waiters.indexOf(n);if(s!==-1)this.waiters.splice(s,1);r(Yr)},this.queueWaitMs);i.unref?.(),this.waiters.push(n)})}release(e){if(this.inUse.delete(e),e.closed){this.open--,this.wakeWaiter();return}e.clearStreaming(),e.compact(),e.fresh=!1;let t=this.waiters.shift();if(t){e.socket?.ref(),this.trackCheckout(e),t(e);return}e.idleSince=Date.now(),e.socket?.unref(),this.idle.push(e),this.ensureSweeper()}destroy(e){this.inUse.delete(e),e.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let e=this.waiters.shift();if(e)e(null)}ensureSweeper(){if(this.sweeper)return;let e=this.checkoutIdleMs>0?Math.min(Bh,this.checkoutIdleMs):Bh;this.sweeper=setInterval(()=>this.sweep(),e),this.sweeper.unref?.()}sweep(){let e=Date.now(),t=e-Bh;if(this.idle.length){let r=[];for(let n of this.idle)if(n.closed||n.idleSince<=t)n.destroy(),this.open--;else r.push(n);this.idle=r}if(this.checkoutIdleMs>0&&this.inUse.size){let r=e-this.checkoutIdleMs;for(let n of this.inUse)if(!n.closed&&n.lastActivityAt>0&&n.lastActivityAt<=r)n.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&pc.get(this.key)===this)pc.delete(this.key)}}}function _A(e,t){let r=pc.get(e);if(!r){let n=e.lastIndexOf(":"),i=n===-1?e:e.slice(0,n),s=n===-1?80:Number(e.slice(n+1));r=new Zw(i,s,t??OA(),e),pc.set(e,r)}return r}function Gw(e,t,r){for(let n=r+3;n<t;n++)if(e[n]===10&&e[n-1]===13&&e[n-2]===10&&e[n-3]===13)return n-3;return-1}function jA(e,t,r){let n=Jw.decode(e.subarray(t,r)),i=n.indexOf(`\r
|
|
279
|
+
`),s=i===-1?n:n.slice(0,i),o=s.indexOf(" "),c=Number.parseInt(s.slice(o+1,o+5),10),a=s.startsWith("HTTP/1.0"),l=[],u=-1,f=!1,h=a,d=!1,y=!1,g=i===-1?n.length:i+2;while(g<n.length){let p=n.indexOf(`\r
|
|
280
|
+
`,g);if(p===-1)p=n.length;let w=n.slice(g,p);if(g=p+2,w==="")continue;let v=w.indexOf(":");if(v===-1)continue;let P=w.slice(0,v),A=w.slice(v+1).trim(),R=P.charCodeAt(0)|32;if(R===99||R===116||R===107){let D=P.toLowerCase();if(D==="content-length"){let F=/^\d+$/.test(A)?Number(A):Number.NaN;if(!Number.isSafeInteger(F)||u>=0&&u!==F)y=!0;else u=F;continue}if(D==="transfer-encoding"){if(A.toLowerCase().includes("chunked"))f=!0;continue}if(D==="connection"){let F=A.toLowerCase();if(F.includes("close"))h=!0;if(F.includes("keep-alive"))d=!0;continue}if(D==="keep-alive")continue}l.push([P,A])}if(a&&d)h=!1;if(f&&u>=0)u=-1;return{status:c,headerEnd:r,headers:l,contentLength:u,chunked:f,closeConn:h,malformed:y}}function UA(e,t){return t||e===204||e===304}async function Qw(e){let{hostPort:t,method:r,path:n,reqHeaders:i,forwardedHost:s,clientIp:o,originOverride:c,body:a}=e,l=r==="HEAD",u=i.get("accept")?.toLowerCase()??"";if(i.get("expect")||i.get("upgrade")||u.includes("text/event-stream"))throw as;let f=null;if(a){let g=i.get("content-length"),p=g?Number.parseInt(g,10):Number.NaN;if(Number.isNaN(p)||p>qw)throw as;if(f=await qA(a),f===null)throw as}let h=GA(r,n,i,t,s,o,c,f),d=h;if(f&&f.length)d=new Uint8Array(h.length+f.length),d.set(h),d.set(f,h.length);let y=_A(t,e.maxPerHost);for(let g=0;;g++){if(g>0)await new Promise((w)=>{setTimeout(w,g)});let p;try{p=y.acquireIdleSync()??await y.acquireOrDial()}catch(w){if(w!==Yr&&g<4)continue;throw w}try{let w=p.socket.write(d);if(w<d.length)await p.writeAll(d.subarray(w));return await WA(y,p,l,e.signal)}catch(w){let v=w===gc&&g<4&&(p.fresh||TA(r));if(y.destroy(p),v)continue;if(w===gc)throw Error("upstream closed connection");throw w}}}async function KA(e){let t=Gw(e.buf,e.len,e.pos);while(t===-1){if(e.closed){if(e.timedOut)throw Ih;if(e.len===e.pos)throw gc;throw Error("upstream closed mid-header")}if(e.len-e.pos>Yw)throw Error("upstream header block too large");await e.waitForData(e.len),t=Gw(e.buf,e.len,e.pos)}return t}async function WA(e,t,r,n){let i;for(;;){let o=await KA(t);if(i=jA(t.buf,t.pos,o),t.pos=o+4,i.status>=100&&i.status<200)continue;break}if(i.malformed)throw e.destroy(t),Error("upstream sent malformed response framing");let s=i.headers;if(UA(i.status,r))return ev(e,t,i.closeConn),new Response(null,{status:i.status,headers:s});if(i.chunked)return new Response(zA(e,t,i.closeConn,n),{status:i.status,headers:s});if(i.contentLength>=0){if(t.len-t.pos>=i.contentLength){let c=t.pos+i.contentLength,a=t.len>c,l=null;if(i.contentLength>=LA)l=t.buf.subarray(t.pos,c),t.buf=new Uint8Array(BA);else if(i.contentLength>0)l=t.buf.slice(t.pos,c);if(t.pos=0,t.len=0,i.closeConn||a)e.destroy(t);else e.release(t);return new Response(l,{status:i.status,headers:s})}return new Response(VA(e,t,i.contentLength,i.closeConn),{status:i.status,headers:s})}return new Response(HA(t),{status:i.status,headers:s})}function ev(e,t,r){if(r||t.pos!==t.len)e.destroy(t);else e.release(t)}function VA(e,t,r,n){let i=t.len-t.pos,s=i>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=r-i,t.queuedBytes=0,t.streamingBody=!0;let o=(c)=>{if(t.bodyQueue=null,n||t.len>0)e.destroy(t);else e.release(t);c.close()};return new ReadableStream({start(c){if(s)c.enqueue(s);if(t.bodyRemaining===0&&t.bodyQueue.length===0)o(c)},async pull(c){for(;;){let a=t.bodyQueue;if(a&&a.length>0){let l=a.shift();if(t.queuedBytes-=l.length,t.resumeIfDrained(),c.enqueue(l),t.bodyRemaining===0&&a.length===0)o(c);return}if(t.bodyRemaining===0){if(t.bodyQueue)o(c);return}if(t.closed){t.bodyQueue=null,e.destroy(t),c.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,e.destroy(t)}})}function HA(e){return e.streamingBody=!0,new ReadableStream({async pull(t){for(;;){if(e.len>e.pos){t.enqueue(e.buf.slice(e.pos,e.len)),e.pos=e.len,e.resumeIfDrained();return}if(e.closed){e.destroy(),t.close();return}await e.waitForData(e.len)}},cancel(){e.destroy()}})}function zA(e,t,r,n){t.streamingBody=!0;let i=0,s=!1,o=!1,c,a=()=>n?.removeEventListener("abort",l),l=()=>{if(o)return;o=!0,e.destroy(t);try{c?.close()}catch{}};async function u(f=!1){for(;;){for(let h=t.pos;h+1<t.len;h++)if(t.buf[h]===13&&t.buf[h+1]===10){let d=Jw.decode(t.buf.subarray(t.pos,h));return t.pos=h+2,d}if(t.closed){if(f&&t.pos===t.len)return null;throw Error("upstream closed mid-chunk-header")}if(t.len-t.pos>Yw)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({start(f){if(c=f,n?.aborted)l();else n?.addEventListener("abort",l,{once:!0})},async pull(f){try{for(;;){if(i>0){if(t.len===t.pos){if(t.closed){e.destroy(t),f.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let g=Math.min(i,t.len-t.pos);if(f.enqueue(t.buf.slice(t.pos,t.pos+g)),t.pos+=g,i-=g,t.resumeIfDrained(),i===0)s=!0;return}if(s)await u(),s=!1;let h=await u(!0);if(h===null){e.destroy(t),a(),f.close();return}let d=h.indexOf(";"),y=Number.parseInt(d===-1?h:h.slice(0,d),16);if(!Number.isInteger(y)||y<0){e.destroy(t),f.error(Error("upstream sent malformed chunk size"));return}if(y===0){for(;;)if(await u()==="")break;ev(e,t,r),a(),f.close();return}i=y}}catch(h){if(e.destroy(t),a(),!o)f.error(h)}},cancel(){o=!0,a(),e.destroy(t)}})}function GA(e,t,r,n,i,s,o,c){let a=s||"127.0.0.1",l=`${e} ${t} HTTP/1.1\r
|
|
281
|
+
host: ${n}\r
|
|
224
282
|
x-forwarded-for: ${a}\r
|
|
225
283
|
x-real-ip: ${a}\r
|
|
226
284
|
x-forwarded-proto: https\r
|
|
227
|
-
x-forwarded-host: ${
|
|
285
|
+
x-forwarded-host: ${i}\r
|
|
228
286
|
`;if(o!==void 0)l+=`origin: ${o}\r
|
|
229
|
-
`;let u=!1;for(let[f,h]of r){let d=f.toLowerCase();if(
|
|
287
|
+
`;let u=!1;for(let[f,h]of r){let d=f.toLowerCase();if(MA.has(d))continue;if(o!==void 0&&d==="origin")continue;if(d==="content-length")u=!0;l+=`${f}: ${h}\r
|
|
230
288
|
`}if(l+=`connection: keep-alive\r
|
|
231
289
|
`,c&&!u)l+=`content-length: ${c.length}\r
|
|
232
290
|
`;return l+=`\r
|
|
233
|
-
`,YT.encode(l)}async function iP(e){let t=e.getReader(),r=[],i=0;for(;;){let{done:o,value:c}=await t.read();if(o)break;if(c){if(i+=c.length,i>yy)return t.cancel().catch(()=>{}),null;r.push(c)}}if(r.length===1)return r[0];let n=new Uint8Array(i),s=0;for(let o of r)n.set(o,s),s+=o.length;return n}var DT,Pn,wa,FT,df,_r,yy=1048576,hf=30000,UT=16384,wy=262144,WT=2097152,KT=524288,HT=8192,VT=4096,YT,vy,zT,va;var Sy=Q(()=>{({connect:DT}=Bun),Pn=Symbol("rpx.pool.fallback"),wa=Symbol("rpx.pool.stale"),FT=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);df=Symbol("rpx.pool.timeout"),_r=Symbol("rpx.pool.busy");YT=new TextEncoder,vy=new TextDecoder,zT=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host","x-real-ip"]);va=new Map});function Ey(e){let t=typeof e==="string"?{to:e}:e,r=(t.to??"").trim();if(r&&!/^[a-z][\w+.-]*:\/\//i.test(r))r=`https://${r}`;return r=r.replace(/\/+$/,""),{to:r,status:t.status??301,preservePath:t.preservePath??!0}}function Ty(e,t,r){if(!e.preservePath)return e.to||"/";let i=`${t}${r}`;return i==="/"?`${e.to}/`:`${e.to}${i}`}import*as yt from"node:path";function ba(e,t){if(typeof e==="string")return{dir:e,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:e.dir,spa:e.spa??!1,pathRewriteStyle:e.pathRewriteStyle??"directory",maxAge:e.maxAge??0,cleanUrls:t}}function sP(e){let t=yt.extname(e).toLowerCase();return nP[t]??"application/octet-stream"}function oP(e){let t;try{t=decodeURIComponent(e)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=yt.posix.normalize(`/${t}`);if(r.split("/").includes(".."))return null;return r.replace(/^\/+/,"")}function aP(e,t){let r=oP(e);if(r===null)return null;let i=yt.posix.extname(r);if(t.cleanUrls&&i===".html"){let n=e.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:yt.join(t.dir,r),redirectTo:n||"/"}}if(r===""||e.endsWith("/"))return{filePath:yt.join(t.dir,r,"index.html")};if(i!=="")return{filePath:yt.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:yt.join(t.dir,`${r}.html`)};return{filePath:yt.join(t.dir,r,"index.html")}}async function Py(e,t){let r=aP(e,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let i=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",n=Bun.file(r.filePath);if(await n.exists())return new Response(n,{status:200,headers:{"Content-Type":sP(r.filePath),"Cache-Control":i}});if(t.spa){let s=yt.join(t.dir,"index.html"),o=Bun.file(s);if(await o.exists())return new Response(o,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var nP;var $a=Q(()=>{nP={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".pdf":"application/pdf",".wasm":"application/wasm",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"}});function cP(e,t){let r;try{r=t?.requestIP?.(e)?.address}catch{return mf}if(!r)return mf;return/^[0-9a-f.:]{1,45}$/i.test(r)?r:mf}function lP(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function dP(e){if(!e)return!1;let t=null;for(let r of e.split(",")){let[i,...n]=r.trim().split(";"),s=i.trim().toLowerCase();if(s!=="gzip"&&s!=="*")continue;let o=1;for(let c of n){let a=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(c);if(a)o=Number.parseFloat(a[1])}if(s==="gzip")return Number.isFinite(o)&&o>0;t=o}return t!==null&&Number.isFinite(t)&&t>0}function mP(e){let t=e.get("vary");if(!t){e.set("vary","Accept-Encoding");return}if(!t.split(",").some((r)=>r.trim().toLowerCase()==="accept-encoding"))e.set("vary",`${t}, Accept-Encoding`)}function gP(e,t){if(e.method==="HEAD"||t.status===204||t.status===206||t.status===304||!t.body||t.headers.has("content-encoding")||t.headers.get("cache-control")?.toLowerCase().includes("no-transform")||e.headers.has("range")||!dP(e.headers.get("accept-encoding")))return t;let r=t.headers.get("content-type")?.toLowerCase()??"";if(!fP.some((s)=>r.startsWith(s)))return t;let i=t.headers.get("content-length");if(i!==null){let s=Number.parseInt(i,10);if(Number.isFinite(s)&&s<hP)return t}let n=new Headers(t.headers);return n.set("content-encoding","gzip"),mP(n),n.delete("content-length"),n.delete("content-md5"),n.delete("content-digest"),n.delete("accept-ranges"),n.delete("etag"),new Response(t.body.pipeThrough(new CompressionStream("gzip")),{status:t.status,statusText:t.statusText,headers:n})}function pP(e){let t=e.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function ky(e,t){if(!t||t==="/")return e;if(e===t)return"/";if(e.startsWith(`${t}/`)){let r=e.slice(t.length);return r===""?"/":r}return e}function Ry(e){if(e.upstreamPool)return hy(e.upstreamPool);if(e.sourceHost)return{url:e.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function Ay(e,t,r,i){let n=r?.url??t.sourceHost??"",o=t.stripBasePathPrefix??!1?ky(e,t.basePath):e,c=Zu(o,t.pathRewrites);if(c)n=c.targetHost,o=c.targetPath,m("request",`Path rewrite: ${e} → ${n}${o}`,i);return{targetHost:n,targetPath:o}}function yP(e){let t=e.indexOf("://"),r=t===-1?e.indexOf("/"):e.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let i=e.indexOf("?",r);if(i===-1)return{pathname:e.slice(r),search:""};return{pathname:e.slice(r,i),search:e.slice(i)}}function Rn(e,t,r){let i=async(n,s)=>{let{pathname:o,search:c}=yP(n.url),a=pP(n),l=cP(n,s),u=e(a,o);if(!u&&r){let w=await r(a,o,n);if(w instanceof Response)return w;if(w&&w.retry)u=e(a,o)}if(!u)return m("request",`No route found for host: ${a}`,t),new Response(`No proxy configured for ${a}`,{status:404});if(u.auth){let w=gy(n,o,u.auth);if(w)return m("request",`401 challenge for ${a}${o}`,t),w}if(u.redirect){let w=Ty(u.redirect,o,c);return m("request",`${u.redirect.status} redirect ${a}${o} → ${w}`,t),new Response(null,{status:u.redirect.status,headers:{location:w}})}if(u.static){let b=u.stripBasePathPrefix??!0?ky(o,u.basePath):o;return Py(b,u.static)}if(n.headers.get("upgrade")?.toLowerCase()==="websocket"){let w=Ry(u);if(!s||!w)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:b,targetPath:P}=Ay(o,u,w,t),R=`ws://${b}${P}${c}`,v={};for(let[D,W]of n.headers)if(!uP.has(D.toLowerCase())&&D.toLowerCase()!=="host")v[D]=W;v.host=b,v["x-forwarded-for"]=l,v["x-real-ip"]=l,v["x-forwarded-proto"]="https",v["x-forwarded-host"]=a;let T={targetUrl:R,forwardHeaders:v};if(s.upgrade(n,{data:T})){m("ws",`upgraded ${a}${P} → ${R}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let f=Ry(u);if(!f)return new Response(`No upstream configured for ${a}`,{status:502});if(u.cleanUrls&&o.endsWith(".html")){let w=o.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:w}})}let{targetHost:h,targetPath:d}=Ay(o,u,f,t),y=u.changeOrigin?`http://${h}`:void 0,g=n.body!=null&&n.method!=="GET"&&n.method!=="HEAD",p=u.upstreamPool;if(p)f.activeConnections++;try{let w=await xy({hostPort:h,method:n.method,path:`${d}${c}`,reqHeaders:n.headers,forwardedHost:a,clientIp:l,originOverride:y,body:n.body,signal:n.signal});if(p)pa(p,f);return w}catch(w){if(w===df){if(m("request",`Upstream timeout for ${a}`,t),p)Cn(p,f);return new Response("Gateway Timeout",{status:504})}if(w===_r)return m("request",`Upstream pool saturated for ${a}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(w===Pn||!g)try{let b=new Headers(n.headers);if(b.set("host",h),b.set("x-forwarded-for",l),b.set("x-real-ip",l),b.set("x-forwarded-proto","https"),b.set("x-forwarded-host",a),y!==void 0)b.set("origin",y);let P=await fetch(`http://${h}${d}${c}`,{method:n.method,headers:b,body:n.body,redirect:"manual"});if(p)pa(p,f);return P}catch(b){if(m("request",`Proxy error for ${a}: ${b}`,t),p)Cn(p,f);return new Response(`Proxy Error: ${b}`,{status:502})}if(m("request",`Proxy error for ${a}: ${w}`,t),p)Cn(p,f);return new Response(`Proxy Error: ${w}`,{status:502})}finally{if(p)f.activeConnections--}};return async(n,s)=>{try{let o=await i(n,s);return o?gP(n,o):o}catch(o){return m("request",`Unhandled proxy handler error: ${o}`,t),new Response("Bad Gateway",{status:502})}}}function An(e){let t=new WeakMap,r=lP();return{open(i){let{targetUrl:n,forwardHeaders:s}=i.data,o;try{o=new WebSocket(n,{headers:s})}catch(a){m("ws",`failed to open upstream ${n}: ${a}`,e),i.close(1011,"upstream connect failed");return}o.binaryType="arraybuffer";let c={upstream:o,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(i,c),o.addEventListener("open",()=>{c.upstreamOpen=!0;for(let a of c.pending)o.send(a);c.pending=[],c.pendingBytes=0}),o.addEventListener("message",(a)=>{i.send(a.data)}),o.addEventListener("close",(a)=>{try{i.close(a.code||1000,a.reason||"")}catch{}}),o.addEventListener("error",()=>{m("ws",`upstream error for ${n}`,e);try{i.close(1011,"upstream error")}catch{}})},message(i,n){let s=t.get(i);if(!s)return;let o=typeof n==="string"?n:new Uint8Array(n);if(s.upstreamOpen){s.upstream.send(o);return}let c=typeof o==="string"?Buffer.byteLength(o):o.byteLength;if(s.pendingBytes+c>r){m("ws",`pending buffer would exceed ${r}B before upstream open; closing socket`,e);try{i.close(1009,"buffer limit")}catch{}try{s.upstream.close(1011,"client buffer overflow")}catch{}t.delete(i);return}s.pending.push(o),s.pendingBytes+=c},close(i,n,s){let o=t.get(i);if(!o)return;t.delete(i);try{o.upstream.close(n||1000,s||"")}catch{}}}}var mf="127.0.0.1",uP,fP,hP=1024;var gf=Q(()=>{ya();Sy();$a();he();uP=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]),fP=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"]});import*as Ny from"node:fs";import*as Dy from"node:path";function xa(e,t){if(!e||!t.startsWith(Oy))return null;let r=t.slice(Oy.length);if(!r||!/^[A-Za-z0-9_-]+$/.test(r))return null;try{return Ny.readFileSync(Dy.join(e,r),"utf8")}catch{return null}}var Oy="/.well-known/acme-challenge/";var pf=()=>{};function rr(e){if(!e||e==="/")return"/";let t=e.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function wP(e,t){if(t==="/")return!0;if(e===t)return!0;return e.startsWith(`${t}/`)}function kn(e){let t=new Map;for(let i of e){let n=rr(i.path),s=t.get(i.host);if(!s)s=new Map,t.set(i.host,s);s.set(n,i.route)}let r=new Map;for(let[i,n]of t){let s=[];for(let[o,c]of n)s.push({path:o,route:c});s.sort((o,c)=>c.path.length-o.path.length),r.set(i,s)}return r}function yf(e,t){let r=e.get(t);if(r!==void 0)return r;let i,n=-1;for(let[s,o]of e){if(!ai(s))continue;if(Or(t,s)){let c=s.length-1;if(c>n)n=c,i=o}}return i}function On(e,t,r){let i=yf(e,t);if(!i)return;for(let n of i)if(wP(r,n.path))return n.route;return}var Ca=()=>{};import*as Nn from"node:fs/promises";import*as wf from"node:path";function jr(e){if(Array.isArray(e))return e.map((t)=>({...t,lowMemoryMode:!0}));return{...e,lowMemoryMode:!0}}function vP(e){if(!e.endsWith(".crt"))return null;let t=e.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function bP(e,t,r,i){try{let[n,s]=await Promise.all([Nn.readFile(t,"utf8"),Nn.readFile(r,"utf8")]);return{serverName:e,cert:n,key:s}}catch(n){return m("sni",`skipping ${e}: ${n.message}`,i),null}}async function Dn(e,t){let r=new Map,i=e.certsDirServerNames?new Set(e.certsDirServerNames):void 0;if(e.certsDir){let s=[];try{s=await Nn.readdir(e.certsDir)}catch(o){m("sni",`certsDir read failed (${e.certsDir}): ${o.message}`,t)}for(let o of s){let c=vP(o);if(!c)continue;if(i&&!i.has(c))continue;let a=o.slice(0,-4);r.set(c,{certPath:wf.join(e.certsDir,o),keyPath:wf.join(e.certsDir,`${a}.key`)})}}if(e.domains)for(let[s,o]of Object.entries(e.domains))r.set(s,o);let n=[];for(let[s,o]of r){let c=await bP(s,o.certPath,o.keyPath,t);if(c)n.push(c)}return n}var vf=Q(()=>{he()});import*as Pt from"node:fs/promises";import*as Sa from"node:path";function Fn(e=process.env){let t=e.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if(t==="restart"||t==="rebind")return t;return e.INVOCATION_ID?"restart":"rebind"}function CP(e,t){if(!t||t.length===0)return!1;return t.some((r)=>{let i=r.startsWith(".")?r.slice(1):r;return e===i||e.endsWith(`.${i}`)})}function By(e){if(!e||e.length>253)return!1;if(e.includes("/")||e.includes(":")||e.includes(" "))return!1;if(e.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(e)}class Ii{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(e){this.config=e.config,this.certsDir=e.certsDir,this.onCertAdded=e.onCertAdded,this.http01Store=e.http01Store??So,this.issuer=e.issuer??ql,this.verbose=e.verbose??!1,this.negativeCacheMs=e.negativeCacheMs??xP;for(let t of e.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(e){return this.certs.has(e)}async isApproved(e){if(!By(e))return!1;if(CP(e,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(e)}catch(t){return m("on-demand",`ask(${e}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(e){if(!this.config.enabled)return!1;if(this.certs.has(e))return!0;if(!By(e))return!1;let t=this.inFlight.get(e);if(t)return t;let r=this.negativeCache.get(e);if(r!==void 0&&Date.now()<r){if(await this.loadFromDisk(e))return this.negativeCache.delete(e),!0;return m("on-demand",`${e} negatively cached for ${r-Date.now()}ms`,this.verbose),!1}let i=this.issue(e).finally(()=>{this.inFlight.delete(e)});return this.inFlight.set(e,i),i}async issue(e){if(this.certs.has(e))return!0;if(await this.loadFromDisk(e))return!0;if(!await this.isApproved(e))return m("on-demand",`refused issuance for ${e} (not approved)`,this.verbose),this.cacheNegative(e),!1;try{m("on-demand",`issuing cert for ${e} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[e],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(e,t.fullChainPem,t.keyPem);let r={serverName:e,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(e,r),this.negativeCache.delete(e),m("on-demand",`issued + installed cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(e),m("on-demand",`issuance for ${e} failed: ${t.message}`,this.verbose),!1}}cacheNegative(e){if(this.negativeCache.size>=Fy){let t=Date.now();for(let[r,i]of this.negativeCache)if(i<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=Fy){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(e,Date.now()+this.negativeCacheMs)}async loadFromDisk(e){let{certPath:t,keyPath:r}=this.pathsFor(e);try{let[i,n]=await Promise.all([Pt.readFile(t,"utf8"),Pt.readFile(r,"utf8")]),s={serverName:e,cert:i,key:n};return this.certs.set(e,s),m("on-demand",`adopted existing on-disk cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(e){return{certPath:Sa.join(this.certsDir,`${e}.crt`),keyPath:Sa.join(this.certsDir,`${e}.key`)}}async persist(e,t,r){await Pt.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:i,keyPath:n}=this.pathsFor(e);await Promise.all([Pt.writeFile(i,t,"utf8"),Pt.writeFile(n,r,{encoding:"utf8",mode:384})])}get accountKeyPath(){return Sa.join(this.certsDir,$P)}async loadAccountKey(){try{return await Pt.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(e){if(!e||this.accountKeyPem===e)return;this.accountKeyPem=e,await Pt.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Pt.writeFile(this.accountKeyPath,e,{encoding:"utf8",mode:384}).catch(()=>{})}}var $P="acme-account.key",xP=60000,Fy=4096;var bf=Q(()=>{No();he()});import*as Ea from"node:net";function Cr(e,t,r){return m("port",`Checking if port ${e} is in use on ${t}`,r),new Promise((i)=>{let n=Ea.createServer(),s=setTimeout(()=>{m("port",`Checking port ${e} timed out, assuming it's in use`,r),n.close(),i(!0)},3000);n.once("error",(o)=>{if(clearTimeout(s),o.code==="EADDRINUSE")m("port",`Port ${e} is in use`,r),i(!0);else m("port",`Error checking port ${e}: ${o.message}`,r),i(!0)}),n.once("listening",()=>{clearTimeout(s),m("port",`Port ${e} is available`,r),n.close(),i(!1)});try{n.listen(e,t)}catch(o){clearTimeout(s),m("port",`Exception checking port ${e}: ${o}`,r),i(!0)}})}async function $f(e,t,r,i=50){m("port",`Finding available port starting from ${e} (max attempts: ${i})`,r);let n=e,s=0;while(s<i){if(s++,!await Cr(n,t,r))return m("port",`Found available port: ${n} after ${s} attempts`,r),n;m("port",`Port ${n} is in use, trying ${n+1} (attempt ${s}/${i})`,r),n++}throw Error(`Unable to find available port after ${i} attempts starting from ${e}`)}function Ly(e,t,r=5000,i){return m("port",`Testing connection to ${t}:${e}`,i),new Promise((n)=>{let s=Ea.connect({host:t,port:e,timeout:r});s.once("connect",()=>{m("port",`Successfully connected to ${t}:${e}`,i),s.end(),n(!0)}),s.once("timeout",()=>{m("port",`Connection to ${t}:${e} timed out`,i),s.destroy(),n(!1)}),s.once("error",(o)=>{m("port",`Failed to connect to ${t}:${e}: ${o.message}`,i),s.destroy(),n(!1)})})}class Ta{usedPorts=new Set;hostname;verbose;maxRetries;constructor(e="0.0.0.0",t,r=50){this.hostname=e,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(e,t=!1){if(this.usedPorts.has(e))return this.findNextAvailablePort(e+1,t);if(await Cr(e,this.hostname,this.verbose))return this.findNextAvailablePort(e+1,t);if(t){if(!await Ly(e,this.hostname,3000,this.verbose))return m("port",`Port ${e} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(e+1,t)}return this.usedPorts.add(e),e}async findNextAvailablePort(e,t=!1){let r=await $f(e,this.hostname,this.verbose,this.maxRetries);if(t){if(!await Ly(r,this.hostname,3000,this.verbose))if(r<e+this.maxRetries)return this.findNextAvailablePort(r+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(r),r}releasePort(e){m("port",`Releasing port ${e}`,this.verbose),this.usedPorts.delete(e)}}var EB;var xf=Q(()=>{he();EB=new Ta});import*as Pa from"node:fs";import*as Je from"node:fs/promises";import{homedir as SP}from"node:os";import*as Cf from"node:path";import*as Ra from"node:process";function st(){return Cf.join(SP(),".stacks","rpx","registry.d")}function Sr(e){return typeof e==="string"&&e.length>0&&e.length<=128&&EP.test(e)}function Sf(e,t){if(!Sr(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return Cf.join(e,`${t}.json`)}function ot(e){if(!Number.isInteger(e)||e<=0)return!1;try{return Ra.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function My(e){if(!e||typeof e!=="object")return!1;let t=e,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,i=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,n=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",s=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&Sr(t.id)&&(i||n)&&typeof t.to==="string"&&t.to.length>0&&s&&r&&typeof t.createdAt==="string"}async function TP(e){await Je.mkdir(e,{recursive:!0})}async function _i(e,t=st(),r){if(!My(e))throw Error(`invalid registry entry: ${JSON.stringify(e)}`);await TP(t);let i=Sf(t,e.id),n=`${i}.tmp.${Ra.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{await Je.writeFile(n,s,{encoding:"utf8",mode:420}),await Je.rename(n,i),m("registry",`wrote entry ${e.id} → ${i}`,r)}catch(o){throw await Je.unlink(n).catch(()=>{}),o}}async function Ur(e,t=st(),r){let i=Sf(t,e);try{await Je.unlink(i),m("registry",`removed entry ${e}`,r)}catch(n){if(n.code!=="ENOENT")throw n}}async function Ef(e,t=st(),r){let i=Sf(t,e);try{let n=await Je.readFile(i,"utf8"),s=JSON.parse(n);if(!My(s))return m("registry",`entry ${e} failed validation, removing`,r),await Je.unlink(i).catch(()=>{}),null;return s}catch(n){if(n.code==="ENOENT")return null;if(n instanceof SyntaxError)return m("registry",`entry ${e} has invalid JSON, removing`,r),await Je.unlink(i).catch(()=>{}),null;throw n}}async function wt(e=st(),t){let r;try{r=await Je.readdir(e)}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.endsWith(".json"))continue;let s=n.slice(0,-5);if(!Sr(s))continue;let o=await Ef(s,e,t);if(o)i.push(o)}return i}async function Bn(e=st(),t){let r=await wt(e,t),i=0;for(let n of r){if(n.pid===void 0)continue;if(!ot(n.pid))m("registry",`GC: pid ${n.pid} for ${n.id} is dead, removing`,t),await Ur(n.id,e,t).catch(()=>{}),i++}return i}function Aa(e,t={}){let r=t.dir??st(),i=t.debounceMs??100,n=t.pollMs??Math.max(i*2,250),s=t.verbose;Pa.mkdirSync(r,{recursive:!0});let o=null,c=!1,a=null,l=!1,u=(p)=>JSON.stringify(p.map((w)=>({id:w.id,from:w.from,to:w.to,path:w.path,pid:w.pid,pathRewrites:w.pathRewrites,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,static:w.static,loadBalancer:w.loadBalancer})).sort((w,b)=>w.id.localeCompare(b.id))),f=()=>{if(o=null,c)return;wt(r,s).then((p)=>(a=u(p),e(p))).catch((p)=>{m("registry",`watcher onChange failed: ${p}`,s)})},h=()=>{if(c)return;if(o)clearTimeout(o);o=setTimeout(f,i)},y=setInterval(()=>{if(c||l)return;l=!0,wt(r,s).then((p)=>{if(u(p)!==a)h()}).catch((p)=>{m("registry",`watcher poll failed: ${p}`,s)}).finally(()=>{l=!1})},n),g=Pa.watch(r,{persistent:!0},(p,w)=>{if(w&&/\.tmp\.\d+\.\d+$/.test(w))return;h()});return g.on("error",(p)=>{m("registry",`watcher error: ${p}`,s)}),h(),{close:()=>{if(c=!0,o)clearTimeout(o);clearInterval(y),g.close()}}}var EP;var Wr=Q(()=>{he();EP=/^[a-zA-Z0-9._-]+$/});import{closeSync as Iy,openSync as PP,readFileSync as RP}from"node:fs";import*as _y from"node:fs/promises";import{spawn as AP}from"node:child_process";import{homedir as kP}from"node:os";import*as Ln from"node:path";import*as Rt from"node:process";class Pf{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(e){this.resolver=e.resolver,this.registryDir=e.registryDir??st(),this.rpxDir=e.rpxDir??Ln.join(kP(),".stacks","rpx"),this.verbose=e.verbose??!1,this.startupTimeoutMs=e.startupTimeoutMs??OP,this.pollIntervalMs=e.pollIntervalMs??NP,this.restartDelayMs=e.restartDelayMs??FP,this.killGraceMs=e.killGraceMs??BP,this.launch=e.launcher??MP(this.verbose),this.probePort=e.probePort??LP,this.pickPort=e.pickPort??((r)=>$f(r,"127.0.0.1")),this.isHostRoutable=e.isHostRoutable??(()=>!1),this.onSiteActivating=e.onSiteActivating,this.now=e.now??Date.now,this.writeEntry=e.writeEntry??_i,this.removeEntry=e.removeEntry??Ur;let t=e.reapIntervalMs??DP;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(e){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(e);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(e),t=void 0;if(!t){let r=this.resolver.resolve(e);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:e};if(t.status==="failed")return{kind:"failed",host:e,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:e,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(e){try{this.onSiteActivating?.(e.host)}catch{}let t=new Map;if(!e.selfRegisters)for(let c of e.routes){if(t.has(c.portEnv))continue;let a=await this.pickPort(c.defaultPort??3000);t.set(c.portEnv,a)}let r=Ln.join(this.rpxDir,"sites",`${e.id}.log`);await _y.mkdir(Ln.dirname(r),{recursive:!0}).catch(()=>{});let i=this.buildEnv(e,t),n=null,s;try{n=this.launch({command:e.command,cwd:e.dir,env:i,logPath:r})}catch(c){s=`failed to spawn: ${c.message}`}let o={site:e,status:s?"failed":"starting",handle:n,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:s?this.now():0,error:s,logPath:r,exited:!1,ready:Promise.resolve()};if(this.sites.set(e.host,o),s)return x.warn(`rpx: site ${e.host} ${s}`),o;return x.info(`rpx: booting ${e.host} → ${e.command} (${e.dir})`),n.exited.then((c)=>this.onProcessExit(o,c)).catch(()=>{}),o.ready=this.driveReadiness(o).catch((c)=>{m("sites",`readiness loop for ${e.host} threw: ${c}`,this.verbose)}),o}async onProcessExit(e,t){if(e.exited=!0,this.stopped||this.sites.get(e.site.host)!==e)return;if(e.status==="ready"){x.warn(`rpx: ${e.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(e.site.host);for(let r of e.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(e.status==="starting")this.fail(e,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(e){let{site:t}=e,r=this.now()+this.startupTimeoutMs,i=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,e.ports);while(this.now()<r&&!this.stopped){if(e.status!=="starting"||e.exited)return;if(await i()){if(await this.publishRoutes(e),e.status==="starting")e.status="ready",x.success(`rpx: ${t.host} ready`);return}await Tf(this.pollIntervalMs)}if(e.status==="starting")this.fail(e,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(e,t){let r=e.routes.filter((n)=>n.readyGate??rr(n.path)==="/").map((n)=>t.get(n.portEnv)).filter((n)=>typeof n==="number"),i=r.length>0?r:[...t.values()];return async()=>{for(let n of i)if(!await this.probePort(n))return!1;return i.length>0}}async publishRoutes(e){let{site:t,ports:r}=e;if(t.selfRegisters||t.routes.length===0)return;let i=t.routes.find((a)=>rr(a.path)==="/")??t.routes[0],n=r.get(i.portEnv);if(n===void 0)return;let s=[];for(let a of t.routes){if(a===i)continue;let l=r.get(a.portEnv);if(l===void 0)continue;s.push({from:rr(a.path),to:`localhost:${l}`,stripPrefix:a.stripPrefix??!1})}let o={id:t.id,from:`localhost:${n}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:s.length>0?s:void 0,pid:e.handle?.pid};await this.writeEntry(o,this.registryDir,this.verbose),e.routeIds=[t.id];let c=this.now()+2000;while(this.now()<c&&!this.isHostRoutable(t.host))await Tf(50)}fail(e,t){e.status="failed",e.error=t,e.failedAt=this.now(),x.warn(`rpx: site ${e.site.host} failed — ${t}`),this.killProcess(e)}buildEnv(e,t){let r={};for(let[i,n]of Object.entries(Rt.env))if(typeof n==="string")r[i]=n;Object.assign(r,e.env);for(let[i,n]of t)r[i]=String(n);return r.RPX_SITE_HOST=e.host,r.RPX_SITE_URL=`https://${e.host}`,r}readLogTail(e,t=40){try{return RP(e.logPath,"utf8").split(`
|
|
291
|
+
`,IA.encode(l)}async function qA(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:c}=await t.read();if(o)break;if(c){if(n+=c.length,n>qw)return t.cancel().catch(()=>{}),null;r.push(c)}}if(r.length===1)return r[0];let i=new Uint8Array(n),s=0;for(let o of r)i.set(o,s),s+=o.length;return i}var SA,as,gc,EA,Ih,Yr,qw=1048576,Bh=30000,NA=16384,Yw=262144,DA=2097152,FA=524288,LA=8192,BA=4096,IA,Jw,MA,pc;var tv=te(()=>{({connect:SA}=Bun),as=Symbol("rpx.pool.fallback"),gc=Symbol("rpx.pool.stale"),EA=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);Ih=Symbol("rpx.pool.timeout"),Yr=Symbol("rpx.pool.busy");IA=new TextEncoder,Jw=new TextDecoder,MA=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host","x-real-ip"]);pc=new Map});function rv(e){let t=typeof e==="string"?{to:e}:e,r=(t.to??"").trim();if(r&&!/^[a-z][\w+.-]*:\/\//i.test(r))r=`https://${r}`;return r=r.replace(/\/+$/,""),{to:r,status:t.status??301,preservePath:t.preservePath??!0}}function nv(e,t,r){if(!e.preservePath)return e.to||"/";let n=`${t}${r}`;return n==="/"?`${e.to}/`:`${e.to}${n}`}import*as Ct from"node:path";function yc(e,t){if(typeof e==="string")return{dir:e,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:e.dir,spa:e.spa??!1,pathRewriteStyle:e.pathRewriteStyle??"directory",maxAge:e.maxAge??0,cleanUrls:t}}function JA(e){let t=Ct.extname(e).toLowerCase();return YA[t]??"application/octet-stream"}function XA(e){let t;try{t=decodeURIComponent(e)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=Ct.posix.normalize(`/${t}`);if(r.split("/").includes(".."))return null;return r.replace(/^\/+/,"")}function ZA(e,t){let r=XA(e);if(r===null)return null;let n=Ct.posix.extname(r);if(t.cleanUrls&&n===".html"){let i=e.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ct.join(t.dir,r),redirectTo:i||"/"}}if(r===""||e.endsWith("/"))return{filePath:Ct.join(t.dir,r,"index.html")};if(n!=="")return{filePath:Ct.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:Ct.join(t.dir,`${r}.html`)};return{filePath:Ct.join(t.dir,r,"index.html")}}async function iv(e,t){let r=ZA(e,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",i=Bun.file(r.filePath);if(await i.exists())return new Response(i,{status:200,headers:{"Content-Type":JA(r.filePath),"Cache-Control":n}});if(t.spa){let s=Ct.join(t.dir,"index.html"),o=Bun.file(s);if(await o.exists())return new Response(o,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var YA;var wc=te(()=>{YA={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".pdf":"application/pdf",".wasm":"application/wasm",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"}});function QA(e,t){let r;try{r=t?.requestIP?.(e)?.address}catch{return Mh}if(!r)return Mh;return/^[0-9a-f.:]{1,45}$/i.test(r)?r:Mh}function eR(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function iR(e){if(!e)return!1;let t=null;for(let r of e.split(",")){let[n,...i]=r.trim().split(";"),s=n.trim().toLowerCase();if(s!=="gzip"&&s!=="*")continue;let o=1;for(let c of i){let a=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(c);if(a)o=Number.parseFloat(a[1])}if(s==="gzip")return Number.isFinite(o)&&o>0;t=o}return t!==null&&Number.isFinite(t)&&t>0}function sR(e){let t=e.get("vary");if(!t){e.set("vary","Accept-Encoding");return}if(!t.split(",").some((r)=>r.trim().toLowerCase()==="accept-encoding"))e.set("vary",`${t}, Accept-Encoding`)}function oR(e,t){if(e.method==="HEAD"||t.status===204||t.status===206||t.status===304||!t.body||t.headers.has("content-encoding")||t.headers.get("cache-control")?.toLowerCase().includes("no-transform")||e.headers.has("range")||!iR(e.headers.get("accept-encoding")))return t;let r=t.headers.get("content-type")?.toLowerCase()??"";if(!rR.some((s)=>r.startsWith(s)))return t;let n=t.headers.get("content-length");if(n!==null){let s=Number.parseInt(n,10);if(Number.isFinite(s)&&s<nR)return t}let i=new Headers(t.headers);return i.set("content-encoding","gzip"),sR(i),i.delete("content-length"),i.delete("content-md5"),i.delete("content-digest"),i.delete("accept-ranges"),i.delete("etag"),new Response(t.body.pipeThrough(new CompressionStream("gzip")),{status:t.status,statusText:t.statusText,headers:i})}function aR(e){let t=e.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function av(e,t){if(!t||t==="/")return e;if(e===t)return"/";if(e.startsWith(`${t}/`)){let r=e.slice(t.length);return r===""?"/":r}return e}function sv(e){if(e.upstreamPool)return Ww(e.upstreamPool);if(e.sourceHost)return{url:e.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function ov(e,t,r,n){let i=r?.url??t.sourceHost??"",o=t.stripBasePathPrefix??!1?av(e,t.basePath):e,c=Sh(o,t.pathRewrites);if(c)i=c.targetHost,o=c.targetPath,m("request",`Path rewrite: ${e} → ${i}${o}`,n);return{targetHost:i,targetPath:o}}function cR(e){let t=e.indexOf("://"),r=t===-1?e.indexOf("/"):e.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let n=e.indexOf("?",r);if(n===-1)return{pathname:e.slice(r),search:""};return{pathname:e.slice(r,n),search:e.slice(n)}}function cs(e,t,r){let n=async(i,s)=>{let{pathname:o,search:c}=cR(i.url),a=aR(i),l=QA(i,s),u=e(a,o);if(!u&&r){let w=await r(a,o,i);if(w instanceof Response)return w;if(w&&w.retry)u=e(a,o)}if(!u)return m("request",`No route found for host: ${a}`,t),new Response(`No proxy configured for ${a}`,{status:404});if(u.auth){let w=zw(i,o,u.auth);if(w)return m("request",`401 challenge for ${a}${o}`,t),w}if(u.redirect){let w=nv(u.redirect,o,c);return m("request",`${u.redirect.status} redirect ${a}${o} → ${w}`,t),new Response(null,{status:u.redirect.status,headers:{location:w}})}if(u.static){let v=u.stripBasePathPrefix??!0?av(o,u.basePath):o;return iv(v,u.static)}if(i.headers.get("upgrade")?.toLowerCase()==="websocket"){let w=sv(u);if(!s||!w)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:v,targetPath:P}=ov(o,u,w,t),A=`ws://${v}${P}${c}`,R={};for(let[x,k]of i.headers)if(!tR.has(x.toLowerCase())&&x.toLowerCase()!=="host")R[x]=k;R.host=v,R["x-forwarded-for"]=l,R["x-real-ip"]=l,R["x-forwarded-proto"]="https",R["x-forwarded-host"]=a;let D={targetUrl:A,forwardHeaders:R};if(s.upgrade(i,{data:D})){m("ws",`upgraded ${a}${P} → ${A}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let f=sv(u);if(!f)return new Response(`No upstream configured for ${a}`,{status:502});if(u.cleanUrls&&o.endsWith(".html")){let w=o.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:w}})}let{targetHost:h,targetPath:d}=ov(o,u,f,t),y=u.changeOrigin?`http://${h}`:void 0,g=i.body!=null&&i.method!=="GET"&&i.method!=="HEAD",p=u.upstreamPool;if(p)f.activeConnections++;try{let w=await Qw({hostPort:h,method:i.method,path:`${d}${c}`,reqHeaders:i.headers,forwardedHost:a,clientIp:l,originOverride:y,body:i.body,signal:i.signal});if(p)dc(p,f);return w}catch(w){if(w===Ih){if(m("request",`Upstream timeout for ${a}`,t),p)ns(p,f);return new Response("Gateway Timeout",{status:504})}if(w===Yr)return m("request",`Upstream pool saturated for ${a}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(w===as||!g)try{let v=new Headers(i.headers);if(v.set("host",h),v.set("x-forwarded-for",l),v.set("x-real-ip",l),v.set("x-forwarded-proto","https"),v.set("x-forwarded-host",a),y!==void 0)v.set("origin",y);let P=await fetch(`http://${h}${d}${c}`,{method:i.method,headers:v,body:i.body,redirect:"manual"});if(p)dc(p,f);return P}catch(v){if(m("request",`Proxy error for ${a}: ${v}`,t),p)ns(p,f);return new Response(`Proxy Error: ${v}`,{status:502})}if(m("request",`Proxy error for ${a}: ${w}`,t),p)ns(p,f);return new Response(`Proxy Error: ${w}`,{status:502})}finally{if(p)f.activeConnections--}};return async(i,s)=>{try{let o=await n(i,s);return o?oR(i,o):o}catch(o){return m("request",`Unhandled proxy handler error: ${o}`,t),new Response("Bad Gateway",{status:502})}}}function ls(e){let t=new WeakMap,r=eR();return{open(n){let{targetUrl:i,forwardHeaders:s}=n.data,o;try{o=new WebSocket(i,{headers:s})}catch(a){m("ws",`failed to open upstream ${i}: ${a}`,e),n.close(1011,"upstream connect failed");return}o.binaryType="arraybuffer";let c={upstream:o,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(n,c),o.addEventListener("open",()=>{c.upstreamOpen=!0;for(let a of c.pending)o.send(a);c.pending=[],c.pendingBytes=0}),o.addEventListener("message",(a)=>{n.send(a.data)}),o.addEventListener("close",(a)=>{try{n.close(a.code||1000,a.reason||"")}catch{}}),o.addEventListener("error",()=>{m("ws",`upstream error for ${i}`,e);try{n.close(1011,"upstream error")}catch{}})},message(n,i){let s=t.get(n);if(!s)return;let o=typeof i==="string"?i:new Uint8Array(i);if(s.upstreamOpen){s.upstream.send(o);return}let c=typeof o==="string"?Buffer.byteLength(o):o.byteLength;if(s.pendingBytes+c>r){m("ws",`pending buffer would exceed ${r}B before upstream open; closing socket`,e);try{n.close(1009,"buffer limit")}catch{}try{s.upstream.close(1011,"client buffer overflow")}catch{}t.delete(n);return}s.pending.push(o),s.pendingBytes+=c},close(n,i,s){let o=t.get(n);if(!o)return;t.delete(n);try{o.upstream.close(i||1000,s||"")}catch{}}}}var Mh="127.0.0.1",tR,rR,nR=1024;var _h=te(()=>{mc();tv();wc();fe();tR=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]),rR=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"]});import*as lv from"node:fs";import*as uv from"node:path";function vc(e,t){if(!e||!t.startsWith(cv))return null;let r=t.slice(cv.length);if(!r||!/^[A-Za-z0-9_-]+$/.test(r))return null;try{return lv.readFileSync(uv.join(e,r),"utf8")}catch{return null}}var cv="/.well-known/acme-challenge/";var jh=()=>{};function fr(e){if(!e||e==="/")return"/";let t=e.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function lR(e,t){if(t==="/")return!0;if(e===t)return!0;return e.startsWith(`${t}/`)}function us(e){let t=new Map;for(let n of e){let i=fr(n.path),s=t.get(n.host);if(!s)s=new Map,t.set(n.host,s);s.set(i,n.route)}let r=new Map;for(let[n,i]of t){let s=[];for(let[o,c]of i)s.push({path:o,route:c});s.sort((o,c)=>c.path.length-o.path.length),r.set(n,s)}return r}function Uh(e,t){let r=e.get(t);if(r!==void 0)return r;let n,i=-1;for(let[s,o]of e){if(!yn(s))continue;if(Ur(t,s)){let c=s.length-1;if(c>i)i=c,n=o}}return n}function fs(e,t,r){let n=Uh(e,t);if(!n)return;for(let i of n)if(lR(r,i.path))return i.route;return}var bc=()=>{};import*as hs from"node:fs/promises";import*as Kh from"node:path";function $c(e,t=fv,r){let n=Number.isFinite(t)&&t>0?Math.floor(t):fv;if(e.length<=n)return e;let i=e.slice(0,n),s=e.slice(n).map((o)=>o.serverName);return b.warn(`rpx: ${e.length} TLS contexts exceed maxTlsContexts=${n}; keeping the first ${n} and dropping ${s.length} host(s): ${s.join(", ")}`),m("sni",`capped SNI set to ${n} of ${e.length}`,r),i}function ds(e){let r=$c(e.sni,e.maxTlsContexts,e.verbose).map((i)=>({serverName:i.serverName,cert:i.cert,key:i.key})),n=e.defaultTls?[{cert:e.defaultTls.cert,key:e.defaultTls.key},...r]:r;return si(n)}function si(e){if(Array.isArray(e))return e.map((t)=>({...t,lowMemoryMode:!0}));return{...e,lowMemoryMode:!0}}function uR(e){if(!e.endsWith(".crt"))return null;let t=e.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function fR(e,t,r,n){try{let[i,s]=await Promise.all([hs.readFile(t,"utf8"),hs.readFile(r,"utf8")]);return{serverName:e,cert:i,key:s}}catch(i){return m("sni",`skipping ${e}: ${i.message}`,n),null}}async function ms(e,t){let r=new Map,n=e.certsDirServerNames?new Set(e.certsDirServerNames):void 0;if(e.certsDir){let s=[];try{s=await hs.readdir(e.certsDir)}catch(o){m("sni",`certsDir read failed (${e.certsDir}): ${o.message}`,t)}for(let o of s){let c=uR(o);if(!c)continue;if(n&&!n.has(c))continue;let a=o.slice(0,-4);r.set(c,{certPath:Kh.join(e.certsDir,o),keyPath:Kh.join(e.certsDir,`${a}.key`)})}}if(e.domains)for(let[s,o]of Object.entries(e.domains))r.set(s,o);let i=[];for(let[s,o]of r){let c=await fR(s,o.certPath,o.keyPath,t);if(c)i.push(c)}return i}var fv=256;var Wh=te(()=>{qt();fe()});import*as Ot from"node:fs/promises";import*as Cc from"node:path";function gs(e=process.env){let t=e.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if(t==="restart"||t==="rebind")return t;return e.INVOCATION_ID?"restart":"rebind"}function Vh(e,t){if(!t||t.length===0)return!1;return t.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return e===n||e.endsWith(`.${n}`)})}function dv(e){if(!e||e.length>253)return!1;if(e.includes("/")||e.includes(":")||e.includes(" "))return!1;if(e.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(e)}class oi{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(e){this.config=e.config,this.certsDir=e.certsDir,this.onCertAdded=e.onCertAdded,this.http01Store=e.http01Store??Ui,this.issuer=e.issuer??la,this.verbose=e.verbose??!1,this.negativeCacheMs=e.negativeCacheMs??dR;for(let t of e.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(e){return this.certs.has(e)}async isApproved(e){if(!dv(e))return!1;if(Vh(e,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(e)}catch(t){return m("on-demand",`ask(${e}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(e){if(!this.config.enabled)return!1;if(this.certs.has(e))return!0;if(!dv(e))return!1;let t=this.inFlight.get(e);if(t)return t;let r=this.negativeCache.get(e);if(r!==void 0&&Date.now()<r){if(await this.loadFromDisk(e))return this.negativeCache.delete(e),!0;return m("on-demand",`${e} negatively cached for ${r-Date.now()}ms`,this.verbose),!1}let n=this.issue(e).finally(()=>{this.inFlight.delete(e)});return this.inFlight.set(e,n),n}async issue(e){if(this.certs.has(e))return!0;if(await this.loadFromDisk(e))return!0;if(!await this.isApproved(e))return m("on-demand",`refused issuance for ${e} (not approved)`,this.verbose),this.cacheNegative(e),!1;try{m("on-demand",`issuing cert for ${e} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[e],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(e,t.fullChainPem,t.keyPem);let r={serverName:e,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(e,r),this.negativeCache.delete(e),m("on-demand",`issued + installed cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(e),m("on-demand",`issuance for ${e} failed: ${t.message}`,this.verbose),!1}}cacheNegative(e){if(this.negativeCache.size>=hv){let t=Date.now();for(let[r,n]of this.negativeCache)if(n<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=hv){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(e,Date.now()+this.negativeCacheMs)}async loadFromDisk(e){let{certPath:t,keyPath:r}=this.pathsFor(e);try{let[n,i]=await Promise.all([Ot.readFile(t,"utf8"),Ot.readFile(r,"utf8")]),s={serverName:e,cert:n,key:i};return this.certs.set(e,s),m("on-demand",`adopted existing on-disk cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(e){return{certPath:Cc.join(this.certsDir,`${e}.crt`),keyPath:Cc.join(this.certsDir,`${e}.key`)}}async persist(e,t,r){await Ot.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:i}=this.pathsFor(e);await Promise.all([Ot.writeFile(n,t,"utf8"),Ot.writeFile(i,r,{encoding:"utf8",mode:384})])}get accountKeyPath(){return Cc.join(this.certsDir,hR)}async loadAccountKey(){try{return await Ot.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(e){if(!e||this.accountKeyPem===e)return;this.accountKeyPem=e,await Ot.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Ot.writeFile(this.accountKeyPath,e,{encoding:"utf8",mode:384}).catch(()=>{})}}var hR="acme-account.key",dR=60000,hv=4096;var xc=te(()=>{Hi();fe()});import{X509Certificate as Hh,createPrivateKey as mR}from"node:crypto";import*as ps from"node:fs/promises";import{isIP as zh}from"node:net";import*as ys from"node:path";function $R(e){let t=uc(e);return{caCertPath:t.caCertPath,caKeyPath:t.caKeyPath,certPath:ys.join(e,gR),keyPath:ys.join(e,pR)}}function ws(e,t){if(!e||typeof e.dir!=="string"||e.dir.trim()==="")throw Error("localCa.dir is required");let r=[...new Set((e.hosts??[]).map((o)=>String(o).trim().toLowerCase()).filter(Boolean))];if(r.length===0)throw Error("localCa.hosts must name at least one host");for(let o of r)if(o.startsWith("*")||o.includes("/")||o.includes(":")||o.includes(" ")||zh(o)!==0)throw Error(`localCa.hosts entry ${JSON.stringify(o)} is not a hostname (wildcards are not supported; put IP addresses in localCa.ips)`);let n=[...new Set((e.ips??[]).map((o)=>String(o).trim()).filter(Boolean))];for(let o of n)if(zh(o)===0)throw Error(`localCa.ips entry ${JSON.stringify(o)} is not an IP address`);if(t?.enabled){let o=r.filter((c)=>Vh(c,t.allowedSuffixes));if(o.length>0)throw Error(`localCa.hosts and onDemandTls.allowedSuffixes overlap on ${o.join(", ")}; a host is either LAN-only (local CA) or public (ACME), never both`)}let i=e.validityDays??wR,s=e.renewBeforeDays??vR;if(!(i>0))throw Error("localCa.validityDays must be a positive number of days");if(!(s>=0)||s>=i)throw Error("localCa.renewBeforeDays must be between 0 and localCa.validityDays");return{dir:e.dir,hosts:r,ips:n,installTrust:e.installTrust===!0,validityDays:i,renewBeforeDays:s}}function gv(e){let t=zh(e);if(t===4)return e;if(t!==6)return e.toLowerCase();let r=[],n=[],[i,s]=e.split("::");r=i?i.split(":"):[],n=s?s.split(":"):[];let o=(l)=>l.flatMap((u)=>{if(!u.includes("."))return[u];let f=u.split(".").map((h)=>Number.parseInt(h,10));return[(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16)]});r=o(r),n=o(n);let c=e.includes("::")?8-r.length-n.length:0;return[...r,...Array.from({length:Math.max(0,c)},()=>"0"),...n].map((l)=>Number.parseInt(l||"0",16).toString(16)).join(":")}function CR(e){let t=new Set,r=new Set;for(let n of(e??"").split(",")){let i=n.trim();if(i.startsWith("DNS:"))t.add(i.slice(4).toLowerCase());else if(i.startsWith("IP Address:"))r.add(gv(i.slice(11)))}return{dns:t,ips:r}}function xR(e,t,r=new Date){let n,i;try{n=new Hh(e.cert),i=new Hh(e.caCert)}catch(h){return`unreadable certificate (${h.message})`}try{if(!n.checkPrivateKey(mR(e.key)))return"private key does not match the certificate"}catch(h){return`unreadable private key (${h.message})`}let s=!1;try{s=n.verify(i.publicKey)}catch{s=!1}if(!s)return"not issued by the current Root CA";let o=CR(n.subjectAltName),c=t.hosts.filter((h)=>!o.dns.has(h));if(c.length>0)return`missing DNS SAN(s): ${c.join(", ")}`;let a=t.ips.filter((h)=>!o.ips.has(gv(h)));if(a.length>0)return`missing IP SAN(s): ${a.join(", ")}`;let l=new Date(n.validTo).getTime(),u=new Date(n.validFrom).getTime();if(Number.isNaN(l)||Number.isNaN(u))return"unreadable validity period";if(u>r.getTime())return"not valid yet";let f=(l-r.getTime())/bR;if(f<t.renewBeforeDays)return f<=0?"expired":`${Math.floor(f)} day(s) left, under renewBeforeDays=${t.renewBeforeDays}`;return null}async function SR(e,t){let r=Reflect.get(Mf,"isCertTrusted");if(typeof r==="function")try{return await r(e,{verbose:t})}catch(n){m("local-ca",`tlsx isCertTrusted failed (${n.message}); using rpx's own check`,t)}return fc(e,{verbose:t,regenerateUntrustedCerts:!0})}async function ER(e,t){if(await SR(e.caCertPath,t))return m("local-ca",`Root CA ${e.caCertPath} already trusted; skipping installCA`,t),{alreadyTrusted:!0,installed:!1};try{let r=await Ta({basePath:ys.dirname(e.caCertPath),caCertPath:e.caCertPath,verbose:t});if(t)b.success(`Root CA ${r.alreadyTrusted?"already trusted":"installed"} in the system trust store (${e.caCertPath})`);return{alreadyTrusted:r.alreadyTrusted,installed:r.trustInstalled}}catch(r){return b.warn(`rpx: could not install the local Root CA into the system trust store: ${r.message}`),b.warn(`rpx: trust it manually: ${e.caCertPath}`),{alreadyTrusted:!1,installed:!1}}}async function mv(e){try{return await ps.readFile(e,"utf8")}catch{return null}}async function vs(e,t={}){let r=t.verbose,n=ws(e,t.onDemandTls),i=t.now??(()=>new Date),s=$R(n.dir),o=await Fh(n.dir,{verbose:r,caOptions:{commonName:yR,organization:"rpx",verbose:r}});if(o.created&&r)b.info(`Created local Root CA at ${s.caCertPath}`);let[c,a]=await Promise.all([mv(s.certPath),mv(s.keyPath)]),l;if(c&&a)l=xR({cert:c,key:a,caCert:o.certificate},n,i());else l="no leaf on disk";let u,f;if(l===null&&c&&a)u=c,f=a,m("local-ca",`reusing leaf ${s.certPath}`,r);else{m("local-ca",`minting leaf for ${[...n.hosts,...n.ips].join(", ")} (${l})`,r);let y={domain:n.hosts[0],domains:n.hosts,altNameIPs:n.ips,commonName:n.hosts[0],organizationName:"rpx",validityDays:n.validityDays,rootCA:{certificate:o.certificate,privateKey:o.privateKey},verbose:r},g=await Un(y);if(u=g.certificate,f=g.privateKey,await ps.writeFile(s.keyPath,f,{mode:384}),await ps.writeFile(s.certPath,u),r)b.success(`Minted local certificate for ${[...n.hosts,...n.ips].join(", ")} (${l})`)}let h=new Date(new Hh(u).validTo),d={paths:s,caCert:o.certificate,cert:u,key:f,caCreated:o.created,leafMinted:l!==null,renewalReason:l,notAfter:h,entries:n.hosts.map((y)=>({serverName:y,cert:u,key:f})),defaultTls:{cert:u,key:f}};if(n.installTrust)d.trust=await ER(s,r);return d}var gR="rpx-local-host.crt",pR="rpx-local-host.key",yR="rpx Local CA",wR=825,vR=30,bR=86400000;var Gh=te(()=>{Hi();hc();qt();xc();fe()});import*as Sc from"node:net";function Nr(e,t,r){return m("port",`Checking if port ${e} is in use on ${t}`,r),new Promise((n)=>{let i=Sc.createServer(),s=setTimeout(()=>{m("port",`Checking port ${e} timed out, assuming it's in use`,r),i.close(),n(!0)},3000);i.once("error",(o)=>{if(clearTimeout(s),o.code==="EADDRINUSE")m("port",`Port ${e} is in use`,r),n(!0);else m("port",`Error checking port ${e}: ${o.message}`,r),n(!0)}),i.once("listening",()=>{clearTimeout(s),m("port",`Port ${e} is available`,r),i.close(),n(!1)});try{i.listen(e,t)}catch(o){clearTimeout(s),m("port",`Exception checking port ${e}: ${o}`,r),n(!0)}})}async function qh(e,t,r,n=50){m("port",`Finding available port starting from ${e} (max attempts: ${n})`,r);let i=e,s=0;while(s<n){if(s++,!await Nr(i,t,r))return m("port",`Found available port: ${i} after ${s} attempts`,r),i;m("port",`Port ${i} is in use, trying ${i+1} (attempt ${s}/${n})`,r),i++}throw Error(`Unable to find available port after ${n} attempts starting from ${e}`)}function pv(e,t,r=5000,n){return m("port",`Testing connection to ${t}:${e}`,n),new Promise((i)=>{let s=Sc.connect({host:t,port:e,timeout:r});s.once("connect",()=>{m("port",`Successfully connected to ${t}:${e}`,n),s.end(),i(!0)}),s.once("timeout",()=>{m("port",`Connection to ${t}:${e} timed out`,n),s.destroy(),i(!1)}),s.once("error",(o)=>{m("port",`Failed to connect to ${t}:${e}: ${o.message}`,n),s.destroy(),i(!1)})})}class Ec{usedPorts=new Set;hostname;verbose;maxRetries;constructor(e="0.0.0.0",t,r=50){this.hostname=e,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(e,t=!1){if(this.usedPorts.has(e))return this.findNextAvailablePort(e+1,t);if(await Nr(e,this.hostname,this.verbose))return this.findNextAvailablePort(e+1,t);if(t){if(!await pv(e,this.hostname,3000,this.verbose))return m("port",`Port ${e} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(e+1,t)}return this.usedPorts.add(e),e}async findNextAvailablePort(e,t=!1){let r=await qh(e,this.hostname,this.verbose,this.maxRetries);if(t){if(!await pv(r,this.hostname,3000,this.verbose))if(r<e+this.maxRetries)return this.findNextAvailablePort(r+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(r),r}releasePort(e){m("port",`Releasing port ${e}`,this.verbose),this.usedPorts.delete(e)}}var AI;var Yh=te(()=>{fe();AI=new Ec});import*as Tc from"node:fs";import*as tt from"node:fs/promises";import{homedir as TR}from"node:os";import*as Jh from"node:path";import*as Pc from"node:process";function dt(){return Jh.join(TR(),".stacks","rpx","registry.d")}function Dr(e){return typeof e==="string"&&e.length>0&&e.length<=128&&PR.test(e)}function Xh(e,t){if(!Dr(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return Jh.join(e,`${t}.json`)}function mt(e){if(!Number.isInteger(e)||e<=0)return!1;try{return Pc.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function yv(e){if(!e||typeof e!=="object")return!1;let t=e,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,n=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,i=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",s=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&Dr(t.id)&&(n||i)&&typeof t.to==="string"&&t.to.length>0&&s&&r&&typeof t.createdAt==="string"}async function AR(e){await tt.mkdir(e,{recursive:!0})}async function ai(e,t=dt(),r){if(!yv(e))throw Error(`invalid registry entry: ${JSON.stringify(e)}`);await AR(t);let n=Xh(t,e.id),i=`${n}.tmp.${Pc.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{await tt.writeFile(i,s,{encoding:"utf8",mode:420}),await tt.rename(i,n),m("registry",`wrote entry ${e.id} → ${n}`,r)}catch(o){throw await tt.unlink(i).catch(()=>{}),o}}async function Jr(e,t=dt(),r){let n=Xh(t,e);try{await tt.unlink(n),m("registry",`removed entry ${e}`,r)}catch(i){if(i.code!=="ENOENT")throw i}}async function Zh(e,t=dt(),r){let n=Xh(t,e);try{let i=await tt.readFile(n,"utf8"),s=JSON.parse(i);if(!yv(s))return m("registry",`entry ${e} failed validation, removing`,r),await tt.unlink(n).catch(()=>{}),null;return s}catch(i){if(i.code==="ENOENT")return null;if(i instanceof SyntaxError)return m("registry",`entry ${e} has invalid JSON, removing`,r),await tt.unlink(n).catch(()=>{}),null;throw i}}async function xt(e=dt(),t){let r;try{r=await tt.readdir(e)}catch(i){if(i.code==="ENOENT")return[];throw i}let n=[];for(let i of r){if(!i.endsWith(".json"))continue;let s=i.slice(0,-5);if(!Dr(s))continue;let o=await Zh(s,e,t);if(o)n.push(o)}return n}async function bs(e=dt(),t){let r=await xt(e,t),n=0;for(let i of r){if(i.pid===void 0)continue;if(!mt(i.pid))m("registry",`GC: pid ${i.pid} for ${i.id} is dead, removing`,t),await Jr(i.id,e,t).catch(()=>{}),n++}return n}function Ac(e,t={}){let r=t.dir??dt(),n=t.debounceMs??100,i=t.pollMs??Math.max(n*2,250),s=t.verbose;Tc.mkdirSync(r,{recursive:!0});let o=null,c=!1,a=null,l=!1,u=(p)=>JSON.stringify(p.map((w)=>({id:w.id,from:w.from,to:w.to,path:w.path,pid:w.pid,pathRewrites:w.pathRewrites,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,static:w.static,loadBalancer:w.loadBalancer})).sort((w,v)=>w.id.localeCompare(v.id))),f=()=>{if(o=null,c)return;xt(r,s).then((p)=>(a=u(p),e(p))).catch((p)=>{m("registry",`watcher onChange failed: ${p}`,s)})},h=()=>{if(c)return;if(o)clearTimeout(o);o=setTimeout(f,n)},y=setInterval(()=>{if(c||l)return;l=!0,xt(r,s).then((p)=>{if(u(p)!==a)h()}).catch((p)=>{m("registry",`watcher poll failed: ${p}`,s)}).finally(()=>{l=!1})},i),g=Tc.watch(r,{persistent:!0},(p,w)=>{if(w&&/\.tmp\.\d+\.\d+$/.test(w))return;h()});return g.on("error",(p)=>{m("registry",`watcher error: ${p}`,s)}),h(),{close:()=>{if(c=!0,o)clearTimeout(o);clearInterval(y),g.close()}}}var PR;var Xr=te(()=>{fe();PR=/^[a-zA-Z0-9._-]+$/});import{closeSync as wv,openSync as RR,readFileSync as kR}from"node:fs";import*as vv from"node:fs/promises";import{spawn as OR}from"node:child_process";import{homedir as NR}from"node:os";import*as $s from"node:path";import*as Nt from"node:process";class ed{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(e){this.resolver=e.resolver,this.registryDir=e.registryDir??dt(),this.rpxDir=e.rpxDir??$s.join(NR(),".stacks","rpx"),this.verbose=e.verbose??!1,this.startupTimeoutMs=e.startupTimeoutMs??DR,this.pollIntervalMs=e.pollIntervalMs??FR,this.restartDelayMs=e.restartDelayMs??BR,this.killGraceMs=e.killGraceMs??IR,this.launch=e.launcher??_R(this.verbose),this.probePort=e.probePort??MR,this.pickPort=e.pickPort??((r)=>qh(r,"127.0.0.1")),this.isHostRoutable=e.isHostRoutable??(()=>!1),this.onSiteActivating=e.onSiteActivating,this.now=e.now??Date.now,this.writeEntry=e.writeEntry??ai,this.removeEntry=e.removeEntry??Jr;let t=e.reapIntervalMs??LR;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(e){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(e);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(e),t=void 0;if(!t){let r=this.resolver.resolve(e);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:e};if(t.status==="failed")return{kind:"failed",host:e,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:e,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(e){try{this.onSiteActivating?.(e.host)}catch{}let t=new Map;if(!e.selfRegisters)for(let c of e.routes){if(t.has(c.portEnv))continue;let a=await this.pickPort(c.defaultPort??3000);t.set(c.portEnv,a)}let r=$s.join(this.rpxDir,"sites",`${e.id}.log`);await vv.mkdir($s.dirname(r),{recursive:!0}).catch(()=>{});let n=this.buildEnv(e,t),i=null,s;try{i=this.launch({command:e.command,cwd:e.dir,env:n,logPath:r})}catch(c){s=`failed to spawn: ${c.message}`}let o={site:e,status:s?"failed":"starting",handle:i,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:s?this.now():0,error:s,logPath:r,exited:!1,ready:Promise.resolve()};if(this.sites.set(e.host,o),s)return b.warn(`rpx: site ${e.host} ${s}`),o;return b.info(`rpx: booting ${e.host} → ${e.command} (${e.dir})`),i.exited.then((c)=>this.onProcessExit(o,c)).catch(()=>{}),o.ready=this.driveReadiness(o).catch((c)=>{m("sites",`readiness loop for ${e.host} threw: ${c}`,this.verbose)}),o}async onProcessExit(e,t){if(e.exited=!0,this.stopped||this.sites.get(e.site.host)!==e)return;if(e.status==="ready"){b.warn(`rpx: ${e.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(e.site.host);for(let r of e.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(e.status==="starting")this.fail(e,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(e){let{site:t}=e,r=this.now()+this.startupTimeoutMs,n=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,e.ports);while(this.now()<r&&!this.stopped){if(e.status!=="starting"||e.exited)return;if(await n()){if(await this.publishRoutes(e),e.status==="starting")e.status="ready",b.success(`rpx: ${t.host} ready`);return}await Qh(this.pollIntervalMs)}if(e.status==="starting")this.fail(e,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(e,t){let r=e.routes.filter((i)=>i.readyGate??fr(i.path)==="/").map((i)=>t.get(i.portEnv)).filter((i)=>typeof i==="number"),n=r.length>0?r:[...t.values()];return async()=>{for(let i of n)if(!await this.probePort(i))return!1;return n.length>0}}async publishRoutes(e){let{site:t,ports:r}=e;if(t.selfRegisters||t.routes.length===0)return;let n=t.routes.find((a)=>fr(a.path)==="/")??t.routes[0],i=r.get(n.portEnv);if(i===void 0)return;let s=[];for(let a of t.routes){if(a===n)continue;let l=r.get(a.portEnv);if(l===void 0)continue;s.push({from:fr(a.path),to:`localhost:${l}`,stripPrefix:a.stripPrefix??!1})}let o={id:t.id,from:`localhost:${i}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:s.length>0?s:void 0,pid:e.handle?.pid};await this.writeEntry(o,this.registryDir,this.verbose),e.routeIds=[t.id];let c=this.now()+2000;while(this.now()<c&&!this.isHostRoutable(t.host))await Qh(50)}fail(e,t){e.status="failed",e.error=t,e.failedAt=this.now(),b.warn(`rpx: site ${e.site.host} failed — ${t}`),this.killProcess(e)}buildEnv(e,t){let r={};for(let[n,i]of Object.entries(Nt.env))if(typeof i==="string")r[n]=i;Object.assign(r,e.env);for(let[n,i]of t)r[n]=String(i);return r.RPX_SITE_HOST=e.host,r.RPX_SITE_URL=`https://${e.host}`,r}readLogTail(e,t=40){try{return kR(e.logPath,"utf8").split(`
|
|
234
292
|
`).slice(-t).join(`
|
|
235
|
-
`).trim()}catch{return""}}async stop(e){let t=this.sites.get(e);if(!t)return;this.sites.delete(e);for(let r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),
|
|
293
|
+
`).trim()}catch{return""}}async stop(e){let t=this.sites.get(e);if(!t)return;this.sites.delete(e);for(let r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),b.info(`rpx: stopped ${e}`)}async killProcess(e){let t=e.handle;if(!t)return;e.handle=null;try{t.stop("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof r.unref==="function")r.unref();await Promise.race([t.exited.catch(()=>{}),Qh(this.killGraceMs+500)]),clearTimeout(r)}async reapIdle(){if(this.stopped)return;let e=this.now();for(let[t,r]of this.sites){let n=r.site.idleTimeoutMs;if(n<=0)continue;let i=e-r.lastAccess;if((r.status==="ready"||e-r.startedAt>this.startupTimeoutMs)&&i>n)m("sites",`reaping ${t} (idle ${Math.round(i/1000)}s)`,this.verbose),await this.stop(t)}}list(){let e=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:e-t.startedAt,idleMs:e-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((e)=>this.stop(e)))}}function Qh(e){return new Promise((t)=>setTimeout(t,e))}async function MR(e){let t=new AbortController,r=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${e}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(r)}}function _R(e){let t=jR();return({command:r,cwd:n,env:i,logPath:s})=>{let o=RR(s,"a");try{let c=OR("sh",["-c",r],{cwd:n,env:i,detached:!0,stdio:["ignore",o,o],...t?{uid:t.uid,gid:t.gid}:{}}),a=c.pid;if(a===void 0)throw Error("spawn returned no pid");let l=new Promise((u)=>{c.once("exit",(f)=>{u(f)}),c.once("error",()=>{u(null)})}).finally(()=>{try{wv(o)}catch{}});return m("sites",`spawned pid ${a}: sh -c ${r} (cwd ${n})`,e),{pid:a,exited:l,stop:(u="SIGTERM")=>{try{Nt.kill(-a,u)}catch{try{c.kill(u)}catch{}}}}}catch(c){try{wv(o)}catch{}throw c}}}function jR(){if(Nt.platform==="win32")return null;if(!(typeof Nt.getuid==="function"&&Nt.getuid()===0))return null;let t=Number.parseInt(Nt.env.SUDO_UID??"",10),r=Number.parseInt(Nt.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(r)||r<=0)return null;return{uid:t,gid:r}}var DR=120000,FR=200,LR=30000,BR=3000,IR=4000;var bv=te(()=>{bc();Yh();Xr();fe();qt()});function ci(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function $v(e,t,r){return`<!doctype html>
|
|
236
294
|
<html lang="en">
|
|
237
295
|
<head>
|
|
238
296
|
<meta charset="utf-8">
|
|
239
297
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
240
298
|
${r>0?`<meta http-equiv="refresh" content="${r}">`:""}
|
|
241
|
-
<title>${
|
|
242
|
-
<style>${
|
|
299
|
+
<title>${ci(e)}</title>
|
|
300
|
+
<style>${UR}</style>
|
|
243
301
|
</head>
|
|
244
302
|
<body><main class="card">${t}</main></body>
|
|
245
|
-
</html>`}function
|
|
246
|
-
<div class="row"><div class="spinner"></div><h1>Starting ${
|
|
303
|
+
</html>`}function Cv(e){let t=Math.max(1,Math.round(e.sinceMs/1000)),r=e.logTail?`<pre>${ci(e.logTail)}</pre>`:"",n=`
|
|
304
|
+
<div class="row"><div class="spinner"></div><h1>Starting ${ci(e.host)}…</h1></div>
|
|
247
305
|
<p>rpx is booting this site's dev server on demand. This page reloads itself —
|
|
248
306
|
it'll switch to the app as soon as it's ready (usually a few seconds).</p>
|
|
249
307
|
<p>Booting for ${t}s.</p>
|
|
250
|
-
${r}`;return new Response(
|
|
251
|
-
<div class="row"><div class="dot"></div><h1>${
|
|
252
|
-
<p>${
|
|
308
|
+
${r}`;return new Response($v(`Starting ${e.host}`,n,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function xv(e){let t=e.logTail?`<pre>${ci(e.logTail)}</pre>`:"<p>No output was captured.</p>",r=`
|
|
309
|
+
<div class="row"><div class="dot"></div><h1>${ci(e.host)} failed to start</h1></div>
|
|
310
|
+
<p>${ci(e.error)}</p>
|
|
253
311
|
${t}
|
|
254
|
-
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(
|
|
312
|
+
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response($v(`${e.host} failed`,r,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var UR=`
|
|
255
313
|
:root { color-scheme: light dark }
|
|
256
314
|
* { box-sizing: border-box }
|
|
257
315
|
body {
|
|
@@ -277,54 +335,54 @@ ${r>0?`<meta http-equiv="refresh" content="${r}">`:""}
|
|
|
277
335
|
}
|
|
278
336
|
.dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
|
|
279
337
|
@keyframes spin { to { transform: rotate(360deg) } }
|
|
280
|
-
`;import{exec as
|
|
281
|
-
`),s=[],o=0;while(o<
|
|
338
|
+
`;import{exec as KR}from"node:child_process";import Rc from"node:fs";import WR from"node:os";import Tv from"node:path";import*as Zr from"node:process";import{promisify as VR}from"node:util";function Sv(e){let t=e.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}async function Pv(e){if(Zr.platform==="win32")throw Error("Administrator privileges required on Windows");if(Zi()){let{stdout:n}=await Cs(e);return n}let t=Er(),r=e.replace(/'/g,"'\\''");try{if(t){let{stdout:n}=await Cs(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`);return td=!0,n}if(td)try{let{stdout:n}=await Cs(`sudo -n sh -c '${r}'`);return n}catch(n){m("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:n}=await Cs(`sudo -n sh -c '${r}'`);return td=!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}`)}}function Oc(e){let t=e.indexOf("#"),r=(t===-1?e:e.slice(0,t)).trim();if(!r)return null;let n=t===-1?"":e.slice(t+1).trim(),[i,...s]=r.split(/\s+/);if(!i||s.length===0)return null;let o=/^rpx(?::pid=(\d+))?$/.exec(n);return{address:i,names:s,comment:n,rpxPid:o?.[1]?Number.parseInt(o[1],10):null,rpxManaged:o!==null}}function Av(e,t){let r=Oc(e);return r!==null&&kc.has(r.address)&&r.names.includes(t)}function zR(e,t){let r=new Set(t),n=new Set,i=e.split(`
|
|
339
|
+
`),s=[],o=0;while(o<i.length){let c=i[o];if(c.trim()===HR){let l=[],u=o+1;while(u<i.length){let h=i[u];if(h.trim()===""||h.trim().startsWith("#"))break;l.push(h),u++}let f=l.filter((h)=>{let d=Oc(h),y=d!==null&&kc.has(d.address)&&d.names.some((g)=>r.has(g));if(y){for(let g of d.names)if(r.has(g))n.add(g)}return!y});if(f.length>0||l.length===0)s.push(c,...f);o=u;continue}let a=Oc(c);if(a?.rpxManaged&&kc.has(a.address)&&a.names.some((l)=>r.has(l))){for(let l of a.names)if(r.has(l))n.add(l);o++;continue}s.push(c),o++}while(s.length>0&&s[s.length-1].trim()==="")s.pop();return{content:`${s.join(`
|
|
282
340
|
`)}
|
|
283
|
-
`,removed:[...
|
|
284
|
-
`)){let o=
|
|
341
|
+
`,removed:[...n]}}function GR(e,t){let r=[],n=new Set,i=[];for(let s of e.split(`
|
|
342
|
+
`)){let o=Oc(s);if(o?.rpxManaged&&o.rpxPid!==null&&kc.has(o.address)&&!t(o.rpxPid)){r.push(...o.names),n.add(o.rpxPid);continue}i.push(s)}while(i.length>0&&i[i.length-1].trim()==="")i.pop();return{content:`${i.join(`
|
|
285
343
|
`)}
|
|
286
|
-
`,removed:r,stalePids:[...
|
|
287
|
-
`),o=r.filter((l)=>!s.some((u)=>
|
|
288
|
-
127.0.0.1 ${l} ${
|
|
289
|
-
::1 ${l} ${
|
|
290
|
-
`);try{await
|
|
291
|
-
`);return e.map((
|
|
292
|
-
`,"utf8")}async function
|
|
344
|
+
`,removed:r,stalePids:[...n]}}async function rd(e){try{return await Rc.promises.readFile(hr,"utf-8")}catch{return m("hosts","Reading hosts file requires elevated permissions, using sudo",e),Pv(`cat "${hr}"`)}}async function nd(e,t){let r=Tv.join(WR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Rc.promises.writeFile(r,e,"utf8"),await Pv(`cat "${r}" | tee "${hr}" > /dev/null`)}finally{await Rc.promises.unlink(r).catch((n)=>{m("hosts",`Failed to remove temporary file: ${n}`,t)})}}async function xs(e,t){let r=e.filter((i)=>!Sv(i)),n=e.filter((i)=>Sv(i));if(n.length>0)m("hosts",`Skipping /etc/hosts for loopback dev names: ${n.join(", ")}`,t);if(r.length===0)return;m("hosts",`Adding hosts: ${r.join(", ")}`,t),m("hosts",`Using hosts file at: ${hr}`,t);try{let i;try{i=await rd(t)}catch(l){throw console.log(" Could not read hosts file — skipping hosts setup"),m("hosts",`sudo read also failed: ${l}`,t),Error(`Cannot read hosts file: ${l}`)}let s=i.split(`
|
|
345
|
+
`),o=r.filter((l)=>!s.some((u)=>Av(u,l)));if(o.length===0){m("hosts","All hosts already exist in hosts file",t);return}let c=Zr.pid,a=o.map((l)=>`
|
|
346
|
+
127.0.0.1 ${l} ${Ev}:pid=${c}
|
|
347
|
+
::1 ${l} ${Ev}:pid=${c}`).join(`
|
|
348
|
+
`);try{await nd(i+a,t),console.log(` Hosts updated: ${o.join(", ")}`)}catch(l){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),o.forEach((u)=>{console.log(` 127.0.0.1 ${u}`),console.log(` ::1 ${u}`)}),console.log(` Or run: sudo nano ${hr}`)}}catch(i){m("hosts",`Failed to manage hosts file: ${i.message}`,t)}}async function Rv(e,t){m("hosts",`Removing hosts: ${e.join(", ")}`,t);try{let r;try{r=await rd(t)}catch(s){throw m("hosts",`sudo read also failed: ${s}`,t),Error(`Cannot read hosts file: ${s}`)}let{content:n,removed:i}=zR(r,e);if(i.length===0){m("hosts","No matching rpx-managed hosts found to remove",t);return}try{await nd(n,t),m("hosts",`Hosts removed successfully: ${i.join(", ")}`,t)}catch(s){m("hosts","Could not clean up hosts file automatically",t)}}catch(r){m("hosts",`Failed to clean up hosts file: ${r.message}`,t)}}async function Ss(e,t){m("hosts",`Checking hosts: ${e}`,t);let r;try{r=await Rc.promises.readFile(hr,"utf-8")}catch(i){m("hosts",`Error reading hosts file: ${i}`,t);try{let s=Er(),o;if(s)o=`echo '${s}' | sudo -S cat "${hr}" 2>/dev/null`;else o=`sudo -n cat "${hr}" 2>/dev/null || cat "${hr}" 2>/dev/null || echo ""`;let{stdout:c}=await Cs(o);r=c}catch(s){return m("hosts",`Cannot read hosts file, assuming entries don't exist: ${s}`,t),e.map(()=>!1)}}let n=r.split(`
|
|
349
|
+
`);return e.map((i)=>n.some((s)=>Av(s,i)))}async function Es(e={}){let t=e.isAlive??mt,r;try{r=await rd(e.verbose)}catch(o){return m("hosts",`stale hosts GC: cannot read hosts file: ${o}`,e.verbose),[]}let{content:n,removed:i,stalePids:s}=GR(r,t);if(i.length===0)return[];try{return await nd(n,e.verbose),m("hosts",`stale hosts GC: removed ${i.join(", ")} (dead pid(s): ${s.join(", ")})`,e.verbose),[...new Set(i)]}catch(o){return m("hosts",`stale hosts GC: write failed: ${o}`,e.verbose),[]}}var Cs,hr,Ev="# rpx",HR="# Added by rpx",kc,td=!1;var id=te(()=>{Xr();fe();Cs=VR(KR);hr=Zr.platform==="win32"?Tv.join(Zr.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",kc=new Set(["127.0.0.1","::1"])});import*as Fr from"node:fs/promises";import{homedir as qR}from"node:os";import*as sd from"node:path";function Ov(){return sd.join(qR(),".stacks","rpx")}function od(e=Ov()){return sd.join(e,YR)}async function Dc(e=Ov()){try{let t=await Fr.readFile(od(e),"utf8"),r=JSON.parse(t);if(r.version!==Nc||!Array.isArray(r.resolvers))return null;return{version:Nc,resolvers:r.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(r.domains)?r.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Nv(e,t){await Fr.mkdir(e,{recursive:!0}),await Fr.writeFile(od(e),`${JSON.stringify(t,null,2)}
|
|
350
|
+
`,"utf8")}async function ad(e){await Fr.rm(od(e),{force:!0})}function Dv(e){let t=e.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function XR(e){let t=Dv(e);if(!t)return null;let r=t.split(".");if(r.length<2)return null;let n=r[r.length-1];if(JR.has(n))return r.slice(-2).join(".");return t}function cd(e){let t=new Set;for(let r of e){let n=XR(r);if(n)t.add(n)}return Array.from(t).sort()}function ld(e){let t=new Set;for(let r of e){let n=Dv(r);if(n)t.add(n)}return Array.from(t).sort()}var Nc=1,YR="dns-state.json",kv,JR;var Fv=te(()=>{kv=["com","test","dev","app","page","local","localhost","example","invalid"];JR=new Set(["test","localhost","local","example","invalid","internal","home","lan"])});var Lc={};nl(Lc,{DNS_PORT:()=>Ps,RPX_RESOLVER_MARKER:()=>Mv,contentLooksLikeRpxResolver:()=>Vv,isDnsServerRunning:()=>tk,isRpxDevelopmentDnsAnswering:()=>Wv,reconcileStaleDevelopmentDns:()=>en,removeLegacyTldResolvers:()=>dd,removeResolver:()=>lk,resolverFilePath:()=>li,setupDevelopmentDns:()=>md,setupResolver:()=>ak,startDnsServer:()=>Kv,stopDnsServer:()=>ud,syncDevelopmentDnsFromRegistry:()=>ui,tearDownDevelopmentDns:()=>Qr});import Lv from"node:dgram";import*as Bv from"node:fs/promises";import*as Iv from"node:path";import*as dr from"node:process";function jv(e){return{id:e.readUInt16BE(0),flags:e.readUInt16BE(2),qdcount:e.readUInt16BE(4),ancount:e.readUInt16BE(6),nscount:e.readUInt16BE(8),arcount:e.readUInt16BE(10)}}function Uv(e,t,r=0){let n=[],i=t,s=0;while(!0){if(i>=e.length||++s>128)break;let o=e[i];if(o===0){i++;break}if((o&192)===192){if(i+1>=e.length||r>=10)break;let c=e.readUInt16BE(i)&16383,{name:a}=Uv(e,c,r+1);if(a)n.push(a);i+=2;break}if(i++,i+o>e.length)break;n.push(e.subarray(i,i+o).toString("ascii")),i+=o}return{name:n.join("."),newOffset:i}}function ZR(e,t){let{name:r,newOffset:n}=Uv(e,t),i=e.readUInt16BE(n),s=e.readUInt16BE(n+2);return{question:{name:r,type:i,class:s},newOffset:n+4}}function Ts(e){let t=e.split("."),r=[];for(let n of t)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function QR(e,t,r){let n=[],i=Buffer.alloc(12);i.writeUInt16BE(e,0),i.writeUInt16BE(33152,2),i.writeUInt16BE(1,4),i.writeUInt16BE(1,6),i.writeUInt16BE(0,8),i.writeUInt16BE(0,10),n.push(i),n.push(Ts(t.name));let s=Buffer.alloc(4);s.writeUInt16BE(t.type,0),s.writeUInt16BE(t.class,2),n.push(s),n.push(Ts(t.name));let o=Buffer.alloc(10);if(o.writeUInt16BE(t.type,0),o.writeUInt16BE(1,2),o.writeUInt32BE(300,4),t.type===1){o.writeUInt16BE(4,8),n.push(o);let c=r.split(".").map((a)=>Number.parseInt(a,10));n.push(Buffer.from(c))}else if(t.type===28)o.writeUInt16BE(16,8),n.push(o),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return i.writeUInt16BE(33155,2),i.writeUInt16BE(0,6),Buffer.concat([i,Ts(t.name),s]);return Buffer.concat(n)}function ek(e,t){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(e,0),n.writeUInt16BE(33155,2),n.writeUInt16BE(1,4),n.writeUInt16BE(0,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),r.push(n),r.push(Ts(t.name));let i=Buffer.alloc(4);return i.writeUInt16BE(t.type,0),i.writeUInt16BE(t.class,2),r.push(i),Buffer.concat(r)}async function Kv(e,t){if(dr.platform!=="darwin")return!1;let r=ld(e);if(r.length===0)return!1;if(st){for(let n of r)Fc.add(n);return m("dns","DNS server already running — merged domains",t),!0}return Fc=new Set(r),new Promise((n)=>{st=Lv.createSocket("udp4"),st.on("error",(i)=>{m("dns",`DNS server error: ${i.message}`,t),st?.close(),st=null,n(!1)}),st.on("message",(i,s)=>{try{let o=jv(i),{question:c}=ZR(i,12);m("dns",`Query for ${c.name} type ${c.type} from ${s.address}`,t);let a=c.name.toLowerCase(),l=!1;for(let f of Fc)if(a===f||a.endsWith(`.${f}`)){l=!0;break}let u;if(l&&(c.type===1||c.type===28))u=QR(o.id,c,"127.0.0.1"),m("dns",`Responding with localhost for ${c.name}`,t);else u=ek(o.id,c),m("dns",`NXDOMAIN for ${c.name}`,t);st?.send(u,s.port,s.address)}catch(o){m("dns",`Error processing DNS query: ${o}`,t)}}),st.on("listening",()=>{let i=st?.address();m("dns",`DNS server listening on ${i?.address}:${i?.port}`,t),n(!0)});try{st.bind(Ps,"127.0.0.1")}catch(i){m("dns",`Failed to bind DNS server: ${i}`,t),n(!1)}})}function ud(e){if(st)m("dns","Stopping DNS server",e),st.close(),st=null,Fc=new Set}function tk(){return st!==null}async function Wv(e,t=500){let r=e.trim().toLowerCase().replace(/\.$/,"");if(!r)return!1;return new Promise((n)=>{let i=Lv.createSocket("udp4"),s=setTimeout(()=>{i.close(),n(!1)},t);i.on("message",(c)=>{clearTimeout(s),i.close();try{let a=jv(c);n(a.ancount>0)}catch{n(!1)}}),i.on("error",()=>{clearTimeout(s),i.close(),n(!1)});let o=rk(r,1);i.send(o,Ps,"127.0.0.1",(c)=>{if(c)clearTimeout(s),i.close(),n(!1)})})}function rk(e,t){let r=Buffer.alloc(12);r.writeUInt16BE(1,0),r.writeUInt16BE(256,2),r.writeUInt16BE(1,4);let n=Buffer.concat([Ts(e),Buffer.from([0,t,0,1])]);return Buffer.concat([r,n])}function nk(){return`${Mv}
|
|
293
351
|
nameserver 127.0.0.1
|
|
294
|
-
port ${
|
|
295
|
-
`}function
|
|
296
|
-
`)}finally{await
|
|
297
|
-
`),l.stdin.end();l.unref();let h=Pr(e),d=Date.now()+15000;while(Date.now()<d){if(u)throw u;let y=await Tr(e);if(y!==null&&ot(y)){if(i)x.success(`rpx daemon elevated to root (pid=${y}, https on :${t})`);return{httpsPort:t,httpPort:r,pidPath:h,done:Promise.resolve(),stop:async()=>{try{E.kill(y,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(f!==null&&f!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${f}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((g)=>setTimeout(g,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${e})`)}function Wf(){if(hw)return;hw=!0,E.on("uncaughtException",(e)=>{x.error(`rpx daemon: uncaught exception (continuing): ${e?.stack??e}`)}),E.on("unhandledRejection",(e)=>{x.error(`rpx daemon: unhandled rejection (continuing): ${e}`)})}function vw(e,t,r){let i;try{i=new URL(e.url)}catch{return new Response("Bad Request",{status:400})}let n=(e.headers.get("host")??i.hostname).split(":")[0];if(i.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let s=t.challengeStore.handlePath(i.pathname);if(s!==void 0)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(r){let s=xa(r,i.pathname);if(s!=null)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(n))t.ensureCert(n).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${n}${i.pathname}${i.search}`}})}async function bw(e={}){Wf();let t=e.verbose??!1,r=e.rpxDir??Pe(),i=e.registryDir??Ot.join(r,"registry.d"),n=e.httpsPort??443,s=e.httpPort??80,o=e.hostname??"::",c=e.hostname==null,a=e.gcIntervalMs??cR;if(E.env.RPX_DAEMON_WORKER==="1")return mR({rpxDir:E.env.RPX_WORKER_RPXDIR??r,registryDir:E.env.RPX_WORKER_REGISTRYDIR??i,httpsPort:Number.parseInt(E.env.RPX_WORKER_HTTPSPORT??"",10)||n,hostname:E.env.RPX_WORKER_HOSTNAME??o,verbose:E.env.RPX_WORKER_VERBOSE==="1"||t});let l=n>0&&n<1024||s>0&&s<1024,u=typeof E.getuid==="function"&&E.getuid()===0;if(E.platform!=="win32"&&l&&!u)return fR(r,n,s,t);let f=Math.max(1,e.workers??(Number.parseInt(E.env.RPX_WORKERS??"",10)||1));if(f>1){if(e.onDemandSites?.enabled)x.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return gR(e,{rpxDir:r,registryDir:i,httpsPort:n,httpPort:s,hostname:o,verbose:t,gcIntervalMs:a,workers:f})}let h=await yw(r),d=new Map,y=(C,N)=>On(d,C,N);function g(C){d=kn(C.map((Ze)=>({host:Ze.to,path:Ze.path,route:ww(Ze)}))),ja(new Set(C.map((Ze)=>Ze.id)));let N=Array.from(d.keys());m("daemon",`routing table now covers ${N.length} host(s): ${N.join(", ")||"<empty>"}`,t)}await Bn(i,t).catch((C)=>{m("daemon",`initial gc failed: ${C}`,t)}),await jn({verbose:t}).catch((C)=>{m("daemon",`stale hosts GC on start failed: ${C}`,t)});let p=await wt(i,t);g(p),await Vr({rpxDir:r,verbose:t}).catch((C)=>{m("daemon",`DNS reconcile on start failed: ${C}`,t)}),await Wi(p,{rpxDir:r,verbose:t,ownerPid:E.pid}).catch((C)=>{m("daemon",`DNS setup on start failed: ${C}`,t)});let w=[];if(e.productionCerts){if(w=await Dn(e.productionCerts,t),t&&w.length>0)x.info(`SNI: serving ${w.length} real cert(s): ${w.map((C)=>C.serverName).join(", ")}`)}let b=new Set,P=null,R;if(e.onDemandSites?.enabled){if(P=new Pf({resolver:sl(e.onDemandSites),registryDir:i,rpxDir:r,verbose:t,startupTimeoutMs:e.onDemandSites.startupTimeoutMs,isHostRoutable:(C)=>yf(d,C)!==void 0,onSiteActivating:(C)=>{Gn(C)}}),R=async(C)=>{let N=await P.onRequest(C);switch(N.kind){case"ready":return{retry:!0};case"starting":return Wy({host:N.host,sinceMs:N.sinceMs,logTail:N.logTail});case"failed":return Ky({host:N.host,error:N.error,logTail:N.logTail});case"unknown":default:return}},t)x.info("rpx: on-demand sites enabled")}let v=Rn(y,t,R),T=An(t),S=null;if(w.length===0)S=await Ia(e,i);let D=e.onDemandTls,W=D?.enabled?new Ii({config:D,certsDir:D.certsDir??e.productionCerts?.certsDir??Ot.join(r,"on-demand-certs"),initial:w,verbose:t,onCertAdded:(C)=>{if(Fn()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",t),setTimeout(()=>E.kill(E.pid,"SIGTERM"),10).unref();else O(C)}}):null;function Xe(C){if(C.length>0)return jr(C.map((N)=>({serverName:N.serverName,cert:N.cert,key:N.key})));return jr({key:S.key,cert:S.cert,ca:S.ca,requestCert:!1,rejectUnauthorized:!1})}function at(C){try{return Bun.serve(C)}catch(N){let Ze=N instanceof Error?N.message:String(N),Yi=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test(Ze);if(!c||C.hostname!=="::"||!Yi)throw N;return m("daemon",`no IPv6 on this host (${Ze}); binding 0.0.0.0`,e.verbose),Bun.serve({...C,hostname:"0.0.0.0"})}}function Yr(C){return at({port:n,hostname:o,reusePort:wn(),tls:Xe(C),fetch(N,Ze){return v(N,Ze)},websocket:T,error(N){return m("daemon",`https server error: ${N}`,t),new Response(`Server Error: ${N.message}`,{status:500})}})}let Hi=(C)=>[...new Set(C.map((N)=>N.to).filter(Boolean))],sr=(C)=>{if(!S)return w;return sy([...Hi(C),...b,"rpx.localhost"],S)},Ie=Yr(W?W.sniEntries():w.length>0?w:sr(p)),ct=null,Ue=!1;async function O(C){if(At)return;if(ct=C,Ue)return;Ue=!0;try{while(!At&&ct){let N=ct;ct=null,m("daemon",`rebuilding :443 with ${N.length} SNI cert(s)`,t),Ie.stop(!1);let Ze,Yi=!1,Xf=60,Mw=500;for(let ic=0;!At&&!Yi;ic++)try{Ie=Yr(N),Yi=!0;break}catch(Iw){if(Ze=Iw,ic>=Xf)break;await new Promise((_w)=>setTimeout(_w,Math.min(25*2**Math.min(ic,4),Mw)))}if(!Yi)x.error(`rpx: CRITICAL — could not rebind :443 after ${Xf} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Ze?.message}`)}}finally{Ue=!1}}let We=null;if(s>0)We=at({port:s,hostname:o,fetch(C){return vw(C,W,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)x.success(`rpx daemon listening on https://${o}:${n}${We?` (http→https on :${s})`:""}`),x.info(`pid file: ${h}`),x.info(`registry: ${i}`);async function Vi(C){if(At||w.length>0||W||!S)return;try{S=await Ia(e,i,[...b]),await O(sr(C))}catch(N){m("daemon",`TLS sync on registry change failed: ${N}`,t)}}async function Gn(C){if(At||w.length>0||W||!S||!C)return;if(b.has(C))return;b.add(C);try{S=await Ia(e,i,[...b],!0);let N=await wt(i,t);await O(sr(N))}catch(N){m("daemon",`dev cert refresh for ${C} failed: ${N}`,t)}}let qn=Aa((C)=>{g(C),Vi(C),Wi(C,{rpxDir:r,verbose:t,ownerPid:E.pid}).catch((N)=>{m("daemon",`DNS sync on registry change failed: ${N}`,t)})},{dir:i,verbose:t}),zr=setInterval(()=>{Bn(i,t).then((C)=>{if(C>0)m("daemon",`gc reaped ${C} stale entries`,t)}).catch((C)=>{m("daemon",`periodic gc failed: ${C}`,t)}),jn({verbose:t}).then((C)=>{if(C.length>0)m("daemon",`gc reaped stale hosts entries: ${C.join(", ")}`,t)}).catch((C)=>{m("daemon",`periodic hosts gc failed: ${C}`,t)})},a);if(typeof zr.unref==="function")zr.unref();let At=!1,tc,rc=new Promise((C)=>{tc=C});async function qf(){if(At)return rc;if(At=!0,clearInterval(zr),qn.close(),await P?.stopAll().catch((C)=>{m("daemon",`site supervisor stopAll failed: ${C}`,t)}),Ie.stop(!1),We?.stop(!1),await Hr({rpxDir:r,verbose:t}).catch((C)=>{m("daemon",`DNS teardown failed: ${C}`,t)}),ja(new Set),await Ki(r),t)x.info("rpx daemon stopped");return tc(),rc}let Jf=(C)=>{m("daemon",`received ${C}, shutting down`,t),qf().catch(()=>{})};return E.once("SIGINT",Jf),E.once("SIGTERM",Jf),{stop:qf,done:rc,httpsPort:typeof Ie.port==="number"?Ie.port:n,httpPort:We&&typeof We.port==="number"?We.port:s,pidPath:h,ensureCert:(C)=>W?W.ensureCert(C):Promise.resolve(!1),listSites:()=>P?.list()??[]}}function Kf(e){return Ot.join(e,"cluster-sni.json")}async function dw(e,t,r){let i=Kf(e),n=`${i}.${E.pid}.tmp`;await _e.writeFile(n,JSON.stringify({sni:t,dev:r}),"utf8"),await _e.rename(n,i)}async function mw(e){try{return JSON.parse(await _e.readFile(Kf(e),"utf8"))}catch{return{sni:[],dev:null}}}function hR(e){if(e.sni.length>0)return jr(e.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key})));if(e.dev)return jr({key:e.dev.key,cert:e.dev.cert,ca:e.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function dR(){let e=E.execPath,t=E.env.RPX_WORKER_BIN;if(t)return[e,t,"daemon:start"];let r=Ot.basename(e).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&E.argv[1])return[e,E.argv[1],"daemon:start"];return[e,"daemon:start"]}async function mR(e){Wf();let{rpxDir:t,registryDir:r,httpsPort:i,hostname:n,verbose:s}=e,o=new Map,c=(T,S)=>On(o,T,S),a=(T)=>{o=kn(T.map((S)=>({host:S.to,path:S.path,route:ww(S)}))),ja(new Set(T.map((S)=>S.id)))};a(await wt(r,s));let l=Rn(c,s),u=An(s),f=!1,h=(T)=>Bun.serve({port:i,hostname:n,reusePort:!0,tls:hR(T),fetch(S,D){return l(S,D)},websocket:u,error(S){return m("daemon",`worker https error: ${S}`,s),new Response(`Server Error: ${S.message}`,{status:500})}}),d=h(await mw(t));async function y(){if(f)return;let T=await mw(t),S=null;for(let W=0;W<20&&!f;W++)try{S=h(T);break}catch{await new Promise((Xe)=>setTimeout(Xe,25))}if(!S){m("daemon","worker reloadTls: could not bind new listener; keeping current",s);return}let D=d;d=S,D.stop(!1)}let g=Aa((T)=>a(T),{dir:r,verbose:s}),p=()=>{y().catch(()=>{})};E.on("SIGHUP",p);let w=()=>{let T=E.removeListener??E.off;if(typeof T==="function")T.call(E,"SIGHUP",p)},b,P=new Promise((T)=>{b=T});async function R(){if(f)return P;return f=!0,w(),g.close(),d.stop(!1),ja(new Set),b(),P}let v=()=>{R().then(()=>E.exit(0)).catch(()=>E.exit(0))};if(E.once("SIGTERM",v),E.once("SIGINT",v),s)x.success(`rpx worker (pid ${E.pid}) serving :${i}`);return{stop:R,done:P,httpsPort:typeof d.port==="number"?d.port:i,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function gR(e,t){Wf();let{rpxDir:r,registryDir:i,httpsPort:n,httpPort:s,hostname:o,verbose:c,gcIntervalMs:a,workers:l}=t,u=await yw(r),f=[];if(e.productionCerts)f=await Dn(e.productionCerts,c);let h=null;if(f.length===0)h=await Ia(e,i);let d=h?{key:h.key,cert:h.cert,ca:Array.isArray(h.ca)?h.ca.join(`
|
|
298
|
-
`):h.ca}:null,y=!1,g=[];function p(O){for(let We of g)try{We.kill(O)}catch{}}async function w(O){await dw(r,O,d),p("SIGHUP")}let b=e.onDemandTls,P=b?.enabled?new Ii({config:b,certsDir:b.certsDir??e.productionCerts?.certsDir??Ot.join(r,"on-demand-certs"),initial:f,verbose:c,onCertAdded:(O)=>{if(Fn()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",c),setTimeout(()=>E.kill(E.pid,"SIGTERM"),10).unref();else w(O)}}):null;await dw(r,P?P.sniEntries():f,d);let R=await wt(i,c);await Vr({rpxDir:r,verbose:c}).catch((O)=>{m("daemon",`DNS reconcile on start failed: ${O}`,c)}),await Wi(R,{rpxDir:r,verbose:c,ownerPid:E.pid}).catch((O)=>{m("daemon",`DNS setup on start failed: ${O}`,c)}),await Bn(i,c).catch(()=>{}),await jn({verbose:c}).catch(()=>{});let v=Aa((O)=>{Wi(O,{rpxDir:r,verbose:c,ownerPid:E.pid}).catch((We)=>{m("daemon",`DNS sync on registry change failed: ${We}`,c)})},{dir:i,verbose:c}),T=setInterval(()=>{Bn(i,c).catch(()=>{}),jn({verbose:c}).catch(()=>{})},a);T.unref?.();let S=null;if(s>0)S=Bun.serve({port:s,hostname:o,fetch(O){return vw(O,P,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let D=10,W=60000,Xe=30000,at=0,Yr=Date.now();function Hi(){if(y)return;let O={...E.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:i,RPX_WORKER_HTTPSPORT:String(n),RPX_WORKER_HOSTNAME:o,RPX_WORKER_VERBOSE:c?"1":"0"},We=Bun.spawn(dR(),{env:O,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(Vi,Gn){if(y)return;let qn=g.indexOf(Vi);if(qn!==-1)g.splice(qn,1);let zr=Date.now();if(zr-Yr>W)Yr=zr,at=0;if(at++,at>D){x.error(`rpx: worker keeps exiting (code ${Gn}); giving up after ${D} restarts in ${Math.round(W/1000)}s`);return}let At=Math.min(Xe,100*2**Math.min(at,8));m("daemon",`worker exited (code ${Gn}); respawning in ${At}ms (restart ${at}/${D})`,c),setTimeout(Hi,At).unref?.()}});g.push(We)}for(let O=0;O<l;O++)Hi();if(c)x.success(`rpx coordinator listening on https://${o}:${n} via ${l} worker(s)${S?` (http→https on :${s})`:""}`),x.info(`pid file: ${u}`);let sr,Ie=new Promise((O)=>{sr=O});async function ct(){if(y)return Ie;if(y=!0,clearInterval(T),v.close(),S?.stop(!1),p("SIGTERM"),await Promise.race([Promise.all(g.map((O)=>O.exited)),new Promise((O)=>setTimeout(O,3000))]),p("SIGKILL"),await Hr({rpxDir:r,verbose:c}).catch((O)=>{m("daemon",`DNS teardown failed: ${O}`,c)}),await Ki(r),await _e.unlink(Kf(r)).catch(()=>{}),c)x.info("rpx coordinator stopped");return sr(),Ie}let Ue=(O)=>{m("daemon",`coordinator received ${O}, shutting down`,c),ct().catch(()=>{})};return E.once("SIGINT",Ue),E.once("SIGTERM",Ue),{stop:ct,done:Ie,httpsPort:n,httpPort:s,pidPath:u,ensureCert:(O)=>P?P.ensureCert(O):Promise.resolve(!1),listSites:()=>[]}}function pR(){let e=E.execPath,t=Ot.basename(e).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&E.argv[1])return[e,E.argv[1],"daemon:start"];return[e,"daemon:start"]}async function Wa(e={}){let t=e.rpxDir??Pe(),r=e.verbose??!1;await Vr({rpxDir:t,verbose:r}).catch((u)=>{m("daemon",`DNS reconcile before ensureDaemonRunning: ${u}`,r)});let i=await Tr(t);if(i!==null&&ot(i))return m("daemon",`ensureDaemonRunning: already running pid=${i}`,r),{pid:i,spawned:!1};if(i!==null)m("daemon",`ensureDaemonRunning: clearing stale pid=${i}`,r),await Ki(t);await _e.mkdir(t,{recursive:!0});let n=e.spawnCommand??pR();if(n.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");m("daemon",`spawning daemon: ${n.join(" ")}`,r);let s=gw(n[0],n.slice(1),{detached:!0,stdio:"ignore",cwd:e.spawnCwd??E.cwd(),env:e.spawnEnv?{...E.env,...e.spawnEnv}:E.env});s.unref();let o=null;s.once("error",(u)=>{o=u});let c=e.startupTimeoutMs??5000,a=e.pollIntervalMs??50,l=Date.now()+c;while(Date.now()<l){if(o)throw o;let u=await Tr(t);if(u!==null&&ot(u))return m("daemon",`daemon registered with pid=${u}`,r),{pid:u,spawned:!0};await new Promise((f)=>setTimeout(f,a))}if(o)throw o;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${t})`)}async function $w(e={}){let t=e.rpxDir??Pe(),r=e.verbose??!1,i=e.timeoutMs??5000,n=e.pollIntervalMs??50,s=e.forceAfterTimeout??!0,o=await Tr(t);if(o===null||!ot(o)){if(o!==null)await Ki(t);return await Vr({rpxDir:t,verbose:r}).catch(()=>{}),{stopped:!1,pid:o,forced:!1}}try{E.kill(o,"SIGTERM")}catch(a){let l=a.code;if(l==="ESRCH")return await Ki(t),{stopped:!1,pid:o,forced:!1};if(l==="EPERM")yr(`kill -TERM ${o}`);else throw a}let c=Date.now()+i;while(Date.now()<c){if(!ot(o))return m("daemon",`daemon pid=${o} stopped cleanly`,r),{stopped:!0,pid:o,forced:!1};await new Promise((a)=>setTimeout(a,n))}if(!s)throw Error(`rpx daemon (pid=${o}) did not exit within ${i}ms`);m("daemon",`daemon pid=${o} did not exit, escalating to SIGKILL`,r);try{E.kill(o,"SIGKILL")}catch(a){let l=a.code;if(l==="EPERM")yr(`kill -KILL ${o}`);else if(l!=="ESRCH")throw a}return await Ki(t),await Hr({rpxDir:t,verbose:r}).catch((a)=>{m("daemon",`DNS teardown after SIGKILL: ${a}`,r)}),{stopped:!0,pid:o,forced:!0}}async function xw(e={}){let t=e.rpxDir??Pe();if(await Ua(t))return;await Vr({rpxDir:t,verbose:e.verbose})}var cR=5000,_a,hw=!1;var Ma=Q(()=>{Nr();ff();gf();pf();Ca();vf();bf();ol();jy();$a();ya();Wr();Of();Kn();he();_a=new Map});import{dirname as kR,join as OR}from"node:path";import*as Me from"node:process";import{fileURLToPath as NR}from"node:url";import{existsSync as Hw}from"node:fs";import nc from"node:fs/promises";import Zf from"node:os";import sc from"node:path";import Rr from"node:process";import{EventEmitter as Vw}from"node:events";import or from"node:process";import eh from"node:process";import cc from"node:process";import Xn from"node:process";import qi from"node:process";import nh from"node:tty";import Dv,{stdin as ZR,stdout as eA}from"node:process";class sh{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Zf.homedir(),t=sc.join(e,".config","clapp");this.configPath=sc.join(t,"telemetry.json")}async isEnabled(){if(Rr.env.DO_NOT_TRACK==="1"||Rr.env.DO_NOT_TRACK==="true")return!1;if(Rr.env.NO_TELEMETRY==="1"||Rr.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let i={event:e,...t,timestamp:Date.now(),platform:Zf.platform(),nodeVersion:Rr.version};if(this.events.push(i),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:Rr.env.DO_NOT_TRACK==="1"||Rr.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Hw(this.configPath)){let e=await nc.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=sc.dirname(this.configPath);await nc.mkdir(t,{recursive:!0}),await nc.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var jR=new sh;function Yw(e,t={}){let r={_:[]},i=t.alias||{},n=new Set(t.boolean||[]),s={};for(let c of Object.keys(i))for(let a of i[c])s[a]=c;for(let c of n)if(i[c])for(let a of i[c])n.add(a);function o(c,a){let l=s[c]||c;if(r[l]=a,i[l])for(let u of i[l])r[u]=a;if(s[c]&&i[s[c]])for(let u of i[s[c]])r[u]=a;r[c]=a}for(let c=0;c<e.length;c++){let a=e[c];if(a==="--"){r._.push(...e.slice(c+1));break}if(a.startsWith("--")){let l=a.indexOf("=");if(l!==-1){let u=a.slice(2,l),f=a.slice(l+1);o(u,f)}else{let u=a.slice(2);if(u.startsWith("no-")){let h=u.slice(3);o(h,!1);continue}let f=s[u]||u;if(n.has(f)||n.has(u))o(u,!0);else{let h=e[c+1];if(h!==void 0&&!h.startsWith("-"))o(u,h),c++;else o(u,!0)}}}else if(a.startsWith("-")&&a.length>1){let l=a.slice(1);for(let u=0;u<l.length;u++){let f=l[u],h=s[f]||f;if(u===l.length-1&&!n.has(h)&&!n.has(f)){let d=e[c+1];if(d!==void 0&&!d.startsWith("-"))o(f,d),c++;else o(f,!0)}else o(f,!0)}}else r._.push(a)}return r}function ac(e){return e.replace(/[<[].+/,"").trim()}function zw(e){let t=/<([^>]+)>/g,r=/\[([^\]]+)\]/g,i=[],n=(c)=>{let a=!1,l=c[1];if(l.startsWith("..."))l=l.slice(3),a=!0;return{required:c[0].startsWith("<"),value:l,variadic:a}},s;while(s=t.exec(e))i.push(n(s));let o;while(o=r.exec(e))i.push(n(o));return i}function Gw(e){let t={alias:{},boolean:[]};for(let[r,i]of e.entries()){if(i.names.length>1)t.alias[i.names[0]]=i.names.slice(1);if(i.isBoolean)if(i.negated){if(!e.some((s,o)=>o!==r&&s.names.some((c)=>i.names.includes(c))&&typeof s.required==="boolean"))t.boolean.push(i.names[0])}else t.boolean.push(i.names[0])}return t}function th(e){return e.reduce((t,r)=>t.length>=r.length?t:r,"")}function oc(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function qw(e){return e.replace(/([a-z])-([a-z])/g,(t,r,i)=>r+i.toUpperCase())}function Jw(e,t,r){let i=0,n=t.length,s=e,o;for(;i<n;++i)o=s[t[i]],s=s[t[i]]=i===n-1?r:o!=null?o:!!~t[i+1].indexOf(".")||!(+t[i+1]>-1)?{}:[]}function Xw(e,t){for(let r of Object.keys(t)){let i=t[r];if(i.shouldTransform){if(e[r]=Array.prototype.concat.call([],e[r]),typeof i.transformFunction==="function")e[r]=e[r].map(i.transformFunction)}}}function Qw(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function oh(e){return e.split(".").map((t,r)=>r===0?qw(t):t).join(".")}class Jn extends Error{exitCode=2;isUsageError=!0;constructor(e){super(e);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
|
|
352
|
+
port ${Ps}
|
|
353
|
+
`}function li(e){return Iv.join(_v,e)}function Vv(e){return e.includes("127.0.0.1")&&e.includes(String(Ps))}async function ik(e){try{return await Bv.readFile(li(e),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function fd(e){if(dr.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:r,isProcessElevated:n}=await Promise.resolve().then(() => (fe(),ri));if(!n()&&!r()){m("dns","Cannot flush DNS cache without SUDO_PASSWORD",e);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),m("dns","DNS cache flushed",e)}catch(i){m("dns",`Could not flush DNS cache: ${i}`,e)}}function Hv(e){if(!/^[a-z0-9.-]+$/.test(e))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(e)}`)}async function sk(e,t){Hv(e);let{execSudoSync:r}=await Promise.resolve().then(() => (fe(),ri)),n=nk().replace(/\n/g,"\\n"),i=`bash -c 'mkdir -p ${_v} && printf "%b" "${n}" > ${li(e)}'`;r(i),m("dns",`Created ${li(e)}`,t)}async function ok(e,t){Hv(e);let{execSudoSync:r}=await Promise.resolve().then(() => (fe(),ri));r(`rm -f ${li(e)}`),m("dns",`Removed ${li(e)}`,t)}async function ak(e,t){return md({domains:t??[],verbose:e})}async function ck(e,t){if(dr.platform!=="darwin")return!0;let{getSudoPassword:r,isProcessElevated:n}=await Promise.resolve().then(() => (fe(),ri));if(!n()&&!r())return m("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let i of e)await sk(i,t);return await fd(t),!0}catch(i){return m("dns",`Failed to create resolver file: ${i}`,t),!1}}async function hd(e,t){if(dr.platform!=="darwin")return;let{getSudoPassword:r,isProcessElevated:n}=await Promise.resolve().then(() => (fe(),ri));if(!n()&&!r())return;try{for(let i of e)await ok(i,t);await fd(t)}catch(i){m("dns",`Failed to remove resolver files: ${i}`,t)}}async function dd(e){if(dr.platform!=="darwin")return[];let t=[];for(let r of kv){let n=await ik(r);if(n&&Vv(n))await hd([r],e),t.push(r)}return t}async function md(e){let t=e.rpxDir??De(),r=ld(e.domains);if(r.length===0)return!1;let n=cd(r),i=await Kv(r,e.verbose);if(!i){let c=r[0];if(c&&await Wv(c))i=!0;else m("dns","Dev DNS server not available on 127.0.0.1:15353",e.verbose)}if(!i)return!1;if(!await ck(n,e.verbose))return!1;let o={version:Nc,resolvers:n,domains:r,ownerPid:e.ownerPid??dr.pid,updatedAt:new Date().toISOString()};return await Nv(t,o),!0}async function ui(e,t={}){let r=e.map((a)=>a.to).filter(Boolean),n=t.rpxDir??De(),i=cd(r),c=((await Dc(n))?.resolvers??[]).filter((a)=>!i.includes(a));if(c.length>0)await hd(c,t.verbose);if(i.length===0){ud(t.verbose),await ad(n);return}await md({domains:r,rpxDir:n,verbose:t.verbose,ownerPid:t.ownerPid??dr.pid})}async function Qr(e={}){let t=e.rpxDir??De();ud(e.verbose);let n=(await Dc(t))?.resolvers??[];await hd(n,e.verbose),await dd(e.verbose),await ad(t)}async function lk(e){await Qr({verbose:e})}async function en(e={}){let t=e.rpxDir??De(),r=await Dc(t),n=r?.ownerPid!=null&&mt(r.ownerPid);if(r&&!n){m("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,e.verbose),await Qr(e);return}let i=await dd(e.verbose);if(i.length>0)m("dns",`reconcile: removed legacy TLD resolvers: ${i.join(", ")}`,e.verbose);await fd(e.verbose)}var Ps=15353,Mv="# managed-by: rpx",_v="/etc/resolver",st=null,Fc;var As=te(()=>{Bc();Fv();Xr();fe();Fc=new Set});import{spawn as Yv}from"node:child_process";import*as ze from"node:fs/promises";import{homedir as Jv}from"node:os";import*as It from"node:path";import*as T from"node:process";function De(){return It.join(Jv(),".stacks","rpx")}function Br(e=De()){return It.join(e,"daemon.pid")}async function Lr(e=De()){try{let t=await ze.readFile(Br(e),"utf8"),r=Number.parseInt(t.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(t){if(t.code==="ENOENT")return null;throw t}}async function jc(e=De()){let t=await Lr(e);return t!==null&&mt(t)}async function Xv(e=De()){await ze.mkdir(e,{recursive:!0});let t=Br(e);while(!0){try{let n=await ze.open(t,"wx");try{await n.write(`${T.pid}
|
|
354
|
+
`)}finally{await n.close()}return t}catch(n){if(n.code!=="EEXIST")throw n}let r=await Lr(e);if(r!==null&&mt(r))throw Error(`rpx daemon already running (pid=${r})`);await ze.unlink(t).catch(()=>{})}}async function fi(e=De()){await ze.unlink(Br(e)).catch(()=>{})}function _c(e){for(let[t,r]of Mc)if(!e.has(t))ii(r),Mc.delete(t)}function fk(e,t){let r=Kw(t??"localhost:1");if(e.upstreams.length!==r.length)return!1;return e.upstreams.every((n,i)=>n.url===r[i])}function Zv(e){let t=e.cleanUrls??!1,r=fr(e.path),n=os(e.auth);if(e.static)return{static:yc(e.static,t),cleanUrls:t,basePath:r,auth:n};let i=e.from??"localhost:1",s=qr(i),o=new URL(s.startsWith("http")?s:`http://${s}`),c=Mc.get(e.id);if(c&&!fk(c,i))ii(c),c=void 0;if(!c)c=rs(i,e.loadBalancer),is(c),Mc.set(e.id,c);return{sourceHost:o.host,upstreamPool:c,cleanUrls:t,changeOrigin:e.changeOrigin??!1,pathRewrites:e.pathRewrites,basePath:r,auth:n}}function hk(e){return e.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??e[0]??"rpx.localhost"}async function Ic(e,t,r=[],n=!1){let i=await xt(t,e.verbose),s=[...new Set([...i.map((u)=>u.to).filter(Boolean),...r])],o=hk(s),c=[...new Set([o,...s,"rpx.localhost"])],a=_w(s,o,e.verbose);if(typeof e.https==="object"&&typeof a.https==="object")a.https={...a.https,...e.https};let l=await Or(a);if(l&&(n||!jf(Dh,c)))m("daemon",`regenerating shared cert for host(s): ${c.join(", ")}`,e.verbose),Lh(),l=null;if(!l)m("daemon","no usable cert on disk, generating one via tlsx",e.verbose),await es({...a,forceRegenerate:!0}),l=await Or(a);if(!l)throw Error("failed to bootstrap TLS for rpx daemon");return l}async function dk(e,t,r,n){let i=T.env.SUDO_PASSWORD,s=T.env.HOME??Jv(),o=[T.execPath,...T.argv.slice(1)],c=[`HOME=${s}`,`PATH=${T.env.PATH??""}`];if(n)c.push("RPX_VERBOSE=1");for(let[y,g]of Object.entries(T.env))if(g!==void 0&&y!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(y))c.push(`${y}=${g}`);let a=i?["-S","-p","","env",...c,...o]:["-n","env",...c,...o];m("daemon",`elevating daemon via sudo for privileged ports ${t}/${r}`,n);let l=Yv("sudo",a,{detached:!0,stdio:["pipe","ignore","ignore"]}),u=null,f=null;if(l.once("error",(y)=>{u=y}),l.once("exit",(y)=>{f=y??0}),i&&l.stdin)l.stdin.write(`${i}
|
|
355
|
+
`),l.stdin.end();l.unref();let h=Br(e),d=Date.now()+15000;while(Date.now()<d){if(u)throw u;let y=await Lr(e);if(y!==null&&mt(y)){if(n)b.success(`rpx daemon elevated to root (pid=${y}, https on :${t})`);return{httpsPort:t,httpPort:r,pidPath:h,done:Promise.resolve(),stop:async()=>{try{T.kill(y,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(f!==null&&f!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${f}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((g)=>setTimeout(g,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${e})`)}function gd(){if(zv)return;zv=!0,T.on("uncaughtException",(e)=>{b.error(`rpx daemon: uncaught exception (continuing): ${e?.stack??e}`)}),T.on("unhandledRejection",(e)=>{b.error(`rpx daemon: unhandled rejection (continuing): ${e}`)})}function Qv(e,t,r){let n;try{n=new URL(e.url)}catch{return new Response("Bad Request",{status:400})}let i=(e.headers.get("host")??n.hostname).split(":")[0];if(n.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let s=t.challengeStore.handlePath(n.pathname);if(s!==void 0)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(r){let s=vc(r,n.pathname);if(s!=null)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(i))t.ensureCert(i).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${i}${n.pathname}${n.search}`}})}async function eb(e={}){gd();let t=e.verbose??!1,r=e.rpxDir??De(),n=e.registryDir??It.join(r,"registry.d"),i=e.httpsPort??443,s=e.httpPort??80,o=e.https===!1;if(e.localCa)ws(e.localCa,e.onDemandTls);let c=e.hostname??"::",a=e.hostname==null,l=e.gcIntervalMs??uk;if(T.env.RPX_DAEMON_WORKER==="1")return pk({rpxDir:T.env.RPX_WORKER_RPXDIR??r,registryDir:T.env.RPX_WORKER_REGISTRYDIR??n,httpsPort:Number.parseInt(T.env.RPX_WORKER_HTTPSPORT??"",10)||i,hostname:T.env.RPX_WORKER_HOSTNAME??c,verbose:T.env.RPX_WORKER_VERBOSE==="1"||t});let u=!o&&i>0&&i<1024||s>0&&s<1024,f=typeof T.getuid==="function"&&T.getuid()===0;if(T.platform!=="win32"&&u&&!f)return dk(r,i,s,t);let h=Math.max(1,e.workers??(Number.parseInt(T.env.RPX_WORKERS??"",10)||1));if(h>1){if(o)throw Error("rpx daemon: https: false is not supported with workers > 1 (the cluster shares the HTTPS port only); run a single process");if(e.onDemandSites?.enabled)b.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return yk(e,{rpxDir:r,registryDir:n,httpsPort:i,httpPort:s,hostname:c,verbose:t,gcIntervalMs:l,workers:h})}let d=await Xv(r),y=new Map,g=(E,N)=>fs(y,E,N);function p(E){y=us(E.map((Le)=>({host:Le.to,path:Le.path,route:Zv(Le)}))),_c(new Set(E.map((Le)=>Le.id)));let N=Array.from(y.keys());m("daemon",`routing table now covers ${N.length} host(s): ${N.join(", ")||"<empty>"}`,t)}await bs(n,t).catch((E)=>{m("daemon",`initial gc failed: ${E}`,t)}),await Es({verbose:t}).catch((E)=>{m("daemon",`stale hosts GC on start failed: ${E}`,t)});let w=await xt(n,t);p(w),await en({rpxDir:r,verbose:t}).catch((E)=>{m("daemon",`DNS reconcile on start failed: ${E}`,t)}),await ui(w,{rpxDir:r,verbose:t,ownerPid:T.pid}).catch((E)=>{m("daemon",`DNS setup on start failed: ${E}`,t)});let v=[];if(e.productionCerts&&!o){if(v=await ms(e.productionCerts,t),t&&v.length>0)b.info(`SNI: serving ${v.length} real cert(s): ${v.map((E)=>E.serverName).join(", ")}`)}let P=null;if(e.localCa&&!o){let E=await vs(e.localCa,{verbose:t,onDemandTls:e.onDemandTls}),N=new Set(E.entries.map((Le)=>Le.serverName));if(v=[...E.entries,...v.filter((Le)=>!N.has(Le.serverName))],P=E.defaultTls,t)b.info(`Local CA: ${E.leafMinted?`minted leaf (${E.renewalReason})`:"reusing leaf"} for ${[...N].join(", ")}; valid until ${E.notAfter.toISOString()}`)}let A=new Set,R=null,D;if(e.onDemandSites?.enabled){if(R=new ed({resolver:su(e.onDemandSites),registryDir:n,rpxDir:r,verbose:t,startupTimeoutMs:e.onDemandSites.startupTimeoutMs,isHostRoutable:(E)=>Uh(y,E)!==void 0,onSiteActivating:(E)=>{tn(E)}}),D=async(E)=>{let N=await R.onRequest(E);switch(N.kind){case"ready":return{retry:!0};case"starting":return Cv({host:N.host,sinceMs:N.sinceMs,logTail:N.logTail});case"failed":return xv({host:N.host,error:N.error,logTail:N.logTail});case"unknown":default:return}},t)b.info("rpx: on-demand sites enabled")}let F=cs(g,t,D),x=ls(t),k=null;if(!o&&v.length===0)k=await Ic(e,n);let L=e.onDemandTls,ee=L?.enabled&&!o?new oi({config:L,certsDir:L.certsDir??e.productionCerts?.certsDir??It.join(r,"on-demand-certs"),initial:v,verbose:t,onCertAdded:(E)=>{if(gs()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",t),setTimeout(()=>T.kill(T.pid,"SIGTERM"),10).unref();else pe(E)}}):null;function Re(E){if(E.length>0)return ds({sni:E,defaultTls:P,maxTlsContexts:e.maxTlsContexts,verbose:t});return si({key:k.key,cert:k.cert,ca:k.ca,requestCert:!1,rejectUnauthorized:!1})}function Ge(E){try{return Bun.serve(E)}catch(N){let Le=N instanceof Error?N.message:String(N),di=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test(Le);if(!a||E.hostname!=="::"||!di)throw N;return m("daemon",`no IPv6 on this host (${Le}); binding 0.0.0.0`,e.verbose),Bun.serve({...E,hostname:"0.0.0.0"})}}function jt(E){return Ge({port:i,hostname:c,reusePort:ti(),tls:Re(E),fetch(N,Le){return F(N,Le)},websocket:x,error(N){return m("daemon",`https server error: ${N}`,t),new Response(`Server Error: ${N.message}`,{status:500})}})}let hi=(E)=>[...new Set(E.map((N)=>N.to).filter(Boolean))],mr=(E)=>{if(!k)return v;return Mw([...hi(E),...A,"rpx.localhost"],k)},St=o?null:jt(ee?ee.sniEntries():v.length>0?v:mr(w)),rt=null,O=!1;async function pe(E){if(gr||o)return;if(rt=E,O)return;O=!0;try{while(!gr&&rt){let N=rt;rt=null,m("daemon",`rebuilding :443 with ${N.length} SNI cert(s)`,t),St?.stop(!1);let Le,di=!1,Td=60,$b=500;for(let rl=0;!gr&&!di;rl++)try{St=jt(N),di=!0;break}catch(Cb){if(Le=Cb,rl>=Td)break;await new Promise((xb)=>setTimeout(xb,Math.min(25*2**Math.min(rl,4),$b)))}if(!di)b.error(`rpx: CRITICAL — could not rebind :443 after ${Td} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Le?.message}`)}}finally{O=!1}}let ye=null;if(o)ye=Ge({port:s,hostname:c,reusePort:ti(),fetch(E,N){return F(E,N)},websocket:x,error(E){return m("daemon",`http server error: ${E}`,t),new Response(`Server Error: ${E.message}`,{status:500})}});else if(s>0)ye=Ge({port:s,hostname:c,fetch(E){return Qv(E,ee,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t){if(o)b.success(`rpx daemon listening on http://${c}:${ye?.port??s} (https disabled)`);else b.success(`rpx daemon listening on https://${c}:${i}${ye?` (http→https on :${s})`:""}`);b.info(`pid file: ${d}`),b.info(`registry: ${n}`)}async function Ir(E){if(gr||v.length>0||ee||!k)return;try{k=await Ic(e,n,[...A]),await pe(mr(E))}catch(N){m("daemon",`TLS sync on registry change failed: ${N}`,t)}}async function tn(E){if(gr||v.length>0||ee||!k||!E)return;if(A.has(E))return;A.add(E);try{k=await Ic(e,n,[...A],!0);let N=await xt(n,t);await pe(mr(N))}catch(N){m("daemon",`dev cert refresh for ${E} failed: ${N}`,t)}}let Fs=Ac((E)=>{p(E),Ir(E),ui(E,{rpxDir:r,verbose:t,ownerPid:T.pid}).catch((N)=>{m("daemon",`DNS sync on registry change failed: ${N}`,t)})},{dir:n,verbose:t}),rn=setInterval(()=>{bs(n,t).then((E)=>{if(E>0)m("daemon",`gc reaped ${E} stale entries`,t)}).catch((E)=>{m("daemon",`periodic gc failed: ${E}`,t)}),Es({verbose:t}).then((E)=>{if(E.length>0)m("daemon",`gc reaped stale hosts entries: ${E.join(", ")}`,t)}).catch((E)=>{m("daemon",`periodic hosts gc failed: ${E}`,t)})},l);if(typeof rn.unref==="function")rn.unref();let gr=!1,xd,tl=new Promise((E)=>{xd=E});async function Sd(){if(gr)return tl;if(gr=!0,clearInterval(rn),Fs.close(),await R?.stopAll().catch((E)=>{m("daemon",`site supervisor stopAll failed: ${E}`,t)}),St?.stop(!1),ye?.stop(!1),await Qr({rpxDir:r,verbose:t}).catch((E)=>{m("daemon",`DNS teardown failed: ${E}`,t)}),_c(new Set),await fi(r),t)b.info("rpx daemon stopped");return xd(),tl}let Ed=(E)=>{m("daemon",`received ${E}, shutting down`,t),Sd().catch(()=>{})};return T.once("SIGINT",Ed),T.once("SIGTERM",Ed),{stop:Sd,done:tl,httpsPort:St&&typeof St.port==="number"?St.port:o?0:i,httpPort:ye&&typeof ye.port==="number"?ye.port:s,pidPath:d,ensureCert:(E)=>ee?ee.ensureCert(E):Promise.resolve(!1),listSites:()=>R?.list()??[]}}function pd(e){return It.join(e,"cluster-sni.json")}async function Gv(e,t,r,n=null){let i=pd(e),s=`${i}.${T.pid}.tmp`;await ze.writeFile(s,JSON.stringify({sni:t,dev:r,defaultTls:n}),"utf8"),await ze.rename(s,i)}async function qv(e){try{return JSON.parse(await ze.readFile(pd(e),"utf8"))}catch{return{sni:[],dev:null}}}function mk(e){if(e.sni.length>0)return ds({sni:e.sni,defaultTls:e.defaultTls??null});if(e.dev)return si({key:e.dev.key,cert:e.dev.cert,ca:e.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function gk(){let e=T.execPath,t=T.env.RPX_WORKER_BIN;if(t)return[e,t,"daemon:start"];let r=It.basename(e).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&T.argv[1])return[e,T.argv[1],"daemon:start"];return[e,"daemon:start"]}async function pk(e){gd();let{rpxDir:t,registryDir:r,httpsPort:n,hostname:i,verbose:s}=e,o=new Map,c=(D,F)=>fs(o,D,F),a=(D)=>{o=us(D.map((F)=>({host:F.to,path:F.path,route:Zv(F)}))),_c(new Set(D.map((F)=>F.id)))};a(await xt(r,s));let l=cs(c,s),u=ls(s),f=!1,h=(D)=>Bun.serve({port:n,hostname:i,reusePort:!0,tls:mk(D),fetch(F,x){return l(F,x)},websocket:u,error(F){return m("daemon",`worker https error: ${F}`,s),new Response(`Server Error: ${F.message}`,{status:500})}}),d=h(await qv(t));async function y(){if(f)return;let D=await qv(t),F=null;for(let k=0;k<20&&!f;k++)try{F=h(D);break}catch{await new Promise((L)=>setTimeout(L,25))}if(!F){m("daemon","worker reloadTls: could not bind new listener; keeping current",s);return}let x=d;d=F,x.stop(!1)}let g=Ac((D)=>a(D),{dir:r,verbose:s}),p=()=>{y().catch(()=>{})};T.on("SIGHUP",p);let w=()=>{let D=T.removeListener??T.off;if(typeof D==="function")D.call(T,"SIGHUP",p)},v,P=new Promise((D)=>{v=D});async function A(){if(f)return P;return f=!0,w(),g.close(),d.stop(!1),_c(new Set),v(),P}let R=()=>{A().then(()=>T.exit(0)).catch(()=>T.exit(0))};if(T.once("SIGTERM",R),T.once("SIGINT",R),s)b.success(`rpx worker (pid ${T.pid}) serving :${n}`);return{stop:A,done:P,httpsPort:typeof d.port==="number"?d.port:n,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function yk(e,t){gd();let{rpxDir:r,registryDir:n,httpsPort:i,httpPort:s,hostname:o,verbose:c,gcIntervalMs:a,workers:l}=t,u=await Xv(r),f=[];if(e.productionCerts)f=await ms(e.productionCerts,c);let h=null;if(e.localCa){let O=await vs(e.localCa,{verbose:c,onDemandTls:e.onDemandTls}),pe=new Set(O.entries.map((ye)=>ye.serverName));f=[...O.entries,...f.filter((ye)=>!pe.has(ye.serverName))],h=O.defaultTls}let d=null;if(f.length===0)d=await Ic(e,n);let y=d?{key:d.key,cert:d.cert,ca:Array.isArray(d.ca)?d.ca.join(`
|
|
356
|
+
`):d.ca}:null,g=!1,p=[];function w(O){for(let pe of p)try{pe.kill(O)}catch{}}async function v(O){await Gv(r,$c(O,e.maxTlsContexts,c),y,h),w("SIGHUP")}let P=e.onDemandTls,A=P?.enabled?new oi({config:P,certsDir:P.certsDir??e.productionCerts?.certsDir??It.join(r,"on-demand-certs"),initial:f,verbose:c,onCertAdded:(O)=>{if(gs()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",c),setTimeout(()=>T.kill(T.pid,"SIGTERM"),10).unref();else v(O)}}):null;await Gv(r,$c(A?A.sniEntries():f,e.maxTlsContexts,c),y,h);let R=await xt(n,c);await en({rpxDir:r,verbose:c}).catch((O)=>{m("daemon",`DNS reconcile on start failed: ${O}`,c)}),await ui(R,{rpxDir:r,verbose:c,ownerPid:T.pid}).catch((O)=>{m("daemon",`DNS setup on start failed: ${O}`,c)}),await bs(n,c).catch(()=>{}),await Es({verbose:c}).catch(()=>{});let D=Ac((O)=>{ui(O,{rpxDir:r,verbose:c,ownerPid:T.pid}).catch((pe)=>{m("daemon",`DNS sync on registry change failed: ${pe}`,c)})},{dir:n,verbose:c}),F=setInterval(()=>{bs(n,c).catch(()=>{}),Es({verbose:c}).catch(()=>{})},a);F.unref?.();let x=null;if(s>0)x=Bun.serve({port:s,hostname:o,fetch(O){return Qv(O,A,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let k=10,L=60000,ee=30000,Re=0,Ge=Date.now();function jt(){if(g)return;let O={...T.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:n,RPX_WORKER_HTTPSPORT:String(i),RPX_WORKER_HOSTNAME:o,RPX_WORKER_VERBOSE:c?"1":"0"},pe=Bun.spawn(gk(),{env:O,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(ye,Ir){if(g)return;let tn=p.indexOf(ye);if(tn!==-1)p.splice(tn,1);let Fs=Date.now();if(Fs-Ge>L)Ge=Fs,Re=0;if(Re++,Re>k){b.error(`rpx: worker keeps exiting (code ${Ir}); giving up after ${k} restarts in ${Math.round(L/1000)}s`);return}let rn=Math.min(ee,100*2**Math.min(Re,8));m("daemon",`worker exited (code ${Ir}); respawning in ${rn}ms (restart ${Re}/${k})`,c),setTimeout(jt,rn).unref?.()}});p.push(pe)}for(let O=0;O<l;O++)jt();if(c)b.success(`rpx coordinator listening on https://${o}:${i} via ${l} worker(s)${x?` (http→https on :${s})`:""}`),b.info(`pid file: ${u}`);let hi,mr=new Promise((O)=>{hi=O});async function St(){if(g)return mr;if(g=!0,clearInterval(F),D.close(),x?.stop(!1),w("SIGTERM"),await Promise.race([Promise.all(p.map((O)=>O.exited)),new Promise((O)=>setTimeout(O,3000))]),w("SIGKILL"),await Qr({rpxDir:r,verbose:c}).catch((O)=>{m("daemon",`DNS teardown failed: ${O}`,c)}),await fi(r),await ze.unlink(pd(r)).catch(()=>{}),c)b.info("rpx coordinator stopped");return hi(),mr}let rt=(O)=>{m("daemon",`coordinator received ${O}, shutting down`,c),St().catch(()=>{})};return T.once("SIGINT",rt),T.once("SIGTERM",rt),{stop:St,done:mr,httpsPort:i,httpPort:s,pidPath:u,ensureCert:(O)=>A?A.ensureCert(O):Promise.resolve(!1),listSites:()=>[]}}function wk(){let e=T.execPath,t=It.basename(e).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&T.argv[1])return[e,T.argv[1],"daemon:start"];return[e,"daemon:start"]}async function Uc(e={}){let t=e.rpxDir??De(),r=e.verbose??!1;await en({rpxDir:t,verbose:r}).catch((u)=>{m("daemon",`DNS reconcile before ensureDaemonRunning: ${u}`,r)});let n=await Lr(t);if(n!==null&&mt(n))return m("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)m("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await fi(t);await ze.mkdir(t,{recursive:!0});let i=e.spawnCommand??wk();if(i.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");m("daemon",`spawning daemon: ${i.join(" ")}`,r);let s=Yv(i[0],i.slice(1),{detached:!0,stdio:"ignore",cwd:e.spawnCwd??T.cwd(),env:e.spawnEnv?{...T.env,...e.spawnEnv}:T.env});s.unref();let o=null;s.once("error",(u)=>{o=u});let c=e.startupTimeoutMs??5000,a=e.pollIntervalMs??50,l=Date.now()+c;while(Date.now()<l){if(o)throw o;let u=await Lr(t);if(u!==null&&mt(u))return m("daemon",`daemon registered with pid=${u}`,r),{pid:u,spawned:!0};await new Promise((f)=>setTimeout(f,a))}if(o)throw o;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${t})`)}async function tb(e={}){let t=e.rpxDir??De(),r=e.verbose??!1,n=e.timeoutMs??5000,i=e.pollIntervalMs??50,s=e.forceAfterTimeout??!0,o=await Lr(t);if(o===null||!mt(o)){if(o!==null)await fi(t);return await en({rpxDir:t,verbose:r}).catch(()=>{}),{stopped:!1,pid:o,forced:!1}}try{T.kill(o,"SIGTERM")}catch(a){let l=a.code;if(l==="ESRCH")return await fi(t),{stopped:!1,pid:o,forced:!1};if(l==="EPERM")Tr(`kill -TERM ${o}`);else throw a}let c=Date.now()+n;while(Date.now()<c){if(!mt(o))return m("daemon",`daemon pid=${o} stopped cleanly`,r),{stopped:!0,pid:o,forced:!1};await new Promise((a)=>setTimeout(a,i))}if(!s)throw Error(`rpx daemon (pid=${o}) did not exit within ${n}ms`);m("daemon",`daemon pid=${o} did not exit, escalating to SIGKILL`,r);try{T.kill(o,"SIGKILL")}catch(a){let l=a.code;if(l==="EPERM")Tr(`kill -KILL ${o}`);else if(l!=="ESRCH")throw a}return await fi(t),await Qr({rpxDir:t,verbose:r}).catch((a)=>{m("daemon",`DNS teardown after SIGKILL: ${a}`,r)}),{stopped:!0,pid:o,forced:!0}}async function rb(e={}){let t=e.rpxDir??De();if(await jc(t))return;await en({rpxDir:t,verbose:e.verbose})}var uk=5000,Mc,zv=!1;var Bc=te(()=>{qt();hc();_h();jh();bc();Wh();Gh();xc();ou();bv();wc();mc();Xr();id();As();fe();Mc=new Map});import{dirname as Mk,join as _k}from"node:path";import*as Fe from"node:process";import{fileURLToPath as jk}from"node:url";import{existsSync as Ab}from"node:fs";import il from"node:fs/promises";import Pd from"node:os";import sl from"node:path";import Mr from"node:process";import{EventEmitter as Rb}from"node:events";import pr from"node:process";import Ad from"node:process";import cl from"node:process";import Bs from"node:process";import pi from"node:process";import Nd from"node:tty";import y$,{stdin as a1,stdout as c1}from"node:process";class Dd{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Pd.homedir(),t=sl.join(e,".config","clapp");this.configPath=sl.join(t,"telemetry.json")}async isEnabled(){if(Mr.env.DO_NOT_TRACK==="1"||Mr.env.DO_NOT_TRACK==="true")return!1;if(Mr.env.NO_TELEMETRY==="1"||Mr.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let n={event:e,...t,timestamp:Date.now(),platform:Pd.platform(),nodeVersion:Mr.version};if(this.events.push(n),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:Mr.env.DO_NOT_TRACK==="1"||Mr.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Ab(this.configPath)){let e=await il.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=sl.dirname(this.configPath);await il.mkdir(t,{recursive:!0}),await il.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var qk=new Dd;function kb(e,t={}){let r={_:[]},n=t.alias||{},i=new Set(t.boolean||[]),s={};for(let c of Object.keys(n))for(let a of n[c])s[a]=c;for(let c of i)if(n[c])for(let a of n[c])i.add(a);function o(c,a){let l=s[c]||c;if(r[l]=a,n[l])for(let u of n[l])r[u]=a;if(s[c]&&n[s[c]])for(let u of n[s[c]])r[u]=a;r[c]=a}for(let c=0;c<e.length;c++){let a=e[c];if(a==="--"){r._.push(...e.slice(c+1));break}if(a.startsWith("--")){let l=a.indexOf("=");if(l!==-1){let u=a.slice(2,l),f=a.slice(l+1);o(u,f)}else{let u=a.slice(2);if(u.startsWith("no-")){let h=u.slice(3);o(h,!1);continue}let f=s[u]||u;if(i.has(f)||i.has(u))o(u,!0);else{let h=e[c+1];if(h!==void 0&&!h.startsWith("-"))o(u,h),c++;else o(u,!0)}}}else if(a.startsWith("-")&&a.length>1){let l=a.slice(1);for(let u=0;u<l.length;u++){let f=l[u],h=s[f]||f;if(u===l.length-1&&!i.has(h)&&!i.has(f)){let d=e[c+1];if(d!==void 0&&!d.startsWith("-"))o(f,d),c++;else o(f,!0)}else o(f,!0)}}else r._.push(a)}return r}function al(e){return e.replace(/[<[].+/,"").trim()}function Ob(e){let t=/<([^>]+)>/g,r=/\[([^\]]+)\]/g,n=[],i=(c)=>{let a=!1,l=c[1];if(l.startsWith("..."))l=l.slice(3),a=!0;return{required:c[0].startsWith("<"),value:l,variadic:a}},s;while(s=t.exec(e))n.push(i(s));let o;while(o=r.exec(e))n.push(i(o));return n}function Nb(e){let t={alias:{},boolean:[]};for(let[r,n]of e.entries()){if(n.names.length>1)t.alias[n.names[0]]=n.names.slice(1);if(n.isBoolean)if(n.negated){if(!e.some((s,o)=>o!==r&&s.names.some((c)=>n.names.includes(c))&&typeof s.required==="boolean"))t.boolean.push(n.names[0])}else t.boolean.push(n.names[0])}return t}function Rd(e){return e.reduce((t,r)=>t.length>=r.length?t:r,"")}function ol(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function Db(e){return e.replace(/([a-z])-([a-z])/g,(t,r,n)=>r+n.toUpperCase())}function Fb(e,t,r){let n=0,i=t.length,s=e,o;for(;n<i;++n)o=s[t[n]],s=s[t[n]]=n===i-1?r:o!=null?o:!!~t[n+1].indexOf(".")||!(+t[n+1]>-1)?{}:[]}function Lb(e,t){for(let r of Object.keys(t)){let n=t[r];if(n.shouldTransform){if(e[r]=Array.prototype.concat.call([],e[r]),typeof n.transformFunction==="function")e[r]=e[r].map(n.transformFunction)}}}function Bb(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function Fd(e){return e.split(".").map((t,r)=>r===0?Db(t):t).join(".")}class Ls extends Error{exitCode=2;isUsageError=!0;constructor(e){super(e);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
|
|
299
357
|
|
|
300
358
|
Stack trace:
|
|
301
|
-
${this.stack}`;return this.message}}function
|
|
359
|
+
${this.stack}`;return this.message}}function Ib(){let{env:e}=Ad,{TERM:t,TERM_PROGRAM:r}=e;if(Ad.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||r==="Terminus-Sublime"||r==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Is="\x1B",ge=`${Is}[`;var kd={to(e,t){if(!t)return`${ge}${e+1}G`;return`${ge}${t+1};${e+1}H`},move(e,t){let r="";if(e<0)r+=`${ge}${-e}D`;else if(e>0)r+=`${ge}${e}C`;if(t<0)r+=`${ge}${-t}A`;else if(t>0)r+=`${ge}${t}B`;return r},up:(e=1)=>`${ge}${e}A`,down:(e=1)=>`${ge}${e}B`,forward:(e=1)=>`${ge}${e}C`,backward:(e=1)=>`${ge}${e}D`,nextLine:(e=1)=>`${ge}E`.repeat(e),prevLine:(e=1)=>`${ge}F`.repeat(e),left:`${ge}G`,hide:`${ge}?25l`,show:`${ge}?25h`,save:`${Is}7`,restore:`${Is}8`};var Zk={screen:`${ge}2J`,up:(e=1)=>`${ge}1J`.repeat(e),down:(e=1)=>`${ge}J`.repeat(e),line:`${ge}2K`,lineEnd:`${ge}K`,lineStart:`${ge}1K`,lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?kd.up():"");if(e)t+=kd.left;return t}},Qk={screen:`${Is}c`};function Mb(e,t){let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=t.length;n++)for(let i=1;i<=e.length;i++)if(t.charAt(n-1)===e.charAt(i-1))r[n][i]=r[n-1][i-1];else r[n][i]=Math.min(r[n-1][i-1]+1,r[n][i-1]+1,r[n-1][i]+1);return r[t.length][e.length]}function Ld(e,t,r=2,n=3){return t.map((i)=>({cmd:i,distance:Mb(e,i)})).filter(({distance:i})=>i<=r).sort((i,s)=>i.distance-s.distance).slice(0,n).map(({cmd:i})=>i)}class Bd{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,r){if(this.rawName=e,this.description=t,this.config=Object.assign({},r),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=al(e).split(",").map((n)=>{let i=n.trim().replace(/^-{1,2}/,"");if(i.startsWith("no-"))this.negated=!0,i=i.replace(/^no-/,"");return Fd(i)}).sort((n,i)=>n.length>i.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var t1=cl.argv,_b=`${cl.platform}-${cl.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,Od=Bs.argv,jb=`${Bs.platform}-${Bs.arch} node-${Bs.version}`;class ll{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,r,n){this.rawName=e,this.description=t,this.config=r,this.cli=n,this.options=[],this.aliasNames=[],this.name=al(e);let i=al(e),s=i.indexOf(":");if(s>0)this.namespace=i.substring(0,s),this.name=i.substring(s+1);if(this.args=Ob(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!r)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,r){let n=new Bd(e,t,r);return this.options.push(n),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof ul}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){return e=e.split(".")[0],!!this.options.find((t)=>t.names.includes(e))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:r,options:n,helpCallback:i}=this.cli.globalCommand,s=[{body:`${e}${r?`/${r}`:""}`}];if(s.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let a=Rd(t.map((d)=>d.rawName)),l=new Map,u=[];for(let d of t)if(d.namespace){if(!l.has(d.namespace))l.set(d.namespace,[]);l.get(d.namespace).push(d)}else u.push(d);let f="";if(u.length>0)f+=u.map((d)=>` ${ol(d.rawName,a.length)} ${d.description}`).join(`
|
|
302
360
|
`);let h=Array.from(l.keys()).sort();for(let d of h){let y=l.get(d);if(f.length>0)f+=`
|
|
303
361
|
|
|
304
362
|
`;f+=` ${d}:
|
|
305
|
-
`,f+=y.map((g)=>` ${
|
|
363
|
+
`,f+=y.map((g)=>` ${ol(g.rawName,a.length-2)} ${g.description}`).join(`
|
|
306
364
|
`)}s.push({title:"Commands",body:f}),s.push({title:"For more info, run any command with the `--help` flag",body:t.map((d)=>` $ ${e}${d.displayName===""?"":` ${d.displayName}`} --help`).join(`
|
|
307
|
-
`)})}let c=this.isGlobalCommand?
|
|
365
|
+
`)})}let c=this.isGlobalCommand?n:[...this.options,...n||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)c=c.filter((a)=>a.name!=="version");if(c.length>0){let a=Rd(c.map((l)=>l.rawName));s.push({title:"Options",body:c.map((l)=>` ${ol(l.rawName,a.length)} ${l.description} ${l.config.default===void 0?"":`(default: ${l.config.default})`}`).join(`
|
|
308
366
|
`)})}if(this.examples.length>0)s.push({title:"Examples",body:this.examples.map((a)=>{if(typeof a==="function")return a(e);return a}).join(`
|
|
309
|
-
`)});if(
|
|
367
|
+
`)});if(i)s=i(s)||s;console.log(s.map((a)=>a.title?`${a.title}:
|
|
310
368
|
${a.body}`:a.body).join(`
|
|
311
369
|
|
|
312
|
-
`))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;if(t)console.log(`${e}/${t} ${typeof Bun<"u"?
|
|
370
|
+
`))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;if(t)console.log(`${e}/${t} ${typeof Bun<"u"?_b:jb}`)}checkRequiredArgs(){let e=this.args.filter((t)=>t.required).length;if(this.cli.args.length<e){let r=this.args.filter((i)=>i.required).slice(this.cli.args.length),n=r.map((i)=>`<${i.value}>`).join(" ");throw new Ls(`Missing required argument${r.length>1?"s":""}: ${n}
|
|
313
371
|
|
|
314
|
-
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let r of Object.keys(e))if(r!=="--"&&!this.hasOption(r)&&!t.hasOption(r)){let
|
|
372
|
+
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let r of Object.keys(e))if(r!=="--"&&!this.hasOption(r)&&!t.hasOption(r)){let i=[...t.options,...this.options].flatMap((a)=>a.names),s=r.length>1?`--${r}`:`-${r}`,o=Ld(r,i),c=`Unknown option \`${s}\``;if(o.length>0)c+=`
|
|
315
373
|
|
|
316
374
|
Did you mean one of these?`,o.forEach((a)=>{let l=a.length>1?`--${a}`:`-${a}`;c+=`
|
|
317
375
|
• ${l}`});throw c+=`
|
|
318
376
|
|
|
319
|
-
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new
|
|
377
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new Ls(c)}}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,r=[...t.options,...this.options];for(let n of r){let i=e[n.name.split(".")[0]];if(n.required){let s=r.some((o)=>o.negated&&o.names.includes(n.name));if(i===!0||i===!1&&!s)throw new Ls(`Option \`${n.rawName}\` requires a value.
|
|
320
378
|
|
|
321
|
-
Example: ${this.cli.name} ${this.rawName} ${
|
|
379
|
+
Example: ${this.cli.name} ${this.rawName} ${n.rawName} <value>`)}}}}class ul extends ll{constructor(e){super("@@global@@","",{},e)}}var Ub=ll,yr={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var mi={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function Kb(){return!0}function Wb(){let e={};e.supportsColor=Kb();function t(n,i=[]){let s=n===""?[]:[...i,n],o=function(a){if(!e.supportsColor)return a;let l="",u="";for(let f of s)if(f in mi&&mi[f]in yr){let h=mi[f];l+=yr[h][0],u=yr[h][1]+u}else if(f in yr)l+=yr[f][0],u=yr[f][1]+u;return l+a+u},c=[...Object.keys(yr),...Object.keys(mi)];for(let a of c)if(!(a in o))Object.defineProperty(o,a,{get(){return t(a,s)}});return o}let r=[...Object.keys(yr),...Object.keys(mi)];for(let n of r)if(!(n in e))Object.defineProperty(e,n,{get(){return t(n)}});return e}var gi=Wb();class fl extends Rb{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(e=""){super();this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new ul(this),this.globalCommand.usage("<command> [options]")}handleSignals(e){if(this.signalHandlersSet)return this;let t=async(r)=>{if(console.log(`
|
|
322
380
|
|
|
323
|
-
Received ${r}, cleaning up...`),e)try{await e()}catch(
|
|
381
|
+
Received ${r}, cleaning up...`),e)try{await e()}catch(n){console.error("Error during cleanup:",n)}pr.exit(0)};return pr.on("SIGINT",()=>t("SIGINT")),pr.on("SIGTERM",()=>t("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(e=!0){return this.enableDidYouMean=e,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(e){return this.globalCommand.usage(e),this}command(e,t,r){if(!r)r={};let n=new Ub(e,t||"",r,this);return n.globalCommand=this.globalCommand,this.commands.push(n),n}option(e,t,r){return this.globalCommand.option(e,t,r),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t="-v, --version"){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},r,n){if(this.args=e,this.options=t,r)this.matchedCommand=r;if(n)this.matchedCommandName=n;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(e){if(console.log(gi.red(`
|
|
324
382
|
✗ Command "${e}" not found.
|
|
325
|
-
`)),this.enableDidYouMean){let t=[];for(let
|
|
326
|
-
Run \`${this.name??"cli"} --help\` for usage.`;
|
|
327
|
-
`),
|
|
328
|
-
`,o=(a)=>{let l=za(a);return r.has(l)||i.some((u)=>Or(l,u))},c=(a)=>{let l=xR(a);if(!o(l))return;let u="/";try{u=new URL(a.url).pathname}catch{}if(n.some((f)=>u.startsWith(f)))return;if(bR(a.headers.get(t),e.value))return;return new Response(s,{status:403,headers:{"content-type":"text/plain"}})};return c.protects=o,c}gf();pf();ya();Ca();vf();bf();$a();he();var Tw={name:"@stacksjs/rpx",type:"module",version:"0.11.46",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build --production ./bin/cli.ts --compile --outfile bin/rpx",compile:"bun build --production ./bin/cli.ts --compile --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build --production ./bin/cli.ts --compile --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build --production ./bin/cli.ts --compile --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build --production ./bin/cli.ts --compile --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build --production ./bin/cli.ts --compile --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build --production ./bin/cli.ts --compile --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.13"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var Hn=Tw.version;var qa=new Ha,ER=new Ta("0.0.0.0"),Yn=new Set,Xa=new Set,Vf=!1,Ga=null,Yf=null;async function ec(e){if(Vf)return m("cleanup","Cleanup already in progress, skipping",e?.verbose),Yf||Promise.resolve();Vf=!0,m("cleanup","Starting cleanup process",e?.verbose),Yf=new Promise((t)=>{Ga=t});try{await qa.stopAll(e?.verbose),x.info("Shutting down proxy servers...");let t=[],r=Array.from(Yn).map((i)=>new Promise((n)=>{let s=i;try{if(typeof s.stop==="function")s.stop(!0),m("cleanup","Bun server stopped",e?.verbose),n();else if(typeof s.close==="function")s.close(()=>{m("cleanup","Server closed successfully",e?.verbose),n()});else n()}catch(o){m("cleanup",`Error stopping server: ${o}`,e?.verbose),n()}}));t.push(...r),Yn.clear();for(let i of Xa)Mi(i);if(Xa.clear(),e?.hosts&&e.domains?.length){m("cleanup","Cleaning up hosts file entries",e?.verbose),m("cleanup",`Original domains for cleanup: ${JSON.stringify(e.domains)}`,e?.verbose);let i=e.domains.filter((n)=>{if(n==="test.local")return!0;return n!=="localhost"&&!n.startsWith("localhost.")&&n!=="127.0.0.1"});if(m("cleanup",`Filtered domains for cleanup: ${JSON.stringify(i)}`,e?.verbose),i.length>0)x.info("Cleaning up hosts file entries..."),t.push(qy(i,e?.verbose).then(()=>{m("cleanup",`Removed hosts entries for ${i.join(", ")}`,e?.verbose)}).catch((n)=>{m("cleanup",`Failed to remove hosts entries: ${n}`,e?.verbose),x.warn(`Failed to clean up hosts file entries for ${i.join(", ")}:`,n)}))}if(e?.certs&&e.domains?.length){m("cleanup","Cleaning up SSL certificates",e?.verbose),x.info("Cleaning up SSL certificates...");let i=e.domains.map(async(n)=>{try{await ly(n,e?.verbose),m("cleanup",`Removed certificates for ${n}`,e?.verbose)}catch(s){m("cleanup",`Failed to remove certificates for ${n}: ${s}`,e?.verbose),x.warn(`Failed to clean up certificates for ${n}:`,s)}});t.push(...i)}await Promise.allSettled(t),m("cleanup","All cleanup tasks completed successfully",e?.verbose),x.success("All cleanup tasks completed successfully")}catch(t){m("cleanup",`Error during cleanup: ${t}`,e?.verbose),x.error("Error during cleanup:",t)}finally{if(Ga)Ga();Ga=null,Vf=!1;let t=e&&"vitePluginUsage"in e&&e.vitePluginUsage===!0;if(Y.env.NODE_ENV!=="test"&&Y.env.BUN_ENV!=="test"&&!t)Y.exit(0)}return Yf}var zf=!1;function kw(e){if(zf){m("signal",`Received second ${e} signal, forcing exit`,!0),Y.exit(1);return}zf=!0,m("signal",`Received ${e} signal, initiating cleanup`,!0),ec().catch((t)=>{m("signal",`Cleanup failed after ${e}: ${t}`,!0),Y.exit(1)}).finally(()=>{zf=!1})}Y.once("SIGINT",()=>kw("SIGINT"));Y.once("SIGTERM",()=>kw("SIGTERM"));Y.on("uncaughtException",(e)=>{x.error("Uncaught exception (continuing):",e)});Y.on("unhandledRejection",(e)=>{x.error("Unhandled rejection (continuing):",e)});async function zn(e,t,r,i=5){m("connection",`Testing connection to ${e}:${t} (retries left: ${i})`,r);let n=15000,s=Date.now();if(Y.env.RPX_BYPASS_CONNECTION_TEST==="true"){m("connection",`Bypassing connection test for ${e}:${t} due to RPX_BYPASS_CONNECTION_TEST flag`,r);return}let o=()=>new Promise((c,a)=>{let l=Rw.connect({host:e,port:t,timeout:3000});l.once("connect",()=>{m("connection",`Successfully connected to ${e}:${t}`,r),l.end(),c()}),l.once("timeout",()=>{m("connection",`Connection to ${e}:${t} timed out`,r),l.destroy(),a(Error("Connection timed out"))}),l.once("error",(u)=>{m("connection",`Failed to connect to ${e}:${t}: ${u}`,r),l.destroy(),a(u)})});try{await o()}catch(c){let a=c;if(Date.now()-s>n){m("connection",`Connection test timed out after ${n}ms, but continuing anyway`,r),x.warn(`Connection test to ${e}:${t} timed out, but RPX will try to proceed anyway.`);return}if(a.code==="ECONNREFUSED"&&i>0)return m("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${i} retries left)`,r),await new Promise((u)=>setTimeout(u,2000)),zn(e,t,r,i-1);if(i>0)try{m("connection",`Trying HTTP request to ${e}:${t}`,r),await new Promise((u,f)=>{let h=Qa.request({hostname:e,port:t,path:"/",method:"HEAD",timeout:5000},(d)=>{m("connection",`Received HTTP response with status: ${d.statusCode}`,r),u()});h.on("error",(d)=>f(d)),h.on("timeout",()=>{h.destroy(),f(Error("HTTP request timed out"))}),h.end()}),m("connection",`HTTP request to ${e}:${t} succeeded`,r);return}catch(u){return m("connection",`HTTP request to ${e}:${t} failed: ${u}`,r),m("connection",`Retrying socket connection in 2 seconds... (${i} retries left)`,r),await new Promise((f)=>setTimeout(f,2000)),zn(e,t,r,i-1)}let l=`Failed to connect to ${e}:${t} after ${5-i} attempts: ${a.message}`;m("connection",`${l}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,r),x.warn(l),x.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 Ow(e){m("server",`Starting server with options: ${tr(e)}`,e.verbose);let t=Ir(e.from),r=new URL(t.startsWith("http")?t:`http://${t}`),i=new URL((e.to?.startsWith("http")?e.to:`http://${e.to}`)||"rpx.localhost"),n=Number.parseInt(r.port)||(r.protocol.includes("https:")?443:80),s=[i.hostname];if(Gf(e)&&!i.hostname.includes("localhost")&&!i.hostname.includes("127.0.0.1")){m("hosts",`Checking if hosts file entry exists for: ${i.hostname}`,e?.verbose);try{if(!(await _n(s,e.verbose))[0]){x.info(`Adding ${i.hostname} to hosts file...`),x.info("This may require sudo/administrator privileges");try{await In(s,e.verbose)}catch(a){if(x.error("Failed to add hosts entry:",a.message),x.warn("You can manually add this entry to your hosts file:"),x.warn(`127.0.0.1 ${i.hostname}`),x.warn(`::1 ${i.hostname}`),Y.platform==="win32")x.warn("On Windows:"),x.warn("1. Run notepad as administrator"),x.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else x.warn("On Unix systems:"),x.warn("sudo nano /etc/hosts")}}else m("hosts",`Host entry already exists for ${i.hostname}`,e.verbose)}catch(c){x.error("Failed to check hosts file:",c.message)}}try{await zn(r.hostname,n,e.verbose)}catch(c){m("server",`Connection test failed: ${c}`,e.verbose),x.error(c.message),x.warn("Continuing with proxy setup despite connection test failure..."),x.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let o=e._cachedSSLConfig||null;if(e.https)try{if(e.https===!0)e.https=$n({...e,to:i.hostname});if(o=await xr({...e,to:i.hostname,https:e.https}),!o){if(m("ssl",`Generating new certificates for ${i.hostname}`,e.verbose),await bn({...e,from:r.toString(),to:i.hostname,https:e.https}),o=await xr({...e,to:i.hostname,https:e.https}),!o)throw Error(`Failed to load SSL configuration after generating certificates for ${i.hostname}`)}}catch(c){throw m("server",`SSL setup failed: ${c}`,e.verbose),c}m("server",`Setting up reverse proxy with SSL config for ${i.hostname}`,e.verbose),await PR({...e,from:t,originalFrom:e.from||t,to:i.hostname,fromPort:n,sourceUrl:{hostname:r.hostname,host:r.host},ssl:o})}async function TR(e,t,r,i,n,s,o,c,a,l,u,f){m("proxy",`Creating proxy server ${e} -> ${t} with cleanUrls: ${c}`,o);let h=xn(u??i.host,f);Sn(h);let d=[{host:t,route:{sourceHost:i.host,upstreamPool:h,cleanUrls:c||!1,changeOrigin:a||!1,basePath:"/",auth:l}}];if(!Ja({routeEntries:d,listenPort:r,sslConfig:n,originGuard:null,verbose:o??!1}))throw Mi(h),Error(`Failed to start proxy server for ${t} on port ${r}`);Xa.add(h),AR({from:e,to:t,vitePluginUsage:s,listenPort:r,ssl:!!n,cleanUrls:c,verbose:o})}async function PR(e){m("setup",`Setting up reverse proxy: ${tr(e)}`,e.verbose);let{from:t,originalFrom:r,to:i,sourceUrl:n,ssl:s,verbose:o,cleanup:c,vitePluginUsage:a,changeOrigin:l,cleanUrls:u}=e,f=80,h=443,d=Bw(),y=e.portManager||ER,g=Gf(e);try{if(g&&i&&!i.includes("localhost")&&!i.includes("127.0.0.1")){if(!(await _n([i],o))[0]){x.warn(`The hostname ${i} isn't in your hosts file. Adding it now...`);try{await In([i],o),x.success(`Added ${i} to your hosts file.`)}catch(R){x.error(`Failed to add ${i} to your hosts file: ${R}`),x.info(`You may need to manually add '127.0.0.1 ${i}' to your /etc/hosts file.`)}}}else if(g&&Y.platform!=="darwin"&&i&&i.includes("localhost")&&!i.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await _n([i],o))[0]){m("hosts",`${i} not found in hosts file, adding...`,o);try{await In([i],o)}catch(R){m("hosts",`Failed to add ${i} to hosts file: ${R}`,o)}}}if(s&&!y.usedPorts.has(f)){if(!await Cr(f,d,o))m("setup","Starting HTTP redirect server",o),Nw(o),y.usedPorts.add(f);else if(m("setup","Port 80 is in use, skipping HTTP redirect",o),o)x.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let p=s?h:f,w=await Cr(p,d,o),b;if(w){if(m("setup",`Port ${p} is already in use`,o),o)x.warn(`Port ${p} is already in use. This may be another instance of rpx or another service.`);if(p===443){if(b=await y.getNextAvailablePort(3443,!0),m("setup",`Using port ${b} instead of ${p}`,o),o)x.info(`Using port ${b} instead. Access your site at https://${i}:${b}`)}else if(b=await y.getNextAvailablePort(p+1000,!0),m("setup",`Using port ${b} instead of ${p}`,o),o)x.info(`Using port ${b} instead. Access your site at http://${i}:${b}`)}else b=p,y.usedPorts.add(b),m("setup",`Using standard ${p===443?"HTTPS":"HTTP"} port ${p} for ${i}`,o);await TR(t,i,b,n,s,a,o,u,l,Tn(e.auth),r,e.loadBalancer)}catch(p){m("setup",`Setup failed: ${p}`,o),x.error(`Failed to setup reverse proxy: ${p.message}`),ec({domains:[i],hosts:typeof c==="boolean"?c:c?.hosts,certs:typeof c==="boolean"?c:c?.certs,verbose:o,vitePluginUsage:a})}}function Nw(e,t=80,r=443,i,n,s){m("redirect",`Starting HTTP redirect server on port ${t}`,e);let o=Qa.createServer((c,a)=>{let l=c.url?c.url.split("?",1)[0]:"";if(l.startsWith("/.well-known/acme-challenge/")){if(n){let d=n.challengeStore.handlePath(l);if(d!==void 0){m("redirect",`Serving on-demand ACME challenge ${l}`,e),a.writeHead(200,{"content-type":"text/plain"}),a.end(d);return}}if(i){let d=xa(i,l);if(d!=null){m("redirect",`Serving ACME challenge ${l}`,e),a.writeHead(200,{"content-type":"text/plain"}),a.end(d);return}}if(n){a.writeHead(404,{"content-type":"text/plain"}),a.end("challenge not found");return}}let u=c.headers.host||"",f=u.includes(":")?u.slice(0,u.indexOf(":")):u;if(n&&f&&!n.hasCert(f)&&(!s||s(f)))n.ensureCert(f).catch(()=>{});let h=r===443?f:`${f}:${r}`;m("redirect",`Redirecting request from ${u}${c.url} to https://${h}`,e),a.writeHead(301,{Location:`https://${h}${c.url}`}),a.end()}).listen(t);Yn.add(o),m("redirect","HTTP redirect server started",e)}function Dw(e){let t={...jt,...e};if(m("proxy",`Starting proxy with options: ${tr(t)}`,t?.verbose),t.viaDaemon){if(!t.from||!t.to){x.error("viaDaemon mode requires both `from` and `to`");return}Hf({proxies:[{id:t.id,from:t.from,to:t.to,path:t.path,cleanUrls:t.cleanUrls,changeOrigin:t.changeOrigin,pathRewrites:t.pathRewrites}],verbose:t.verbose}).catch((a)=>{x.error(`Failed to register with rpx daemon: ${a.message}`),Y.exit(1)});return}let r=t.to||"",i=r.split(".").pop()?.toLowerCase()||"",n=Y.platform==="darwin"&&r&&!r.includes("localhost")&&!r.includes("127.0.0.1"),s=["dev","app","page","new","day","foo"],o=["test","localhost","local","example","invalid"];if(n&&s.includes(i)&&t?.verbose)x.warn(`The .${i} TLD may not work reliably for local development`),x.info(` Google owns .${i} with HSTS preloading, which can bypass local DNS`),x.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(n)Promise.resolve().then(() => (Kn(),La)).then(({setupDevelopmentDns:a})=>{a({domains:[r],verbose:t.verbose}).then((l)=>{if(l)Promise.resolve().then(()=>{if(t.verbose)if(o.includes(i))x.success(`DNS server started for .${i} domains`);else x.success(`DNS server started for .${i} domains (hosts file entry also added)`)});else m("dns",`Could not start DNS server - ${r} may not resolve in browser`,t.verbose)})}).catch((a)=>{m("dns",`Failed to start DNS server: ${a}`,t.verbose)});let c={from:t.from,to:t.to,cleanUrls:t.cleanUrls,https:$n(t),cleanup:t.cleanup,vitePluginUsage:t.vitePluginUsage,changeOrigin:t.changeOrigin,verbose:t.verbose,regenerateUntrustedCerts:t.regenerateUntrustedCerts};m("proxy",`Server options: ${tr(c)}`,t.verbose),Ow(c).catch((a)=>{m("proxy",`Failed to start proxy: ${a}`,t.verbose),x.error(`Failed to start proxy: ${a.message}`),ec({domains:[t.to],hosts:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.hosts,certs:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.certs,verbose:t.verbose})})}function RR(e){return e?.verbose||!1}function Gf(e){if(e?.hostsManagement===!1)return!1;let t=e?.cleanup;if(t===!1)return!1;if(t&&typeof t==="object"&&t.hosts===!1)return!1;return!0}async function Fw(e){let t={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(e)t={...t,...e};let r=RR(t),i=Gf(t);if(m("config",`Starting with config: ${tr(t,2)}`,r),m("config",`Is multi-proxy? ${"proxies"in t}`,r),m("config",`Hosts management enabled? ${i}`,r),t.viaDaemon){let T="proxies"in t&&Array.isArray(t.proxies)?t.proxies.map((S)=>({id:S.id,from:S.from,to:S.to,path:S.path,cleanUrls:S.cleanUrls??t.cleanUrls,changeOrigin:S.changeOrigin??t.changeOrigin,pathRewrites:S.pathRewrites})):[{id:t.id,from:t.from,to:t.to??"rpx.localhost",path:t.path,cleanUrls:t.cleanUrls,changeOrigin:t.changeOrigin,pathRewrites:t.pathRewrites}];await Hf({proxies:T,verbose:r});return}if("proxies"in t&&Array.isArray(t.proxies)){m("servers",`Found ${t.proxies.length} proxies in config`,r);for(let v of t.proxies)if(v.start){let T=`${v.from}-${v.to}`;try{m("watch",`Starting command for ${T} with command: ${v.start.command}`,r),x.info(`Starting command for ${T}...`),await qa.startProcess(T,v.start,r);let S=Ir(v.from),D=new URL(S.startsWith("http")?S:`http://${S}`),W=D.hostname||"localhost",Xe=Number(D.port)||80;try{await zn(W,Xe,r),m("watch",`Dev server is ready at ${W}:${Xe}`,r)}catch(at){m("watch",`Connection check failed, but continuing with proxy setup: ${at}`,r),x.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(S){throw m("watch",`Failed to start command for ${T}: ${S}`,r),Error(`Failed to start command for ${T}: ${S}`)}}else m("watch",`No start command for proxy ${v.from} -> ${v.to}`,r)}else if("start"in t&&t.start){m("watch","Found start command in single proxy config",r);let v=`${t.from}-${t.to}`;try{if(t.start)m("watch",`Starting command: ${t.start.command}`,r),await qa.startProcess(v,t.start,r);let T=Ir(t.from),S=new URL(T.startsWith("http")?T:`http://${T}`),D=S.hostname||"localhost",W=Number(S.port)||80;try{await zn(D,W,r),m("watch",`Dev server is ready at ${D}:${W}`,r)}catch(Xe){m("watch",`Connection check failed, but continuing with proxy setup: ${Xe}`,r),x.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(T){throw m("watch",`Failed to run start command: ${T}`,r),Error(`Failed to run start command: ${T}`)}}else m("watch","No start command found in config",r);let n="proxies"in t&&Array.isArray(t.proxies)?t.proxies[0]?.to:("to"in t)?t.to:"rpx.localhost";if(Y.platform!=="win32"&&(t.https||i)){if(!pr())try{m("sudo","Pre-acquiring sudo credentials for privileged operations",r),SR("sudo -v",{stdio:"inherit"})}catch{m("sudo","Could not pre-acquire sudo credentials",r)}}let s=[];if(t.productionCerts){if(s=await Dn(t.productionCerts,r),s.length>0)m("ssl",`Using ${s.length} production SNI cert(s): ${s.map((v)=>v.serverName).join(", ")}`,r)}if(t.https){let v=s.length>0?null:await xr(t);if(!v&&s.length===0){if(m("ssl",`No valid or trusted certificates found for ${n}, generating new ones`,t.verbose),await bn(t),v=await xr(t),!v)throw Error(`Failed to load SSL certificates after generation for ${n}`)}else m("ssl",`Using existing and trusted certificates for ${n}`,t.verbose);t._cachedSSLConfig=v}let o="proxies"in t&&Array.isArray(t.proxies)?t.proxies.map((v)=>({...v,https:t.https,cleanup:t.cleanup,cleanUrls:v.cleanUrls??("cleanUrls"in t?t.cleanUrls:!1),vitePluginUsage:t.vitePluginUsage,changeOrigin:v.changeOrigin??t.changeOrigin,verbose:r,_cachedSSLConfig:t._cachedSSLConfig})):[{from:"from"in t?t.from:"localhost:5173",to:"to"in t?t.to:"rpx.localhost",cleanUrls:"cleanUrls"in t?t.cleanUrls:!1,https:t.https,cleanup:t.cleanup,vitePluginUsage:t.vitePluginUsage,start:"start"in t?t.start:void 0,changeOrigin:t.changeOrigin,auth:"auth"in t?t.auth:void 0,verbose:r,_cachedSSLConfig:t._cachedSSLConfig}],c=o.map((v)=>v.to||"rpx.localhost"),a=s.length>0?s:t._cachedSSLConfig??null,l=c.filter((v)=>v&&!v.includes("localhost")&&!v.includes("127.0.0.1")),u=["dev","app","page","new","day","foo"],f=["test","localhost","local","example","invalid"],h=[...new Set(l.map((v)=>v.split(".").pop()?.toLowerCase()))],d=h.filter((v)=>!!v&&u.includes(v));if(d.length>0&&r)x.warn(`The following TLDs may not work reliably for local development: ${d.map((v)=>`.${v}`).join(", ")}`),x.info(" These TLDs have HSTS preloading which can bypass local DNS"),x.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(i&&Y.platform==="darwin"&&l.length>0){let{setupDevelopmentDns:v}=await Promise.resolve().then(() => (Kn(),La));if(await v({domains:l,verbose:r})){if(r)if(h.every((D)=>!!D&&f.includes(D)))x.success(`DNS server started for ${h.map((D)=>`.${D}`).join(", ")} domains`);else x.success(`DNS server started for ${h.map((D)=>`.${D}`).join(", ")} domains (hosts file entries also added)`)}else m("dns","Could not start DNS server - custom domains may not resolve",r)}let y=async()=>{m("cleanup","Starting cleanup handler",t.verbose);try{let{tearDownDevelopmentDns:v}=await Promise.resolve().then(() => (Kn(),La));await v({verbose:t.verbose})}catch(v){m("cleanup",`Error stopping DNS server: ${v}`,t.verbose)}try{await qa.stopAll(t.verbose)}catch(v){m("cleanup",`Error stopping processes: ${v}`,t.verbose)}await ec({domains:c,hosts:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.hosts,certs:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.certs,verbose:t.verbose||!1})};Y.on("SIGINT",y),Y.on("SIGTERM",y);let g=t.singlePortMode===!0,p=t.httpsPort??443,w=t.httpPort??80,b=t.originGuard?Ew(t.originGuard):null,P=!!a&&(o.length>1||g||s.length>0),R=!a&&g&&o.length>0;if(P&&a){m("proxies",`Creating shared HTTPS server for ${o.length} domains on port ${p}`,r);let v=await Pw(o,i,r),T=null,S=t.onDemandTls,D=S?.enabled?new Ii({config:S,certsDir:S.certsDir??t.productionCerts?.certsDir??Aw.join(Za.homedir(),".stacks","rpx","on-demand-certs"),initial:s,verbose:r,onCertAdded:(Ie)=>{if(Fn()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",r),setTimeout(()=>Y.kill(Y.pid,"SIGTERM"),10).unref();else at(Ie)}}):null,W=null,Xe=!1;async function at(Ie){if(W=Ie,Xe)return;Xe=!0;try{while(W){let ct=W;if(W=null,m("proxies",`rebuilding :${p} with ${ct.length} SNI cert(s)`,r),T)Yn.delete(T),T.stop(!1);let Ue=!1;for(let O=0;!Ue&&O<60;O++){let We=Ja({routeEntries:v,listenPort:p,sslConfig:ct,originGuard:b,verbose:r});if(We){T=We,Ue=!0;break}await new Promise((Vi)=>setTimeout(Vi,Math.min(25*2**Math.min(O,4),500)))}if(!Ue)x.error(`rpx: CRITICAL — could not rebind :${p} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{Xe=!1}}if(!await Cr(w,"0.0.0.0",r)){let Ie=new Set(v.map((Ue)=>Ue.host)),ct=(Ue)=>Ie.has(Ue)||[...Ie].some((O)=>Or(Ue,O));Nw(r,w,p,t.acmeChallengeWebroot,D,ct)}if(await Cr(p,"0.0.0.0",r)){if(m("proxies",`Port ${p} is already in use, cannot start shared proxy`,r),r)x.warn(`Port ${p} is in use. Shared HTTPS proxy cannot start.`);return}let sr=D&&D.sniEntries().length>0?D.sniEntries():a;if(T=Ja({routeEntries:v,listenPort:p,sslConfig:sr,originGuard:b,verbose:r}),!T){x.error(`Shared HTTPS proxy failed to bind :${p}; not exiting`);return}}else if(R){m("proxies",`Creating shared HTTP server for ${o.length} domains on port ${w}`,r);let v=await Pw(o,i,r);if(await Cr(w,"0.0.0.0",r)){if(m("proxies",`Port ${w} is already in use, cannot start shared proxy`,r),r)x.warn(`Port ${w} is in use. Shared HTTP proxy cannot start.`);return}if(!Ja({routeEntries:v,listenPort:w,sslConfig:null,originGuard:b,verbose:r})){x.error(`Shared HTTP proxy failed to bind :${w}; not exiting`);return}}else for(let v of o)try{let T=v.to||"rpx.localhost";m("proxy",`Starting proxy for ${T} with SSL config: ${!!a}`,v.verbose),await Ow({from:v.from||"localhost:5173",to:T,cleanUrls:v.cleanUrls||!1,https:v.https||!1,cleanup:v.cleanup||!1,vitePluginUsage:v.vitePluginUsage||!1,verbose:v.verbose||!1,_cachedSSLConfig:t._cachedSSLConfig,changeOrigin:v.changeOrigin||!1,loadBalancer:v.loadBalancer,auth:v.auth,path:v.path,pathRewrites:v.pathRewrites})}catch(T){m("proxies",`Failed to start proxy for ${v.to}: ${T}`,v.verbose),x.error(`Failed to start proxy for ${v.to}:`,T)}}async function Pw(e,t,r){let i=[],n=new Set;for(let s of e){let o=s.to||"rpx.localhost",c=s.cleanUrls||!1,a=s.path,l=rr(a),u=Tn(s.auth);if(s.redirect){let f=Ey(s.redirect);i.push({host:o,path:a,route:{redirect:f,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → redirect ${f.status} ${f.to}${u?" (auth)":""}`,r)}else if(s.static)i.push({host:o,path:a,route:{static:ba(s.static,c),cleanUrls:c,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → static ${typeof s.static==="string"?s.static:s.static.dir}${u?" (auth)":""}`,r);else{let f=Ir(s.from),h=new URL(f.startsWith("http")?f:`http://${f}`),d=xn(s.from??h.host,s.loadBalancer);Sn(d),Xa.add(d),i.push({host:o,path:a,route:{sourceHost:h.host,upstreamPool:d,cleanUrls:c,changeOrigin:s.changeOrigin||!1,pathRewrites:s.pathRewrites,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → ${h.host}${u?" (auth)":""}`,r)}if(n.has(o))continue;if(n.add(o),t&&!ai(o)&&!o.includes("localhost")&&!o.includes("127.0.0.1"))try{if(!(await _n([o],r))[0])await In([o],r)}catch{m("hosts",`Could not add hosts entry for ${o}`,r)}}return i}var Vn=null;function Bw(){if(Y.env.RPX_BIND_HOSTNAME)return Y.env.RPX_BIND_HOSTNAME;if(Vn)return Vn;try{Vn=Object.values(Za.networkInterfaces()).flat().some((r)=>r&&r.family==="IPv6")?"::":"0.0.0.0"}catch{Vn="0.0.0.0"}return Vn}function Ja(e){let{routeEntries:t,listenPort:r,sslConfig:i,originGuard:n,verbose:s}=e,o=kn(t),c=Rn((u,f)=>On(o,u,f),s),a=n?(u,f)=>n(u)??c(u,f):c,l=An(s);try{let u=Bun.serve({port:r,hostname:Bw(),reusePort:wn(),...i?{tls:jr(Array.isArray(i)?i.map((f)=>({serverName:f.serverName,key:f.key,cert:f.cert})):{key:i.key,cert:i.cert,ca:i.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(f,h){return a(f,h)},websocket:l,error(f){return m("server",`Shared proxy server error: ${f}`,s),new Response(`Server Error: ${f.message}`,{status:500})}});return Yn.add(u),m("proxies",`Shared ${i?"HTTPS":"HTTP"} proxy listening on port ${r} for ${o.size} domains`,s),u}catch(u){return m("proxies",`Failed to start shared proxy: ${u}`,s),console.error("Failed to start shared proxy:",u),null}}function AR(e){if(e?.vitePluginUsage||!e?.verbose)return;if(console.log(""),console.log(` ${Nt.green(Nt.bold("rpx"))} ${Nt.green(`v${Hn}`)}`),console.log(` ${Nt.green("➜")} ${Nt.dim(e?.from??"")} ${Nt.dim("➜")} ${Nt.cyan(e?.ssl?`https://${e?.to}`:`http://${e?.to}`)}`),e?.listenPort!==(e?.ssl?443:80))console.log(` ${Nt.green("➜")} Listening on port ${e?.listenPort}`);if(e?.cleanUrls)console.log(` ${Nt.green("➜")} Clean URLs enabled`)}he();Me.chdir(OR(kR(NR(import.meta.url)),".."));var je=new fc("rpx");je.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async(e)=>{if(!e?.from||!e.to)return Fw(jt);let t={from:e.from,to:e.to,https:{keyPath:e.keyPath,certPath:e.certPath,caCertPath:e.caCertPath},cleanup:{certs:e.certsCleanup||!1,hosts:e.hostsCleanup||!1},verbose:e.verbose||!1,changeOrigin:e.changeOrigin||!1,singlePortMode:e.singlePortMode||!1,httpPort:e.httpPort!==void 0?Number(e.httpPort):void 0,httpsPort:e.httpsPort!==void 0?Number(e.httpsPort):void 0,viaDaemon:e.viaDaemon||!1,id:e.id};if(e.startCommand){let r={command:e.startCommand};if(e.startCwd)r.cwd=e.startCwd;if(e.startEnv)try{r.env=JSON.parse(e.startEnv)}catch(i){console.error("Failed to parse start-env JSON:",i),Me.exit(1)}t.start=r}return Dw(t)});je.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{let r=ha(jt)?jt.proxies.find((i)=>i.to===e||`${i.from}-${i.to}`===e):jt.to===e?jt:null;if(!r?.start)console.error(`No watch configuration found for proxy: ${e}`),Me.exit(1);try{await Va.startProcess(e,r.start,t.verbose),console.log(`Started dev server for ${e}`)}catch(i){console.error(`Failed to start dev server for ${e}:`,i),Me.exit(1)}});je.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{try{await Va.stopProcess(e,t.verbose),console.log(`Stopped dev server for ${e}`)}catch(r){console.error(`Failed to stop dev server for ${e}:`,r),Me.exit(1)}});je.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(e)=>{try{await Va.stopAll(e.verbose),console.log("Stopped all dev servers")}catch(t){console.error("Failed to stop all dev servers:",t),Me.exit(1)}});async function Lw(e){let r={...(await Ld().catch(()=>null))?.onDemand??{},enabled:!0};if(e){let i=e.split(",").map((n)=>n.trim()).filter(Boolean);if(i.length>0)r.roots=i}return r}je.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(e)=>{try{let t=e.onDemand?await Lw(e.roots):void 0;await(await bw({rpxDir:e.rpxDir,registryDir:e.registryDir,httpsPort:typeof e.httpsPort==="string"?Number.parseInt(e.httpsPort,10):e.httpsPort,httpPort:typeof e.httpPort==="string"?Number.parseInt(e.httpPort,10):e.httpPort,hostname:e.hostname,productionCerts:e.certsDir?{certsDir:e.certsDir}:void 0,workers:e.workers===void 0?void 0:typeof e.workers==="string"?Number.parseInt(e.workers,10):e.workers,onDemandSites:t,verbose:e.verbose??!0})).done,Me.exit(0)}catch(t){console.error(`Failed to start rpx daemon: ${t.message}`),Me.exit(1)}});je.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async(e)=>{let t=typeof e.timeout==="string"?Number.parseInt(e.timeout,10):e.timeout,r=await $w({rpxDir:e.rpxDir,timeoutMs:t,forceAfterTimeout:e.force!==!1,verbose:e.verbose});if(!r.stopped&&r.pid===null){console.log("rpx daemon is not running");return}if(!r.stopped){console.log(`rpx daemon pid=${r.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${r.pid} stopped${r.forced?" (SIGKILL)":""}`)});je.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async(e)=>{let t=e.rpxDir??Pe(),r=await Tr(t),i=await Ua(t),n=e.registryDir,s=await wt(n).catch(()=>[]);if(e.json){console.log(JSON.stringify({running:i,pid:r,pidFile:Pr(t),rpxDir:t,registryDir:n??st(),entries:s},null,2));return}if(!i){if(console.log("rpx daemon: not running"),r!==null)console.log(`(stale pid file at ${Pr(t)} → pid ${r})`)}else console.log(`rpx daemon: running (pid=${r})`),console.log(`pid file: ${Pr(t)}`);if(console.log(`registry: ${n??st()}`),s.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${s.length}):`);for(let o of s){let c=o.pid!==void 0?`, pid=${o.pid}`:"";console.log(` https://${o.to} → ${o.from} (id=${o.id}${c})`)}});je.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async(e)=>{if(!e.id||!e.from||!e.to)console.error("rpx register requires --id, --from, and --to"),Me.exit(1);if(!Sr(e.id))console.error(`invalid id: ${JSON.stringify(e.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),Me.exit(1);try{await _i({id:e.id,from:e.from,to:e.to,cwd:e.cwd,createdAt:new Date().toISOString(),cleanUrls:e.cleanUrls,changeOrigin:e.changeOrigin},e.registryDir,e.verbose)}catch(t){console.error(`failed to write registry entry: ${t.message}`),Me.exit(1)}if(e.skipSpawn){console.log(`registered ${e.to} → ${e.from} (daemon spawn skipped)`);return}try{let t=await Wa({rpxDir:e.rpxDir,verbose:e.verbose}),r=t.spawned?"spawned":"attached to";console.log(`registered https://${e.to} → ${e.from} (${r} daemon pid=${t.pid})`)}catch(t){console.error(`registered entry but daemon spawn failed: ${t.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),Me.exit(1)}});je.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async(e,t)=>{if(!Sr(e))console.error(`invalid id: ${JSON.stringify(e)}`),Me.exit(1);let r=await Ef(e,t.registryDir,t.verbose);if(!r){console.log(`no registry entry for id=${e}`);return}await Ur(e,t.registryDir,t.verbose),console.log(`unregistered ${r.to} (id=${e})`)});je.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async(e)=>{let t=e.rpxDir??Pe();if(await Ua(t)){console.log("rpx daemon is running — DNS overrides are managed by the daemon");return}await xw({rpxDir:t,verbose:e.verbose}),console.log("DNS reconcile complete")});je.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(e)=>{let t=await Lw(e.roots),r=Wd(t),i=await wt(e.registryDir).catch(()=>[]),n=new Set(i.map((c)=>c.to)),s=r.map((c)=>({host:c.host,dir:c.dir,command:c.command,source:c.source,live:n.has(c.host)}));if(e.json){console.log(JSON.stringify(s,null,2));return}let o=t.roots??["~/Code"];if(s.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${o.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${s.length}) — scanned ${o.join(", ")}:`);for(let c of s)console.log(` ${c.live?"●":"○"} https://${c.host} ${c.live?"(live)":"(idle)"}`),console.log(` ${c.command} ${c.dir}`)});je.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(e,t)=>{let{readFile:r}=await import("node:fs/promises"),{join:i}=await import("node:path"),n=t.rpxDir??Pe(),s=i(n,"sites",`${Ms(e.split(":")[0])}.log`),o;try{o=await r(s,"utf8")}catch{console.log(`no log for ${e} (it may not have been booted yet) — looked in ${s}`);return}let c=t.lines===void 0?void 0:typeof t.lines==="string"?Number.parseInt(t.lines,10):t.lines,a=o.split(`
|
|
329
|
-
`);
|
|
330
|
-
`))});
|
|
383
|
+
`)),this.enableDidYouMean){let t=[];for(let n of this.commands){if(n.displayName)t.push(n.displayName);if(n.aliasNames)t.push(...n.aliasNames)}let r=Ld(e,t);if(r.length>0)console.log(gi.yellow("Did you mean one of these?")),r.forEach((n)=>console.log(` ${gi.dim("•")} ${this.name} ${n}`)),console.log("")}console.log(gi.dim("Run"),`${this.name} --help`,gi.dim("to see all available commands")),pr.exit(1)}async parse(e=Od,t={}){let{run:r=!0,exitOnError:n=!1}=t;if(n)try{return await this.parse(e,{run:r})}catch(a){throw this.handleUsageError(a),a}if(this.rawArgs=e,!this.name)this.name=e[1]?Bb(e[1]):"cli";let i=!0,s=e.slice(2),o=s[0];if(o&&!o.startsWith("-")){for(let a of this.commands)if(a.isMatched(o)){let l=this.mri(s,a);i=!1;let u={...l,args:l.args.slice(1)};this.setParsedInfo(u,a,o),this.emit(`command:${o}`,a);break}}if(i){for(let a of this.commands)if(a.name===""){i=!1;let l=this.mri(s,a);this.setParsedInfo(l,a),this.emit("command:!",a);break}}if(i){let a=this.mri(e.slice(2));this.setParsedInfo(a)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),r=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),r=!1,this.unsetMatchedCommand();let c={args:this.args,options:this.options};if(r)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return c}mri(e,t){let r=[...this.globalCommand.options,...t?t.options:[]],n=Nb(r),i=[],s=e.indexOf("--");if(s>-1)i=e.slice(s+1),e=e.slice(0,s);let o=kb(e,n),c={_:o._};for(let h of Object.keys(o))if(h!=="_")c[Fd(h)]=o[h];let a=c._,l={"--":i},u=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,f=Object.create(null);for(let h of r){if(!u&&h.config.default!==void 0)for(let d of h.names)l[d]=h.config.default;if(Array.isArray(h.config.type)){if(f[h.name]===void 0)f[h.name]={shouldTransform:!0,transformFunction:h.config.type[0]}}}for(let h of Object.keys(c))if(h!=="_"){let d=h.split(".");Fb(l,d,c[h]),Lb(l,f)}return{args:a,options:l}}async run(e=Od){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!(!!e&&typeof e==="object"&&e.name==="ClappError"&&e.isUsageError!==!1))return;let n=e,i=n.message??"command-line error",s=this.name?`${this.name}: `:"",o=/--help/.test(i)?"":`
|
|
384
|
+
Run \`${this.name??"cli"} --help\` for usage.`;pr.stderr.write(`${s}${i}${o}
|
|
385
|
+
`),pr.exit(n.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:r}=this;if(!r||!r.commandAction)return;r.checkUnknownOptions(),r.checkOptionValue(),r.checkRequiredArgs();let n=[];r.args.forEach((c,a)=>{if(c.variadic)n.push(e.slice(a));else n.push(e[a])}),n.push(t);let i={command:r,args:n,options:t};for(let c of r.beforeHooks)await c(i);let s,o=async()=>{let c=r.commandAction.apply(this,n);if(c instanceof Promise)s=await c;else s=c;return s};if(r.middleware.length>0){let c=0,a=async()=>{if(c<r.middleware.length){let l=r.middleware[c++];await l({...i,next:a})}else await o()};await a()}else await o();for(let c of r.afterHooks)await c(i);return s}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return pr.removeAllListeners("SIGINT"),pr.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class Id{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,r=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:r})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let e=Date.now();for(let[t,r]of this.cache.entries())if(e-r.timestamp>r.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var n1=new Id;function Vb(){if("FORCE_COLOR"in pi.env)return pi.env.FORCE_COLOR!=="0";if("NO_COLOR"in pi.env||pi.env.TERM==="dumb")return!1;if(pi.platform==="win32")return!0;return Nd.isatty(1)&&Nd.isatty(2)}var Md=Vb();function ue(e,t){if(!Md)return(r)=>r;return(r)=>e+r+t}var Hb=ue("\x1B[0m","\x1B[0m"),zb=ue("\x1B[31m","\x1B[39m"),Gb=ue("\x1B[32m","\x1B[39m"),qb=ue("\x1B[33m","\x1B[39m"),Yb=ue("\x1B[34m","\x1B[39m"),Jb=ue("\x1B[35m","\x1B[39m"),Xb=ue("\x1B[36m","\x1B[39m"),Zb=ue("\x1B[37m","\x1B[39m"),Qb=ue("\x1B[90m","\x1B[39m"),e$=ue("\x1B[1m","\x1B[22m"),t$=ue("\x1B[3m","\x1B[23m"),r$=ue("\x1B[4m","\x1B[24m"),n$=ue("\x1B[2m","\x1B[22m"),i$=ue("\x1B[7m","\x1B[27m"),s$=ue("\x1B[8m","\x1B[28m"),o$=ue("\x1B[9m","\x1B[29m"),a$=ue("\x1B[41m","\x1B[49m"),c$=ue("\x1B[42m","\x1B[49m"),l$=ue("\x1B[43m","\x1B[49m"),u$=ue("\x1B[44m","\x1B[49m"),f$=ue("\x1B[45m","\x1B[49m"),h$=ue("\x1B[46m","\x1B[49m"),d$=ue("\x1B[47m","\x1B[49m"),m$=Md,g$={reset:Hb,red:zb,green:Gb,yellow:qb,blue:Yb,magenta:Jb,cyan:Xb,white:Zb,gray:Qb,bold:e$,italic:t$,underline:r$,dim:n$,inverse:i$,hidden:s$,strikethrough:o$,bgRed:a$,bgGreen:c$,bgYellow:l$,bgBlue:u$,bgMagenta:f$,bgCyan:h$,bgWhite:d$,isColorSupported:m$},p$=g$,w$=["up","down","left","right","space","enter","cancel"],l1={actions:new Set(w$),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var u1=y$.platform.startsWith("win"),f1=Symbol("clapp:cancel");var v$=Ib();var oe=(e,t)=>v$?e:t,h1=oe("◆","*"),d1=oe("■","x"),m1=oe("▲","x"),g1=oe("◇","o"),p1=oe("┌","T"),b$=oe("│","|"),y1=oe("└","—"),w1=oe("●",">"),v1=oe("○"," "),b1=oe("◻","[•]"),$1=oe("◼","[+]"),C1=oe("◻","[ ]"),x1=oe("▪","•"),S1=oe("─","-"),E1=oe("╮","+"),T1=oe("├","+"),P1=oe("╯","+"),A1=oe("●","•"),R1=oe("◆","*"),k1=oe("▲","!"),O1=oe("■","x");var N1={light:oe("─","-"),heavy:oe("━","="),block:oe("█","#")};function $$(){return`${p$.gray(b$)} `}var D1=$$();Co();ou();Bc();qt();fe();import{spawn as vk}from"node:child_process";import*as Kc from"node:process";class Wc{processes=new Map;isShuttingDown=!1;async startProcess(e,t,r){if(this.processes.has(e)){m("start",`Process ${e} is already running`,r);return}let[n,...i]=t.command.split(" "),s=t.cwd||Kc.cwd();m("start",`Starting process ${e}:`,r),m("start",` Command: ${n} ${i.join(" ")}`,r),m("start",` Working directory: ${s}`,r),m("start",` Environment variables: ${ur(t.env)}`,r);let o=vk(n,i,{cwd:s,env:{...Kc.env,...t.env},shell:!0,stdio:"inherit"});return this.processes.set(e,{command:t.command,cwd:s,process:o,env:t.env}),new Promise((c,a)=>{if(o.on("error",(l)=>{if(!this.isShuttingDown)m("start",`Process ${e} failed to start: ${l}`,r),this.processes.delete(e),a(l)}),o.on("exit",(l)=>{if(!this.isShuttingDown&&l!==null&&l!==0)m("start",`Process ${e} exited with code ${l}; leaving the proxy running`,r),this.processes.delete(e),a(Error(`Process ${e} exited with code ${l}`))}),r)o.stdout?.on("data",(l)=>{m("process",`[${e}] ${l.toString().trim()}`,!0)}),o.stderr?.on("data",(l)=>{m("process",`[${e}] ERR: ${l.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&o.killed)this.processes.delete(e),a(Error(`Process ${e} was killed during startup`));else m("start",`Process ${e} started successfully`,r),c()},1000)})}async stopProcess(e,t){let r=this.processes.get(e);if(!r?.process){m("start",`No process found for ${e}`,t);return}return m("start",`Stopping process ${e}`,t),new Promise((n)=>{if(!r.process){n();return}r.process.once("exit",()=>{this.processes.delete(e),m("start",`Process ${e} stopped`,t),n()});try{r.process.kill("SIGTERM"),setTimeout(()=>{if(r.process){m("start",`Force killing process ${e}`,t);try{r.process.kill("SIGKILL")}catch(i){}}},3000)}catch(i){m("start",`Error stopping process ${e}: ${i}`,t),this.processes.delete(e),n()}})}async stopAll(e){if(this.isShuttingDown){m("start","Already shutting down, skipping duplicate stopAll call",e);return}this.isShuttingDown=!0,m("start","Stopping all processes",e);let t=Array.from(this.processes.keys()).map((r)=>this.stopProcess(r,e).catch((n)=>{b.error(`Failed to stop process ${r}:`,n)}));await Promise.allSettled(t),this.processes.clear(),this.isShuttingDown=!1}isRunning(e){let t=this.processes.get(e);return!!t?.process&&!t.process.killed}}var Vc=new Wc;Xr();import{readdir as Nk,readFile as Dk}from"node:fs/promises";import*as gb from"node:path";import*as pb from"node:process";qt();import{execSync as Tk}from"node:child_process";import*as Xc from"node:http";import*as cb from"node:net";import*as Zc from"node:os";import*as lb from"node:path";import*as q from"node:process";var Hc=(e,t)=>(r)=>`\x1B[${e}m${r}\x1B[${t}m`,Mt={bold:Hc(1,22),dim:Hc(2,22),green:Hc(32,39),cyan:Hc(36,39)};Co();Bc();qt();Xr();fe();import*as nb from"node:fs";import*as ib from"node:path";import*as _t from"node:process";function bk(e,t){let n=(t&&t!=="/"?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}async function yd(e){if(e.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let t=e.verbose??!1,r=e.registryDir,n=new Set,i=e.proxies.map((h)=>{let d=h.id??bk(h.to,h.path);if(!Dr(d))throw Error(`invalid registry id "${d}" derived from to="${h.to}"`);if(n.has(d))throw Error(`duplicate registry id "${d}" — set an explicit \`id\` on one of the proxies`);return n.add(d),{...h,id:d}}),s=new Date().toISOString();for(let h of i)await ai({id:h.id,from:h.from,to:h.to,path:h.path,pid:e.persistent?void 0:_t.pid,cwd:_t.cwd(),createdAt:s,cleanUrls:h.cleanUrls,changeOrigin:h.changeOrigin,pathRewrites:h.pathRewrites,static:h.static,loadBalancer:h.loadBalancer},r,t);let o=await Uc({rpxDir:e.rpxDir,verbose:t,spawnCommand:e.spawnCommand,startupTimeoutMs:e.startupTimeoutMs,spawnEnv:e.spawnEnv});for(let h of i){let d=h.static?`static ${typeof h.static==="string"?h.static:h.static.dir}`:h.from;b.success(`https://${h.to} → ${d}`)}if(b.info(`(via rpx daemon pid=${o.pid}; \`rpx daemon:status\` to inspect)`),e.detached)return;let c=!1,a=r??dt(),l=i.map((h)=>h.id),u=async()=>{if(c)return;c=!0;for(let h of l)await Jr(h,r,t).catch((d)=>{m("runner",`removeEntry(${h}) failed: ${d}`,t)})},f=(h)=>{m("runner",`received ${h}, unregistering ${l.length} entries`,t),u().finally(()=>_t.exit(0))};_t.once("SIGINT",f),_t.once("SIGTERM",f),_t.once("exit",()=>{if(c)return;for(let h of l)try{nb.unlinkSync(ib.join(a,`${h}.json`))}catch{}}),await new Promise(()=>{})}id();hc();Yh();import{timingSafeEqual as $k}from"node:crypto";function Ck(e,t){if(e==null)return!1;let r=Buffer.from(e),n=Buffer.from(t);if(r.length!==n.length)return!1;return $k(r,n)}function zc(e){return e.toLowerCase().replace(/\.$/,"")}var xk=["/.well-known/acme-challenge/"];function Sk(e){let t=e.headers.get("host");if(t)return zc(t.split(":")[0]);try{return zc(new URL(e.url).hostname)}catch{return""}}function sb(e){let t=e.header.toLowerCase(),r=new Set,n=[];for(let a of e.hosts){let l=zc(a);if(l.startsWith("*."))n.push(l);else r.add(l)}let i=e.exemptPaths??xk,s=e.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
386
|
+
`,o=(a)=>{let l=zc(a);return r.has(l)||n.some((u)=>Ur(l,u))},c=(a)=>{let l=Sk(a);if(!o(l))return;let u="/";try{u=new URL(a.url).pathname}catch{}if(i.some((f)=>u.startsWith(f)))return;if(Ck(a.headers.get(t),e.value))return;return new Response(s,{status:403,headers:{"content-type":"text/plain"}})};return c.protects=o,c}_h();jh();mc();bc();Wh();Gh();xc();wc();fe();var ob={name:"@stacksjs/rpx",type:"module",version:"0.11.48",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build --production ./bin/cli.ts --compile --outfile bin/rpx",compile:"bun build --production ./bin/cli.ts --compile --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build --production ./bin/cli.ts --compile --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build --production ./bin/cli.ts --compile --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build --production ./bin/cli.ts --compile --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build --production ./bin/cli.ts --compile --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build --production ./bin/cli.ts --compile --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.19"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var Rs=ob.version;var qc=new Wc,Pk=new Ec("0.0.0.0"),Os=new Set,Jc=new Set,wd=!1,Gc=null,vd=null;async function Qc(e){if(wd)return m("cleanup","Cleanup already in progress, skipping",e?.verbose),vd||Promise.resolve();wd=!0,m("cleanup","Starting cleanup process",e?.verbose),vd=new Promise((t)=>{Gc=t});try{await qc.stopAll(e?.verbose),b.info("Shutting down proxy servers...");let t=[],r=Array.from(Os).map((n)=>new Promise((i)=>{let s=n;try{if(typeof s.stop==="function")s.stop(!0),m("cleanup","Bun server stopped",e?.verbose),i();else if(typeof s.close==="function")s.close(()=>{m("cleanup","Server closed successfully",e?.verbose),i()});else i()}catch(o){m("cleanup",`Error stopping server: ${o}`,e?.verbose),i()}}));t.push(...r),Os.clear();for(let n of Jc)ii(n);if(Jc.clear(),e?.hosts&&e.domains?.length){m("cleanup","Cleaning up hosts file entries",e?.verbose),m("cleanup",`Original domains for cleanup: ${JSON.stringify(e.domains)}`,e?.verbose);let n=e.domains.filter((i)=>{if(i==="test.local")return!0;return i!=="localhost"&&!i.startsWith("localhost.")&&i!=="127.0.0.1"});if(m("cleanup",`Filtered domains for cleanup: ${JSON.stringify(n)}`,e?.verbose),n.length>0)b.info("Cleaning up hosts file entries..."),t.push(Rv(n,e?.verbose).then(()=>{m("cleanup",`Removed hosts entries for ${n.join(", ")}`,e?.verbose)}).catch((i)=>{m("cleanup",`Failed to remove hosts entries: ${i}`,e?.verbose),b.warn(`Failed to clean up hosts file entries for ${n.join(", ")}:`,i)}))}if(e?.certs&&e.domains?.length){m("cleanup","Cleaning up SSL certificates",e?.verbose),b.info("Cleaning up SSL certificates...");let n=e.domains.map(async(i)=>{try{await Uw(i,e?.verbose),m("cleanup",`Removed certificates for ${i}`,e?.verbose)}catch(s){m("cleanup",`Failed to remove certificates for ${i}: ${s}`,e?.verbose),b.warn(`Failed to clean up certificates for ${i}:`,s)}});t.push(...n)}await Promise.allSettled(t),m("cleanup","All cleanup tasks completed successfully",e?.verbose),b.success("All cleanup tasks completed successfully")}catch(t){m("cleanup",`Error during cleanup: ${t}`,e?.verbose),b.error("Error during cleanup:",t)}finally{if(Gc)Gc();Gc=null,wd=!1;let t=e&&"vitePluginUsage"in e&&e.vitePluginUsage===!0;if(q.env.NODE_ENV!=="test"&&q.env.BUN_ENV!=="test"&&!t)q.exit(0)}return vd}var bd=!1;function ub(e){if(bd){m("signal",`Received second ${e} signal, forcing exit`,!0),q.exit(1);return}bd=!0,m("signal",`Received ${e} signal, initiating cleanup`,!0),Qc().catch((t)=>{m("signal",`Cleanup failed after ${e}: ${t}`,!0),q.exit(1)}).finally(()=>{bd=!1})}q.once("SIGINT",()=>ub("SIGINT"));q.once("SIGTERM",()=>ub("SIGTERM"));q.on("uncaughtException",(e)=>{b.error("Uncaught exception (continuing):",e)});q.on("unhandledRejection",(e)=>{b.error("Unhandled rejection (continuing):",e)});async function Ns(e,t,r,n=5){m("connection",`Testing connection to ${e}:${t} (retries left: ${n})`,r);let i=15000,s=Date.now();if(q.env.RPX_BYPASS_CONNECTION_TEST==="true"){m("connection",`Bypassing connection test for ${e}:${t} due to RPX_BYPASS_CONNECTION_TEST flag`,r);return}let o=()=>new Promise((c,a)=>{let l=cb.connect({host:e,port:t,timeout:3000});l.once("connect",()=>{m("connection",`Successfully connected to ${e}:${t}`,r),l.end(),c()}),l.once("timeout",()=>{m("connection",`Connection to ${e}:${t} timed out`,r),l.destroy(),a(Error("Connection timed out"))}),l.once("error",(u)=>{m("connection",`Failed to connect to ${e}:${t}: ${u}`,r),l.destroy(),a(u)})});try{await o()}catch(c){let a=c;if(Date.now()-s>i){m("connection",`Connection test timed out after ${i}ms, but continuing anyway`,r),b.warn(`Connection test to ${e}:${t} timed out, but RPX will try to proceed anyway.`);return}if(a.code==="ECONNREFUSED"&&n>0)return m("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${n} retries left)`,r),await new Promise((u)=>setTimeout(u,2000)),Ns(e,t,r,n-1);if(n>0)try{m("connection",`Trying HTTP request to ${e}:${t}`,r),await new Promise((u,f)=>{let h=Xc.request({hostname:e,port:t,path:"/",method:"HEAD",timeout:5000},(d)=>{m("connection",`Received HTTP response with status: ${d.statusCode}`,r),u()});h.on("error",(d)=>f(d)),h.on("timeout",()=>{h.destroy(),f(Error("HTTP request timed out"))}),h.end()}),m("connection",`HTTP request to ${e}:${t} succeeded`,r);return}catch(u){return m("connection",`HTTP request to ${e}:${t} failed: ${u}`,r),m("connection",`Retrying socket connection in 2 seconds... (${n} retries left)`,r),await new Promise((f)=>setTimeout(f,2000)),Ns(e,t,r,n-1)}let l=`Failed to connect to ${e}:${t} after ${5-n} attempts: ${a.message}`;m("connection",`${l}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,r),b.warn(l),b.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 fb(e){m("server",`Starting server with options: ${ur(e)}`,e.verbose);let t=qr(e.from),r=new URL(t.startsWith("http")?t:`http://${t}`),n=new URL((e.to?.startsWith("http")?e.to:`http://${e.to}`)||"rpx.localhost"),i=Number.parseInt(r.port)||(r.protocol.includes("https:")?443:80),s=[n.hostname];if($d(e)&&!n.hostname.includes("localhost")&&!n.hostname.includes("127.0.0.1")){m("hosts",`Checking if hosts file entry exists for: ${n.hostname}`,e?.verbose);try{if(!(await Ss(s,e.verbose))[0]){b.info(`Adding ${n.hostname} to hosts file...`),b.info("This may require sudo/administrator privileges");try{await xs(s,e.verbose)}catch(a){if(b.error("Failed to add hosts entry:",a.message),b.warn("You can manually add this entry to your hosts file:"),b.warn(`127.0.0.1 ${n.hostname}`),b.warn(`::1 ${n.hostname}`),q.platform==="win32")b.warn("On Windows:"),b.warn("1. Run notepad as administrator"),b.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else b.warn("On Unix systems:"),b.warn("sudo nano /etc/hosts")}}else m("hosts",`Host entry already exists for ${n.hostname}`,e.verbose)}catch(c){b.error("Failed to check hosts file:",c.message)}}try{await Ns(r.hostname,i,e.verbose)}catch(c){m("server",`Connection test failed: ${c}`,e.verbose),b.error(c.message),b.warn("Continuing with proxy setup despite connection test failure..."),b.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let o=e._cachedSSLConfig||null;if(e.https)try{if(e.https===!0)e.https=ts({...e,to:n.hostname});if(o=await Or({...e,to:n.hostname,https:e.https}),!o){if(m("ssl",`Generating new certificates for ${n.hostname}`,e.verbose),await es({...e,from:r.toString(),to:n.hostname,https:e.https}),o=await Or({...e,to:n.hostname,https:e.https}),!o)throw Error(`Failed to load SSL configuration after generating certificates for ${n.hostname}`)}}catch(c){throw m("server",`SSL setup failed: ${c}`,e.verbose),c}m("server",`Setting up reverse proxy with SSL config for ${n.hostname}`,e.verbose),await Rk({...e,from:t,originalFrom:e.from||t,to:n.hostname,fromPort:i,sourceUrl:{hostname:r.hostname,host:r.host},ssl:o})}async function Ak(e,t,r,n,i,s,o,c,a,l,u,f){m("proxy",`Creating proxy server ${e} -> ${t} with cleanUrls: ${c}`,o);let h=rs(u??n.host,f);is(h);let d=[{host:t,route:{sourceHost:n.host,upstreamPool:h,cleanUrls:c||!1,changeOrigin:a||!1,basePath:"/",auth:l}}];if(!Yc({routeEntries:d,listenPort:r,sslConfig:i,originGuard:null,verbose:o??!1}))throw ii(h),Error(`Failed to start proxy server for ${t} on port ${r}`);Jc.add(h),Ok({from:e,to:t,vitePluginUsage:s,listenPort:r,ssl:!!i,cleanUrls:c,verbose:o})}async function Rk(e){m("setup",`Setting up reverse proxy: ${ur(e)}`,e.verbose);let{from:t,originalFrom:r,to:n,sourceUrl:i,ssl:s,verbose:o,cleanup:c,vitePluginUsage:a,changeOrigin:l,cleanUrls:u}=e,f=e.httpPort??80,h=e.httpsPort??443,d=mb(),y=e.portManager||Pk,g=$d(e);try{if(g&&n&&!n.includes("localhost")&&!n.includes("127.0.0.1")){if(!(await Ss([n],o))[0]){b.warn(`The hostname ${n} isn't in your hosts file. Adding it now...`);try{await xs([n],o),b.success(`Added ${n} to your hosts file.`)}catch(A){b.error(`Failed to add ${n} to your hosts file: ${A}`),b.info(`You may need to manually add '127.0.0.1 ${n}' to your /etc/hosts file.`)}}}else if(g&&q.platform!=="darwin"&&n&&n.includes("localhost")&&!n.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await Ss([n],o))[0]){m("hosts",`${n} not found in hosts file, adding...`,o);try{await xs([n],o)}catch(A){m("hosts",`Failed to add ${n} to hosts file: ${A}`,o)}}}if(s&&!y.usedPorts.has(f)){if(!await Nr(f,d,o))m("setup","Starting HTTP redirect server",o),hb(o,f,h),y.usedPorts.add(f);else if(m("setup","Port 80 is in use, skipping HTTP redirect",o),o)b.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let p=s?h:f,w=await Nr(p,d,o),v;if(w){if(m("setup",`Port ${p} is already in use`,o),o)b.warn(`Port ${p} is already in use. This may be another instance of rpx or another service.`);if(p===443){if(v=await y.getNextAvailablePort(3443,!0),m("setup",`Using port ${v} instead of ${p}`,o),o)b.info(`Using port ${v} instead. Access your site at https://${n}:${v}`)}else if(v=await y.getNextAvailablePort(p+1000,!0),m("setup",`Using port ${v} instead of ${p}`,o),o)b.info(`Using port ${v} instead. Access your site at http://${n}:${v}`)}else v=p,y.usedPorts.add(v),m("setup",`Using standard ${p===443?"HTTPS":"HTTP"} port ${p} for ${n}`,o);await Ak(t,n,v,i,s,a,o,u,l,os(e.auth),r,e.loadBalancer)}catch(p){m("setup",`Setup failed: ${p}`,o),b.error(`Failed to setup reverse proxy: ${p.message}`),Qc({domains:[n],hosts:typeof c==="boolean"?c:c?.hosts,certs:typeof c==="boolean"?c:c?.certs,verbose:o,vitePluginUsage:a})}}function hb(e,t=80,r=443,n,i,s){m("redirect",`Starting HTTP redirect server on port ${t}`,e);let o=Xc.createServer((c,a)=>{let l=c.url?c.url.split("?",1)[0]:"";if(l.startsWith("/.well-known/acme-challenge/")){if(i){let d=i.challengeStore.handlePath(l);if(d!==void 0){m("redirect",`Serving on-demand ACME challenge ${l}`,e),a.writeHead(200,{"content-type":"text/plain"}),a.end(d);return}}if(n){let d=vc(n,l);if(d!=null){m("redirect",`Serving ACME challenge ${l}`,e),a.writeHead(200,{"content-type":"text/plain"}),a.end(d);return}}if(i){a.writeHead(404,{"content-type":"text/plain"}),a.end("challenge not found");return}}let u=c.headers.host||"",f=u.includes(":")?u.slice(0,u.indexOf(":")):u;if(i&&f&&!i.hasCert(f)&&(!s||s(f)))i.ensureCert(f).catch(()=>{});let h=r===443?f:`${f}:${r}`;m("redirect",`Redirecting request from ${u}${c.url} to https://${h}`,e),a.writeHead(301,{Location:`https://${h}${c.url}`}),a.end()}).listen(t);Os.add(o),m("redirect","HTTP redirect server started",e)}function db(e){let t={...Gt,...e};if(m("proxy",`Starting proxy with options: ${ur(t)}`,t?.verbose),t.viaDaemon){if(!t.from||!t.to){b.error("viaDaemon mode requires both `from` and `to`");return}yd({proxies:[{id:t.id,from:t.from,to:t.to,path:t.path,cleanUrls:t.cleanUrls,changeOrigin:t.changeOrigin,pathRewrites:t.pathRewrites}],verbose:t.verbose}).catch((a)=>{b.error(`Failed to register with rpx daemon: ${a.message}`),q.exit(1)});return}let r=t.to||"",n=r.split(".").pop()?.toLowerCase()||"",i=q.platform==="darwin"&&r&&!r.includes("localhost")&&!r.includes("127.0.0.1"),s=["dev","app","page","new","day","foo"],o=["test","localhost","local","example","invalid"];if(i&&s.includes(n)&&t?.verbose)b.warn(`The .${n} TLD may not work reliably for local development`),b.info(` Google owns .${n} with HSTS preloading, which can bypass local DNS`),b.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(i)Promise.resolve().then(() => (As(),Lc)).then(({setupDevelopmentDns:a})=>{a({domains:[r],verbose:t.verbose}).then((l)=>{if(l)Promise.resolve().then(()=>{if(t.verbose)if(o.includes(n))b.success(`DNS server started for .${n} domains`);else b.success(`DNS server started for .${n} domains (hosts file entry also added)`)});else m("dns",`Could not start DNS server - ${r} may not resolve in browser`,t.verbose)})}).catch((a)=>{m("dns",`Failed to start DNS server: ${a}`,t.verbose)});let c={from:t.from,to:t.to,cleanUrls:t.cleanUrls,https:ts(t),cleanup:t.cleanup,vitePluginUsage:t.vitePluginUsage,changeOrigin:t.changeOrigin,verbose:t.verbose,regenerateUntrustedCerts:t.regenerateUntrustedCerts};m("proxy",`Server options: ${ur(c)}`,t.verbose),fb(c).catch((a)=>{m("proxy",`Failed to start proxy: ${a}`,t.verbose),b.error(`Failed to start proxy: ${a.message}`),Qc({domains:[t.to],hosts:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.hosts,certs:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.certs,verbose:t.verbose})})}function kk(e){return e?.verbose||!1}function $d(e){if(e?.hostsManagement===!1)return!1;let t=e?.cleanup;if(t===!1)return!1;if(t&&typeof t==="object"&&t.hosts===!1)return!1;return!0}async function el(e){let t={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(e)t={...t,...e};let r=kk(t),n=t.https===!1;if(t.localCa)ws(t.localCa,t.onDemandTls);let i=$d(t);if(m("config",`Starting with config: ${ur(t,2)}`,r),m("config",`Is multi-proxy? ${"proxies"in t}`,r),m("config",`Hosts management enabled? ${i}`,r),t.viaDaemon){let k="proxies"in t&&Array.isArray(t.proxies)?t.proxies.map((L)=>({id:L.id,from:L.from,to:L.to,path:L.path,cleanUrls:L.cleanUrls??t.cleanUrls,changeOrigin:L.changeOrigin??t.changeOrigin,pathRewrites:L.pathRewrites})):[{id:t.id,from:t.from,to:t.to??"rpx.localhost",path:t.path,cleanUrls:t.cleanUrls,changeOrigin:t.changeOrigin,pathRewrites:t.pathRewrites}];await yd({proxies:k,verbose:r});return}if("proxies"in t&&Array.isArray(t.proxies)){m("servers",`Found ${t.proxies.length} proxies in config`,r);for(let x of t.proxies)if(x.start){let k=`${x.from}-${x.to}`;try{m("watch",`Starting command for ${k} with command: ${x.start.command}`,r),b.info(`Starting command for ${k}...`),await qc.startProcess(k,x.start,r);let L=qr(x.from),ee=new URL(L.startsWith("http")?L:`http://${L}`),Re=ee.hostname||"localhost",Ge=Number(ee.port)||80;try{await Ns(Re,Ge,r),m("watch",`Dev server is ready at ${Re}:${Ge}`,r)}catch(jt){m("watch",`Connection check failed, but continuing with proxy setup: ${jt}`,r),b.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(L){throw m("watch",`Failed to start command for ${k}: ${L}`,r),Error(`Failed to start command for ${k}: ${L}`)}}else m("watch",`No start command for proxy ${x.from} -> ${x.to}`,r)}else if("start"in t&&t.start){m("watch","Found start command in single proxy config",r);let x=`${t.from}-${t.to}`;try{if(t.start)m("watch",`Starting command: ${t.start.command}`,r),await qc.startProcess(x,t.start,r);let k=qr(t.from),L=new URL(k.startsWith("http")?k:`http://${k}`),ee=L.hostname||"localhost",Re=Number(L.port)||80;try{await Ns(ee,Re,r),m("watch",`Dev server is ready at ${ee}:${Re}`,r)}catch(Ge){m("watch",`Connection check failed, but continuing with proxy setup: ${Ge}`,r),b.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(k){throw m("watch",`Failed to run start command: ${k}`,r),Error(`Failed to run start command: ${k}`)}}else m("watch","No start command found in config",r);let s="proxies"in t&&Array.isArray(t.proxies)?t.proxies[0]?.to:("to"in t)?t.to:"rpx.localhost";if(q.platform!=="win32"&&(t.https||i)){if(!Er())try{m("sudo","Pre-acquiring sudo credentials for privileged operations",r),Tk("sudo -v",{stdio:"inherit"})}catch{m("sudo","Could not pre-acquire sudo credentials",r)}}let o=[],c=null;if(t.productionCerts&&!n){if(o=await ms(t.productionCerts,r),o.length>0)m("ssl",`Using ${o.length} production SNI cert(s): ${o.map((x)=>x.serverName).join(", ")}`,r)}if(t.localCa&&!n){let x=await vs(t.localCa,{verbose:r,onDemandTls:t.onDemandTls}),k=new Set(x.entries.map((L)=>L.serverName));o=[...x.entries,...o.filter((L)=>!k.has(L.serverName))],c=x.defaultTls,m("ssl",`Local CA: ${x.leafMinted?`minted leaf (${x.renewalReason})`:"reusing leaf"} for ${[...k].join(", ")}; valid until ${x.notAfter.toISOString()}`,r)}if(t.https){let x=o.length>0?null:await Or(t);if(!x&&o.length===0){if(m("ssl",`No valid or trusted certificates found for ${s}, generating new ones`,t.verbose),await es(t),x=await Or(t),!x)throw Error(`Failed to load SSL certificates after generation for ${s}`)}else m("ssl",`Using existing and trusted certificates for ${s}`,t.verbose);t._cachedSSLConfig=x}let a="proxies"in t&&Array.isArray(t.proxies)?t.proxies.map((x)=>({...x,https:t.https,cleanup:t.cleanup,cleanUrls:x.cleanUrls??("cleanUrls"in t?t.cleanUrls:!1),vitePluginUsage:t.vitePluginUsage,changeOrigin:x.changeOrigin??t.changeOrigin,verbose:r,_cachedSSLConfig:t._cachedSSLConfig})):[{from:"from"in t?t.from:"localhost:5173",to:"to"in t?t.to:"rpx.localhost",cleanUrls:"cleanUrls"in t?t.cleanUrls:!1,https:t.https,cleanup:t.cleanup,vitePluginUsage:t.vitePluginUsage,start:"start"in t?t.start:void 0,changeOrigin:t.changeOrigin,auth:"auth"in t?t.auth:void 0,verbose:r,_cachedSSLConfig:t._cachedSSLConfig}],l=a.map((x)=>x.to||"rpx.localhost"),u=n?null:o.length>0?o:t._cachedSSLConfig??null,f=l.filter((x)=>x&&!x.includes("localhost")&&!x.includes("127.0.0.1")),h=["dev","app","page","new","day","foo"],d=["test","localhost","local","example","invalid"],y=[...new Set(f.map((x)=>x.split(".").pop()?.toLowerCase()))],g=y.filter((x)=>!!x&&h.includes(x));if(g.length>0&&r)b.warn(`The following TLDs may not work reliably for local development: ${g.map((x)=>`.${x}`).join(", ")}`),b.info(" These TLDs have HSTS preloading which can bypass local DNS"),b.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(i&&q.platform==="darwin"&&f.length>0){let{setupDevelopmentDns:x}=await Promise.resolve().then(() => (As(),Lc));if(await x({domains:f,verbose:r})){if(r)if(y.every((ee)=>!!ee&&d.includes(ee)))b.success(`DNS server started for ${y.map((ee)=>`.${ee}`).join(", ")} domains`);else b.success(`DNS server started for ${y.map((ee)=>`.${ee}`).join(", ")} domains (hosts file entries also added)`)}else m("dns","Could not start DNS server - custom domains may not resolve",r)}let p=async()=>{m("cleanup","Starting cleanup handler",t.verbose);try{let{tearDownDevelopmentDns:x}=await Promise.resolve().then(() => (As(),Lc));await x({verbose:t.verbose})}catch(x){m("cleanup",`Error stopping DNS server: ${x}`,t.verbose)}try{await qc.stopAll(t.verbose)}catch(x){m("cleanup",`Error stopping processes: ${x}`,t.verbose)}await Qc({domains:l,hosts:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.hosts,certs:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.certs,verbose:t.verbose||!1})};q.on("SIGINT",p),q.on("SIGTERM",p);let w=t.singlePortMode===!0,v=t.httpsPort??443,P=t.httpPort??80,A=t.originGuard?sb(t.originGuard):null,R=!!u&&(a.length>1||w||o.length>0),D=!u&&a.length>0&&(w||a.length>1),F=t.maxTlsContexts;if(R&&u){m("proxies",`Creating shared HTTPS server for ${a.length} domains on port ${v}`,r);let x=await ab(a,i,r),k=null,L=t.onDemandTls,ee=L?.enabled?new oi({config:L,certsDir:L.certsDir??t.productionCerts?.certsDir??lb.join(Zc.homedir(),".stacks","rpx","on-demand-certs"),initial:o,verbose:r,onCertAdded:(rt)=>{if(gs()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",r),setTimeout(()=>q.kill(q.pid,"SIGTERM"),10).unref();else jt(rt)}}):null,Re=null,Ge=!1;async function jt(rt){if(Re=rt,Ge)return;Ge=!0;try{while(Re){let O=Re;if(Re=null,m("proxies",`rebuilding :${v} with ${O.length} SNI cert(s)`,r),k)Os.delete(k),k.stop(!1);let pe=!1;for(let ye=0;!pe&&ye<60;ye++){let Ir=Yc({routeEntries:x,listenPort:v,sslConfig:O,defaultTls:c,maxTlsContexts:F,originGuard:A,verbose:r});if(Ir){k=Ir,pe=!0;break}await new Promise((tn)=>setTimeout(tn,Math.min(25*2**Math.min(ye,4),500)))}if(!pe)b.error(`rpx: CRITICAL — could not rebind :${v} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{Ge=!1}}if(!await Nr(P,"0.0.0.0",r)){let rt=new Set(x.map((pe)=>pe.host)),O=(pe)=>rt.has(pe)||[...rt].some((ye)=>Ur(pe,ye));hb(r,P,v,t.acmeChallengeWebroot,ee,O)}if(await Nr(v,"0.0.0.0",r)){if(m("proxies",`Port ${v} is already in use, cannot start shared proxy`,r),r)b.warn(`Port ${v} is in use. Shared HTTPS proxy cannot start.`);return}let St=ee&&ee.sniEntries().length>0?ee.sniEntries():u;if(k=Yc({routeEntries:x,listenPort:v,sslConfig:St,defaultTls:c,maxTlsContexts:F,originGuard:A,verbose:r}),!k){b.error(`Shared HTTPS proxy failed to bind :${v}; not exiting`);return}}else if(D){m("proxies",`Creating shared HTTP server for ${a.length} domains on port ${P}`,r);let x=await ab(a,i,r);if(await Nr(P,"0.0.0.0",r)){if(m("proxies",`Port ${P} is already in use, cannot start shared proxy`,r),r)b.warn(`Port ${P} is in use. Shared HTTP proxy cannot start.`);return}if(!Yc({routeEntries:x,listenPort:P,sslConfig:null,originGuard:A,verbose:r})){b.error(`Shared HTTP proxy failed to bind :${P}; not exiting`);return}}else for(let x of a)try{let k=x.to||"rpx.localhost";m("proxy",`Starting proxy for ${k} with SSL config: ${!!u}`,x.verbose),await fb({from:x.from||"localhost:5173",to:k,cleanUrls:x.cleanUrls||!1,https:x.https||!1,cleanup:x.cleanup||!1,vitePluginUsage:x.vitePluginUsage||!1,verbose:x.verbose||!1,_cachedSSLConfig:t._cachedSSLConfig,changeOrigin:x.changeOrigin||!1,loadBalancer:x.loadBalancer,auth:x.auth,path:x.path,pathRewrites:x.pathRewrites,httpPort:t.httpPort,httpsPort:t.httpsPort})}catch(k){m("proxies",`Failed to start proxy for ${x.to}: ${k}`,x.verbose),b.error(`Failed to start proxy for ${x.to}:`,k)}}async function ab(e,t,r){let n=[],i=new Set;for(let s of e){let o=s.to||"rpx.localhost",c=s.cleanUrls||!1,a=s.path,l=fr(a),u=os(s.auth);if(s.redirect){let f=rv(s.redirect);n.push({host:o,path:a,route:{redirect:f,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → redirect ${f.status} ${f.to}${u?" (auth)":""}`,r)}else if(s.static)n.push({host:o,path:a,route:{static:yc(s.static,c),cleanUrls:c,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → static ${typeof s.static==="string"?s.static:s.static.dir}${u?" (auth)":""}`,r);else{let f=qr(s.from),h=new URL(f.startsWith("http")?f:`http://${f}`),d=rs(s.from??h.host,s.loadBalancer);is(d),Jc.add(d),n.push({host:o,path:a,route:{sourceHost:h.host,upstreamPool:d,cleanUrls:c,changeOrigin:s.changeOrigin||!1,pathRewrites:s.pathRewrites,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → ${h.host}${u?" (auth)":""}`,r)}if(i.has(o))continue;if(i.add(o),t&&!yn(o)&&!o.includes("localhost")&&!o.includes("127.0.0.1"))try{if(!(await Ss([o],r))[0])await xs([o],r)}catch{m("hosts",`Could not add hosts entry for ${o}`,r)}}return n}var ks=null;function mb(){if(q.env.RPX_BIND_HOSTNAME)return q.env.RPX_BIND_HOSTNAME;if(ks)return ks;try{ks=Object.values(Zc.networkInterfaces()).flat().some((r)=>r&&r.family==="IPv6")?"::":"0.0.0.0"}catch{ks="0.0.0.0"}return ks}function Yc(e){let{routeEntries:t,listenPort:r,sslConfig:n,defaultTls:i,maxTlsContexts:s,originGuard:o,verbose:c}=e,a=us(t),l=cs((h,d)=>fs(a,h,d),c),u=o?(h,d)=>o(h)??l(h,d):l,f=ls(c);try{let h=Bun.serve({port:r,hostname:mb(),reusePort:ti(),...n?{tls:Array.isArray(n)?ds({sni:n,defaultTls:i,maxTlsContexts:s,verbose:c}):si({key:n.key,cert:n.cert,ca:n.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(d,y){return u(d,y)},websocket:f,error(d){return m("server",`Shared proxy server error: ${d}`,c),new Response(`Server Error: ${d.message}`,{status:500})}});return Os.add(h),m("proxies",`Shared ${n?"HTTPS":"HTTP"} proxy listening on port ${r} for ${a.size} domains`,c),h}catch(h){return m("proxies",`Failed to start shared proxy: ${h}`,c),console.error("Failed to start shared proxy:",h),null}}function Ok(e){if(e?.vitePluginUsage||!e?.verbose)return;if(console.log(""),console.log(` ${Mt.green(Mt.bold("rpx"))} ${Mt.green(`v${Rs}`)}`),console.log(` ${Mt.green("➜")} ${Mt.dim(e?.from??"")} ${Mt.dim("➜")} ${Mt.cyan(e?.ssl?`https://${e?.to}`:`http://${e?.to}`)}`),e?.listenPort!==(e?.ssl?443:80))console.log(` ${Mt.green("➜")} Listening on port ${e?.listenPort}`);if(e?.cleanUrls)console.log(` ${Mt.green("➜")} Clean URLs enabled`)}fe();var Cd="/etc/rpx/certs",Ds="/etc/rpx/sites.d";function Fk(e,t){console.error(`[rpx gateway] SKIPPING malformed fragment ${e}; its host(s) will 404 until fixed: ${t.message}`)}async function Lk(e,t=Fk){let r=[];try{r=(await Nk(e)).filter((i)=>i.endsWith(".json")).sort()}catch{return[]}let n=[];for(let i of r)try{let s=JSON.parse(await Dk(gb.join(e,i),"utf8"));if(!s||typeof s!=="object"||Array.isArray(s))throw TypeError("fragment is not a JSON object");n.push({file:i,fragment:s})}catch(s){t(i,s instanceof Error?s:Error(String(s)))}return n}function Bk(e,t={}){let r=t.onWarning??((y)=>console.warn(`[rpx gateway] ${y}`)),n=[],i=new Set,s=new Map,o=new Set,c=new Set,a,l=t.certsDir??Cd,u,f,h=!1;for(let{file:y,fragment:g}of e){for(let p of Array.isArray(g.proxies)?g.proxies:[]){let w=p.id||`${p.to}${p.path??""}`;if(i.has(w)){r(`duplicate route ${w} in ${y} ignored; first declared by ${s.get(w)}`);continue}i.add(w),s.set(w,y),n.push(p)}for(let p of g.onDemandTls?.allowedSuffixes??[])o.add(p);if(a??=g.onDemandTls?.email,g.onDemandTls&&g.onDemandTls.staging!==!0)h=!0;if(g.productionCerts?.certsDir)l=g.productionCerts.certsDir;if(u??=g.acmeChallengeWebroot,g.originGuard&&g.originGuard.header&&g.originGuard.value)if(f??={header:g.originGuard.header,value:g.originGuard.value},g.originGuard.header===f.header&&g.originGuard.value===f.value)for(let p of g.originGuard.hosts??[])c.add(p);else r(`origin-guard secret in ${y} differs from the one already in force; its hosts stay unguarded rather than rejecting all traffic`)}let d={proxies:n,productionCerts:{certsDir:l,certsDirServerNames:[...new Set(n.map((y)=>y.to).filter(Boolean))]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(o.size>0)d.onDemandTls={enabled:!0,allowedSuffixes:[...o],email:a,certsDir:l,staging:!h};if(u)d.acmeChallengeWebroot=u;if(f)d.originGuard={header:f.header,value:f.value,hosts:[...c]};return d}async function Ik(e={}){let t=e.sitesDir??Ds,r=e.verbose??pb.env.RPX_VERBOSE!=="false",n=await Lk(t,e.onFragmentError);m("gateway",`merged ${n.length} fragment(s) from ${t}: ${n.map((o)=>o.file).join(", ")||"<none>"}`,r);let s={...Bk(n,{certsDir:e.certsDir}),verbose:r,singlePortMode:!0};if(e.https===!1)s.https=!1;if(e.httpPort!==void 0)s.httpPort=e.httpPort;if(e.httpsPort!==void 0)s.httpsPort=e.httpsPort;if(e.localCa)s.localCa=e.localCa;if(e.maxTlsContexts!==void 0)s.maxTlsContexts=e.maxTlsContexts;return s}async function yb(e={}){let t=await Ik(e);if(("proxies"in t&&Array.isArray(t.proxies)?t.proxies:[]).length===0&&!e.localCa)console.warn(`[rpx gateway] no routes found under ${e.sitesDir??Ds}; every request will answer 404 until a fragment is deployed`);await el(t)}fe();Fe.chdir(_k(Mk(jk(import.meta.url)),".."));var He=new fl("rpx");He.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async(e)=>{if(!e?.from||!e.to)return el(Gt);let t={from:e.from,to:e.to,https:{keyPath:e.keyPath,certPath:e.certPath,caCertPath:e.caCertPath},cleanup:{certs:e.certsCleanup||!1,hosts:e.hostsCleanup||!1},verbose:e.verbose||!1,changeOrigin:e.changeOrigin||!1,singlePortMode:e.singlePortMode||!1,httpPort:e.httpPort!==void 0?Number(e.httpPort):void 0,httpsPort:e.httpsPort!==void 0?Number(e.httpsPort):void 0,viaDaemon:e.viaDaemon||!1,id:e.id};if(e.startCommand){let r={command:e.startCommand};if(e.startCwd)r.cwd=e.startCwd;if(e.startEnv)try{r.env=JSON.parse(e.startEnv)}catch(n){console.error("Failed to parse start-env JSON:",n),Fe.exit(1)}t.start=r}return db(t)});He.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{let r=oc(Gt)?Gt.proxies.find((n)=>n.to===e||`${n.from}-${n.to}`===e):Gt.to===e?Gt:null;if(!r?.start)console.error(`No watch configuration found for proxy: ${e}`),Fe.exit(1);try{await Vc.startProcess(e,r.start,t.verbose),console.log(`Started dev server for ${e}`)}catch(n){console.error(`Failed to start dev server for ${e}:`,n),Fe.exit(1)}});He.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{try{await Vc.stopProcess(e,t.verbose),console.log(`Stopped dev server for ${e}`)}catch(r){console.error(`Failed to stop dev server for ${e}:`,r),Fe.exit(1)}});He.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(e)=>{try{await Vc.stopAll(e.verbose),console.log("Stopped all dev servers")}catch(t){console.error("Failed to stop all dev servers:",t),Fe.exit(1)}});function wb(e){if(e===void 0)return;let t=typeof e==="string"?Number.parseInt(e,10):e;if(!Number.isInteger(t)||t<0||t>65535)throw Error(`invalid port: ${JSON.stringify(e)}`);return t}function vb(e){return(e??"").split(",").map((t)=>t.trim()).filter(Boolean)}He.command("gateway","Serve every app fragment under a sites.d directory on :80/:443 (production gateway)").option("--sites-dir <path>",`Directory of per-app <slug>.json fragments (default ${Ds})`).option("--certs-dir <path>",`Fallback directory of real PEM certs when no fragment names one (default ${Cd})`).option("--no-https","Serve plain HTTP on the http port only; bind nothing on the https port").option("--http-port <port>","Shared HTTP port: redirect + ACME http-01, or the only listener with --no-https (default 80)").option("--https-port <port>","Shared HTTPS port (default 443)").option("--local-ca-dir <path>","LAN production mode: directory for a local Root CA and its leaf (enables localCa)").option("--local-ca-hosts <hosts>","Comma-separated LAN hostnames the local leaf must cover (e.g. pi-stacks.local)").option("--local-ca-ips <ips>","Comma-separated IP addresses the local leaf must cover (e.g. 192.168.1.20)").option("--install-trust","Install the local Root CA into the system trust store on start (needs root)").option("--max-tls-contexts <n>","Memory guard: most SNI certificates kept live (default 256)").option("--verbose","Enable verbose logging (default on; RPX_VERBOSE=false turns it off)").example("rpx gateway --sites-dir /etc/rpx/sites.d").example("rpx gateway --sites-dir /etc/rpx/sites.d --no-https --http-port 8080").example("rpx gateway --local-ca-dir /etc/rpx/local-ca --local-ca-hosts pi-stacks.local --local-ca-ips 192.168.1.20 --install-trust").action(async(e)=>{try{let t=vb(e.localCaHosts),r=vb(e.localCaIps);if((t.length>0||r.length>0||e.installTrust)&&!e.localCaDir)throw Error("--local-ca-hosts / --local-ca-ips / --install-trust need --local-ca-dir");if(e.localCaDir&&t.length===0)throw Error("--local-ca-dir needs at least one --local-ca-hosts entry");await yb({sitesDir:e.sitesDir??Ds,certsDir:e.certsDir,https:e.https!==!1,httpPort:wb(e.httpPort),httpsPort:wb(e.httpsPort),maxTlsContexts:e.maxTlsContexts===void 0?void 0:Number.parseInt(String(e.maxTlsContexts),10),localCa:e.localCaDir?{dir:e.localCaDir,hosts:t,ips:r,installTrust:e.installTrust===!0}:void 0,verbose:e.verbose===void 0?void 0:e.verbose})}catch(t){console.error(`Failed to start rpx gateway: ${t.message}`),Fe.exit(1)}});async function bb(e){let r={...(await ug().catch(()=>null))?.onDemand??{},enabled:!0};if(e){let n=e.split(",").map((i)=>i.trim()).filter(Boolean);if(n.length>0)r.roots=n}return r}He.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(e)=>{try{let t=e.onDemand?await bb(e.roots):void 0;await(await eb({rpxDir:e.rpxDir,registryDir:e.registryDir,httpsPort:typeof e.httpsPort==="string"?Number.parseInt(e.httpsPort,10):e.httpsPort,httpPort:typeof e.httpPort==="string"?Number.parseInt(e.httpPort,10):e.httpPort,hostname:e.hostname,productionCerts:e.certsDir?{certsDir:e.certsDir}:void 0,workers:e.workers===void 0?void 0:typeof e.workers==="string"?Number.parseInt(e.workers,10):e.workers,onDemandSites:t,verbose:e.verbose??!0})).done,Fe.exit(0)}catch(t){console.error(`Failed to start rpx daemon: ${t.message}`),Fe.exit(1)}});He.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async(e)=>{let t=typeof e.timeout==="string"?Number.parseInt(e.timeout,10):e.timeout,r=await tb({rpxDir:e.rpxDir,timeoutMs:t,forceAfterTimeout:e.force!==!1,verbose:e.verbose});if(!r.stopped&&r.pid===null){console.log("rpx daemon is not running");return}if(!r.stopped){console.log(`rpx daemon pid=${r.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${r.pid} stopped${r.forced?" (SIGKILL)":""}`)});He.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async(e)=>{let t=e.rpxDir??De(),r=await Lr(t),n=await jc(t),i=e.registryDir,s=await xt(i).catch(()=>[]);if(e.json){console.log(JSON.stringify({running:n,pid:r,pidFile:Br(t),rpxDir:t,registryDir:i??dt(),entries:s},null,2));return}if(!n){if(console.log("rpx daemon: not running"),r!==null)console.log(`(stale pid file at ${Br(t)} → pid ${r})`)}else console.log(`rpx daemon: running (pid=${r})`),console.log(`pid file: ${Br(t)}`);if(console.log(`registry: ${i??dt()}`),s.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${s.length}):`);for(let o of s){let c=o.pid!==void 0?`, pid=${o.pid}`:"";console.log(` https://${o.to} → ${o.from} (id=${o.id}${c})`)}});He.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async(e)=>{if(!e.id||!e.from||!e.to)console.error("rpx register requires --id, --from, and --to"),Fe.exit(1);if(!Dr(e.id))console.error(`invalid id: ${JSON.stringify(e.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),Fe.exit(1);try{await ai({id:e.id,from:e.from,to:e.to,cwd:e.cwd,createdAt:new Date().toISOString(),cleanUrls:e.cleanUrls,changeOrigin:e.changeOrigin},e.registryDir,e.verbose)}catch(t){console.error(`failed to write registry entry: ${t.message}`),Fe.exit(1)}if(e.skipSpawn){console.log(`registered ${e.to} → ${e.from} (daemon spawn skipped)`);return}try{let t=await Uc({rpxDir:e.rpxDir,verbose:e.verbose}),r=t.spawned?"spawned":"attached to";console.log(`registered https://${e.to} → ${e.from} (${r} daemon pid=${t.pid})`)}catch(t){console.error(`registered entry but daemon spawn failed: ${t.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),Fe.exit(1)}});He.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async(e,t)=>{if(!Dr(e))console.error(`invalid id: ${JSON.stringify(e)}`),Fe.exit(1);let r=await Zh(e,t.registryDir,t.verbose);if(!r){console.log(`no registry entry for id=${e}`);return}await Jr(e,t.registryDir,t.verbose),console.log(`unregistered ${r.to} (id=${e})`)});He.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async(e)=>{let t=e.rpxDir??De();if(await jc(t)){console.log("rpx daemon is running — DNS overrides are managed by the daemon");return}await rb({rpxDir:t,verbose:e.verbose}),console.log("DNS reconcile complete")});He.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(e)=>{let t=await bb(e.roots),r=pg(t),n=await xt(e.registryDir).catch(()=>[]),i=new Set(n.map((c)=>c.to)),s=r.map((c)=>({host:c.host,dir:c.dir,command:c.command,source:c.source,live:i.has(c.host)}));if(e.json){console.log(JSON.stringify(s,null,2));return}let o=t.roots??["~/Code"];if(s.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${o.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${s.length}) — scanned ${o.join(", ")}:`);for(let c of s)console.log(` ${c.live?"●":"○"} https://${c.host} ${c.live?"(live)":"(idle)"}`),console.log(` ${c.command} ${c.dir}`)});He.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(e,t)=>{let{readFile:r}=await import("node:fs/promises"),{join:n}=await import("node:path"),i=t.rpxDir??De(),s=n(i,"sites",`${xo(e.split(":")[0])}.log`),o;try{o=await r(s,"utf8")}catch{console.log(`no log for ${e} (it may not have been booted yet) — looked in ${s}`);return}let c=t.lines===void 0?void 0:typeof t.lines==="string"?Number.parseInt(t.lines,10):t.lines,a=o.split(`
|
|
387
|
+
`);Fe.stdout.write((c&&c>0?a.slice(-c):a).join(`
|
|
388
|
+
`))});He.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(Rs)});He.version(Rs);He.help();He.run();
|