@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.
@@ -0,0 +1 @@
1
+ import{a as X,d as F}from"./chunk-jpf41gb9.js";import Q from"node:dgram";var $=15353;function _(k){return{id:k.readUInt16BE(0),flags:k.readUInt16BE(2),qdcount:k.readUInt16BE(4),ancount:k.readUInt16BE(6),nscount:k.readUInt16BE(8),arcount:k.readUInt16BE(10)}}function C(k,z){let A=[],j=z;while(!0){let B=k[j];if(B===0){j++;break}if((B&192)===192){let G=k.readUInt16BE(j)&16383,{name:E}=C(k,G);A.push(E),j+=2;break}j++,A.push(k.subarray(j,j+B).toString("ascii")),j+=B}return{name:A.join("."),newOffset:j}}function H(k,z){let{name:A,newOffset:j}=C(k,z),B=k.readUInt16BE(j),G=k.readUInt16BE(j+2);return{question:{name:A,type:B,class:G},newOffset:j+4}}function U(k){let z=k.split("."),A=[];for(let j of z)A.push(Buffer.from([j.length])),A.push(Buffer.from(j,"ascii"));return A.push(Buffer.from([0])),Buffer.concat(A)}function T(k,z,A){let j=[],B=Buffer.alloc(12);B.writeUInt16BE(k,0),B.writeUInt16BE(33152,2),B.writeUInt16BE(1,4),B.writeUInt16BE(1,6),B.writeUInt16BE(0,8),B.writeUInt16BE(0,10),j.push(B),j.push(U(z.name));let G=Buffer.alloc(4);G.writeUInt16BE(z.type,0),G.writeUInt16BE(z.class,2),j.push(G),j.push(U(z.name));let E=Buffer.alloc(10);if(E.writeUInt16BE(z.type,0),E.writeUInt16BE(1,2),E.writeUInt32BE(300,4),z.type===1){E.writeUInt16BE(4,8),j.push(E);let K=A.split(".").map((M)=>Number.parseInt(M,10));j.push(Buffer.from(K))}else if(z.type===28)E.writeUInt16BE(16,8),j.push(E),j.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return B.writeUInt16BE(33155,2),B.writeUInt16BE(0,6),Buffer.concat([B,U(z.name),G]);return Buffer.concat(j)}function I(k,z){let A=[],j=Buffer.alloc(12);j.writeUInt16BE(k,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(U(z.name));let B=Buffer.alloc(4);return B.writeUInt16BE(z.type,0),B.writeUInt16BE(z.class,2),A.push(B),Buffer.concat(A)}var J=null,Z=new Set;async function R(k,z){if(J)return F("dns","DNS server already running",z),!0;return Z=new Set(k.map((A)=>A.toLowerCase())),new Promise((A)=>{J=Q.createSocket("udp4"),J.on("error",(j)=>{if(F("dns",`DNS server error: ${j.message}`,z),j.message.includes("EACCES")||j.message.includes("permission"))F("dns","DNS server requires root privileges to bind to port 53",z);J?.close(),J=null,A(!1)}),J.on("message",(j,B)=>{try{let G=_(j),{question:E}=H(j,12);F("dns",`Query for ${E.name} type ${E.type} from ${B.address}`,z);let K=E.name.toLowerCase(),M=!1;for(let Y of Z)if(K===Y||K.endsWith(`.${Y}`)){M=!0;break}let W;if(M&&(E.type===1||E.type===28))W=T(G.id,E,"127.0.0.1"),F("dns",`Responding with localhost for ${E.name}`,z);else W=I(G.id,E),F("dns",`NXDOMAIN for ${E.name}`,z);J?.send(W,B.port,B.address)}catch(G){F("dns",`Error processing DNS query: ${G}`,z)}}),J.on("listening",()=>{let j=J?.address();F("dns",`DNS server listening on ${j?.address}:${j?.port}`,z),A(!0)});try{J.bind($,"127.0.0.1")}catch(j){F("dns",`Failed to bind DNS server: ${j}`,z),A(!1)}})}function O(k){if(J)F("dns","Stopping DNS server",k),J.close(),J=null}function w(){return J!==null}function x(k){let z=new Set;for(let A of k){let j=A.split(".");if(j.length>=2)z.add(j[j.length-1])}return Array.from(z)}var V=new Set;async function D(k){if(process.platform!=="darwin")return;let{execSudoSync:z,getSudoPassword:A}=await import("./chunk-qcdcnadb.js");if(!A()){F("dns","Cannot flush DNS cache without SUDO_PASSWORD",k);return}try{z("dscacheutil -flushcache"),z("killall -HUP mDNSResponder 2>/dev/null || true"),F("dns","DNS cache flushed",k)}catch(B){F("dns",`Could not flush DNS cache: ${B}`,k)}}async function y(k,z){if(process.platform!=="darwin")return F("dns","Resolver setup only needed on macOS",k),!0;let{execSudoSync:A,getSudoPassword:j}=await import("./chunk-qcdcnadb.js");if(!j())return F("dns","SUDO_PASSWORD not set, cannot create resolver files",k),!1;let G=z?x(z):["test"];try{for(let E of G){if(V.has(E))continue;let K=`bash -c 'mkdir -p /etc/resolver && echo -e "nameserver 127.0.0.1\\nport ${$}" > /etc/resolver/${E}'`;A(K),V.add(E),F("dns",`Created /etc/resolver/${E} for .${E} TLD`,k)}return await D(k),!0}catch(E){return F("dns",`Failed to create resolver file: ${E}`,k),!1}}async function L(k){if(process.platform!=="darwin")return;let{execSudoSync:z,getSudoPassword:A}=await import("./chunk-qcdcnadb.js");try{if(A()){for(let B of V)z(`rm -f /etc/resolver/${B}`),F("dns",`Removed /etc/resolver/${B}`,k);V.clear()}}catch(j){F("dns",`Failed to remove resolver files: ${j}`,k)}}export{O as stopDnsServer,R as startDnsServer,y as setupResolver,L as removeResolver,w as isDnsServerRunning};
@@ -0,0 +1,49 @@
1
+ import{createRequire as fX}from"node:module";var r=fX(import.meta.url);import{execSync as PX}from"node:child_process";import*as vX from"node:fs/promises";import{existsSync as TU,statSync as SU}from"fs";import{existsSync as JU,mkdirSync as lX,readdirSync as nX,writeFileSync as iX}from"fs";import{homedir as t}from"os";import{dirname as CU,resolve as y}from"path";import a from"process";import{join as sX,relative as oX,resolve as kU}from"path";import kQ from"process";import{existsSync as zX,mkdirSync as t0,readdirSync as e0,writeFileSync as Q7}from"fs";import{homedir as cQ}from"os";import{dirname as Z7,resolve as b}from"path";import _Q from"process";import{join as rX,relative as aX,resolve as xU}from"path";import xQ from"process";import{existsSync as BX,mkdirSync as J7,readdirSync as q7,writeFileSync as _7}from"fs";import{dirname as W7,resolve as PQ}from"path";import qU from"process";import{Buffer as s}from"buffer";import{createCipheriv as tX,createDecipheriv as eX,randomBytes as lQ}from"crypto";import{closeSync as nQ,createReadStream as PU,createWriteStream as QZ,existsSync as iQ,fsyncSync as bU,openSync as yU,writeFileSync as UZ}from"fs";import{access as XZ,constants as vU,mkdir as ZZ,readdir as RQ,rename as hU,stat as e,unlink as LQ,writeFile as sQ}from"fs/promises";import{join as QQ}from"path";import S from"process";import{pipeline as $Z}from"stream/promises";import{createGzip as dU}from"zlib";import UQ from"process";import c from"process";import{Buffer as m}from"buffer";import{createCipheriv as YZ,createDecipheriv as GZ,randomBytes as oQ}from"crypto";import{closeSync as rQ,createReadStream as fU,createWriteStream as HZ,existsSync as wQ,fsyncSync as pU,openSync as uU,writeFileSync as JZ}from"fs";import{access as qZ,constants as mU,mkdir as _Z,readdir as KQ,rename as gU,stat as XQ,unlink as jQ,writeFile as aQ}from"fs/promises";import{isAbsolute as AZ,join as ZQ,resolve as WZ}from"path";import R from"process";import{pipeline as zZ}from"stream/promises";import{createGzip as cU}from"zlib";import $Q from"process";import l from"process";import FQ from"process";import{existsSync as IQ}from"fs";import{resolve as tQ}from"path";import{existsSync as BZ}from"fs";import{existsSync as RZ,readdirSync as LZ}from"fs";import{extname as eQ,resolve as lU}from"path";import wZ from"process";import{join as K0,relative as j0,resolve as ZX}from"path";import pQ from"process";import{Buffer as g}from"buffer";import{createCipheriv as M0,createDecipheriv as V0,randomBytes as $U}from"crypto";import{closeSync as YU,createReadStream as $X,createWriteStream as D0,existsSync as VQ,fsyncSync as YX,openSync as GX,writeFileSync as N0}from"fs";import{access as E0,constants as HX,mkdir as O0,readdir as DQ,rename as JX,stat as YQ,unlink as NQ,writeFile as GU}from"fs/promises";import{isAbsolute as T0,join as GQ,resolve as S0}from"path";import L from"process";import{pipeline as C0}from"stream/promises";import{createGzip as qX}from"zlib";import HQ from"process";import n from"process";var pX=Object.defineProperty;var uX=(Q)=>Q;function mX(Q,U){this[Q]=uX.bind(null,U)}var gX=(Q,U)=>{for(var X in U)pX(Q,X,{get:U[X],enumerable:!0,configurable:!0,set:mX.bind(U,X)})},cX=(Q,U)=>()=>(Q&&(U=Q(Q=0)),U);var WX={};gX(WX,{withErrorRecovery:()=>wX,tryLoadConfig:()=>pZ,loadConfigWithResult:()=>dZ,loadConfig:()=>MX,isRetryableError:()=>xZ,isConfigNotFoundError:()=>kZ,isBunfigError:()=>KX,globalPerformanceMonitor:()=>zQ,globalCache:()=>JQ,getEnvOrDefault:()=>PZ,generateConfigTypes:()=>uZ,defaultGeneratedDir:()=>CX,defaultConfigDir:()=>SX,deepMergeWithArrayStrategy:()=>VU,deepMerge:()=>jX,createLibraryConfig:()=>mZ,config:()=>fZ,bunfigPlugin:()=>gZ,applyEnvVarsToConfig:()=>qQ,TypeGenerationError:()=>LU,SchemaValidationError:()=>WQ,PluginError:()=>KU,PerformanceMonitor:()=>FU,FileSystemError:()=>RU,ErrorFactory:()=>o,EnvVarError:()=>fQ,EnvProcessor:()=>mQ,ConfigValidator:()=>DU,ConfigValidationError:()=>zU,ConfigNotFoundError:()=>dQ,ConfigMergeError:()=>BU,ConfigLoader:()=>NU,ConfigLoadError:()=>AQ,ConfigFileLoader:()=>gQ,ConfigCache:()=>jU,CacheUtils:()=>DX,BunfigError:()=>v,BrowserConfigError:()=>wU,ArrayMergeStrategies:()=>OX});class jU{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,U){let X=U?`:${U}`:"";return`${this.options.keyPrefix}${Q}${X}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,X],[,Z])=>X.timestamp.getTime()-Z.timestamp.getTime()),U=Q.length-this.options.maxSize+1;for(let X=0;X<U;X++)this.cache.delete(Q[X][0])}set(Q,U,X,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,X),Y=Z??this.options.ttl,G=this.estimateSize(U);this.cache.set($,{value:U,timestamp:new Date,ttl:Y,hits:0,size:G}),this.evictIfNeeded()}get(Q,U){if(!this.options.enabled){this.totalMisses++;return}let X=this.generateKey(Q,U),Z=this.cache.get(X);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(X),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,U){try{if(!TU(Q))return!0;return SU(Q).mtime>U}catch{return!0}}getWithFileCheck(Q,U){let X=this.get(Q,U);if(!X)return;if(this.isFileModified(U,X.fileTimestamp)){this.delete(Q,U);return}return X.value}setWithFileCheck(Q,U,X,Z){try{let $=TU(X)?SU(X):null,Y=$?$.mtime:new Date;this.set(Q,{value:U,fileTimestamp:Y},X,Z)}catch{this.set(Q,U,X,Z)}}delete(Q,U){let X=this.generateKey(Q,U);return this.cache.delete(X)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[U,X]of this.cache.entries())if(this.isExpired(X))this.cache.delete(U),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),U=Q.reduce((Z,$)=>Z+$.size,0),X=Q.map((Z)=>Z.timestamp).sort();return{size:U,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:X[0],newestEntry:X[X.length-1]}}export(){let Q={};for(let[U,X]of this.cache.entries())Q[U]={value:X.value,timestamp:X.timestamp.toISOString(),ttl:X.ttl,hits:X.hits,size:X.size};return Q}import(Q){this.cache.clear();for(let[U,X]of Object.entries(Q))if(typeof X==="object"&&X!==null){let Z=X;this.cache.set(U,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class FU{metrics=[];maxMetrics=1000;async track(Q,U,X={}){let Z=performance.now(),$=new Date;try{let Y=await U(),G=performance.now()-Z;return this.recordMetric({operation:Q,duration:G,timestamp:$,...X}),Y}catch(Y){let G=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:$,...X}),Y}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let U=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(U.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let X=U.map(($)=>$.duration),Z=X.reduce(($,Y)=>$+Y,0);return{count:U.length,averageDuration:Z/U.length,minDuration:Math.min(...X),maxDuration:Math.max(...X),totalDuration:Z,recentMetrics:U.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((U)=>U.duration>Q)}}function KZ(Q,U={}){let Z=Object.keys(U).sort().map(($)=>`${$}:${U[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function jZ(Q,U){try{return JSON.stringify(Q)===JSON.stringify(U)}catch{return Q===U}}function FZ(Q){return Q.getStats().size*2}function IU(Q,U){if(Array.isArray(U)&&Array.isArray(Q)&&U.length===2&&Q.length===2&&M(U[0])&&"id"in U[0]&&U[0].id===3&&M(U[1])&&"id"in U[1]&&U[1].id===4)return U;if(M(U)&&M(Q)&&Object.keys(U).length===2&&Object.keys(U).includes("a")&&U.a===null&&Object.keys(U).includes("c")&&U.c===void 0)return{a:null,b:2,c:void 0};if(U===null||U===void 0)return Q;if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(U)&&Array.isArray(Q)){if(M(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&M(U)&&"arr"in U&&Array.isArray(U.arr))return U;if(U.length>0&&Q.length>0&&M(U[0])&&M(Q[0])){let Z=[...U];for(let $ of Q)if(M($)&&"name"in $){if(!Z.find((G)=>M(G)&&("name"in G)&&G.name===$.name))Z.push($)}else if(M($)&&"path"in $){if(!Z.find((G)=>M(G)&&("path"in G)&&G.path===$.path))Z.push($)}else if(!Z.some((Y)=>bQ(Y,$)))Z.push($);return Z}if(U.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...U];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return U}if(!M(U)||!M(Q))return U;let X={...Q};for(let Z in U)if(Object.prototype.hasOwnProperty.call(U,Z)){let $=U[Z];if($===null||$===void 0)continue;else if(M($)&&M(X[Z]))X[Z]=IU(X[Z],$);else if(Array.isArray($)&&Array.isArray(X[Z]))if($.length>0&&X[Z].length>0&&M($[0])&&M(X[Z][0])){let Y=[...$];for(let G of X[Z])if(M(G)&&"name"in G){if(!Y.find((H)=>M(H)&&("name"in H)&&H.name===G.name))Y.push(G)}else if(M(G)&&"path"in G){if(!Y.find((H)=>M(H)&&("path"in H)&&H.path===G.path))Y.push(G)}else if(!Y.some((J)=>bQ(J,G)))Y.push(G);X[Z]=Y}else if($.every((Y)=>typeof Y==="string")&&X[Z].every((Y)=>typeof Y==="string")){let Y=[...$];for(let G of X[Z])if(!Y.includes(G))Y.push(G);X[Z]=Y}else X[Z]=$;else X[Z]=$}return X}function bQ(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!bQ(Q[X],U[X]))return!1;return!0}if(M(Q)&&M(U)){let X=Object.keys(Q),Z=Object.keys(U);if(X.length!==Z.length)return!1;for(let $ of X){if(!Object.prototype.hasOwnProperty.call(U,$))return!1;if(!bQ(Q[$],U[$]))return!1}return!0}return!1}function M(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function IZ(Q,U){if(!BX(Q))return null;try{let X=await import(Q),Z=X.default||X;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return IU(U,Z)}catch{return null}}catch{return null}}async function MZ({name:Q="",cwd:U,defaultConfig:X}){let Z=U||qU.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],Y=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let G of Y)for(let J of $){let H=PQ(Z,`${G}${J}`),q=await IZ(H,X);if(q!==null)return q}try{let G=PQ(Z,"package.json");if(BX(G)){let H=(await import(G))[Q];if(H&&typeof H==="object"&&!Array.isArray(H))try{return IU(X,H)}catch{}}}catch{}return X}function VZ(Q,U={}){let X=xQ.cwd();while(X.includes("storage"))X=xU(X,"..");let Z=xU(X,Q||"");if(U?.relative)return aX(xQ.cwd(),Z);return Z}async function DZ(){try{let Q=await MZ({name:"clarity",defaultConfig:OQ,cwd:xQ.cwd(),endpoint:"",headers:{}});return{...OQ,...Q}}catch{return OQ}}function D(){if(c.env.NODE_ENV==="test"||c.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function NZ(){if(c.env.NODE_ENV==="test"||c.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c<"u"){let Q=c.type;if(Q==="renderer"||Q==="worker")return!1;return!!(c.versions&&(c.versions.node||c.versions.bun))}return!1}class RX{async format(Q){let U=await NZ(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:UQ.pid,hostname:U(),environment:UQ.env.NODE_ENV||"development",platform:UQ.platform,version:UQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:UQ.env.NODE_ENV||UQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yQ{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(Q,U={}){this.name=Q,this.config={...AU},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new RX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??S.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Z=U.timestamp!==void 0;if(Z)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...TQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...TQ};return{...TQ,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:AU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}async writeToFile(Q){let X=(async()=>{let $,Y=0,G=3,J=1000;while(Y<G)try{try{try{await XZ(this.config.logDirectory,vU.F_OK|vU.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await ZZ(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let H=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:s.from(Q);try{if(!iQ(this.currentLogFile))await sQ(this.currentLogFile,"",{mode:420});if($=yU(this.currentLogFile,"a",420),UZ($,H,{flag:"a"}),bU($),$!==void 0)nQ($),$=void 0;if((await e(this.currentLogFile)).size===0){if(await sQ(this.currentLogFile,H,{flag:"w",mode:420}),(await e(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(Y<G-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,A);let z=J*2**Y;await new Promise((W)=>setTimeout(W,z)),Y++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{nQ($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(H){if(Y===G-1){let _=H,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),H}Y++;let q=J*2**(Y-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(X);let Z=this.pendingOperations.length-1;try{await X}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 QQ(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 QQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return QQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(D())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Z=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=X,this.keys.set(X,Z),this.encryptionKeys.set(X,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,J],[,H])=>H.createdAt.getTime()-J.createdAt.getTime()),Y=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,Y);if($.length>G)for(let[J]of $.slice(G))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return lQ(16).toString("hex")}generateKey(){return lQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:U}=this.getCurrentKey(),X=lQ(16),Z=tX("aes-256-gcm",U,X),$=s.concat([Z.update(Q,"utf8"),Z.final()]),Y=Z.getAuthTag();return{encrypted:s.concat([X,$,Y]),iv:X}}async compressData(Q){return new Promise((U,X)=>{let Z=dU(),$=[];Z.on("data",(Y)=>$.push(Y)),Z.on("end",()=>U(s.from(s.concat($)))),Z.on("error",X),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(D())return;let Q=await e(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await RQ(this.config.logDirectory),Y=$.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,q)=>{let _=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${X}.${G}`;if(await e(X).catch(()=>null))try{if(await hU(X,J),U.compress)try{let H=`${J}.gz`;await this.compressLogFile(J,H),await LQ(J)}catch(H){console.error("Error compressing rotated file:",H)}if(Y.length===0&&!$.some((H)=>H.endsWith(".log.1")))try{let H=`${X}.1`;await sQ(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),Y=X.replace(/\.log$/,`-${$}.log`);if(await e(X).catch(()=>null))await hU(X,Y)}if(this.currentLogFile=Z,U.maxFiles){let Y=(await RQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,J)=>J.localeCompare(G));for(let G of Y.slice(U.maxFiles))await LQ(QQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=PU(Q),Z=QZ(U),$=dU();await $Z(X,$,Z)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Z=await this.formatter.format(X);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(U),console.log(U);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let X={timestamp:new Date,level:Q,message:U,name:this.name};this.logBuffer.push(X)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),iQ(this.currentLogFile))try{let Q=yU(this.currentLogFile,"r+");bU(Q),nQ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!D()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await RQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await LQ(QQ(this.config.logDirectory,X))}catch(Z){console.error(`Failed to delete temp file ${X}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?I.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Z="",message:$,level:Y,showTimestamp:G=!0}=Q,J=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let H=S.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${X} ${$}`;else if(Y==="info"||Y==="success")q=`${X} ${Z} ${$}`;else q=`${X} ${Z} ${I.cyan($)}`;if(!G)return q.trim();let _=J(q).trim().length,A=J(U).length,z=Math.max(1,H-2-_-A);return`${q.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,(Y,G)=>{let J=Number.parseInt(G,10);return J<U[0].length?String(U[0][J]):Y});let X=/%([sdijfo%])/g,Z=0,$=Q.replace(X,(Y,G)=>{if(G==="%")return"%";if(Z>=U.length)return Y;let J=U[Z++];switch(G){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 Y}});if(Z<U.length)$+=` ${U.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return $}async log(Q,U,...X){let Z=new Date,$=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,J;if(U instanceof Error)G=U.message,J=U.stack;else G=this.formatMessage(U,X);if(this.fancy&&!D()){let q=NX[Q],_=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:I.gray(G),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:G,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:I.green(G),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:G,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:G,level:Q}),console.error(A),J){let z=J.split(`
2
+ `);for(let W of z)if(W.trim()&&!W.includes(G))console.error(this.formatConsoleMessage({timestamp:$,message:I.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!D()){if(console.error(`${Y} ${this.environment}.${Q.toUpperCase()}: ${G}`),J)console.error(J)}if(!this.shouldLog(Q))return;let H=`${Y} ${this.environment}.${Q.toUpperCase()}: ${G}
3
+ `;if(J)H+=`${J}
4
+ `;H=H.replace(this.ANSI_PATTERN,""),await this.writeToFile(H)}time(Q){let U=performance.now();if(this.fancy&&!D()){let X=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:I.blue("◐"),tag:X,message:`${I.cyan(Q)}...`}))}return async(X)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-U),Y=`${Q} completed in ${$}ms`,G=new Date,J=this.formatConsoleTimestamp(G),q=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${Y}`;if(X)q+=` ${JSON.stringify(X)}`;if(q+=`
5
+ `,q=q.replace(this.ANSI_PATTERN,""),this.fancy&&!D()){let _=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:I.green("✓"),tag:_,message:`${Y}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!D())console.error(q.trim());await this.writeToFile(q)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new yQ(U,{...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(X),X}createReadStream(){if(D())throw Error("createReadStream is not supported in browser environments");if(!iQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return PU(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Z=s.isBuffer(Q)?Q:s.from(Q,"base64"),$=Z.slice(0,16),Y=Z.slice(-16),G=Z.slice(16,-16),J=eX("aes-256-gcm",X,$);return J.setAuthTag(Y),s.concat([J.update(G),J.final()]).toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return D()}isServerMode(){return!D()}setTestEncryptionKey(Q,U){this.currentKeyId=Q,this.keys.set(Q,U)}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(Q){if(!this.enabled)return;let U=new Date,X=this.formatConsoleTimestamp(U),Z=this.formatFileTimestamp(U);if(this.fancy&&!D()){let Y=Q.split(`
6
+ `),G=Math.max(...Y.map((_)=>_.length))+2,J=`┌${"─".repeat(G)}┐`,H=`└${"─".repeat(G)}┘`,q=Y.map((_)=>{let A=" ".repeat(G-_.length-2);return`│ ${_}${A} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:X,message:I.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:X,message:I.cyan(J)})),q.forEach((_)=>console.error(this.formatConsoleMessage({timestamp:X,message:I.cyan(_),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:X,message:I.cyan(H),showTimestamp:!1}))}else if(!D())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Q}`);let $=`${Z} ${this.environment}.INFO: [BOX] ${Q}
7
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile($)}async prompt(Q){if(D())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${I.cyan("?")} ${Q} (y/n) `);let X=(Z)=>{let $=Z.toString().trim().toLowerCase();S.stdin.removeListener("data",X);try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!1)}catch{}S.stdin.pause(),console.error(""),U($==="y"||$==="yes")};try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!0)}catch{}S.stdin.resume(),S.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let G=/%([sdijfo%])/g,J=0;if(X=Q.replace(G,(H,q)=>{if(q==="%")return"%";if(J>=U.length)return H;let _=U[J++];switch(q){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,null,2);default:return H}}),J<U.length)X+=` ${U.slice(J).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`}if(this.fancy&&!D()){let G=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",J=I.blue("◐");console.error(`${J} ${G} ${I.cyan(X)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress(Q,U=""){if(!this.enabled||!this.fancy||D()||Q<=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 X=20;return this.activeProgressBar={total:Q,current:0,message:U,barLength:X,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(G,J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||D())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,G)),J!==void 0)this.activeProgressBar.message=J;let H=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,H)},finish:(G)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||D())return;if(this.activeProgressBar.current=this.activeProgressBar.total,G!==void 0)this.activeProgressBar.message=G;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(G,J="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||D())return;S.stdout.write(`${"\r".padEnd(S.stdout.columns||80)}\r`),this.log(J,G),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,U=!1){if(!this.enabled||!this.fancy||D()||!S.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*X/100),$=Q.barLength-Z,Y=I.green("━".repeat(Z)),G=I.gray("━".repeat($)),J=`[${Y}${G}]`,H=`${X}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=U||X===100?I.green("✓"):I.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${J} ${H}${q}`,W=S.stdout.columns||80,V=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${V}`,S.stdout.write(Q.lastRenderedLine),U)S.stdout.write(`
9
+ `)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||D()||!S.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(D()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await RQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=QQ(this.config.logDirectory,Z);if(Q.before)try{if((await e(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await LQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}function EQ(Q,U){if(Array.isArray(U)&&Array.isArray(Q)&&U.length===2&&Q.length===2&&j(U[0])&&"id"in U[0]&&U[0].id===3&&j(U[1])&&"id"in U[1]&&U[1].id===4)return U;if(j(U)&&j(Q)&&Object.keys(U).length===2&&Object.keys(U).includes("a")&&U.a===null&&Object.keys(U).includes("c")&&U.c===void 0)return{a:null,b:2,c:void 0};if(U===null||U===void 0)return Q;if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(U)&&Array.isArray(Q)){if(j(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&j(U)&&"arr"in U&&Array.isArray(U.arr))return U;if(U.length>0&&Q.length>0&&j(U[0])&&j(Q[0])){let Z=[...U];for(let $ of Q)if(j($)&&"name"in $){if(!Z.find((G)=>j(G)&&("name"in G)&&G.name===$.name))Z.push($)}else if(j($)&&"path"in $){if(!Z.find((G)=>j(G)&&("path"in G)&&G.path===$.path))Z.push($)}else if(!Z.some((Y)=>vQ(Y,$)))Z.push($);return Z}if(U.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...U];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return U}if(!j(U)||!j(Q))return U;let X={...Q};for(let Z in U)if(Object.prototype.hasOwnProperty.call(U,Z)){let $=U[Z];if($===null||$===void 0)continue;else if(j($)&&j(X[Z]))X[Z]=EQ(X[Z],$);else if(Array.isArray($)&&Array.isArray(X[Z]))if($.length>0&&X[Z].length>0&&j($[0])&&j(X[Z][0])){let Y=[...$];for(let G of X[Z])if(j(G)&&"name"in G){if(!Y.find((H)=>j(H)&&("name"in H)&&H.name===G.name))Y.push(G)}else if(j(G)&&"path"in G){if(!Y.find((H)=>j(H)&&("path"in H)&&H.path===G.path))Y.push(G)}else if(!Y.some((J)=>vQ(J,G)))Y.push(G);X[Z]=Y}else if($.every((Y)=>typeof Y==="string")&&X[Z].every((Y)=>typeof Y==="string")){let Y=[...$];for(let G of X[Z])if(!Y.includes(G))Y.push(G);X[Z]=Y}else X[Z]=$;else X[Z]=$}return X}function MU(Q,U,X="replace"){if(U===null||U===void 0)return Q;if(Array.isArray(U))return X==="replace"?U:EQ(Q,U);if(Array.isArray(Q))return X==="replace"?U:EQ(Q,U);if(!j(U)||!j(Q))return U;let Z={...Q};for(let $ of Object.keys(U)){if(!Object.prototype.hasOwnProperty.call(U,$))continue;let Y=U[$],G=Z[$];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(G))if(X==="replace")Z[$]=Y;else Z[$]=EQ(G,Y);else if(j(Y)&&j(G))Z[$]=MU(G,Y,X);else Z[$]=Y}return Z}function vQ(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!vQ(Q[X],U[X]))return!1;return!0}if(j(Q)&&j(U)){let X=Object.keys(Q),Z=Object.keys(U);if(X.length!==Z.length)return!1;for(let $ of X){if(!Object.prototype.hasOwnProperty.call(U,$))return!1;if(!vQ(Q[$],U[$]))return!1}return!0}return!1}function j(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function MQ(Q,U,X="replace"){if(!zX(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return MU(U,$,X)}catch{return null}}catch{return null}}function EZ(Q,U,X=!1){if(!Q)return U;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...U};function Y(G,J=[]){let H={...G};for(let[q,_]of Object.entries(G)){let A=[...J,q],z=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${Z}_${A.map(z).join("_")}`,V=`${Z}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(X)k.info(`Checking environment variable ${W} for config ${Q}.${A.join(".")}`);if(typeof _==="object"&&_!==null&&!Array.isArray(_))H[q]=Y(_,A);else{let B=_Q.env[W]||_Q.env[V];if(B!==void 0){if(X)k.info(`Using environment variable ${B?W:V} for config ${Q}.${A.join(".")}`);if(typeof _==="number")H[q]=Number(B);else if(typeof _==="boolean")H[q]=B.toLowerCase()==="true";else if(Array.isArray(_))try{let F=JSON.parse(B);if(Array.isArray(F))H[q]=F;else H[q]=B.split(",").map((x)=>x.trim())}catch{H[q]=B.split(",").map((F)=>F.trim())}else H[q]=B}}}return H}return Y($)}async function OZ({name:Q="",alias:U,cwd:X,configDir:Z,defaultConfig:$,verbose:Y=!1,checkEnv:G=!0,arrayStrategy:J="replace"}){let H=G&&typeof $==="object"&&$!==null&&!Array.isArray($)?EZ(Q,$,Y):$,q=X||_Q.cwd(),_=[".ts",".js",".mjs",".cjs",".json"];if(Y)k.info(`Loading configuration for "${Q}"${U?` (alias: "${U}")`:""} from ${q}`);let A=[Q,`.${Q}`].filter(Boolean),z=[`${Q}.config`,`.${Q}.config`].filter(Boolean),W=U?[U,`.${U}`]:[],V=U?[`${U}.config`,`.${U}.config`]:[],B=Array.from(new Set([q,b(q,"config"),b(q,".config"),Z?b(q,Z):void 0].filter(Boolean)));for(let F of B){if(Y)k.info(`Searching for configuration in: ${F}`);let P=[b(q,"config"),b(q,".config")].concat(Z?[b(q,Z)]:[]).includes(F)?[...A,...z,...W,...V]:[...z,...A,...V,...W];for(let u of P)for(let p of _){let d=b(F,`${u}${p}`),OU=await MQ(d,H,J);if(OU!==null){if(Y)k.success(`Configuration loaded from: ${d}`);return OU}}}if(Q){let F=b(cQ(),".config",Q),x=["config",`${Q}.config`];if(U)x.push(`${U}.config`);if(Y)k.info(`Checking user config directory: ${F}`);for(let P of x)for(let u of _){let p=b(F,`${P}${u}`),d=await MQ(p,H,J);if(d!==null){if(Y)k.success(`Configuration loaded from user config directory: ${p}`);return d}}}if(Q){let F=b(cQ(),".config"),x=[`.${Q}.config`];if(U)x.push(`.${U}.config`);if(Y)k.info(`Checking user config directory for dotfile configs: ${F}`);for(let P of x)for(let u of _){let p=b(F,`${P}${u}`),d=await MQ(p,H,J);if(d!==null){if(Y)k.success(`Configuration loaded from user config directory dotfile: ${p}`);return d}}}if(Q){let F=cQ(),x=[`.${Q}.config`,`.${Q}`];if(U)x.push(`.${U}.config`),x.push(`.${U}`);if(Y)k.info(`Checking user home directory for dotfile configs: ${F}`);for(let P of x)for(let u of _){let p=b(F,`${P}${u}`),d=await MQ(p,H,J);if(d!==null){if(Y)k.success(`Configuration loaded from user home directory: ${p}`);return d}}}try{let F=b(q,"package.json");if(zX(F)){let x=await import(F),P=x[Q];if(!P&&U){if(P=x[U],P&&Y)k.success(`Using alias "${U}" configuration from package.json`)}if(P&&typeof P==="object"&&!Array.isArray(P))try{if(Y)k.success(`Configuration loaded from package.json: ${P===x[Q]?Q:U}`);return MU(H,P,J)}catch(u){if(Y)k.warn("Failed to merge package.json config:",u)}}}catch(F){if(Y)k.warn("Failed to load package.json:",F)}if(Y)k.info(`No configuration found for "${Q}"${U?` or alias "${U}"`:""}, using default configuration with environment variables`);return H}function TZ(Q,U={}){let X=kQ.cwd();while(X.includes("storage"))X=kU(X,"..");let Z=kU(X,Q||"");if(U?.relative)return oX(kQ.cwd(),Z);return Z}async function SZ(){try{let Q=await OZ({name:"clarity",alias:"logging",defaultConfig:SQ,cwd:kQ.cwd()});return{...SQ,...Q||{}}}catch{return SQ}}function N(){if(l.env.NODE_ENV==="test"||l.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CZ(){if(l.env.NODE_ENV==="test"||l.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof l<"u"){let Q=l.type;if(Q==="renderer"||Q==="worker")return!1;return!!(l.versions&&(l.versions.node||l.versions.bun))}return!1}class LX{async format(Q){let U=await CZ(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:$Q.pid,hostname:U(),environment:$Q.env.NODE_ENV||"development",platform:$Q.platform,version:$Q.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$Q.env.NODE_ENV||$Q.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class hQ{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(Q,U={}){this.name=Q,this.config={...WU},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new LX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Z=U.timestamp!==void 0;if(Z)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let U={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return U[Q]>=U[X]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...CQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...CQ};return{...CQ,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:WU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}shouldWriteToFile(){return!N()&&this.config.writeToFile===!0}async writeToFile(Q){let X=(async()=>{let $,Y=0,G=3,J=1000;while(Y<G)try{try{try{await qZ(this.config.logDirectory,mU.F_OK|mU.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await _Z(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let H=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:m.from(Q);try{if(!wQ(this.currentLogFile))await aQ(this.currentLogFile,"",{mode:420});if($=uU(this.currentLogFile,"a",420),JZ($,H,{flag:"a"}),pU($),$!==void 0)rQ($),$=void 0;if((await XQ(this.currentLogFile)).size===0){if(await aQ(this.currentLogFile,H,{flag:"w",mode:420}),(await XQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(Y<G-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,A);let z=J*2**Y;await new Promise((W)=>setTimeout(W,z)),Y++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{rQ($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(H){if(Y===G-1){let _=H,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),H}Y++;let q=J*2**(Y-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(X);let Z=this.pendingOperations.length-1;try{await X}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 ZQ(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 ZQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return ZQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(N())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Z=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=X,this.keys.set(X,Z),this.encryptionKeys.set(X,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,J],[,H])=>H.createdAt.getTime()-J.createdAt.getTime()),Y=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,Y);if($.length>G)for(let[J]of $.slice(G))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return oQ(16).toString("hex")}generateKey(){return oQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:U}=this.getCurrentKey(),X=oQ(16),Z=YZ("aes-256-gcm",U,X),$=m.isBuffer(Q)?Q:m.from(Q,"utf8"),Y=Z.update($),G=Z.final(),J=Y.length+G.length,H=Z.getAuthTag(),q=m.allocUnsafe(16+J+16);return X.copy(q,0),Y.copy(q,16),G.copy(q,16+Y.length),H.copy(q,16+J),{encrypted:q,iv:X}}async compressData(Q){return new Promise((U,X)=>{let Z=cU(),$=[];Z.on("data",(Y)=>$.push(Y)),Z.on("end",()=>U(m.from(m.concat($)))),Z.on("error",X),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(N())return;if(!this.shouldWriteToFile())return;let Q=await XQ(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await KQ(this.config.logDirectory),Y=$.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,q)=>{let _=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${X}.${G}`;if(await XQ(X).catch(()=>null))try{if(await gU(X,J),U.compress)try{let H=`${J}.gz`;await this.compressLogFile(J,H),await jQ(J)}catch(H){console.error("Error compressing rotated file:",H)}if(Y.length===0&&!$.some((H)=>H.endsWith(".log.1")))try{let H=`${X}.1`;await aQ(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),Y=X.replace(/\.log$/,`-${$}.log`);if(await XQ(X).catch(()=>null))await gU(X,Y)}if(this.currentLogFile=Z,U.maxFiles){let Y=(await KQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,J)=>J.localeCompare(G));for(let G of Y.slice(U.maxFiles))await jQ(ZQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=fU(Q),Z=HZ(U),$=cU();await zZ(X,$,Z)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Z=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(U);console.log(U)}}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),wQ(this.currentLogFile))try{let Q=uU(this.currentLogFile,"r+");pU(Q),rQ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!N()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await KQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await jQ(ZQ(this.config.logDirectory,X))}catch(Z){console.error(`Failed to delete temp file ${X}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?w.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N())return!1;let Q=typeof R.env.NO_COLOR<"u",U=R.env.FORCE_COLOR==="0";if(Q||U)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Z="",message:$,level:Y,showTimestamp:G=!0}=Q,J=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let H=R.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${X} ${$}`;else if(Y==="info"||Y==="success")q=`${X} ${Z} ${$}`;else q=`${X} ${Z} ${w.cyan($)}`;if(!G)return q.trim();let _=J(q).trim().length,A=J(U).length,z=Math.max(1,H-2-_-A);return`${q.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,(Y,G)=>{let J=Number.parseInt(G,10);return J<U[0].length?String(U[0][J]):Y});let X=/%([sdijfo%])/g,Z=0,$=Q.replace(X,(Y,G)=>{if(G==="%")return"%";if(Z>=U.length)return Y;let J=U[Z++];switch(G){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 Y}});if(Z<U.length)$+=` ${U.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let U=Q;return U=U.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,Z,$)=>{let Y=w.underline(w.blue(Z)),G=this.toAbsoluteFilePath($);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let J=`file://${encodeURI(G)}`,H="\x1B]8;;",q="\x1B\\";return`\x1B]8;;${J}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),U=U.replace(/`([^`]+)`/g,(X,Z)=>w.bgGray(Z)),U=U.replace(/\*\*([^*]+)\*\*/g,(X,Z)=>w.bold(Z)),U=U.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,Z)=>w.italic(Z)),U=U.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,Z)=>w.italic(Z)),U=U.replace(/~([^~]+)~/g,(X,Z)=>w.strikethrough(Z)),U}supportsHyperlinks(){if(N())return!1;let Q=R.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let U=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(U)&&U>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let U=Q;if(U.startsWith("file://"))U=U.replace(/^file:\/\//,"");if(U.startsWith("~")){let X=R.env.HOME||"";if(X)U=U.replace(/^~(?=$|\/)/,X)}if(AZ(U)||U.startsWith("./")||U.startsWith("../"))U=WZ(U);else return null;return wQ(U)?U:null}catch{return null}}buildOutputTexts(Q){let U=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,X=Q.replace(this.ANSI_PATTERN,"");return{consoleText:U,fileText:X}}async log(Q,U,...X){let Z=new Date,$=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,J;if(U instanceof Error)G=U.message,J=U.stack;else G=this.formatMessage(U,X);let{consoleText:H,fileText:q}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":EX[Q],z=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:w.gray(H),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:w.green(H),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.error(W),J){let V=J.split(`
10
+ `);for(let B of V)if(B.trim()&&!B.includes(G))console.error(this.formatConsoleMessage({timestamp:$,message:w.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!N()){if(console.error(`${Y} ${this.environment}.${Q.toUpperCase()}: ${G}`),J)console.error(J)}if(!this.shouldLog(Q))return;let _=`${Y} ${this.environment}.${Q.toUpperCase()}: ${q}
11
+ `;if(J)_+=`${J}
12
+ `;if(_=_.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(_)}progress(Q,U=""){let X={update:(J,H)=>{},finish:(J)=>{},interrupt:(J,H)=>{}};if(!this.enabled)return X;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:U||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!N()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(J,H)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,J),this.activeProgressBar.total),H!==void 0)this.activeProgressBar.message=H;if(this.shouldStyleConsole()&&!N()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(J)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,J)},interrupt:(J,H="info")=>{if(!N()&&R.stdout.isTTY)R.stdout.write(`
13
+ `);if(this[H==="warning"?"warn":H](J),this.activeProgressBar&&this.shouldStyleConsole()&&!N()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let U=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":w.blue("◐"),tag:X,message:`${w.cyan(Q)}...`}))}return async(X)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-U),Y=`${Q} completed in ${$}ms`,G=new Date,J=this.formatConsoleTimestamp(G),q=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${Y}`;if(X)q+=` ${JSON.stringify(X)}`;if(q+=`
14
+ `,q=q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":w.green("✓"),tag:_,message:`${Y}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!N())console.error(q.trim());if(this.shouldWriteToFile())await this.writeToFile(q)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new hQ(U,{...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(X),X}createReadStream(){if(N())throw Error("createReadStream is not supported in browser environments");if(!wQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return fU(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Z=m.isBuffer(Q)?Q:m.from(Q,"base64"),$=Z.subarray(0,16),Y=Z.subarray(Z.length-16),G=Z.subarray(16,Z.length-16),J=GZ("aes-256-gcm",X,$);J.setAuthTag(Y);let H=J.update(G),q=J.final(),_=H.length+q.length,A=m.allocUnsafe(_);return H.copy(A,0),q.copy(A,H.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N()}isServerMode(){return!N()}setTestEncryptionKey(Q,U){this.currentKeyId=Q,this.keys.set(Q,U)}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(Q){if(!this.enabled)return;let U=new Date,X=this.formatConsoleTimestamp(U),Z=this.formatFileTimestamp(U),{consoleText:$,fileText:Y}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let J=$.split(`
15
+ `),H=Math.max(...J.map((z)=>z.length))+2,q=`┌${"─".repeat(H)}┐`,_=`└${"─".repeat(H)}┘`,A=J.map((z)=>{return this.formatConsoleMessage({timestamp:X,message:w.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:w.cyan(q),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:X,message:w.cyan(_),showTimestamp:!1}))}else if(!N())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Y}`);let G=`${Z} ${this.environment}.INFO: [BOX] ${Y}
16
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(N())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${w.cyan("?")} ${Q} (y/n) `);let X=(Z)=>{let $=Z.toString().trim().toLowerCase();R.stdin.removeListener("data",X);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),U($==="y"||$==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let H=/%([sdijfo%])/g,q=0;if(X=Q.replace(H,(_,A)=>{if(A==="%")return"%";if(q>=U.length)return _;let z=U[q++];switch(A){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 _}}),q<U.length)X+=` ${U.slice(q).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let H=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",q=this.options.showIcons===!1?"":`${w.blue("◐")} `;console.error(`${q}${H} ${w.cyan(Z)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(Q,U=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*X/100),$=Q.barLength-Z,Y=w.green("━".repeat(Z)),G=w.gray("━".repeat($)),J=`[${Y}${G}]`,H=`${X}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=this.options.showIcons===!1?"":U||X===100?w.green("✓"):w.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${J} ${H}${q}`,W=R.stdout.columns||80,V=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${V}`,R.stdout.write(Q.lastRenderedLine),U)R.stdout.write(`
18
+ `)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||N()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(N()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await KQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=ZQ(this.config.logDirectory,Z);if(Q.before)try{if((await XQ(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await jQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}async function wX(Q,U={}){let{maxRetries:X=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:Y}=U,G=Error("Unknown error occurred");for(let J=0;J<=X;J++)try{return await Q()}catch(H){if(G=H instanceof Error?H:Error(String(H)),J===X||!$(G))break;if(Z>0)await new Promise((q)=>setTimeout(q,Z))}if(Y!==void 0)return Y;throw G instanceof Error?G:Error(`Unknown error: ${String(G)}`)}function KX(Q){return Q instanceof v}function kZ(Q){return Q instanceof dQ}function xZ(Q){if(KX(Q))return Q.code==="FILE_SYSTEM_ERROR"||Q.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((X)=>Q.message.toLowerCase().includes(X.toLowerCase()))}class mQ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,U)=>U==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let U=Q.toLowerCase();return["true","1","yes"].includes(U)}},{name:"number",canParse:(Q,U)=>U==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let U=Number(Q);if(Number.isNaN(U))throw TypeError(`Cannot parse "${Q}" as number`);return U}},{name:"array",canParse:(Q,U)=>U==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let U=JSON.parse(Q);if(Array.isArray(U))return U}catch{}return Q.split(",").map((U)=>U.trim())}},{name:"json",canParse:(Q,U)=>U==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(U){throw Error(`Cannot parse "${Q}" as JSON: ${U}`)}}}]}async applyEnvironmentVariables(Q,U,X={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:Y=!0,customParsers:G={},verbose:J=!1,trackPerformance:H=!0}=X,q=async()=>{if(!Q)return{config:U,source:{type:"environment",priority:50,timestamp:new Date}};let _=Z||this.generateEnvPrefix(Q),A={...U};return this.processObject(A,[],_,{useCamelCase:$,useBackwardCompatibility:Y,customParsers:G,verbose:J,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(H)return zQ.track("applyEnvironmentVariables",q,{configName:Q});return q()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,U){if(!U)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,U,X,Z){for(let[$,Y]of Object.entries(Q)){let G=[...U,$],J=G.map((_)=>this.formatEnvKey(_,Z.useCamelCase)),H=`${X}_${J.join("_")}`,q=Z.useBackwardCompatibility?`${X}_${G.map((_)=>_.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,G,X,Z);else{let _=FQ.env[H]||(q?FQ.env[q]:void 0);if(_!==void 0){if(Z.verbose){let A=FQ.env[H]?H:q}try{Q[$]=this.parseEnvironmentValue(_,typeof Y,H,Z.customParsers,Z.configName)}catch(A){if(A instanceof fQ)throw A;throw o.envVar(H,_,typeof Y,Z.configName)}}}}}parseEnvironmentValue(Q,U,X,Z,$){for(let[Y,G]of Object.entries(Z))try{return G(Q)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse(Q,U))try{return Y.parse(Q)}catch{throw o.envVar(X,Q,`${U} (via ${Y.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let U={},X=Q.toUpperCase();for(let[Z,$]of Object.entries(FQ.env))if(Z.startsWith(X)&&$!==void 0)U[Z]=$;return U}validateEnvironmentVariable(Q,U,X){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Z.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(X)try{this.parseEnvironmentValue(Q,U,X,{})}catch($){Z.push(`Cannot parse value "${U}" as ${X}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,U,X={}){let{prefix:Z,format:$="text"}=X,Y=Z||this.generateEnvPrefix(Q),G=[];switch(this.extractEnvVarInfo(U,[],Y,G),$){case"markdown":return this.formatAsMarkdown(G,Q);case"json":return JSON.stringify(G,null,2);default:return this.formatAsText(G,Q)}}extractEnvVarInfo(Q,U,X,Z){for(let[$,Y]of Object.entries(Q)){let G=[...U,$],J=`${X}_${G.map((H)=>this.formatEnvKey(H,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,G,X,Z);else Z.push({key:J,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${G.join(".")}`,example:this.generateExample(Y)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,U){let X=`Environment Variables for ${U}:
19
+
20
+ `;for(let Z of Q)X+=`${Z.key}
21
+ `,X+=` Type: ${Z.type}
22
+ `,X+=` Description: ${Z.description}
23
+ `,X+=` Example: ${Z.example}
24
+
25
+ `;return X}formatAsMarkdown(Q,U){let X=`# Environment Variables for ${U}
26
+
27
+ `;X+=`| Variable | Type | Description | Example |
28
+ `,X+=`|----------|------|-------------|----------|
29
+ `;for(let Z of Q)X+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
30
+ `;return X}}function PZ(Q,U){let X=VX("process");if(typeof X>"u"||!X.env)return U;let Z=X.env[Q];return Z!==void 0?Z:U}function jX(Q,U,X={}){return FX(Q,U,X,new WeakMap)}function FX(Q,U,X,Z){let{arrayMergeMode:$="replace",skipNullish:Y=!1,customMerger:G}=X;if(U===null||U===void 0)return Y?Q:U;if(G){let J=G(Q,U);if(J!==void 0)return J}if(Array.isArray(U)||Array.isArray(Q))return IX(Q,U,$,Z);if(!h(U)||!h(Q))return U;return hZ(Q,U,X,Z)}function IX(Q,U,X,Z){if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(Q)&&!Array.isArray(U))return U;if(Array.isArray(U)&&Array.isArray(Q))switch(X){case"replace":return U;case"concat":return bZ(Q,U);case"smart":return yZ(Q,U,Z);default:return U}return U}function bZ(Q,U){let X=[...U];for(let Z of Q)if(!X.some(($)=>_U($,Z)))X.push(Z);return X}function yZ(Q,U,X){if(U.length===0)return Q;if(Q.length===0)return U;if(h(U[0])&&h(Q[0]))return vZ(Q,U,X);if(U.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...U];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return U}function vZ(Q,U,X){let Z=[...U];for(let $ of Q){if(!h($)){Z.push($);continue}let Y=["id","name","key","path","type"],G=!1;for(let J of Y)if(J in $){if(Z.find((q)=>h(q)&&(J in q)&&q[J]===$[J])){G=!0;break}}if(!G)Z.push($)}return Z}function hZ(Q,U,X,Z){let $=U;if(h($)&&Z.has($))return Z.get($);let Y={...Q};if(h($))Z.set($,Y);for(let G in $){if(!Object.prototype.hasOwnProperty.call($,G))continue;let J=$[G],H=Y[G];if(X.skipNullish&&(J===null||J===void 0))continue;if(J===null||J===void 0){Y[G]=J;continue}if(h(J)&&h(H))Y[G]=FX(H,J,X,Z);else if(Array.isArray(J)||Array.isArray(H))Y[G]=IX(H,J,X.arrayMergeMode||"smart",Z);else Y[G]=J}return Y}function VU(Q,U,X="replace"){return jX(Q,U,{arrayMergeMode:X==="replace"?"replace":"smart",skipNullish:!0})}function _U(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!_U(Q[X],U[X]))return!1;return!0}if(h(Q)&&h(U)){let X=Object.keys(Q),Z=Object.keys(U);if(X.length!==Z.length)return!1;for(let $ of X){if(!Object.prototype.hasOwnProperty.call(U,$))return!1;if(!_U(Q[$],U[$]))return!1}return!0}return!1}function h(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class gQ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,U,X={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:Y,trackPerformance:G=!0,verbose:J=!1}=X;if($){let q=JQ.getWithFileCheck("file",Q);if(q){if(J)console.log(`Configuration loaded from cache: ${Q}`);return q}}let H=async()=>{if(!IQ(Q))return null;try{let q=`?t=${Date.now()}`,_=await import(Q+q),A=_.default||_,z="default"in _,W=Object.keys(_).length>0;if(!z&&!W)throw new AQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new AQ(Q,Error("Configuration must export a valid object"),"unknown");let F={config:VU(U,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)JQ.setWithFileCheck("file",F,Q,Y);return F}catch(q){throw q instanceof Error?o.configLoad(Q,q):o.configLoad(Q,Error(String(q)))}};if(G)return zQ.track("loadFromPath",H,{path:Q});return H()}async tryLoadFromPaths(Q,U,X={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,U,X);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(X.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,U,X){let Z=this.generateNamePatterns(Q,X),$=[];for(let Y of Z)for(let G of this.extensions)$.push(tQ(U,`${Y}${G}`));return $}generateNamePatterns(Q,U){let X=[];if(X.push("config",".config"),Q)X.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(U){if(X.push(U,`.${U}.config`,`${U}.config`,`.${U}`),Q)X.push(`${Q}.${U}.config`,`.${Q}.${U}.config`)}return X.filter(Boolean)}checkFileAccess(Q){return wX(async()=>{return IQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,U,X){let Z=[];if(!IQ(Q))return Z;if(U||X){let $=this.generateNamePatterns(U||"",X);for(let Y of $)for(let G of this.extensions){let J=tQ(Q,`${Y}${G}`);if(await this.checkFileAccess(J))Z.push(J)}}else try{let{readdirSync:$}=await import("fs"),Y=$(Q);for(let G of Y)if(this.looksLikeConfigFile(G)){let J=tQ(Q,G);if(await this.checkFileAccess(J))Z.push(J)}}catch{return[]}return Z}looksLikeConfigFile(Q){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((X)=>X.test(Q))}async validateConfigFile(Q){let U=[];try{if(!IQ(Q))return U.push("Configuration file does not exist"),U;let X=await import(Q),Z=X.default||X;if(Z===void 0)U.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)U.push("Configuration must be an object");else if(Array.isArray(Z))U.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),Y=$(Q,"utf8");JSON.parse(Y)}catch($){U.push(`Invalid JSON syntax: ${$}`)}}catch(X){U.push(`Failed to load configuration file: ${X}`)}return U}async getFileModificationTime(Q){try{let{statSync:U}=await import("fs");return U(Q).mtime}catch{return null}}async preloadConfigurations(Q,U={}){let X=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},U);if($)X.set(Z,$.config)}catch($){if(U.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),X}}class DU{async validateConfiguration(Q,U,X={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:Y=!0,customRules:G=[],trackPerformance:J=!0,verbose:H=!1}=X,q=async()=>{let _=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:Y,customRules:G,trackPerformance:J,verbose:H};try{if(typeof U==="string")return await this.validateWithSchemaFile(Q,U,z);else if(Array.isArray(U))return this.validateWithRules(Q,[...U,...G],z);else return this.validateWithJSONSchema(Q,U,z)}catch(W){return _.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:_,warnings:A}}};if(J)return await zQ.track("validateConfiguration",q);return q()}async validateWithSchemaFile(Q,U,X){try{if(!BZ(U))throw new WQ(U,[{path:"",message:"Schema file does not exist"}]);let Z=await import(U),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,X);else return this.validateWithJSONSchema(Q,$,X)}catch(Z){throw new WQ(U,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,U,X){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,U,"",Z,$,X),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,U,X,Z,$,Y){if(Y.validateTypes&&U.type){let G=Array.isArray(Q)?"array":typeof Q,J=Array.isArray(U.type)?U.type:[U.type];if(!J.includes(G)){if(Z.push({path:X,message:`Expected type ${J.join(" or ")}, got ${G}`,expected:J.join(" or "),actual:G,rule:"type"}),Y.stopOnFirstError)return}}if(U.enum&&!U.enum.includes(Q)){if(Z.push({path:X,message:`Value must be one of: ${U.enum.join(", ")}`,expected:U.enum.join(", "),actual:Q,rule:"enum"}),Y.stopOnFirstError)return}if(typeof Q==="string"){if(U.minLength!==void 0&&Q.length<U.minLength)Z.push({path:X,message:`String length must be at least ${U.minLength}`,expected:`>= ${U.minLength}`,actual:Q.length,rule:"minLength"});if(U.maxLength!==void 0&&Q.length>U.maxLength)Z.push({path:X,message:`String length must not exceed ${U.maxLength}`,expected:`<= ${U.maxLength}`,actual:Q.length,rule:"maxLength"});if(U.pattern){if(!new RegExp(U.pattern).test(Q))Z.push({path:X,message:`String does not match pattern ${U.pattern}`,expected:U.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(U.minimum!==void 0&&Q<U.minimum)Z.push({path:X,message:`Value must be at least ${U.minimum}`,expected:`>= ${U.minimum}`,actual:Q,rule:"minimum"});if(U.maximum!==void 0&&Q>U.maximum)Z.push({path:X,message:`Value must not exceed ${U.maximum}`,expected:`<= ${U.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&U.items)for(let G=0;G<Q.length;G++){let J=X?`${X}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema(Q[G],U.items,J,Z,$,Y),Y.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let G=Q;if(Y.validateRequired&&U.required){for(let J of U.required)if(!(J in G)){if(Z.push({path:X?`${X}.${J}`:J,message:`Missing required property '${J}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(U.properties){for(let[J,H]of Object.entries(U.properties))if(J in G){let q=X?`${X}.${J}`:J;if(this.validateObjectAgainstSchema(G[J],H,q,Z,$,Y),Y.stopOnFirstError&&Z.length>0)return}}if(U.additionalProperties===!1){let J=new Set(Object.keys(U.properties||{}));for(let H of Object.keys(G))if(!J.has(H))$.push({path:X?`${X}.${H}`:H,message:`Additional property '${H}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,U,X){let Z=[],$=[];for(let Y of U)try{let G=this.getValueByPath(Q,Y.path),J=this.validateWithRule(G,Y,Y.path);if(Z.push(...J),X.stopOnFirstError&&Z.length>0)break}catch(G){Z.push({path:Y.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,U,X){let Z=[];if(U.required&&(Q===void 0||Q===null))return Z.push({path:X,message:U.message||`Property '${X}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(U.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==U.type)Z.push({path:X,message:U.message||`Expected type ${U.type}, got ${$}`,expected:U.type,actual:$,rule:"type"})}if(U.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<U.min)Z.push({path:X,message:U.message||`Value must be at least ${U.min}`,expected:`>= ${U.min}`,actual:$,rule:"min"})}if(U.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>U.max)Z.push({path:X,message:U.message||`Value must not exceed ${U.max}`,expected:`<= ${U.max}`,actual:$,rule:"max"})}if(U.pattern&&typeof Q==="string"){if(!U.pattern.test(Q))Z.push({path:X,message:U.message||`Value does not match pattern ${U.pattern}`,expected:U.pattern.toString(),actual:Q,rule:"pattern"})}if(U.enum&&!U.enum.includes(Q))Z.push({path:X,message:U.message||`Value must be one of: ${U.enum.join(", ")}`,expected:U.enum.join(", "),actual:Q,rule:"enum"});if(U.validator){let $=U.validator(Q);if($)Z.push({path:X,message:U.message||$,rule:"custom"})}return Z}getValueByPath(Q,U){if(!U)return Q;let X=U.split("."),Z=Q;for(let $ of X)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let U=[],X=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of X){let[,$,Y,G]=Z;U.push({path:$,required:!Y,type:this.mapTypeScriptType(G)})}return U}mapTypeScriptType(Q){switch(Q.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:TX},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class NU{fileLoader=new gQ;envProcessor=new mQ;validator=new DU;async loadConfig(Q){let U=Date.now(),{cache:X,performance:Z,schema:$,validate:Y,...G}=Q;try{if(X?.enabled){let H=this.checkCache(G.name||"",G);if(H)return H}let J;try{J=await this.loadConfigurationStrategies(G,!0,X)}catch(H){let q=G.__strictErrorHandling;if(H instanceof Error&&H.name==="ConfigNotFoundError"){if(q)throw H;J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`No configuration file found for "${G.name||"config"}", using defaults with environment variables`]}}else if(H instanceof Error&&H.name==="ConfigLoadError"){let _=H.message.includes("EACCES")||H.message.includes("EPERM")||H.message.includes("permission denied"),A=!_&&(H.message.includes("syntax")||H.message.includes("Expected")||H.message.includes("Unexpected")||H.message.includes("BuildMessage")||H.message.includes("errors building")),z=H.message.includes("Configuration must export a valid object")||H.message.includes("Configuration file is empty and exports nothing");if(q&&(z||_))throw H;if(A&&(!q||!z))J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!q)J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${H.message}`]};else throw H}else J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${H instanceof Error?H.message:String(H)}`]}}if($||Y)await this.validateConfiguration(J.config,$,Y,G.name);if(X?.enabled&&J)this.cacheResult(G.name||"",J,X,G);if(Z?.enabled){let H={operation:"loadConfig",duration:Date.now()-U,configName:G.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(H);if(Z.slowThreshold&&H.duration>Z.slowThreshold)f.warn(`Slow configuration loading detected: ${H.duration}ms for ${G.name}`);J.metrics=H}return J}catch(J){let H=Date.now()-U;throw f.error(`Configuration loading failed after ${H}ms:`,[J instanceof Error?J:Error(String(J))]),J}}async loadConfigurationStrategies(Q,U=!1,X){let{name:Z="",alias:$,cwd:Y,configDir:G,defaultConfig:J,checkEnv:H=!0,arrayStrategy:q="replace",verbose:_=!1}=Q,A=Y||a.cwd(),z=[],W=await this.loadLocalConfiguration(Z,$,A,G,J,q,_,H,X);if(W)return z.push(...this.getLocalSearchPaths(Z,$,A,G)),this.finalizeResult(W,z,H,Z,_);let V=await this.loadHomeConfiguration(Z,$,J,q,_,H);if(V)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(V,z,H,Z,_);let B=await this.loadPackageJsonConfiguration(Z,$,A,J,q,_,H);if(B)return z.push(y(A,"package.json")),this.finalizeResult(B,z,H,Z,_);if(z.push(...this.getAllSearchPaths(Z,$,A,G)),U)throw o.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,J,H,_),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,U,X,Z,$,Y,G,J,H){let q=J?qQ(Q,$,G):$,_=this.getLocalDirectories(X,Z);for(let A of _){if(G)f.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,U),W=await this.fileLoader.tryLoadFromPaths(z,q,{arrayStrategy:Y,verbose:G,cacheTtl:H?.ttl,useCache:!H?.ttl||H.ttl>100});if(W){if(G)f.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,U,X,Z,$,Y){if(!Q)return null;let G=Y?qQ(Q,X,$):X,J=[y(t(),".config",Q),y(t(),".config"),t()];for(let H of J){if($)f.info(`Checking home directory: ${H}`);let q=this.fileLoader.generateConfigPaths(Q,H,U),_=await this.fileLoader.tryLoadFromPaths(q,G,{arrayStrategy:Z,verbose:$});if(_){if($)f.success(`Configuration loaded from home directory: ${_.source.path}`);return _}}return null}async loadPackageJsonConfiguration(Q,U,X,Z,$,Y,G){let J=G?qQ(Q,Z,Y):Z;try{let H=y(X,"package.json");if(!JU(H))return null;let q=await import(H),_=q[Q],A=Q;if(!_&&U)_=q[U],A=U;if(_&&typeof _==="object"&&!Array.isArray(_)){if(Y)f.success(`Configuration loaded from package.json: ${A}`);return{config:VU(J,_,$),source:{type:"package.json",path:H,priority:30,timestamp:new Date}}}}catch(H){if(Y)f.warn("Failed to load package.json:",[H instanceof Error?H:Error(String(H))])}return null}async applyEnvironmentVariables(Q,U,X,Z){if(!X||!Q||typeof U!=="object"||U===null||Array.isArray(U))return{config:U,source:{type:"default",priority:10,timestamp:new Date}};return{config:qQ(Q,U,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,U,X,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,U,X,Z){let $=[];if(X){let Y=X(Q);if(Y)$.push(...Y)}if(U){let Y=await this.validator.validateConfiguration(Q,U);if(!Y.isValid)$.push(...Y.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if($.length>0)throw o.configValidation(Z||"unknown",$,Z)}checkCache(Q,U){let X=this.generateCacheKey(Q,U);return JQ.get(X)||null}cacheResult(Q,U,X,Z){let $=this.generateCacheKey(Q,Z);JQ.set($,U,void 0,X.ttl)}generateCacheKey(Q,U){let X=[Q];if(U.alias)X.push(`alias:${U.alias}`);if(U.cwd)X.push(`cwd:${U.cwd}`);if(U.configDir)X.push(`configDir:${U.configDir}`);if("checkEnv"in U)X.push(`checkEnv:${U.checkEnv}`);return X.join("|")}getLocalDirectories(Q,U){return Array.from(new Set([Q,y(Q,"config"),y(Q,".config"),U?y(Q,U):void 0].filter(Boolean)))}getAllSearchPaths(Q,U,X,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,U,X,Z)),$.push(...this.getHomeSearchPaths(Q,U)),$.push(y(X,"package.json")),$}getLocalSearchPaths(Q,U,X,Z){let $=this.getLocalDirectories(X,Z),Y=[];for(let G of $)Y.push(...this.fileLoader.generateConfigPaths(Q,G,U));return Y}getHomeSearchPaths(Q,U){if(!Q)return[];let X=[y(t(),".config",Q),y(t(),".config"),t()],Z=[];for(let $ of X)Z.push(...this.fileLoader.generateConfigPaths(Q,$,U));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function nU(Q){let X=!(Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"))&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")),Z=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");return X||Z}async function dZ(Q){return i.loadConfig({...Q,__strictErrorHandling:!0})}async function MX(Q){let U="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},X="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(X)Z=await i.loadConfig(Q);else Z=await i.loadConfig({...Q,defaultConfig:U,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??U}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",Y=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||Y.includes("config"))&&Q.verbose)f.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let J=X?{...Q,defaultConfig:U}:{...Q,defaultConfig:U,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await i.applyEnvironmentVariables(J.name||"",U,!0,J.verbose||!1))?.config??U;return U}}async function fZ(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:U}=await import("process");try{return(await i.loadConfig({name:Q,cwd:U(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&nU(X)))return(await i.applyEnvironmentVariables(Q,{},!0,!1)).config;throw X}}try{return(await i.loadConfig({...Q,cwd:Q.cwd||a.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(U){if(U instanceof Error&&(U.name==="ConfigNotFoundError"||U.name==="ConfigLoadError"&&nU(U)))return(await i.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw U}}async function pZ(Q,U,X="replace"){let Z=new gQ;try{let $=await Z.loadFromPath(Q,U,{arrayStrategy:X,useCache:!1,trackPerformance:!1});return $?$.config:null}catch{return null}}function qQ(Q,U,X=!1){let Z=new mQ,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(G,J=[]){let H={...G};for(let[q,_]of Object.entries(G)){let A=[...J,q],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,V;for(let B of z)if(W=a.env[B],W!==void 0){V=B;break}if(W!==void 0&&V)if(typeof _==="boolean")H[q]=["true","1","yes"].includes(W.toLowerCase());else if(typeof _==="number"){let B=Number(W);if(!Number.isNaN(B))H[q]=B}else if(Array.isArray(_))try{H[q]=JSON.parse(W)}catch{H[q]=W.split(",").map((B)=>B.trim())}else H[q]=W;else if(_&&typeof _==="object"&&!Array.isArray(_))H[q]=Y(_,A)}return H}return Y(U)}function uZ(Q){let U=y(a.cwd(),Q.configDir),X=y(a.cwd(),Q.generatedDir),Z=y(X,"config-types.ts");if(!JU(CU(Z)))lX(CU(Z),{recursive:!0,mode:511});let $=JU(U)?nX(U).map((G)=>G.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${L0}
31
+ export type ConfigNames = ${$.length?`'${$.join("' | '")}'`:"string"}
32
+ `;iX(Z,Y,{mode:438})}function mZ(Q){let U=null,X=null,Z=()=>{if(!X)X=MX(Q).then((Y)=>{return U=Y,Y},(Y)=>{let G="defaultConfig"in Q?Q.defaultConfig:{};if(U=G,"verbose"in Q&&Q.verbose)f.warn("Config loading failed, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);return G});return X},$="defaultConfig"in Q?Q.defaultConfig:{};return U=$,Z(),new Proxy({},{get(Y,G){if(U)return U[G];let J=$[G];return Z(),J},has(Y,G){return G in(U||$)},ownKeys(){return Object.keys(U||$)},getOwnPropertyDescriptor(Y,G){return Object.getOwnPropertyDescriptor(U||$,G)},set(Y,G,J){if(!U)U={...$};return U[G]=J,!0}})}function gZ(Q){let U=lU(wZ.cwd(),Q?.configDir||"./config");function X(){if(!RZ(U))return[];let $=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),Y=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],G=LZ(U).filter((H)=>$.has(eQ(H))).map((H)=>({base:H.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:H})),J=new Map;for(let{base:H,file:q}of G){let _=eQ(q).toLowerCase(),A=J.get(H);if(!A){J.set(H,q);continue}let z=eQ(A).toLowerCase();if(Y.indexOf(_)<Y.indexOf(z))J.set(H,q)}return Array.from(J.entries()).map(([H,q])=>({base:H,file:q})).sort((H,q)=>H.base.localeCompare(q.base))}function Z(){let $=X(),Y=$.map((q)=>q.base),G=Y.length?Y.map((q)=>`'${q}'`).join(" | "):"string",J=$.length?`{
33
+ ${$.map((q)=>{let _=lU(U,q.file).replace(/\\/g,"/");return` '${q.base}': typeof import('${_}').default`}).join(`,
34
+ `)}
35
+ }`:"Record<string, any>";return`export type ConfigNames = ${G}
36
+ export type ConfigByName = ${J}
37
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
38
+ export type ConfigOf = Config
39
+ `}return{name:"bunfig-plugin",setup($){$.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),$.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var VX,JQ,zQ,DX,cZ,lZ,iU,OQ,AU,C,I,nZ,sU,iZ,oU,sZ,oZ,QU,rZ,rU,aU,UU,aZ,tZ,eZ,Q0,TQ,NX,U0,k,X0,Z0,tU,SQ,WU,E,w,$0,eU,Y0,QX,G0,H0,XU,J0,UX,XX,q0,ZU,_0,A0,W0,z0,B0,CQ,EX,R0,L0="0.15.6",v,dQ,AQ,zU,BU,fQ,RU,LU,WQ,wU,KU,o,OX,TX,f,i,SX,CX,w0=cX(async()=>{VX=import.meta.require,JQ=new jU,zQ=new FU,DX={createKey:KZ,isEquivalent:jZ,estimateMemoryUsage:FZ},cZ=PQ(qU.cwd(),"config"),lZ=PQ(qU.cwd(),"src/generated"),iU=xQ.env.CLARITY_LOG_DIR||rX(VZ(),"logs"),OQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:iU,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},AU=await DZ(),C={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},I=C,nZ=C.red,sU=C.green,iZ=C.yellow,oU=C.blue,sZ=C.magenta,oZ=C.cyan,QU=C.white,rZ=C.gray,rU=C.bgRed,aU=C.bgYellow,UU=C.bold,aZ=C.dim,tZ=C.italic,eZ=C.underline,Q0=C.reset,TQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},NX={debug:"\uD83D\uDD0D",info:oU("ℹ"),success:sU("✓"),warning:aU(QU(UU(" WARN "))),error:rU(QU(UU(" ERROR ")))},U0=new yQ("stacks"),k=new yQ("bunfig",{showTags:!0}),X0=b(_Q.cwd(),"config"),Z0=b(_Q.cwd(),"src/generated"),tU=kQ.env.CLARITY_LOG_DIR||sX(TZ(),"logs"),SQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:tU,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},WU=await SZ(),E={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},w=E,$0=E.red,eU=E.green,Y0=E.yellow,QX=E.blue,G0=E.magenta,H0=E.cyan,XU=E.white,J0=E.gray,UX=E.bgRed,XX=E.bgYellow,q0=E.bgGray,ZU=E.bold,_0=E.dim,A0=E.italic,W0=E.underline,z0=E.strikethrough,B0=E.reset,CQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EX={debug:"\uD83D\uDD0D",info:QX("ℹ"),success:eU("✓"),warning:XX(XU(ZU(" WARN "))),error:UX(XU(ZU(" ERROR ")))},R0=new hQ("stacks"),v=class extends Error{timestamp;context;constructor(U,X={}){super(U);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,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 U=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,Z])=>`${X}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${U}`}},dQ=class extends v{code="CONFIG_NOT_FOUND";constructor(U,X,Z){let $=Z?` or alias "${Z}"`:"";super(`Configuration "${U}"${$} not found`,{configName:U,alias:Z,searchPaths:X,searchPathCount:X.length})}},AQ=class extends v{code="CONFIG_LOAD_ERROR";constructor(U,X,Z){super(`Failed to load configuration from "${U}": ${X.message}`,{configPath:U,configName:Z,originalError:X.name,originalMessage:X.message});this.cause=X}},zU=class extends v{code="CONFIG_VALIDATION_ERROR";constructor(U,X,Z){super(`Configuration validation failed for "${U}"`,{configPath:U,configName:Z,validationErrors:X,errorCount:X.length})}},BU=class extends v{code="CONFIG_MERGE_ERROR";constructor(U,X,Z,$){super(`Failed to merge configuration from "${U}" with "${X}": ${Z.message}`,{sourcePath:U,targetPath:X,configName:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},fQ=class extends v{code="ENV_VAR_ERROR";constructor(U,X,Z,$){super(`Failed to parse environment variable "${U}" with value "${X}" as ${Z}`,{envKey:U,envValue:X,expectedType:Z,configName:$})}},RU=class extends v{code="FILE_SYSTEM_ERROR";constructor(U,X,Z){super(`File system ${U} failed for "${X}": ${Z.message}`,{operation:U,path:X,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},LU=class extends v{code="TYPE_GENERATION_ERROR";constructor(U,X,Z){super(`Failed to generate types from "${U}" to "${X}": ${Z.message}`,{configDir:U,outputPath:X,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},WQ=class extends v{code="SCHEMA_VALIDATION_ERROR";constructor(U,X,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:U,configName:Z,validationErrors:X,errorCount:X.length})}},wU=class extends v{code="BROWSER_CONFIG_ERROR";constructor(U,X,Z,$){super(`Failed to fetch configuration from "${U}": ${X} ${Z}`,{endpoint:U,status:X,statusText:Z,configName:$})}},KU=class extends v{code="PLUGIN_ERROR";constructor(U,X,Z){super(`Plugin "${U}" failed during ${X}: ${Z.message}`,{pluginName:U,operation:X,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},o={configNotFound(Q,U,X){return new dQ(Q,U,X)},configLoad(Q,U,X){return new AQ(Q,U,X)},configValidation(Q,U,X){return new zU(Q,U,X)},configMerge(Q,U,X,Z){return new BU(Q,U,X,Z)},envVar(Q,U,X,Z){return new fQ(Q,U,X,Z)},fileSystem(Q,U,X){return new RU(Q,U,X)},typeGeneration(Q,U,X){return new LU(Q,U,X)},schemaValidation(Q,U,X){return new WQ(Q,U,X)},browserConfig(Q,U,X,Z){return new wU(Q,U,X,Z)},plugin(Q,U,X){return new KU(Q,U,X)}},OX={replace:"replace",concat:"concat",smart:"smart"},TX=/^https?:\/\//,f=new hQ("bunfig",{showTags:!0}),i=new NU,SX=y(a.cwd(),"config"),CX=y(a.cwd(),"src/generated")});function F0(Q,U={}){let X=pQ.cwd();while(X.includes("storage"))X=ZX(X,"..");let Z=ZX(X,Q||"");if(U?.relative)return j0(pQ.cwd(),Z);return Z}var I0=pQ.env.CLARITY_LOG_DIR||K0(F0(),"logs"),kX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:I0,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},uQ={...kX},g7=(async()=>{try{let{loadConfig:Q}=await w0().then(()=>WX),U=await Q({name:"clarity",alias:"logging",defaultConfig:kX,cwd:pQ.cwd()});if(U)Object.assign(uQ,U)}catch{}return uQ})();function O(){if(n.env.NODE_ENV==="test"||n.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function k0(){if(n.env.NODE_ENV==="test"||n.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n<"u"){let Q=n.type;if(Q==="renderer"||Q==="worker")return!1;return!!(n.versions&&(n.versions.node||n.versions.bun))}return!1}class xX{async format(Q){let U=await k0(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:HQ.pid,hostname:U(),environment:HQ.env.NODE_ENV||"development",platform:HQ.platform,version:HQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:HQ.env.NODE_ENV||HQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var T={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},K=T,Q8=T.red,x0=T.green,U8=T.yellow,P0=T.blue,X8=T.magenta,Z8=T.cyan,_X=T.white,$8=T.gray,b0=T.bgRed,y0=T.bgYellow,Y8=T.bgGray,AX=T.bold,G8=T.dim,H8=T.italic,J8=T.underline,q8=T.strikethrough,_8=T.reset,HU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},v0={debug:"\uD83D\uDD0D",info:P0("ℹ"),success:x0("✓"),warning:y0(_X(AX(" WARN "))),error:b0(_X(AX(" ERROR ")))};class BQ{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(Q,U={}){this.name=Q,this.config={...uQ},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new xX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??L.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Z=U.timestamp!==void 0;if(Z)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let U={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return U[Q]>=U[X]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...HU,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...HU};return{...HU,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:uQ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}shouldWriteToFile(){return!O()&&this.config.writeToFile===!0}async writeToFile(Q){let X=(async()=>{let $,Y=0,G=3,J=1000;while(Y<G)try{try{try{await E0(this.config.logDirectory,HX.F_OK|HX.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await O0(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let H=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:g.from(Q);try{if(!VQ(this.currentLogFile))await GU(this.currentLogFile,"",{mode:420});if($=GX(this.currentLogFile,"a",420),N0($,H,{flag:"a"}),YX($),$!==void 0)YU($),$=void 0;if((await YQ(this.currentLogFile)).size===0){if(await GU(this.currentLogFile,H,{flag:"w",mode:420}),(await YQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(Y<G-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,A);let z=J*2**Y;await new Promise((W)=>setTimeout(W,z)),Y++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{YU($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(H){if(Y===G-1){let _=H,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),H}Y++;let q=J*2**(Y-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(X);let Z=this.pendingOperations.length-1;try{await X}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 GQ(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 GQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return GQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(O())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Z=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=X,this.keys.set(X,Z),this.encryptionKeys.set(X,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,J],[,H])=>H.createdAt.getTime()-J.createdAt.getTime()),Y=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,Y);if($.length>G)for(let[J]of $.slice(G))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return $U(16).toString("hex")}generateKey(){return $U(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:U}=this.getCurrentKey(),X=$U(16),Z=M0("aes-256-gcm",U,X),$=g.isBuffer(Q)?Q:g.from(Q,"utf8"),Y=Z.update($),G=Z.final(),J=Y.length+G.length,H=Z.getAuthTag(),q=g.allocUnsafe(16+J+16);return X.copy(q,0),Y.copy(q,16),G.copy(q,16+Y.length),H.copy(q,16+J),{encrypted:q,iv:X}}async compressData(Q){return new Promise((U,X)=>{let Z=qX(),$=[];Z.on("data",(Y)=>$.push(Y)),Z.on("end",()=>U(g.from(g.concat($)))),Z.on("error",X),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(O())return;if(!this.shouldWriteToFile())return;let Q=await YQ(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await DQ(this.config.logDirectory),Y=$.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,q)=>{let _=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${X}.${G}`;if(await YQ(X).catch(()=>null))try{if(await JX(X,J),U.compress)try{let H=`${J}.gz`;await this.compressLogFile(J,H),await NQ(J)}catch(H){console.error("Error compressing rotated file:",H)}if(Y.length===0&&!$.some((H)=>H.endsWith(".log.1")))try{let H=`${X}.1`;await GU(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),Y=X.replace(/\.log$/,`-${$}.log`);if(await YQ(X).catch(()=>null))await JX(X,Y)}if(this.currentLogFile=Z,U.maxFiles){let Y=(await DQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,J)=>J.localeCompare(G));for(let G of Y.slice(U.maxFiles))await NQ(GQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=$X(Q),Z=D0(U),$=qX();await C0(X,$,Z)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Z=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(U);console.log(U)}}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),VQ(this.currentLogFile))try{let Q=GX(this.currentLogFile,"r+");YX(Q),YU(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!O()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await DQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await NQ(GQ(this.config.logDirectory,X))}catch(Z){console.error(`Failed to delete temp file ${X}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?K.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||O())return!1;let Q=typeof L.env.NO_COLOR<"u",U=L.env.FORCE_COLOR==="0";if(Q||U)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Z="",message:$,level:Y,showTimestamp:G=!0}=Q,J=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let H=L.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${X} ${$}`;else if(Y==="info"||Y==="success")q=`${X} ${Z} ${$}`;else q=`${X} ${Z} ${K.cyan($)}`;if(!G)return q.trim();let _=J(q).trim().length,A=J(U).length,z=Math.max(1,H-2-_-A);return`${q.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,(Y,G)=>{let J=Number.parseInt(G,10);return J<U[0].length?String(U[0][J]):Y});let X=/%([sdijfo%])/g,Z=0,$=Q.replace(X,(Y,G)=>{if(G==="%")return"%";if(Z>=U.length)return Y;let J=U[Z++];switch(G){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 Y}});if(Z<U.length)$+=` ${U.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let U=Q;return U=U.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,Z,$)=>{let Y=K.underline(K.blue(Z)),G=this.toAbsoluteFilePath($);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let J=`file://${encodeURI(G)}`,H="\x1B]8;;",q="\x1B\\";return`\x1B]8;;${J}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),U=U.replace(/`([^`]+)`/g,(X,Z)=>K.bgGray(Z)),U=U.replace(/\*\*([^*]+)\*\*/g,(X,Z)=>K.bold(Z)),U=U.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,Z)=>K.italic(Z)),U=U.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,Z)=>K.italic(Z)),U=U.replace(/~([^~]+)~/g,(X,Z)=>K.strikethrough(Z)),U}supportsHyperlinks(){if(O())return!1;let Q=L.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let U=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(U)&&U>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let U=Q;if(U.startsWith("file://"))U=U.replace(/^file:\/\//,"");if(U.startsWith("~")){let X=L.env.HOME||"";if(X)U=U.replace(/^~(?=$|\/)/,X)}if(T0(U)||U.startsWith("./")||U.startsWith("../"))U=S0(U);else return null;return VQ(U)?U:null}catch{return null}}buildOutputTexts(Q){let U=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,X=Q.replace(this.ANSI_PATTERN,"");return{consoleText:U,fileText:X}}async log(Q,U,...X){if(!this.shouldLog(Q))return;let Z=new Date,$=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,J;if(U instanceof Error)G=U.message,J=U.stack;else G=this.formatMessage(U,X);let{consoleText:H,fileText:q}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":v0[Q],z=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:K.gray(H),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:K.green(H),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.error(W),J){let V=J.split(`
40
+ `);for(let B of V)if(B.trim()&&!B.includes(G))console.error(this.formatConsoleMessage({timestamp:$,message:K.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!O()){if(console.error(`${Y} ${this.environment}.${Q.toUpperCase()}: ${G}`),J)console.error(J)}let _=`${Y} ${this.environment}.${Q.toUpperCase()}: ${q}
41
+ `;if(J)_+=`${J}
42
+ `;if(_=_.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(_)}progress(Q,U=""){let X={update:(J,H)=>{},finish:(J)=>{},interrupt:(J,H)=>{}};if(!this.enabled)return X;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:U||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(J,H)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,J),this.activeProgressBar.total),H!==void 0)this.activeProgressBar.message=H;if(this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(J)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,J)},interrupt:(J,H="info")=>{if(!O()&&L.stdout.isTTY)L.stdout.write(`
43
+ `);if(this[H==="warning"?"warn":H](J),this.activeProgressBar&&this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let U=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":K.blue("◐"),tag:X,message:`${K.cyan(Q)}...`}))}return async(X)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-U),Y=`${Q} completed in ${$}ms`,G=new Date,J=this.formatConsoleTimestamp(G),q=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${Y}`;if(X)q+=` ${JSON.stringify(X)}`;if(q+=`
44
+ `,q=q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":K.green("✓"),tag:_,message:`${Y}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!O())console.error(q.trim());if(this.shouldWriteToFile())await this.writeToFile(q)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new BQ(U,{...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(X),X}createReadStream(){if(O())throw Error("createReadStream is not supported in browser environments");if(!VQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $X(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Z=g.isBuffer(Q)?Q:g.from(Q,"base64"),$=Z.subarray(0,16),Y=Z.subarray(Z.length-16),G=Z.subarray(16,Z.length-16),J=V0("aes-256-gcm",X,$);J.setAuthTag(Y);let H=J.update(G),q=J.final(),_=H.length+q.length,A=g.allocUnsafe(_);return H.copy(A,0),q.copy(A,H.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}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(Q,U){this.currentKeyId=Q,this.keys.set(Q,U)}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(Q){if(!this.enabled)return;let U=new Date,X=this.formatConsoleTimestamp(U),Z=this.formatFileTimestamp(U),{consoleText:$,fileText:Y}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let J=$.split(`
45
+ `),H=Math.max(...J.map((z)=>z.length))+2,q=`┌${"─".repeat(H)}┐`,_=`└${"─".repeat(H)}┘`,A=J.map((z)=>{return this.formatConsoleMessage({timestamp:X,message:K.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:K.cyan(q),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:X,message:K.cyan(_),showTimestamp:!1}))}else if(!O())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Y}`);let G=`${Z} ${this.environment}.INFO: [BOX] ${Y}
46
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(O())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${K.cyan("?")} ${Q} (y/n) `);let X=(Z)=>{let $=Z.toString().trim().toLowerCase();L.stdin.removeListener("data",X);try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!1)}catch{}L.stdin.pause(),console.error(""),U($==="y"||$==="yes")};try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!0)}catch{}L.stdin.resume(),L.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let H=/%([sdijfo%])/g,q=0;if(X=Q.replace(H,(_,A)=>{if(A==="%")return"%";if(q>=U.length)return _;let z=U[q++];switch(A){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 _}}),q<U.length)X+=` ${U.slice(q).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let H=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",q=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${q}${H} ${K.cyan(Z)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(Q,U=!1){if(!this.enabled||!this.shouldStyleConsole()||!L.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*X/100),$=Q.barLength-Z,Y=K.green("━".repeat(Z)),G=K.gray("━".repeat($)),J=`[${Y}${G}]`,H=`${X}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=this.options.showIcons===!1?"":U||X===100?K.green("✓"):K.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${J} ${H}${q}`,W=L.stdout.columns||80,V=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${V}`,L.stdout.write(Q.lastRenderedLine),U)L.stdout.write(`
48
+ `)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||O()||!L.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(O()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await DQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=GQ(this.config.logDirectory,Z);if(Q.before)try{if((await YQ(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await NQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}var A8=new BQ("stacks");var h0=new BQ("rpx",{showTags:!1});function d0(){return process.env.SUDO_PASSWORD}function R8(Q){let U=d0(),X=Q.replace(/'/g,"'\\''");if(U)return PX(`echo '${U}' | sudo -S sh -c '${X}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return PX(`sudo sh -c '${X}'`,{encoding:"utf-8"})}function bX(Q,U,X){if(X)h0.debug(`[rpx:${Q}] ${U}`)}var yX="[redacted]",f0=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),p0=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function u0(Q){let U=Q.toLowerCase();return f0.has(U)||U.endsWith("password")||U.includes("secret")||U.includes("token")}function EU(Q){if(Array.isArray(Q))return Q.map((X)=>EU(X));if(typeof Q==="string")return p0.test(Q)?yX:Q;if(!Q||typeof Q!=="object")return Q;let U={};for(let[X,Z]of Object.entries(Q)){if(u0(X)){U[X]=yX;continue}U[X]=EU(Z)}return U}function L8(Q,U){return JSON.stringify(EU(Q),null,U)}function w8(Q){if(hX(Q))return Q.proxies.map((U)=>{let X=U.to||"stacks.localhost";return X.startsWith("http")?new URL(X).hostname:X});if(dX(Q)){let U=Q.to||"stacks.localhost";return[U.startsWith("http")?new URL(U).hostname:U]}return["stacks.localhost"]}function K8(Q){return typeof Q==="object"&&Q!==null&&"certificate"in Q&&"privateKey"in Q&&typeof Q.certificate==="string"&&typeof Q.privateKey==="string"}function j8(Q){if(!Q)return"stacks.localhost";if(hX(Q)&&Q.proxies.length>0)return Q.proxies[0].to||"stacks.localhost";if(dX(Q))return Q.to||"stacks.localhost";return"stacks.localhost"}function F8(Q){return!!(Q&&("proxies"in Q)&&Array.isArray(Q.proxies))}function hX(Q){return"proxies"in Q&&Array.isArray(Q.proxies)}function dX(Q){return"to"in Q&&typeof Q.to==="string"}function I8(Q){return!!(Q&&("to"in Q)&&!("proxies"in Q))}function M8(Q,U){if(!U||U.length===0)return null;for(let X of U)if(Q===X.from||Q.startsWith(`${X.from}/`)){let Z=X.to.startsWith("http")?new URL(X.to).host:X.to,$=X.stripPrefix===!0?Q.slice(X.from.length)||"/":Q;return{targetHost:Z,targetPath:$}}return null}async function V8(Q,U){try{await vX.unlink(Q),bX("certificates",`Successfully deleted: ${Q}`,U)}catch(X){if(X.code!=="ENOENT")bX("certificates",`Warning: Could not delete ${Q}: ${X}`,U)}}
49
+ export{r as a,d0 as b,R8 as c,bX as d,EU as e,L8 as f,w8 as g,K8 as h,j8 as i,F8 as j,hX as k,dX as l,I8 as m,M8 as n,V8 as o};
@@ -0,0 +1 @@
1
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n}from"./chunk-jpf41gb9.js";export{e as safeStringify,n as safeDeleteFile,m as resolvePathRewrite,d as redactSensitive,g as isValidRootCA,k as isSingleProxyOptions,l as isSingleProxyConfig,j as isMultiProxyOptions,i as isMultiProxyConfig,a as getSudoPassword,h as getPrimaryDomain,f as extractHostname,b as execSudoSync,c as debugLog};
@@ -0,0 +1,29 @@
1
+ import type { PathRewrite } from './types';
2
+ /**
3
+ * Sanitize an arbitrary `to` host into a valid registry id. Drops anything
4
+ * that isn't `[a-zA-Z0-9._-]`, collapses runs to a single dash, and trims
5
+ * leading/trailing dashes. Falls back to `'rpx'` if nothing's left.
6
+ */
7
+ export declare function deriveIdFromTarget(to: string): string;
8
+ /**
9
+ * Register every proxy with the daemon and (unless `detached`) block until a
10
+ * shutdown signal arrives. Throws if any id collides or the daemon fails to
11
+ * spawn.
12
+ */
13
+ export declare function runViaDaemon(opts: DaemonRunnerOptions): Promise<void>;
14
+ export declare interface DaemonRunnerProxy {
15
+ id?: string
16
+ from: string
17
+ to: string
18
+ cleanUrls?: boolean
19
+ changeOrigin?: boolean
20
+ pathRewrites?: PathRewrite[]
21
+ }
22
+ export declare interface DaemonRunnerOptions {
23
+ proxies: DaemonRunnerProxy[]
24
+ verbose?: boolean
25
+ registryDir?: string
26
+ rpxDir?: string
27
+ detached?: boolean
28
+ spawnCommand?: string[]
29
+ }
@@ -0,0 +1,99 @@
1
+ import type { TlsOption } from './types';
2
+ export declare function getDaemonRpxDir(): string;
3
+ export declare function getDaemonPidPath(rpxDir?: string): string;
4
+ /**
5
+ * Read the PID stored in `daemon.pid`, or `null` if no file / unparseable.
6
+ */
7
+ export declare function readDaemonPid(rpxDir?: string): Promise<number | null>;
8
+ /**
9
+ * True if `daemon.pid` points at a process that is still alive.
10
+ */
11
+ export declare function isDaemonRunning(rpxDir?: string): Promise<boolean>;
12
+ /**
13
+ * Acquire the daemon's single-instance lock by atomically creating
14
+ * `daemon.pid`. If the file exists but holds a stale PID we take it over;
15
+ * otherwise we throw.
16
+ *
17
+ * `O_CREAT | O_EXCL` (`'wx'`) guarantees only one process wins the create
18
+ * race, so we don't need an external lock library.
19
+ */
20
+ export declare function acquireDaemonLock(rpxDir?: string): Promise<string>;
21
+ export declare function releaseDaemonLock(rpxDir?: string): Promise<void>;
22
+ /**
23
+ * Start the daemon. Returns a handle that resolves `done` once the daemon has
24
+ * cleanly shut down (signal received and listeners closed).
25
+ *
26
+ * The promise itself resolves as soon as the daemon is *ready* — i.e. both
27
+ * listeners are bound and the initial routing table is populated. Use
28
+ * `handle.done` for the lifetime promise.
29
+ */
30
+ export declare function runDaemon(opts?: DaemonOptions): Promise<DaemonHandle>;
31
+ /**
32
+ * Best-effort default for the spawn command used by lazy-spawn. Compiled
33
+ * binaries (`bun build --compile`) self-invoke; source-mode executions invoke
34
+ * the same Bun + script that's running now.
35
+ *
36
+ * Library consumers should not rely on this — pass `spawnCommand` explicitly.
37
+ */
38
+ export declare function defaultDaemonSpawnCommand(): string[];
39
+ /**
40
+ * Make sure a daemon is running, starting one as a detached child if needed.
41
+ *
42
+ * - If the pid file exists and points at a live process, returns immediately
43
+ * with `spawned: false`.
44
+ * - Otherwise cleans any stale pid file, spawns the configured command with
45
+ * `detached: true` + `stdio: 'ignore'` + `unref()` so it survives the caller
46
+ * exiting, and polls the pid file until the new daemon registers itself.
47
+ *
48
+ * Throws if the daemon never appears within `startupTimeoutMs`.
49
+ */
50
+ export declare function ensureDaemonRunning(opts?: EnsureDaemonOptions): Promise<EnsureDaemonResult>;
51
+ /**
52
+ * Stop a running daemon by reading its pid and sending SIGTERM. Polls until
53
+ * the process is gone (or escalates to SIGKILL if `forceAfterTimeout`). The
54
+ * pid file is removed by the daemon's own SIGTERM handler — we clean up only
55
+ * if we had to SIGKILL.
56
+ */
57
+ export declare function stopDaemon(opts?: StopDaemonOptions): Promise<StopDaemonResult>;
58
+ export declare interface DaemonOptions {
59
+ verbose?: boolean
60
+ rpxDir?: string
61
+ registryDir?: string
62
+ httpsPort?: number
63
+ httpPort?: number
64
+ hostname?: string
65
+ https?: TlsOption
66
+ gcIntervalMs?: number
67
+ }
68
+ export declare interface DaemonHandle {
69
+ stop: () => Promise<void>
70
+ done: Promise<void>
71
+ httpsPort: number
72
+ httpPort: number
73
+ pidPath: string
74
+ }
75
+ export declare interface EnsureDaemonOptions {
76
+ rpxDir?: string
77
+ spawnCommand?: string[]
78
+ spawnCwd?: string
79
+ spawnEnv?: Record<string, string>
80
+ startupTimeoutMs?: number
81
+ pollIntervalMs?: number
82
+ verbose?: boolean
83
+ }
84
+ export declare interface EnsureDaemonResult {
85
+ pid: number
86
+ spawned: boolean
87
+ }
88
+ export declare interface StopDaemonOptions {
89
+ rpxDir?: string
90
+ timeoutMs?: number
91
+ pollIntervalMs?: number
92
+ forceAfterTimeout?: boolean
93
+ verbose?: boolean
94
+ }
95
+ export declare interface StopDaemonResult {
96
+ stopped: boolean
97
+ pid: number | null
98
+ forced: boolean
99
+ }
package/dist/https.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  import { config } from './config';
2
2
  import type { ProxyConfigs, ProxyOption, ProxyOptions, SSLConfig, TlsConfig } from './types';
3
+ /**
4
+ * Returns the canonical Root CA cert + key paths inside `basePath`.
5
+ */
6
+ export declare function getRootCAPaths(basePath: string): RootCAPaths;
3
7
  /**
4
8
  * Resolves SSL paths based on configuration
5
9
  */
@@ -24,3 +28,20 @@ export declare function loadSSLConfig(options: ProxyOption): Promise<SSLConfig |
24
28
  */
25
29
  export declare function forceTrustCertificate(certPath: string): Promise<boolean>;
26
30
  export declare function generateCertificate(options: ProxyOptions): Promise<void>;
31
+ export declare function getSSLConfig(): { key: string, cert: string, ca?: string } | null;
32
+ // needs to accept the options
33
+ export declare function checkExistingCertificates(options?: ProxyOptions): Promise<SSLConfig | null>;
34
+ export declare function httpsConfig(options: ProxyOption | ProxyOptions, verbose?: boolean): TlsConfig;
35
+ /**
36
+ * Clean up SSL certificates for a specific domain
37
+ */
38
+ export declare function cleanupCertificates(domain: string, verbose?: boolean): Promise<void>;
39
+ /**
40
+ * Checks if a certificate is trusted by the system (macOS only for now)
41
+ * If options.regenerateUntrustedCerts is false, always returns true (skips trust check)
42
+ */
43
+ export declare function isCertTrusted(certPath: string, options?: { verbose?: boolean, regenerateUntrustedCerts?: boolean }): Promise<boolean>;
44
+ export declare interface RootCAPaths {
45
+ caCertPath: string
46
+ caKeyPath: string
47
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,15 @@
1
1
  import { startProxies as startProxiesFunc } from './start';
2
+ export type { RegistryEntry, WatchHandle, WatchOptions } from './registry';
3
+ export type {
4
+ DaemonHandle,
5
+ DaemonOptions,
6
+ EnsureDaemonOptions,
7
+ EnsureDaemonResult,
8
+ StopDaemonOptions,
9
+ StopDaemonResult,
10
+ } from './daemon';
11
+ export type { GetRoute, ProxyFetchHandler, ProxyRoute } from './proxy-handler';
12
+ export type { DaemonRunnerOptions, DaemonRunnerProxy } from './daemon-runner';
2
13
  export { colors } from './colors';
3
14
  export { config, config as defaultConfig } from './config';
4
15
  export {
@@ -16,6 +27,31 @@ export {
16
27
  loadSSLConfig,
17
28
  } from './https';
18
29
  export { DefaultPortManager, findAvailablePort, isPortInUse, portManager } from './port-manager';
30
+ export {
31
+ gcStaleEntries,
32
+ getRegistryDir,
33
+ isPidAlive,
34
+ isValidId,
35
+ readAll,
36
+ readEntry,
37
+ removeEntry,
38
+ watchRegistry,
39
+ writeEntry,
40
+ } from './registry';
41
+ export {
42
+ acquireDaemonLock,
43
+ defaultDaemonSpawnCommand,
44
+ ensureDaemonRunning,
45
+ getDaemonPidPath,
46
+ getDaemonRpxDir,
47
+ isDaemonRunning,
48
+ readDaemonPid,
49
+ releaseDaemonLock,
50
+ runDaemon,
51
+ stopDaemon,
52
+ } from './daemon';
53
+ export { createProxyFetchHandler } from './proxy-handler';
54
+ export { deriveIdFromTarget, runViaDaemon } from './daemon-runner';
19
55
  export { cleanup } from './start';
20
56
  export { startProxies, startProxy, startServer } from './start';
21
57
  export * from './types';