@stacksjs/dnsx
Version:
A command-line & library DNS client. Like dig & dog, but for TypeScript.
9 lines • 155 kB
JavaScript
import{b as l,c as j$,d as I$,e as F$,f as M$,g as D$,i as S$,j as V$,k as E$,l as T$,m as O$,n as N$,o as C$,p as x$,q as k$,r as P$,t as b$}from"../chunk-zyb8fbk3.js";import{existsSync as nX,statSync as iX}from"fs";import{existsSync as RZ,mkdirSync as T8,readdirSync as O8,readFileSync as wZ,writeFileSync as N8}from"fs";import{homedir as YQ}from"os";import{dirname as k8,resolve as d}from"path";import eQ from"process";import{existsSync as sX,statSync as oX}from"fs";import{existsSync as DX,mkdirSync as LZ,readdirSync as KZ,writeFileSync as jZ}from"fs";import{homedir as ZQ}from"os";import{dirname as tX,resolve as y}from"path";import XQ from"process";import{join as IZ,relative as FZ,resolve as rX}from"path";import pQ from"process";import{existsSync as bY,mkdirSync as u8,readdirSync as g8,writeFileSync as c8}from"fs";import{homedir as ZX}from"os";import{dirname as i8,resolve as b}from"path";import wQ from"process";import{join as MZ,relative as DZ,resolve as aX}from"path";import mQ from"process";import{existsSync as yY,mkdirSync as a8,readdirSync as e8,writeFileSync as Q9}from"fs";import{dirname as Y9,resolve as uQ}from"path";import SX from"process";import{Buffer as e}from"buffer";import{createCipheriv as SZ,createDecipheriv as VZ,randomBytes as $X}from"crypto";import{closeSync as HX,createReadStream as eX,createWriteStream as EZ,existsSync as UX,fsyncSync as QY,openSync as XY,writeFileSync as TZ}from"fs";import{access as OZ,constants as YY,mkdir as NZ,readdir as IQ,rename as ZY,stat as $Q,unlink as FQ,writeFile as JX}from"fs/promises";import{join as HQ}from"path";import N from"process";import{pipeline as CZ}from"stream/promises";import{createGzip as $Y}from"zlib";import UQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as xZ,createDecipheriv as kZ,randomBytes as GX}from"crypto";import{closeSync as _X,createReadStream as HY,createWriteStream as PZ,existsSync as MQ,fsyncSync as UY,openSync as JY,writeFileSync as bZ}from"fs";import{access as yZ,constants as GY,mkdir as vZ,readdir as DQ,rename as _Y,stat as JQ,unlink as SQ,writeFile as qX}from"fs/promises";import{isAbsolute as dZ,join as GQ,resolve as hZ}from"path";import R from"process";import{pipeline as fZ}from"stream/promises";import{createGzip as qY}from"zlib";import _Q from"process";import t from"process";import VQ from"process";import{existsSync as EQ}from"fs";import{resolve as AX}from"path";import{existsSync as pZ}from"fs";import{existsSync as mZ,readdirSync as uZ}from"fs";import{extname as WX,resolve as AY}from"path";import gZ from"process";import{join as cZ,relative as lZ,resolve as WY}from"path";import gQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as nZ,createDecipheriv as iZ,randomBytes as zX}from"crypto";import{closeSync as BX,createReadStream as zY,createWriteStream as sZ,existsSync as TQ,fsyncSync as BY,openSync as RY,writeFileSync as oZ}from"fs";import{access as tZ,constants as wY,mkdir as rZ,readdir as OQ,rename as LY,stat as qQ,unlink as NQ,writeFile as RX}from"fs/promises";import{isAbsolute as aZ,join as AQ,resolve as eZ}from"path";import w from"process";import{pipeline as Q0}from"stream/promises";import{createGzip as KY}from"zlib";import WQ from"process";import r from"process";import xQ from"process";import{existsSync as kQ}from"fs";import{resolve as FX}from"path";import{existsSync as I8}from"fs";class kY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}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(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!nX(Q))return!0;return iX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=nX(Y)?iX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class PY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var fQ=new kY,yX=new PY;var X0=Object.defineProperty,Y0=(Q)=>Q;function Z0(Q,X){this[Q]=Y0.bind(null,X)}var $0=(Q,X)=>{for(var Y in X)X0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:Z0.bind(X,Y)})},H0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),vY={};$0(vY,{withErrorRecovery:()=>fY,tryLoadConfig:()=>O0,loadConfigWithResult:()=>E0,loadConfig:()=>cY,isRetryableError:()=>I0,isConfigNotFoundError:()=>j0,isBunfigError:()=>pY,globalPerformanceMonitor:()=>jQ,globalCache:()=>zQ,getEnvOrDefault:()=>F0,generateConfigTypes:()=>N0,defaultGeneratedDir:()=>aY,defaultConfigDir:()=>rY,deepMergeWithArrayStrategy:()=>pX,deepMerge:()=>mY,createLibraryConfig:()=>C0,config:()=>T0,bunfigPlugin:()=>x0,applyEnvVarsToConfig:()=>RQ,TypeGenerationError:()=>xX,SchemaValidationError:()=>KQ,PluginError:()=>PX,PerformanceMonitor:()=>dX,FileSystemError:()=>CX,ErrorFactory:()=>QQ,EnvVarError:()=>oQ,EnvProcessor:()=>QX,ConfigValidator:()=>mX,ConfigValidationError:()=>OX,ConfigNotFoundError:()=>sQ,ConfigMergeError:()=>NX,ConfigLoader:()=>uX,ConfigLoadError:()=>LQ,ConfigFileLoader:()=>XX,ConfigCache:()=>vX,CacheUtils:()=>nY,BunfigError:()=>v,BrowserConfigError:()=>kX,ArrayMergeStrategies:()=>oY});class vX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}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(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!sX(Q))return!0;return oX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=sX(Y)?oX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function U0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function J0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function G0(Q){return Q.getStats().size*2}function hX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>cQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=hX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>cQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function cQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!cQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!cQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function _0(Q,X){if(!yY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return hX(X,Z)}catch{return null}}catch{return null}}async function q0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||SX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=uQ(Z,`${U}${G}`),_=await _0(J,Y);if(_!==null)return _}try{let U=uQ(Z,"package.json");if(yY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return hX(Y,J)}catch{}}}catch{}return Y}function A0(Q,X={}){let Y=mQ.cwd();while(Y.includes("storage"))Y=aX(Y,"..");let Z=aX(Y,Q||"");if(X?.relative)return DZ(mQ.cwd(),Z);return Z}async function W0(){try{let Q=await q0({name:"clarity",defaultConfig:yQ,cwd:mQ.cwd(),endpoint:"",headers:{}});return{...yQ,...Q}}catch{return yQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function z0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class dY{async format(Q){let X=await z0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:UQ.pid,hostname:X(),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 lQ{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,X={}){this.name=Q,this.config={...EX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new dY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...vQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...vQ};return{...vQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:EX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await OZ(this.config.logDirectory,YY.F_OK|YY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await NZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!UX(this.currentLogFile))await JX(this.currentLogFile,"",{mode:420});if($=XY(this.currentLogFile,"a",420),TZ($,J,{flag:"a"}),QY($),$!==void 0)HX($),$=void 0;if((await $Q(this.currentLogFile)).size===0){if(await JX(this.currentLogFile,J,{flag:"w",mode:420}),(await $Q(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{HX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}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 HQ(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 HQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return HQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,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 X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return $X(16).toString("hex")}generateKey(){return $X(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:X}=this.getCurrentKey(),Y=$X(16),Z=SZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=$Y(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),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 X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await $Q(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await IQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await $Q(Y).catch(()=>null))try{if(await ZY(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await FQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await JX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await $Q(Y).catch(()=>null))await ZY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await IQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await FQ(HQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=eX(Q),Z=EZ(X),$=$Y();await CZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}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 X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),UX(this.currentLogFile))try{let Q=XY(this.currentLogFile,"r+");QY(Q),HX(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(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await IQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await FQ(HQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,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?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=N.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=iY[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
`);for(let W of z)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:M.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let J=`${H} ${this.environment}.${Q.toUpperCase()}: ${U}
`;if(G)J+=`${G}
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!S()){let Y=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:M.blue("◐"),tag:Y,message:`${M.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
`,_=_.replace(this.ANSI_PATTERN,""),this.fancy&&!S()){let q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:M.green("✓"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!S())console.error(_.trim());await this.writeToFile(_)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new lQ(X,{...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(Y),Y}createReadStream(){if(S())throw Error("createReadStream is not supported in browser environments");if(!UX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return eX(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=e.isBuffer(Q)?Q:e.from(Q,"base64"),$=Z.slice(0,16),H=Z.slice(-16),U=Z.slice(16,-16),G=VZ("aes-256-gcm",Y,$);return G.setAuthTag(H),e.concat([G.update(U),G.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 S()}isServerMode(){return!S()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}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 X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X);if(this.fancy&&!S()){let H=Q.split(`
`),U=Math.max(...H.map((q)=>q.length))+2,G=`┌${"─".repeat(U)}┐`,J=`└${"─".repeat(U)}┘`,_=H.map((q)=>{let A=" ".repeat(U-q.length-2);return`│ ${q}${A} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:M.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(G)})),_.forEach((q)=>console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(q),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(J),showTimestamp:!1}))}else if(!S())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Q}`);let $=`${Z} ${this.environment}.INFO: [BOX] ${Q}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile($)}async prompt(Q){if(S())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${M.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();N.stdin.removeListener("data",Y);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let U=/%([sdijfo%])/g,G=0;if(Y=Q.replace(U,(J,_)=>{if(_==="%")return"%";if(G>=X.length)return J;let q=X[G++];switch(_){case"s":return String(q);case"d":case"i":return Number(q).toString();case"j":case"o":return JSON.stringify(q,null,2);default:return J}}),G<X.length)Y+=` ${X.slice(G).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!S()){let U=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",G=M.blue("◐");console.error(`${G} ${U} ${M.cyan(Y)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(H)}progress(Q,X=""){if(!this.enabled||!this.fancy||S()||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 Y=20;return this.activeProgressBar={total:Q,current:0,message:X,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,G)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,U)),G!==void 0)this.activeProgressBar.message=G;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,G="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(G,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,X=!1){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=M.green("━".repeat(Z)),U=M.gray("━".repeat($)),G=`[${H}${U}]`,J=`${Y}%`.padStart(4),_=Q.message?` ${Q.message}`:"",q=X||Y===100?M.green("✓"):M.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${G} ${J}${_}`,W=N.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,N.stdout.write(Q.lastRenderedLine),X)N.stdout.write(`
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await IQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=HQ(this.config.logDirectory,Z);if(Q.before)try{if((await $Q(H)).mtime>=Q.before)continue}catch(U){console.error(`Failed to get stats for file ${H}:`,U);continue}Y.push(H)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await FQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}function bQ(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&F(X[0])&&"id"in X[0]&&X[0].id===3&&F(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(F(X)&&F(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(F(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&F(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&F(X[0])&&F(Q[0])){let Z=[...X];for(let $ of Q)if(F($)&&"name"in $){if(!Z.find((U)=>F(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(F($)&&"path"in $){if(!Z.find((U)=>F(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>nQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!F(X)||!F(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(F($)&&F(Y[Z]))Y[Z]=bQ(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&F($[0])&&F(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(F(U)&&"name"in U){if(!H.find((J)=>F(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(F(U)&&"path"in U){if(!H.find((J)=>F(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>nQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function fX(Q,X,Y="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return Y==="replace"?X:bQ(Q,X);if(Array.isArray(Q))return Y==="replace"?X:bQ(Q,X);if(!F(X)||!F(Q))return X;let Z={...Q};for(let $ of Object.keys(X)){if(!Object.prototype.hasOwnProperty.call(X,$))continue;let H=X[$],U=Z[$];if(H===null||H===void 0)continue;if(Array.isArray(H)||Array.isArray(U))if(Y==="replace")Z[$]=H;else Z[$]=bQ(U,H);else if(F(H)&&F(U))Z[$]=fX(U,H,Y);else Z[$]=H}return Z}function nQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!nQ(Q[Y],X[Y]))return!1;return!0}if(F(Q)&&F(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!nQ(Q[$],X[$]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function CQ(Q,X,Y="replace"){if(!bY(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return fX(X,$,Y)}catch{return null}}catch{return null}}function B0(Q,X,Y=!1){if(!Q)return X;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...X};function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let A=[...G,_],z=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${Z}_${A.map(z).join("_")}`,I=`${Z}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(Y)x.info(`Checking environment variable ${W} for config ${Q}.${A.join(".")}`);if(typeof q==="object"&&q!==null&&!Array.isArray(q))J[_]=H(q,A);else{let B=wQ.env[W]||wQ.env[I];if(B!==void 0){if(Y)x.info(`Using environment variable ${B?W:I} for config ${Q}.${A.join(".")}`);if(typeof q==="number")J[_]=Number(B);else if(typeof q==="boolean")J[_]=B.toLowerCase()==="true";else if(Array.isArray(q))try{let K=JSON.parse(B);if(Array.isArray(K))J[_]=K;else J[_]=B.split(",").map((k)=>k.trim())}catch{J[_]=B.split(",").map((K)=>K.trim())}else J[_]=B}}}return J}return H($)}async function R0({name:Q="",alias:X,cwd:Y,configDir:Z,defaultConfig:$,verbose:H=!1,checkEnv:U=!0,arrayStrategy:G="replace"}){let J=U&&typeof $==="object"&&$!==null&&!Array.isArray($)?B0(Q,$,H):$,_=Y||wQ.cwd(),q=[".ts",".js",".mjs",".cjs",".json"];if(H)x.info(`Loading configuration for "${Q}"${X?` (alias: "${X}")`:""} from ${_}`);let A=[Q,`.${Q}`].filter(Boolean),z=[`${Q}.config`,`.${Q}.config`].filter(Boolean),W=X?[X,`.${X}`]:[],I=X?[`${X}.config`,`.${X}.config`]:[],B=Array.from(new Set([_,b(_,"config"),b(_,".config"),Z?b(_,Z):void 0].filter(Boolean)));for(let K of B){if(H)x.info(`Searching for configuration in: ${K}`);let P=[b(_,"config"),b(_,".config")].concat(Z?[b(_,Z)]:[]).includes(K)?[...A,...z,...W,...I]:[...z,...A,...I,...W];for(let n of P)for(let g of q){let p=b(K,`${n}${g}`),lX=await CQ(p,J,G);if(lX!==null){if(H)x.success(`Configuration loaded from: ${p}`);return lX}}}if(Q){let K=b(ZX(),".config",Q),k=["config",`${Q}.config`];if(X)k.push(`${X}.config`);if(H)x.info(`Checking user config directory: ${K}`);for(let P of k)for(let n of q){let g=b(K,`${P}${n}`),p=await CQ(g,J,G);if(p!==null){if(H)x.success(`Configuration loaded from user config directory: ${g}`);return p}}}if(Q){let K=b(ZX(),".config"),k=[`.${Q}.config`];if(X)k.push(`.${X}.config`);if(H)x.info(`Checking user config directory for dotfile configs: ${K}`);for(let P of k)for(let n of q){let g=b(K,`${P}${n}`),p=await CQ(g,J,G);if(p!==null){if(H)x.success(`Configuration loaded from user config directory dotfile: ${g}`);return p}}}if(Q){let K=ZX(),k=[`.${Q}.config`,`.${Q}`];if(X)k.push(`.${X}.config`),k.push(`.${X}`);if(H)x.info(`Checking user home directory for dotfile configs: ${K}`);for(let P of k)for(let n of q){let g=b(K,`${P}${n}`),p=await CQ(g,J,G);if(p!==null){if(H)x.success(`Configuration loaded from user home directory: ${g}`);return p}}}try{let K=b(_,"package.json");if(bY(K)){let k=await import(K),P=k[Q];if(!P&&X){if(P=k[X],P&&H)x.success(`Using alias "${X}" configuration from package.json`)}if(P&&typeof P==="object"&&!Array.isArray(P))try{if(H)x.success(`Configuration loaded from package.json: ${P===k[Q]?Q:X}`);return fX(J,P,G)}catch(n){if(H)x.warn("Failed to merge package.json config:",n)}}}catch(K){if(H)x.warn("Failed to load package.json:",K)}if(H)x.info(`No configuration found for "${Q}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return J}function w0(Q,X={}){let Y=pQ.cwd();while(Y.includes("storage"))Y=rX(Y,"..");let Z=rX(Y,Q||"");if(X?.relative)return FZ(pQ.cwd(),Z);return Z}async function L0(){try{let Q=await R0({name:"clarity",alias:"logging",defaultConfig:dQ,cwd:pQ.cwd()});return{...dQ,...Q||{}}}catch{return dQ}}function V(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function K0(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t<"u"){let Q=t.type;if(Q==="renderer"||Q==="worker")return!1;return!!(t.versions&&(t.versions.node||t.versions.bun))}return!1}class hY{async format(Q){let X=await K0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:_Q.pid,hostname:X(),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 iQ{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,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new hY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return X[Q]>=X[Y]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}shouldWriteToFile(){return!V()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await yZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await vZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:i.from(Q);try{if(!MQ(this.currentLogFile))await qX(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),bZ($,J,{flag:"a"}),UY($),$!==void 0)_X($),$=void 0;if((await JQ(this.currentLogFile)).size===0){if(await qX(this.currentLogFile,J,{flag:"w",mode:420}),(await JQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{_X($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}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(V())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKey