@stacksjs/rpx 0.11.5 → 0.11.7

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 CHANGED
@@ -1,8 +1,243 @@
1
- import{b as N,c as d,r as O,u as B,v as U}from"../chunk-grcvjvzg.js";import"../chunk-hj5q1vd6.js";import{C as q}from"../chunk-cvt0dqrv.js";import"../chunk-sqn04kae.js";import*as g from"node:process";import{EventEmitter as R}from"events";function C(e){return e==null?[]:Array.isArray(e)?e:[e]}function H(e,t,n,s){var i,a=e[t],r=~s.string.indexOf(t)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~s.boolean.indexOf(t)?n==="false"?!1:n==="true"||(e._.push((i=+n,i*0===0)?i:n),!!n):(i=+n,i*0===0)?i:n;e[t]=a==null?r:Array.isArray(a)?a.concat(r):[a,r]}function G(e,t){e=e||[],t=t||{};var n,s,i,a,r,h={_:[]},o=0,l=0,m=0,c=e.length;let u=t.alias!==void 0,w=t.unknown!==void 0,_=t.default!==void 0;if(t.alias=t.alias||{},t.string=C(t.string),t.boolean=C(t.boolean),u)for(n in t.alias){s=t.alias[n]=C(t.alias[n]);for(o=0;o<s.length;o++)(t.alias[s[o]]=s.concat(n)).splice(o,1)}for(o=t.boolean.length;o-- >0;){s=t.alias[t.boolean[o]]||[];for(l=s.length;l-- >0;)t.boolean.push(s[l])}for(o=t.string.length;o-- >0;){s=t.alias[t.string[o]]||[];for(l=s.length;l-- >0;)t.string.push(s[l])}if(_){for(n in t.default)if(a=typeof t.default[n],s=t.alias[n]=t.alias[n]||[],t[a]!==void 0){t[a].push(n);for(o=0;o<s.length;o++)t[a].push(s[o])}}let D=w?Object.keys(t.alias):[];for(o=0;o<c;o++){if(i=e[o],i==="--"){h._=h._.concat(e.slice(++o));break}for(l=0;l<i.length;l++)if(i.charCodeAt(l)!==45)break;if(l===0)h._.push(i);else if(i.substring(l,l+3)==="no-"){if(a=i.substring(l+3),w&&!~D.indexOf(a))return t.unknown(i);h[a]=!1}else{for(m=l+1;m<i.length;m++)if(i.charCodeAt(m)===61)break;a=i.substring(l,m),r=i.substring(++m)||(o+1===c||(""+e[o+1]).charCodeAt(0)===45||e[++o]),s=l===2?[a]:a;for(m=0;m<s.length;m++){if(a=s[m],w&&!~D.indexOf(a))return t.unknown("-".repeat(l)+a);H(h,a,m+1<s.length||r,t)}}}if(_){for(n in t.default)if(h[n]===void 0)h[n]=t.default[n]}if(u)for(n in h){s=t.alias[n]||[];while(s.length>0)h[s.shift()]=h[n]}return h}var v=(e)=>e.replace(/[<[].+/,"").trim(),L=(e)=>{let t=/<([^>]+)>/g,n=/\[([^\]]+)\]/g,s=[],i=(h)=>{let o=!1,l=h[1];if(l.startsWith("..."))l=l.slice(3),o=!0;return{required:h[0].startsWith("<"),value:l,variadic:o}},a;while(a=t.exec(e))s.push(i(a));let r;while(r=n.exec(e))s.push(i(r));return s},M=(e)=>{let t={alias:{},boolean:[]};for(let[n,s]of e.entries()){if(s.names.length>1)t.alias[s.names[0]]=s.names.slice(1);if(s.isBoolean)if(s.negated){if(!e.some((a,r)=>{return r!==n&&a.names.some((h)=>s.names.includes(h))&&typeof a.required==="boolean"}))t.boolean.push(s.names[0])}else t.boolean.push(s.names[0])}return t},E=(e)=>{return e.sort((t,n)=>{return t.length>n.length?-1:1})[0]},V=(e,t)=>{return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`},S=(e)=>{return e.replace(/([a-z])-([a-z])/g,(t,n,s)=>{return n+s.toUpperCase()})},y=(e,t,n)=>{let s=0,i=t.length,a=e,r;for(;s<i;++s)r=a[t[s]],a=a[t[s]]=s===i-1?n:r!=null?r:!!~t[s+1].indexOf(".")||!(+t[s+1]>-1)?{}:[]},F=(e,t)=>{for(let n of Object.keys(t)){let s=t[n];if(s.shouldTransform){if(e[n]=Array.prototype.concat.call([],e[n]),typeof s.transformFunction==="function")e[n]=e[n].map(s.transformFunction)}}},x=(e)=>{let t=/([^\\\/]+)$/.exec(e);return t?t[1]:""},j=(e)=>{return e.split(".").map((t,n)=>{return n===0?S(t):t}).join(".")};class p extends Error{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}}class T{constructor(e,t,n){if(this.rawName=e,this.description=t,this.config=Object.assign({},n),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=v(e).split(",").map((s)=>{let i=s.trim().replace(/^-{1,2}/,"");if(i.startsWith("no-"))this.negated=!0,i=i.replace(/^no-/,"");return j(i)}).sort((s,i)=>s.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 P=process.argv,W=`${process.platform}-${process.arch} node-${process.version}`;class ${constructor(e,t,n={},s){this.rawName=e,this.description=t,this.config=n,this.cli=s,this.options=[],this.aliasNames=[],this.name=v(e),this.args=L(e),this.examples=[]}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,n){let s=new T(e,t,n);return this.options.push(s),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}isMatched(e){return this.name===e||this.aliasNames.includes(e)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof k}hasOption(e){return e=e.split(".")[0],this.options.find((t)=>{return t.names.includes(e)})}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:n,options:s,helpCallback:i}=this.cli.globalCommand,a=[{body:`${e}${n?`/${n}`:""}`}];if(a.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let o=E(t.map((l)=>l.rawName));a.push({title:"Commands",body:t.map((l)=>{return` ${V(l.rawName,o.length)} ${l.description}`}).join(`
2
- `)}),a.push({title:"For more info, run any command with the `--help` flag",body:t.map((l)=>` $ ${e}${l.name===""?"":` ${l.name}`} --help`).join(`
3
- `)})}let h=this.isGlobalCommand?s:[...this.options,...s||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)h=h.filter((o)=>o.name!=="version");if(h.length>0){let o=E(h.map((l)=>l.rawName));a.push({title:"Options",body:h.map((l)=>{return` ${V(l.rawName,o.length)} ${l.description} ${l.config.default===void 0?"":`(default: ${l.config.default})`}`}).join(`
4
- `)})}if(this.examples.length>0)a.push({title:"Examples",body:this.examples.map((o)=>{if(typeof o==="function")return o(e);return o}).join(`
5
- `)});if(i)a=i(a)||a;console.log(a.map((o)=>{return o.title?`${o.title}:
6
- ${o.body}`:o.body}).join(`
7
-
8
- `))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;if(t)console.log(`${e}/${t} ${W}`)}checkRequiredArgs(){let e=this.args.filter((t)=>t.required).length;if(this.cli.args.length<e)throw new p(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let n of Object.keys(e))if(n!=="--"&&!this.hasOption(n)&&!t.hasOption(n))throw new p(`Unknown option \`${n.length>1?`--${n}`:`-${n}`}\``)}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,n=[...t.options,...this.options];for(let s of n){let i=e[s.name.split(".")[0]];if(s.required){let a=n.some((r)=>r.negated&&r.names.includes(s.name));if(i===!0||i===!1&&!a)throw new p(`option \`${s.rawName}\` value is missing`)}}}}class k extends ${constructor(e){super("@@global@@","",{},e)}}var b=Object.assign;class A extends R{constructor(e=""){super();this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new k(this),this.globalCommand.usage("<command> [options]")}usage(e){return this.globalCommand.usage(e),this}command(e,t,n){let s=new $(e,t||"",n,this);return s.globalCommand=this.globalCommand,this.commands.push(s),s}option(e,t,n){return this.globalCommand.option(e,t,n),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},n,s){if(this.args=e,this.options=t,n)this.matchedCommand=n;if(s)this.matchedCommandName=s;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(e=P,{run:t=!0}={}){if(this.rawArgs=e,!this.name)this.name=e[1]?x(e[1]):"cli";let n=!0;for(let i of this.commands){let a=this.mri(e.slice(2),i),r=a.args[0];if(i.isMatched(r)){n=!1;let h=b(b({},a),{args:a.args.slice(1)});this.setParsedInfo(h,i,r),this.emit(`command:${r}`,i)}}if(n){for(let i of this.commands)if(i.name===""){n=!1;let a=this.mri(e.slice(2),i);this.setParsedInfo(a,i),this.emit("command:!",i)}}if(n){let i=this.mri(e.slice(2));this.setParsedInfo(i)}if(this.options.help&&this.showHelpOnExit)this.outputHelp(),t=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),t=!1,this.unsetMatchedCommand();let s={args:this.args,options:this.options};if(t)this.runMatchedCommand();if(!this.matchedCommand&&this.args[0])this.emit("command:*");return s}mri(e,t){let n=[...this.globalCommand.options,...t?t.options:[]],s=M(n),i=[],a=e.indexOf("--");if(a>-1)i=e.slice(a+1),e=e.slice(0,a);let r=G(e,s);r=Object.keys(r).reduce((c,u)=>{return b(b({},c),{[j(u)]:r[u]})},{_:[]});let h=r._,o={"--":i},l=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,m=Object.create(null);for(let c of n){if(!l&&c.config.default!==void 0)for(let u of c.names)o[u]=c.config.default;if(Array.isArray(c.config.type)){if(m[c.name]===void 0)m[c.name]=Object.create(null),m[c.name].shouldTransform=!0,m[c.name].transformFunction=c.config.type[0]}}for(let c of Object.keys(r))if(c!=="_"){let u=c.split(".");y(o,u,r[c]),F(o,m)}return{args:h,options:o}}runMatchedCommand(){let{args:e,options:t,matchedCommand:n}=this;if(!n||!n.commandAction)return;n.checkUnknownOptions(),n.checkOptionValue(),n.checkRequiredArgs();let s=[];return n.args.forEach((i,a)=>{if(i.variadic)s.push(e.slice(a));else s.push(e[a])}),s.push(t),n.commandAction.apply(this,s)}}var f=new A("rpx");f.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("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").action(async(e)=>{if(!e?.from||!e.to)return U(d);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};if(e.startCommand){let n={command:e.startCommand};if(e.startCwd)n.cwd=e.startCwd;if(e.startEnv)try{n.env=JSON.parse(e.startEnv)}catch(s){console.error("Failed to parse start-env JSON:",s),g.exit(1)}t.start=n}return B(t)});f.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{let n=q(d)?d.proxies.find((s)=>s.to===e||`${s.from}-${s.to}`===e):d.to===e?d:null;if(!n?.start)console.error(`No watch configuration found for proxy: ${e}`),g.exit(1);try{await O.startProcess(e,n.start,t.verbose),console.log(`Started dev server for ${e}`)}catch(s){console.error(`Failed to start dev server for ${e}:`,s),g.exit(1)}});f.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{try{await O.stopProcess(e,t.verbose),console.log(`Stopped dev server for ${e}`)}catch(n){console.error(`Failed to stop dev server for ${e}:`,n),g.exit(1)}});f.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(e)=>{try{await O.stopAll(e.verbose),console.log("Stopped all dev servers")}catch(t){console.error("Failed to stop all dev servers:",t),g.exit(1)}});f.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(N)});f.version(N);f.help();f.parse();
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ #!/usr/bin/env bun
4
+ import{createRequire as bF}from"node:module";var xF=Object.defineProperty;var PF=($)=>$;function iF($,w){this[$]=PF.bind(null,w)}var G8=($,w)=>{for(var A in w)xF($,A,{get:w[A],enumerable:!0,configurable:!0,set:iF.bind(w,A)})};var Wh=($,w)=>()=>($&&(w=$($=0)),w);var i=bF(import.meta.url);import{existsSync as mE,statSync as dE}from"fs";import{existsSync as VY,mkdirSync as dT,readdirSync as gT,writeFileSync as lT}from"fs";import{homedir as mw}from"os";import{dirname as gE,resolve as Q$}from"path";import e0 from"process";import{join as tT,relative as pT,resolve as lE}from"path";import OJ from"process";import{existsSync as DW,mkdirSync as UK,readdirSync as YK,writeFileSync as fK}from"fs";import{homedir as FY}from"os";import{dirname as WK,resolve as k$}from"path";import M1 from"process";import{join as rT,relative as aT,resolve as tE}from"path";import _J from"process";import{existsSync as VW,mkdirSync as HK,readdirSync as TK,writeFileSync as GK}from"fs";import{dirname as RK,resolve as XJ}from"path";import OY from"process";import{Buffer as l0}from"buffer";import{createCipheriv as sT,createDecipheriv as oT,randomBytes as BY}from"crypto";import{closeSync as jY,createReadStream as pE,createWriteStream as eT,existsSync as zY,fsyncSync as rE,openSync as aE,writeFileSync as $G}from"fs";import{access as wG,constants as sE,mkdir as AG,readdir as zJ,rename as oE,stat as dw,unlink as HJ,writeFile as HY}from"fs/promises";import{join as gw}from"path";import I$ from"process";import{pipeline as JG}from"stream/promises";import{createGzip as eE}from"zlib";import lw from"process";import Q0 from"process";import{Buffer as X0}from"buffer";import{createCipheriv as hG,createDecipheriv as UG,randomBytes as TY}from"crypto";import{closeSync as GY,createReadStream as $W,createWriteStream as YG,existsSync as TJ,fsyncSync as wW,openSync as AW,writeFileSync as fG}from"fs";import{access as ZG,constants as JW,mkdir as EG,readdir as GJ,rename as hW,stat as tw,unlink as qJ,writeFile as qY}from"fs/promises";import{isAbsolute as WG,join as pw,resolve as FG}from"path";import V from"process";import{pipeline as BG}from"stream/promises";import{createGzip as UW}from"zlib";import rw from"process";import x0 from"process";import RJ from"process";import{existsSync as NJ}from"fs";import{resolve as RY}from"path";import{existsSync as jG}from"fs";import{existsSync as zG,readdirSync as HG}from"fs";import{extname as NY,resolve as YW}from"path";import TG from"process";import{join as G2,relative as q2,resolve as qW}from"path";import cJ from"process";import{Buffer as k0}from"buffer";import{createCipheriv as K2,createDecipheriv as M2,randomBytes as LY}from"crypto";import{closeSync as CY,createReadStream as RW,createWriteStream as y2,existsSync as MJ,fsyncSync as NW,openSync as KW,writeFileSync as I2}from"fs";import{access as L2,constants as MW,mkdir as C2,readdir as yJ,rename as yW,stat as aw,unlink as IJ,writeFile as SY}from"fs/promises";import{isAbsolute as S2,join as sw,resolve as D2}from"path";import O from"process";import{pipeline as V2}from"stream/promises";import{createGzip as IW}from"zlib";import ow from"process";import P0 from"process";function uT($,w){this[$]=nT.bind(null,w)}class nY{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let h=this.generateKey($,A),U=J??this.options.ttl,Y=this.estimateSize(w);this.cache.set(h,{value:w,timestamp:new Date,ttl:U,hits:0,size:Y}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!mE($))return!0;return dE($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let h=mE(A)?dE(A):null,U=h?h.mtime:new Date;this.set($,{value:w,fileTimestamp:U},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,h)=>J+h.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class uY{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),h=new Date;try{let U=await w(),Y=performance.now()-J;return this.recordMetric({operation:$,duration:Y,timestamp:h,...A}),U}catch(U){let Y=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:Y,timestamp:h,...A}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((h)=>h.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((h)=>h.duration),J=A.reduce((h,U)=>h+U,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function GG($,w={}){let J=Object.keys(w).sort().map((h)=>`${h}:${w[h]}`).join("|");return J?`${$}:${J}`:$}function qG($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function RG($){return $.getStats().size*2}function vY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&r(w[0])&&"id"in w[0]&&w[0].id===3&&r(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(r(w)&&r($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(r($)&&"arr"in $&&Array.isArray($.arr)&&r(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&r(w[0])&&r($[0])){let J=[...w];for(let h of $)if(r(h)&&"name"in h){if(!J.find((Y)=>r(Y)&&("name"in Y)&&Y.name===h.name))J.push(h)}else if(r(h)&&"path"in h){if(!J.find((Y)=>r(Y)&&("path"in Y)&&Y.path===h.path))J.push(h)}else if(!J.some((U)=>kJ(U,h)))J.push(h);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}if(!r(w)||!r($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let h=w[J];if(h===null||h===void 0)continue;else if(r(h)&&r(A[J]))A[J]=vY(A[J],h);else if(Array.isArray(h)&&Array.isArray(A[J]))if(h.length>0&&A[J].length>0&&r(h[0])&&r(A[J][0])){let U=[...h];for(let Y of A[J])if(r(Y)&&"name"in Y){if(!U.find((f)=>r(f)&&("name"in f)&&f.name===Y.name))U.push(Y)}else if(r(Y)&&"path"in Y){if(!U.find((f)=>r(f)&&("path"in f)&&f.path===Y.path))U.push(Y)}else if(!U.some((Z)=>kJ(Z,Y)))U.push(Y);A[J]=U}else if(h.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...h];for(let Y of A[J])if(!U.includes(Y))U.push(Y);A[J]=U}else A[J]=h;else A[J]=h}return A}function kJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!kJ($[A],w[A]))return!1;return!0}if(r($)&&r(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!kJ($[h],w[h]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function NG($,w){if(!VW($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return vY(w,J)}catch{return null}}catch{return null}}async function KG({name:$="",cwd:w,defaultConfig:A}){let J=w||OY.cwd(),h=[".ts",".js",".mjs",".cjs",".json"],U=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Y of U)for(let Z of h){let f=XJ(J,`${Y}${Z}`),E=await NG(f,A);if(E!==null)return E}try{let Y=XJ(J,"package.json");if(VW(Y)){let f=(await import(Y))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return vY(A,f)}catch{}}}catch{}return A}function MG($,w={}){let A=_J.cwd();while(A.includes("storage"))A=tE(A,"..");let J=tE(A,$||"");if(w?.relative)return aT(_J.cwd(),J);return J}async function yG(){try{let $=await KG({name:"clarity",defaultConfig:CJ,cwd:_J.cwd(),endpoint:"",headers:{}});return{...CJ,...$}}catch{return CJ}}function $$(){if(Q0.env.NODE_ENV==="test"||Q0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function IG(){if(Q0.env.NODE_ENV==="test"||Q0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Q0<"u"){let $=Q0.type;if($==="renderer"||$==="worker")return!1;return!!(Q0.versions&&(Q0.versions.node||Q0.versions.bun))}return!1}class OW{async format($){let w=await IG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:lw.pid,hostname:w(),environment:lw.env.NODE_ENV||"development",platform:lw.platform,version:lw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:lw.env.NODE_ENV||lw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class QJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...XY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new OW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??I$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let h=this.generateKeyId(),U=this.generateKey();this.currentKeyId=h,this.keys.set(h,U),this.encryptionKeys.set(h,{key:U,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...SJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...SJ};return{...SJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:XY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let h,U=0,Y=3,Z=1000;while(U<Y)try{try{try{await wG(this.config.logDirectory,sE.F_OK|sE.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await AG(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:l0.from($);try{if(!zY(this.currentLogFile))await HY(this.currentLogFile,"",{mode:420});if(h=aE(this.currentLogFile,"a",420),$G(h,f,{flag:"a"}),rE(h),h!==void 0)jY(h),h=void 0;if((await dw(this.currentLogFile)).size===0){if(await HY(this.currentLogFile,f,{flag:"w",mode:420}),(await dw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(U<Y-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,F);let j=Z*2**U;await new Promise((B)=>setTimeout(B,j)),U++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(h!==void 0)try{jY(h)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(U===Y-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}U++;let E=Z*2**(U-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(h){throw console.error("Debug: [writeToFile] Error in operation:",h),h}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return gw(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 gw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return gw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if($$())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((h)=>{console.error("Error rotating keys:",h)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let h=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Y=Math.max(1,U);if(h.length>Y)for(let[Z]of h.slice(Y))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return BY(16).toString("hex")}generateKey(){return BY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=BY(16),J=sT("aes-256-gcm",w,A),h=l0.concat([J.update($,"utf8"),J.final()]),U=J.getAuthTag();return{encrypted:l0.concat([A,h,U]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=eE(),h=[];J.on("data",(U)=>h.push(U)),J.on("end",()=>w(l0.from(l0.concat(h)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if($$())return;let $=await dw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let h=await zJ(this.config.logDirectory),U=h.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),Y=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${Y}`;if(await dw(A).catch(()=>null))try{if(await oE(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await HJ(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(U.length===0&&!h.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await HY(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let h=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${h}.log`);if(await dw(A).catch(()=>null))await oE(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await zJ(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,Z)=>Z.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await HJ(gw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=pE($),J=eT(w),h=eE();await JG(A,h,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),zY(this.currentLogFile))try{let $=aE(this.currentLogFile,"r+");rE($),jY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!$$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await zJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await HJ(gw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:h,level:U,showTimestamp:Y=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(Y)B.push(w);if(U==="warning")B.push("WARN");else if(U==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(h),B.join(" ")}let f=I$.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${h}`;else if(U==="info"||U==="success")E=`${A} ${J} ${h}`;else E=`${A} ${J} ${g.cyan(h)}`;if(!Y)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Y)=>{let Z=Number.parseInt(Y,10);return Z<w[0].length?String(w[0][Z]):U});let A=/%([sdijfo%])/g,J=0,h=$.replace(A,(U,Y)=>{if(Y==="%")return"%";if(J>=w.length)return U;let Z=w[J++];switch(Y){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return U}});if(J<w.length)h+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return h}async log($,w,...A){let J=new Date,h=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Y,Z;if(w instanceof Error)Y=w.message,Z=w.stack;else Y=this.formatMessage(w,A);if(this.fancy&&!$$()){let E=nW[$],W=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:g.gray(Y),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:Y,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:g.green(Y),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:Y,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:Y,level:$}),console.error(F),Z){let j=Z.split(`
5
+ `);for(let B of j)if(B.trim()&&!B.includes(Y))console.error(this.formatConsoleMessage({timestamp:h,message:g.gray(` ${B}`),level:$,showTimestamp:!1}))}break}}else if(!$$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Y}`),Z)console.error(Z)}if(!this.shouldLog($))return;let f=`${U} ${this.environment}.${$.toUpperCase()}: ${Y}
6
+ `;if(Z)f+=`${Z}
7
+ `;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!$$()){let A=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:g.blue("◐"),tag:A,message:`${g.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),h=Math.round(J-w),U=`${$} completed in ${h}ms`,Y=new Date,Z=this.formatConsoleTimestamp(Y),E=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
8
+ `,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!$$()){let W=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:g.green("✓"),tag:W,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!$$())console.error(E.trim());await this.writeToFile(E)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new QJ(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if($$())throw Error("createReadStream is not supported in browser environments");if(!zY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return pE(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=l0.isBuffer($)?$:l0.from($,"base64"),h=J.slice(0,16),U=J.slice(-16),Y=J.slice(16,-16),Z=oT("aes-256-gcm",A,h);return Z.setAuthTag(U),l0.concat([Z.update(Y),Z.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return $$()}isServerMode(){return!$$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w);if(this.fancy&&!$$()){let U=$.split(`
9
+ `),Y=Math.max(...U.map((W)=>W.length))+2,Z=`┌${"─".repeat(Y)}┐`,f=`└${"─".repeat(Y)}┘`,E=U.map((W)=>{let F=" ".repeat(Y-W.length-2);return`│ ${W}${F} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:g.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(Z)})),E.forEach((W)=>console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(W),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(f),showTimestamp:!1}))}else if(!$$())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let h=`${J} ${this.environment}.INFO: [BOX] ${$}
10
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(h)}async prompt($){if($$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${g.cyan("?")} ${$} (y/n) `);let A=(J)=>{let h=J.toString().trim().toLowerCase();I$.stdin.removeListener("data",A);try{if(typeof I$.stdin.setRawMode==="function")I$.stdin.setRawMode(!1)}catch{}I$.stdin.pause(),console.error(""),w(h==="y"||h==="yes")};try{if(typeof I$.stdin.setRawMode==="function")I$.stdin.setRawMode(!0)}catch{}I$.stdin.resume(),I$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let Y=/%([sdijfo%])/g,Z=0;if(A=$.replace(Y,(f,E)=>{if(E==="%")return"%";if(Z>=w.length)return f;let W=w[Z++];switch(E){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return f}}),Z<w.length)A+=` ${w.slice(Z).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!$$()){let Y=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",Z=g.blue("◐");console.error(`${Z} ${Y} ${g.cyan(A)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
11
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}progress($,w=""){if(!this.enabled||!this.fancy||$$()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(Y,Z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,Y)),Z!==void 0)this.activeProgressBar.message=Z;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(Y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Y!==void 0)this.activeProgressBar.message=Y;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Y,Z="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;I$.stdout.write(`${"\r".padEnd(I$.stdout.columns||80)}\r`),this.log(Z,Y),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||$$()||!I$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),h=$.barLength-J,U=g.green("━".repeat(J)),Y=g.gray("━".repeat(h)),Z=`[${U}${Y}]`,f=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",W=w||A===100?g.green("✓"):g.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",j=`\r${W}${F} ${Z} ${f}${E}`,B=I$.stdout.columns||80,T=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,I$.stdout.write($.lastRenderedLine),w)I$.stdout.write(`
12
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||$$()||!I$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if($$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await zJ(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=gw(this.config.logDirectory,J);if($.before)try{if((await dw(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await HJ(J),console.warn(`Deleted log file: ${J}`)}catch(h){console.error(`Failed to delete log file ${J}:`,h)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function LJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&v(w[0])&&"id"in w[0]&&w[0].id===3&&v(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(v(w)&&v($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(v($)&&"arr"in $&&Array.isArray($.arr)&&v(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&v(w[0])&&v($[0])){let J=[...w];for(let h of $)if(v(h)&&"name"in h){if(!J.find((Y)=>v(Y)&&("name"in Y)&&Y.name===h.name))J.push(h)}else if(v(h)&&"path"in h){if(!J.find((Y)=>v(Y)&&("path"in Y)&&Y.path===h.path))J.push(h)}else if(!J.some((U)=>xJ(U,h)))J.push(h);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}if(!v(w)||!v($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let h=w[J];if(h===null||h===void 0)continue;else if(v(h)&&v(A[J]))A[J]=LJ(A[J],h);else if(Array.isArray(h)&&Array.isArray(A[J]))if(h.length>0&&A[J].length>0&&v(h[0])&&v(A[J][0])){let U=[...h];for(let Y of A[J])if(v(Y)&&"name"in Y){if(!U.find((f)=>v(f)&&("name"in f)&&f.name===Y.name))U.push(Y)}else if(v(Y)&&"path"in Y){if(!U.find((f)=>v(f)&&("path"in f)&&f.path===Y.path))U.push(Y)}else if(!U.some((Z)=>xJ(Z,Y)))U.push(Y);A[J]=U}else if(h.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...h];for(let Y of A[J])if(!U.includes(Y))U.push(Y);A[J]=U}else A[J]=h;else A[J]=h}return A}function mY($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:LJ($,w);if(Array.isArray($))return A==="replace"?w:LJ($,w);if(!v(w)||!v($))return w;let J={...$};for(let h of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,h))continue;let U=w[h],Y=J[h];if(U===null||U===void 0)continue;if(Array.isArray(U)||Array.isArray(Y))if(A==="replace")J[h]=U;else J[h]=LJ(Y,U);else if(v(U)&&v(Y))J[h]=mY(Y,U,A);else J[h]=U}return J}function xJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!xJ($[A],w[A]))return!1;return!0}if(v($)&&v(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!xJ($[h],w[h]))return!1}return!0}return!1}function v($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function KJ($,w,A="replace"){if(!DW($))return null;try{let J=await import($),h=J.default||J;if(typeof h!=="object"||h===null||Array.isArray(h))return null;try{return mY(w,h,A)}catch{return null}}catch{return null}}function LG($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),h={...w};function U(Y,Z=[]){let f={...Y};for(let[E,W]of Object.entries(Y)){let F=[...Z,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),B=`${J}_${F.map(j).join("_")}`,T=`${J}_${F.map((H)=>H.toUpperCase()).join("_")}`;if(A)C$.info(`Checking environment variable ${B} for config ${$}.${F.join(".")}`);if(typeof W==="object"&&W!==null&&!Array.isArray(W))f[E]=U(W,F);else{let H=M1.env[B]||M1.env[T];if(H!==void 0){if(A)C$.info(`Using environment variable ${H?B:T} for config ${$}.${F.join(".")}`);if(typeof W==="number")f[E]=Number(H);else if(typeof W==="boolean")f[E]=H.toLowerCase()==="true";else if(Array.isArray(W))try{let q=JSON.parse(H);if(Array.isArray(q))f[E]=q;else f[E]=H.split(",").map((G)=>G.trim())}catch{f[E]=H.split(",").map((q)=>q.trim())}else f[E]=H}}}return f}return U(h)}async function CG({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:h,verbose:U=!1,checkEnv:Y=!0,arrayStrategy:Z="replace"}){let f=Y&&typeof h==="object"&&h!==null&&!Array.isArray(h)?LG($,h,U):h,E=A||M1.cwd(),W=[".ts",".js",".mjs",".cjs",".json"];if(U)C$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let F=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),B=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,k$(E,"config"),k$(E,".config"),J?k$(E,J):void 0].filter(Boolean)));for(let q of H){if(U)C$.info(`Searching for configuration in: ${q}`);let R=[k$(E,"config"),k$(E,".config")].concat(J?[k$(E,J)]:[]).includes(q)?[...F,...j,...B,...T]:[...j,...F,...T,...B];for(let y of R)for(let L of W){let C=k$(q,`${y}${L}`),K=await KJ(C,f,Z);if(K!==null){if(U)C$.success(`Configuration loaded from: ${C}`);return K}}}if($){let q=k$(FY(),".config",$),G=["config",`${$}.config`];if(w)G.push(`${w}.config`);if(U)C$.info(`Checking user config directory: ${q}`);for(let R of G)for(let y of W){let L=k$(q,`${R}${y}`),C=await KJ(L,f,Z);if(C!==null){if(U)C$.success(`Configuration loaded from user config directory: ${L}`);return C}}}if($){let q=k$(FY(),".config"),G=[`.${$}.config`];if(w)G.push(`.${w}.config`);if(U)C$.info(`Checking user config directory for dotfile configs: ${q}`);for(let R of G)for(let y of W){let L=k$(q,`${R}${y}`),C=await KJ(L,f,Z);if(C!==null){if(U)C$.success(`Configuration loaded from user config directory dotfile: ${L}`);return C}}}if($){let q=FY(),G=[`.${$}.config`,`.${$}`];if(w)G.push(`.${w}.config`),G.push(`.${w}`);if(U)C$.info(`Checking user home directory for dotfile configs: ${q}`);for(let R of G)for(let y of W){let L=k$(q,`${R}${y}`),C=await KJ(L,f,Z);if(C!==null){if(U)C$.success(`Configuration loaded from user home directory: ${L}`);return C}}}try{let q=k$(E,"package.json");if(DW(q)){let G=await import(q),R=G[$];if(!R&&w){if(R=G[w],R&&U)C$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(U)C$.success(`Configuration loaded from package.json: ${R===G[$]?$:w}`);return mY(f,R,Z)}catch(y){if(U)C$.warn("Failed to merge package.json config:",y)}}}catch(q){if(U)C$.warn("Failed to load package.json:",q)}if(U)C$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function SG($,w={}){let A=OJ.cwd();while(A.includes("storage"))A=lE(A,"..");let J=lE(A,$||"");if(w?.relative)return pT(OJ.cwd(),J);return J}async function DG(){try{let $=await CG({name:"clarity",alias:"logging",defaultConfig:DJ,cwd:OJ.cwd()});return{...DJ,...$||{}}}catch{return DJ}}function E$(){if(x0.env.NODE_ENV==="test"||x0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function VG(){if(x0.env.NODE_ENV==="test"||x0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof x0<"u"){let $=x0.type;if($==="renderer"||$==="worker")return!1;return!!(x0.versions&&(x0.versions.node||x0.versions.bun))}return!1}class _W{async format($){let w=await VG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:rw.pid,hostname:w(),environment:rw.env.NODE_ENV||"development",platform:rw.platform,version:rw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:rw.env.NODE_ENV||rw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class PJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...kY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new _W,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??V.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let h=this.generateKeyId(),U=this.generateKey();this.currentKeyId=h,this.keys.set(h,U),this.encryptionKeys.set(h,{key:U,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...VJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...VJ};return{...VJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:kY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!E$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let h,U=0,Y=3,Z=1000;while(U<Y)try{try{try{await ZG(this.config.logDirectory,JW.F_OK|JW.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await EG(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:X0.from($);try{if(!TJ(this.currentLogFile))await qY(this.currentLogFile,"",{mode:420});if(h=AW(this.currentLogFile,"a",420),fG(h,f,{flag:"a"}),wW(h),h!==void 0)GY(h),h=void 0;if((await tw(this.currentLogFile)).size===0){if(await qY(this.currentLogFile,f,{flag:"w",mode:420}),(await tw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(U<Y-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,F);let j=Z*2**U;await new Promise((B)=>setTimeout(B,j)),U++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(h!==void 0)try{GY(h)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(U===Y-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}U++;let E=Z*2**(U-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(h){throw console.error("Debug: [writeToFile] Error in operation:",h),h}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return pw(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 pw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return pw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(E$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((h)=>{console.error("Error rotating keys:",h)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let h=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Y=Math.max(1,U);if(h.length>Y)for(let[Z]of h.slice(Y))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return TY(16).toString("hex")}generateKey(){return TY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=TY(16),J=hG("aes-256-gcm",w,A),h=X0.isBuffer($)?$:X0.from($,"utf8"),U=J.update(h),Y=J.final(),Z=U.length+Y.length,f=J.getAuthTag(),E=X0.allocUnsafe(16+Z+16);return A.copy(E,0),U.copy(E,16),Y.copy(E,16+U.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=UW(),h=[];J.on("data",(U)=>h.push(U)),J.on("end",()=>w(X0.from(X0.concat(h)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(E$())return;if(!this.shouldWriteToFile())return;let $=await tw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let h=await GJ(this.config.logDirectory),U=h.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),Y=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${Y}`;if(await tw(A).catch(()=>null))try{if(await hW(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await qJ(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(U.length===0&&!h.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await qY(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let h=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${h}.log`);if(await tw(A).catch(()=>null))await hW(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await GJ(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,Z)=>Z.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await qJ(pw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=$W($),J=YG(w),h=UW();await BG(A,h,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),TJ(this.currentLogFile))try{let $=AW(this.currentLogFile,"r+");wW($),GY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!E$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await GJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await qJ(pw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?k.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E$())return!1;let $=typeof V.env.NO_COLOR<"u",w=V.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof V.stderr<"u"&&V.stderr.isTTY||typeof V.stdout<"u"&&V.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:h,level:U,showTimestamp:Y=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(Y)B.push(w);if(U==="warning")B.push("WARN");else if(U==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(h),B.join(" ")}let f=V.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${h}`;else if(U==="info"||U==="success")E=`${A} ${J} ${h}`;else E=`${A} ${J} ${k.cyan(h)}`;if(!Y)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Y)=>{let Z=Number.parseInt(Y,10);return Z<w[0].length?String(w[0][Z]):U});let A=/%([sdijfo%])/g,J=0,h=$.replace(A,(U,Y)=>{if(Y==="%")return"%";if(J>=w.length)return U;let Z=w[J++];switch(Y){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return U}});if(J<w.length)h+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return h}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,h)=>{let U=k.underline(k.blue(J)),Y=this.toAbsoluteFilePath(h);if(Y&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(Y)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${h}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),w=w.replace(/`([^`]+)`/g,(A,J)=>k.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>k.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>k.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>k.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>k.strikethrough(J)),w}supportsHyperlinks(){if(E$())return!1;let $=V.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=V.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(WG(w)||w.startsWith("./")||w.startsWith("../"))w=FG(w);else return null;return TJ(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,h=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Y,Z;if(w instanceof Error)Y=w.message,Z=w.stack;else Y=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":uW[$],j=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:k.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:k.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
13
+ `);for(let H of T)if(H.trim()&&!H.includes(Y))console.error(this.formatConsoleMessage({timestamp:h,message:k.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!E$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Y}`),Z)console.error(Z)}if(!this.shouldLog($))return;let W=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
14
+ `;if(Z)W+=`${Z}
15
+ `;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress($,w=""){let A={update:(Z,f)=>{},finish:(Z)=>{},interrupt:(Z,f)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!E$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Z,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Z),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!E$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Z)},interrupt:(Z,f="info")=>{if(!E$()&&V.stdout.isTTY)V.stdout.write(`
16
+ `);if(this[f==="warning"?"warn":f](Z),this.activeProgressBar&&this.shouldStyleConsole()&&!E$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":k.blue("◐"),tag:A,message:`${k.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),h=Math.round(J-w),U=`${$} completed in ${h}ms`,Y=new Date,Z=this.formatConsoleTimestamp(Y),E=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
17
+ `,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":k.green("✓"),tag:W,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!E$())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new PJ(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(E$())throw Error("createReadStream is not supported in browser environments");if(!TJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $W(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=X0.isBuffer($)?$:X0.from($,"base64"),h=J.subarray(0,16),U=J.subarray(J.length-16),Y=J.subarray(16,J.length-16),Z=UG("aes-256-gcm",A,h);Z.setAuthTag(U);let f=Z.update(Y),E=Z.final(),W=f.length+E.length,F=X0.allocUnsafe(W);return f.copy(F,0),E.copy(F,f.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return E$()}isServerMode(){return!E$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:h,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=h.split(`
18
+ `),f=Math.max(...Z.map((j)=>j.length))+2,E=`┌${"─".repeat(f)}┐`,W=`└${"─".repeat(f)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:k.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:k.cyan(E),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:k.cyan(W),showTimestamp:!1}))}else if(!E$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Y=`${J} ${this.environment}.INFO: [BOX] ${U}
19
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}async prompt($){if(E$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${k.cyan("?")} ${$} (y/n) `);let A=(J)=>{let h=J.toString().trim().toLowerCase();V.stdin.removeListener("data",A);try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!1)}catch{}V.stdin.pause(),console.error(""),w(h==="y"||h==="yes")};try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!0)}catch{}V.stdin.resume(),V.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,E=0;if(A=$.replace(f,(W,F)=>{if(F==="%")return"%";if(E>=w.length)return W;let j=w[E++];switch(F){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return W}}),E<w.length)A+=` ${w.slice(E).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:J,fileText:h}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${k.blue("◐")} `;console.error(`${E}${f} ${k.cyan(J)}`)}let Z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${h}
20
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!V.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),h=$.barLength-J,U=k.green("━".repeat(J)),Y=k.gray("━".repeat(h)),Z=`[${U}${Y}]`,f=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",W=this.options.showIcons===!1?"":w||A===100?k.green("✓"):k.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",j=`\r${W}${F} ${Z} ${f}${E}`,B=V.stdout.columns||80,T=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,V.stdout.write($.lastRenderedLine),w)V.stdout.write(`
21
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||E$()||!V.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(E$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await GJ(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=pw(this.config.logDirectory,J);if($.before)try{if((await tw(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await qJ(J),console.warn(`Deleted log file: ${J}`)}catch(h){console.error(`Failed to delete log file ${J}:`,h)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function XW($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:h=()=>!0,fallback:U}=w,Y=Error("Unknown error occurred");for(let Z=0;Z<=A;Z++)try{return await $()}catch(f){if(Y=f instanceof Error?f:Error(String(f)),Z===A||!h(Y))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(U!==void 0)return U;throw Y instanceof Error?Y:Error(`Unknown error: ${String(Y)}`)}function kW($){return $ instanceof d$}function OG($){return $ instanceof iJ}function _G($){if(kW($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((A)=>$.message.toLowerCase().includes(A.toLowerCase()))}class uJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:J,useCamelCase:h=!0,useBackwardCompatibility:U=!0,customParsers:Y={},verbose:Z=!1,trackPerformance:f=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let W=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],W,{useCamelCase:h,useBackwardCompatibility:U,customParsers:Y,verbose:Z,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return L1.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[h,U]of Object.entries($)){let Y=[...w,h],Z=Y.map((W)=>this.formatEnvKey(W,J.useCamelCase)),f=`${A}_${Z.join("_")}`,E=J.useBackwardCompatibility?`${A}_${Y.map((W)=>W.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Y,A,J);else{let W=RJ.env[f]||(E?RJ.env[E]:void 0);if(W!==void 0){if(J.verbose){let F=RJ.env[f]?f:E}try{$[h]=this.parseEnvironmentValue(W,typeof U,f,J.customParsers,J.configName)}catch(F){if(F instanceof bJ)throw F;throw t0.envVar(f,W,typeof U,J.configName)}}}}}parseEnvironmentValue($,w,A,J,h){for(let[U,Y]of Object.entries(J))try{return Y($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,w))try{return U.parse($)}catch{throw t0.envVar(A,$,`${w} (via ${U.name} parser)`,h)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,h]of Object.entries(RJ.env))if(J.startsWith(A)&&h!==void 0)w[J]=h;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(h){J.push(`Cannot parse value "${w}" as ${A}: ${h}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:h="text"}=A,U=J||this.generateEnvPrefix($),Y=[];switch(this.extractEnvVarInfo(w,[],U,Y),h){case"markdown":return this.formatAsMarkdown(Y,$);case"json":return JSON.stringify(Y,null,2);default:return this.formatAsText(Y,$)}}extractEnvVarInfo($,w,A,J){for(let[h,U]of Object.entries($)){let Y=[...w,h],Z=`${A}_${Y.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Y,A,J);else J.push({key:Z,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Y.join(".")}`,example:this.generateExample(U)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
22
+
23
+ `;for(let J of $)A+=`${J.key}
24
+ `,A+=` Type: ${J.type}
25
+ `,A+=` Description: ${J.description}
26
+ `,A+=` Example: ${J.example}
27
+
28
+ `;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
29
+
30
+ `;A+=`| Variable | Type | Description | Example |
31
+ `,A+=`|----------|------|-------------|----------|
32
+ `;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
33
+ `;return A}}function XG($,w){let A=bW("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function QW($,w,A={}){return xW($,w,A,new WeakMap)}function xW($,w,A,J){let{arrayMergeMode:h="replace",skipNullish:U=!1,customMerger:Y}=A;if(w===null||w===void 0)return U?$:w;if(Y){let Z=Y($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return PW($,w,h,J);if(!$0(w)||!$0($))return w;return PG($,w,A,J)}function PW($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return kG($,w);case"smart":return QG($,w,J);default:return w}return w}function kG($,w){let A=[...w];for(let J of $)if(!A.some((h)=>_Y(h,J)))A.push(J);return A}function QG($,w,A){if(w.length===0)return $;if($.length===0)return w;if($0(w[0])&&$0($[0]))return xG($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}function xG($,w,A){let J=[...w];for(let h of $){if(!$0(h)){J.push(h);continue}let U=["id","name","key","path","type"],Y=!1;for(let Z of U)if(Z in h){if(J.find((E)=>$0(E)&&(Z in E)&&E[Z]===h[Z])){Y=!0;break}}if(!Y)J.push(h)}return J}function PG($,w,A,J){let h=w;if($0(h)&&J.has(h))return J.get(h);let U={...$};if($0(h))J.set(h,U);for(let Y in h){if(!Object.prototype.hasOwnProperty.call(h,Y))continue;let Z=h[Y],f=U[Y];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){U[Y]=Z;continue}if($0(Z)&&$0(f))U[Y]=xW(f,Z,A,J);else if(Array.isArray(Z)||Array.isArray(f))U[Y]=PW(f,Z,A.arrayMergeMode||"smart",J);else U[Y]=Z}return U}function dY($,w,A="replace"){return QW($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function _Y($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!_Y($[A],w[A]))return!1;return!0}if($0($)&&$0(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!_Y($[h],w[h]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class vJ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:h=!0,cacheTtl:U,trackPerformance:Y=!0,verbose:Z=!1}=A;if(h){let E=ew.getWithFileCheck("file",$);if(E){if(Z)console.log(`Configuration loaded from cache: ${$}`);return E}}let f=async()=>{if(!NJ($))return null;try{let E=`?t=${Date.now()}`,W=await import($+E),F=W.default||W,j="default"in W,B=Object.keys(W).length>0;if(!j&&!B)throw new y1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new y1($,Error("Configuration must export a valid object"),"unknown");let q={config:dY(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(h)ew.setWithFileCheck("file",q,$,U);return q}catch(E){throw E instanceof Error?t0.configLoad($,E):t0.configLoad($,Error(String(E)))}};if(Y)return L1.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let h=await this.loadFromPath(J,w,A);if(h)return h}catch(h){if(h instanceof Error&&h.name==="ConfigLoadError")throw h;if(A.verbose)console.warn(`Failed to load config from ${J}:`,h)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),h=[];for(let U of J)for(let Y of this.extensions)h.push(RY(w,`${U}${Y}`));return h}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return XW(async()=>{return NJ($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!NJ($))return J;if(w||A){let h=this.generateNamePatterns(w||"",A);for(let U of h)for(let Y of this.extensions){let Z=RY($,`${U}${Y}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:h}=await import("fs"),U=h($);for(let Y of U)if(this.looksLikeConfigFile(Y)){let Z=RY($,Y);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!NJ($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:h}=await import("fs"),U=h($,"utf8");JSON.parse(U)}catch(h){w.push(`Invalid JSON syntax: ${h}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let h=await this.loadFromPath(J,{},w);if(h)A.set(J,h.config)}catch(h){if(w.verbose)console.warn(`Failed to preload ${J}:`,h)}})),A}}class gY{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:h=!0,validateTypes:U=!0,customRules:Y=[],trackPerformance:Z=!0,verbose:f=!1}=A,E=async()=>{let W=[],F=[],j={stopOnFirstError:J,validateRequired:h,validateTypes:U,customRules:Y,trackPerformance:Z,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...Y],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return W.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:W,warnings:F}}};if(Z)return await L1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!jG(w))throw new I1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),h=J.default||J;if(Array.isArray(h))return this.validateWithRules($,h,A);else return this.validateWithJSONSchema($,h,A)}catch(J){throw new I1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],h=[];return this.validateObjectAgainstSchema($,w,"",J,h,A),{isValid:J.length===0,errors:J,warnings:h}}validateObjectAgainstSchema($,w,A,J,h,U){if(U.validateTypes&&w.type){let Y=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(Y)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${Y}`,expected:Z.join(" or "),actual:Y,rule:"type"}),U.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),U.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let Y=0;Y<$.length;Y++){let Z=A?`${A}[${Y}]`:`[${Y}]`;if(this.validateObjectAgainstSchema($[Y],w.items,Z,J,h,U),U.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Y=$;if(U.validateRequired&&w.required){for(let Z of w.required)if(!(Z in Y)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(w.properties){for(let[Z,f]of Object.entries(w.properties))if(Z in Y){let E=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(Y[Z],f,E,J,h,U),U.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(Y))if(!Z.has(f))h.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],h=[];for(let U of w)try{let Y=this.getValueByPath($,U.path),Z=this.validateWithRule(Y,U,U.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(Y){J.push({path:U.path,message:`Rule validation failed: ${Y}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:h}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let h=Array.isArray($)?"array":typeof $;if(h!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${h}`,expected:w.type,actual:h,rule:"type"})}if(w.min!==void 0){let h=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(h<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:h,rule:"min"})}if(w.max!==void 0){let h=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(h>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:h,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let h=w.validator($);if(h)J.push({path:A,message:w.message||h,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let h of A)if(J&&typeof J==="object"&&h in J)J=J[h];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,h,U,Y]=J;w.push({path:h,required:!U,type:this.mapTypeScriptType(Y)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:mW},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class lY{fileLoader=new vJ;envProcessor=new uJ;validator=new gY;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:h,validate:U,...Y}=$;try{if(A?.enabled){let f=this.checkCache(Y.name||"",Y);if(f)return f}let Z;try{Z=await this.loadConfigurationStrategies(Y,!0,A)}catch(f){let E=Y.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(E)throw f;Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`No configuration file found for "${Y.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let W=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),F=!W&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),j=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(E&&(j||W))throw f;if(F&&(!E||!j))Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(h||U)await this.validateConfiguration(Z.config,h,U,Y.name);if(A?.enabled&&Z)this.cacheResult(Y.name||"",Z,A,Y);if(J?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:Y.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(f);if(J.slowThreshold&&f.duration>J.slowThreshold)W0.warn(`Slow configuration loading detected: ${f.duration}ms for ${Y.name}`);Z.metrics=f}return Z}catch(Z){let f=Date.now()-w;throw W0.error(`Configuration loading failed after ${f}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:h,cwd:U,configDir:Y,defaultConfig:Z,checkEnv:f=!0,arrayStrategy:E="replace",verbose:W=!1}=$,F=U||e0.cwd(),j=[],B=await this.loadLocalConfiguration(J,h,F,Y,Z,E,W,f,A);if(B)return j.push(...this.getLocalSearchPaths(J,h,F,Y)),this.finalizeResult(B,j,f,J,W);let T=await this.loadHomeConfiguration(J,h,Z,E,W,f);if(T)return j.push(...this.getHomeSearchPaths(J,h)),this.finalizeResult(T,j,f,J,W);let H=await this.loadPackageJsonConfiguration(J,h,F,Z,E,W,f);if(H)return j.push(Q$(F,"package.json")),this.finalizeResult(H,j,f,J,W);if(j.push(...this.getAllSearchPaths(J,h,F,Y)),w)throw t0.configNotFound(J,j,h);return{...await this.applyEnvironmentVariables(J,Z,f,W),warnings:[`No configuration file found for "${J}"${h?` or alias "${h}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,h,U,Y,Z,f){let E=Z?K1($,h,Y):h,W=this.getLocalDirectories(A,J);for(let F of W){if(Y)W0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:U,verbose:Y,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(B){if(Y)W0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,h,U){if(!$)return null;let Y=U?K1($,A,h):A,Z=[Q$(mw(),".config",$),Q$(mw(),".config"),mw()];for(let f of Z){if(h)W0.info(`Checking home directory: ${f}`);let E=this.fileLoader.generateConfigPaths($,f,w),W=await this.fileLoader.tryLoadFromPaths(E,Y,{arrayStrategy:J,verbose:h});if(W){if(h)W0.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,w,A,J,h,U,Y){let Z=Y?K1($,J,U):J;try{let f=Q$(A,"package.json");if(!VY(f))return null;let E=await import(f),W=E[$],F=$;if(!W&&w)W=E[w],F=w;if(W&&typeof W==="object"&&!Array.isArray(W)){if(U)W0.success(`Configuration loaded from package.json: ${F}`);return{config:dY(Z,W,h),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(U)W0.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:K1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,h){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let h=[];if(A){let U=A($);if(U)h.push(...U)}if(w){let U=await this.validator.validateConfiguration($,w);if(!U.isValid)h.push(...U.errors.map((Y)=>Y.path?`${Y.path}: ${Y.message}`:Y.message))}if(h.length>0)throw t0.configValidation(J||"unknown",h,J)}checkCache($,w){let A=this.generateCacheKey($,w);return ew.get(A)||null}cacheResult($,w,A,J){let h=this.generateCacheKey($,J);ew.set(h,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,Q$($,"config"),Q$($,".config"),w?Q$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let h=[];return h.push(...this.getLocalSearchPaths($,w,A,J)),h.push(...this.getHomeSearchPaths($,w)),h.push(Q$(A,"package.json")),h}getLocalSearchPaths($,w,A,J){let h=this.getLocalDirectories(A,J),U=[];for(let Y of h)U.push(...this.fileLoader.generateConfigPaths($,Y,w));return U}getHomeSearchPaths($,w){if(!$)return[];let A=[Q$(mw(),".config",$),Q$(mw(),".config"),mw()],J=[];for(let h of A)J.push(...this.fileLoader.generateConfigPaths($,h,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function fW($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),J=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||J}async function iG($){return i0.loadConfig({...$,__strictErrorHandling:!0})}async function iW($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await i0.loadConfig($);else J=await i0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let h=J instanceof Error?J.name:"UnknownError",U=J instanceof Error?J.message:String(J);if(!(h==="ConfigNotFoundError"||h==="ConfigLoadError"||h==="ConfigValidationError"||U.includes("config"))&&$.verbose)W0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let Z=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await i0.applyEnvironmentVariables(Z.name||"",w,!0,Z.verbose||!1))?.config??w;return w}}async function bG($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await i0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&fW(A)))return(await i0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await i0.loadConfig({...$,cwd:$.cwd||e0.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&fW(w)))return(await i0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function cG($,w,A="replace"){let J=new vJ;try{let h=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return h?h.config:null}catch{return null}}function K1($,w,A=!1){let J=new uJ,h=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Y,Z=[]){let f={...Y};for(let[E,W]of Object.entries(Y)){let F=[...Z,E],j=[`${h}_${F.join("_").toUpperCase()}`,`${h}_${F.map((H)=>H.toUpperCase()).join("")}`,`${h}_${F.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,T;for(let H of j)if(B=e0.env[H],B!==void 0){T=H;break}if(B!==void 0&&T)if(typeof W==="boolean")f[E]=["true","1","yes"].includes(B.toLowerCase());else if(typeof W==="number"){let H=Number(B);if(!Number.isNaN(H))f[E]=H}else if(Array.isArray(W))try{f[E]=JSON.parse(B)}catch{f[E]=B.split(",").map((H)=>H.trim())}else f[E]=B;else if(W&&typeof W==="object"&&!Array.isArray(W))f[E]=U(W,F)}return f}return U(w)}function nG($){let w=Q$(e0.cwd(),$.configDir),A=Q$(e0.cwd(),$.generatedDir),J=Q$(A,"config-types.ts");if(!VY(gE(J)))dT(gE(J),{recursive:!0,mode:511});let h=VY(w)?gT(w).map((Y)=>Y.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],U=`// Generated by bunfig v${H2}
34
+ export type ConfigNames = ${h.length?`'${h.join("' | '")}'`:"string"}
35
+ `;lT(J,U,{mode:438})}function uG($){let w=null,A=null,J=()=>{if(!A)A=iW($).then((U)=>{return w=U,U},(U)=>{let Y="defaultConfig"in $?$.defaultConfig:{};if(w=Y,"verbose"in $&&$.verbose)W0.warn("Config loading failed, using defaults:",[U instanceof Error?U:Error(String(U))]);return Y});return A},h="defaultConfig"in $?$.defaultConfig:{};return w=h,J(),new Proxy({},{get(U,Y){if(w)return w[Y];let Z=h[Y];return J(),Z},has(U,Y){return Y in(w||h)},ownKeys(){return Object.keys(w||h)},getOwnPropertyDescriptor(U,Y){return Object.getOwnPropertyDescriptor(w||h,Y)},set(U,Y,Z){if(!w)w={...h};return w[Y]=Z,!0}})}function vG($){let w=YW(TG.cwd(),$?.configDir||"./config");function A(){if(!zG(w))return[];let h=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),U=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Y=HG(w).filter((f)=>h.has(NY(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),Z=new Map;for(let{base:f,file:E}of Y){let W=NY(E).toLowerCase(),F=Z.get(f);if(!F){Z.set(f,E);continue}let j=NY(F).toLowerCase();if(U.indexOf(W)<U.indexOf(j))Z.set(f,E)}return Array.from(Z.entries()).map(([f,E])=>({base:f,file:E})).sort((f,E)=>f.base.localeCompare(E.base))}function J(){let h=A(),U=h.map((E)=>E.base),Y=U.length?U.map((E)=>`'${E}'`).join(" | "):"string",Z=h.length?`{
36
+ ${h.map((E)=>{let W=YW(w,E.file).replace(/\\/g,"/");return` '${E.base}': typeof import('${W}').default`}).join(`,
37
+ `)}
38
+ }`:"Record<string, any>";return`export type ConfigNames = ${Y}
39
+ export type ConfigByName = ${Z}
40
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
41
+ export type ConfigOf = Config
42
+ `}return{name:"bunfig-plugin",setup(h){h.onResolve({filter:/^virtual:bunfig-types$/},(U)=>{return{path:U.path,namespace:"bunfig-virtual"}}),h.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}function R2($,w={}){let A=cJ.cwd();while(A.includes("storage"))A=qW(A,"..");let J=qW(A,$||"");if(w?.relative)return q2(cJ.cwd(),J);return J}function F$(){if(P0.env.NODE_ENV==="test"||P0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function O2(){if(P0.env.NODE_ENV==="test"||P0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof P0<"u"){let $=P0.type;if($==="renderer"||$==="worker")return!1;return!!(P0.versions&&(P0.versions.node||P0.versions.bun))}return!1}class tW{async format($){let w=await O2(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:ow.pid,hostname:w(),environment:ow.env.NODE_ENV||"development",platform:ow.platform,version:ow.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ow.env.NODE_ENV||ow.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $w{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...nJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new tW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let h=this.generateKeyId(),U=this.generateKey();this.currentKeyId=h,this.keys.set(h,U),this.encryptionKeys.set(h,{key:U,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...DY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...DY};return{...DY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:nJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!F$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let h,U=0,Y=3,Z=1000;while(U<Y)try{try{try{await L2(this.config.logDirectory,MW.F_OK|MW.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await C2(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:k0.from($);try{if(!MJ(this.currentLogFile))await SY(this.currentLogFile,"",{mode:420});if(h=KW(this.currentLogFile,"a",420),I2(h,f,{flag:"a"}),NW(h),h!==void 0)CY(h),h=void 0;if((await aw(this.currentLogFile)).size===0){if(await SY(this.currentLogFile,f,{flag:"w",mode:420}),(await aw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(U<Y-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,F);let j=Z*2**U;await new Promise((B)=>setTimeout(B,j)),U++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(h!==void 0)try{CY(h)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(U===Y-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}U++;let E=Z*2**(U-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(h){throw console.error("Debug: [writeToFile] Error in operation:",h),h}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return sw(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 sw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return sw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(F$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((h)=>{console.error("Error rotating keys:",h)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let h=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Y=Math.max(1,U);if(h.length>Y)for(let[Z]of h.slice(Y))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return LY(16).toString("hex")}generateKey(){return LY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=LY(16),J=K2("aes-256-gcm",w,A),h=k0.isBuffer($)?$:k0.from($,"utf8"),U=J.update(h),Y=J.final(),Z=U.length+Y.length,f=J.getAuthTag(),E=k0.allocUnsafe(16+Z+16);return A.copy(E,0),U.copy(E,16),Y.copy(E,16+U.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=IW(),h=[];J.on("data",(U)=>h.push(U)),J.on("end",()=>w(k0.from(k0.concat(h)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(F$())return;if(!this.shouldWriteToFile())return;let $=await aw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let h=await yJ(this.config.logDirectory),U=h.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),Y=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${Y}`;if(await aw(A).catch(()=>null))try{if(await yW(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await IJ(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(U.length===0&&!h.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await SY(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let h=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${h}.log`);if(await aw(A).catch(()=>null))await yW(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await yJ(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,Z)=>Z.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await IJ(sw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=RW($),J=y2(w),h=IW();await V2(A,h,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),MJ(this.currentLogFile))try{let $=KW(this.currentLogFile,"r+");NW($),CY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!F$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await yJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await IJ(sw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?P.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F$())return!1;let $=typeof O.env.NO_COLOR<"u",w=O.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof O.stderr<"u"&&O.stderr.isTTY||typeof O.stdout<"u"&&O.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:h,level:U,showTimestamp:Y=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(Y)B.push(w);if(U==="warning")B.push("WARN");else if(U==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(h),B.join(" ")}let f=O.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${h}`;else if(U==="info"||U==="success")E=`${A} ${J} ${h}`;else E=`${A} ${J} ${P.cyan(h)}`;if(!Y)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Y)=>{let Z=Number.parseInt(Y,10);return Z<w[0].length?String(w[0][Z]):U});let A=/%([sdijfo%])/g,J=0,h=$.replace(A,(U,Y)=>{if(Y==="%")return"%";if(J>=w.length)return U;let Z=w[J++];switch(Y){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return U}});if(J<w.length)h+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return h}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,h)=>{let U=P.underline(P.blue(J)),Y=this.toAbsoluteFilePath(h);if(Y&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(Y)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${h}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),w=w.replace(/`([^`]+)`/g,(A,J)=>P.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>P.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>P.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>P.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>P.strikethrough(J)),w}supportsHyperlinks(){if(F$())return!1;let $=O.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=O.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(S2(w)||w.startsWith("./")||w.startsWith("../"))w=D2(w);else return null;return MJ(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,h=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Y,Z;if(w instanceof Error)Y=w.message,Z=w.stack;else Y=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":x2[$],j=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:P.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:P.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
43
+ `);for(let H of T)if(H.trim()&&!H.includes(Y))console.error(this.formatConsoleMessage({timestamp:h,message:P.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!F$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Y}`),Z)console.error(Z)}let W=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
44
+ `;if(Z)W+=`${Z}
45
+ `;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress($,w=""){let A={update:(Z,f)=>{},finish:(Z)=>{},interrupt:(Z,f)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!F$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Z,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Z),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!F$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Z)},interrupt:(Z,f="info")=>{if(!F$()&&O.stdout.isTTY)O.stdout.write(`
46
+ `);if(this[f==="warning"?"warn":f](Z),this.activeProgressBar&&this.shouldStyleConsole()&&!F$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":P.blue("◐"),tag:A,message:`${P.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),h=Math.round(J-w),U=`${$} completed in ${h}ms`,Y=new Date,Z=this.formatConsoleTimestamp(Y),E=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
47
+ `,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":P.green("✓"),tag:W,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!F$())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new $w(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(F$())throw Error("createReadStream is not supported in browser environments");if(!MJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return RW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=k0.isBuffer($)?$:k0.from($,"base64"),h=J.subarray(0,16),U=J.subarray(J.length-16),Y=J.subarray(16,J.length-16),Z=M2("aes-256-gcm",A,h);Z.setAuthTag(U);let f=Z.update(Y),E=Z.final(),W=f.length+E.length,F=k0.allocUnsafe(W);return f.copy(F,0),E.copy(F,f.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F$()}isServerMode(){return!F$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:h,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=h.split(`
48
+ `),f=Math.max(...Z.map((j)=>j.length))+2,E=`┌${"─".repeat(f)}┐`,W=`└${"─".repeat(f)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:P.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(E),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(W),showTimestamp:!1}))}else if(!F$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Y=`${J} ${this.environment}.INFO: [BOX] ${U}
49
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}async prompt($){if(F$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${P.cyan("?")} ${$} (y/n) `);let A=(J)=>{let h=J.toString().trim().toLowerCase();O.stdin.removeListener("data",A);try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!1)}catch{}O.stdin.pause(),console.error(""),w(h==="y"||h==="yes")};try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!0)}catch{}O.stdin.resume(),O.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,E=0;if(A=$.replace(f,(W,F)=>{if(F==="%")return"%";if(E>=w.length)return W;let j=w[E++];switch(F){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return W}}),E<w.length)A+=` ${w.slice(E).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:J,fileText:h}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${P.blue("◐")} `;console.error(`${E}${f} ${P.cyan(J)}`)}let Z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${h}
50
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!O.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),h=$.barLength-J,U=P.green("━".repeat(J)),Y=P.gray("━".repeat(h)),Z=`[${U}${Y}]`,f=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",W=this.options.showIcons===!1?"":w||A===100?P.green("✓"):P.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",j=`\r${W}${F} ${Z} ${f}${E}`,B=O.stdout.columns||80,T=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,O.stdout.write($.lastRenderedLine),w)O.stdout.write(`
51
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F$()||!O.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(F$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await yJ(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=sw(this.config.logDirectory,J);if($.before)try{if((await aw(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await IJ(J),console.warn(`Deleted log file: ${J}`)}catch(h){console.error(`Failed to delete log file ${J}:`,h)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var cT,nT=($)=>$,vT=($,w)=>{for(var A in w)cT($,A,{get:w[A],enumerable:!0,configurable:!0,set:uT.bind(w,A)})},mT=($,w)=>()=>($&&(w=$($=0)),w),SW,bW,ew,L1,cW,mG,dG,ZW,CJ,XY,L$,g,gG,EW,lG,WW,tG,pG,KY,rG,FW,BW,MY,aG,sG,oG,eG,SJ,nW,$2,C$,w2,A2,jW,DJ,kY,W$,k,J2,zW,h2,HW,U2,Y2,yY,f2,TW,GW,Z2,IY,E2,W2,F2,B2,j2,VJ,uW,z2,H2="0.15.6",d$,iJ,y1,QY,xY,bJ,PY,iY,I1,bY,cY,t0,vW,mW,W0,i0,dW,gW,T2,N2,lW,nJ,aK,H$,P,fM,_2,ZM,X2,EM,WM,LW,FM,k2,Q2,BM,CW,jM,zM,HM,TM,GM,DY,x2,qM;var tY=Wh(()=>{cT=Object.defineProperty;SW={};vT(SW,{withErrorRecovery:()=>XW,tryLoadConfig:()=>cG,loadConfigWithResult:()=>iG,loadConfig:()=>iW,isRetryableError:()=>_G,isConfigNotFoundError:()=>OG,isBunfigError:()=>kW,globalPerformanceMonitor:()=>L1,globalCache:()=>ew,getEnvOrDefault:()=>XG,generateConfigTypes:()=>nG,defaultGeneratedDir:()=>gW,defaultConfigDir:()=>dW,deepMergeWithArrayStrategy:()=>dY,deepMerge:()=>QW,createLibraryConfig:()=>uG,config:()=>bG,bunfigPlugin:()=>vG,applyEnvVarsToConfig:()=>K1,TypeGenerationError:()=>iY,SchemaValidationError:()=>I1,PluginError:()=>cY,PerformanceMonitor:()=>uY,FileSystemError:()=>PY,ErrorFactory:()=>t0,EnvVarError:()=>bJ,EnvProcessor:()=>uJ,ConfigValidator:()=>gY,ConfigValidationError:()=>QY,ConfigNotFoundError:()=>iJ,ConfigMergeError:()=>xY,ConfigLoader:()=>lY,ConfigLoadError:()=>y1,ConfigFileLoader:()=>vJ,ConfigCache:()=>nY,CacheUtils:()=>cW,BunfigError:()=>d$,BrowserConfigError:()=>bY,ArrayMergeStrategies:()=>vW});T2=mT(async()=>{bW=import.meta.require,ew=new nY,L1=new uY,cW={createKey:GG,isEquivalent:qG,estimateMemoryUsage:RG},mG=XJ(OY.cwd(),"config"),dG=XJ(OY.cwd(),"src/generated"),ZW=_J.env.CLARITY_LOG_DIR||rT(MG(),"logs"),CJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ZW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},XY=await yG(),L$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},g=L$,gG=L$.red,EW=L$.green,lG=L$.yellow,WW=L$.blue,tG=L$.magenta,pG=L$.cyan,KY=L$.white,rG=L$.gray,FW=L$.bgRed,BW=L$.bgYellow,MY=L$.bold,aG=L$.dim,sG=L$.italic,oG=L$.underline,eG=L$.reset,SJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nW={debug:"\uD83D\uDD0D",info:WW("ℹ"),success:EW("✓"),warning:BW(KY(MY(" WARN "))),error:FW(KY(MY(" ERROR ")))},$2=new QJ("stacks"),C$=new QJ("bunfig",{showTags:!0}),w2=k$(M1.cwd(),"config"),A2=k$(M1.cwd(),"src/generated"),jW=OJ.env.CLARITY_LOG_DIR||tT(SG(),"logs"),DJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:jW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},kY=await DG(),W$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},k=W$,J2=W$.red,zW=W$.green,h2=W$.yellow,HW=W$.blue,U2=W$.magenta,Y2=W$.cyan,yY=W$.white,f2=W$.gray,TW=W$.bgRed,GW=W$.bgYellow,Z2=W$.bgGray,IY=W$.bold,E2=W$.dim,W2=W$.italic,F2=W$.underline,B2=W$.strikethrough,j2=W$.reset,VJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},uW={debug:"\uD83D\uDD0D",info:HW("ℹ"),success:zW("✓"),warning:GW(yY(IY(" WARN "))),error:TW(yY(IY(" ERROR ")))},z2=new PJ("stacks"),d$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,J])=>`${A}: ${J}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},iJ=class extends d${code="CONFIG_NOT_FOUND";constructor(w,A,J){let h=J?` or alias "${J}"`:"";super(`Configuration "${w}"${h} not found`,{configName:w,alias:J,searchPaths:A,searchPathCount:A.length})}},y1=class extends d${code="CONFIG_LOAD_ERROR";constructor(w,A,J){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},QY=class extends d${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},xY=class extends d${code="CONFIG_MERGE_ERROR";constructor(w,A,J,h){super(`Failed to merge configuration from "${w}" with "${A}": ${J.message}`,{sourcePath:w,targetPath:A,configName:h,originalError:J.name,originalMessage:J.message});this.cause=J}},bJ=class extends d${code="ENV_VAR_ERROR";constructor(w,A,J,h){super(`Failed to parse environment variable "${w}" with value "${A}" as ${J}`,{envKey:w,envValue:A,expectedType:J,configName:h})}},PY=class extends d${code="FILE_SYSTEM_ERROR";constructor(w,A,J){super(`File system ${w} failed for "${A}": ${J.message}`,{operation:w,path:A,originalError:J.name,originalMessage:J.message});this.cause=J}},iY=class extends d${code="TYPE_GENERATION_ERROR";constructor(w,A,J){super(`Failed to generate types from "${w}" to "${A}": ${J.message}`,{configDir:w,outputPath:A,originalError:J.name,originalMessage:J.message});this.cause=J}},I1=class extends d${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,J){super(`Schema validation failed${J?` for config "${J}"`:""}`,{schemaPath:w,configName:J,validationErrors:A,errorCount:A.length})}},bY=class extends d${code="BROWSER_CONFIG_ERROR";constructor(w,A,J,h){super(`Failed to fetch configuration from "${w}": ${A} ${J}`,{endpoint:w,status:A,statusText:J,configName:h})}},cY=class extends d${code="PLUGIN_ERROR";constructor(w,A,J){super(`Plugin "${w}" failed during ${A}: ${J.message}`,{pluginName:w,operation:A,originalError:J.name,originalMessage:J.message});this.cause=J}},t0={configNotFound($,w,A){return new iJ($,w,A)},configLoad($,w,A){return new y1($,w,A)},configValidation($,w,A){return new QY($,w,A)},configMerge($,w,A,J){return new xY($,w,A,J)},envVar($,w,A,J){return new bJ($,w,A,J)},fileSystem($,w,A){return new PY($,w,A)},typeGeneration($,w,A){return new iY($,w,A)},schemaValidation($,w,A){return new I1($,w,A)},browserConfig($,w,A,J){return new bY($,w,A,J)},plugin($,w,A){return new cY($,w,A)}},vW={replace:"replace",concat:"concat",smart:"smart"},mW=/^https?:\/\//,W0=new PJ("bunfig",{showTags:!0}),i0=new lY,dW=Q$(e0.cwd(),"config"),gW=Q$(e0.cwd(),"src/generated")});N2=cJ.env.CLARITY_LOG_DIR||G2(R2(),"logs"),lW={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:N2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},nJ={...lW},aK=(async()=>{try{let{loadConfig:$}=await T2().then(()=>SW),w=await $({name:"clarity",alias:"logging",defaultConfig:lW,cwd:cJ.cwd()});if(w)Object.assign(nJ,w)}catch{}return nJ})();H$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P=H$,fM=H$.red,_2=H$.green,ZM=H$.yellow,X2=H$.blue,EM=H$.magenta,WM=H$.cyan,LW=H$.white,FM=H$.gray,k2=H$.bgRed,Q2=H$.bgYellow,BM=H$.bgGray,CW=H$.bold,jM=H$.dim,zM=H$.italic,HM=H$.underline,TM=H$.strikethrough,GM=H$.reset,DY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},x2={debug:"\uD83D\uDD0D",info:X2("ℹ"),success:_2("✓"),warning:Q2(LW(CW(" WARN "))),error:k2(LW(CW(" ERROR ")))};qM=new $w("stacks")});var gJ={};G8(gJ,{safeStringify:()=>w0,safeDeleteFile:()=>sY,resolvePathRewrite:()=>aY,redactSensitive:()=>mJ,isValidRootCA:()=>rY,isSingleProxyOptions:()=>C1,isSingleProxyConfig:()=>u2,isMultiProxyOptions:()=>Aw,isMultiProxyConfig:()=>sW,getSudoPassword:()=>ww,getPrimaryDomain:()=>dJ,extractHostname:()=>n2,execSudoSync:()=>pY,debugLog:()=>z});import{execSync as pW}from"node:child_process";import*as aW from"node:fs/promises";function ww(){return process.env.SUDO_PASSWORD}function pY($){let w=ww(),A=$.replace(/'/g,"'\\''");if(w)return pW(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return pW(`sudo sh -c '${A}'`,{encoding:"utf-8"})}function z($,w,A){if(A)P2.debug(`[rpx:${$}] ${w}`)}function c2($){let w=$.toLowerCase();return i2.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function mJ($){if(Array.isArray($))return $.map((A)=>mJ(A));if(typeof $==="string")return b2.test($)?rW:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(c2(A)){w[A]=rW;continue}w[A]=mJ(J)}return w}function w0($,w){return JSON.stringify(mJ($),null,w)}function n2($){if(Aw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if(C1($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function rY($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function dJ($){if(!$)return"stacks.localhost";if(Aw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(C1($))return $.to||"stacks.localhost";return"stacks.localhost"}function sW($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function Aw($){return"proxies"in $&&Array.isArray($.proxies)}function C1($){return"to"in $&&typeof $.to==="string"}function u2($){return!!($&&("to"in $)&&!("proxies"in $))}function aY($,w){if(!w||w.length===0)return null;for(let A of w)if($===A.from||$.startsWith(`${A.from}/`)){let J=A.to.startsWith("http")?new URL(A.to).host:A.to,h=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:J,targetPath:h}}return null}async function sY($,w){try{await aW.unlink($),z("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")z("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var P2,rW="[redacted]",i2,b2;var T$=Wh(()=>{tY();P2=new $w("rpx",{showTags:!1});i2=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),b2=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});var Uh={};G8(Uh,{stopDnsServer:()=>M7,startDnsServer:()=>K7,setupResolver:()=>C7,removeResolver:()=>S7,isDnsServerRunning:()=>y7});import T7 from"node:dgram";function G7($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function IF($,w){let A=[],J=w;while(!0){let h=$[J];if(h===0){J++;break}if((h&192)===192){let U=$.readUInt16BE(J)&16383,{name:Y}=IF($,U);A.push(Y),J+=2;break}J++,A.push($.subarray(J,J+h).toString("ascii")),J+=h}return{name:A.join("."),newOffset:J}}function q7($,w){let{name:A,newOffset:J}=IF($,w),h=$.readUInt16BE(J),U=$.readUInt16BE(J+2);return{question:{name:A,type:h,class:U},newOffset:J+4}}function Jh($){let w=$.split("."),A=[];for(let J of w)A.push(Buffer.from([J.length])),A.push(Buffer.from(J,"ascii"));return A.push(Buffer.from([0])),Buffer.concat(A)}function R7($,w,A){let J=[],h=Buffer.alloc(12);h.writeUInt16BE($,0),h.writeUInt16BE(33152,2),h.writeUInt16BE(1,4),h.writeUInt16BE(1,6),h.writeUInt16BE(0,8),h.writeUInt16BE(0,10),J.push(h),J.push(Jh(w.name));let U=Buffer.alloc(4);U.writeUInt16BE(w.type,0),U.writeUInt16BE(w.class,2),J.push(U),J.push(Jh(w.name));let Y=Buffer.alloc(10);if(Y.writeUInt16BE(w.type,0),Y.writeUInt16BE(1,2),Y.writeUInt32BE(300,4),w.type===1){Y.writeUInt16BE(4,8),J.push(Y);let Z=A.split(".").map((f)=>Number.parseInt(f,10));J.push(Buffer.from(Z))}else if(w.type===28)Y.writeUInt16BE(16,8),J.push(Y),J.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return h.writeUInt16BE(33155,2),h.writeUInt16BE(0,6),Buffer.concat([h,Jh(w.name),U]);return Buffer.concat(J)}function N7($,w){let A=[],J=Buffer.alloc(12);J.writeUInt16BE($,0),J.writeUInt16BE(33155,2),J.writeUInt16BE(1,4),J.writeUInt16BE(0,6),J.writeUInt16BE(0,8),J.writeUInt16BE(0,10),A.push(J),A.push(Jh(w.name));let h=Buffer.alloc(4);return h.writeUInt16BE(w.type,0),h.writeUInt16BE(w.class,2),A.push(h),Buffer.concat(A)}async function K7($,w){if(b$)return z("dns","DNS server already running",w),!0;return MF=new Set($.map((A)=>A.toLowerCase())),new Promise((A)=>{b$=T7.createSocket("udp4"),b$.on("error",(J)=>{if(z("dns",`DNS server error: ${J.message}`,w),J.message.includes("EACCES")||J.message.includes("permission"))z("dns","DNS server requires root privileges to bind to port 53",w);b$?.close(),b$=null,A(!1)}),b$.on("message",(J,h)=>{try{let U=G7(J),{question:Y}=q7(J,12);z("dns",`Query for ${Y.name} type ${Y.type} from ${h.address}`,w);let Z=Y.name.toLowerCase(),f=!1;for(let W of MF)if(Z===W||Z.endsWith(`.${W}`)){f=!0;break}let E;if(f&&(Y.type===1||Y.type===28))E=R7(U.id,Y,"127.0.0.1"),z("dns",`Responding with localhost for ${Y.name}`,w);else E=N7(U.id,Y),z("dns",`NXDOMAIN for ${Y.name}`,w);b$?.send(E,h.port,h.address)}catch(U){z("dns",`Error processing DNS query: ${U}`,w)}}),b$.on("listening",()=>{let J=b$?.address();z("dns",`DNS server listening on ${J?.address}:${J?.port}`,w),A(!0)});try{b$.bind(yF,"127.0.0.1")}catch(J){z("dns",`Failed to bind DNS server: ${J}`,w),A(!1)}})}function M7($){if(b$)z("dns","Stopping DNS server",$),b$.close(),b$=null}function y7(){return b$!==null}function I7($){let w=new Set;for(let A of $){let J=A.split(".");if(J.length>=2)w.add(J[J.length-1])}return Array.from(w)}async function L7($){if(process.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A}=await Promise.resolve().then(() => (T$(),gJ));if(!A()){z("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),z("dns","DNS cache flushed",$)}catch(h){z("dns",`Could not flush DNS cache: ${h}`,$)}}async function C7($,w){if(process.platform!=="darwin")return z("dns","Resolver setup only needed on macOS",$),!0;let{execSudoSync:A,getSudoPassword:J}=await Promise.resolve().then(() => (T$(),gJ));if(!J())return z("dns","SUDO_PASSWORD not set, cannot create resolver files",$),!1;let U=w?I7(w):["test"];try{for(let Y of U){if(hh.has(Y))continue;let Z=`bash -c 'mkdir -p /etc/resolver && echo -e "nameserver 127.0.0.1\\nport ${yF}" > /etc/resolver/${Y}'`;A(Z),hh.add(Y),z("dns",`Created /etc/resolver/${Y} for .${Y} TLD`,$)}return await L7($),!0}catch(Y){return z("dns",`Failed to create resolver file: ${Y}`,$),!1}}async function S7($){if(process.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A}=await Promise.resolve().then(() => (T$(),gJ));try{if(A()){for(let h of hh)w(`rm -f /etc/resolver/${h}`),z("dns",`Removed /etc/resolver/${h}`,$);hh.clear()}}catch(J){z("dns",`Failed to remove resolver files: ${J}`,$)}}var yF=15353,b$=null,MF,hh;var Yh=Wh(()=>{T$();MF=new Set;hh=new Set});import*as l$ from"process";import{existsSync as cF}from"node:fs";import Fh from"node:fs/promises";import q8 from"node:os";import Bh from"node:path";import a0 from"node:process";import{EventEmitter as nF}from"node:events";import c0 from"node:process";import R8 from"node:process";import Th from"node:process";import u1 from"node:process";import f1 from"node:process";import M8 from"node:tty";import SB,{stdin as e7,stdout as $5}from"node:process";import I8,{stdin as OB,stdout as _B}from"node:process";import XB from"node:readline";class C8{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=q8.homedir(),w=Bh.join($,".config","clapp");this.configPath=Bh.join(w,"telemetry.json")}async isEnabled(){if(a0.env.DO_NOT_TRACK==="1"||a0.env.DO_NOT_TRACK==="true")return!1;if(a0.env.NO_TELEMETRY==="1"||a0.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,w){if(!await this.isEnabled())return;let J={event:$,...w,timestamp:Date.now(),platform:q8.platform(),nodeVersion:a0.version};if(this.events.push(J),this.events.length>=10)await this.send()}async trackCommand($,w){await this.track("command",{command:$,duration:w})}async trackError($,w){await this.track("error",{error:$,command:w})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let w=await this.loadConfig();return w.lastSent=Date.now(),await this.saveConfig(w),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let w=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(w),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((w)=>setTimeout(w,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:a0.env.DO_NOT_TRACK==="1"||a0.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(cF(this.configPath)){let $=await Fh.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let w=Bh.dirname(this.configPath);await Fh.mkdir(w,{recursive:!0}),await Fh.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),w=Date.now().toString(36);return`${$}-${w}`}}var u7=new C8;function uF($,w={}){let A={_:[]},J=w.alias||{},h=new Set(w.boolean||[]),U={};for(let Z of Object.keys(J))for(let f of J[Z])U[f]=Z;for(let Z of h)if(J[Z])for(let f of J[Z])h.add(f);function Y(Z,f){let E=U[Z]||Z;if(A[E]=f,J[E])for(let W of J[E])A[W]=f;if(U[Z]&&J[U[Z]])for(let W of J[U[Z]])A[W]=f;A[Z]=f}for(let Z=0;Z<$.length;Z++){let f=$[Z];if(f==="--"){A._.push(...$.slice(Z+1));break}if(f.startsWith("--")){let E=f.indexOf("=");if(E!==-1){let W=f.slice(2,E),F=f.slice(E+1);Y(W,F)}else{let W=f.slice(2);if(W.startsWith("no-")){let j=W.slice(3);Y(j,!1);continue}let F=U[W]||W;if(h.has(F)||h.has(W))Y(W,!0);else{let j=$[Z+1];if(j!==void 0&&!j.startsWith("-"))Y(W,j),Z++;else Y(W,!0)}}}else if(f.startsWith("-")&&f.length>1){let E=f.slice(1);for(let W=0;W<E.length;W++){let F=E[W],j=U[F]||F;if(W===E.length-1&&!h.has(j)&&!h.has(F)){let B=$[Z+1];if(B!==void 0&&!B.startsWith("-"))Y(F,B),Z++;else Y(F,!0)}else Y(F,!0)}}else A._.push(f)}return A}function Hh($){return $.replace(/[<[].+/,"").trim()}function vF($){let w=/<([^>]+)>/g,A=/\[([^\]]+)\]/g,J=[],h=(Z)=>{let f=!1,E=Z[1];if(E.startsWith("..."))E=E.slice(3),f=!0;return{required:Z[0].startsWith("<"),value:E,variadic:f}},U;while(U=w.exec($))J.push(h(U));let Y;while(Y=A.exec($))J.push(h(Y));return J}function mF($){let w={alias:{},boolean:[]};for(let[A,J]of $.entries()){if(J.names.length>1)w.alias[J.names[0]]=J.names.slice(1);if(J.isBoolean)if(J.negated){if(!$.some((U,Y)=>{return Y!==A&&U.names.some((Z)=>J.names.includes(Z))&&typeof U.required==="boolean"}))w.boolean.push(J.names[0])}else w.boolean.push(J.names[0])}return w}function N8($){return $.reduce((w,A)=>w.length>=A.length?w:A,"")}function jh($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function dF($){return $.replace(/([a-z])-([a-z])/g,(w,A,J)=>{return A+J.toUpperCase()})}function gF($,w,A){let J=0,h=w.length,U=$,Y;for(;J<h;++J)Y=U[w[J]],U=U[w[J]]=J===h-1?A:Y!=null?Y:!!~w[J+1].indexOf(".")||!(+w[J+1]>-1)?{}:[]}function lF($,w){for(let A of Object.keys(w)){let J=w[A];if(J.shouldTransform){if($[A]=Array.prototype.concat.call([],$[A]),typeof J.transformFunction==="function")$[A]=$[A].map(J.transformFunction)}}}function tF($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function S8($){return $.split(".").map((w,A)=>{return A===0?dF(w):w}).join(".")}class n1 extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
52
+
53
+ Stack trace:
54
+ ${this.stack}`;return this.message}}function pF(){let{env:$}=R8,{TERM:w,TERM_PROGRAM:A}=$;if(R8.platform!=="win32")return w!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||A==="Terminus-Sublime"||A==="vscode"||w==="xterm-256color"||w==="alacritty"||w==="rxvt-unicode"||w==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var d1="\x1B",w$=`${d1}[`;var T0={to($,w){if(!w)return`${w$}${$+1}G`;return`${w$}${w+1};${$+1}H`},move($,w){let A="";if($<0)A+=`${w$}${-$}D`;else if($>0)A+=`${w$}${$}C`;if(w<0)A+=`${w$}${-w}A`;else if(w>0)A+=`${w$}${w}B`;return A},up:($=1)=>`${w$}${$}A`,down:($=1)=>`${w$}${$}B`,forward:($=1)=>`${w$}${$}C`,backward:($=1)=>`${w$}${$}D`,nextLine:($=1)=>`${w$}E`.repeat($),prevLine:($=1)=>`${w$}F`.repeat($),left:`${w$}G`,hide:`${w$}?25l`,show:`${w$}?25h`,save:`${d1}7`,restore:`${d1}8`};var zh={screen:`${w$}2J`,up:($=1)=>`${w$}1J`.repeat($),down:($=1)=>`${w$}J`.repeat($),line:`${w$}2K`,lineEnd:`${w$}K`,lineStart:`${w$}1K`,lines($){let w="";for(let A=0;A<$;A++)w+=this.line+(A<$-1?T0.up():"");if($)w+=T0.left;return w}},g7={screen:`${d1}c`};function rF($,w){let A=[];for(let J=0;J<=w.length;J++)A[J]=[J];for(let J=0;J<=$.length;J++)A[0][J]=J;for(let J=1;J<=w.length;J++)for(let h=1;h<=$.length;h++)if(w.charAt(J-1)===$.charAt(h-1))A[J][h]=A[J-1][h-1];else A[J][h]=Math.min(A[J-1][h-1]+1,A[J][h-1]+1,A[J-1][h]+1);return A[w.length][$.length]}function D8($,w,A=2,J=3){return w.map((h)=>({cmd:h,distance:rF($,h)})).filter(({distance:h})=>h<=A).sort((h,U)=>h.distance-U.distance).slice(0,J).map(({cmd:h})=>h)}class V8{rawName;description;name;names;isBoolean;required;config;negated;constructor($,w,A){if(this.rawName=$,this.description=w,this.config=Object.assign({},A),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=Hh($).split(",").map((J)=>{let h=J.trim().replace(/^-{1,2}/,"");if(h.startsWith("no-"))this.negated=!0,h=h.replace(/^no-/,"");return S8(h)}).sort((J,h)=>J.length>h.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var t7=Th.argv,aF=`${Th.platform}-${Th.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,K8=u1.argv,sF=`${u1.platform}-${u1.arch} node-${u1.version}`;class Gh{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,A,J){this.rawName=$,this.description=w,this.config=A,this.cli=J,this.options=[],this.aliasNames=[],this.name=Hh($);let h=Hh($),U=h.indexOf(":");if(U>0)this.namespace=h.substring(0,U),this.name=h.substring(U+1);if(this.args=vF($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!A)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,w="-v, --version"){return this.versionNumber=$,this.option(w,"Display version number"),this}example($){return this.examples.push($),this}option($,w,A){let J=new V8($,w,A);return this.options.push(J),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===$;return this.name===$}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof qh}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption($){return $=$.split(".")[0],!!this.options.find((w)=>{return w.names.includes($)})}outputHelp(){let{name:$,commands:w}=this.cli,{versionNumber:A,options:J,helpCallback:h}=this.cli.globalCommand,U=[{body:`${$}${A?`/${A}`:""}`}];if(U.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let f=N8(w.map((B)=>B.rawName)),E=new Map,W=[];for(let B of w)if(B.namespace){if(!E.has(B.namespace))E.set(B.namespace,[]);E.get(B.namespace).push(B)}else W.push(B);let F="";if(W.length>0)F+=W.map((B)=>{return` ${jh(B.rawName,f.length)} ${B.description}`}).join(`
55
+ `);let j=Array.from(E.keys()).sort();for(let B of j){let T=E.get(B);if(F.length>0)F+=`
56
+
57
+ `;F+=` ${B}:
58
+ `,F+=T.map((H)=>{return` ${jh(H.rawName,f.length-2)} ${H.description}`}).join(`
59
+ `)}U.push({title:"Commands",body:F}),U.push({title:"For more info, run any command with the `--help` flag",body:w.map((B)=>` $ ${$}${B.displayName===""?"":` ${B.displayName}`} --help`).join(`
60
+ `)})}let Z=this.isGlobalCommand?J:[...this.options,...J||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)Z=Z.filter((f)=>f.name!=="version");if(Z.length>0){let f=N8(Z.map((E)=>E.rawName));U.push({title:"Options",body:Z.map((E)=>{return` ${jh(E.rawName,f.length)} ${E.description} ${E.config.default===void 0?"":`(default: ${E.config.default})`}`}).join(`
61
+ `)})}if(this.examples.length>0)U.push({title:"Examples",body:this.examples.map((f)=>{if(typeof f==="function")return f($);return f}).join(`
62
+ `)});if(h)U=h(U)||U;console.log(U.map((f)=>{return f.title?`${f.title}:
63
+ ${f.body}`:f.body}).join(`
64
+
65
+ `))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?aF:sF}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let A=this.args.filter((h)=>h.required).slice(this.cli.args.length),J=A.map((h)=>`<${h.value}>`).join(" ");throw new n1(`Missing required argument${A.length>1?"s":""}: ${J}
66
+
67
+ Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let A of Object.keys($))if(A!=="--"&&!this.hasOption(A)&&!w.hasOption(A)){let h=[...w.options,...this.options].flatMap((f)=>f.names),U=A.length>1?`--${A}`:`-${A}`,Y=D8(A,h),Z=`Unknown option \`${U}\``;if(Y.length>0)Z+=`
68
+
69
+ Did you mean one of these?`,Y.forEach((f)=>{let E=f.length>1?`--${f}`:`-${f}`;Z+=`
70
+ • ${E}`});throw Z+=`
71
+
72
+ Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new n1(Z)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,A=[...w.options,...this.options];for(let J of A){let h=$[J.name.split(".")[0]];if(J.required){let U=A.some((Y)=>Y.negated&&Y.names.includes(J.name));if(h===!0||h===!1&&!U)throw new n1(`Option \`${J.rawName}\` requires a value.
73
+
74
+ Example: ${this.cli.name} ${this.rawName} ${J.rawName} <value>`)}}}}class qh extends Gh{constructor($){super("@@global@@","",{},$)}}var oF=Gh,n0={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 U1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function eF(){return!0}function $B(){let $={};$.supportsColor=eF();function w(J,h=[]){let U=J===""?[]:[...h,J],Y=function(f){if(!$.supportsColor)return f;let E="",W="";for(let F of U)if(F in U1&&U1[F]in n0){let j=U1[F];E+=n0[j][0],W=n0[j][1]+W}else if(F in n0)E+=n0[F][0],W=n0[F][1]+W;return E+f+W},Z=[...Object.keys(n0),...Object.keys(U1)];for(let f of Z)if(!(f in Y))Object.defineProperty(Y,f,{get(){return w(f,U)}});return Y}let A=[...Object.keys(n0),...Object.keys(U1)];for(let J of A)if(!(J in $))Object.defineProperty($,J,{get(){return w(J)}});return $}var Y1=$B();class Rh extends nF{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new qh(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(A)=>{if(console.log(`
75
+
76
+ Received ${A}, cleaning up...`),$)try{await $()}catch(J){console.error("Error during cleanup:",J)}c0.exit(0)};return c0.on("SIGINT",()=>w("SIGINT")),c0.on("SIGTERM",()=>w("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,w,A){if(!A)A={};let J=new oF($,w||"",A,this);return J.globalCommand=this.globalCommand,this.commands.push(J),J}option($,w,A){return this.globalCommand.option($,w,A),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,w="-v, --version"){return this.globalCommand.version($,w),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:w},A,J){if(this.args=$,this.options=w,A)this.matchedCommand=A;if(J)this.matchedCommandName=J;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(Y1.red(`
77
+ ✗ Command "${$}" not found.
78
+ `)),this.enableDidYouMean){let w=[];for(let J of this.commands){if(J.displayName)w.push(J.displayName);if(J.aliasNames)w.push(...J.aliasNames)}let A=D8($,w);if(A.length>0)console.log(Y1.yellow("Did you mean one of these?")),A.forEach((J)=>console.log(` ${Y1.dim("•")} ${this.name} ${J}`)),console.log("")}console.log(Y1.dim("Run"),`${this.name} --help`,Y1.dim("to see all available commands")),c0.exit(1)}async parse($=K8,w={}){let{run:A=!0,exitOnError:J=!1}=w;if(J)try{return await this.parse($,{run:A})}catch(f){throw this.handleUsageError(f),f}if(this.rawArgs=$,!this.name)this.name=$[1]?tF($[1]):"cli";let h=!0,U=$.slice(2),Y=U[0];if(Y&&!Y.startsWith("-")){for(let f of this.commands)if(f.isMatched(Y)){let E=this.mri(U,f);h=!1;let W={...E,args:E.args.slice(1)};this.setParsedInfo(W,f,Y),this.emit(`command:${Y}`,f);break}}if(h){for(let f of this.commands)if(f.name===""){h=!1;let E=this.mri(U,f);this.setParsedInfo(E,f),this.emit("command:!",f);break}}if(h){let f=this.mri($.slice(2));this.setParsedInfo(f)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),A=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),A=!1,this.unsetMatchedCommand();let Z={args:this.args,options:this.options};if(A)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return Z}mri($,w){let A=[...this.globalCommand.options,...w?w.options:[]],J=mF(A),h=[],U=$.indexOf("--");if(U>-1)h=$.slice(U+1),$=$.slice(0,U);let Y=uF($,J),Z={_:Y._};for(let j of Object.keys(Y))if(j!=="_")Z[S8(j)]=Y[j];let f=Z._,E={"--":h},W=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,F=Object.create(null);for(let j of A){if(!W&&j.config.default!==void 0)for(let B of j.names)E[B]=j.config.default;if(Array.isArray(j.config.type)){if(F[j.name]===void 0)F[j.name]={shouldTransform:!0,transformFunction:j.config.type[0]}}}for(let j of Object.keys(Z))if(j!=="_"){let B=j.split(".");gF(E,B,Z[j]),lF(E,F)}return{args:f,options:E}}async run($=K8){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let J=$,h=J.message??"command-line error",U=this.name?`${this.name}: `:"",Y=/--help/.test(h)?"":`
79
+ Run \`${this.name??"cli"} --help\` for usage.`;c0.stderr.write(`${U}${h}${Y}
80
+ `),c0.exit(J.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:A}=this;if(!A||!A.commandAction)return;A.checkUnknownOptions(),A.checkOptionValue(),A.checkRequiredArgs();let J=[];A.args.forEach((Z,f)=>{if(Z.variadic)J.push($.slice(f));else J.push($[f])}),J.push(w);let h={command:A,args:J,options:w};for(let Z of A.beforeHooks)await Z(h);let U,Y=async()=>{let Z=A.commandAction.apply(this,J);if(Z instanceof Promise)U=await Z;else U=Z;return U};if(A.middleware.length>0){let Z=0,f=async()=>{if(Z<A.middleware.length){let E=A.middleware[Z++];await E({...h,next:f})}else await Y()};await f()}else await Y();for(let Z of A.afterHooks)await Z(h);return U}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return c0.removeAllListeners("SIGINT"),c0.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 O8{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let w=this.cache.get($);if(!w){this.misses++;return}if(Date.now()-w.timestamp>w.ttl){this.cache.delete($),this.misses++;return}return this.hits++,w.value}set($,w,A=5000){if(!this.enabled)return;this.cache.set($,{value:w,timestamp:Date.now(),ttl:A})}has($){if(!this.enabled)return!1;let w=this.cache.get($);if(!w)return!1;if(Date.now()-w.timestamp>w.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[w,A]of this.cache.entries())if($-A.timestamp>A.ttl)this.cache.delete(w)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var r7=new O8;function wB(){if("FORCE_COLOR"in f1.env)return f1.env.FORCE_COLOR!=="0";if("NO_COLOR"in f1.env||f1.env.TERM==="dumb")return!1;if(f1.platform==="win32")return!0;return M8.isatty(1)&&M8.isatty(2)}var _8=wB();function a($,w){if(!_8)return(A)=>A;return(A)=>$+A+w}var AB=a("\x1B[0m","\x1B[0m"),JB=a("\x1B[31m","\x1B[39m"),hB=a("\x1B[32m","\x1B[39m"),UB=a("\x1B[33m","\x1B[39m"),YB=a("\x1B[34m","\x1B[39m"),fB=a("\x1B[35m","\x1B[39m"),ZB=a("\x1B[36m","\x1B[39m"),EB=a("\x1B[37m","\x1B[39m"),WB=a("\x1B[90m","\x1B[39m"),FB=a("\x1B[1m","\x1B[22m"),BB=a("\x1B[3m","\x1B[23m"),jB=a("\x1B[4m","\x1B[24m"),zB=a("\x1B[2m","\x1B[22m"),HB=a("\x1B[7m","\x1B[27m"),TB=a("\x1B[8m","\x1B[28m"),GB=a("\x1B[9m","\x1B[29m"),qB=a("\x1B[41m","\x1B[49m"),RB=a("\x1B[42m","\x1B[49m"),NB=a("\x1B[43m","\x1B[49m"),KB=a("\x1B[44m","\x1B[49m"),MB=a("\x1B[45m","\x1B[49m"),yB=a("\x1B[46m","\x1B[49m"),IB=a("\x1B[47m","\x1B[49m"),LB=_8,CB={reset:AB,red:JB,green:hB,yellow:UB,blue:YB,magenta:fB,cyan:ZB,white:EB,gray:WB,bold:FB,italic:BB,underline:jB,dim:zB,inverse:HB,hidden:TB,strikethrough:GB,bgRed:qB,bgGreen:RB,bgYellow:NB,bgBlue:KB,bgMagenta:MB,bgCyan:yB,bgWhite:IB,isColorSupported:LB},v1=CB,DB=["up","down","left","right","space","enter","cancel"],m1={actions:new Set(DB),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function X8($,w){if(typeof $==="string")return m1.aliases.get($)===w;for(let A of $){if(A===void 0)continue;if(X8(A,w))return!0}return!1}function VB($,w){if($===w)return[];let A=$.split(`
81
+ `),J=w.split(`
82
+ `),h=[];for(let U=0;U<Math.max(A.length,J.length);U++)if(A[U]!==J[U])h.push(U);return h}var w5=SB.platform.startsWith("win"),y8=Symbol("clapp:cancel");function c1($,w){let A=$;if(A.isTTY)A.setRawMode(w)}function kB($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function QB($){return kB($).length}function L8($,w,A){if(!w||w<1)return $;let J=A?.hard??!1,h=A?.trim??!0,U=$.split(`
83
+ `),Y=[];for(let Z of U){if(QB(Z)<=w){Y.push(h?Z.trimEnd():Z);continue}if(J){let f="",E=0,W=0;while(W<Z.length){let F=Z.slice(W).match(/^\x1b\[[0-9;]*m/);if(F){f+=F[0],W+=F[0].length;continue}if(E>=w)Y.push(h?f.trimEnd():f),f="",E=0;f+=Z[W],E++,W++}if(f)Y.push(h?f.trimEnd():f)}else Y.push(h?Z.trimEnd():Z)}return Y.join(`
84
+ `)}class Nh{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor($,w=!0){let{input:A=OB,output:J=_B,render:h,signal:U,...Y}=$;this.opts=Y,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=h.bind(this),this._track=w,this._abortSignal=U,this.input=A,this.output=J}unsubscribe(){this._subscribers.clear()}setSubscriber($,w){let A=this._subscribers.get($)??[];A.push(w),this._subscribers.set($,A)}on($,w){return this.setSubscriber($,{cb:w}),this}once($,w){return this.setSubscriber($,{cb:w,once:!0}),this}emit($,...w){let A=this._subscribers.get($)??[],J=[];for(let h of A)if(h.cb(...w),h.once)J.push(()=>A.splice(A.indexOf(h),1));for(let h of J)h();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(y8);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=XB.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),c1(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(T0.show),this.output.off("resize",this.render),c1(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(T0.show),this.output.off("resize",this.render),c1(this.input,!1),$(y8)})})}_isActionKey($,w){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,w){if(this.userInput=$??"",this.emit("userInput",this.userInput),w&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,w){if(this._track&&w.name!=="return"){if(w.name&&this._isActionKey($,w))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let A=w.name==="tab"||w.name==="escape"||w.name==="backspace"||w.name==="delete"||w.name==="enter"||w.name==="return"||w.name&&["up","down","left","right"].includes(w.name);if($&&!A&&$.length===1&&$>=" ")this._manualLine+=$;else if(w.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let J=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(J)}if(this.state==="error")this.state="active",this.error="";if(w?.name){if(!this._track&&m1.aliases.has(w.name))this.emit("cursor",m1.aliases.get(w.name));if(m1.actions.has(w.name))this.emit("cursor",w.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),w),w?.name==="return"){if(this.opts.validate){let A=this.opts.validate(this.value);if(A)this.error=A instanceof Error?A.message:A,this.state="error"}if(this.state!=="error")this.state="submit"}if(X8([$,w?.name,w?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
85
+ `),c1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let $=L8(this._prevFrame,I8.stdout.columns,{hard:!0,trim:!1}).split(`
86
+ `).length-1;this.output.write(T0.move(-999,$*-1))}render(){let $=L8(this._render(this)??"",I8.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(T0.hide);else{let w=VB(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let A=w[0];this.output.write(T0.move(0,A)),this.output.write(zh.lines(1));let J=$.split(`
87
+ `);this.output.write(J[A]),this._prevFrame=$,this.output.write(T0.move(0,J.length-A-1));return}if(w&&w?.length>1){let A=w[0];this.output.write(T0.move(0,A)),this.output.write(zh.down());let h=$.split(`
88
+ `).slice(A);this.output.write(h.join(`
89
+ `)),this._prevFrame=$;return}this.output.write(zh.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function xB($,w){if($===void 0)return 0;if(w.length===0)return 0;let J=w.findIndex((h)=>h.value===$);return J!==-1?J:0}function PB($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function iB($,w){if(!w)return;if($)return w;return w[0]}class bB extends Nh{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#A="";#J;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return v1.inverse(v1.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[w,...A]=this.userInput.slice(this._cursor);return`${$}${v1.inverse(w)}${A.join("")}`}get options(){if(typeof this.#w==="function")return this.#w();return this.#w}constructor($){super($);this.#w=$.options;let w=this.options;this.filteredOptions=[...w],this.multiple=$.multiple===!0,this.#J=$.filter??PB;let A;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)A=$.initialValue;else A=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)A=[this.options[0].value];if(A)for(let J of A){let h=w.findIndex((U)=>U.value===J);if(h!==-1)this.toggleSelected(J),this.#$=h}this.focusedValue=this.options[this.#$]?.value,this.on("key",(J,h)=>this.#h(J,h)),this.on("userInput",(J)=>this.#U(J))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#h($,w){let A=w.name==="up",J=w.name==="down",h=w.name==="return";if(A||J){if(this.#$=Math.max(0,Math.min(this.#$+(A?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(h)this.value=iB(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(w.name==="tab"||this.isNavigating&&w.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((w)=>w!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#U($){if($!==this.#A){this.#A=$;let w=this.options;if($)this.filteredOptions=w.filter((A)=>this.#J($,A));else this.filteredOptions=[...w];if(this.#$=xB(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class cB extends Nh{options;cursor=0;#$;getGroupItems($){return this.options.filter((w)=>w.group===$)}isGroupSelected($){let w=this.getGroupItems($),A=this.value;if(A===void 0)return!1;return w.every((J)=>A.includes(J.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let w=String($.value),A=this.getGroupItems(w);if(this.isGroupSelected(w))this.value=this.value.filter((J)=>A.findIndex((h)=>h.value===J)===-1);else this.value=[...this.value,...A.map((J)=>J.value)];this.value=Array.from(new Set(this.value))}else{let w=this.value.includes($.value);this.value=w?this.value.filter((A)=>A!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:w}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(w).flatMap(([A,J])=>[{value:A,group:!0,label:A},...J.map((h)=>({...h,group:A}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:A})=>A===$.cursorAt),this.#$?0:1),this.on("cursor",(A)=>{switch(A){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let J=this.options[this.cursor]?.group===!0;if(!this.#$&&J)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let J=this.options[this.cursor]?.group===!0;if(!this.#$&&J)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var nB=pF();var l=($,w)=>nB?$:w,h5=l("◆","*"),U5=l("■","x"),Y5=l("▲","x"),f5=l("◇","o"),Z5=l("┌","T"),uB=l("│","|"),E5=l("└","—"),W5=l("●",">"),F5=l("○"," "),B5=l("◻","[•]"),j5=l("◼","[+]"),z5=l("◻","[ ]"),H5=l("▪","•"),T5=l("─","-"),G5=l("╮","+"),q5=l("├","+"),R5=l("╯","+"),N5=l("●","•"),K5=l("◆","*"),M5=l("▲","!"),y5=l("■","x");var I5={light:l("─","-"),heavy:l("━","="),block:l("█","#")};function vB(){return`${v1.gray(uB)} `}var L5=vB();import{homedir as ZU}from"node:os";import{join as EU,resolve as z6}from"node:path";import{existsSync as k8,statSync as Q8}from"fs";import{existsSync as mB,mkdirSync as V5,readdirSync as O5,readFileSync as dB,writeFileSync as _5}from"fs";import{homedir as zw}from"os";import{dirname as Q5,resolve as p$}from"path";import IA from"process";import{existsSync as x8,statSync as P8}from"fs";import{existsSync as nh,mkdirSync as gB,readdirSync as lB,writeFileSync as tB}from"fs";import{homedir as Hw}from"os";import{dirname as i8,resolve as V$}from"path";import s0 from"process";import{join as pB,relative as rB,resolve as b8}from"path";import FA from"process";import{existsSync as Kf,mkdirSync as d5,readdirSync as g5,writeFileSync as l5}from"fs";import{homedir as Kh}from"os";import{dirname as r5,resolve as D$}from"path";import E1 from"process";import{join as aB,relative as sB,resolve as c8}from"path";import BA from"process";import{existsSync as Mf,mkdirSync as $q,readdirSync as wq,writeFileSync as Aq}from"fs";import{dirname as hq,resolve as jA}from"path";import uh from"process";import{Buffer as u0}from"buffer";import{createCipheriv as oB,createDecipheriv as eB,randomBytes as Mh}from"crypto";import{closeSync as yh,createReadStream as n8,createWriteStream as $j,existsSync as Ih,fsyncSync as u8,openSync as v8,writeFileSync as wj}from"fs";import{access as Aj,constants as m8,mkdir as Jj,readdir as g1,rename as d8,stat as Tw,unlink as l1,writeFile as Lh}from"fs/promises";import{join as Gw}from"path";import q$ from"process";import{pipeline as hj}from"stream/promises";import{createGzip as g8}from"zlib";import qw from"process";import N0 from"process";import{Buffer as G0}from"buffer";import{createCipheriv as Uj,createDecipheriv as Yj,randomBytes as Ch}from"crypto";import{closeSync as Sh,createReadStream as l8,createWriteStream as fj,existsSync as t1,fsyncSync as t8,openSync as p8,writeFileSync as Zj}from"fs";import{access as Ej,constants as r8,mkdir as Wj,readdir as p1,rename as a8,stat as Rw,unlink as r1,writeFile as Dh}from"fs/promises";import{isAbsolute as Fj,join as Nw,resolve as Bj}from"path";import S from"process";import{pipeline as jj}from"stream/promises";import{createGzip as s8}from"zlib";import Kw from"process";import K0 from"process";import a1 from"process";import{existsSync as s1}from"fs";import{resolve as Vh}from"path";import{existsSync as zj}from"fs";import{existsSync as Hj,readdirSync as Tj}from"fs";import{extname as Oh,resolve as o8}from"path";import Gj from"process";import{join as qj,relative as Rj,resolve as e8}from"path";import zA from"process";import{Buffer as q0}from"buffer";import{createCipheriv as Nj,createDecipheriv as Kj,randomBytes as _h}from"crypto";import{closeSync as Xh,createReadStream as $f,createWriteStream as Mj,existsSync as o1,fsyncSync as wf,openSync as Af,writeFileSync as yj}from"fs";import{access as Ij,constants as Jf,mkdir as Lj,readdir as e1,rename as hf,stat as Mw,unlink as $A,writeFile as kh}from"fs/promises";import{isAbsolute as Cj,join as yw,resolve as Sj}from"path";import D from"process";import{pipeline as Dj}from"stream/promises";import{createGzip as Uf}from"zlib";import Iw from"process";import M0 from"process";import AA from"process";import{existsSync as JA}from"fs";import{resolve as ch}from"path";import{existsSync as pz}from"fs";class Rf{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let h=this.generateKey($,A),U=J??this.options.ttl,Y=this.estimateSize(w);this.cache.set(h,{value:w,timestamp:new Date,ttl:U,hits:0,size:Y}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!k8($))return!0;return Q8($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let h=k8(A)?Q8(A):null,U=h?h.mtime:new Date;this.set($,{value:w,fileTimestamp:U},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,h)=>J+h.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class Nf{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),h=new Date;try{let U=await w(),Y=performance.now()-J;return this.recordMetric({operation:$,duration:Y,timestamp:h,...A}),U}catch(U){let Y=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:Y,timestamp:h,...A}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((h)=>h.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((h)=>h.duration),J=A.reduce((h,U)=>h+U,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}var WA=new Rf,oh=new Nf;var Vj=Object.defineProperty,Oj=($)=>$;function _j($,w){this[$]=Oj.bind(null,w)}var Xj=($,w)=>{for(var A in w)Vj($,A,{get:w[A],enumerable:!0,configurable:!0,set:_j.bind(w,A)})},kj=($,w)=>()=>($&&(w=$($=0)),w),yf={};Xj(yf,{withErrorRecovery:()=>Cf,tryLoadConfig:()=>Az,loadConfigWithResult:()=>$z,loadConfig:()=>_f,isRetryableError:()=>pj,isConfigNotFoundError:()=>tj,isBunfigError:()=>Sf,globalPerformanceMonitor:()=>B1,globalCache:()=>Lw,getEnvOrDefault:()=>rj,generateConfigTypes:()=>Jz,defaultGeneratedDir:()=>nf,defaultConfigDir:()=>cf,deepMergeWithArrayStrategy:()=>JU,deepMerge:()=>Df,createLibraryConfig:()=>hz,config:()=>wz,bunfigPlugin:()=>Uz,applyEnvVarsToConfig:()=>Z1,TypeGenerationError:()=>ph,SchemaValidationError:()=>F1,PluginError:()=>ah,PerformanceMonitor:()=>$U,FileSystemError:()=>th,ErrorFactory:()=>v0,EnvVarError:()=>NA,EnvProcessor:()=>LA,ConfigValidator:()=>hU,ConfigValidationError:()=>gh,ConfigNotFoundError:()=>RA,ConfigMergeError:()=>lh,ConfigLoader:()=>UU,ConfigLoadError:()=>W1,ConfigFileLoader:()=>CA,ConfigCache:()=>eh,CacheUtils:()=>kf,BunfigError:()=>n$,BrowserConfigError:()=>rh,ArrayMergeStrategies:()=>Pf});class eh{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let h=this.generateKey($,A),U=J??this.options.ttl,Y=this.estimateSize(w);this.cache.set(h,{value:w,timestamp:new Date,ttl:U,hits:0,size:Y}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!x8($))return!0;return P8($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let h=x8(A)?P8(A):null,U=h?h.mtime:new Date;this.set($,{value:w,fileTimestamp:U},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,h)=>J+h.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class $U{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),h=new Date;try{let U=await w(),Y=performance.now()-J;return this.recordMetric({operation:$,duration:Y,timestamp:h,...A}),U}catch(U){let Y=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:Y,timestamp:h,...A}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((h)=>h.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((h)=>h.duration),J=A.reduce((h,U)=>h+U,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function Qj($,w={}){let J=Object.keys(w).sort().map((h)=>`${h}:${w[h]}`).join("|");return J?`${$}:${J}`:$}function xj($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function Pj($){return $.getStats().size*2}function wU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&t(w[0])&&"id"in w[0]&&w[0].id===3&&t(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(t(w)&&t($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(t($)&&"arr"in $&&Array.isArray($.arr)&&t(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&t(w[0])&&t($[0])){let J=[...w];for(let h of $)if(t(h)&&"name"in h){if(!J.find((Y)=>t(Y)&&("name"in Y)&&Y.name===h.name))J.push(h)}else if(t(h)&&"path"in h){if(!J.find((Y)=>t(Y)&&("path"in Y)&&Y.path===h.path))J.push(h)}else if(!J.some((U)=>HA(U,h)))J.push(h);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}if(!t(w)||!t($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let h=w[J];if(h===null||h===void 0)continue;else if(t(h)&&t(A[J]))A[J]=wU(A[J],h);else if(Array.isArray(h)&&Array.isArray(A[J]))if(h.length>0&&A[J].length>0&&t(h[0])&&t(A[J][0])){let U=[...h];for(let Y of A[J])if(t(Y)&&"name"in Y){if(!U.find((f)=>t(f)&&("name"in f)&&f.name===Y.name))U.push(Y)}else if(t(Y)&&"path"in Y){if(!U.find((f)=>t(f)&&("path"in f)&&f.path===Y.path))U.push(Y)}else if(!U.some((Z)=>HA(Z,Y)))U.push(Y);A[J]=U}else if(h.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...h];for(let Y of A[J])if(!U.includes(Y))U.push(Y);A[J]=U}else A[J]=h;else A[J]=h}return A}function HA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!HA($[A],w[A]))return!1;return!0}if(t($)&&t(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!HA($[h],w[h]))return!1}return!0}return!1}function t($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function ij($,w){if(!Mf($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return wU(w,J)}catch{return null}}catch{return null}}async function bj({name:$="",cwd:w,defaultConfig:A}){let J=w||uh.cwd(),h=[".ts",".js",".mjs",".cjs",".json"],U=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Y of U)for(let Z of h){let f=jA(J,`${Y}${Z}`),E=await ij(f,A);if(E!==null)return E}try{let Y=jA(J,"package.json");if(Mf(Y)){let f=(await import(Y))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return wU(A,f)}catch{}}}catch{}return A}function cj($,w={}){let A=BA.cwd();while(A.includes("storage"))A=c8(A,"..");let J=c8(A,$||"");if(w?.relative)return sB(BA.cwd(),J);return J}async function nj(){try{let $=await bj({name:"clarity",defaultConfig:YA,cwd:BA.cwd(),endpoint:"",headers:{}});return{...YA,...$}}catch{return YA}}function o(){if(N0.env.NODE_ENV==="test"||N0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function uj(){if(N0.env.NODE_ENV==="test"||N0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof N0<"u"){let $=N0.type;if($==="renderer"||$==="worker")return!1;return!!(N0.versions&&(N0.versions.node||N0.versions.bun))}return!1}class If{async format($){let w=await uj(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:qw.pid,hostname:w(),environment:qw.env.NODE_ENV||"development",platform:qw.platform,version:qw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qw.env.NODE_ENV||qw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class TA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...mh},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new If,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??q$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let h=this.generateKeyId(),U=this.generateKey();this.currentKeyId=h,this.keys.set(h,U),this.encryptionKeys.set(h,{key:U,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...fA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...fA};return{...fA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:mh.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let h,U=0,Y=3,Z=1000;while(U<Y)try{try{try{await Aj(this.config.logDirectory,m8.F_OK|m8.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Jj(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:u0.from($);try{if(!Ih(this.currentLogFile))await Lh(this.currentLogFile,"",{mode:420});if(h=v8(this.currentLogFile,"a",420),wj(h,f,{flag:"a"}),u8(h),h!==void 0)yh(h),h=void 0;if((await Tw(this.currentLogFile)).size===0){if(await Lh(this.currentLogFile,f,{flag:"w",mode:420}),(await Tw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(U<Y-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,F);let j=Z*2**U;await new Promise((B)=>setTimeout(B,j)),U++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(h!==void 0)try{yh(h)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(U===Y-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}U++;let E=Z*2**(U-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(h){throw console.error("Debug: [writeToFile] Error in operation:",h),h}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Gw(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 Gw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Gw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(o())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((h)=>{console.error("Error rotating keys:",h)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let h=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Y=Math.max(1,U);if(h.length>Y)for(let[Z]of h.slice(Y))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return Mh(16).toString("hex")}generateKey(){return Mh(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=Mh(16),J=oB("aes-256-gcm",w,A),h=u0.concat([J.update($,"utf8"),J.final()]),U=J.getAuthTag();return{encrypted:u0.concat([A,h,U]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=g8(),h=[];J.on("data",(U)=>h.push(U)),J.on("end",()=>w(u0.from(u0.concat(h)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(o())return;let $=await Tw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let h=await g1(this.config.logDirectory),U=h.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),Y=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${Y}`;if(await Tw(A).catch(()=>null))try{if(await d8(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await l1(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(U.length===0&&!h.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await Lh(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let h=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${h}.log`);if(await Tw(A).catch(()=>null))await d8(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await g1(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,Z)=>Z.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await l1(Gw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=n8($),J=$j(w),h=g8();await hj(A,h,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),Ih(this.currentLogFile))try{let $=v8(this.currentLogFile,"r+");u8($),yh($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!o()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await g1(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await l1(Gw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?m.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:h,level:U,showTimestamp:Y=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(Y)B.push(w);if(U==="warning")B.push("WARN");else if(U==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(h),B.join(" ")}let f=q$.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${h}`;else if(U==="info"||U==="success")E=`${A} ${J} ${h}`;else E=`${A} ${J} ${m.cyan(h)}`;if(!Y)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Y)=>{let Z=Number.parseInt(Y,10);return Z<w[0].length?String(w[0][Z]):U});let A=/%([sdijfo%])/g,J=0,h=$.replace(A,(U,Y)=>{if(Y==="%")return"%";if(J>=w.length)return U;let Z=w[J++];switch(Y){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return U}});if(J<w.length)h+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return h}async log($,w,...A){let J=new Date,h=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Y,Z;if(w instanceof Error)Y=w.message,Z=w.stack;else Y=this.formatMessage(w,A);if(this.fancy&&!o()){let E=Qf[$],W=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:m.gray(Y),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:Y,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:m.green(Y),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:Y,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:Y,level:$}),console.error(F),Z){let j=Z.split(`
90
+ `);for(let B of j)if(B.trim()&&!B.includes(Y))console.error(this.formatConsoleMessage({timestamp:h,message:m.gray(` ${B}`),level:$,showTimestamp:!1}))}break}}else if(!o()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Y}`),Z)console.error(Z)}if(!this.shouldLog($))return;let f=`${U} ${this.environment}.${$.toUpperCase()}: ${Y}
91
+ `;if(Z)f+=`${Z}
92
+ `;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!o()){let A=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:m.blue("◐"),tag:A,message:`${m.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),h=Math.round(J-w),U=`${$} completed in ${h}ms`,Y=new Date,Z=this.formatConsoleTimestamp(Y),E=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
93
+ `,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!o()){let W=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:m.green("✓"),tag:W,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!o())console.error(E.trim());await this.writeToFile(E)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new TA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(o())throw Error("createReadStream is not supported in browser environments");if(!Ih(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return n8(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=u0.isBuffer($)?$:u0.from($,"base64"),h=J.slice(0,16),U=J.slice(-16),Y=J.slice(16,-16),Z=eB("aes-256-gcm",A,h);return Z.setAuthTag(U),u0.concat([Z.update(Y),Z.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return o()}isServerMode(){return!o()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w);if(this.fancy&&!o()){let U=$.split(`
94
+ `),Y=Math.max(...U.map((W)=>W.length))+2,Z=`┌${"─".repeat(Y)}┐`,f=`└${"─".repeat(Y)}┘`,E=U.map((W)=>{let F=" ".repeat(Y-W.length-2);return`│ ${W}${F} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:m.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:m.cyan(Z)})),E.forEach((W)=>console.error(this.formatConsoleMessage({timestamp:A,message:m.cyan(W),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:m.cyan(f),showTimestamp:!1}))}else if(!o())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let h=`${J} ${this.environment}.INFO: [BOX] ${$}
95
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(h)}async prompt($){if(o())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${m.cyan("?")} ${$} (y/n) `);let A=(J)=>{let h=J.toString().trim().toLowerCase();q$.stdin.removeListener("data",A);try{if(typeof q$.stdin.setRawMode==="function")q$.stdin.setRawMode(!1)}catch{}q$.stdin.pause(),console.error(""),w(h==="y"||h==="yes")};try{if(typeof q$.stdin.setRawMode==="function")q$.stdin.setRawMode(!0)}catch{}q$.stdin.resume(),q$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let Y=/%([sdijfo%])/g,Z=0;if(A=$.replace(Y,(f,E)=>{if(E==="%")return"%";if(Z>=w.length)return f;let W=w[Z++];switch(E){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return f}}),Z<w.length)A+=` ${w.slice(Z).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!o()){let Y=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",Z=m.blue("◐");console.error(`${Z} ${Y} ${m.cyan(A)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
96
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}progress($,w=""){if(!this.enabled||!this.fancy||o()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(Y,Z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,Y)),Z!==void 0)this.activeProgressBar.message=Z;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(Y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Y!==void 0)this.activeProgressBar.message=Y;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Y,Z="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;q$.stdout.write(`${"\r".padEnd(q$.stdout.columns||80)}\r`),this.log(Z,Y),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||o()||!q$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),h=$.barLength-J,U=m.green("━".repeat(J)),Y=m.gray("━".repeat(h)),Z=`[${U}${Y}]`,f=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",W=w||A===100?m.green("✓"):m.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",j=`\r${W}${F} ${Z} ${f}${E}`,B=q$.stdout.columns||80,T=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,q$.stdout.write($.lastRenderedLine),w)q$.stdout.write(`
97
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||o()||!q$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(o()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await g1(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=Gw(this.config.logDirectory,J);if($.before)try{if((await Tw(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await l1(J),console.warn(`Deleted log file: ${J}`)}catch(h){console.error(`Failed to delete log file ${J}:`,h)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function UA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&b(w[0])&&"id"in w[0]&&w[0].id===3&&b(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(b(w)&&b($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(b($)&&"arr"in $&&Array.isArray($.arr)&&b(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&b(w[0])&&b($[0])){let J=[...w];for(let h of $)if(b(h)&&"name"in h){if(!J.find((Y)=>b(Y)&&("name"in Y)&&Y.name===h.name))J.push(h)}else if(b(h)&&"path"in h){if(!J.find((Y)=>b(Y)&&("path"in Y)&&Y.path===h.path))J.push(h)}else if(!J.some((U)=>GA(U,h)))J.push(h);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}if(!b(w)||!b($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let h=w[J];if(h===null||h===void 0)continue;else if(b(h)&&b(A[J]))A[J]=UA(A[J],h);else if(Array.isArray(h)&&Array.isArray(A[J]))if(h.length>0&&A[J].length>0&&b(h[0])&&b(A[J][0])){let U=[...h];for(let Y of A[J])if(b(Y)&&"name"in Y){if(!U.find((f)=>b(f)&&("name"in f)&&f.name===Y.name))U.push(Y)}else if(b(Y)&&"path"in Y){if(!U.find((f)=>b(f)&&("path"in f)&&f.path===Y.path))U.push(Y)}else if(!U.some((Z)=>GA(Z,Y)))U.push(Y);A[J]=U}else if(h.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...h];for(let Y of A[J])if(!U.includes(Y))U.push(Y);A[J]=U}else A[J]=h;else A[J]=h}return A}function AU($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:UA($,w);if(Array.isArray($))return A==="replace"?w:UA($,w);if(!b(w)||!b($))return w;let J={...$};for(let h of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,h))continue;let U=w[h],Y=J[h];if(U===null||U===void 0)continue;if(Array.isArray(U)||Array.isArray(Y))if(A==="replace")J[h]=U;else J[h]=UA(Y,U);else if(b(U)&&b(Y))J[h]=AU(Y,U,A);else J[h]=U}return J}function GA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!GA($[A],w[A]))return!1;return!0}if(b($)&&b(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!GA($[h],w[h]))return!1}return!0}return!1}function b($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function wA($,w,A="replace"){if(!Kf($))return null;try{let J=await import($),h=J.default||J;if(typeof h!=="object"||h===null||Array.isArray(h))return null;try{return AU(w,h,A)}catch{return null}}catch{return null}}function vj($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),h={...w};function U(Y,Z=[]){let f={...Y};for(let[E,W]of Object.entries(Y)){let F=[...Z,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),B=`${J}_${F.map(j).join("_")}`,T=`${J}_${F.map((H)=>H.toUpperCase()).join("_")}`;if(A)N$.info(`Checking environment variable ${B} for config ${$}.${F.join(".")}`);if(typeof W==="object"&&W!==null&&!Array.isArray(W))f[E]=U(W,F);else{let H=E1.env[B]||E1.env[T];if(H!==void 0){if(A)N$.info(`Using environment variable ${H?B:T} for config ${$}.${F.join(".")}`);if(typeof W==="number")f[E]=Number(H);else if(typeof W==="boolean")f[E]=H.toLowerCase()==="true";else if(Array.isArray(W))try{let q=JSON.parse(H);if(Array.isArray(q))f[E]=q;else f[E]=H.split(",").map((G)=>G.trim())}catch{f[E]=H.split(",").map((q)=>q.trim())}else f[E]=H}}}return f}return U(h)}async function mj({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:h,verbose:U=!1,checkEnv:Y=!0,arrayStrategy:Z="replace"}){let f=Y&&typeof h==="object"&&h!==null&&!Array.isArray(h)?vj($,h,U):h,E=A||E1.cwd(),W=[".ts",".js",".mjs",".cjs",".json"];if(U)N$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let F=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),B=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,D$(E,"config"),D$(E,".config"),J?D$(E,J):void 0].filter(Boolean)));for(let q of H){if(U)N$.info(`Searching for configuration in: ${q}`);let R=[D$(E,"config"),D$(E,".config")].concat(J?[D$(E,J)]:[]).includes(q)?[...F,...j,...B,...T]:[...j,...F,...T,...B];for(let y of R)for(let L of W){let C=D$(q,`${y}${L}`),K=await wA(C,f,Z);if(K!==null){if(U)N$.success(`Configuration loaded from: ${C}`);return K}}}if($){let q=D$(Kh(),".config",$),G=["config",`${$}.config`];if(w)G.push(`${w}.config`);if(U)N$.info(`Checking user config directory: ${q}`);for(let R of G)for(let y of W){let L=D$(q,`${R}${y}`),C=await wA(L,f,Z);if(C!==null){if(U)N$.success(`Configuration loaded from user config directory: ${L}`);return C}}}if($){let q=D$(Kh(),".config"),G=[`.${$}.config`];if(w)G.push(`.${w}.config`);if(U)N$.info(`Checking user config directory for dotfile configs: ${q}`);for(let R of G)for(let y of W){let L=D$(q,`${R}${y}`),C=await wA(L,f,Z);if(C!==null){if(U)N$.success(`Configuration loaded from user config directory dotfile: ${L}`);return C}}}if($){let q=Kh(),G=[`.${$}.config`,`.${$}`];if(w)G.push(`.${w}.config`),G.push(`.${w}`);if(U)N$.info(`Checking user home directory for dotfile configs: ${q}`);for(let R of G)for(let y of W){let L=D$(q,`${R}${y}`),C=await wA(L,f,Z);if(C!==null){if(U)N$.success(`Configuration loaded from user home directory: ${L}`);return C}}}try{let q=D$(E,"package.json");if(Kf(q)){let G=await import(q),R=G[$];if(!R&&w){if(R=G[w],R&&U)N$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(U)N$.success(`Configuration loaded from package.json: ${R===G[$]?$:w}`);return AU(f,R,Z)}catch(y){if(U)N$.warn("Failed to merge package.json config:",y)}}}catch(q){if(U)N$.warn("Failed to load package.json:",q)}if(U)N$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function dj($,w={}){let A=FA.cwd();while(A.includes("storage"))A=b8(A,"..");let J=b8(A,$||"");if(w?.relative)return rB(FA.cwd(),J);return J}async function gj(){try{let $=await mj({name:"clarity",alias:"logging",defaultConfig:ZA,cwd:FA.cwd()});return{...ZA,...$||{}}}catch{return ZA}}function J$(){if(K0.env.NODE_ENV==="test"||K0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lj(){if(K0.env.NODE_ENV==="test"||K0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof K0<"u"){let $=K0.type;if($==="renderer"||$==="worker")return!1;return!!(K0.versions&&(K0.versions.node||K0.versions.bun))}return!1}class Lf{async format($){let w=await lj(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Kw.pid,hostname:w(),environment:Kw.env.NODE_ENV||"development",platform:Kw.platform,version:Kw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Kw.env.NODE_ENV||Kw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...dh},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Lf,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??S.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let h=this.generateKeyId(),U=this.generateKey();this.currentKeyId=h,this.keys.set(h,U),this.encryptionKeys.set(h,{key:U,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...EA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...EA};return{...EA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:dh.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!J$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let h,U=0,Y=3,Z=1000;while(U<Y)try{try{try{await Ej(this.config.logDirectory,r8.F_OK|r8.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Wj(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:G0.from($);try{if(!t1(this.currentLogFile))await Dh(this.currentLogFile,"",{mode:420});if(h=p8(this.currentLogFile,"a",420),Zj(h,f,{flag:"a"}),t8(h),h!==void 0)Sh(h),h=void 0;if((await Rw(this.currentLogFile)).size===0){if(await Dh(this.currentLogFile,f,{flag:"w",mode:420}),(await Rw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(U<Y-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,F);let j=Z*2**U;await new Promise((B)=>setTimeout(B,j)),U++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(h!==void 0)try{Sh(h)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(U===Y-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}U++;let E=Z*2**(U-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(h){throw console.error("Debug: [writeToFile] Error in operation:",h),h}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Nw(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 Nw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Nw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(J$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((h)=>{console.error("Error rotating keys:",h)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let h=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Y=Math.max(1,U);if(h.length>Y)for(let[Z]of h.slice(Y))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return Ch(16).toString("hex")}generateKey(){return Ch(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=Ch(16),J=Uj("aes-256-gcm",w,A),h=G0.isBuffer($)?$:G0.from($,"utf8"),U=J.update(h),Y=J.final(),Z=U.length+Y.length,f=J.getAuthTag(),E=G0.allocUnsafe(16+Z+16);return A.copy(E,0),U.copy(E,16),Y.copy(E,16+U.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=s8(),h=[];J.on("data",(U)=>h.push(U)),J.on("end",()=>w(G0.from(G0.concat(h)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(J$())return;if(!this.shouldWriteToFile())return;let $=await Rw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let h=await p1(this.config.logDirectory),U=h.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),Y=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${Y}`;if(await Rw(A).catch(()=>null))try{if(await a8(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await r1(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(U.length===0&&!h.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await Dh(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let h=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${h}.log`);if(await Rw(A).catch(()=>null))await a8(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await p1(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,Z)=>Z.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await r1(Nw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=l8($),J=fj(w),h=s8();await jj(A,h,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),t1(this.currentLogFile))try{let $=p8(this.currentLogFile,"r+");t8($),Sh($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!J$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await p1(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await r1(Nw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?_.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||J$())return!1;let $=typeof S.env.NO_COLOR<"u",w=S.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof S.stderr<"u"&&S.stderr.isTTY||typeof S.stdout<"u"&&S.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:h,level:U,showTimestamp:Y=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(Y)B.push(w);if(U==="warning")B.push("WARN");else if(U==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(h),B.join(" ")}let f=S.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${h}`;else if(U==="info"||U==="success")E=`${A} ${J} ${h}`;else E=`${A} ${J} ${_.cyan(h)}`;if(!Y)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Y)=>{let Z=Number.parseInt(Y,10);return Z<w[0].length?String(w[0][Z]):U});let A=/%([sdijfo%])/g,J=0,h=$.replace(A,(U,Y)=>{if(Y==="%")return"%";if(J>=w.length)return U;let Z=w[J++];switch(Y){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return U}});if(J<w.length)h+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return h}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,h)=>{let U=_.underline(_.blue(J)),Y=this.toAbsoluteFilePath(h);if(Y&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(Y)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${h}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),w=w.replace(/`([^`]+)`/g,(A,J)=>_.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>_.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>_.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>_.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>_.strikethrough(J)),w}supportsHyperlinks(){if(J$())return!1;let $=S.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=S.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(Fj(w)||w.startsWith("./")||w.startsWith("../"))w=Bj(w);else return null;return t1(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,h=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Y,Z;if(w instanceof Error)Y=w.message,Z=w.stack;else Y=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":xf[$],j=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:_.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:_.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
98
+ `);for(let H of T)if(H.trim()&&!H.includes(Y))console.error(this.formatConsoleMessage({timestamp:h,message:_.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!J$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Y}`),Z)console.error(Z)}if(!this.shouldLog($))return;let W=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
99
+ `;if(Z)W+=`${Z}
100
+ `;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress($,w=""){let A={update:(Z,f)=>{},finish:(Z)=>{},interrupt:(Z,f)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!J$()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Z,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Z),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!J$()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Z)},interrupt:(Z,f="info")=>{if(!J$()&&S.stdout.isTTY)S.stdout.write(`
101
+ `);if(this[f==="warning"?"warn":f](Z),this.activeProgressBar&&this.shouldStyleConsole()&&!J$()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":_.blue("◐"),tag:A,message:`${_.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),h=Math.round(J-w),U=`${$} completed in ${h}ms`,Y=new Date,Z=this.formatConsoleTimestamp(Y),E=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
102
+ `,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":_.green("✓"),tag:W,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!J$())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new qA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(J$())throw Error("createReadStream is not supported in browser environments");if(!t1(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return l8(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=G0.isBuffer($)?$:G0.from($,"base64"),h=J.subarray(0,16),U=J.subarray(J.length-16),Y=J.subarray(16,J.length-16),Z=Yj("aes-256-gcm",A,h);Z.setAuthTag(U);let f=Z.update(Y),E=Z.final(),W=f.length+E.length,F=G0.allocUnsafe(W);return f.copy(F,0),E.copy(F,f.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return J$()}isServerMode(){return!J$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:h,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=h.split(`
103
+ `),f=Math.max(...Z.map((j)=>j.length))+2,E=`┌${"─".repeat(f)}┐`,W=`└${"─".repeat(f)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:_.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:_.cyan(E),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:_.cyan(W),showTimestamp:!1}))}else if(!J$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Y=`${J} ${this.environment}.INFO: [BOX] ${U}
104
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}async prompt($){if(J$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${_.cyan("?")} ${$} (y/n) `);let A=(J)=>{let h=J.toString().trim().toLowerCase();S.stdin.removeListener("data",A);try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!1)}catch{}S.stdin.pause(),console.error(""),w(h==="y"||h==="yes")};try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!0)}catch{}S.stdin.resume(),S.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,E=0;if(A=$.replace(f,(W,F)=>{if(F==="%")return"%";if(E>=w.length)return W;let j=w[E++];switch(F){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return W}}),E<w.length)A+=` ${w.slice(E).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:J,fileText:h}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${_.blue("◐")} `;console.error(`${E}${f} ${_.cyan(J)}`)}let Z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${h}
105
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!S.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),h=$.barLength-J,U=_.green("━".repeat(J)),Y=_.gray("━".repeat(h)),Z=`[${U}${Y}]`,f=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",W=this.options.showIcons===!1?"":w||A===100?_.green("✓"):_.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${_.gray(this.formatTag(this.name))}`:"",j=`\r${W}${F} ${Z} ${f}${E}`,B=S.stdout.columns||80,T=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,S.stdout.write($.lastRenderedLine),w)S.stdout.write(`
106
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||J$()||!S.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(J$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await p1(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=Nw(this.config.logDirectory,J);if($.before)try{if((await Rw(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await r1(J),console.warn(`Deleted log file: ${J}`)}catch(h){console.error(`Failed to delete log file ${J}:`,h)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function Cf($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:h=()=>!0,fallback:U}=w,Y=Error("Unknown error occurred");for(let Z=0;Z<=A;Z++)try{return await $()}catch(f){if(Y=f instanceof Error?f:Error(String(f)),Z===A||!h(Y))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(U!==void 0)return U;throw Y instanceof Error?Y:Error(`Unknown error: ${String(Y)}`)}function Sf($){return $ instanceof n$}function tj($){return $ instanceof RA}function pj($){if(Sf($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((A)=>$.message.toLowerCase().includes(A.toLowerCase()))}class LA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:J,useCamelCase:h=!0,useBackwardCompatibility:U=!0,customParsers:Y={},verbose:Z=!1,trackPerformance:f=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let W=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],W,{useCamelCase:h,useBackwardCompatibility:U,customParsers:Y,verbose:Z,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return B1.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[h,U]of Object.entries($)){let Y=[...w,h],Z=Y.map((W)=>this.formatEnvKey(W,J.useCamelCase)),f=`${A}_${Z.join("_")}`,E=J.useBackwardCompatibility?`${A}_${Y.map((W)=>W.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Y,A,J);else{let W=a1.env[f]||(E?a1.env[E]:void 0);if(W!==void 0){if(J.verbose){let F=a1.env[f]?f:E}try{$[h]=this.parseEnvironmentValue(W,typeof U,f,J.customParsers,J.configName)}catch(F){if(F instanceof NA)throw F;throw v0.envVar(f,W,typeof U,J.configName)}}}}}parseEnvironmentValue($,w,A,J,h){for(let[U,Y]of Object.entries(J))try{return Y($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,w))try{return U.parse($)}catch{throw v0.envVar(A,$,`${w} (via ${U.name} parser)`,h)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,h]of Object.entries(a1.env))if(J.startsWith(A)&&h!==void 0)w[J]=h;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(h){J.push(`Cannot parse value "${w}" as ${A}: ${h}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:h="text"}=A,U=J||this.generateEnvPrefix($),Y=[];switch(this.extractEnvVarInfo(w,[],U,Y),h){case"markdown":return this.formatAsMarkdown(Y,$);case"json":return JSON.stringify(Y,null,2);default:return this.formatAsText(Y,$)}}extractEnvVarInfo($,w,A,J){for(let[h,U]of Object.entries($)){let Y=[...w,h],Z=`${A}_${Y.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Y,A,J);else J.push({key:Z,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Y.join(".")}`,example:this.generateExample(U)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
107
+
108
+ `;for(let J of $)A+=`${J.key}
109
+ `,A+=` Type: ${J.type}
110
+ `,A+=` Description: ${J.description}
111
+ `,A+=` Example: ${J.example}
112
+
113
+ `;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
114
+
115
+ `;A+=`| Variable | Type | Description | Example |
116
+ `,A+=`|----------|------|-------------|----------|
117
+ `;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
118
+ `;return A}}function rj($,w){let A=Xf("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function Df($,w,A={}){return Vf($,w,A,new WeakMap)}function Vf($,w,A,J){let{arrayMergeMode:h="replace",skipNullish:U=!1,customMerger:Y}=A;if(w===null||w===void 0)return U?$:w;if(Y){let Z=Y($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return Of($,w,h,J);if(!r$(w)||!r$($))return w;return ej($,w,A,J)}function Of($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return aj($,w);case"smart":return sj($,w,J);default:return w}return w}function aj($,w){let A=[...w];for(let J of $)if(!A.some((h)=>vh(h,J)))A.push(J);return A}function sj($,w,A){if(w.length===0)return $;if($.length===0)return w;if(r$(w[0])&&r$($[0]))return oj($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}function oj($,w,A){let J=[...w];for(let h of $){if(!r$(h)){J.push(h);continue}let U=["id","name","key","path","type"],Y=!1;for(let Z of U)if(Z in h){if(J.find((E)=>r$(E)&&(Z in E)&&E[Z]===h[Z])){Y=!0;break}}if(!Y)J.push(h)}return J}function ej($,w,A,J){let h=w;if(r$(h)&&J.has(h))return J.get(h);let U={...$};if(r$(h))J.set(h,U);for(let Y in h){if(!Object.prototype.hasOwnProperty.call(h,Y))continue;let Z=h[Y],f=U[Y];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){U[Y]=Z;continue}if(r$(Z)&&r$(f))U[Y]=Vf(f,Z,A,J);else if(Array.isArray(Z)||Array.isArray(f))U[Y]=Of(f,Z,A.arrayMergeMode||"smart",J);else U[Y]=Z}return U}function JU($,w,A="replace"){return Df($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function vh($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!vh($[A],w[A]))return!1;return!0}if(r$($)&&r$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!vh($[h],w[h]))return!1}return!0}return!1}function r$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class CA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:h=!0,cacheTtl:U,trackPerformance:Y=!0,verbose:Z=!1}=A;if(h){let E=Lw.getWithFileCheck("file",$);if(E){if(Z)console.log(`Configuration loaded from cache: ${$}`);return E}}let f=async()=>{if(!s1($))return null;try{let E=`?t=${Date.now()}`,W=await import($+E),F=W.default||W,j="default"in W,B=Object.keys(W).length>0;if(!j&&!B)throw new W1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new W1($,Error("Configuration must export a valid object"),"unknown");let q={config:JU(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(h)Lw.setWithFileCheck("file",q,$,U);return q}catch(E){throw E instanceof Error?v0.configLoad($,E):v0.configLoad($,Error(String(E)))}};if(Y)return B1.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let h=await this.loadFromPath(J,w,A);if(h)return h}catch(h){if(h instanceof Error&&h.name==="ConfigLoadError")throw h;if(A.verbose)console.warn(`Failed to load config from ${J}:`,h)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),h=[];for(let U of J)for(let Y of this.extensions)h.push(Vh(w,`${U}${Y}`));return h}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return Cf(async()=>{return s1($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!s1($))return J;if(w||A){let h=this.generateNamePatterns(w||"",A);for(let U of h)for(let Y of this.extensions){let Z=Vh($,`${U}${Y}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:h}=await import("fs"),U=h($);for(let Y of U)if(this.looksLikeConfigFile(Y)){let Z=Vh($,Y);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!s1($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:h}=await import("fs"),U=h($,"utf8");JSON.parse(U)}catch(h){w.push(`Invalid JSON syntax: ${h}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let h=await this.loadFromPath(J,{},w);if(h)A.set(J,h.config)}catch(h){if(w.verbose)console.warn(`Failed to preload ${J}:`,h)}})),A}}class hU{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:h=!0,validateTypes:U=!0,customRules:Y=[],trackPerformance:Z=!0,verbose:f=!1}=A,E=async()=>{let W=[],F=[],j={stopOnFirstError:J,validateRequired:h,validateTypes:U,customRules:Y,trackPerformance:Z,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...Y],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return W.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:W,warnings:F}}};if(Z)return await B1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!zj(w))throw new F1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),h=J.default||J;if(Array.isArray(h))return this.validateWithRules($,h,A);else return this.validateWithJSONSchema($,h,A)}catch(J){throw new F1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],h=[];return this.validateObjectAgainstSchema($,w,"",J,h,A),{isValid:J.length===0,errors:J,warnings:h}}validateObjectAgainstSchema($,w,A,J,h,U){if(U.validateTypes&&w.type){let Y=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(Y)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${Y}`,expected:Z.join(" or "),actual:Y,rule:"type"}),U.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),U.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let Y=0;Y<$.length;Y++){let Z=A?`${A}[${Y}]`:`[${Y}]`;if(this.validateObjectAgainstSchema($[Y],w.items,Z,J,h,U),U.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Y=$;if(U.validateRequired&&w.required){for(let Z of w.required)if(!(Z in Y)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(w.properties){for(let[Z,f]of Object.entries(w.properties))if(Z in Y){let E=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(Y[Z],f,E,J,h,U),U.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(Y))if(!Z.has(f))h.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],h=[];for(let U of w)try{let Y=this.getValueByPath($,U.path),Z=this.validateWithRule(Y,U,U.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(Y){J.push({path:U.path,message:`Rule validation failed: ${Y}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:h}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let h=Array.isArray($)?"array":typeof $;if(h!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${h}`,expected:w.type,actual:h,rule:"type"})}if(w.min!==void 0){let h=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(h<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:h,rule:"min"})}if(w.max!==void 0){let h=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(h>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:h,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let h=w.validator($);if(h)J.push({path:A,message:w.message||h,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let h of A)if(J&&typeof J==="object"&&h in J)J=J[h];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,h,U,Y]=J;w.push({path:h,required:!U,type:this.mapTypeScriptType(Y)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:bf},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class UU{fileLoader=new CA;envProcessor=new LA;validator=new hU;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:h,validate:U,...Y}=$;try{if(A?.enabled){let f=this.checkCache(Y.name||"",Y);if(f)return f}let Z;try{Z=await this.loadConfigurationStrategies(Y,!0,A)}catch(f){let E=Y.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(E)throw f;Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`No configuration file found for "${Y.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let W=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),F=!W&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),j=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(E&&(j||W))throw f;if(F&&(!E||!j))Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(h||U)await this.validateConfiguration(Z.config,h,U,Y.name);if(A?.enabled&&Z)this.cacheResult(Y.name||"",Z,A,Y);if(J?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:Y.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(f);if(J.slowThreshold&&f.duration>J.slowThreshold)J0.warn(`Slow configuration loading detected: ${f.duration}ms for ${Y.name}`);Z.metrics=f}return Z}catch(Z){let f=Date.now()-w;throw J0.error(`Configuration loading failed after ${f}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:h,cwd:U,configDir:Y,defaultConfig:Z,checkEnv:f=!0,arrayStrategy:E="replace",verbose:W=!1}=$,F=U||s0.cwd(),j=[],B=await this.loadLocalConfiguration(J,h,F,Y,Z,E,W,f,A);if(B)return j.push(...this.getLocalSearchPaths(J,h,F,Y)),this.finalizeResult(B,j,f,J,W);let T=await this.loadHomeConfiguration(J,h,Z,E,W,f);if(T)return j.push(...this.getHomeSearchPaths(J,h)),this.finalizeResult(T,j,f,J,W);let H=await this.loadPackageJsonConfiguration(J,h,F,Z,E,W,f);if(H)return j.push(V$(F,"package.json")),this.finalizeResult(H,j,f,J,W);if(j.push(...this.getAllSearchPaths(J,h,F,Y)),w)throw v0.configNotFound(J,j,h);return{...await this.applyEnvironmentVariables(J,Z,f,W),warnings:[`No configuration file found for "${J}"${h?` or alias "${h}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,h,U,Y,Z,f){let E=Z?Z1($,h,Y):h,W=this.getLocalDirectories(A,J);for(let F of W){if(Y)J0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:U,verbose:Y,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(B){if(Y)J0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,h,U){if(!$)return null;let Y=U?Z1($,A,h):A,Z=[V$(Hw(),".config",$),V$(Hw(),".config"),Hw()];for(let f of Z){if(h)J0.info(`Checking home directory: ${f}`);let E=this.fileLoader.generateConfigPaths($,f,w),W=await this.fileLoader.tryLoadFromPaths(E,Y,{arrayStrategy:J,verbose:h});if(W){if(h)J0.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,w,A,J,h,U,Y){let Z=Y?Z1($,J,U):J;try{let f=V$(A,"package.json");if(!nh(f))return null;let E=await import(f),W=E[$],F=$;if(!W&&w)W=E[w],F=w;if(W&&typeof W==="object"&&!Array.isArray(W)){if(U)J0.success(`Configuration loaded from package.json: ${F}`);return{config:JU(Z,W,h),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(U)J0.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:Z1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,h){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let h=[];if(A){let U=A($);if(U)h.push(...U)}if(w){let U=await this.validator.validateConfiguration($,w);if(!U.isValid)h.push(...U.errors.map((Y)=>Y.path?`${Y.path}: ${Y.message}`:Y.message))}if(h.length>0)throw v0.configValidation(J||"unknown",h,J)}checkCache($,w){let A=this.generateCacheKey($,w);return Lw.get(A)||null}cacheResult($,w,A,J){let h=this.generateCacheKey($,J);Lw.set(h,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,V$($,"config"),V$($,".config"),w?V$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let h=[];return h.push(...this.getLocalSearchPaths($,w,A,J)),h.push(...this.getHomeSearchPaths($,w)),h.push(V$(A,"package.json")),h}getLocalSearchPaths($,w,A,J){let h=this.getLocalDirectories(A,J),U=[];for(let Y of h)U.push(...this.fileLoader.generateConfigPaths($,Y,w));return U}getHomeSearchPaths($,w){if(!$)return[];let A=[V$(Hw(),".config",$),V$(Hw(),".config"),Hw()],J=[];for(let h of A)J.push(...this.fileLoader.generateConfigPaths($,h,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function Yf($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),J=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||J}async function $z($){return y0.loadConfig({...$,__strictErrorHandling:!0})}async function _f($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await y0.loadConfig($);else J=await y0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let h=J instanceof Error?J.name:"UnknownError",U=J instanceof Error?J.message:String(J);if(!(h==="ConfigNotFoundError"||h==="ConfigLoadError"||h==="ConfigValidationError"||U.includes("config"))&&$.verbose)J0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let Z=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await y0.applyEnvironmentVariables(Z.name||"",w,!0,Z.verbose||!1))?.config??w;return w}}async function wz($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await y0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&Yf(A)))return(await y0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await y0.loadConfig({...$,cwd:$.cwd||s0.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&Yf(w)))return(await y0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function Az($,w,A="replace"){let J=new CA;try{let h=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return h?h.config:null}catch{return null}}function Z1($,w,A=!1){let J=new LA,h=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Y,Z=[]){let f={...Y};for(let[E,W]of Object.entries(Y)){let F=[...Z,E],j=[`${h}_${F.join("_").toUpperCase()}`,`${h}_${F.map((H)=>H.toUpperCase()).join("")}`,`${h}_${F.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,T;for(let H of j)if(B=s0.env[H],B!==void 0){T=H;break}if(B!==void 0&&T)if(typeof W==="boolean")f[E]=["true","1","yes"].includes(B.toLowerCase());else if(typeof W==="number"){let H=Number(B);if(!Number.isNaN(H))f[E]=H}else if(Array.isArray(W))try{f[E]=JSON.parse(B)}catch{f[E]=B.split(",").map((H)=>H.trim())}else f[E]=B;else if(W&&typeof W==="object"&&!Array.isArray(W))f[E]=U(W,F)}return f}return U(w)}function Jz($){let w=V$(s0.cwd(),$.configDir),A=V$(s0.cwd(),$.generatedDir),J=V$(A,"config-types.ts");if(!nh(i8(J)))gB(i8(J),{recursive:!0,mode:511});let h=nh(w)?lB(w).map((Y)=>Y.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],U=`// Generated by bunfig v${Xz}
119
+ export type ConfigNames = ${h.length?`'${h.join("' | '")}'`:"string"}
120
+ `;tB(J,U,{mode:438})}function hz($){let w=null,A=null,J=()=>{if(!A)A=_f($).then((U)=>{return w=U,U},(U)=>{let Y="defaultConfig"in $?$.defaultConfig:{};if(w=Y,"verbose"in $&&$.verbose)J0.warn("Config loading failed, using defaults:",[U instanceof Error?U:Error(String(U))]);return Y});return A},h="defaultConfig"in $?$.defaultConfig:{};return w=h,J(),new Proxy({},{get(U,Y){if(w)return w[Y];let Z=h[Y];return J(),Z},has(U,Y){return Y in(w||h)},ownKeys(){return Object.keys(w||h)},getOwnPropertyDescriptor(U,Y){return Object.getOwnPropertyDescriptor(w||h,Y)},set(U,Y,Z){if(!w)w={...h};return w[Y]=Z,!0}})}function Uz($){let w=o8(Gj.cwd(),$?.configDir||"./config");function A(){if(!Hj(w))return[];let h=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),U=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Y=Tj(w).filter((f)=>h.has(Oh(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),Z=new Map;for(let{base:f,file:E}of Y){let W=Oh(E).toLowerCase(),F=Z.get(f);if(!F){Z.set(f,E);continue}let j=Oh(F).toLowerCase();if(U.indexOf(W)<U.indexOf(j))Z.set(f,E)}return Array.from(Z.entries()).map(([f,E])=>({base:f,file:E})).sort((f,E)=>f.base.localeCompare(E.base))}function J(){let h=A(),U=h.map((E)=>E.base),Y=U.length?U.map((E)=>`'${E}'`).join(" | "):"string",Z=h.length?`{
121
+ ${h.map((E)=>{let W=o8(w,E.file).replace(/\\/g,"/");return` '${E.base}': typeof import('${W}').default`}).join(`,
122
+ `)}
123
+ }`:"Record<string, any>";return`export type ConfigNames = ${Y}
124
+ export type ConfigByName = ${Z}
125
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
126
+ export type ConfigOf = Config
127
+ `}return{name:"bunfig-plugin",setup(h){h.onResolve({filter:/^virtual:bunfig-types$/},(U)=>{return{path:U.path,namespace:"bunfig-virtual"}}),h.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}var Xf,Lw,B1,kf,Yz,fz,ff,YA,mh,R$,m,Zz,Zf,Ez,Ef,Wz,Fz,Qh,Bz,Wf,Ff,xh,jz,zz,Hz,Tz,fA,Qf,Gz,N$,qz,Rz,Bf,ZA,dh,h$,_,Nz,jf,Kz,zf,Mz,yz,Ph,Iz,Hf,Tf,Lz,ih,Cz,Sz,Dz,Vz,Oz,EA,xf,_z,Xz="0.15.6",n$,RA,W1,gh,lh,NA,th,ph,F1,rh,ah,v0,Pf,bf,J0,y0,cf,nf,kz=kj(async()=>{Xf=import.meta.require,Lw=new eh,B1=new $U,kf={createKey:Qj,isEquivalent:xj,estimateMemoryUsage:Pj},Yz=jA(uh.cwd(),"config"),fz=jA(uh.cwd(),"src/generated"),ff=BA.env.CLARITY_LOG_DIR||aB(cj(),"logs"),YA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ff,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},mh=await nj(),R$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},m=R$,Zz=R$.red,Zf=R$.green,Ez=R$.yellow,Ef=R$.blue,Wz=R$.magenta,Fz=R$.cyan,Qh=R$.white,Bz=R$.gray,Wf=R$.bgRed,Ff=R$.bgYellow,xh=R$.bold,jz=R$.dim,zz=R$.italic,Hz=R$.underline,Tz=R$.reset,fA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Qf={debug:"\uD83D\uDD0D",info:Ef("ℹ"),success:Zf("✓"),warning:Ff(Qh(xh(" WARN "))),error:Wf(Qh(xh(" ERROR ")))},Gz=new TA("stacks"),N$=new TA("bunfig",{showTags:!0}),qz=D$(E1.cwd(),"config"),Rz=D$(E1.cwd(),"src/generated"),Bf=FA.env.CLARITY_LOG_DIR||pB(dj(),"logs"),ZA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Bf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},dh=await gj(),h$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},_=h$,Nz=h$.red,jf=h$.green,Kz=h$.yellow,zf=h$.blue,Mz=h$.magenta,yz=h$.cyan,Ph=h$.white,Iz=h$.gray,Hf=h$.bgRed,Tf=h$.bgYellow,Lz=h$.bgGray,ih=h$.bold,Cz=h$.dim,Sz=h$.italic,Dz=h$.underline,Vz=h$.strikethrough,Oz=h$.reset,EA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xf={debug:"\uD83D\uDD0D",info:zf("ℹ"),success:jf("✓"),warning:Tf(Ph(ih(" WARN "))),error:Hf(Ph(ih(" ERROR ")))},_z=new qA("stacks"),n$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,J])=>`${A}: ${J}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},RA=class extends n${code="CONFIG_NOT_FOUND";constructor(w,A,J){let h=J?` or alias "${J}"`:"";super(`Configuration "${w}"${h} not found`,{configName:w,alias:J,searchPaths:A,searchPathCount:A.length})}},W1=class extends n${code="CONFIG_LOAD_ERROR";constructor(w,A,J){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},gh=class extends n${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},lh=class extends n${code="CONFIG_MERGE_ERROR";constructor(w,A,J,h){super(`Failed to merge configuration from "${w}" with "${A}": ${J.message}`,{sourcePath:w,targetPath:A,configName:h,originalError:J.name,originalMessage:J.message});this.cause=J}},NA=class extends n${code="ENV_VAR_ERROR";constructor(w,A,J,h){super(`Failed to parse environment variable "${w}" with value "${A}" as ${J}`,{envKey:w,envValue:A,expectedType:J,configName:h})}},th=class extends n${code="FILE_SYSTEM_ERROR";constructor(w,A,J){super(`File system ${w} failed for "${A}": ${J.message}`,{operation:w,path:A,originalError:J.name,originalMessage:J.message});this.cause=J}},ph=class extends n${code="TYPE_GENERATION_ERROR";constructor(w,A,J){super(`Failed to generate types from "${w}" to "${A}": ${J.message}`,{configDir:w,outputPath:A,originalError:J.name,originalMessage:J.message});this.cause=J}},F1=class extends n${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,J){super(`Schema validation failed${J?` for config "${J}"`:""}`,{schemaPath:w,configName:J,validationErrors:A,errorCount:A.length})}},rh=class extends n${code="BROWSER_CONFIG_ERROR";constructor(w,A,J,h){super(`Failed to fetch configuration from "${w}": ${A} ${J}`,{endpoint:w,status:A,statusText:J,configName:h})}},ah=class extends n${code="PLUGIN_ERROR";constructor(w,A,J){super(`Plugin "${w}" failed during ${A}: ${J.message}`,{pluginName:w,operation:A,originalError:J.name,originalMessage:J.message});this.cause=J}},v0={configNotFound($,w,A){return new RA($,w,A)},configLoad($,w,A){return new W1($,w,A)},configValidation($,w,A){return new gh($,w,A)},configMerge($,w,A,J){return new lh($,w,A,J)},envVar($,w,A,J){return new NA($,w,A,J)},fileSystem($,w,A){return new th($,w,A)},typeGeneration($,w,A){return new ph($,w,A)},schemaValidation($,w,A){return new F1($,w,A)},browserConfig($,w,A,J){return new rh($,w,A,J)},plugin($,w,A){return new ah($,w,A)}},Pf={replace:"replace",concat:"concat",smart:"smart"},bf=/^https?:\/\//,J0=new qA("bunfig",{showTags:!0}),y0=new UU,cf=V$(s0.cwd(),"config"),nf=V$(s0.cwd(),"src/generated")});function Qz($,w={}){let A=zA.cwd();while(A.includes("storage"))A=e8(A,"..");let J=e8(A,$||"");if(w?.relative)return Rj(zA.cwd(),J);return J}var xz=zA.env.CLARITY_LOG_DIR||qj(Qz(),"logs"),uf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},KA={...uf},gq=(async()=>{try{let{loadConfig:$}=await kz().then(()=>yf),w=await $({name:"clarity",alias:"logging",defaultConfig:uf,cwd:zA.cwd()});if(w)Object.assign(KA,w)}catch{}return KA})();function U$(){if(M0.env.NODE_ENV==="test"||M0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Pz(){if(M0.env.NODE_ENV==="test"||M0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof M0<"u"){let $=M0.type;if($==="renderer"||$==="worker")return!1;return!!(M0.versions&&(M0.versions.node||M0.versions.bun))}return!1}class vf{async format($){let w=await Pz(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Iw.pid,hostname:w(),environment:Iw.env.NODE_ENV||"development",platform:Iw.platform,version:Iw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Iw.env.NODE_ENV||Iw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var j$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},Q=j$,lq=j$.red,iz=j$.green,tq=j$.yellow,bz=j$.blue,pq=j$.magenta,rq=j$.cyan,Gf=j$.white,aq=j$.gray,cz=j$.bgRed,nz=j$.bgYellow,sq=j$.bgGray,qf=j$.bold,oq=j$.dim,eq=j$.italic,$6=j$.underline,w6=j$.strikethrough,A6=j$.reset,bh={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},uz={debug:"\uD83D\uDD0D",info:bz("ℹ"),success:iz("✓"),warning:nz(Gf(qf(" WARN "))),error:cz(Gf(qf(" ERROR ")))};class SA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...KA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new vf,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let h=this.generateKeyId(),U=this.generateKey();this.currentKeyId=h,this.keys.set(h,U),this.encryptionKeys.set(h,{key:U,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...bh,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...bh};return{...bh,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:KA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!U$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let h,U=0,Y=3,Z=1000;while(U<Y)try{try{try{await Ij(this.config.logDirectory,Jf.F_OK|Jf.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Lj(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:q0.from($);try{if(!o1(this.currentLogFile))await kh(this.currentLogFile,"",{mode:420});if(h=Af(this.currentLogFile,"a",420),yj(h,f,{flag:"a"}),wf(h),h!==void 0)Xh(h),h=void 0;if((await Mw(this.currentLogFile)).size===0){if(await kh(this.currentLogFile,f,{flag:"w",mode:420}),(await Mw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(U<Y-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,F);let j=Z*2**U;await new Promise((B)=>setTimeout(B,j)),U++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(h!==void 0)try{Xh(h)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(U===Y-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}U++;let E=Z*2**(U-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(h){throw console.error("Debug: [writeToFile] Error in operation:",h),h}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return yw(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 yw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return yw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(U$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((h)=>{console.error("Error rotating keys:",h)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let h=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Y=Math.max(1,U);if(h.length>Y)for(let[Z]of h.slice(Y))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return _h(16).toString("hex")}generateKey(){return _h(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=_h(16),J=Nj("aes-256-gcm",w,A),h=q0.isBuffer($)?$:q0.from($,"utf8"),U=J.update(h),Y=J.final(),Z=U.length+Y.length,f=J.getAuthTag(),E=q0.allocUnsafe(16+Z+16);return A.copy(E,0),U.copy(E,16),Y.copy(E,16+U.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=Uf(),h=[];J.on("data",(U)=>h.push(U)),J.on("end",()=>w(q0.from(q0.concat(h)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(U$())return;if(!this.shouldWriteToFile())return;let $=await Mw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let h=await e1(this.config.logDirectory),U=h.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),Y=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${Y}`;if(await Mw(A).catch(()=>null))try{if(await hf(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await $A(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(U.length===0&&!h.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await kh(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let h=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${h}.log`);if(await Mw(A).catch(()=>null))await hf(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await e1(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,Z)=>Z.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await $A(yw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=$f($),J=Mj(w),h=Uf();await Dj(A,h,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),o1(this.currentLogFile))try{let $=Af(this.currentLogFile,"r+");wf($),Xh($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!U$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await e1(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await $A(yw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?Q.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||U$())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:h,level:U,showTimestamp:Y=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(Y)B.push(w);if(U==="warning")B.push("WARN");else if(U==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(h),B.join(" ")}let f=D.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${h}`;else if(U==="info"||U==="success")E=`${A} ${J} ${h}`;else E=`${A} ${J} ${Q.cyan(h)}`;if(!Y)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Y)=>{let Z=Number.parseInt(Y,10);return Z<w[0].length?String(w[0][Z]):U});let A=/%([sdijfo%])/g,J=0,h=$.replace(A,(U,Y)=>{if(Y==="%")return"%";if(J>=w.length)return U;let Z=w[J++];switch(Y){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return U}});if(J<w.length)h+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return h}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,h)=>{let U=Q.underline(Q.blue(J)),Y=this.toAbsoluteFilePath(h);if(Y&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(Y)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${h}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),w=w.replace(/`([^`]+)`/g,(A,J)=>Q.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>Q.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>Q.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>Q.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>Q.strikethrough(J)),w}supportsHyperlinks(){if(U$())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=D.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(Cj(w)||w.startsWith("./")||w.startsWith("../"))w=Sj(w);else return null;return o1(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,h=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Y,Z;if(w instanceof Error)Y=w.message,Z=w.stack;else Y=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":uz[$],j=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:Q.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:Q.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
128
+ `);for(let H of T)if(H.trim()&&!H.includes(Y))console.error(this.formatConsoleMessage({timestamp:h,message:Q.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!U$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Y}`),Z)console.error(Z)}let W=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
129
+ `;if(Z)W+=`${Z}
130
+ `;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress($,w=""){let A={update:(Z,f)=>{},finish:(Z)=>{},interrupt:(Z,f)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!U$()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Z,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Z),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!U$()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Z)},interrupt:(Z,f="info")=>{if(!U$()&&D.stdout.isTTY)D.stdout.write(`
131
+ `);if(this[f==="warning"?"warn":f](Z),this.activeProgressBar&&this.shouldStyleConsole()&&!U$()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":Q.blue("◐"),tag:A,message:`${Q.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),h=Math.round(J-w),U=`${$} completed in ${h}ms`,Y=new Date,Z=this.formatConsoleTimestamp(Y),E=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
132
+ `,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":Q.green("✓"),tag:W,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!U$())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new SA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(U$())throw Error("createReadStream is not supported in browser environments");if(!o1(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $f(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=q0.isBuffer($)?$:q0.from($,"base64"),h=J.subarray(0,16),U=J.subarray(J.length-16),Y=J.subarray(16,J.length-16),Z=Kj("aes-256-gcm",A,h);Z.setAuthTag(U);let f=Z.update(Y),E=Z.final(),W=f.length+E.length,F=q0.allocUnsafe(W);return f.copy(F,0),E.copy(F,f.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U$()}isServerMode(){return!U$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:h,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=h.split(`
133
+ `),f=Math.max(...Z.map((j)=>j.length))+2,E=`┌${"─".repeat(f)}┐`,W=`└${"─".repeat(f)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:Q.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:Q.cyan(E),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:Q.cyan(W),showTimestamp:!1}))}else if(!U$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Y=`${J} ${this.environment}.INFO: [BOX] ${U}
134
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}async prompt($){if(U$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${Q.cyan("?")} ${$} (y/n) `);let A=(J)=>{let h=J.toString().trim().toLowerCase();D.stdin.removeListener("data",A);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),w(h==="y"||h==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,E=0;if(A=$.replace(f,(W,F)=>{if(F==="%")return"%";if(E>=w.length)return W;let j=w[E++];switch(F){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return W}}),E<w.length)A+=` ${w.slice(E).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:J,fileText:h}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${Q.blue("◐")} `;console.error(`${E}${f} ${Q.cyan(J)}`)}let Z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${h}
135
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),h=$.barLength-J,U=Q.green("━".repeat(J)),Y=Q.gray("━".repeat(h)),Z=`[${U}${Y}]`,f=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",W=this.options.showIcons===!1?"":w||A===100?Q.green("✓"):Q.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${Q.gray(this.formatTag(this.name))}`:"",j=`\r${W}${F} ${Z} ${f}${E}`,B=D.stdout.columns||80,T=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,D.stdout.write($.lastRenderedLine),w)D.stdout.write(`
136
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||U$()||!D.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(U$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await e1(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=yw(this.config.logDirectory,J);if($.before)try{if((await Mw(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await $A(J),console.warn(`Deleted log file: ${J}`)}catch(h){console.error(`Failed to delete log file ${J}:`,h)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var J6=new SA("stacks");class h0 extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}}class mf extends h0{code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],h="";if(J.length===1)h=` or alias "${J[0]}"`;else if(J.length>1)h=` or aliases ${J.map((U)=>`"${U}"`).join(", ")}`;super(`Configuration "${$}"${h} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}}class MA extends h0{code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}}class df extends h0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}}class gf extends h0{code="CONFIG_MERGE_ERROR";constructor($,w,A,J){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}}class YU extends h0{code="ENV_VAR_ERROR";constructor($,w,A,J){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:J})}}class lf extends h0{code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}}class tf extends h0{code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}}class yA extends h0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}}class pf extends h0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}}class rf extends h0{code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}}var Cw={configNotFound($,w,A){return new mf($,w,A)},configLoad($,w,A){return new MA($,w,A)},configValidation($,w,A){return new df($,w,A)},configMerge($,w,A,J){return new gf($,w,A,J)},envVar($,w,A,J){return new YU($,w,A,J)},fileSystem($,w,A){return new lf($,w,A)},typeGeneration($,w,A){return new tf($,w,A)},schemaValidation($,w,A){return new yA($,w,A)},browserConfig($,w,A,J){return new pf($,w,A,J)},plugin($,w,A){return new rf($,w,A)}};async function vz($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:h=()=>!0,fallback:U}=w,Y=Error("Unknown error occurred");for(let Z=0;Z<=A;Z++)try{return await $()}catch(f){if(Y=f instanceof Error?f:Error(String(f)),Z===A||!h(Y))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(U!==void 0)return U;throw Y instanceof Error?Y:Error(`Unknown error: ${String(Y)}`)}class fU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:J,useCamelCase:h=!0,useBackwardCompatibility:U=!0,customParsers:Y={},verbose:Z=!1,trackPerformance:f=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let W=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],W,{useCamelCase:h,useBackwardCompatibility:U,customParsers:Y,verbose:Z,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return oh.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[h,U]of Object.entries($)){let Y=[...w,h],Z=Y.map((W)=>this.formatEnvKey(W,J.useCamelCase)),f=`${A}_${Z.join("_")}`,E=J.useBackwardCompatibility?`${A}_${Y.map((W)=>W.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Y,A,J);else{let W=AA.env[f]||(E?AA.env[E]:void 0);if(W!==void 0){if(J.verbose){let F=AA.env[f]?f:E}try{$[h]=this.parseEnvironmentValue(W,typeof U,f,J.customParsers,J.configName)}catch(F){if(F instanceof YU)throw F;throw Cw.envVar(f,W,typeof U,J.configName)}}}}}parseEnvironmentValue($,w,A,J,h){for(let[U,Y]of Object.entries(J))try{return Y($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,w))try{return U.parse($)}catch{throw Cw.envVar(A,$,`${w} (via ${U.name} parser)`,h)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,h]of Object.entries(AA.env))if(J.startsWith(A)&&h!==void 0)w[J]=h;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(h){J.push(`Cannot parse value "${w}" as ${A}: ${h}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:h="text"}=A,U=J||this.generateEnvPrefix($),Y=[];switch(this.extractEnvVarInfo(w,[],U,Y),h){case"markdown":return this.formatAsMarkdown(Y,$);case"json":return JSON.stringify(Y,null,2);default:return this.formatAsText(Y,$)}}extractEnvVarInfo($,w,A,J){for(let[h,U]of Object.entries($)){let Y=[...w,h],Z=`${A}_${Y.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Y,A,J);else J.push({key:Z,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Y.join(".")}`,example:this.generateExample(U)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
137
+
138
+ `;for(let J of $)A+=`${J.key}
139
+ `,A+=` Type: ${J.type}
140
+ `,A+=` Description: ${J.description}
141
+ `,A+=` Example: ${J.example}
142
+
143
+ `;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
144
+
145
+ `;A+=`| Variable | Type | Description | Example |
146
+ `,A+=`|----------|------|-------------|----------|
147
+ `;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
148
+ `;return A}}function mz($,w,A={}){return af($,w,A,new WeakMap)}function af($,w,A,J){let{arrayMergeMode:h="replace",skipNullish:U=!1,customMerger:Y}=A;if(w===null||w===void 0)return U?$:w;if(Y){let Z=Y($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return sf($,w,h,J);if(!a$(w)||!a$($))return w;return tz($,w,A,J)}function sf($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return dz($,w);case"smart":return gz($,w,J);default:return w}return w}function dz($,w){let A=[...w];for(let J of $)if(!A.some((h)=>sh(h,J)))A.push(J);return A}function gz($,w,A){if(w.length===0)return $;if($.length===0)return w;if(a$(w[0])&&a$($[0]))return lz($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}function lz($,w,A){let J=[...w];for(let h of $){if(!a$(h)){J.push(h);continue}let U=["id","name","key","path","type"],Y=!1;for(let Z of U)if(Z in h){if(J.find((E)=>a$(E)&&(Z in E)&&E[Z]===h[Z])){Y=!0;break}}if(!Y)J.push(h)}return J}function tz($,w,A,J){let h=w;if(a$(h)&&J.has(h))return J.get(h);let U={...$};if(a$(h))J.set(h,U);for(let Y in h){if(!Object.prototype.hasOwnProperty.call(h,Y))continue;let Z=h[Y],f=U[Y];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){U[Y]=Z;continue}if(a$(Z)&&a$(f))U[Y]=af(f,Z,A,J);else if(Array.isArray(Z)||Array.isArray(f))U[Y]=sf(f,Z,A.arrayMergeMode||"smart",J);else U[Y]=Z}return U}function of($,w,A="replace"){return mz($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function sh($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!sh($[A],w[A]))return!1;return!0}if(a$($)&&a$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!sh($[h],w[h]))return!1}return!0}return!1}function a$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class ef{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:h=!0,cacheTtl:U,trackPerformance:Y=!0,verbose:Z=!1}=A;if(h){let E=WA.getWithFileCheck("file",$);if(E){if(Z)console.log(`Configuration loaded from cache: ${$}`);return E}}let f=async()=>{if(!JA($))return null;try{let E=`?t=${Date.now()}`,W=await import($+E),F=W.default||W,j="default"in W,B=Object.keys(W).length>0;if(!j&&!B)throw new MA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new MA($,Error("Configuration must export a valid object"),"unknown");let q={config:of(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(h)WA.setWithFileCheck("file",q,$,U);return q}catch(E){throw E instanceof Error?Cw.configLoad($,E):Cw.configLoad($,Error(String(E)))}};if(Y)return oh.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let h=await this.loadFromPath(J,w,A);if(h)return h}catch(h){if(h instanceof Error&&h.name==="ConfigLoadError")throw h;if(A.verbose)console.warn(`Failed to load config from ${J}:`,h)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),h=[];for(let U of J)for(let Y of this.extensions)h.push(ch(w,`${U}${Y}`));return h}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let J=w===void 0?[]:Array.isArray(w)?w:[w];for(let U of J){if(!U)continue;if(A.push(U,`.${U}.config`,`${U}.config`,`.${U}`),$)A.push(`${$}.${U}.config`,`.${$}.${U}.config`)}let h=new Set;return A.filter((U)=>{if(!U||h.has(U))return!1;return h.add(U),!0})}checkFileAccess($){return vz(async()=>{return JA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!JA($))return J;if(w||A){let h=this.generateNamePatterns(w||"",A);for(let U of h)for(let Y of this.extensions){let Z=ch($,`${U}${Y}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:h}=await import("fs"),U=h($);for(let Y of U)if(this.looksLikeConfigFile(Y)){let Z=ch($,Y);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!JA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:h}=await import("fs"),U=h($,"utf8");JSON.parse(U)}catch(h){w.push(`Invalid JSON syntax: ${h}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let h=await this.loadFromPath(J,{},w);if(h)A.set(J,h.config)}catch(h){if(w.verbose)console.warn(`Failed to preload ${J}:`,h)}})),A}}var rz=/^https?:\/\//;class $Z{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:h=!0,validateTypes:U=!0,customRules:Y=[],trackPerformance:Z=!0,verbose:f=!1}=A,E=async()=>{let W=[],F=[],j={stopOnFirstError:J,validateRequired:h,validateTypes:U,customRules:Y,trackPerformance:Z,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...Y],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return W.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:W,warnings:F}}};if(Z)return await oh.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!pz(w))throw new yA(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),h=J.default||J;if(Array.isArray(h))return this.validateWithRules($,h,A);else return this.validateWithJSONSchema($,h,A)}catch(J){throw new yA(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],h=[];return this.validateObjectAgainstSchema($,w,"",J,h,A),{isValid:J.length===0,errors:J,warnings:h}}validateObjectAgainstSchema($,w,A,J,h,U){if(U.validateTypes&&w.type){let Y=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(Y)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${Y}`,expected:Z.join(" or "),actual:Y,rule:"type"}),U.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),U.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let Y=0;Y<$.length;Y++){let Z=A?`${A}[${Y}]`:`[${Y}]`;if(this.validateObjectAgainstSchema($[Y],w.items,Z,J,h,U),U.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Y=$;if(U.validateRequired&&w.required){for(let Z of w.required)if(!(Z in Y)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(w.properties){for(let[Z,f]of Object.entries(w.properties))if(Z in Y){let E=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(Y[Z],f,E,J,h,U),U.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(Y))if(!Z.has(f))h.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],h=[];for(let U of w)try{let Y=this.getValueByPath($,U.path),Z=this.validateWithRule(Y,U,U.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(Y){J.push({path:U.path,message:`Rule validation failed: ${Y}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:h}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let h=Array.isArray($)?"array":typeof $;if(h!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${h}`,expected:w.type,actual:h,rule:"type"})}if(w.min!==void 0){let h=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(h<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:h,rule:"min"})}if(w.max!==void 0){let h=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(h>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:h,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let h=w.validator($);if(h)J.push({path:A,message:w.message||h,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let h of A)if(J&&typeof J==="object"&&h in J)J=J[h];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,h,U,Y]=J;w.push({path:h,required:!U,type:this.mapTypeScriptType(Y)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:rz},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var R0=new SA("bunfig",{showTags:!0});function az($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class wZ{fileLoader=new ef;envProcessor=new fU;validator=new $Z;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:h,validate:U,...Y}=$;try{if(A?.enabled){let f=this.checkCache(Y.name||"",Y);if(f)return f}let Z;try{Z=await this.loadConfigurationStrategies(Y,!0,A)}catch(f){let E=Y.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(E)throw f;Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`No configuration file found for "${Y.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let W=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),F=!W&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),j=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(E&&(j||W))throw f;if(F&&(!E||!j))Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(h||U)await this.validateConfiguration(Z.config,h,U,Y.name);if(A?.enabled&&Z)this.cacheResult(Y.name||"",Z,A,Y);if(J?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:Y.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(f);if(J.slowThreshold&&f.duration>J.slowThreshold)R0.warn(`Slow configuration loading detected: ${f.duration}ms for ${Y.name}`);Z.metrics=f}return Z}catch(Z){if(Z instanceof Error&&Z.name==="ConfigNotFoundError")throw Z;let f=Date.now()-w;throw R0.error(`Configuration loading failed after ${f}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:h,cwd:U,configDir:Y,defaultConfig:Z,checkEnv:f=!0,arrayStrategy:E="replace",verbose:W=!1}=$,F=U||IA.cwd(),j=[],B=await this.loadLocalConfiguration(J,h,F,Y,Z,E,W,f,A);if(B)return j.push(...this.getLocalSearchPaths(J,h,F,Y)),this.finalizeResult(B,j,f,J,W);let T=await this.loadHomeConfiguration(J,h,Z,E,W,f);if(T)return j.push(...this.getHomeSearchPaths(J,h)),this.finalizeResult(T,j,f,J,W);let H=await this.loadPackageJsonConfiguration(J,h,F,Z,E,W,f);if(H)return j.push(p$(F,"package.json")),this.finalizeResult(H,j,f,J,W);if(j.push(...this.getAllSearchPaths(J,h,F,Y)),w)throw Cw.configNotFound(J,j,h);return{...await this.applyEnvironmentVariables(J,Z,f,W),warnings:[`No configuration file found for "${J}"${az(h)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,h,U,Y,Z,f){let E=Z?hA($,h,Y):h,W=this.getLocalDirectories(A,J);for(let F of W){if(Y)R0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:U,verbose:Y,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(B){if(Y)R0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,h,U){if(!$)return null;let Y=U?hA($,A,h):A,Z=[p$(zw(),".config",$),p$(zw(),".config"),zw()];for(let f of Z){if(h)R0.info(`Checking home directory: ${f}`);let E=this.fileLoader.generateConfigPaths($,f,w),W=await this.fileLoader.tryLoadFromPaths(E,Y,{arrayStrategy:J,verbose:h});if(W){if(h)R0.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,w,A,J,h,U,Y){let Z=Y?hA($,J,U):J;try{let f=p$(A,"package.json");if(!mB(f))return null;let E={};try{E=JSON.parse(dB(f,"utf8"))}catch(j){if(U)R0.warn("Failed to parse package.json:",[j instanceof Error?j:Error(String(j))]);return null}let W=E[$],F=$;if(!W&&w){let j=Array.isArray(w)?w:[w];for(let B of j){if(!B)continue;if(E[B]){W=E[B],F=B;break}}}if(W&&typeof W==="object"&&!Array.isArray(W)){if(U)R0.success(`Configuration loaded from package.json: ${F}`);return{config:of(Z,W,h),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(U)R0.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:hA($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,h){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let h=[];if(A){let U=A($);if(U)h.push(...U)}if(w){let U=await this.validator.validateConfiguration($,w);if(!U.isValid)h.push(...U.errors.map((Y)=>Y.path?`${Y.path}: ${Y.message}`:Y.message))}if(h.length>0)throw Cw.configValidation(J||"unknown",h,J)}checkCache($,w){let A=this.generateCacheKey($,w);return WA.get(A)||null}cacheResult($,w,A,J){let h=this.generateCacheKey($,J);WA.set(h,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let J=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${J}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,p$($,"config"),p$($,".config"),w?p$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let h=[];return h.push(...this.getLocalSearchPaths($,w,A,J)),h.push(...this.getHomeSearchPaths($,w)),h.push(p$(A,"package.json")),h}getLocalSearchPaths($,w,A,J){let h=this.getLocalDirectories(A,J),U=[];for(let Y of h)U.push(...this.fileLoader.generateConfigPaths($,Y,w));return U}getHomeSearchPaths($,w){if(!$)return[];let A=[p$(zw(),".config",$),p$(zw(),".config"),zw()],J=[];for(let h of A)J.push(...this.fileLoader.generateConfigPaths($,h,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}var Z6=new wZ;function hA($,w,A=!1){let J=new fU,h=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Y,Z=[]){let f={...Y};for(let[E,W]of Object.entries(Y)){let F=[...Z,E],j=[`${h}_${F.join("_").toUpperCase()}`,`${h}_${F.map((H)=>H.toUpperCase()).join("")}`,`${h}_${F.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,T;for(let H of j)if(B=IA.env[H],B!==void 0){T=H;break}if(B!==void 0&&T)if(typeof W==="boolean")f[E]=["true","1","yes"].includes(B.toLowerCase());else if(typeof W==="number"){let H=Number(B);if(!Number.isNaN(H))f[E]=H}else if(Array.isArray(W))try{f[E]=JSON.parse(B)}catch{f[E]=B.split(",").map((H)=>H.trim())}else f[E]=B;else if(W&&typeof W==="object"&&!Array.isArray(W))f[E]=U(W,F)}return f}return U(w)}var E6=p$(IA.cwd(),"config"),W6=p$(IA.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",oz={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:EU(ZU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:EU(ZU(),".stacks","ssl","stacks.localhost.crt"),keyPath:EU(ZU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Sw=oz;import{spawn as a2}from"node:child_process";import*as B0 from"node:fs/promises";import{homedir as s2}from"node:os";import*as A1 from"node:path";import*as G$ from"node:process";var N={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)};import{execSync as Jw}from"node:child_process";import B$ from"node:fs/promises";import*as oY from"node:os";import{homedir as eY}from"node:os";import{join as x$}from"node:path";import*as p0 from"node:process";import{createRequire as ez}from"node:module";import WU from"node:os";import FU from"node:path";import{existsSync as AZ,statSync as JZ}from"fs";import{existsSync as $H,mkdirSync as I6,readdirSync as L6,readFileSync as wH,writeFileSync as C6}from"fs";import{homedir as Dw}from"os";import{dirname as V6,resolve as s$}from"path";import EJ from"process";import{existsSync as hZ,statSync as UZ}from"fs";import{existsSync as _U,mkdirSync as AH,readdirSync as JH,writeFileSync as hH}from"fs";import{homedir as Vw}from"os";import{dirname as YZ,resolve as _$}from"path";import o0 from"process";import{join as UH,relative as YH,resolve as fZ}from"path";import tA from"process";import{existsSync as pZ,mkdirSync as c6,readdirSync as n6,writeFileSync as u6}from"fs";import{homedir as BU}from"os";import{dirname as d6,resolve as O$}from"path";import T1 from"process";import{join as fH,relative as ZH,resolve as ZZ}from"path";import pA from"process";import{existsSync as rZ,mkdirSync as r6,readdirSync as a6,writeFileSync as s6}from"fs";import{dirname as e6,resolve as rA}from"path";import XU from"process";import{Buffer as m0}from"buffer";import{createCipheriv as EH,createDecipheriv as WH,randomBytes as jU}from"crypto";import{closeSync as zU,createReadStream as EZ,createWriteStream as FH,existsSync as HU,fsyncSync as WZ,openSync as FZ,writeFileSync as BH}from"fs";import{access as jH,constants as BZ,mkdir as zH,readdir as DA,rename as jZ,stat as Ow,unlink as VA,writeFile as TU}from"fs/promises";import{join as _w}from"path";import K$ from"process";import{pipeline as HH}from"stream/promises";import{createGzip as zZ}from"zlib";import Xw from"process";import S0 from"process";import{Buffer as I0}from"buffer";import{createCipheriv as TH,createDecipheriv as GH,randomBytes as GU}from"crypto";import{closeSync as qU,createReadStream as HZ,createWriteStream as qH,existsSync as OA,fsyncSync as TZ,openSync as GZ,writeFileSync as RH}from"fs";import{access as NH,constants as qZ,mkdir as KH,readdir as _A,rename as RZ,stat as kw,unlink as XA,writeFile as RU}from"fs/promises";import{isAbsolute as MH,join as Qw,resolve as yH}from"path";import c from"process";import{pipeline as IH}from"stream/promises";import{createGzip as NZ}from"zlib";import xw from"process";import D0 from"process";import kA from"process";import{existsSync as QA}from"fs";import{resolve as NU}from"path";import{existsSync as LH}from"fs";import{existsSync as CH,readdirSync as SH}from"fs";import{extname as KU,resolve as KZ}from"path";import DH from"process";import{join as VH,relative as OH,resolve as MZ}from"path";import aA from"process";import{Buffer as L0}from"buffer";import{createCipheriv as _H,createDecipheriv as XH,randomBytes as MU}from"crypto";import{closeSync as yU,createReadStream as yZ,createWriteStream as kH,existsSync as xA,fsyncSync as IZ,openSync as LZ,writeFileSync as QH}from"fs";import{access as xH,constants as CZ,mkdir as PH,readdir as PA,rename as SZ,stat as Pw,unlink as iA,writeFile as IU}from"fs/promises";import{isAbsolute as iH,join as iw,resolve as bH}from"path";import n from"process";import{pipeline as cH}from"stream/promises";import{createGzip as DZ}from"zlib";import bw from"process";import V0 from"process";import bA from"process";import{existsSync as cA}from"fs";import{resolve as LU}from"path";import{existsSync as nH}from"fs";import{exec as ZT}from"node:child_process";import vZ from"node:fs";import ET from"node:os";import U0 from"node:path";import _E from"node:process";import{promisify as WT}from"node:util";import vw from"node:crypto";import O0 from"node:fs";import gU from"node:path";import{execSync as tZ}from"node:child_process";import ZJ from"node:os";var R6=ez(import.meta.url);class aZ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let h=this.generateKey($,A),U=J??this.options.ttl,Y=this.estimateSize(w);this.cache.set(h,{value:w,timestamp:new Date,ttl:U,hits:0,size:Y}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!AZ($))return!0;return JZ($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let h=AZ(A)?JZ(A):null,U=h?h.mtime:new Date;this.set($,{value:w,fileTimestamp:U},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,h)=>J+h.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class sZ{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),h=new Date;try{let U=await w(),Y=performance.now()-J;return this.recordMetric({operation:$,duration:Y,timestamp:h,...A}),U}catch(U){let Y=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:Y,timestamp:h,...A}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((h)=>h.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((h)=>h.duration),J=A.reduce((h,U)=>h+U,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}var sA=new aZ,lU=new sZ,uH=Object.defineProperty,vH=($)=>$;function mH($,w){this[$]=vH.bind(null,w)}var dH=($,w)=>{for(var A in w)uH($,A,{get:w[A],enumerable:!0,configurable:!0,set:mH.bind(w,A)})},gH=($,w)=>()=>($&&(w=$($=0)),w),oZ={};dH(oZ,{withErrorRecovery:()=>wE,tryLoadConfig:()=>z9,loadConfigWithResult:()=>B9,loadConfig:()=>YE,isRetryableError:()=>Y9,isConfigNotFoundError:()=>U9,isBunfigError:()=>AE,globalPerformanceMonitor:()=>N1,globalCache:()=>nw,getEnvOrDefault:()=>f9,generateConfigTypes:()=>H9,defaultGeneratedDir:()=>zE,defaultConfigDir:()=>jE,deepMergeWithArrayStrategy:()=>sU,deepMerge:()=>JE,createLibraryConfig:()=>T9,config:()=>j9,bunfigPlugin:()=>G9,applyEnvVarsToConfig:()=>z1,TypeGenerationError:()=>cU,SchemaValidationError:()=>q1,PluginError:()=>uU,PerformanceMonitor:()=>pU,FileSystemError:()=>bU,ErrorFactory:()=>g0,EnvVarError:()=>JJ,EnvProcessor:()=>WJ,ConfigValidator:()=>oU,ConfigValidationError:()=>PU,ConfigNotFoundError:()=>AJ,ConfigMergeError:()=>iU,ConfigLoader:()=>eU,ConfigLoadError:()=>G1,ConfigFileLoader:()=>FJ,ConfigCache:()=>tU,CacheUtils:()=>ZE,BunfigError:()=>u$,BrowserConfigError:()=>nU,ArrayMergeStrategies:()=>FE});class tU{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let h=this.generateKey($,A),U=J??this.options.ttl,Y=this.estimateSize(w);this.cache.set(h,{value:w,timestamp:new Date,ttl:U,hits:0,size:Y}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!hZ($))return!0;return UZ($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let h=hZ(A)?UZ(A):null,U=h?h.mtime:new Date;this.set($,{value:w,fileTimestamp:U},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,h)=>J+h.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class pU{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),h=new Date;try{let U=await w(),Y=performance.now()-J;return this.recordMetric({operation:$,duration:Y,timestamp:h,...A}),U}catch(U){let Y=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:Y,timestamp:h,...A}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((h)=>h.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((h)=>h.duration),J=A.reduce((h,U)=>h+U,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function lH($,w={}){let A=Object.keys(w).sort().map((J)=>`${J}:${w[J]}`).join("|");return A?`${$}:${A}`:$}function tH($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function pH($){return $.getStats().size*2}function rU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let J=[...w];for(let h of $)if(p(h)&&"name"in h){if(!J.find((U)=>p(U)&&("name"in U)&&U.name===h.name))J.push(h)}else if(p(h)&&"path"in h){if(!J.find((U)=>p(U)&&("path"in U)&&U.path===h.path))J.push(h)}else if(!J.some((U)=>oA(U,h)))J.push(h);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}if(!p(w)||!p($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let h=w[J];if(h===null||h===void 0)continue;else if(p(h)&&p(A[J]))A[J]=rU(A[J],h);else if(Array.isArray(h)&&Array.isArray(A[J]))if(h.length>0&&A[J].length>0&&p(h[0])&&p(A[J][0])){let U=[...h];for(let Y of A[J])if(p(Y)&&"name"in Y){if(!U.find((Z)=>p(Z)&&("name"in Z)&&Z.name===Y.name))U.push(Y)}else if(p(Y)&&"path"in Y){if(!U.find((Z)=>p(Z)&&("path"in Z)&&Z.path===Y.path))U.push(Y)}else if(!U.some((Z)=>oA(Z,Y)))U.push(Y);A[J]=U}else if(h.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...h];for(let Y of A[J])if(!U.includes(Y))U.push(Y);A[J]=U}else A[J]=h;else A[J]=h}return A}function oA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!oA($[A],w[A]))return!1;return!0}if(p($)&&p(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!oA($[h],w[h]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function rH($,w){if(!rZ($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return rU(w,J)}catch{return null}}catch{return null}}async function aH({name:$="",cwd:w,defaultConfig:A}){let J=w||XU.cwd(),h=[".ts",".js",".mjs",".cjs",".json"],U=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Y of U)for(let Z of h){let f=rA(J,`${Y}${Z}`),E=await rH(f,A);if(E!==null)return E}try{let Y=rA(J,"package.json");if(rZ(Y)){let Z=(await import(Y))[$];if(Z&&typeof Z==="object"&&!Array.isArray(Z))try{return rU(A,Z)}catch{}}}catch{}return A}function sH($,w={}){let A=pA.cwd();while(A.includes("storage"))A=ZZ(A,"..");let J=ZZ(A,$||"");if(w?.relative)return ZH(pA.cwd(),J);return J}async function oH(){try{let $=await aH({name:"clarity",defaultConfig:mA,cwd:pA.cwd(),endpoint:"",headers:{}});return{...mA,...$}}catch{return mA}}function e(){if(S0.env.NODE_ENV==="test"||S0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function eH(){if(S0.env.NODE_ENV==="test"||S0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof S0<"u"){let $=S0.type;if($==="renderer"||$==="worker")return!1;return!!(S0.versions&&(S0.versions.node||S0.versions.bun))}return!1}class eZ{async format($){let w=await eH(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Xw.pid,hostname:w(),environment:Xw.env.NODE_ENV||"development",platform:Xw.platform,version:Xw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Xw.env.NODE_ENV||Xw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class 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($,w={}){this.name=$,this.config={...QU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new eZ,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??K$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let h=this.generateKeyId(),U=this.generateKey();this.currentKeyId=h,this.keys.set(h,U),this.encryptionKeys.set(h,{key:U,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...dA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...dA};return{...dA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:QU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let w=(async()=>{let J,h=0,U=3,Y=1000;while(h<U)try{try{try{await jH(this.config.logDirectory,BZ.F_OK|BZ.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await zH(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:m0.from($);try{if(!HU(this.currentLogFile))await TU(this.currentLogFile,"",{mode:420});if(J=FZ(this.currentLogFile,"a",420),BH(J,Z,{flag:"a"}),WZ(J),J!==void 0)zU(J),J=void 0;if((await Ow(this.currentLogFile)).size===0){if(await TU(this.currentLogFile,Z,{flag:"w",mode:420}),(await Ow(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let E=f;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(h<U-1){let W=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${h+1}/${U}:`,W);let F=Y*2**h;await new Promise((j)=>setTimeout(j,F)),h++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(J!==void 0)try{zU(J)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(Z){if(h===U-1){let E=Z,W=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),Z}h++;let f=Y*2**(h-1);await new Promise((E)=>setTimeout(E,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return _w(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 _w(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return _w(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(e())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,Y],[,Z])=>Z.createdAt.getTime()-Y.createdAt.getTime()),h=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,h);if(J.length>U)for(let[Y]of J.slice(U))this.encryptionKeys.delete(Y),this.keys.delete(Y)}generateKeyId(){return jU(16).toString("hex")}generateKey(){return jU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=jU(16),J=EH("aes-256-gcm",w,A),h=m0.concat([J.update($,"utf8"),J.final()]),U=J.getAuthTag();return{encrypted:m0.concat([A,h,U]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=zZ(),h=[];J.on("data",(U)=>h.push(U)),J.on("end",()=>w(m0.from(m0.concat(h)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(e())return;let $=await Ow(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let h=await DA(this.config.logDirectory),U=h.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),Y=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${Y}`;if(await Ow(A).catch(()=>null))try{if(await jZ(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await VA(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(U.length===0&&!h.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await TU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let h=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${h}.log`);if(await Ow(A).catch(()=>null))await jZ(A,U)}if(this.currentLogFile=J,w.maxFiles){let h=(await DA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Y)=>Y.localeCompare(U));for(let U of h.slice(w.maxFiles))await VA(_w(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=EZ($),J=FH(w),h=zZ();await HH(A,h,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),HU(this.currentLogFile))try{let $=FZ(this.currentLogFile,"r+");WZ($),zU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await DA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await VA(_w(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?d.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:h,level:U,showTimestamp:Y=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(Y)B.push(w);if(U==="warning")B.push("WARN");else if(U==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(h),B.join(" ")}let f=K$.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${h}`;else if(U==="info"||U==="success")E=`${A} ${J} ${h}`;else E=`${A} ${J} ${d.cyan(h)}`;if(!Y)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Y)=>{let Z=Number.parseInt(Y,10);return Z<w[0].length?String(w[0][Z]):U});let A=/%([sdijfo%])/g,J=0,h=$.replace(A,(U,Y)=>{if(Y==="%")return"%";if(J>=w.length)return U;let Z=w[J++];switch(Y){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return U}});if(J<w.length)h+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return h}async log($,w,...A){let J=new Date,h=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Y,Z;if(w instanceof Error)Y=w.message,Z=w.stack;else Y=this.formatMessage(w,A);if(this.fancy&&!e()){let E=EE[$],W=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:d.gray(Y),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:Y,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:d.green(Y),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:Y,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:h,icon:E,tag:W,message:Y,level:$}),console.error(F),Z){let j=Z.split(`
149
+ `);for(let B of j)if(B.trim()&&!B.includes(Y))console.error(this.formatConsoleMessage({timestamp:h,message:d.gray(` ${B}`),level:$,showTimestamp:!1}))}break}}else if(!e()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Y}`),Z)console.error(Z)}if(!this.shouldLog($))return;let f=`${U} ${this.environment}.${$.toUpperCase()}: ${Y}
150
+ `;if(Z)f+=`${Z}
151
+ `;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!e()){let A=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:d.blue("◐"),tag:A,message:`${d.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),h=Math.round(J-w),U=`${$} completed in ${h}ms`,Y=new Date,Z=this.formatConsoleTimestamp(Y),f=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${U}`;if(A)f+=` ${JSON.stringify(A)}`;if(f+=`
152
+ `,f=f.replace(this.ANSI_PATTERN,""),this.fancy&&!e()){let E=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:d.green("✓"),tag:E,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!e())console.error(f.trim());await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new eA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(e())throw Error("createReadStream is not supported in browser environments");if(!HU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return EZ(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=m0.isBuffer($)?$:m0.from($,"base64"),h=J.slice(0,16),U=J.slice(-16),Y=J.slice(16,-16),Z=WH("aes-256-gcm",A,h);return Z.setAuthTag(U),m0.concat([Z.update(Y),Z.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return e()}isServerMode(){return!e()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w);if(this.fancy&&!e()){let U=$.split(`
153
+ `),Y=Math.max(...U.map((W)=>W.length))+2,Z=`┌${"─".repeat(Y)}┐`,f=`└${"─".repeat(Y)}┘`,E=U.map((W)=>{let F=" ".repeat(Y-W.length-2);return`│ ${W}${F} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:d.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:d.cyan(Z)})),E.forEach((W)=>console.error(this.formatConsoleMessage({timestamp:A,message:d.cyan(W),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:d.cyan(f),showTimestamp:!1}))}else if(!e())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let h=`${J} ${this.environment}.INFO: [BOX] ${$}
154
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(h)}async prompt($){if(e())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${d.cyan("?")} ${$} (y/n) `);let A=(J)=>{let h=J.toString().trim().toLowerCase();K$.stdin.removeListener("data",A);try{if(typeof K$.stdin.setRawMode==="function")K$.stdin.setRawMode(!1)}catch{}K$.stdin.pause(),console.error(""),w(h==="y"||h==="yes")};try{if(typeof K$.stdin.setRawMode==="function")K$.stdin.setRawMode(!0)}catch{}K$.stdin.resume(),K$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let h=/%([sdijfo%])/g,U=0;if(A=$.replace(h,(Y,Z)=>{if(Z==="%")return"%";if(U>=w.length)return Y;let f=w[U++];switch(Z){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return Y}}),U<w.length)A+=` ${w.slice(U).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`}if(this.fancy&&!e()){let h=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",U=d.blue("◐");console.error(`${U} ${h} ${d.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
155
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||e()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,h)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,J)),h!==void 0)this.activeProgressBar.message=h;let U=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,U)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;if(this.activeProgressBar.current=this.activeProgressBar.total,J!==void 0)this.activeProgressBar.message=J;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(J,h="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;K$.stdout.write(`${"\r".padEnd(K$.stdout.columns||80)}\r`),this.log(h,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||e()||!K$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),h=$.barLength-J,U=d.green("━".repeat(J)),Y=d.gray("━".repeat(h)),Z=`[${U}${Y}]`,f=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",W=w||A===100?d.green("✓"):d.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${d.gray(this.formatTag(this.name))}`:"",j=`\r${W}${F} ${Z} ${f}${E}`,B=K$.stdout.columns||80,T=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,K$.stdout.write($.lastRenderedLine),w)K$.stdout.write(`
156
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||e()||!K$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await DA(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let h=_w(this.config.logDirectory,J);if($.before)try{if((await Ow(h)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${h}:`,U);continue}A.push(h)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await VA(J),console.warn(`Deleted log file: ${J}`)}catch(h){console.error(`Failed to delete log file ${J}:`,h)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function vA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&u(w[0])&&"id"in w[0]&&w[0].id===3&&u(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(u(w)&&u($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(u($)&&"arr"in $&&Array.isArray($.arr)&&u(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&u(w[0])&&u($[0])){let J=[...w];for(let h of $)if(u(h)&&"name"in h){if(!J.find((U)=>u(U)&&("name"in U)&&U.name===h.name))J.push(h)}else if(u(h)&&"path"in h){if(!J.find((U)=>u(U)&&("path"in U)&&U.path===h.path))J.push(h)}else if(!J.some((U)=>$J(U,h)))J.push(h);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}if(!u(w)||!u($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let h=w[J];if(h===null||h===void 0)continue;else if(u(h)&&u(A[J]))A[J]=vA(A[J],h);else if(Array.isArray(h)&&Array.isArray(A[J]))if(h.length>0&&A[J].length>0&&u(h[0])&&u(A[J][0])){let U=[...h];for(let Y of A[J])if(u(Y)&&"name"in Y){if(!U.find((Z)=>u(Z)&&("name"in Z)&&Z.name===Y.name))U.push(Y)}else if(u(Y)&&"path"in Y){if(!U.find((Z)=>u(Z)&&("path"in Z)&&Z.path===Y.path))U.push(Y)}else if(!U.some((Z)=>$J(Z,Y)))U.push(Y);A[J]=U}else if(h.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...h];for(let Y of A[J])if(!U.includes(Y))U.push(Y);A[J]=U}else A[J]=h;else A[J]=h}return A}function aU($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:vA($,w);if(Array.isArray($))return A==="replace"?w:vA($,w);if(!u(w)||!u($))return w;let J={...$};for(let h of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,h))continue;let U=w[h],Y=J[h];if(U===null||U===void 0)continue;if(Array.isArray(U)||Array.isArray(Y))if(A==="replace")J[h]=U;else J[h]=vA(Y,U);else if(u(U)&&u(Y))J[h]=aU(Y,U,A);else J[h]=U}return J}function $J($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!$J($[A],w[A]))return!1;return!0}if(u($)&&u(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!$J($[h],w[h]))return!1}return!0}return!1}function u($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function nA($,w,A="replace"){if(!pZ($))return null;try{let J=await import($),h=J.default||J;if(typeof h!=="object"||h===null||Array.isArray(h))return null;try{return aU(w,h,A)}catch{return null}}catch{return null}}function $9($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),h={...w};function U(Y,Z=[]){let f={...Y};for(let[E,W]of Object.entries(Y)){let F=[...Z,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),B=`${J}_${F.map(j).join("_")}`,T=`${J}_${F.map((H)=>H.toUpperCase()).join("_")}`;if(A)y$.info(`Checking environment variable ${B} for config ${$}.${F.join(".")}`);if(typeof W==="object"&&W!==null&&!Array.isArray(W))f[E]=U(W,F);else{let H=T1.env[B]||T1.env[T];if(H!==void 0){if(A)y$.info(`Using environment variable ${H?B:T} for config ${$}.${F.join(".")}`);if(typeof W==="number")f[E]=Number(H);else if(typeof W==="boolean")f[E]=H.toLowerCase()==="true";else if(Array.isArray(W))try{let q=JSON.parse(H);if(Array.isArray(q))f[E]=q;else f[E]=H.split(",").map((G)=>G.trim())}catch{f[E]=H.split(",").map((q)=>q.trim())}else f[E]=H}}}return f}return U(h)}async function w9({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:h,verbose:U=!1,checkEnv:Y=!0,arrayStrategy:Z="replace"}){let f=Y&&typeof h==="object"&&h!==null&&!Array.isArray(h)?$9($,h,U):h,E=A||T1.cwd(),W=[".ts",".js",".mjs",".cjs",".json"];if(U)y$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let F=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),B=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,O$(E,"config"),O$(E,".config"),J?O$(E,J):void 0].filter(Boolean)));for(let q of H){if(U)y$.info(`Searching for configuration in: ${q}`);let G=[O$(E,"config"),O$(E,".config")].concat(J?[O$(E,J)]:[]).includes(q)?[...F,...j,...B,...T]:[...j,...F,...T,...B];for(let R of G)for(let y of W){let L=O$(q,`${R}${y}`),C=await nA(L,f,Z);if(C!==null){if(U)y$.success(`Configuration loaded from: ${L}`);return C}}}if($){let q=O$(BU(),".config",$),G=["config",`${$}.config`];if(w)G.push(`${w}.config`);if(U)y$.info(`Checking user config directory: ${q}`);for(let R of G)for(let y of W){let L=O$(q,`${R}${y}`),C=await nA(L,f,Z);if(C!==null){if(U)y$.success(`Configuration loaded from user config directory: ${L}`);return C}}}if($){let q=O$(BU(),".config"),G=[`.${$}.config`];if(w)G.push(`.${w}.config`);if(U)y$.info(`Checking user config directory for dotfile configs: ${q}`);for(let R of G)for(let y of W){let L=O$(q,`${R}${y}`),C=await nA(L,f,Z);if(C!==null){if(U)y$.success(`Configuration loaded from user config directory dotfile: ${L}`);return C}}}if($){let q=BU(),G=[`.${$}.config`,`.${$}`];if(w)G.push(`.${w}.config`),G.push(`.${w}`);if(U)y$.info(`Checking user home directory for dotfile configs: ${q}`);for(let R of G)for(let y of W){let L=O$(q,`${R}${y}`),C=await nA(L,f,Z);if(C!==null){if(U)y$.success(`Configuration loaded from user home directory: ${L}`);return C}}}try{let q=O$(E,"package.json");if(pZ(q)){let G=await import(q),R=G[$];if(!R&&w){if(R=G[w],R&&U)y$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(U)y$.success(`Configuration loaded from package.json: ${R===G[$]?$:w}`);return aU(f,R,Z)}catch(y){if(U)y$.warn("Failed to merge package.json config:",y)}}}catch(q){if(U)y$.warn("Failed to load package.json:",q)}if(U)y$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function A9($,w={}){let A=tA.cwd();while(A.includes("storage"))A=fZ(A,"..");let J=fZ(A,$||"");if(w?.relative)return YH(tA.cwd(),J);return J}async function J9(){try{let $=await w9({name:"clarity",alias:"logging",defaultConfig:gA,cwd:tA.cwd()});return{...gA,...$||{}}}catch{return gA}}function Y$(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function h9(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D0<"u"){let $=D0.type;if($==="renderer"||$==="worker")return!1;return!!(D0.versions&&(D0.versions.node||D0.versions.bun))}return!1}class $E{async format($){let w=await h9(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:xw.pid,hostname:w(),environment:xw.env.NODE_ENV||"development",platform:xw.platform,version:xw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xw.env.NODE_ENV||xw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class wJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...xU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new $E,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??c.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let h=this.generateKeyId(),U=this.generateKey();this.currentKeyId=h,this.keys.set(h,U),this.encryptionKeys.set(h,{key:U,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...lA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...lA};return{...lA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:xU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!Y$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let J,h=0,U=3,Y=1000;while(h<U)try{try{try{await NH(this.config.logDirectory,qZ.F_OK|qZ.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await KH(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:I0.from($);try{if(!OA(this.currentLogFile))await RU(this.currentLogFile,"",{mode:420});if(J=GZ(this.currentLogFile,"a",420),RH(J,Z,{flag:"a"}),TZ(J),J!==void 0)qU(J),J=void 0;if((await kw(this.currentLogFile)).size===0){if(await RU(this.currentLogFile,Z,{flag:"w",mode:420}),(await kw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let E=f;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(h<U-1){let W=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${h+1}/${U}:`,W);let F=Y*2**h;await new Promise((j)=>setTimeout(j,F)),h++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(J!==void 0)try{qU(J)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(Z){if(h===U-1){let E=Z,W=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),Z}h++;let f=Y*2**(h-1);await new Promise((E)=>setTimeout(E,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Qw(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 Qw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Qw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(Y$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,Y],[,Z])=>Z.createdAt.getTime()-Y.createdAt.getTime()),h=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,h);if(J.length>U)for(let[Y]of J.slice(U))this.encryptionKeys.delete(Y),this.keys.delete(Y)}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 $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=GU(16),J=TH("aes-256-gcm",w,A),h=I0.isBuffer($)?$:I0.from($,"utf8"),U=J.update(h),Y=J.final(),Z=U.length+Y.length,f=J.getAuthTag(),E=I0.allocUnsafe(16+Z+16);return A.copy(E,0),U.copy(E,16),Y.copy(E,16+U.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=NZ(),h=[];J.on("data",(U)=>h.push(U)),J.on("end",()=>w(I0.from(I0.concat(h)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(Y$())return;if(!this.shouldWriteToFile())return;let $=await kw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let h=await _A(this.config.logDirectory),U=h.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),Y=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${Y}`;if(await kw(A).catch(()=>null))try{if(await RZ(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await XA(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(U.length===0&&!h.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await RU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let h=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${h}.log`);if(await kw(A).catch(()=>null))await RZ(A,U)}if(this.currentLogFile=J,w.maxFiles){let h=(await _A(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Y)=>Y.localeCompare(U));for(let U of h.slice(w.maxFiles))await XA(Qw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=HZ($),J=qH(w),h=NZ();await IH(A,h,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),OA(this.currentLogFile))try{let $=GZ(this.currentLogFile,"r+");TZ($),qU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!Y$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await _A(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await XA(Qw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?X.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Y$())return!1;let $=typeof c.env.NO_COLOR<"u",w=c.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof c.stderr<"u"&&c.stderr.isTTY||typeof c.stdout<"u"&&c.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:h,level:U,showTimestamp:Y=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(Y)B.push(w);if(U==="warning")B.push("WARN");else if(U==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(h),B.join(" ")}let f=c.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${h}`;else if(U==="info"||U==="success")E=`${A} ${J} ${h}`;else E=`${A} ${J} ${X.cyan(h)}`;if(!Y)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Y)=>{let Z=Number.parseInt(Y,10);return Z<w[0].length?String(w[0][Z]):U});let A=/%([sdijfo%])/g,J=0,h=$.replace(A,(U,Y)=>{if(Y==="%")return"%";if(J>=w.length)return U;let Z=w[J++];switch(Y){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return U}});if(J<w.length)h+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return h}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,h)=>{let U=X.underline(X.blue(J)),Y=this.toAbsoluteFilePath(h);if(Y&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(Y)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${h}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),w=w.replace(/`([^`]+)`/g,(A,J)=>X.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>X.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>X.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>X.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>X.strikethrough(J)),w}supportsHyperlinks(){if(Y$())return!1;let $=c.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=c.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(MH(w)||w.startsWith("./")||w.startsWith("../"))w=yH(w);else return null;return OA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,h=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Y,Z;if(w instanceof Error)Y=w.message,Z=w.stack;else Y=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":WE[$],j=this.options.showTags!==!1&&this.name?X.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:X.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:X.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
157
+ `);for(let H of T)if(H.trim()&&!H.includes(Y))console.error(this.formatConsoleMessage({timestamp:h,message:X.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!Y$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Y}`),Z)console.error(Z)}if(!this.shouldLog($))return;let W=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
158
+ `;if(Z)W+=`${Z}
159
+ `;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress($,w=""){let A={update:(h,U)=>{},finish:(h)=>{},interrupt:(h,U)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!Y$()&&c.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(h,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!Y$()&&c.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,U="info")=>{if(!Y$()&&c.stdout.isTTY)c.stdout.write(`
160
+ `);if(this[U==="warning"?"warn":U](h),this.activeProgressBar&&this.shouldStyleConsole()&&!Y$()&&c.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?X.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":X.blue("◐"),tag:A,message:`${X.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),h=Math.round(J-w),U=`${$} completed in ${h}ms`,Y=new Date,Z=this.formatConsoleTimestamp(Y),f=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${U}`;if(A)f+=` ${JSON.stringify(A)}`;if(f+=`
161
+ `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?X.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":X.green("✓"),tag:E,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!Y$())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new wJ(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(Y$())throw Error("createReadStream is not supported in browser environments");if(!OA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return HZ(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=I0.isBuffer($)?$:I0.from($,"base64"),h=J.subarray(0,16),U=J.subarray(J.length-16),Y=J.subarray(16,J.length-16),Z=GH("aes-256-gcm",A,h);Z.setAuthTag(U);let f=Z.update(Y),E=Z.final(),W=f.length+E.length,F=I0.allocUnsafe(W);return f.copy(F,0),E.copy(F,f.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Y$()}isServerMode(){return!Y$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:h,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=h.split(`
162
+ `),f=Math.max(...Z.map((j)=>j.length))+2,E=`┌${"─".repeat(f)}┐`,W=`└${"─".repeat(f)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:X.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:X.cyan(E),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:X.cyan(W),showTimestamp:!1}))}else if(!Y$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Y=`${J} ${this.environment}.INFO: [BOX] ${U}
163
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}async prompt($){if(Y$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${X.cyan("?")} ${$} (y/n) `);let A=(J)=>{let h=J.toString().trim().toLowerCase();c.stdin.removeListener("data",A);try{if(typeof c.stdin.setRawMode==="function")c.stdin.setRawMode(!1)}catch{}c.stdin.pause(),console.error(""),w(h==="y"||h==="yes")};try{if(typeof c.stdin.setRawMode==="function")c.stdin.setRawMode(!0)}catch{}c.stdin.resume(),c.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let Y=/%([sdijfo%])/g,Z=0;if(A=$.replace(Y,(f,E)=>{if(E==="%")return"%";if(Z>=w.length)return f;let W=w[Z++];switch(E){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return f}}),Z<w.length)A+=` ${w.slice(Z).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:J,fileText:h}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?X.gray(this.formatTag(this.name)):"",Z=this.options.showIcons===!1?"":`${X.blue("◐")} `;console.error(`${Z}${Y} ${X.cyan(J)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${h}
164
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!c.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),h=$.barLength-J,U=X.green("━".repeat(J)),Y=X.gray("━".repeat(h)),Z=`[${U}${Y}]`,f=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",W=this.options.showIcons===!1?"":w||A===100?X.green("✓"):X.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${X.gray(this.formatTag(this.name))}`:"",j=`\r${W}${F} ${Z} ${f}${E}`,B=c.stdout.columns||80,T=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,c.stdout.write($.lastRenderedLine),w)c.stdout.write(`
165
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Y$()||!c.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(Y$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await _A(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let h=Qw(this.config.logDirectory,J);if($.before)try{if((await kw(h)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${h}:`,U);continue}A.push(h)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await XA(J),console.warn(`Deleted log file: ${J}`)}catch(h){console.error(`Failed to delete log file ${J}:`,h)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function wE($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:h=()=>!0,fallback:U}=w,Y=Error("Unknown error occurred");for(let Z=0;Z<=A;Z++)try{return await $()}catch(f){if(Y=f instanceof Error?f:Error(String(f)),Z===A||!h(Y))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(U!==void 0)return U;throw Y instanceof Error?Y:Error(`Unknown error: ${String(Y)}`)}function AE($){return $ instanceof u$}function U9($){return $ instanceof AJ}function Y9($){if(AE($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((w)=>$.message.toLowerCase().includes(w.toLowerCase()))}class WJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:J,useCamelCase:h=!0,useBackwardCompatibility:U=!0,customParsers:Y={},verbose:Z=!1,trackPerformance:f=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let W=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],W,{useCamelCase:h,useBackwardCompatibility:U,customParsers:Y,verbose:Z,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return N1.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[h,U]of Object.entries($)){let Y=[...w,h],Z=Y.map((W)=>this.formatEnvKey(W,J.useCamelCase)),f=`${A}_${Z.join("_")}`,E=J.useBackwardCompatibility?`${A}_${Y.map((W)=>W.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Y,A,J);else{let W=kA.env[f]||(E?kA.env[E]:void 0);if(W!==void 0){if(J.verbose){let F=kA.env[f]?f:E}try{$[h]=this.parseEnvironmentValue(W,typeof U,f,J.customParsers,J.configName)}catch(F){if(F instanceof JJ)throw F;throw g0.envVar(f,W,typeof U,J.configName)}}}}}parseEnvironmentValue($,w,A,J,h){for(let[U,Y]of Object.entries(J))try{return Y($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,w))try{return U.parse($)}catch{throw g0.envVar(A,$,`${w} (via ${U.name} parser)`,h)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,h]of Object.entries(kA.env))if(J.startsWith(A)&&h!==void 0)w[J]=h;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(h){J.push(`Cannot parse value "${w}" as ${A}: ${h}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:h="text"}=A,U=J||this.generateEnvPrefix($),Y=[];switch(this.extractEnvVarInfo(w,[],U,Y),h){case"markdown":return this.formatAsMarkdown(Y,$);case"json":return JSON.stringify(Y,null,2);default:return this.formatAsText(Y,$)}}extractEnvVarInfo($,w,A,J){for(let[h,U]of Object.entries($)){let Y=[...w,h],Z=`${A}_${Y.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Y,A,J);else J.push({key:Z,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Y.join(".")}`,example:this.generateExample(U)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
166
+
167
+ `;for(let J of $)A+=`${J.key}
168
+ `,A+=` Type: ${J.type}
169
+ `,A+=` Description: ${J.description}
170
+ `,A+=` Example: ${J.example}
171
+
172
+ `;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
173
+
174
+ `;A+=`| Variable | Type | Description | Example |
175
+ `,A+=`|----------|------|-------------|----------|
176
+ `;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
177
+ `;return A}}function f9($,w){let A=fE("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function JE($,w,A={}){return hE($,w,A,new WeakMap)}function hE($,w,A,J){let{arrayMergeMode:h="replace",skipNullish:U=!1,customMerger:Y}=A;if(w===null||w===void 0)return U?$:w;if(Y){let Z=Y($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return UE($,w,h,J);if(!o$(w)||!o$($))return w;return F9($,w,A,J)}function UE($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return Z9($,w);case"smart":return E9($,w,J);default:return w}return w}function Z9($,w){let A=[...w];for(let J of $)if(!A.some((h)=>kU(h,J)))A.push(J);return A}function E9($,w,A){if(w.length===0)return $;if($.length===0)return w;if(o$(w[0])&&o$($[0]))return W9($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}function W9($,w,A){let J=[...w];for(let h of $){if(!o$(h)){J.push(h);continue}let U=["id","name","key","path","type"],Y=!1;for(let Z of U)if(Z in h){if(J.find((f)=>o$(f)&&(Z in f)&&f[Z]===h[Z])){Y=!0;break}}if(!Y)J.push(h)}return J}function F9($,w,A,J){let h=w;if(o$(h)&&J.has(h))return J.get(h);let U={...$};if(o$(h))J.set(h,U);for(let Y in h){if(!Object.prototype.hasOwnProperty.call(h,Y))continue;let Z=h[Y],f=U[Y];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){U[Y]=Z;continue}if(o$(Z)&&o$(f))U[Y]=hE(f,Z,A,J);else if(Array.isArray(Z)||Array.isArray(f))U[Y]=UE(f,Z,A.arrayMergeMode||"smart",J);else U[Y]=Z}return U}function sU($,w,A="replace"){return JE($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function kU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!kU($[A],w[A]))return!1;return!0}if(o$($)&&o$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!kU($[h],w[h]))return!1}return!0}return!1}function o$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class FJ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:h=!0,cacheTtl:U,trackPerformance:Y=!0,verbose:Z=!1}=A;if(h){let E=nw.getWithFileCheck("file",$);if(E){if(Z)console.log(`Configuration loaded from cache: ${$}`);return E}}let f=async()=>{if(!QA($))return null;try{let E=`?t=${Date.now()}`,W=await import($+E),F=W.default||W,j="default"in W,B=Object.keys(W).length>0;if(!j&&!B)throw new G1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new G1($,Error("Configuration must export a valid object"),"unknown");let T={config:sU(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(h)nw.setWithFileCheck("file",T,$,U);return T}catch(E){throw E instanceof Error?g0.configLoad($,E):g0.configLoad($,Error(String(E)))}};if(Y)return N1.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let h=await this.loadFromPath(J,w,A);if(h)return h}catch(h){if(h instanceof Error&&h.name==="ConfigLoadError")throw h;if(A.verbose)console.warn(`Failed to load config from ${J}:`,h)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),h=[];for(let U of J)for(let Y of this.extensions)h.push(NU(w,`${U}${Y}`));return h}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return wE(async()=>{return QA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!QA($))return J;if(w||A){let h=this.generateNamePatterns(w||"",A);for(let U of h)for(let Y of this.extensions){let Z=NU($,`${U}${Y}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:h}=await import("fs"),U=h($);for(let Y of U)if(this.looksLikeConfigFile(Y)){let Z=NU($,Y);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!QA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:h}=await import("fs"),U=h($,"utf8");JSON.parse(U)}catch(h){w.push(`Invalid JSON syntax: ${h}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let h=await this.loadFromPath(J,{},w);if(h)A.set(J,h.config)}catch(h){if(w.verbose)console.warn(`Failed to preload ${J}:`,h)}})),A}}class oU{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:h=!0,validateTypes:U=!0,customRules:Y=[],trackPerformance:Z=!0,verbose:f=!1}=A,E=async()=>{let W=[],F=[],j={stopOnFirstError:J,validateRequired:h,validateTypes:U,customRules:Y,trackPerformance:Z,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...Y],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return W.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:W,warnings:F}}};if(Z)return await N1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!LH(w))throw new q1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),h=J.default||J;if(Array.isArray(h))return this.validateWithRules($,h,A);else return this.validateWithJSONSchema($,h,A)}catch(J){throw new q1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],h=[];return this.validateObjectAgainstSchema($,w,"",J,h,A),{isValid:J.length===0,errors:J,warnings:h}}validateObjectAgainstSchema($,w,A,J,h,U){if(U.validateTypes&&w.type){let Y=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(Y)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${Y}`,expected:Z.join(" or "),actual:Y,rule:"type"}),U.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),U.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let Y=0;Y<$.length;Y++){let Z=A?`${A}[${Y}]`:`[${Y}]`;if(this.validateObjectAgainstSchema($[Y],w.items,Z,J,h,U),U.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Y=$;if(U.validateRequired&&w.required){for(let Z of w.required)if(!(Z in Y)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(w.properties){for(let[Z,f]of Object.entries(w.properties))if(Z in Y){let E=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(Y[Z],f,E,J,h,U),U.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(Y))if(!Z.has(f))h.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],h=[];for(let U of w)try{let Y=this.getValueByPath($,U.path),Z=this.validateWithRule(Y,U,U.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(Y){J.push({path:U.path,message:`Rule validation failed: ${Y}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:h}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let h=Array.isArray($)?"array":typeof $;if(h!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${h}`,expected:w.type,actual:h,rule:"type"})}if(w.min!==void 0){let h=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(h<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:h,rule:"min"})}if(w.max!==void 0){let h=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(h>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:h,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let h=w.validator($);if(h)J.push({path:A,message:w.message||h,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let h of A)if(J&&typeof J==="object"&&h in J)J=J[h];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,h,U,Y]=J;w.push({path:h,required:!U,type:this.mapTypeScriptType(Y)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:BE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class eU{fileLoader=new FJ;envProcessor=new WJ;validator=new oU;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:h,validate:U,...Y}=$;try{if(A?.enabled){let f=this.checkCache(Y.name||"",Y);if(f)return f}let Z;try{Z=await this.loadConfigurationStrategies(Y,!0,A)}catch(f){let E=Y.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(E)throw f;Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`No configuration file found for "${Y.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let W=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),F=!W&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),j=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(E&&(j||W))throw f;if(F&&(!E||!j))Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(h||U)await this.validateConfiguration(Z.config,h,U,Y.name);if(A?.enabled&&Z)this.cacheResult(Y.name||"",Z,A,Y);if(J?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:Y.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(f);if(J.slowThreshold&&f.duration>J.slowThreshold)Y0.warn(`Slow configuration loading detected: ${f.duration}ms for ${Y.name}`);Z.metrics=f}return Z}catch(Z){let f=Date.now()-w;throw Y0.error(`Configuration loading failed after ${f}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:h,cwd:U,configDir:Y,defaultConfig:Z,checkEnv:f=!0,arrayStrategy:E="replace",verbose:W=!1}=$,F=U||o0.cwd(),j=[],B=await this.loadLocalConfiguration(J,h,F,Y,Z,E,W,f,A);if(B)return j.push(...this.getLocalSearchPaths(J,h,F,Y)),this.finalizeResult(B,j,f,J,W);let T=await this.loadHomeConfiguration(J,h,Z,E,W,f);if(T)return j.push(...this.getHomeSearchPaths(J,h)),this.finalizeResult(T,j,f,J,W);let H=await this.loadPackageJsonConfiguration(J,h,F,Z,E,W,f);if(H)return j.push(_$(F,"package.json")),this.finalizeResult(H,j,f,J,W);if(j.push(...this.getAllSearchPaths(J,h,F,Y)),w)throw g0.configNotFound(J,j,h);return{...await this.applyEnvironmentVariables(J,Z,f,W),warnings:[`No configuration file found for "${J}"${h?` or alias "${h}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,h,U,Y,Z,f){let E=Z?z1($,h,Y):h,W=this.getLocalDirectories(A,J);for(let F of W){if(Y)Y0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:U,verbose:Y,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(B){if(Y)Y0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,h,U){if(!$)return null;let Y=U?z1($,A,h):A,Z=[_$(Vw(),".config",$),_$(Vw(),".config"),Vw()];for(let f of Z){if(h)Y0.info(`Checking home directory: ${f}`);let E=this.fileLoader.generateConfigPaths($,f,w),W=await this.fileLoader.tryLoadFromPaths(E,Y,{arrayStrategy:J,verbose:h});if(W){if(h)Y0.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,w,A,J,h,U,Y){let Z=Y?z1($,J,U):J;try{let f=_$(A,"package.json");if(!_U(f))return null;let E=await import(f),W=E[$],F=$;if(!W&&w)W=E[w],F=w;if(W&&typeof W==="object"&&!Array.isArray(W)){if(U)Y0.success(`Configuration loaded from package.json: ${F}`);return{config:sU(Z,W,h),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(U)Y0.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:z1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,h){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let h=[];if(A){let U=A($);if(U)h.push(...U)}if(w){let U=await this.validator.validateConfiguration($,w);if(!U.isValid)h.push(...U.errors.map((Y)=>Y.path?`${Y.path}: ${Y.message}`:Y.message))}if(h.length>0)throw g0.configValidation(J||"unknown",h,J)}checkCache($,w){let A=this.generateCacheKey($,w);return nw.get(A)||null}cacheResult($,w,A,J){let h=this.generateCacheKey($,J);nw.set(h,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,_$($,"config"),_$($,".config"),w?_$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let h=[];return h.push(...this.getLocalSearchPaths($,w,A,J)),h.push(...this.getHomeSearchPaths($,w)),h.push(_$(A,"package.json")),h}getLocalSearchPaths($,w,A,J){let h=this.getLocalDirectories(A,J),U=[];for(let Y of h)U.push(...this.fileLoader.generateConfigPaths($,Y,w));return U}getHomeSearchPaths($,w){if(!$)return[];let A=[_$(Vw(),".config",$),_$(Vw(),".config"),Vw()],J=[];for(let h of A)J.push(...this.fileLoader.generateConfigPaths($,h,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function VZ($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||A}async function B9($){return _0.loadConfig({...$,__strictErrorHandling:!0})}async function YE($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await _0.loadConfig($);else J=await _0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let h=J instanceof Error?J.name:"UnknownError",U=J instanceof Error?J.message:String(J);if(!(h==="ConfigNotFoundError"||h==="ConfigLoadError"||h==="ConfigValidationError"||U.includes("config"))&&$.verbose)Y0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let Y=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await _0.applyEnvironmentVariables(Y.name||"",w,!0,Y.verbose||!1))?.config??w;return w}}async function j9($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await _0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&VZ(A)))return(await _0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await _0.loadConfig({...$,cwd:$.cwd||o0.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&VZ(w)))return(await _0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function z9($,w,A="replace"){let J=new FJ;try{let h=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return h?h.config:null}catch{return null}}function z1($,w,A=!1){let J=new WJ,h=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Y,Z=[]){let f={...Y};for(let[E,W]of Object.entries(Y)){let F=[...Z,E],j=[`${h}_${F.join("_").toUpperCase()}`,`${h}_${F.map((H)=>H.toUpperCase()).join("")}`,`${h}_${F.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,T;for(let H of j)if(B=o0.env[H],B!==void 0){T=H;break}if(B!==void 0&&T)if(typeof W==="boolean")f[E]=["true","1","yes"].includes(B.toLowerCase());else if(typeof W==="number"){let H=Number(B);if(!Number.isNaN(H))f[E]=H}else if(Array.isArray(W))try{f[E]=JSON.parse(B)}catch{f[E]=B.split(",").map((H)=>H.trim())}else f[E]=B;else if(W&&typeof W==="object"&&!Array.isArray(W))f[E]=U(W,F)}return f}return U(w)}function H9($){let w=_$(o0.cwd(),$.configDir),A=_$(o0.cwd(),$.generatedDir),J=_$(A,"config-types.ts");if(!_U(YZ(J)))AH(YZ(J),{recursive:!0,mode:511});let h=_U(w)?JH(w).map((Y)=>Y.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],U=`// Generated by bunfig v${d9}
178
+ export type ConfigNames = ${h.length?`'${h.join("' | '")}'`:"string"}
179
+ `;hH(J,U,{mode:438})}function T9($){let w=null,A=null,J=()=>{if(!A)A=YE($).then((U)=>{return w=U,U},(U)=>{let Y="defaultConfig"in $?$.defaultConfig:{};if(w=Y,"verbose"in $&&$.verbose)Y0.warn("Config loading failed, using defaults:",[U instanceof Error?U:Error(String(U))]);return Y});return A},h="defaultConfig"in $?$.defaultConfig:{};return w=h,J(),new Proxy({},{get(U,Y){if(w)return w[Y];let Z=h[Y];return J(),Z},has(U,Y){return Y in(w||h)},ownKeys(){return Object.keys(w||h)},getOwnPropertyDescriptor(U,Y){return Object.getOwnPropertyDescriptor(w||h,Y)},set(U,Y,Z){if(!w)w={...h};return w[Y]=Z,!0}})}function G9($){let w=KZ(DH.cwd(),$?.configDir||"./config");function A(){if(!CH(w))return[];let h=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),U=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Y=SH(w).filter((f)=>h.has(KU(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),Z=new Map;for(let{base:f,file:E}of Y){let W=KU(E).toLowerCase(),F=Z.get(f);if(!F){Z.set(f,E);continue}let j=KU(F).toLowerCase();if(U.indexOf(W)<U.indexOf(j))Z.set(f,E)}return Array.from(Z.entries()).map(([f,E])=>({base:f,file:E})).sort((f,E)=>f.base.localeCompare(E.base))}function J(){let h=A(),U=h.map((f)=>f.base),Y=U.length?U.map((f)=>`'${f}'`).join(" | "):"string",Z=h.length?`{
180
+ ${h.map((f)=>{let E=KZ(w,f.file).replace(/\\/g,"/");return` '${f.base}': typeof import('${E}').default`}).join(`,
181
+ `)}
182
+ }`:"Record<string, any>";return`export type ConfigNames = ${Y}
183
+ export type ConfigByName = ${Z}
184
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
185
+ export type ConfigOf = Config
186
+ `}return{name:"bunfig-plugin",setup(h){h.onResolve({filter:/^virtual:bunfig-types$/},(U)=>{return{path:U.path,namespace:"bunfig-virtual"}}),h.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}var fE,nw,N1,ZE,q9,R9,OZ,mA,QU,M$,d,N9,_Z,K9,XZ,M9,y9,CU,I9,kZ,QZ,SU,L9,C9,S9,D9,dA,EE,V9,y$,O9,_9,xZ,gA,xU,f$,X,X9,PZ,k9,iZ,Q9,x9,DU,P9,bZ,cZ,i9,VU,b9,c9,n9,u9,v9,lA,WE,m9,d9="0.15.6",u$,AJ,G1,PU,iU,JJ,bU,cU,q1,nU,uU,g0,FE,BE,Y0,_0,jE,zE,g9=gH(async()=>{fE=import.meta.require,nw=new tU,N1=new pU,ZE={createKey:lH,isEquivalent:tH,estimateMemoryUsage:pH},q9=rA(XU.cwd(),"config"),R9=rA(XU.cwd(),"src/generated"),OZ=pA.env.CLARITY_LOG_DIR||fH(sH(),"logs"),mA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:OZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},QU=await oH(),M$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},d=M$,N9=M$.red,_Z=M$.green,K9=M$.yellow,XZ=M$.blue,M9=M$.magenta,y9=M$.cyan,CU=M$.white,I9=M$.gray,kZ=M$.bgRed,QZ=M$.bgYellow,SU=M$.bold,L9=M$.dim,C9=M$.italic,S9=M$.underline,D9=M$.reset,dA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EE={debug:"\uD83D\uDD0D",info:XZ("ℹ"),success:_Z("✓"),warning:QZ(CU(SU(" WARN "))),error:kZ(CU(SU(" ERROR ")))},V9=new eA("stacks"),y$=new eA("bunfig",{showTags:!0}),O9=O$(T1.cwd(),"config"),_9=O$(T1.cwd(),"src/generated"),xZ=tA.env.CLARITY_LOG_DIR||UH(A9(),"logs"),gA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},xU=await J9(),f$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},X=f$,X9=f$.red,PZ=f$.green,k9=f$.yellow,iZ=f$.blue,Q9=f$.magenta,x9=f$.cyan,DU=f$.white,P9=f$.gray,bZ=f$.bgRed,cZ=f$.bgYellow,i9=f$.bgGray,VU=f$.bold,b9=f$.dim,c9=f$.italic,n9=f$.underline,u9=f$.strikethrough,v9=f$.reset,lA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},WE={debug:"\uD83D\uDD0D",info:iZ("ℹ"),success:PZ("✓"),warning:cZ(DU(VU(" WARN "))),error:bZ(DU(VU(" ERROR ")))},m9=new wJ("stacks"),u$=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},AJ=class extends u${code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A?` or alias "${A}"`:"";super(`Configuration "${$}"${J} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}},G1=class extends u${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}},PU=class extends u${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},iU=class extends u${code="CONFIG_MERGE_ERROR";constructor($,w,A,J){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},JJ=class extends u${code="ENV_VAR_ERROR";constructor($,w,A,J){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:J})}},bU=class extends u${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}},cU=class extends u${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}},q1=class extends u${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},nU=class extends u${code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}},uU=class extends u${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}},g0={configNotFound($,w,A){return new AJ($,w,A)},configLoad($,w,A){return new G1($,w,A)},configValidation($,w,A){return new PU($,w,A)},configMerge($,w,A,J){return new iU($,w,A,J)},envVar($,w,A,J){return new JJ($,w,A,J)},fileSystem($,w,A){return new bU($,w,A)},typeGeneration($,w,A){return new cU($,w,A)},schemaValidation($,w,A){return new q1($,w,A)},browserConfig($,w,A,J){return new nU($,w,A,J)},plugin($,w,A){return new uU($,w,A)}},FE={replace:"replace",concat:"concat",smart:"smart"},BE=/^https?:\/\//,Y0=new wJ("bunfig",{showTags:!0}),_0=new eU,jE=_$(o0.cwd(),"config"),zE=_$(o0.cwd(),"src/generated")});function l9($,w={}){let A=aA.cwd();while(A.includes("storage"))A=MZ(A,"..");let J=MZ(A,$||"");if(w?.relative)return OH(aA.cwd(),J);return J}var t9=aA.env.CLARITY_LOG_DIR||VH(l9(),"logs"),HE={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:t9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},hJ={...HE},dR=(async()=>{try{let{loadConfig:$}=await g9().then(()=>oZ),w=await $({name:"clarity",alias:"logging",defaultConfig:HE,cwd:aA.cwd()});if(w)Object.assign(hJ,w)}catch{}return hJ})();function Z$(){if(V0.env.NODE_ENV==="test"||V0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function p9(){if(V0.env.NODE_ENV==="test"||V0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof V0<"u"){let $=V0.type;if($==="renderer"||$==="worker")return!1;return!!(V0.versions&&(V0.versions.node||V0.versions.bun))}return!1}class TE{async format($){let w=await p9(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:bw.pid,hostname:w(),environment:bw.env.NODE_ENV||"development",platform:bw.platform,version:bw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:bw.env.NODE_ENV||bw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var z$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},x=z$,gR=z$.red,r9=z$.green,lR=z$.yellow,a9=z$.blue,tR=z$.magenta,pR=z$.cyan,nZ=z$.white,rR=z$.gray,s9=z$.bgRed,o9=z$.bgYellow,aR=z$.bgGray,uZ=z$.bold,sR=z$.dim,oR=z$.italic,eR=z$.underline,$N=z$.strikethrough,wN=z$.reset,OU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},e9={debug:"\uD83D\uDD0D",info:a9("ℹ"),success:r9("✓"),warning:o9(nZ(uZ(" WARN "))),error:s9(nZ(uZ(" ERROR ")))};class BJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...hJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new TE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let h=this.generateKeyId(),U=this.generateKey();this.currentKeyId=h,this.keys.set(h,U),this.encryptionKeys.set(h,{key:U,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...OU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...OU};return{...OU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:hJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!Z$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let J,h=0,U=3,Y=1000;while(h<U)try{try{try{await xH(this.config.logDirectory,CZ.F_OK|CZ.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await PH(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:L0.from($);try{if(!xA(this.currentLogFile))await IU(this.currentLogFile,"",{mode:420});if(J=LZ(this.currentLogFile,"a",420),QH(J,Z,{flag:"a"}),IZ(J),J!==void 0)yU(J),J=void 0;if((await Pw(this.currentLogFile)).size===0){if(await IU(this.currentLogFile,Z,{flag:"w",mode:420}),(await Pw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let E=f;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(h<U-1){let W=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${h+1}/${U}:`,W);let F=Y*2**h;await new Promise((j)=>setTimeout(j,F)),h++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(J!==void 0)try{yU(J)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(Z){if(h===U-1){let E=Z,W=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),Z}h++;let f=Y*2**(h-1);await new Promise((E)=>setTimeout(E,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return iw(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 iw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return iw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(Z$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,Y],[,Z])=>Z.createdAt.getTime()-Y.createdAt.getTime()),h=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,h);if(J.length>U)for(let[Y]of J.slice(U))this.encryptionKeys.delete(Y),this.keys.delete(Y)}generateKeyId(){return MU(16).toString("hex")}generateKey(){return MU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=MU(16),J=_H("aes-256-gcm",w,A),h=L0.isBuffer($)?$:L0.from($,"utf8"),U=J.update(h),Y=J.final(),Z=U.length+Y.length,f=J.getAuthTag(),E=L0.allocUnsafe(16+Z+16);return A.copy(E,0),U.copy(E,16),Y.copy(E,16+U.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=DZ(),h=[];J.on("data",(U)=>h.push(U)),J.on("end",()=>w(L0.from(L0.concat(h)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(Z$())return;if(!this.shouldWriteToFile())return;let $=await Pw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let h=await PA(this.config.logDirectory),U=h.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),Y=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${Y}`;if(await Pw(A).catch(()=>null))try{if(await SZ(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await iA(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(U.length===0&&!h.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await IU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let h=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${h}.log`);if(await Pw(A).catch(()=>null))await SZ(A,U)}if(this.currentLogFile=J,w.maxFiles){let h=(await PA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Y)=>Y.localeCompare(U));for(let U of h.slice(w.maxFiles))await iA(iw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=yZ($),J=kH(w),h=DZ();await cH(A,h,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),xA(this.currentLogFile))try{let $=LZ(this.currentLogFile,"r+");IZ($),yU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!Z$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await PA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await iA(iw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?x.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Z$())return!1;let $=typeof n.env.NO_COLOR<"u",w=n.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:h,level:U,showTimestamp:Y=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(Y)B.push(w);if(U==="warning")B.push("WARN");else if(U==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(h),B.join(" ")}let f=n.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${h}`;else if(U==="info"||U==="success")E=`${A} ${J} ${h}`;else E=`${A} ${J} ${x.cyan(h)}`;if(!Y)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Y)=>{let Z=Number.parseInt(Y,10);return Z<w[0].length?String(w[0][Z]):U});let A=/%([sdijfo%])/g,J=0,h=$.replace(A,(U,Y)=>{if(Y==="%")return"%";if(J>=w.length)return U;let Z=w[J++];switch(Y){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return U}});if(J<w.length)h+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return h}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,h)=>{let U=x.underline(x.blue(J)),Y=this.toAbsoluteFilePath(h);if(Y&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(Y)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${h}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),w=w.replace(/`([^`]+)`/g,(A,J)=>x.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>x.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>x.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>x.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>x.strikethrough(J)),w}supportsHyperlinks(){if(Z$())return!1;let $=n.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=n.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(iH(w)||w.startsWith("./")||w.startsWith("../"))w=bH(w);else return null;return xA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,h=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Y,Z;if(w instanceof Error)Y=w.message,Z=w.stack;else Y=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":e9[$],j=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:x.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:x.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:h,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
187
+ `);for(let H of T)if(H.trim()&&!H.includes(Y))console.error(this.formatConsoleMessage({timestamp:h,message:x.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!Z$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Y}`),Z)console.error(Z)}let W=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
188
+ `;if(Z)W+=`${Z}
189
+ `;if(W=W.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(W)}progress($,w=""){let A={update:(h,U)=>{},finish:(h)=>{},interrupt:(h,U)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!Z$()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(h,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!Z$()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,U="info")=>{if(!Z$()&&n.stdout.isTTY)n.stdout.write(`
190
+ `);if(this[U==="warning"?"warn":U](h),this.activeProgressBar&&this.shouldStyleConsole()&&!Z$()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":x.blue("◐"),tag:A,message:`${x.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),h=Math.round(J-w),U=`${$} completed in ${h}ms`,Y=new Date,Z=this.formatConsoleTimestamp(Y),f=`${this.formatFileTimestamp(Y)} ${this.environment}.INFO: ${U}`;if(A)f+=` ${JSON.stringify(A)}`;if(f+=`
191
+ `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":x.green("✓"),tag:E,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!Z$())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new BJ(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(Z$())throw Error("createReadStream is not supported in browser environments");if(!xA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return yZ(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=L0.isBuffer($)?$:L0.from($,"base64"),h=J.subarray(0,16),U=J.subarray(J.length-16),Y=J.subarray(16,J.length-16),Z=XH("aes-256-gcm",A,h);Z.setAuthTag(U);let f=Z.update(Y),E=Z.final(),W=f.length+E.length,F=L0.allocUnsafe(W);return f.copy(F,0),E.copy(F,f.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Z$()}isServerMode(){return!Z$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:h,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=h.split(`
192
+ `),f=Math.max(...Z.map((j)=>j.length))+2,E=`┌${"─".repeat(f)}┐`,W=`└${"─".repeat(f)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:x.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:x.cyan(E),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:x.cyan(W),showTimestamp:!1}))}else if(!Z$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Y=`${J} ${this.environment}.INFO: [BOX] ${U}
193
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}async prompt($){if(Z$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${x.cyan("?")} ${$} (y/n) `);let A=(J)=>{let h=J.toString().trim().toLowerCase();n.stdin.removeListener("data",A);try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!1)}catch{}n.stdin.pause(),console.error(""),w(h==="y"||h==="yes")};try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!0)}catch{}n.stdin.resume(),n.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let Y=/%([sdijfo%])/g,Z=0;if(A=$.replace(Y,(f,E)=>{if(E==="%")return"%";if(Z>=w.length)return f;let W=w[Z++];switch(E){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return f}}),Z<w.length)A+=` ${w.slice(Z).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:J,fileText:h}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",Z=this.options.showIcons===!1?"":`${x.blue("◐")} `;console.error(`${Z}${Y} ${x.cyan(J)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${h}
194
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!n.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),h=$.barLength-J,U=x.green("━".repeat(J)),Y=x.gray("━".repeat(h)),Z=`[${U}${Y}]`,f=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",W=this.options.showIcons===!1?"":w||A===100?x.green("✓"):x.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",j=`\r${W}${F} ${Z} ${f}${E}`,B=n.stdout.columns||80,T=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,n.stdout.write($.lastRenderedLine),w)n.stdout.write(`
195
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Z$()||!n.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(Z$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await PA(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let h=iw(this.config.logDirectory,J);if($.before)try{if((await Pw(h)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${h}:`,U);continue}A.push(h)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await iA(J),console.warn(`Deleted log file: ${J}`)}catch(h){console.error(`Failed to delete log file ${J}:`,h)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var AN=new BJ("stacks");class E0 extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}}class GE extends E0{code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],h="";if(J.length===1)h=` or alias "${J[0]}"`;else if(J.length>1)h=` or aliases ${J.map((U)=>`"${U}"`).join(", ")}`;super(`Configuration "${$}"${h} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}}class UJ extends E0{code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}}class qE extends E0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}}class RE extends E0{code="CONFIG_MERGE_ERROR";constructor($,w,A,J){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}}class $Y extends E0{code="ENV_VAR_ERROR";constructor($,w,A,J){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:J})}}class NE extends E0{code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}}class KE extends E0{code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}}class YJ extends E0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}}class ME extends E0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}}class yE extends E0{code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}}var uw={configNotFound($,w,A){return new GE($,w,A)},configLoad($,w,A){return new UJ($,w,A)},configValidation($,w,A){return new qE($,w,A)},configMerge($,w,A,J){return new RE($,w,A,J)},envVar($,w,A,J){return new $Y($,w,A,J)},fileSystem($,w,A){return new NE($,w,A)},typeGeneration($,w,A){return new KE($,w,A)},schemaValidation($,w,A){return new YJ($,w,A)},browserConfig($,w,A,J){return new ME($,w,A,J)},plugin($,w,A){return new yE($,w,A)}};async function $T($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:h=()=>!0,fallback:U}=w,Y=Error("Unknown error occurred");for(let Z=0;Z<=A;Z++)try{return await $()}catch(f){if(Y=f instanceof Error?f:Error(String(f)),Z===A||!h(Y))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(U!==void 0)return U;throw Y instanceof Error?Y:Error(`Unknown error: ${String(Y)}`)}class wY{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:J,useCamelCase:h=!0,useBackwardCompatibility:U=!0,customParsers:Y={},verbose:Z=!1,trackPerformance:f=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let W=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],W,{useCamelCase:h,useBackwardCompatibility:U,customParsers:Y,verbose:Z,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return lU.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[h,U]of Object.entries($)){let Y=[...w,h],Z=Y.map((W)=>this.formatEnvKey(W,J.useCamelCase)),f=`${A}_${Z.join("_")}`,E=J.useBackwardCompatibility?`${A}_${Y.map((W)=>W.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Y,A,J);else{let W=bA.env[f]||(E?bA.env[E]:void 0);if(W!==void 0){if(J.verbose){let F=bA.env[f]?f:E}try{$[h]=this.parseEnvironmentValue(W,typeof U,f,J.customParsers,J.configName)}catch(F){if(F instanceof $Y)throw F;throw uw.envVar(f,W,typeof U,J.configName)}}}}}parseEnvironmentValue($,w,A,J,h){for(let[U,Y]of Object.entries(J))try{return Y($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,w))try{return U.parse($)}catch{throw uw.envVar(A,$,`${w} (via ${U.name} parser)`,h)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,h]of Object.entries(bA.env))if(J.startsWith(A)&&h!==void 0)w[J]=h;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(h){J.push(`Cannot parse value "${w}" as ${A}: ${h}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:h="text"}=A,U=J||this.generateEnvPrefix($),Y=[];switch(this.extractEnvVarInfo(w,[],U,Y),h){case"markdown":return this.formatAsMarkdown(Y,$);case"json":return JSON.stringify(Y,null,2);default:return this.formatAsText(Y,$)}}extractEnvVarInfo($,w,A,J){for(let[h,U]of Object.entries($)){let Y=[...w,h],Z=`${A}_${Y.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Y,A,J);else J.push({key:Z,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Y.join(".")}`,example:this.generateExample(U)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
196
+
197
+ `;for(let J of $)A+=`${J.key}
198
+ `,A+=` Type: ${J.type}
199
+ `,A+=` Description: ${J.description}
200
+ `,A+=` Example: ${J.example}
201
+
202
+ `;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
203
+
204
+ `;A+=`| Variable | Type | Description | Example |
205
+ `,A+=`|----------|------|-------------|----------|
206
+ `;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
207
+ `;return A}}function wT($,w,A={}){return IE($,w,A,new WeakMap)}function IE($,w,A,J){let{arrayMergeMode:h="replace",skipNullish:U=!1,customMerger:Y}=A;if(w===null||w===void 0)return U?$:w;if(Y){let Z=Y($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return LE($,w,h,J);if(!e$(w)||!e$($))return w;return UT($,w,A,J)}function LE($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return AT($,w);case"smart":return JT($,w,J);default:return w}return w}function AT($,w){let A=[...w];for(let J of $)if(!A.some((h)=>vU(h,J)))A.push(J);return A}function JT($,w,A){if(w.length===0)return $;if($.length===0)return w;if(e$(w[0])&&e$($[0]))return hT($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let h of $)if(!J.includes(h))J.push(h);return J}return w}function hT($,w,A){let J=[...w];for(let h of $){if(!e$(h)){J.push(h);continue}let U=["id","name","key","path","type"],Y=!1;for(let Z of U)if(Z in h){if(J.find((f)=>e$(f)&&(Z in f)&&f[Z]===h[Z])){Y=!0;break}}if(!Y)J.push(h)}return J}function UT($,w,A,J){let h=w;if(e$(h)&&J.has(h))return J.get(h);let U={...$};if(e$(h))J.set(h,U);for(let Y in h){if(!Object.prototype.hasOwnProperty.call(h,Y))continue;let Z=h[Y],f=U[Y];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){U[Y]=Z;continue}if(e$(Z)&&e$(f))U[Y]=IE(f,Z,A,J);else if(Array.isArray(Z)||Array.isArray(f))U[Y]=LE(f,Z,A.arrayMergeMode||"smart",J);else U[Y]=Z}return U}function CE($,w,A="replace"){return wT($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function vU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!vU($[A],w[A]))return!1;return!0}if(e$($)&&e$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let h of A){if(!Object.prototype.hasOwnProperty.call(w,h))return!1;if(!vU($[h],w[h]))return!1}return!0}return!1}function e$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class SE{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:h=!0,cacheTtl:U,trackPerformance:Y=!0,verbose:Z=!1}=A;if(h){let E=sA.getWithFileCheck("file",$);if(E){if(Z)console.log(`Configuration loaded from cache: ${$}`);return E}}let f=async()=>{if(!cA($))return null;try{let E=`?t=${Date.now()}`,W=await import($+E),F=W.default||W,j="default"in W,B=Object.keys(W).length>0;if(!j&&!B)throw new UJ($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new UJ($,Error("Configuration must export a valid object"),"unknown");let T={config:CE(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(h)sA.setWithFileCheck("file",T,$,U);return T}catch(E){throw E instanceof Error?uw.configLoad($,E):uw.configLoad($,Error(String(E)))}};if(Y)return lU.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let h=await this.loadFromPath(J,w,A);if(h)return h}catch(h){if(h instanceof Error&&h.name==="ConfigLoadError")throw h;if(A.verbose)console.warn(`Failed to load config from ${J}:`,h)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),h=[];for(let U of J)for(let Y of this.extensions)h.push(LU(w,`${U}${Y}`));return h}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let J=w===void 0?[]:Array.isArray(w)?w:[w];for(let U of J){if(!U)continue;if(A.push(U,`.${U}.config`,`${U}.config`,`.${U}`),$)A.push(`${$}.${U}.config`,`.${$}.${U}.config`)}let h=new Set;return A.filter((U)=>{if(!U||h.has(U))return!1;return h.add(U),!0})}checkFileAccess($){return $T(async()=>{return cA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!cA($))return J;if(w||A){let h=this.generateNamePatterns(w||"",A);for(let U of h)for(let Y of this.extensions){let Z=LU($,`${U}${Y}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:h}=await import("fs"),U=h($);for(let Y of U)if(this.looksLikeConfigFile(Y)){let Z=LU($,Y);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!cA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:h}=await import("fs"),U=h($,"utf8");JSON.parse(U)}catch(h){w.push(`Invalid JSON syntax: ${h}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let h=await this.loadFromPath(J,{},w);if(h)A.set(J,h.config)}catch(h){if(w.verbose)console.warn(`Failed to preload ${J}:`,h)}})),A}}var YT=/^https?:\/\//;class DE{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:h=!0,validateTypes:U=!0,customRules:Y=[],trackPerformance:Z=!0,verbose:f=!1}=A,E=async()=>{let W=[],F=[],j={stopOnFirstError:J,validateRequired:h,validateTypes:U,customRules:Y,trackPerformance:Z,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...Y],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return W.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:W,warnings:F}}};if(Z)return await lU.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!nH(w))throw new YJ(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),h=J.default||J;if(Array.isArray(h))return this.validateWithRules($,h,A);else return this.validateWithJSONSchema($,h,A)}catch(J){throw new YJ(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],h=[];return this.validateObjectAgainstSchema($,w,"",J,h,A),{isValid:J.length===0,errors:J,warnings:h}}validateObjectAgainstSchema($,w,A,J,h,U){if(U.validateTypes&&w.type){let Y=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(Y)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${Y}`,expected:Z.join(" or "),actual:Y,rule:"type"}),U.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),U.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let Y=0;Y<$.length;Y++){let Z=A?`${A}[${Y}]`:`[${Y}]`;if(this.validateObjectAgainstSchema($[Y],w.items,Z,J,h,U),U.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Y=$;if(U.validateRequired&&w.required){for(let Z of w.required)if(!(Z in Y)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(w.properties){for(let[Z,f]of Object.entries(w.properties))if(Z in Y){let E=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(Y[Z],f,E,J,h,U),U.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(Y))if(!Z.has(f))h.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],h=[];for(let U of w)try{let Y=this.getValueByPath($,U.path),Z=this.validateWithRule(Y,U,U.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(Y){J.push({path:U.path,message:`Rule validation failed: ${Y}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:h}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let h=Array.isArray($)?"array":typeof $;if(h!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${h}`,expected:w.type,actual:h,rule:"type"})}if(w.min!==void 0){let h=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(h<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:h,rule:"min"})}if(w.max!==void 0){let h=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(h>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:h,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let h=w.validator($);if(h)J.push({path:A,message:w.message||h,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let h of A)if(J&&typeof J==="object"&&h in J)J=J[h];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,h,U,Y]=J;w.push({path:h,required:!U,type:this.mapTypeScriptType(Y)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:YT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var C0=new BJ("bunfig",{showTags:!0});function fT($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class VE{fileLoader=new SE;envProcessor=new wY;validator=new DE;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:h,validate:U,...Y}=$;try{if(A?.enabled){let f=this.checkCache(Y.name||"",Y);if(f)return f}let Z;try{Z=await this.loadConfigurationStrategies(Y,!0,A)}catch(f){let E=Y.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(E)throw f;Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`No configuration file found for "${Y.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let W=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),F=!W&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),j=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(E&&(j||W))throw f;if(F&&(!E||!j))Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else Z={...await this.applyEnvironmentVariables(Y.name||"",Y.defaultConfig,Y.checkEnv!==!1,Y.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(h||U)await this.validateConfiguration(Z.config,h,U,Y.name);if(A?.enabled&&Z)this.cacheResult(Y.name||"",Z,A,Y);if(J?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:Y.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(f);if(J.slowThreshold&&f.duration>J.slowThreshold)C0.warn(`Slow configuration loading detected: ${f.duration}ms for ${Y.name}`);Z.metrics=f}return Z}catch(Z){if(Z instanceof Error&&Z.name==="ConfigNotFoundError")throw Z;let f=Date.now()-w;throw C0.error(`Configuration loading failed after ${f}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:h,cwd:U,configDir:Y,defaultConfig:Z,checkEnv:f=!0,arrayStrategy:E="replace",verbose:W=!1}=$,F=U||EJ.cwd(),j=[],B=await this.loadLocalConfiguration(J,h,F,Y,Z,E,W,f,A);if(B)return j.push(...this.getLocalSearchPaths(J,h,F,Y)),this.finalizeResult(B,j,f,J,W);let T=await this.loadHomeConfiguration(J,h,Z,E,W,f);if(T)return j.push(...this.getHomeSearchPaths(J,h)),this.finalizeResult(T,j,f,J,W);let H=await this.loadPackageJsonConfiguration(J,h,F,Z,E,W,f);if(H)return j.push(s$(F,"package.json")),this.finalizeResult(H,j,f,J,W);if(j.push(...this.getAllSearchPaths(J,h,F,Y)),w)throw uw.configNotFound(J,j,h);return{...await this.applyEnvironmentVariables(J,Z,f,W),warnings:[`No configuration file found for "${J}"${fT(h)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,h,U,Y,Z,f){let E=Z?uA($,h,Y):h,W=this.getLocalDirectories(A,J);for(let F of W){if(Y)C0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:U,verbose:Y,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(B){if(Y)C0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,h,U){if(!$)return null;let Y=U?uA($,A,h):A,Z=[s$(Dw(),".config",$),s$(Dw(),".config"),Dw()];for(let f of Z){if(h)C0.info(`Checking home directory: ${f}`);let E=this.fileLoader.generateConfigPaths($,f,w),W=await this.fileLoader.tryLoadFromPaths(E,Y,{arrayStrategy:J,verbose:h});if(W){if(h)C0.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,w,A,J,h,U,Y){let Z=Y?uA($,J,U):J;try{let f=s$(A,"package.json");if(!$H(f))return null;let E={};try{E=JSON.parse(wH(f,"utf8"))}catch(j){if(U)C0.warn("Failed to parse package.json:",[j instanceof Error?j:Error(String(j))]);return null}let W=E[$],F=$;if(!W&&w){let j=Array.isArray(w)?w:[w];for(let B of j){if(!B)continue;if(E[B]){W=E[B],F=B;break}}}if(W&&typeof W==="object"&&!Array.isArray(W)){if(U)C0.success(`Configuration loaded from package.json: ${F}`);return{config:CE(Z,W,h),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(U)C0.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:uA($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,h){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let h=[];if(A){let U=A($);if(U)h.push(...U)}if(w){let U=await this.validator.validateConfiguration($,w);if(!U.isValid)h.push(...U.errors.map((Y)=>Y.path?`${Y.path}: ${Y.message}`:Y.message))}if(h.length>0)throw uw.configValidation(J||"unknown",h,J)}checkCache($,w){let A=this.generateCacheKey($,w);return sA.get(A)||null}cacheResult($,w,A,J){let h=this.generateCacheKey($,J);sA.set(h,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let J=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${J}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,s$($,"config"),s$($,".config"),w?s$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let h=[];return h.push(...this.getLocalSearchPaths($,w,A,J)),h.push(...this.getHomeSearchPaths($,w)),h.push(s$(A,"package.json")),h}getLocalSearchPaths($,w,A,J){let h=this.getLocalDirectories(A,J),U=[];for(let Y of h)U.push(...this.fileLoader.generateConfigPaths($,Y,w));return U}getHomeSearchPaths($,w){if(!$)return[];let A=[s$(Dw(),".config",$),s$(Dw(),".config"),Dw()],J=[];for(let h of A)J.push(...this.fileLoader.generateConfigPaths($,h,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}var JN=new VE;function uA($,w,A=!1){let J=new wY,h=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Y,Z=[]){let f={...Y};for(let[E,W]of Object.entries(Y)){let F=[...Z,E],j=[`${h}_${F.join("_").toUpperCase()}`,`${h}_${F.map((H)=>H.toUpperCase()).join("")}`,`${h}_${F.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,T;for(let H of j)if(B=EJ.env[H],B!==void 0){T=H;break}if(B!==void 0&&T)if(typeof W==="boolean")f[E]=["true","1","yes"].includes(B.toLowerCase());else if(typeof W==="number"){let H=Number(B);if(!Number.isNaN(H))f[E]=H}else if(Array.isArray(W))try{f[E]=JSON.parse(B)}catch{f[E]=B.split(",").map((H)=>H.trim())}else f[E]=B;else if(W&&typeof W==="object"&&!Array.isArray(W))f[E]=U(W,F)}return f}return U(w)}var hN=s$(EJ.cwd(),"config"),UN=s$(EJ.cwd(),"src/generated"),OE={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:FU.join(WU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:FU.join(WU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:FU.join(WU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},A$=OE,f0={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var I={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},cw={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};function mU($,w){let A=[];function J(h){let U;try{U=vZ.readdirSync(h)}catch{return}for(let Y of U){let Z=U0.join(h,Y);try{if(vZ.statSync(Z).isDirectory())J(Z);else if(Y===w)A.push(h)}catch{continue}}}return J($),A}function M($,w,A){if(A||A$.verbose)console.debug(`[tlsx:${$}] ${w}`)}var FT=WT(ZT);function XE(){return _E.env.SUDO_PASSWORD}var mZ="[redacted]",BT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),jT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function zT($){let w=$.toLowerCase();return BT.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function fJ($){if(Array.isArray($))return $.map((A)=>fJ(A));if(typeof $==="string")return jT.test($)?mZ:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(zT(A)){w[A]=mZ;continue}w[A]=fJ(J)}return w}function jJ($){return JSON.stringify(fJ($))}function HT($){let w=XE();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let A=w.replace(/'/g,"'\\''"),J=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${A}' | ${J}`}async function d0($,w={}){let A=HT($);try{let{stdout:J,stderr:h}=await FT(A,{cwd:w.cwd||_E.cwd(),timeout:w.timeout||30000});return{stdout:J.trim(),stderr:h.trim()}}catch(J){let h=Error(`Failed to execute command: ${$}
208
+ Error: ${J.message}`);throw h.stack=J.stack,h}}function kE($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function AY($){let w=U0.join(ET.homedir(),".stacks","ssl"),A=$.basePath&&$.basePath.trim()!==""?$.basePath:A$.basePath&&A$.basePath.trim()!==""?A$.basePath:w,J=$.certPath?U0.isAbsolute($.certPath)?$.certPath:U0.join(A,$.certPath):U0.join(A,A$.certPath),h=$.keyPath?U0.isAbsolute($.keyPath)?$.keyPath:U0.join(A,$.keyPath):U0.join(A,A$.keyPath),U=$.caCertPath?U0.isAbsolute($.caCertPath)?$.caCertPath:U0.join(A,$.caCertPath):U0.join(A,A$.caCertPath);return{certPath:J,keyPath:h,caCertPath:U,basePath:A}}function QE($){let w=[],A=new Set;if($.domain)A.add($.domain);if($.domains?.length)$.domains.forEach((J)=>A.add(J));for(let J of A)w.push({type:2,value:J});if($.altNameIPs?.length)for(let J of $.altNameIPs)w.push({type:7,ip:J});if($.altNameURIs?.length)for(let J of $.altNameURIs)w.push({type:6,value:J});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return M(I.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function JY($){let w=$.notBeforeDays??f0.DEFAULT_NOT_BEFORE_DAYS,A=$.validityDays??($.validityYears?$.validityYears*365:f0.DEFAULT_VALIDITY_DAYS);M(I.CERT,"Calculating certificate validity dates",$.verbose);let J=new Date(Date.now()-86400*w*1000),h=new Date(J.getTime()+A*24*60*60*1000);return J.setUTCHours(0,0,0,0),h.setUTCHours(23,59,59,999),M(I.CERT,`Validity period: ${J.toISOString()} to ${h.toISOString()}`,$.verbose),{notBefore:J,notAfter:h}}var Z0={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},X$={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};function H1($){if($<128)return Buffer.from([$]);let w=[],A=$;while(A>0)w.unshift(A&255),A>>=8;return Buffer.from([128|w.length,...w])}function m$($,w){let A=H1(w.length);return Buffer.concat([Buffer.from([$]),A,w])}function R1($){let w=$.split(".").map(Number),A=[];A.push(40*w[0]+w[1]);for(let J=2;J<w.length;J++){let h=w[J],U=[];U.unshift(h&127),h>>=7;while(h>0)U.unshift(h&127|128),h>>=7;A.push(...U)}return m$(Z0.OID,Buffer.from(A))}function dU($){let w;if(typeof $==="bigint"){let A=$.toString(16).padStart(2,"0");w=Buffer.from(A.length%2?`0${A}`:A,"hex")}else if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let A=$.toString(16).padStart(2,"0");w=Buffer.from(A.length%2?`0${A}`:A,"hex")}else w=$;if(w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return m$(Z0.INTEGER,w)}function xE($,w=0){return m$(Z0.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function PE($){return m$(Z0.OCTET_STRING,$)}function v$(...$){return m$(Z0.SEQUENCE,Buffer.concat($))}function TT(...$){return m$(Z0.SET,Buffer.concat($))}function GT($){return m$(Z0.PRINTABLE_STRING,Buffer.from($,"ascii"))}function qT($){return m$(Z0.UTF8_STRING,Buffer.from($,"utf8"))}function RT(){return Buffer.from([Z0.NULL,0])}function dZ($,w,A=!0){let J=160|$|(A?0:0),h=H1(w.length);return Buffer.concat([Buffer.from([J]),h,w])}function gZ($){let w=$.getUTCFullYear();if(w>=2050){let A=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return m$(Z0.GENERALIZED_TIME,Buffer.from(A,"ascii"))}else{let A=(w%100).toString().padStart(2,"0"),J=($.getUTCMonth()+1).toString().padStart(2,"0"),h=$.getUTCDate().toString().padStart(2,"0"),U=$.getUTCHours().toString().padStart(2,"0"),Y=$.getUTCMinutes().toString().padStart(2,"0"),Z=$.getUTCSeconds().toString().padStart(2,"0"),f=`${A}${J}${h}${U}${Y}${Z}Z`;return m$(Z0.UTC_TIME,Buffer.from(f,"ascii"))}}function NT($,w){return v$(gZ($),gZ(w))}function lZ($){let w=[];for(let A of $){let J;switch(A.shortName){case"CN":J=X$.COMMON_NAME;break;case"C":J=X$.COUNTRY;break;case"L":J=X$.LOCALITY;break;case"ST":J=X$.STATE;break;case"O":J=X$.ORGANIZATION;break;case"OU":J=X$.ORGANIZATIONAL_UNIT;break;default:continue}let h=A.shortName==="C"?GT(A.value):qT(A.value),U=v$(R1(J),h);w.push(TT(U))}return v$(...w)}function iE($){return v$(R1($),RT())}function KT($){return $.export({type:"spki",format:"der"})}function MT($){if($.includes(":")){let w=$;if($.includes("::")){let h=$.split("::"),U=h[0]?h[0].split(":"):[],Y=h[1]?h[1].split(":"):[],Z=8-U.length-Y.length,f=Array.from({length:Z},()=>"0");w=[...U,...f,...Y].join(":")}let A=w.split(":"),J=Buffer.alloc(16);for(let h=0;h<8;h++){let U=Number.parseInt(A[h]||"0",16);J.writeUInt16BE(U,h*2)}return J}else{let w=$.split(".").map((A)=>Number.parseInt(A,10));return Buffer.from(w)}}function yT($){let w=[];for(let A of $)if(A.type===2&&A.value){let J=H1(A.value.length);w.push(Buffer.concat([Buffer.from([130]),J,Buffer.from(A.value,"ascii")]))}else if(A.type===7&&A.ip){let J=MT(A.ip),h=H1(J.length);w.push(Buffer.concat([Buffer.from([135]),h,J]))}else if(A.type===6&&A.value){let J=H1(A.value.length);w.push(Buffer.concat([Buffer.from([134]),J,Buffer.from(A.value,"ascii")]))}return v$(...w)}function IT($,w){if($){if(w!==void 0)return v$(m$(1,Buffer.from([255])),dU(w));return v$(m$(1,Buffer.from([255])))}return v$()}function LT($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let A=0,J=w;while(J>0&&(J&1)===0)A++,J>>=1;if(w===0)A=7;return xE(Buffer.from([w]),A)}function CT($){let w=[];if($.serverAuth)w.push(R1(X$.SERVER_AUTH));if($.clientAuth)w.push(R1(X$.CLIENT_AUTH));return v$(...w)}function j1($,w,A){let J=[R1($)];if(w)J.push(m$(1,Buffer.from([255])));return J.push(PE(A)),v$(...J)}function ST($){let w=[];if(w.push(dZ(0,dU(2))),w.push(dU($.serialNumber)),w.push(iE(X$.SHA256_WITH_RSA)),w.push(lZ($.issuer)),w.push(NT($.notBefore,$.notAfter)),w.push(lZ($.subject)),w.push(KT($.publicKey)),$.extensions){let A=[];if($.extensions.basicConstraints)A.push(j1(X$.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,IT($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)A.push(j1(X$.KEY_USAGE,$.extensions.keyUsage.critical??!0,LT($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)A.push(j1(X$.EXTENDED_KEY_USAGE,!1,CT($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)A.push(j1(X$.SUBJECT_ALT_NAME,!1,yT($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)A.push(j1(X$.SUBJECT_KEY_IDENTIFIER,!1,PE($.extensions.subjectKeyIdentifier)));if(A.length>0)w.push(dZ(3,v$(...A)))}return v$(...w)}function DT($,w){let A=vw.createSign("SHA256");A.update($);let J=A.sign(w);return v$($,iE(X$.SHA256_WITH_RSA),xE(J))}function VT($,w){let A=$.toString("base64"),J=[];for(let h=0;h<A.length;h+=64)J.push(A.slice(h,h+64));return`-----BEGIN ${w}-----
209
+ ${J.join(`
210
+ `)}
211
+ -----END ${w}-----
212
+ `}function hY(){return vw.randomBytes(20)}function bE($=2048){let{privateKey:w,publicKey:A}=vw.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:A}}function OT($){let w=$.export({type:"spki",format:"der"});return vw.createHash("sha1").update(w).digest()}function cE($){let w={serialNumber:$.serialNumber||hY(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:OT($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let A=ST(w),J=DT(A,$.signingKey);return{certificate:VT(J,"CERTIFICATE"),certificateDer:J}}function nE($){return $.export({type:"pkcs8",format:"pem"})}function _T($){return vw.createPrivateKey($)}function XT($){let w=new vw.X509Certificate($),A=w.publicKey,J=[],h=w.subject.split(`
213
+ `);for(let U of h){let[Y,...Z]=U.split("="),f=Z.join("=");if(Y&&f)J.push({shortName:Y.trim(),value:f.trim()})}return{publicKey:A,subject:J}}async function UY($={}){M("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||f0.DEFAULT_KEY_SIZE;M("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:J}=bE(w),h=[{shortName:"C",value:$.countryName||A$.countryName},{shortName:"ST",value:$.stateName||A$.stateName},{shortName:"L",value:$.localityName||A$.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:U,notAfter:Y}=JY({validityYears:$.validityYears||f0.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:Z}=cE({serialNumber:hY(),notBefore:U,notAfter:Y,subject:h,publicKey:J,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:Z,privateKey:nE(A),notBefore:U,notAfter:Y}}async function YY($){if(M("ca","Generating new certificate",$.verbose),M("ca",`Options: ${jJ($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=XT($.rootCA.certificate),A=_T($.rootCA.privateKey);M("ca",`Generating ${f0.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let J=f0.DEFAULT_KEY_SIZE,{privateKey:h,publicKey:U}=bE(J),Y=$.commonName||kE($),Z=$.certificateAttributes||[{shortName:"C",value:$.countryName||A$.countryName},{shortName:"ST",value:$.stateName||A$.stateName},{shortName:"L",value:$.localityName||A$.localityName},{shortName:"O",value:$.organizationName||A$.organizationName},{shortName:"CN",value:Y}],{notBefore:f,notAfter:E}=JY({validityDays:$.validityDays||f0.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),W=QE($),F=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},j=$.extKeyUsage||{serverAuth:!0},{certificate:B}=cE({serialNumber:hY(),notBefore:f,notAfter:E,subject:Z,issuer:w,publicKey:U,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:F,extendedKeyUsage:j,subjectAltName:W});return{certificate:B,privateKey:nE(h),notBefore:f,notAfter:E}}function uE($,w){M(I.STORAGE,`Storing certificate and private key with options: ${jJ(w)}`,w?.verbose);let{certPath:A,keyPath:J}=AY({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});M(I.STORAGE,`Certificate path: ${A}`,w?.verbose),M(I.STORAGE,`Private key path: ${J}`,w?.verbose);let h=gU.dirname(A);if(!O0.existsSync(h))M(I.STORAGE,`Creating certificate directory: ${h}`,w?.verbose),O0.mkdirSync(h,{recursive:!0});M(I.STORAGE,"Writing certificate file",w?.verbose),O0.writeFileSync(A,$.certificate);let U=gU.dirname(J);if(!O0.existsSync(U))M(I.STORAGE,`Creating private key directory: ${U}`,w?.verbose),O0.mkdirSync(U,{recursive:!0});return M(I.STORAGE,"Writing private key file",w?.verbose),O0.writeFileSync(J,$.privateKey),M(I.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function vE($,w){M(I.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=AY({basePath:w?.basePath,caCertPath:w?.caCertPath});M(I.STORAGE,`CA certificate path: ${A}`,w?.verbose);let J=gU.dirname(A);if(!O0.existsSync(J))M(I.STORAGE,`Creating CA certificate directory: ${J}`,w?.verbose),O0.mkdirSync(J,{recursive:!0});return M(I.STORAGE,"Writing CA certificate file",w?.verbose),O0.writeFileSync(A,$),M(I.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function kT($,w){if(ZJ.platform()!=="darwin")return!1;try{let A=tZ(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return M(I.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(tZ("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return M(I.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return M(I.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return M(I.TRUST,`Error checking certificate trust: ${A}`,w),!1}}var QT={platform:"darwin",async addCertificate($,w){if(await kT($,w?.verbose)){M(I.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),cw.success("Certificate is already trusted in system keychain");return}M(I.TRUST,"Adding certificate to macOS keychain",w?.verbose),await d0(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let J=A||A$.commonName;M(I.TRUST,`Removing certificate ${J} from macOS keychain`,w?.verbose);try{await d0(`sudo security delete-certificate -c "${J}" /Library/Keychains/System.keychain`),M(I.TRUST,`Removed certificate ${J} from macOS keychain`,w?.verbose)}catch(h){throw M(I.TRUST,`Error removing certificate: ${h}`,w?.verbose),h}}},xT={platform:"win32",async addCertificate($,w){M(I.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await d0(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let J=A||A$.commonName;M(I.TRUST,`Removing certificate ${J} from Windows certificate store`,w?.verbose);try{await d0(`certutil -delstore -enterprise Root "${J}"`),M(I.TRUST,`Removed certificate ${J} from Windows certificate store`,w?.verbose)}catch(h){throw M(I.TRUST,`Error removing certificate: ${h}`,w?.verbose),h}}},PT={platform:"linux",async addCertificate($,w){M(I.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=ZJ.homedir(),J=f0.LINUX_CERT_DB_FILENAME,h=f0.LINUX_TRUST_ARGS;M(I.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let U=mU(A,J);if(U.length===0){cw.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let Y of U){M(I.TRUST,`Processing certificate database in ${Y}`,w?.verbose);try{M(I.TRUST,`Attempting to delete existing cert for ${A$.commonName}`,w?.verbose),await d0(`certutil -d sql:${Y} -D -n ${A$.commonName}`)}catch(Z){M(I.TRUST,`Warning: Error deleting existing cert: ${Z}`,w?.verbose),console.warn(`Error deleting existing cert: ${Z}`)}M(I.TRUST,`Adding new certificate to ${Y}`,w?.verbose),await d0(`certutil -d sql:${Y} -A -t ${h} -n ${A$.commonName} -i ${$}`),cw.info(`Cert added to ${Y}`)}},async removeCertificate($,w,A){let J=A||A$.commonName;M(I.TRUST,`Removing certificate ${J} from Linux certificate store`,w?.verbose);let h=ZJ.homedir(),U=f0.LINUX_CERT_DB_FILENAME;M(I.TRUST,`Searching for certificate databases in ${h}`,w?.verbose);let Y=mU(h,U);if(Y.length===0){cw.warn("No certificate databases found. Cannot remove certificate.");return}for(let Z of Y){M(I.TRUST,`Processing certificate database in ${Z}`,w?.verbose);try{await d0(`certutil -d sql:${Z} -D -n "${J}"`),cw.info(`Cert removed from ${Z}`)}catch(f){M(I.TRUST,`Error removing cert from ${Z}: ${f}`,w?.verbose),console.warn(`Error removing cert from ${Z}: ${f}`)}}}},iT={darwin:QT,win32:xT,linux:PT};async function fY($,w,A){M(I.TRUST,`Adding certificate to system trust store with options: ${jJ(A)}`,A?.verbose),M(I.TRUST,"Storing certificate and private key",A?.verbose);let J=uE($,A);M(I.TRUST,"Storing CA certificate",A?.verbose);let h=vE(w,A),U=ZJ.platform();M(I.TRUST,`Detected platform: ${U}`,A?.verbose);let Y=iT[U];if(!Y){let Z=`Unsupported platform: ${U}`;throw M(I.TRUST,`Error: ${Z}`,A?.verbose),Error(Z)}return await Y.addCertificate(h,A),M(I.TRUST,"Certificate successfully added to system trust store",A?.verbose),J}import{homedir as ZY}from"node:os";import{join as EY,resolve as pN}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",bT={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:EY(ZY(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:EY(ZY(),".stacks","ssl","stacks.localhost.crt"),keyPath:EY(ZY(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var WY=bT;T$();var hw=null,v2="rpx-root-ca.crt",m2="rpx-root-ca.key";function d2($){return{caCertPath:x$($,v2),caKeyPath:x$($,m2)}}async function g2($,w){try{let[A,J]=await Promise.all([B$.readFile($.caCertPath,"utf8"),B$.readFile($.caKeyPath,"utf8")]);if(!A.includes("-----BEGIN CERTIFICATE-----")||!J.includes("PRIVATE KEY-----"))return z("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:A,privateKey:J}}catch(A){return z("ssl",`No existing Root CA at ${$.caCertPath} (${A.code||A}), will create one`,w),null}}function oW($){let w=new Set;w.add($);let A=$.split(".");if(A.length>=2)w.add(`*.${A.slice(1).join(".")}`);return Array.from(w)}function $F($){let A=dJ($).replace(/\*/g,"wildcard"),J=x$(eY(),".stacks","ssl"),h=J;if(typeof $?.https==="object")return h=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:J,{caCertPath:$.https.caCertPath||x$(h,`${A}.ca.crt`),certPath:$.https.certPath||x$(h,`${A}.crt`),keyPath:$.https.keyPath||x$(h,`${A}.key`)};return{caCertPath:x$(h,`${A}.ca.crt`),certPath:x$(h,`${A}.crt`),keyPath:x$(h,`${A}.key`)}}function eW($){let w=new Set;if(Aw($))$.proxies.forEach((A)=>{let J=A.to||"rpx.localhost";oW(J).forEach((h)=>w.add(h))});else if(C1($)){let A=$.to||"rpx.localhost";oW(A).forEach((J)=>w.add(J))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function $1($){if(hw){z("ssl","Using cached SSL configuration",$.verbose);return}let w=Aw($)?$.proxies.map((W)=>W.to):[$.to];z("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let A=S1($,$.verbose),J=A.basePath||x$(eY(),".stacks","ssl");await B$.mkdir(J,{recursive:!0});let h=d2(J),U=await g2(h,$.verbose),Y=!1;if(!U){if($.verbose)N.info("Generating Root CA certificate (one-time)...");U=await UY(A);try{await Promise.all([B$.writeFile(h.caCertPath,U.certificate),B$.writeFile(h.caKeyPath,U.privateKey,{mode:384})]),Y=!0,z("ssl",`Persisted Root CA at ${h.caCertPath}`,$.verbose)}catch(W){throw z("ssl",`Error saving Root CA files: ${W}`,$.verbose),Error(`Failed to save Root CA files: ${W}`)}}else z("ssl",`Reusing existing Root CA from ${h.caCertPath}`,$.verbose);if($.verbose)N.info(`Generating host certificate for: ${w.join(", ")}`);let Z=await YY({...A,rootCA:{certificate:U.certificate,privateKey:U.privateKey}});try{await Promise.all([B$.writeFile(A.certPath,Z.certificate),B$.writeFile(A.keyPath,Z.privateKey),B$.writeFile(A.caCertPath,U.certificate)]),z("ssl","Certificate files saved successfully",$.verbose)}catch(W){throw z("ssl",`Error saving certificate files: ${W}`,$.verbose),Error(`Failed to save certificate files: ${W}`)}if(Y?!1:await AF(h.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(z("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)N.success("Root CA is already trusted in system trust store");if(hw={key:Z.privateKey,cert:Z.certificate,ca:U.certificate},$.verbose)N.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)N.info("Adding certificate to system trust store (may require sudo permission)...");let E=!1;if(p0.platform==="darwin")try{if(pY(`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${h.caCertPath}"`),$.verbose)N.success("Successfully added Root CA to system trust store");E=!0;let W=x$(J,"trust-rpx-cert.sh"),F=`#!/bin/bash
214
+ echo "Trusting RPX Root CA"
215
+ sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${h.caCertPath}"
216
+ echo "Root CA trusted! Please restart your browser."
217
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
218
+ `;await B$.writeFile(W,F,{mode:493})}catch(W){if($.verbose)N.warn(`Could not add Root CA to trust store automatically: ${W}`);let F=x$(J,"trust-rpx-cert.sh"),j=`#!/bin/bash
219
+ echo "Trusting RPX Root CA"
220
+ sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${h.caCertPath}"
221
+ echo "Root CA trusted! Please restart your browser."
222
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
223
+ `;if(await B$.writeFile(F,j,{mode:493}),$.verbose)N.info(`Created a trust helper script at: ${F}`),N.info(`If you're still having certificate issues, run: sh ${F}`)}else if(p0.platform==="linux")try{let{exec:W}=await import("node:child_process"),F="/usr/local/share/ca-certificates/rpx",j=`
224
+ mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
225
+ cp "${h.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
226
+ update-ca-certificates
227
+ echo "RPX Root CA installed. Please restart your browser."
228
+ `,B=x$(oY.tmpdir(),`rpx-trust-${Date.now()}.sh`);await B$.writeFile(B,j,{mode:493}),await new Promise((T)=>{W(`sudo bash "${B}"`,(H)=>{if(H){if($.verbose)N.warn(`Could not trust certificates: ${H}`);T(!1)}else{if($.verbose)N.success("Successfully added certificates to system trust store");T(!0)}})}),await B$.unlink(B).catch(()=>{}),E=!0}catch(W){if($.verbose)N.warn(`Failed to trust certificates: ${W}`)}else if(p0.platform==="win32")try{let W=`
229
+ $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${h.caCertPath.replace(/\//g,"\\")}")
230
+ $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
231
+ $store.Open("ReadWrite")
232
+ $store.Add($cert)
233
+ $store.Close()
234
+ Write-Host "Root CA trusted successfully!"
235
+ `,F=x$(oY.tmpdir(),"rpx-trust.ps1");if(await B$.writeFile(F,W),Jw(`powershell -ExecutionPolicy Bypass -File "${F}"`),$.verbose)N.success("Successfully added certificate to Windows trust store");E=!0}catch(W){if($.verbose)N.warn(`Could not trust certificate: ${W}`)}else try{await fY(Z,U.certificate,A),E=!0}catch(W){if($.verbose)N.warn(`Could not add certificate to trust store: ${W}`)}if(hw={key:Z.privateKey,cert:Z.certificate,ca:U.certificate},$.verbose)N.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!E&&$.verbose)N.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),N.warn("This will bypass the warning and you should only need to do it once")}async function b0($){if(!$)return null;if(hw)return hw;let w=S1($);try{let[A,J,h]=await Promise.all([B$.access(w.keyPath).then(()=>!0).catch(()=>!1),B$.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?B$.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!A||!J)return z("ssl",`Certificate files don't exist: key=${A}, cert=${J}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let U="regenerateUntrustedCerts"in $,Y=$.regenerateUntrustedCerts,Z=U?Y!==!1:!0;if(z("ssl",`Trust check: hasFlag=${U}, flagValue=${Y}, shouldCheckTrust=${Z}`,$.verbose),!(Z?await AF(w.certPath,$):!0))return z("ssl","Certificate exists but is not trusted, will regenerate",$.verbose),null;let[E,W,F]=await Promise.all([B$.readFile(w.keyPath,"utf8"),B$.readFile(w.certPath,"utf8"),h&&w.caCertPath?B$.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return z("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(Aw($))try{let{X509Certificate:j}=await import("node:crypto"),T=new j(W).subjectAltName||"",q=$.proxies.map((G)=>G.to).filter((G)=>!T.includes(`DNS:${G}`));if(q.length>0)return z("ssl",`Certificate missing SANs for: ${q.join(", ")}, will regenerate`,$.verbose),null}catch(j){z("ssl",`Could not verify cert SANs: ${j}`,$.verbose)}return z("ssl","Successfully loaded existing certificates",$.verbose),hw={key:E,cert:W,ca:F},hw}catch(A){return z("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function S1($,w){let A=dJ($);z("ssl",`Primary domain: ${A}`,w);let J=$F($),h=x$(eY(),".stacks","ssl");if(typeof $.https==="object"){let U=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:h,Y={domain:A,hostCertCN:A,basePath:U,caCertPath:$.https.caCertPath||J.caCertPath,certPath:$.https.certPath||J.certPath,keyPath:$.https.keyPath||J.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||A,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(eW($)).map((Z)=>({type:2,value:Z}))};if(rY($.https.rootCA))Y.rootCA=$.https.rootCA;return Y}return{domain:A,hostCertCN:A,basePath:h,...J,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:A,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:w||!1,subjectAltNames:Array.from(eW($)).map((U)=>({type:2,value:U}))}}async function wF($,w){let A=$F({to:$,verbose:w}),J=[A.caCertPath,A.certPath,A.keyPath];z("certificates","Attempting to clean up relating certificates",w),await Promise.all(J.map((h)=>sY(h,w)))}async function AF($,w){try{if(z("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),p0.platform==="darwin")try{let J=Jw(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!J)return z("ssl","Could not extract certificate fingerprint",w?.verbose),!1;if(Jw("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256").toString().includes(J))return z("ssl","Certificate fingerprint found in system keychain",w?.verbose),!0;return z("ssl","Certificate fingerprint not found in system keychain",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust: ${A}`,w?.verbose),!1}else if(p0.platform==="win32")try{let J=Jw(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!J)return z("ssl","Could not extract certificate subject",w?.verbose),!1;let h=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${J}*' } | Select-Object Subject"`;if(Jw(h).toString().includes(J))return z("ssl","Certificate found in trusted root store",w?.verbose),!0;return z("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Windows: ${A}`,w?.verbose),!1}else if(p0.platform==="linux")try{let J=Jw(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"",h=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let U of h)try{if(Jw(`find ${U} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${J}"`).toString().includes(J))return z("ssl",`Certificate fingerprint found in ${U}`,w?.verbose),!0}catch{}return z("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Linux: ${A}`,w?.verbose),!1}return z("ssl",`Platform ${p0.platform} not supported for certificate trust check`,w?.verbose),!1}catch(A){return z("ssl",`Error checking if certificate is trusted: ${A}`,w?.verbose),!1}}T$();T$();function D1($,w){return async(A)=>{let J=new URL(A.url),U=(A.headers.get("host")||"").split(":")[0],Y=$(U);if(!Y)return z("request",`No route found for host: ${U}`,w),new Response(`No proxy configured for ${U}`,{status:404});let Z=Y.sourceHost,f=J.pathname,E=aY(J.pathname,Y.pathRewrites);if(E)Z=E.targetHost,f=E.targetPath,z("request",`Path rewrite: ${J.pathname} → ${Z}${f}`,w);let W=`http://${Z}${f}${J.search}`;try{let F=new Headers(A.headers);if(F.set("host",Z),Y.changeOrigin)F.set("origin",`http://${Y.sourceHost}`);F.set("x-forwarded-for","127.0.0.1"),F.set("x-forwarded-proto","https"),F.set("x-forwarded-host",U);let j=await fetch(W,{method:A.method,headers:F,body:A.body,redirect:"manual"});if(Y.cleanUrls&&J.pathname.endsWith(".html")){let T=J.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:T}})}let B=new Headers(j.headers);return new Response(j.body,{status:j.status,statusText:j.statusText,headers:B})}catch(F){return z("request",`Proxy error for ${U}: ${F}`,w),new Response(`Proxy Error: ${F}`,{status:502})}}}T$();import*as lJ from"node:fs";import*as P$ from"node:fs/promises";import{homedir as l2}from"node:os";import*as $8 from"node:path";import*as tJ from"node:process";var t2=/^[a-zA-Z0-9._-]+$/;function r0(){return $8.join(l2(),".stacks","rpx","registry.d")}function V1($){return typeof $==="string"&&$.length>0&&$.length<=128&&t2.test($)}function w8($,w){if(!V1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return $8.join($,`${w}.json`)}function F0($){if(!Number.isInteger($)||$<=0)return!1;try{return tJ.kill($,0),!0}catch(w){return w.code==="EPERM"}}function JF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0;return typeof w.id==="string"&&V1(w.id)&&typeof w.from==="string"&&w.from.length>0&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function p2($){await P$.mkdir($,{recursive:!0})}async function hF($,w=r0(),A){if(!JF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await p2(w);let J=w8(w,$.id),h=`${J}.tmp.${tJ.pid}.${Date.now()}`,U=JSON.stringify($,null,2);try{await P$.writeFile(h,U,{encoding:"utf8",mode:420}),await P$.rename(h,J),z("registry",`wrote entry ${$.id} → ${J}`,A)}catch(Y){throw await P$.unlink(h).catch(()=>{}),Y}}async function A8($,w=r0(),A){let J=w8(w,$);try{await P$.unlink(J),z("registry",`removed entry ${$}`,A)}catch(h){if(h.code!=="ENOENT")throw h}}async function r2($,w=r0(),A){let J=w8(w,$);try{let h=await P$.readFile(J,"utf8"),U=JSON.parse(h);if(!JF(U))return z("registry",`entry ${$} failed validation, removing`,A),await P$.unlink(J).catch(()=>{}),null;return U}catch(h){if(h.code==="ENOENT")return null;if(h instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await P$.unlink(J).catch(()=>{}),null;throw h}}async function w1($=r0(),w){let A;try{A=await P$.readdir($)}catch(h){if(h.code==="ENOENT")return[];throw h}let J=[];for(let h of A){if(!h.endsWith(".json"))continue;let U=h.slice(0,-5);if(!V1(U))continue;let Y=await r2(U,$,w);if(Y)J.push(Y)}return J}async function pJ($=r0(),w){let A=await w1($,w),J=0;for(let h of A){if(h.pid===void 0)continue;if(!F0(h.pid))z("registry",`GC: pid ${h.pid} for ${h.id} is dead, removing`,w),await A8(h.id,$,w).catch(()=>{}),J++}return J}function J8($,w={}){let A=w.dir??r0(),J=w.debounceMs??100,h=w.pollMs??Math.max(J*2,250),U=w.verbose;lJ.mkdirSync(A,{recursive:!0});let Y=null,Z=!1,f=null,E=!1,W=(q)=>{return JSON.stringify(q.map((G)=>({id:G.id,from:G.from,to:G.to,pid:G.pid,pathRewrites:G.pathRewrites,cleanUrls:G.cleanUrls,changeOrigin:G.changeOrigin})).sort((G,R)=>G.id.localeCompare(R.id)))},F=()=>{if(Y=null,Z)return;w1(A,U).then((q)=>{return f=W(q),$(q)}).catch((q)=>{z("registry",`watcher onChange failed: ${q}`,U)})},j=()=>{if(Z)return;if(Y)clearTimeout(Y);Y=setTimeout(F,J)},T=setInterval(()=>{if(Z||E)return;E=!0,w1(A,U).then((q)=>{if(W(q)!==f)j()}).catch((q)=>{z("registry",`watcher poll failed: ${q}`,U)}).finally(()=>{E=!1})},h),H=lJ.watch(A,{persistent:!0},(q,G)=>{if(G&&/\.tmp\.\d+\.\d+$/.test(G))return;j()});return H.on("error",(q)=>{z("registry",`watcher error: ${q}`,U)}),j(),{close:()=>{if(Z=!0,Y)clearTimeout(Y);clearInterval(T),H.close()}}}T$();var o2=5000;function j0(){return A1.join(s2(),".stacks","rpx")}function Yw($=j0()){return A1.join($,"daemon.pid")}async function Uw($=j0()){try{let w=await B0.readFile(Yw($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function UF($=j0()){let w=await Uw($);return w!==null&&F0(w)}async function e2($=j0()){await B0.mkdir($,{recursive:!0});let w=Yw($);while(!0){try{let J=await B0.open(w,"wx");try{await J.write(`${G$.pid}
236
+ `)}finally{await J.close()}return w}catch(J){if(J.code!=="EEXIST")throw J}let A=await Uw($);if(A!==null&&F0(A))throw Error(`rpx daemon already running (pid=${A})`);await B0.unlink(w).catch(()=>{})}}async function O1($=j0()){await B0.unlink(Yw($)).catch(()=>{})}function $7($){return{sourceHost:new URL($.from.startsWith("http")?$.from:`http://${$.from}`).host,cleanUrls:$.cleanUrls??!1,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites}}async function w7($){let w={https:$.https??!0,to:"rpx.localhost",verbose:$.verbose,regenerateUntrustedCerts:!0},A=await b0(w);if(!A)z("daemon","no usable cert on disk, generating one",$.verbose),await $1(w),A=await b0(w);if(!A)throw Error("failed to bootstrap TLS for rpx daemon");return A}async function YF($={}){let w=$.verbose??!1,A=$.rpxDir??j0(),J=$.registryDir??A1.join(A,"registry.d"),h=$.httpsPort??443,U=$.httpPort??80,Y=$.hostname??"0.0.0.0",Z=$.gcIntervalMs??o2,f=await e2(A),E=new Map,W=(K)=>E.get(K);function F(K){let S$=new Map;for(let c$ of K)S$.set(c$.to,$7(c$));E=S$,z("daemon",`routing table now covers ${S$.size} host(s): ${Array.from(S$.keys()).join(", ")||"<empty>"}`,w)}await pJ(J,w).catch((K)=>{z("daemon",`initial gc failed: ${K}`,w)}),F(await w1(J,w));let j=await w7($),B=Bun.serve({port:h,hostname:Y,tls:{key:j.key,cert:j.cert,ca:j.ca,requestCert:!1,rejectUnauthorized:!1},fetch:D1(W,w),error(K){return z("daemon",`https server error: ${K}`,w),new Response(`Server Error: ${K.message}`,{status:500})}}),T=null;if(U>0)T=Bun.serve({port:U,hostname:Y,fetch(K){let S$=new URL(K.url),c$=(K.headers.get("host")??S$.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${c$}${S$.pathname}${S$.search}`}})}});if(w)N.success(`rpx daemon listening on https://${Y}:${h}${T?` (http→https on :${U})`:""}`),N.info(`pid file: ${f}`),N.info(`registry: ${J}`);let H=J8((K)=>{F(K)},{dir:J,verbose:w}),q=setInterval(()=>{pJ(J,w).then((K)=>{if(K>0)z("daemon",`gc reaped ${K} stale entries`,w)}).catch((K)=>{z("daemon",`periodic gc failed: ${K}`,w)})},Z);if(typeof q.unref==="function")q.unref();let G=!1,R,y=new Promise((K)=>{R=K});async function L(){if(G)return y;if(G=!0,clearInterval(q),H.close(),B.stop(!1),T?.stop(!1),await O1(A),w)N.info("rpx daemon stopped");return R(),y}let C=(K)=>{z("daemon",`received ${K}, shutting down`,w),L().catch(()=>{})};return G$.once("SIGINT",C),G$.once("SIGTERM",C),{stop:L,done:y,httpsPort:typeof B.port==="number"?B.port:h,httpPort:T&&typeof T.port==="number"?T.port:U,pidPath:f}}function A7(){let $=G$.execPath,w=A1.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&G$.argv[1])return[$,G$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function fF($={}){let w=$.rpxDir??j0(),A=$.verbose??!1,J=await Uw(w);if(J!==null&&F0(J))return z("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await O1(w);await B0.mkdir(w,{recursive:!0});let h=$.spawnCommand??A7();if(h.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${h.join(" ")}`,A);let U=a2(h[0],h.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??G$.cwd(),env:$.spawnEnv?{...G$.env,...$.spawnEnv}:G$.env});U.unref();let Y=null;U.once("error",(W)=>{Y=W});let Z=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,E=Date.now()+Z;while(Date.now()<E){if(Y)throw Y;let W=await Uw(w);if(W!==null&&F0(W))return z("daemon",`daemon registered with pid=${W}`,A),{pid:W,spawned:!0};await new Promise((F)=>setTimeout(F,f))}if(Y)throw Y;throw Error(`rpx daemon failed to start within ${Z}ms (rpxDir=${w})`)}async function ZF($={}){let w=$.rpxDir??j0(),A=$.verbose??!1,J=$.timeoutMs??5000,h=$.pollIntervalMs??50,U=$.forceAfterTimeout??!0,Y=await Uw(w);if(Y===null||!F0(Y)){if(Y!==null)await O1(w);return{stopped:!1,pid:Y,forced:!1}}try{G$.kill(Y,"SIGTERM")}catch(f){if(f.code==="ESRCH")return await O1(w),{stopped:!1,pid:Y,forced:!1};throw f}let Z=Date.now()+J;while(Date.now()<Z){if(!F0(Y))return z("daemon",`daemon pid=${Y} stopped cleanly`,A),{stopped:!0,pid:Y,forced:!1};await new Promise((f)=>setTimeout(f,h))}if(!U)throw Error(`rpx daemon (pid=${Y}) did not exit within ${J}ms`);z("daemon",`daemon pid=${Y} did not exit, escalating to SIGKILL`,A);try{G$.kill(Y,"SIGKILL")}catch(f){if(f.code!=="ESRCH")throw f}return await O1(w),{stopped:!0,pid:Y,forced:!0}}import{spawn as J7}from"node:child_process";import*as fw from"node:process";T$();class EF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[J,...h]=w.command.split(" "),U=w.cwd||fw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${J} ${h.join(" ")}`,A),z("start",` Working directory: ${U}`,A),z("start",` Environment variables: ${w0(w.env)}`,A);let Y=J7(J,h,{cwd:U,env:{...fw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:U,process:Y,env:w.env}),new Promise((Z,f)=>{if(Y.on("error",(E)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${E}`,A),this.processes.delete($),f(E),fw.emit("SIGINT")}),Y.on("exit",(E)=>{if(!this.isShuttingDown&&E!==null&&E!==0)z("start",`Process ${$} exited with code ${E}`,A),this.processes.delete($),f(Error(`Process ${$} exited with code ${E}`)),fw.emit("SIGINT")}),A)Y.stdout?.on("data",(E)=>{z("process",`[${$}] ${E.toString().trim()}`,!0)}),Y.stderr?.on("data",(E)=>{z("process",`[${$}] ERR: ${E.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&Y.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),Z()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(h){}}},3000)}catch(h){z("start",`Error stopping process ${$}: ${h}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((J)=>{N.error(`Failed to stop process ${A}:`,J)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var rJ=new EF;T$();import*as i$ from"node:fs/promises";import{homedir as h7}from"node:os";import*as h8 from"node:path";import*as U8 from"node:process";var U7=/^[a-zA-Z0-9._-]+$/;function Zw(){return h8.join(h7(),".stacks","rpx","registry.d")}function J1($){return typeof $==="string"&&$.length>0&&$.length<=128&&U7.test($)}function Y8($,w){if(!J1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return h8.join($,`${w}.json`)}function WF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0;return typeof w.id==="string"&&J1(w.id)&&typeof w.from==="string"&&w.from.length>0&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function Y7($){await i$.mkdir($,{recursive:!0})}async function FF($,w=Zw(),A){if(!WF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await Y7(w);let J=Y8(w,$.id),h=`${J}.tmp.${U8.pid}.${Date.now()}`,U=JSON.stringify($,null,2);try{await i$.writeFile(h,U,{encoding:"utf8",mode:420}),await i$.rename(h,J),z("registry",`wrote entry ${$.id} → ${J}`,A)}catch(Y){throw await i$.unlink(h).catch(()=>{}),Y}}async function BF($,w=Zw(),A){let J=Y8(w,$);try{await i$.unlink(J),z("registry",`removed entry ${$}`,A)}catch(h){if(h.code!=="ENOENT")throw h}}async function f8($,w=Zw(),A){let J=Y8(w,$);try{let h=await i$.readFile(J,"utf8"),U=JSON.parse(h);if(!WF(U))return z("registry",`entry ${$} failed validation, removing`,A),await i$.unlink(J).catch(()=>{}),null;return U}catch(h){if(h.code==="ENOENT")return null;if(h instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await i$.unlink(J).catch(()=>{}),null;throw h}}async function jF($=Zw(),w){let A;try{A=await i$.readdir($)}catch(h){if(h.code==="ENOENT")return[];throw h}let J=[];for(let h of A){if(!h.endsWith(".json"))continue;let U=h.slice(0,-5);if(!J1(U))continue;let Y=await f8(U,$,w);if(Y)J.push(Y)}return J}import{execSync as D7}from"node:child_process";import*as jw from"node:http";import*as CF from"node:http2";import*as SF from"node:net";import*as s from"node:process";var aJ=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,z0={bold:aJ(1,22),dim:aJ(2,22),green:aJ(32,39),cyan:aJ(36,39)};import*as GF from"node:fs";import*as qF from"node:path";import*as H0 from"node:process";import{spawn as f7}from"node:child_process";import*as Ew from"node:fs/promises";import{homedir as Z7}from"node:os";import*as _1 from"node:path";import*as g$ from"node:process";T$();function sJ(){return _1.join(Z7(),".stacks","rpx")}function HF($=sJ()){return _1.join($,"daemon.pid")}async function zF($=sJ()){try{let w=await Ew.readFile(HF($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function E7($=sJ()){await Ew.unlink(HF($)).catch(()=>{})}function W7(){let $=g$.execPath,w=_1.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&g$.argv[1])return[$,g$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function TF($={}){let w=$.rpxDir??sJ(),A=$.verbose??!1,J=await zF(w);if(J!==null&&F0(J))return z("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await E7(w);await Ew.mkdir(w,{recursive:!0});let h=$.spawnCommand??W7();if(h.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${h.join(" ")}`,A);let U=f7(h[0],h.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??g$.cwd(),env:$.spawnEnv?{...g$.env,...$.spawnEnv}:g$.env});U.unref();let Y=null;U.once("error",(W)=>{Y=W});let Z=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,E=Date.now()+Z;while(Date.now()<E){if(Y)throw Y;let W=await zF(w);if(W!==null&&F0(W))return z("daemon",`daemon registered with pid=${W}`,A),{pid:W,spawned:!0};await new Promise((F)=>setTimeout(F,f))}if(Y)throw Y;throw Error(`rpx daemon failed to start within ${Z}ms (rpxDir=${w})`)}T$();function F7($){let w=$.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function Z8($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,J=new Set,h=$.proxies.map((F)=>{let j=F.id??F7(F.to);if(!V1(j))throw Error(`invalid registry id "${j}" derived from to="${F.to}"`);if(J.has(j))throw Error(`duplicate registry id "${j}" — set an explicit \`id\` on one of the proxies`);return J.add(j),{...F,id:j}});for(let F of h)await hF({id:F.id,from:F.from,to:F.to,pid:H0.pid,cwd:H0.cwd(),createdAt:new Date().toISOString(),cleanUrls:F.cleanUrls,changeOrigin:F.changeOrigin,pathRewrites:F.pathRewrites},A,w);let U=await TF({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand});for(let F of h)N.success(`https://${F.to} → ${F.from}`);if(N.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let Y=!1,Z=A??r0(),f=h.map((F)=>F.id),E=async()=>{if(Y)return;Y=!0;for(let F of f)await A8(F,A,w).catch((j)=>{z("runner",`removeEntry(${F}) failed: ${j}`,w)})},W=(F)=>{z("runner",`received ${F}, unregistering ${f.length} entries`,w),E().finally(()=>H0.exit(0))};H0.once("SIGINT",W),H0.once("SIGTERM",W),H0.once("exit",()=>{if(Y)return;for(let F of f)try{GF.unlinkSync(qF.join(Z,`${F}.json`))}catch{}}),await new Promise(()=>{})}T$();import{exec as B7}from"node:child_process";import Ww from"node:fs";import RF from"node:os";import W8 from"node:path";import*as X1 from"node:process";import{promisify as j7}from"node:util";var oJ=j7(B7),A0=X1.platform==="win32"?W8.join(X1.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",E8=!1;async function eJ($){if(X1.platform==="win32")throw Error("Administrator privileges required on Windows");let w=ww(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:h}=await oJ(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return E8=!0,h}if(E8)try{let{stdout:h}=await oJ(`sudo -n sh -c '${A}'`);return h}catch(h){z("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:J}=await oJ(`sudo sh -c '${A}'`);return E8=!0,J}catch(J){throw Error(`Failed to execute sudo command: ${J.message}`)}}async function k1($,w){z("hosts",`Adding hosts: ${$.join(", ")}`,w),z("hosts",`Using hosts file at: ${A0}`,w);try{let A;try{A=await Ww.promises.readFile(A0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await eJ(`cat "${A0}"`)}catch(Y){throw console.log(" Could not read hosts file — skipping hosts setup"),z("hosts",`sudo read also failed: ${Y}`,w),Error(`Cannot read hosts file: ${Y}`)}}let J=$.filter((Y)=>{let Z=`127.0.0.1 ${Y}`,f=`::1 ${Y}`;return!A.includes(Z)&&!A.includes(f)});if(J.length===0){z("hosts","All hosts already exist in hosts file",w);return}let h=J.map((Y)=>`
237
+ # Added by rpx
238
+ 127.0.0.1 ${Y}
239
+ ::1 ${Y}`).join(`
240
+ `),U=W8.join(RF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Ww.promises.writeFile(U,A+h,"utf8"),await eJ(`cat "${U}" | tee "${A0}" > /dev/null`),console.log(` Hosts updated: ${J.join(", ")}`)}catch(Y){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),J.forEach((Z)=>{console.log(` 127.0.0.1 ${Z}`),console.log(` ::1 ${Z}`)}),console.log(` Or run: sudo nano ${A0}`)}finally{try{await Ww.promises.unlink(U)}catch{}}}catch(A){z("hosts",`Failed to manage hosts file: ${A.message}`,w)}}async function NF($,w){z("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let A;try{A=await Ww.promises.readFile(A0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await eJ(`cat "${A0}"`)}catch(f){throw z("hosts",`sudo read also failed: ${f}`,w),Error(`Cannot read hosts file: ${f}`)}}let J=A.split(`
241
+ `),h=!1,U=J.filter((f)=>{if($.some((W)=>f.includes(` ${W}`)&&(f.includes("127.0.0.1")||f.includes("::1"))))return h=!0,!1;if(f.trim()==="# Added by rpx")return h=!0,!1;return!0});if(!h){z("hosts","No matching hosts found to remove",w);return}while(U[U.length-1]?.trim()==="")U.pop();let Y=`${U.join(`
242
+ `)}
243
+ `,Z=W8.join(RF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Ww.promises.writeFile(Z,Y,"utf8"),await eJ(`cat "${Z}" | tee "${A0}" > /dev/null`),z("hosts","Hosts removed successfully",w)}catch(f){z("hosts","Could not clean up hosts file automatically",w)}finally{try{await Ww.promises.unlink(Z)}catch(f){z("hosts",`Failed to remove temporary file: ${f}`,w)}}}catch(A){z("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function Q1($,w){z("hosts",`Checking hosts: ${$}`,w);let A;try{A=await Ww.promises.readFile(A0,"utf-8")}catch(J){z("hosts",`Error reading hosts file: ${J}`,w);try{let h=ww(),U;if(h)U=`echo '${h}' | sudo -S cat "${A0}" 2>/dev/null`;else U=`sudo -n cat "${A0}" 2>/dev/null || cat "${A0}" 2>/dev/null || echo ""`;let{stdout:Y}=await oJ(U);A=Y}catch(h){return z("hosts",`Cannot read hosts file, assuming entries don't exist: ${h}`,w),$.map(()=>!1)}}return $.map((J)=>{let h=`127.0.0.1 ${J}`,U=`::1 ${J}`;return A.includes(h)||A.includes(U)})}T$();import*as $h from"node:net";function Fw($,w,A){return z("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((J)=>{let h=$h.createServer(),U=setTimeout(()=>{z("port",`Checking port ${$} timed out, assuming it's in use`,A),h.close(),J(!0)},3000);h.once("error",(Y)=>{if(clearTimeout(U),Y.code==="EADDRINUSE")z("port",`Port ${$} is in use`,A),J(!0);else z("port",`Error checking port ${$}: ${Y.message}`,A),J(!0)}),h.once("listening",()=>{clearTimeout(U),z("port",`Port ${$} is available`,A),h.close(),J(!1)});try{h.listen($,w)}catch(Y){clearTimeout(U),z("port",`Exception checking port ${$}: ${Y}`,A),J(!0)}})}async function z7($,w,A,J=50){z("port",`Finding available port starting from ${$} (max attempts: ${J})`,A);let h=$,U=0;while(U<J){if(U++,!await Fw(h,w,A))return z("port",`Found available port: ${h} after ${U} attempts`,A),h;z("port",`Port ${h} is in use, trying ${h+1} (attempt ${U}/${J})`,A),h++}throw Error(`Unable to find available port after ${J} attempts starting from ${$}`)}function KF($,w,A=5000,J){return z("port",`Testing connection to ${w}:${$}`,J),new Promise((h)=>{let U=$h.connect({host:w,port:$,timeout:A});U.once("connect",()=>{z("port",`Successfully connected to ${w}:${$}`,J),U.end(),h(!0)}),U.once("timeout",()=>{z("port",`Connection to ${w}:${$} timed out`,J),U.destroy(),h(!1)}),U.once("error",(Y)=>{z("port",`Failed to connect to ${w}:${$}: ${Y.message}`,J),U.destroy(),h(!1)})})}class wh{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,A=50){this.hostname=$,this.verbose=w,this.maxRetries=A}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Fw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await KF($,this.hostname,3000,this.verbose))return z("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let A=await z7($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await KF(A,this.hostname,3000,this.verbose))if(A<$+this.maxRetries)return this.findNextAvailablePort(A+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(A),A}releasePort($){z("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var My=new wh;import{spawn as H7}from"node:child_process";import*as Bw from"node:process";T$();class Ah{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[J,...h]=w.command.split(" "),U=w.cwd||Bw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${J} ${h.join(" ")}`,A),z("start",` Working directory: ${U}`,A),z("start",` Environment variables: ${w0(w.env)}`,A);let Y=H7(J,h,{cwd:U,env:{...Bw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:U,process:Y,env:w.env}),new Promise((Z,f)=>{if(Y.on("error",(E)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${E}`,A),this.processes.delete($),f(E),Bw.emit("SIGINT")}),Y.on("exit",(E)=>{if(!this.isShuttingDown&&E!==null&&E!==0)z("start",`Process ${$} exited with code ${E}`,A),this.processes.delete($),f(Error(`Process ${$} exited with code ${E}`)),Bw.emit("SIGINT")}),A)Y.stdout?.on("data",(E)=>{z("process",`[${$}] ${E.toString().trim()}`,!0)}),Y.stderr?.on("data",(E)=>{z("process",`[${$}] ERR: ${E.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&Y.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),Z()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(h){}}},3000)}catch(h){z("start",`Error stopping process ${$}: ${h}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((J)=>{N.error(`Failed to stop process ${A}:`,J)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var Sy=new Ah;T$();var Zh=new Ah,V7="0.12.0",O7=new wh("0.0.0.0"),x1=new Set,F8=!1,fh=null,B8=null;async function Eh($){if(F8)return z("cleanup","Cleanup already in progress, skipping",$?.verbose),B8||Promise.resolve();F8=!0,z("cleanup","Starting cleanup process",$?.verbose),B8=new Promise((w)=>{fh=w});try{await Zh.stopAll($?.verbose),N.info("Shutting down proxy servers...");let w=[],A=Array.from(x1).map((J)=>new Promise((h)=>{J.close(()=>{z("cleanup","Server closed successfully",$?.verbose),h()})}));if(w.push(...A),$?.hosts&&$.domains?.length){z("cleanup","Cleaning up hosts file entries",$?.verbose),z("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let J=$.domains.filter((h)=>{if(h==="test.local")return!0;return h!=="localhost"&&!h.startsWith("localhost.")&&h!=="127.0.0.1"});if(z("cleanup",`Filtered domains for cleanup: ${JSON.stringify(J)}`,$?.verbose),J.length>0)N.info("Cleaning up hosts file entries..."),w.push(NF(J,$?.verbose).then(()=>{z("cleanup",`Removed hosts entries for ${J.join(", ")}`,$?.verbose)}).catch((h)=>{z("cleanup",`Failed to remove hosts entries: ${h}`,$?.verbose),N.warn(`Failed to clean up hosts file entries for ${J.join(", ")}:`,h)}))}if($?.certs&&$.domains?.length){z("cleanup","Cleaning up SSL certificates",$?.verbose),N.info("Cleaning up SSL certificates...");let J=$.domains.map(async(h)=>{try{await wF(h,$?.verbose),z("cleanup",`Removed certificates for ${h}`,$?.verbose)}catch(U){z("cleanup",`Failed to remove certificates for ${h}: ${U}`,$?.verbose),N.warn(`Failed to clean up certificates for ${h}:`,U)}});w.push(...J)}await Promise.allSettled(w),z("cleanup","All cleanup tasks completed successfully",$?.verbose),N.success("All cleanup tasks completed successfully")}catch(w){z("cleanup",`Error during cleanup: ${w}`,$?.verbose),N.error("Error during cleanup:",w)}finally{if(fh)fh();fh=null,F8=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(s.env.NODE_ENV!=="test"&&s.env.BUN_ENV!=="test"&&!w)s.exit(0)}return B8}var j8=!1;function z8($){if(j8){z("signal",`Received second ${$} signal, forcing exit`,!0),s.exit(1);return}j8=!0,z("signal",`Received ${$} signal, initiating cleanup`,!0),Eh().catch((w)=>{z("signal",`Cleanup failed after ${$}: ${w}`,!0),s.exit(1)}).finally(()=>{j8=!1})}s.once("SIGINT",()=>z8("SIGINT"));s.once("SIGTERM",()=>z8("SIGTERM"));s.on("uncaughtException",($)=>{z("process",`Uncaught exception: ${$}`,!0),N.error("Uncaught exception:",$),z8("uncaughtException")});async function P1($,w,A,J=5){z("connection",`Testing connection to ${$}:${w} (retries left: ${J})`,A);let h=15000,U=Date.now();if(s.env.RPX_BYPASS_CONNECTION_TEST==="true"){z("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let Y=()=>new Promise((Z,f)=>{let E=SF.connect({host:$,port:w,timeout:3000});E.once("connect",()=>{z("connection",`Successfully connected to ${$}:${w}`,A),E.end(),Z()}),E.once("timeout",()=>{z("connection",`Connection to ${$}:${w} timed out`,A),E.destroy(),f(Error("Connection timed out"))}),E.once("error",(W)=>{z("connection",`Failed to connect to ${$}:${w}: ${W}`,A),E.destroy(),f(W)})});try{await Y()}catch(Z){if(Date.now()-U>h){z("connection",`Connection test timed out after ${h}ms, but continuing anyway`,A),N.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(Z.code==="ECONNREFUSED"&&J>0)return z("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${J} retries left)`,A),await new Promise((E)=>setTimeout(E,2000)),P1($,w,A,J-1);if(J>0)try{z("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((E,W)=>{let F=jw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(j)=>{z("connection",`Received HTTP response with status: ${j.statusCode}`,A),E()});F.on("error",(j)=>W(j)),F.on("timeout",()=>{F.destroy(),W(Error("HTTP request timed out"))}),F.end()}),z("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(E){return z("connection",`HTTP request to ${$}:${w} failed: ${E}`,A),z("connection",`Retrying socket connection in 2 seconds... (${J} retries left)`,A),await new Promise((W)=>setTimeout(W,2000)),P1($,w,A,J-1)}let f=`Failed to connect to ${$}:${w} after ${5-J} attempts: ${Z.message}`;z("connection",`${f}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),N.warn(f),N.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 DF($){z("server",`Starting server with options: ${w0($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),J=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),h=[A.hostname];if(!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){z("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await Q1(h,$.verbose))[0]){N.info(`Adding ${A.hostname} to hosts file...`),N.info("This may require sudo/administrator privileges");try{await k1(h,$.verbose)}catch(Z){if(N.error("Failed to add hosts entry:",Z.message),N.warn("You can manually add this entry to your hosts file:"),N.warn(`127.0.0.1 ${A.hostname}`),N.warn(`::1 ${A.hostname}`),s.platform==="win32")N.warn("On Windows:"),N.warn("1. Run notepad as administrator"),N.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else N.warn("On Unix systems:"),N.warn("sudo nano /etc/hosts")}}else z("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(Y){N.error("Failed to check hosts file:",Y.message)}}try{await P1(w.hostname,J,$.verbose)}catch(Y){z("server",`Connection test failed: ${Y}`,$.verbose),N.error(Y.message),N.warn("Continuing with proxy setup despite connection test failure..."),N.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=S1({...$,to:A.hostname});if(U=await b0({...$,to:A.hostname,https:$.https}),!U){if(z("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await $1({...$,from:w.toString(),to:A.hostname,https:$.https}),U=await b0({...$,to:A.hostname,https:$.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(Y){throw z("server",`SSL setup failed: ${Y}`,$.verbose),Y}z("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await X7({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:J,sourceUrl:{hostname:w.hostname,host:w.host},ssl:U})}async function _7($,w,A,J,h,U,Y,Z,f,E,W){z("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${E}`,f);function F(H){let q={};for(let[G,R]of Object.entries(H))if(!G.startsWith(":"))q[G]=R;return q}let j=(H,q)=>{z("request",`Incoming request: ${H.method} ${H.url}`,f);let G=H.url||"/",R=H.method||"GET";if(H instanceof CF.Http2ServerRequest){let K=H.headers;R=K[":method"]||R,G=K[":path"]||G}if(E){if(!G.match(/\.[a-z0-9]+$/i))if(G.endsWith("/"))G=`${G}index.html`;else G=`${G}.html`}let y=F(H.headers);if(W)y.host=`${U.hostname}:${A}`,z("request",`Changed origin: setting host header to ${y.host}`,f);let L={hostname:U.hostname,port:A,path:G,method:R,headers:y};z("request",`Proxy request options: ${w0(L)}`,f);let C=jw.request(L,(K)=>{if(z("response",`Proxy response received with status ${K.statusCode}`,f),E&&K.statusCode===404){let c$=[];if(G.endsWith(".html"))c$.push(G.slice(0,-5));else if(!G.match(/\.[a-z0-9]+$/i))c$.push(`${G}.html`);if(!G.endsWith("/"))c$.push(`${G}/index.html`);if(c$.length>0){z("cleanUrls",`Trying alternative paths: ${c$.join(", ")}`,f);let h1=(i1)=>{if(i1.length===0){q.writeHead(K.statusCode||404,K.headers),K.pipe(q);return}let H8=i1[0],QF={...L,path:H8},T8=jw.request(QF,(b1)=>{if(b1.statusCode===200)z("cleanUrls",`Found matching path: ${H8}`,f),q.writeHead(b1.statusCode,b1.headers),b1.pipe(q);else h1(i1.slice(1))});T8.on("error",()=>h1(i1.slice(1))),T8.end()};h1(c$);return}}let S$={...K.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};q.writeHead(K.statusCode||500,S$),K.pipe(q)});C.on("error",(K)=>{z("request",`Proxy request failed: ${K}`,f),N.error("Proxy request failed:",K),q.writeHead(502),q.end(`Proxy Error: ${K.message}`)}),H.pipe(C)};if(z("server",`Creating server with SSL config: ${!!Y}`,f),Y)return new Promise((H,q)=>{try{let G=Bun.serve({port:J,hostname:h,tls:{key:Y.key,cert:Y.cert,ca:Y.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let y=new URL(R.url);z("request",`Bun.serve received: ${R.method} ${y.pathname}`,f);let L=`http://${U.host}`,C=new URL(y.pathname+y.search,L);try{let K=new Headers(R.headers);if(K.set("host",U.host),W)K.set("origin",L);K.set("x-forwarded-for","127.0.0.1"),K.set("x-forwarded-proto","https"),K.set("x-forwarded-host",w);let S$=await fetch(C.toString(),{method:R.method,headers:K,body:R.body,redirect:"manual"}),c$=new Headers(S$.headers);if(E&&y.pathname.endsWith(".html")){let h1=y.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:h1}})}return new Response(S$.body,{status:S$.status,statusText:S$.statusText,headers:c$})}catch(K){return z("request",`Proxy error: ${K}`,f),new Response(`Proxy Error: ${K}`,{status:502})}},error(R){return z("server",`Bun.serve error: ${R}`,f),new Response(`Server Error: ${R.message}`,{status:500})}});x1.add(G),LF({from:$,to:w,vitePluginUsage:Z,listenPort:J,ssl:!0,cleanUrls:E,verbose:f}),H()}catch(G){q(G)}});let B=jw.createServer(j);function T(H){return x1.add(H),new Promise((q,G)=>{H.listen(J,h,()=>{z("server",`Server listening on port ${J}`,f),LF({from:$,to:w,vitePluginUsage:Z,listenPort:J,ssl:!!Y,cleanUrls:E,verbose:f}),q()}),H.on("error",(R)=>{z("server",`Server error: ${R}`,f),G(R)})})}return T(B)}async function X7($){z("setup",`Setting up reverse proxy: ${w0($)}`,$.verbose);let{from:w,to:A,fromPort:J,sourceUrl:h,ssl:U,verbose:Y,cleanup:Z,vitePluginUsage:f,changeOrigin:E,cleanUrls:W}=$,F=80,j=443,B="0.0.0.0",T=$.portManager||O7;try{if(A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await Q1([A],Y))[0]){N.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await k1([A],Y),N.success(`Added ${A} to your hosts file.`)}catch(y){N.error(`Failed to add ${A} to your hosts file: ${y}`),N.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(s.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await Q1([A],Y))[0]){z("hosts",`${A} not found in hosts file, adding...`,Y);try{await k1([A],Y)}catch(y){z("hosts",`Failed to add ${A} to hosts file: ${y}`,Y)}}}if(U&&!T.usedPorts.has(F)){if(!await Fw(F,B,Y))z("setup","Starting HTTP redirect server",Y),VF(Y),T.usedPorts.add(F);else if(z("setup","Port 80 is in use, skipping HTTP redirect",Y),Y)N.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let H=U?j:F,q=await Fw(H,B,Y),G;if(q){if(z("setup",`Port ${H} is already in use`,Y),Y)N.warn(`Port ${H} is already in use. This may be another instance of rpx or another service.`);if(H===443){if(G=await T.getNextAvailablePort(3443,!0),z("setup",`Using port ${G} instead of ${H}`,Y),Y)N.info(`Using port ${G} instead. Access your site at https://${A}:${G}`)}else if(G=await T.getNextAvailablePort(H+1000,!0),z("setup",`Using port ${G} instead of ${H}`,Y),Y)N.info(`Using port ${G} instead. Access your site at http://${A}:${G}`)}else G=H,T.usedPorts.add(G),z("setup",`Using standard ${H===443?"HTTPS":"HTTP"} port ${H} for ${A}`,Y);await _7(w,A,J,G,B,h,U,f,Y,W,E)}catch(H){z("setup",`Setup failed: ${H}`,Y),N.error(`Failed to setup reverse proxy: ${H.message}`),Eh({domains:[A],hosts:typeof Z==="boolean"?Z:Z?.hosts,certs:typeof Z==="boolean"?Z:Z?.certs,verbose:Y,vitePluginUsage:f})}}function VF($){z("redirect","Starting HTTP redirect server",$);let w=jw.createServer((A,J)=>{let h=A.headers.host||"";z("redirect",`Redirecting request from ${h}${A.url} to HTTPS`,$),J.writeHead(301,{Location:`https://${h}${A.url}`}),J.end()}).listen(80);x1.add(w),z("redirect","HTTP redirect server started",$)}function OF($){let w={...WY,...$};if(z("proxy",`Starting proxy with options: ${w0(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){N.error("viaDaemon mode requires both `from` and `to`");return}Z8({proxies:[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((f)=>{N.error(`Failed to register with rpx daemon: ${f.message}`),s.exit(1)});return}let A=w.to||"",J=A.split(".").pop()?.toLowerCase()||"",h=s.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),U=["dev","app","page","new","day","foo"],Y=["test","localhost","local","example","invalid"];if(h&&U.includes(J)&&w?.verbose)N.warn(`The .${J} TLD may not work reliably for local development`),N.info(` Google owns .${J} with HSTS preloading, which can bypass local DNS`),N.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(h)Promise.resolve().then(() => (Yh(),Uh)).then(({startDnsServer:f,setupResolver:E})=>{f([A],w.verbose).then((W)=>{if(W)E(w.verbose,[A]).then(()=>{if(w.verbose)if(Y.includes(J))N.success(`DNS server started for .${J} domains`);else N.success(`DNS server started for .${J} domains (hosts file entry also added)`)});else z("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((f)=>{z("dns",`Failed to start DNS server: ${f}`,w.verbose)});let Z={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:S1(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};z("proxy",`Server options: ${w0(Z)}`,w.verbose),DF(Z).catch((f)=>{z("proxy",`Failed to start proxy: ${f}`,w.verbose),N.error(`Failed to start proxy: ${f.message}`),Eh({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function k7($){return $?.verbose||!1}async function _F($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let A=k7(w);if(z("config",`Starting with config: ${w0(w,2)}`,A),z("config",`Is multi-proxy? ${"proxies"in w}`,A),w.viaDaemon){let T="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({id:H.id,from:H.from,to:H.to,cleanUrls:H.cleanUrls??w.cleanUrls,changeOrigin:H.changeOrigin??w.changeOrigin,pathRewrites:H.pathRewrites})):[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await Z8({proxies:T,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){z("servers",`Found ${w.proxies.length} proxies in config`,A);for(let B of w.proxies)if(B.start){let T=`${B.from}-${B.to}`;try{z("watch",`Starting command for ${T} with command: ${B.start.command}`,A),N.info(`Starting command for ${T}...`),await Zh.startProcess(T,B.start,A);let H=new URL(B.from.startsWith("http")?B.from:`http://${B.from}`),q=H.hostname||"localhost",G=Number(H.port)||80;try{await P1(q,G,A),z("watch",`Dev server is ready at ${q}:${G}`,A)}catch(R){z("watch",`Connection check failed, but continuing with proxy setup: ${R}`,A),N.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(H){throw z("watch",`Failed to start command for ${T}: ${H}`,A),Error(`Failed to start command for ${T}: ${H}`)}}else z("watch",`No start command for proxy ${B.from} -> ${B.to}`,A)}else if("start"in w&&w.start){z("watch","Found start command in single proxy config",A);let B=`${w.from}-${w.to}`;try{if(w.start)z("watch",`Starting command: ${w.start.command}`,A),await Zh.startProcess(B,w.start,A);let T=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),H=T.hostname||"localhost",q=Number(T.port)||80;try{await P1(H,q,A),z("watch",`Dev server is ready at ${H}:${q}`,A)}catch(G){z("watch",`Connection check failed, but continuing with proxy setup: ${G}`,A),N.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(T){throw z("watch",`Failed to run start command: ${T}`,A),Error(`Failed to run start command: ${T}`)}}else z("watch","No start command found in config",A);let J="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(s.platform!=="win32"&&(w.https||w.cleanup?.hosts!==!1)){if(!ww())try{z("sudo","Pre-acquiring sudo credentials for privileged operations",A),D7("sudo -v",{stdio:"inherit"})}catch{z("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let B=await b0(w);if(!B){if(z("ssl",`No valid or trusted certificates found for ${J}, generating new ones`,w.verbose),await $1(w),B=await b0(w),!B)throw Error(`Failed to load SSL certificates after generation for ${J}`)}else z("ssl",`Using existing and trusted certificates for ${J}`,w.verbose);w._cachedSSLConfig=B}let h="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((B)=>({...B,https:w.https,cleanup:w.cleanup,cleanUrls:B.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:B.changeOrigin??w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig}],U=h.map((B)=>B.to||"rpx.localhost"),Y=w._cachedSSLConfig,Z=U.filter((B)=>B&&!B.includes("localhost")&&!B.includes("127.0.0.1")),f=["dev","app","page","new","day","foo"],E=["test","localhost","local","example","invalid"],W=[...new Set(Z.map((B)=>B.split(".").pop()?.toLowerCase()))],F=W.filter((B)=>!!B&&f.includes(B));if(F.length>0&&A)N.warn(`The following TLDs may not work reliably for local development: ${F.map((B)=>`.${B}`).join(", ")}`),N.info(" These TLDs have HSTS preloading which can bypass local DNS"),N.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(s.platform==="darwin"&&Z.length>0){let{startDnsServer:B,setupResolver:T}=await Promise.resolve().then(() => (Yh(),Uh));if(await B(Z,A)){if(await T(A,Z),A)if(W.every((G)=>!!G&&E.includes(G)))N.success(`DNS server started for ${W.map((G)=>`.${G}`).join(", ")} domains`);else N.success(`DNS server started for ${W.map((G)=>`.${G}`).join(", ")} domains (hosts file entries also added)`)}else z("dns","Could not start DNS server - custom domains may not resolve",A)}let j=async()=>{z("cleanup","Starting cleanup handler",w.verbose);try{let{stopDnsServer:B,removeResolver:T}=await Promise.resolve().then(() => (Yh(),Uh));B(w.verbose),await T(w.verbose)}catch(B){z("cleanup",`Error stopping DNS server: ${B}`,w.verbose)}try{await Zh.stopAll(w.verbose)}catch(B){z("cleanup",`Error stopping processes: ${B}`,w.verbose)}await Eh({domains:U,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};if(s.on("SIGINT",j),s.on("SIGTERM",j),s.on("uncaughtException",(B)=>{z("process",`Uncaught exception: ${B}`,!0),console.error("Uncaught exception:",B),j()}),Y&&h.length>1){z("proxies",`Creating shared HTTPS server for ${h.length} domains`,A);let B=new Map;for(let G of h){let R=G.to||"rpx.localhost",y=new URL(G.from?.startsWith("http")?G.from:`http://${G.from}`);if(B.set(R,{sourceHost:y.host,cleanUrls:G.cleanUrls||!1,changeOrigin:G.changeOrigin||!1,pathRewrites:G.pathRewrites}),z("proxies",`Route: ${R} → ${y.host}`,A),!R.includes("localhost")&&!R.includes("127.0.0.1"))try{if(!(await Q1([R],A))[0])await k1([R],A)}catch{z("hosts",`Could not add hosts entry for ${R}`,A)}}if(!await Fw(80,"0.0.0.0",A))VF(A);let H=443;if(await Fw(H,"0.0.0.0",A)){if(z("proxies",`Port ${H} is already in use, cannot start shared proxy`,A),A)N.warn(`Port ${H} is in use. Shared HTTPS proxy cannot start.`);return}try{let G=Bun.serve({port:H,hostname:"0.0.0.0",tls:{key:Y.key,cert:Y.cert,ca:Y.ca,requestCert:!1,rejectUnauthorized:!1},fetch:D1((R)=>B.get(R),A),error(R){return z("server",`Shared proxy server error: ${R}`,A),new Response(`Server Error: ${R.message}`,{status:500})}});x1.add(G),z("proxies",`Shared HTTPS proxy listening on port ${H} for ${B.size} domains`,A)}catch(G){z("proxies",`Failed to start shared proxy: ${G}`,A),console.error("Failed to start shared HTTPS proxy:",G),j()}}else for(let B of h)try{let T=B.to||"rpx.localhost";z("proxy",`Starting proxy for ${T} with SSL config: ${!!Y}`,B.verbose),await DF({from:B.from||"localhost:5173",to:T,cleanUrls:B.cleanUrls||!1,https:B.https||!1,cleanup:B.cleanup||!1,vitePluginUsage:B.vitePluginUsage||!1,verbose:B.verbose||!1,_cachedSSLConfig:Y,changeOrigin:B.changeOrigin||!1})}catch(T){z("proxies",`Failed to start proxy for ${B.to}: ${T}`,B.verbose),console.error(`Failed to start proxy for ${B.to}:`,T),j()}}function LF($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${z0.green(z0.bold("rpx"))} ${z0.green(`v${V7}`)}`),console.log(` ${z0.green("➜")} ${z0.dim($?.from??"")} ${z0.dim("➜")} ${z0.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${z0.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${z0.green("➜")} Clean URLs enabled`)}tY();var ty=new $w("rpx",{showTags:!1});function XF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}var t$=new Rh("rpx"),kF="0.12.0";t$.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").action(async($)=>{if(!$?.from||!$.to)return _F(Sw);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let A={command:$.startCommand};if($.startCwd)A.cwd=$.startCwd;if($.startEnv)try{A.env=JSON.parse($.startEnv)}catch(J){console.error("Failed to parse start-env JSON:",J),l$.exit(1)}w.start=A}return OF(w)});t$.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=XF(Sw)?Sw.proxies.find((J)=>J.to===$||`${J.from}-${J.to}`===$):Sw.to===$?Sw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),l$.exit(1);try{await rJ.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(J){console.error(`Failed to start dev server for ${$}:`,J),l$.exit(1)}});t$.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await rJ.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),l$.exit(1)}});t$.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await rJ.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),l$.exit(1)}});t$.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--verbose","Enable verbose logging").action(async($)=>{try{await(await YF({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,verbose:$.verbose??!0})).done,l$.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),l$.exit(1)}});t$.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,A=await ZF({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!A.stopped&&A.pid===null){console.log("rpx daemon is not running");return}if(!A.stopped){console.log(`rpx daemon pid=${A.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${A.pid} stopped${A.forced?" (SIGKILL)":""}`)});t$.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??j0(),A=await Uw(w),J=await UF(w),h=$.registryDir,U=await jF(h).catch(()=>[]);if($.json){console.log(JSON.stringify({running:J,pid:A,pidFile:Yw(w),rpxDir:w,registryDir:h??Zw(),entries:U},null,2));return}if(!J){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Yw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Yw(w)}`);if(console.log(`registry: ${h??Zw()}`),U.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${U.length}):`);for(let Y of U){let Z=Y.pid!==void 0?`, pid=${Y.pid}`:"";console.log(` https://${Y.to} \u2192 ${Y.from} (id=${Y.id}${Z})`)}});t$.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),l$.exit(1);if(!J1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),l$.exit(1);try{await FF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),l$.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await fF({rpxDir:$.rpxDir,verbose:$.verbose}),A=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${A} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),l$.exit(1)}});t$.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async($,w)=>{if(!J1($))console.error(`invalid id: ${JSON.stringify($)}`),l$.exit(1);let A=await f8($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await BF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});t$.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(kF)});t$.version(kF);t$.help();t$.run();