@stacksjs/bun-router 0.0.26 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-0gjq8ttx.js +14 -0
- package/dist/chunk-0t5vz87j.js +35 -0
- package/dist/chunk-30rkn2ym.js +2 -0
- package/dist/chunk-38cmrard.js +2 -0
- package/dist/chunk-3qna6dwd.js +2 -0
- package/dist/chunk-4d5fmta0.js +2 -0
- package/dist/chunk-4x3b4b4q.js +2 -0
- package/dist/chunk-5be9x5cq.js +3 -0
- package/dist/chunk-5mxby3fd.js +1654 -0
- package/dist/chunk-5n0ckcmc.js +3 -0
- package/dist/chunk-5ncn73tp.js +3 -0
- package/dist/chunk-5s0pnsd6.js +12 -0
- package/dist/chunk-5s1pr62n.js +3 -0
- package/dist/chunk-67wgad4f.js +60 -0
- package/dist/chunk-6bbmkwng.js +3 -0
- package/dist/chunk-6s1kbajm.js +7851 -0
- package/dist/chunk-6sjvhy5f.js +3 -0
- package/dist/chunk-6xed4va1.js +2 -0
- package/dist/chunk-73k79n7q.js +15413 -0
- package/dist/chunk-748n6ydj.js +2 -0
- package/dist/chunk-7qnxdedn.js +321 -0
- package/dist/chunk-7rsf8tes.js +898 -0
- package/dist/chunk-8aspmtf1.js +2 -0
- package/dist/chunk-8wpj3fqe.js +351 -0
- package/dist/chunk-8yfdg595.js +2 -0
- package/dist/chunk-90eze7av.js +3 -0
- package/dist/chunk-9805tt8n.js +341 -0
- package/dist/chunk-9dvwyej7.js +2 -0
- package/dist/chunk-9ght4n4r.js +216 -0
- package/dist/chunk-a2w45krb.js +2 -0
- package/dist/chunk-a3wahyg7.js +3 -0
- package/dist/chunk-a547f2ab.js +48 -0
- package/dist/chunk-bqdycvtc.js +2 -0
- package/dist/chunk-brpgjyqg.js +3 -0
- package/dist/chunk-cd03rk3x.js +2 -0
- package/dist/chunk-csfrpsp7.js +185 -0
- package/dist/chunk-ct0m17q5.js +2 -0
- package/dist/chunk-dhbvvr5h.js +2 -0
- package/dist/chunk-dhptcsya.js +943 -0
- package/dist/chunk-dq93zag9.js +2 -0
- package/dist/chunk-dxg045wj.js +5 -0
- package/dist/chunk-e3qej0jr.js +4 -0
- package/dist/chunk-edrtesh7.js +2 -0
- package/dist/chunk-ejcws37w.js +2 -0
- package/dist/chunk-ex5fkjah.js +397 -0
- package/dist/chunk-ex890p45.js +51 -0
- package/dist/chunk-f69cpnhw.js +2 -0
- package/dist/chunk-fjf53b44.js +2 -0
- package/dist/chunk-fjzye4qj.js +2 -0
- package/dist/chunk-gfd23b6t.js +2 -0
- package/dist/chunk-habv0vef.js +12 -0
- package/dist/chunk-hmgedrmr.js +11 -0
- package/dist/chunk-hz6fc788.js +2 -0
- package/dist/chunk-jff6j9y3.js +10 -0
- package/dist/chunk-jmeb7n8k.js +70 -0
- package/dist/chunk-jrf5a2ap.js +2 -0
- package/dist/chunk-jy2jhcpy.js +246 -0
- package/dist/chunk-kc659vhx.js +4 -0
- package/dist/chunk-kjtjbcq4.js +71 -0
- package/dist/chunk-krkchy8v.js +4 -0
- package/dist/chunk-kxp888dn.js +4540 -0
- package/dist/chunk-m249t3je.js +3 -0
- package/dist/chunk-m9yabnjx.js +2 -0
- package/dist/chunk-mekrq9wd.js +2 -0
- package/dist/chunk-mmxv535f.js +82 -0
- package/dist/chunk-mypn7jss.js +2 -0
- package/dist/chunk-n18x1k3c.js +2 -0
- package/dist/chunk-nkddjzsa.js +2 -0
- package/dist/chunk-pjmhqmr9.js +2 -0
- package/dist/chunk-qyrnsaq1.js +2 -0
- package/dist/chunk-r19ff2qm.js +62 -0
- package/dist/chunk-r338fssq.js +2 -0
- package/dist/chunk-s36z58x2.js +29 -0
- package/dist/chunk-s3dn1kwx.js +231 -0
- package/dist/chunk-s79dd325.js +471 -0
- package/dist/chunk-sw0chtw4.js +4 -0
- package/dist/chunk-ta38j9em.js +2 -0
- package/dist/chunk-tpfgntwj.js +4211 -0
- package/dist/chunk-vr10sbbh.js +3 -0
- package/dist/chunk-vsh4390q.js +358 -0
- package/dist/chunk-vv3gb1m5.js +84 -0
- package/dist/chunk-vw8rwv6e.js +2 -0
- package/dist/chunk-w4r464v5.js +288 -0
- package/dist/chunk-wcrqs5z9.js +2 -0
- package/dist/chunk-x6d1rmwa.js +2 -0
- package/dist/chunk-x7ft15zz.js +2 -0
- package/dist/chunk-x8trwn7j.js +3 -0
- package/dist/chunk-xg9xscqz.js +1 -0
- package/dist/chunk-xhepdj1f.js +2 -0
- package/dist/chunk-xv2em0q4.js +4 -0
- package/dist/chunk-ypw6g0te.js +2 -0
- package/dist/chunk-z8szsm21.js +2 -0
- package/dist/chunk-zetqzgf3.js +194 -0
- package/dist/chunk-zfbh14qe.js +2 -0
- package/dist/chunk-zhx0hxdd.js +28 -0
- package/dist/cli.js +67 -3240
- package/dist/container/index.js +1 -321
- package/dist/index.js +80 -13987
- package/dist/types.d.ts +12 -2
- package/package.json +1 -1
- package/dist/chunk-1ahs68ys.js +0 -18
- package/dist/chunk-cgptvjdf.js +0 -18131
- package/dist/chunk-g3ybefhg.js +0 -1923
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Zu as n}from"./chunk-a3wahyg7.js";import{existsSync as tX,statSync as rX}from"fs";import{existsSync as OZ}from"fs";import{resolve as KQ}from"path";import NZ from"process";import{existsSync as SX,mkdirSync as kZ,readdirSync as PZ,readFileSync as bZ,writeFileSync as yZ}from"fs";import{homedir as HQ}from"os";import{dirname as aX,resolve as h}from"path";import ZQ from"process";import{existsSync as eX,statSync as QY}from"fs";import{existsSync as VX,mkdirSync as vZ,readdirSync as dZ,writeFileSync as hZ}from"fs";import{homedir as UQ}from"os";import{dirname as XY,resolve as y}from"path";import $Q from"process";import{join as fZ,relative as pZ,resolve as YY}from"path";import gQ from"process";import{existsSync as nY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{homedir as HX}from"os";import{dirname as L9,resolve as b}from"path";import IQ from"process";import{join as mZ,relative as uZ,resolve as ZY}from"path";import cQ from"process";import{existsSync as iY,mkdirSync as M9,readdirSync as D9,writeFileSync as S9}from"fs";import{dirname as E9,resolve as lQ}from"path";import EX from"process";import{Buffer as e}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as $Y,createWriteStream as lZ,existsSync as GX,fsyncSync as HY,openSync as UY,writeFileSync as nZ}from"fs";import{access as iZ,constants as JY,mkdir as sZ,readdir as SQ,rename as GY,stat as JQ,unlink as VQ,writeFile as _X}from"fs/promises";import{join as GQ}from"path";import x from"process";import{pipeline as oZ}from"stream/promises";import{createGzip as _Y}from"zlib";import _Q from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as tZ,createDecipheriv as rZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as qY,createWriteStream as aZ,existsSync as EQ,fsyncSync as AY,openSync as WY,writeFileSync as eZ}from"fs";import{access as Q0,constants as zY,mkdir as X0,readdir as TQ,rename as BY,stat as qQ,unlink as OQ,writeFile as WX}from"fs/promises";import{isAbsolute as Y0,join as AQ,resolve as Z0}from"path";import w from"process";import{pipeline as $0}from"stream/promises";import{createGzip as RY}from"zlib";import WQ from"process";import t from"process";import NQ from"process";import{existsSync as CQ}from"fs";import{resolve as zX}from"path";import{existsSync as H0}from"fs";import{existsSync as U0,readdirSync as J0}from"fs";import{extname as BX,resolve as wY}from"path";import G0 from"process";import{join as _0,relative as q0,resolve as LY}from"path";import nQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as A0,createDecipheriv as W0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as KY,createWriteStream as z0,existsSync as xQ,fsyncSync as jY,openSync as IY,writeFileSync as B0}from"fs";import{access as R0,constants as FY,mkdir as w0,readdir as kQ,rename as MY,stat as zQ,unlink as PQ,writeFile as LX}from"fs/promises";import{isAbsolute as L0,join as BQ,resolve as K0}from"path";import L from"process";import{pipeline as j0}from"stream/promises";import{createGzip as DY}from"zlib";import RQ from"process";import r from"process";import yQ from"process";import{existsSync as vQ}from"fs";import{resolve as dY}from"path";import{existsSync as p8}from"fs";import{existsSync as l8,readdirSync as n8}from"fs";import{extname as DX,resolve as fY}from"path";import i8 from"process";var SZ=import.meta.require;class pY{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(!tX(Q))return!0;return rX(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 $=tX(Y)?rX(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 mY{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 uQ=new pY,dX=new mY;function VZ(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function EZ(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function TZ(Q){return Q.getStats().size*2}var o8={createKey:VZ,isEquivalent:EZ,estimateMemoryUsage:TZ},uY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function gY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function cY(Q){return gY(Q).flatMap((Y)=>uY.map((Z)=>KQ(Q.directory,`${Y}${Z}`)))}function lY(Q={}){let X=KQ(Q.cwd||NZ.cwd());return Array.from(new Set([X,KQ(X,"config"),KQ(X,".config"),Q.configDir?KQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}function CZ(Q={}){return lY(Q).flatMap((X)=>cY({directory:X,name:Q.name,alias:Q.alias}))}function xZ(Q={}){return CZ(Q).find((X)=>OZ(X))??null}function e8(Q={}){return xZ(Q)!==null}var I0=Object.defineProperty,F0=(Q)=>Q;function M0(Q,X){this[Q]=F0.bind(null,X)}var D0=(Q,X)=>{for(var Y in X)I0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:M0.bind(X,Y)})},S0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),sY={};D0(sY,{withErrorRecovery:()=>rY,tryLoadConfig:()=>i0,loadConfigWithResult:()=>l0,loadConfig:()=>YZ,isRetryableError:()=>f0,isConfigNotFoundError:()=>h0,isBunfigError:()=>aY,globalPerformanceMonitor:()=>DQ,globalCache:()=>wQ,getEnvOrDefault:()=>p0,generateConfigTypes:()=>s0,defaultGeneratedDir:()=>qZ,defaultConfigDir:()=>_Z,deepMergeWithArrayStrategy:()=>uX,deepMerge:()=>eY,createLibraryConfig:()=>o0,config:()=>n0,bunfigPlugin:()=>t0,applyEnvVarsToConfig:()=>jQ,TypeGenerationError:()=>PX,SchemaValidationError:()=>MQ,PluginError:()=>yX,PerformanceMonitor:()=>fX,FileSystemError:()=>kX,ErrorFactory:()=>XQ,EnvVarError:()=>aQ,EnvProcessor:()=>YX,ConfigValidator:()=>gX,ConfigValidationError:()=>CX,ConfigNotFoundError:()=>rQ,ConfigMergeError:()=>xX,ConfigLoader:()=>cX,ConfigLoadError:()=>FQ,ConfigFileLoader:()=>ZX,ConfigCache:()=>hX,CacheUtils:()=>$Z,BunfigError:()=>d,BrowserConfigError:()=>bX,ArrayMergeStrategies:()=>JZ});class hX{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(!eX(Q))return!0;return QY(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 $=eX(Y)?QY(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 fX{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 V0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function E0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function T0(Q){return Q.getStats().size*2}function pX(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)=>iQ(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]=pX(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)=>iQ(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 iQ(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(!iQ(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(!iQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function O0(Q,X){if(!iY(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 pX(X,Z)}catch{return null}}catch{return null}}async function N0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||EX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=lQ(Z,`${U}${G}`),_=await O0(J,Y);if(_!==null)return _}try{let U=lQ(Z,"package.json");if(iY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return pX(Y,J)}catch{}}}catch{}return Y}function C0(Q,X={}){let Y=cQ.cwd();while(Y.includes("storage"))Y=ZY(Y,"..");let Z=ZY(Y,Q||"");if(X?.relative)return uZ(cQ.cwd(),Z);return Z}async function x0(){try{let Q=await N0({name:"clarity",defaultConfig:hQ,cwd:cQ.cwd(),endpoint:"",headers:{}});return{...hQ,...Q}}catch{return hQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function k0(){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 oY{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 sQ{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={...OX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new oY,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??x.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{...fQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...fQ};return{...fQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:OX.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 iZ(this.config.logDirectory,JY.F_OK|JY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await sZ(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(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=UY(this.currentLogFile,"a",420),nZ($,J,{flag:"a"}),HY($),$!==void 0)JX($),$=void 0;if((await JQ(this.currentLogFile)).size===0){if(await _X(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{JX($)}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(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 UX(16).toString("hex")}generateKey(){return UX(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=UX(16),Z=gZ("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 JQ(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 SQ(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 JQ(Y).catch(()=>null))try{if(await GY(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await VQ(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 _X(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 JQ(Y).catch(()=>null))await GY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await SQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await VQ(GQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=$Y(Q),Z=lZ(X),$=_Y();await oZ(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()})),GX(this.currentLogFile))try{let Q=UY(this.currentLogFile,"r+");HY(Q),JX(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 SQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await VQ(GQ(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=x.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 _=HZ[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(`
|
|
3
|
+
`);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}
|
|
4
|
+
`;if(G)J+=`${G}
|
|
5
|
+
`;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("\u25D0"),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(_+=`
|
|
6
|
+
`,_=_.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("\u2713"),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 sQ(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(!GX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $Y(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=cZ("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(`
|
|
7
|
+
`),U=Math.max(...H.map((q)=>q.length))+2,G=`\u250C${"\u2500".repeat(U)}\u2510`,J=`\u2514${"\u2500".repeat(U)}\u2518`,_=H.map((q)=>{let A=" ".repeat(U-q.length-2);return`\u2502 ${q}${A} \u2502`});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}
|
|
8
|
+
`.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();x.stdin.removeListener("data",Y);try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!1)}catch{}x.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!0)}catch{}x.stdin.resume(),x.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("\u25D0");console.error(`${G} ${U} ${M.cyan(Y)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
9
|
+
`.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;x.stdout.write(`${"\r".padEnd(x.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()||!x.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("\u2501".repeat(Z)),U=M.gray("\u2501".repeat($)),G=`[${H}${U}]`,J=`${Y}%`.padStart(4),_=Q.message?` ${Q.message}`:"",q=X||Y===100?M.green("\u2713"):M.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${G} ${J}${_}`,W=x.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,x.stdout.write(Q.lastRenderedLine),X)x.stdout.write(`
|
|
10
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||S()||!x.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 SQ(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=GQ(this.config.logDirectory,Z);if(Q.before)try{if((await JQ(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 VQ(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 dQ(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)=>oQ(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]=dQ(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)=>oQ(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 mX(Q,X,Y="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return Y==="replace"?X:dQ(Q,X);if(Array.isArray(Q))return Y==="replace"?X:dQ(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[$]=dQ(U,H);else if(F(H)&&F(U))Z[$]=mX(U,H,Y);else Z[$]=H}return Z}function oQ(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(!oQ(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(!oQ(Q[$],X[$]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function bQ(Q,X,Y="replace"){if(!nY(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return mX(X,$,Y)}catch{return null}}catch{return null}}function P0(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)P.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=IQ.env[W]||IQ.env[I];if(B!==void 0){if(Y)P.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 R=JSON.parse(B);if(Array.isArray(R))J[_]=R;else J[_]=B.split(",").map((C)=>C.trim())}catch{J[_]=B.split(",").map((R)=>R.trim())}else J[_]=B}}}return J}return H($)}async function b0({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($)?P0(Q,$,H):$,_=Y||IQ.cwd(),q=[".ts",".js",".mjs",".cjs",".json"];if(H)P.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 R of B){if(H)P.info(`Searching for configuration in: ${R}`);let V=[b(_,"config"),b(_,".config")].concat(Z?[b(_,Z)]:[]).includes(R)?[...A,...z,...W,...I]:[...z,...A,...I,...W];for(let g of V)for(let v of q){let c=b(R,`${g}${v}`),oX=await bQ(c,J,G);if(oX!==null){if(H)P.success(`Configuration loaded from: ${c}`);return oX}}}if(Q){let R=b(HX(),".config",Q),C=["config",`${Q}.config`];if(X)C.push(`${X}.config`);if(H)P.info(`Checking user config directory: ${R}`);for(let V of C)for(let g of q){let v=b(R,`${V}${g}`),c=await bQ(v,J,G);if(c!==null){if(H)P.success(`Configuration loaded from user config directory: ${v}`);return c}}}if(Q){let R=b(HX(),".config"),C=[`.${Q}.config`];if(X)C.push(`.${X}.config`);if(H)P.info(`Checking user config directory for dotfile configs: ${R}`);for(let V of C)for(let g of q){let v=b(R,`${V}${g}`),c=await bQ(v,J,G);if(c!==null){if(H)P.success(`Configuration loaded from user config directory dotfile: ${v}`);return c}}}if(Q){let R=HX(),C=[`.${Q}.config`,`.${Q}`];if(X)C.push(`.${X}.config`),C.push(`.${X}`);if(H)P.info(`Checking user home directory for dotfile configs: ${R}`);for(let V of C)for(let g of q){let v=b(R,`${V}${g}`),c=await bQ(v,J,G);if(c!==null){if(H)P.success(`Configuration loaded from user home directory: ${v}`);return c}}}try{let R=b(_,"package.json");if(nY(R)){let C=await import(R),V=C[Q];if(!V&&X){if(V=C[X],V&&H)P.success(`Using alias "${X}" configuration from package.json`)}if(V&&typeof V==="object"&&!Array.isArray(V))try{if(H)P.success(`Configuration loaded from package.json: ${V===C[Q]?Q:X}`);return mX(J,V,G)}catch(g){if(H)P.warn("Failed to merge package.json config:",g)}}}catch(R){if(H)P.warn("Failed to load package.json:",R)}if(H)P.info(`No configuration found for "${Q}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return J}function y0(Q,X={}){let Y=gQ.cwd();while(Y.includes("storage"))Y=YY(Y,"..");let Z=YY(Y,Q||"");if(X?.relative)return pZ(gQ.cwd(),Z);return Z}async function v0(){try{let Q=await b0({name:"clarity",alias:"logging",defaultConfig:pQ,cwd:gQ.cwd()});return{...pQ,...Q||{}}}catch{return pQ}}function E(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function d0(){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 tY{async format(Q){let X=await d0(),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:WQ.pid,hostname:X(),environment:WQ.env.NODE_ENV||"development",platform:WQ.platform,version:WQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:WQ.env.NODE_ENV||WQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class tQ{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={...NX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new tY,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??w.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{...mQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...mQ};return{...mQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:NX.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!E()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await Q0(this.config.logDirectory,zY.F_OK|zY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await X0(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(!EQ(this.currentLogFile))await WX(this.currentLogFile,"",{mode:420});if($=WY(this.currentLogFile,"a",420),eZ($,J,{flag:"a"}),AY($),$!==void 0)AX($),$=void 0;if((await qQ(this.currentLogFile)).size===0){if(await WX(this.currentLogFile,J,{flag:"w",mode:420}),(await qQ(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{AX($)}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 AQ(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 AQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return AQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(E())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 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 qX(16).toString("hex")}generateKey(){return qX(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=qX(16),Z=tZ("aes-256-gcm",X,Y),$=i.isBuffer(Q)?Q:i.from(Q,"utf8"),H=Z.update($),U=Z.final(),G=H.length+U.length,J=Z.getAuthTag(),_=i.allocUnsafe(16+G+16);return Y.copy(_,0),H.copy(_,16),U.copy(_,16+H.length),J.copy(_,16+G),{encrypted:_,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=RY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(i.from(i.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(E())return;if(!this.shouldWriteToFile())return;let Q=await qQ(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 TQ(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 qQ(Y).catch(()=>null))try{if(await BY(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await OQ(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 WX(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 qQ(Y).catch(()=>null))await BY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await TQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await OQ(AQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=qY(Q),Z=aZ(X),$=RY();await $0(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);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(X);console.log(X)}}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()})),EQ(this.currentLogFile))try{let Q=WY(this.currentLogFile,"r+");AY(Q),AX(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(!E()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await TQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await OQ(AQ(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.shouldStyleConsole()?K.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E())return!1;let Q=typeof w.env.NO_COLOR<"u",X=w.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof w.stderr<"u"&&w.stderr.isTTY||typeof w.stdout<"u"&&w.stdout.isTTY)}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=w.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${K.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 $}formatMarkdown(Q){if(!Q)return Q;let X=Q;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,$)=>{let H=K.underline(K.blue(Z)),U=this.toAbsoluteFilePath($);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let G=`file://${encodeURI(U)}`,J="\x1B]8;;",_="\x1B\\";return`\x1B]8;;${G}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),X=X.replace(/`([^`]+)`/g,(Y,Z)=>K.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>K.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>K.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>K.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>K.strikethrough(Z)),X}supportsHyperlinks(){if(E())return!1;let Q=w.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 X=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let X=Q;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Y=w.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(Y0(X)||X.startsWith("./")||X.startsWith("../"))X=Z0(X);else return null;return EQ(X)?X:null}catch{return null}}buildOutputTexts(Q){let X=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Y=Q.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Y}}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);let{consoleText:J,fileText:_}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":UZ[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(J),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:K.green(J),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.error(W),G){let I=G.split(`
|
|
11
|
+
`);for(let B of I)if(B.trim()&&!B.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:K.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!E()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let q=`${H} ${this.environment}.${Q.toUpperCase()}: ${_}
|
|
12
|
+
`;if(G)q+=`${G}
|
|
13
|
+
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,X=""){let Y={update:(G,J)=>{},finish:(G)=>{},interrupt:(G,J)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:X||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!E()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(G,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,G),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!E()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(G)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,G)},interrupt:(G,J="info")=>{if(!E()&&w.stdout.isTTY)w.stdout.write(`
|
|
14
|
+
`);if(this[J==="warning"?"warn":J](G),this.activeProgressBar&&this.shouldStyleConsole()&&!E()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=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("\u25D0"),tag:Y,message:`${K.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(_+=`
|
|
15
|
+
`,_=_.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":K.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!E())console.error(_.trim());if(this.shouldWriteToFile())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 tQ(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(E())throw Error("createReadStream is not supported in browser environments");if(!EQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return qY(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=i.isBuffer(Q)?Q:i.from(Q,"base64"),$=Z.subarray(0,16),H=Z.subarray(Z.length-16),U=Z.subarray(16,Z.length-16),G=rZ("aes-256-gcm",Y,$);G.setAuthTag(H);let J=G.update(U),_=G.final(),q=J.length+_.length,A=i.allocUnsafe(q);return J.copy(A,0),_.copy(A,J.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 E()}isServerMode(){return!E()}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),{consoleText:$,fileText:H}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let G=$.split(`
|
|
16
|
+
`),J=Math.max(...G.map((z)=>z.length))+2,_=`\u250C${"\u2500".repeat(J)}\u2510`,q=`\u2514${"\u2500".repeat(J)}\u2518`,A=G.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:K.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:K.cyan(_),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:K.cyan(q),showTimestamp:!1}))}else if(!E())console.error(`${Z} ${this.environment}.INFO: [BOX] ${H}`);let U=`${Z} ${this.environment}.INFO: [BOX] ${H}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Q){if(E())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${K.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();w.stdin.removeListener("data",Y);try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!1)}catch{}w.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!0)}catch{}w.stdin.resume(),w.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 J=/%([sdijfo%])/g,_=0;if(Y=Q.replace(J,(q,A)=>{if(A==="%")return"%";if(_>=X.length)return q;let z=X[_++];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}}),_<X.length)Y+=` ${X.slice(_).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",_=this.options.showIcons===!1?"":`${K.blue("\u25D0")} `;console.error(`${_}${J} ${K.cyan(Z)}`)}let G=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
18
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!w.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=K.green("\u2501".repeat(Z)),U=K.gray("\u2501".repeat($)),G=`[${H}${U}]`,J=`${Y}%`.padStart(4),_=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":X||Y===100?K.green("\u2713"):K.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${G} ${J}${_}`,W=w.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,w.stdout.write(Q.lastRenderedLine),X)w.stdout.write(`
|
|
19
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||E()||!w.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(E()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await TQ(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=AQ(this.config.logDirectory,Z);if(Q.before)try{if((await qQ(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 OQ(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)}}}async function rY(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,U=Error("Unknown error occurred");for(let G=0;G<=Y;G++)try{return await Q()}catch(J){if(U=J instanceof Error?J:Error(String(J)),G===Y||!$(U))break;if(Z>0)await new Promise((_)=>setTimeout(_,Z))}if(H!==void 0)return H;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function aY(Q){return Q instanceof d}function h0(Q){return Q instanceof rQ}function f0(Q){if(aY(Q))return Q.code==="FILE_SYSTEM_ERROR"||Q.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>Q.message.toLowerCase().includes(Y.toLowerCase()))}class YX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,X)=>X==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let X=Q.toLowerCase();return["true","1","yes"].includes(X)}},{name:"number",canParse:(Q,X)=>X==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let X=Number(Q);if(Number.isNaN(X))throw TypeError(`Cannot parse "${Q}" as number`);return X}},{name:"array",canParse:(Q,X)=>X==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let X=JSON.parse(Q);if(Array.isArray(X))return X}catch{}return Q.split(",").map((X)=>X.trim())}},{name:"json",canParse:(Q,X)=>X==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(X){throw Error(`Cannot parse "${Q}" as JSON: ${X}`)}}}]}async applyEnvironmentVariables(Q,X,Y={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:H=!0,customParsers:U={},verbose:G=!1,trackPerformance:J=!0}=Y,_=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let q=Z||this.generateEnvPrefix(Q),A={...X};return this.processObject(A,[],q,{useCamelCase:$,useBackwardCompatibility:H,customParsers:U,verbose:G,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return DQ.track("applyEnvironmentVariables",_,{configName:Q});return _()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,X){if(!X)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],G=U.map((q)=>this.formatEnvKey(q,Z.useCamelCase)),J=`${Y}_${G.join("_")}`,_=Z.useBackwardCompatibility?`${Y}_${U.map((q)=>q.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,U,Y,Z);else{let q=NQ.env[J]||(_?NQ.env[_]:void 0);if(q!==void 0){if(Z.verbose){let A=NQ.env[J]?J:_}try{Q[$]=this.parseEnvironmentValue(q,typeof H,J,Z.customParsers,Z.configName)}catch(A){if(A instanceof aQ)throw A;throw XQ.envVar(J,q,typeof H,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[H,U]of Object.entries(Z))try{return U(Q)}catch{continue}for(let H of this.defaultParsers)if(H.canParse(Q,X))try{return H.parse(Q)}catch{throw XQ.envVar(Y,Q,`${X} (via ${H.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(NQ.env))if(Z.startsWith(Y)&&$!==void 0)X[Z]=$;return X}validateEnvironmentVariable(Q,X,Y){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(Y)try{this.parseEnvironmentValue(Q,X,Y,{})}catch($){Z.push(`Cannot parse value "${X}" as ${Y}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,X,Y={}){let{prefix:Z,format:$="text"}=Y,H=Z||this.generateEnvPrefix(Q),U=[];switch(this.extractEnvVarInfo(X,[],H,U),$){case"markdown":return this.formatAsMarkdown(U,Q);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],G=`${Y}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,U,Y,Z);else Z.push({key:G,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${U.join(".")}`,example:this.generateExample(H)})}}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,X){let Y=`Environment Variables for ${X}:
|
|
20
|
+
|
|
21
|
+
`;for(let Z of Q)Y+=`${Z.key}
|
|
22
|
+
`,Y+=` Type: ${Z.type}
|
|
23
|
+
`,Y+=` Description: ${Z.description}
|
|
24
|
+
`,Y+=` Example: ${Z.example}
|
|
25
|
+
|
|
26
|
+
`;return Y}formatAsMarkdown(Q,X){let Y=`# Environment Variables for ${X}
|
|
27
|
+
|
|
28
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
29
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
30
|
+
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
31
|
+
`;return Y}}function p0(Q,X){let Y=ZZ("process");if(typeof Y>"u"||!Y.env)return X;let Z=Y.env[Q];return Z!==void 0?Z:X}function eY(Q,X,Y={}){return QZ(Q,X,Y,new WeakMap)}function QZ(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:U}=Y;if(X===null||X===void 0)return H?Q:X;if(U){let G=U(Q,X);if(G!==void 0)return G}if(Array.isArray(X)||Array.isArray(Q))return XZ(Q,X,$,Z);if(!p(X)||!p(Q))return X;return c0(Q,X,Y,Z)}function XZ(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return m0(Q,X);case"smart":return u0(Q,X,Z);default:return X}return X}function m0(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>TX($,Z)))Y.push(Z);return Y}function u0(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(p(X[0])&&p(Q[0]))return g0(Q,X,Y);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}function g0(Q,X,Y){let Z=[...X];for(let $ of Q){if(!p($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let G of H)if(G in $){if(Z.find((_)=>p(_)&&(G in _)&&_[G]===$[G])){U=!0;break}}if(!U)Z.push($)}return Z}function c0(Q,X,Y,Z){let $=X;if(p($)&&Z.has($))return Z.get($);let H={...Q};if(p($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let G=$[U],J=H[U];if(Y.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){H[U]=G;continue}if(p(G)&&p(J))H[U]=QZ(J,G,Y,Z);else if(Array.isArray(G)||Array.isArray(J))H[U]=XZ(J,G,Y.arrayMergeMode||"smart",Z);else H[U]=G}return H}function uX(Q,X,Y="replace"){return eY(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function TX(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(!TX(Q[Y],X[Y]))return!1;return!0}if(p(Q)&&p(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(!TX(Q[$],X[$]))return!1}return!0}return!1}function p(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class ZX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:U=!0,verbose:G=!1}=Y;if($){let _=wQ.getWithFileCheck("file",Q);if(_){if(G)console.log(`Configuration loaded from cache: ${Q}`);return _}}let J=async()=>{if(!CQ(Q))return null;try{let _=`?t=${Date.now()}`,q=await import(Q+_),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new FQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new FQ(Q,Error("Configuration must export a valid object"),"unknown");let R={config:uX(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)wQ.setWithFileCheck("file",R,Q,H);return R}catch(_){throw _ instanceof Error?XQ.configLoad(Q,_):XQ.configLoad(Q,Error(String(_)))}};if(U)return DQ.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){let Z=this.generateNamePatterns(Q,Y),$=[];for(let H of Z)for(let U of this.extensions)$.push(zX(X,`${H}${U}`));return $}generateNamePatterns(Q,X){let Y=[];if(Y.push("config",".config"),Q)Y.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(X){if(Y.push(X,`.${X}.config`,`${X}.config`,`.${X}`),Q)Y.push(`${Q}.${X}.config`,`.${Q}.${X}.config`)}return Y.filter(Boolean)}checkFileAccess(Q){return rY(async()=>{return CQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!CQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let G=zX(Q,`${H}${U}`);if(await this.checkFileAccess(G))Z.push(G)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let G=zX(Q,U);if(await this.checkFileAccess(G))Z.push(G)}}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((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!CQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),H=$(Q,"utf8");JSON.parse(H)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}class gX{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:G=!0,verbose:J=!1}=Y,_=async()=>{let q=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:G,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...U],z);else return this.validateWithJSONSchema(Q,X,z)}catch(W){return q.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:q,warnings:A}}};if(G)return await DQ.track("validateConfiguration",_);return _()}async validateWithSchemaFile(Q,X,Y){try{if(!H0(X))throw new MQ(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new MQ(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,H){if(H.validateTypes&&X.type){let U=Array.isArray(Q)?"array":typeof Q,G=Array.isArray(X.type)?X.type:[X.type];if(!G.includes(U)){if(Z.push({path:Y,message:`Expected type ${G.join(" or ")}, got ${U}`,expected:G.join(" or "),actual:U,rule:"type"}),H.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),H.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let U=0;U<Q.length;U++){let G=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let U=Q;if(H.validateRequired&&X.required){for(let G of X.required)if(!(G in U)){if(Z.push({path:Y?`${Y}.${G}`:G,message:`Missing required property '${G}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[G,J]of Object.entries(X.properties))if(G in U){let _=Y?`${Y}.${G}`:G;if(this.validateObjectAgainstSchema(U[G],J,_,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let G=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!G.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let U=this.getValueByPath(Q,H.path),G=this.validateWithRule(U,H,H.path);if(Z.push(...G),Y.stopOnFirstError&&Z.length>0)break}catch(U){Z.push({path:H.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,H,U]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(U)})}return X}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:GZ},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class cX{fileLoader=new ZX;envProcessor=new YX;validator=new gX;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...U}=Q;try{if(Y?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let G;try{G=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){let _=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(_)throw J;G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let q=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!q&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),z=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(_&&(z||q))throw J;if(A&&(!_||!z))G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!_)G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||H)await this.validateConfiguration(G.config,$,H,U.name);if(Y?.enabled&&G)this.cacheResult(U.name||"",G,Y,U);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:U.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)l.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);G.metrics=J}return G}catch(G){let J=Date.now()-X;throw l.error(`Configuration loading failed after ${J}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:U,defaultConfig:G,checkEnv:J=!0,arrayStrategy:_="replace",verbose:q=!1}=Q,A=H||$Q.cwd(),z=[],W=await this.loadLocalConfiguration(Z,$,A,U,G,_,q,J,Y);if(W)return z.push(...this.getLocalSearchPaths(Z,$,A,U)),this.finalizeResult(W,z,J,Z,q);let I=await this.loadHomeConfiguration(Z,$,G,_,q,J);if(I)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(I,z,J,Z,q);let B=await this.loadPackageJsonConfiguration(Z,$,A,G,_,q,J);if(B)return z.push(y(A,"package.json")),this.finalizeResult(B,z,J,Z,q);if(z.push(...this.getAllSearchPaths(Z,$,A,U)),X)throw XQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,G,J,q),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,G,J){let _=G?jQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let A of q){if(U)l.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,_,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(W){if(U)l.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let U=H?jQ(Q,Y,$):Y,G=[y(UQ(),".config",Q),y(UQ(),".config"),UQ()];for(let J of G){if($)l.info(`Checking home directory: ${J}`);let _=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(_,U,{arrayStrategy:Z,verbose:$});if(q){if($)l.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let G=U?jQ(Q,Z,H):Z;try{let J=y(Y,"package.json");if(!VX(J))return null;let _=await import(J),q=_[Q],A=Q;if(!q&&X)q=_[X],A=X;if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)l.success(`Configuration loaded from package.json: ${A}`);return{config:uX(G,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)l.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:jQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let H=Y(Q);if(H)$.push(...H)}if(X){let H=await this.validator.validateConfiguration(Q,X);if(!H.isValid)$.push(...H.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if($.length>0)throw XQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return wQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);wQ.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias)Y.push(`alias:${X.alias}`);if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return Array.from(new Set([Q,y(Q,"config"),y(Q,".config"),X?y(Q,X):void 0].filter(Boolean)))}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(y(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),H=[];for(let U of $)H.push(...this.fileLoader.generateConfigPaths(Q,U,X));return H}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[y(UQ(),".config",Q),y(UQ(),".config"),UQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function SY(Q){let Y=!(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 Y||Z}async function l0(Q){return a.loadConfig({...Q,__strictErrorHandling:!0})}async function YZ(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await a.loadConfig(Q);else Z=await a.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",H=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||H.includes("config"))&&Q.verbose)l.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let G=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await a.applyEnvironmentVariables(G.name||"",X,!0,G.verbose||!1))?.config??X;return X}}async function n0(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:X}=await import("process");try{return(await a.loadConfig({name:Q,cwd:X(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&SY(Y)))return(await a.applyEnvironmentVariables(Q,{},!0,!1)).config;throw Y}}try{return(await a.loadConfig({...Q,cwd:Q.cwd||$Q.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&SY(X)))return(await a.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw X}}async function i0(Q,X,Y="replace"){let Z=new ZX;try{let $=await Z.loadFromPath(Q,X,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return $?$.config:null}catch{return null}}function jQ(Q,X,Y=!1){let Z=new YX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let A=[...G,_],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,I;for(let B of z)if(W=$Q.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof q==="boolean")J[_]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))J[_]=B}else if(Array.isArray(q))try{J[_]=JSON.parse(W)}catch{J[_]=W.split(",").map((B)=>B.trim())}else J[_]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))J[_]=H(q,A)}return J}return H(X)}function s0(Q){let X=y($Q.cwd(),Q.configDir),Y=y($Q.cwd(),Q.generatedDir),Z=y(Y,"config-types.ts");if(!VX(XY(Z)))vZ(XY(Z),{recursive:!0,mode:511});let $=VX(X)?dZ(X).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],H=`// Generated by bunfig v${D8}
|
|
32
|
+
export type ConfigNames = ${$.length?`'${$.join("' | '")}'`:"string"}
|
|
33
|
+
`;hZ(Z,H,{mode:438})}function o0(Q){let X=null,Y=null,Z=()=>{if(!Y)Y=YZ(Q).then((H)=>{return X=H,H},(H)=>{let U="defaultConfig"in Q?Q.defaultConfig:{};if(X=U,"verbose"in Q&&Q.verbose)l.warn("Config loading failed, using defaults:",[H instanceof Error?H:Error(String(H))]);return U});return Y},$="defaultConfig"in Q?Q.defaultConfig:{};return X=$,Z(),new Proxy({},{get(H,U){if(X)return X[U];let G=$[U];return Z(),G},has(H,U){return U in(X||$)},ownKeys(){return Object.keys(X||$)},getOwnPropertyDescriptor(H,U){return Object.getOwnPropertyDescriptor(X||$,U)},set(H,U,G){if(!X)X={...$};return X[U]=G,!0}})}function t0(Q){let X=wY(G0.cwd(),Q?.configDir||"./config");function Y(){if(!U0(X))return[];let $=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),H=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=J0(X).filter((J)=>$.has(BX(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),G=new Map;for(let{base:J,file:_}of U){let q=BX(_).toLowerCase(),A=G.get(J);if(!A){G.set(J,_);continue}let z=BX(A).toLowerCase();if(H.indexOf(q)<H.indexOf(z))G.set(J,_)}return Array.from(G.entries()).map(([J,_])=>({base:J,file:_})).sort((J,_)=>J.base.localeCompare(_.base))}function Z(){let $=Y(),H=$.map((_)=>_.base),U=H.length?H.map((_)=>`'${_}'`).join(" | "):"string",G=$.length?`{
|
|
34
|
+
${$.map((_)=>{let q=wY(X,_.file).replace(/\\/g,"/");return` '${_.base}': typeof import('${q}').default`}).join(`,
|
|
35
|
+
`)}
|
|
36
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
37
|
+
export type ConfigByName = ${G}
|
|
38
|
+
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
|
+
export type ConfigOf = Config
|
|
40
|
+
`}return{name:"bunfig-plugin",setup($){$.onResolve({filter:/^virtual:bunfig-types$/},(H)=>{return{path:H.path,namespace:"bunfig-virtual"}}),$.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var ZZ,wQ,DQ,$Z,r0,a0,VY,hQ,OX,k,M,e0,EY,Q8,TY,X8,Y8,KX,Z8,OY,NY,jX,$8,H8,U8,J8,fQ,HZ,G8,P,_8,q8,CY,pQ,NX,T,K,A8,xY,W8,kY,z8,B8,IX,R8,PY,bY,w8,FX,L8,K8,j8,I8,F8,mQ,UZ,M8,D8="0.15.6",d,rQ,FQ,CX,xX,aQ,kX,PX,MQ,bX,yX,XQ,JZ,GZ,l,a,_Z,qZ,S8=S0(async()=>{ZZ=import.meta.require,wQ=new hX,DQ=new fX,$Z={createKey:V0,isEquivalent:E0,estimateMemoryUsage:T0},r0=lQ(EX.cwd(),"config"),a0=lQ(EX.cwd(),"src/generated"),VY=cQ.env.CLARITY_LOG_DIR||mZ(C0(),"logs"),hQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:VY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},OX=await x0(),k={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"},M=k,e0=k.red,EY=k.green,Q8=k.yellow,TY=k.blue,X8=k.magenta,Y8=k.cyan,KX=k.white,Z8=k.gray,OY=k.bgRed,NY=k.bgYellow,jX=k.bold,$8=k.dim,H8=k.italic,U8=k.underline,J8=k.reset,fQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},HZ={debug:"\uD83D\uDD0D",info:TY("\u2139"),success:EY("\u2713"),warning:NY(KX(jX(" WARN "))),error:OY(KX(jX(" ERROR ")))},G8=new sQ("stacks"),P=new sQ("bunfig",{showTags:!0}),_8=b(IQ.cwd(),"config"),q8=b(IQ.cwd(),"src/generated"),CY=gQ.env.CLARITY_LOG_DIR||fZ(y0(),"logs"),pQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:CY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},NX=await v0(),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,A8=T.red,xY=T.green,W8=T.yellow,kY=T.blue,z8=T.magenta,B8=T.cyan,IX=T.white,R8=T.gray,PY=T.bgRed,bY=T.bgYellow,w8=T.bgGray,FX=T.bold,L8=T.dim,K8=T.italic,j8=T.underline,I8=T.strikethrough,F8=T.reset,mQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},UZ={debug:"\uD83D\uDD0D",info:kY("\u2139"),success:xY("\u2713"),warning:bY(IX(FX(" WARN "))),error:PY(IX(FX(" ERROR ")))},M8=new tQ("stacks"),d=class extends Error{timestamp;context;constructor(X,Y={}){super(X);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,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 X=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,Z])=>`${Y}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${X}`}},rQ=class extends d{code="CONFIG_NOT_FOUND";constructor(X,Y,Z){let $=Z?` or alias "${Z}"`:"";super(`Configuration "${X}"${$} not found`,{configName:X,alias:Z,searchPaths:Y,searchPathCount:Y.length})}},FQ=class extends d{code="CONFIG_LOAD_ERROR";constructor(X,Y,Z){super(`Failed to load configuration from "${X}": ${Y.message}`,{configPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},CX=class extends d{code="CONFIG_VALIDATION_ERROR";constructor(X,Y,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:Y,errorCount:Y.length})}},xX=class extends d{code="CONFIG_MERGE_ERROR";constructor(X,Y,Z,$){super(`Failed to merge configuration from "${X}" with "${Y}": ${Z.message}`,{sourcePath:X,targetPath:Y,configName:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},aQ=class extends d{code="ENV_VAR_ERROR";constructor(X,Y,Z,$){super(`Failed to parse environment variable "${X}" with value "${Y}" as ${Z}`,{envKey:X,envValue:Y,expectedType:Z,configName:$})}},kX=class extends d{code="FILE_SYSTEM_ERROR";constructor(X,Y,Z){super(`File system ${X} failed for "${Y}": ${Z.message}`,{operation:X,path:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},PX=class extends d{code="TYPE_GENERATION_ERROR";constructor(X,Y,Z){super(`Failed to generate types from "${X}" to "${Y}": ${Z.message}`,{configDir:X,outputPath:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},MQ=class extends d{code="SCHEMA_VALIDATION_ERROR";constructor(X,Y,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:X,configName:Z,validationErrors:Y,errorCount:Y.length})}},bX=class extends d{code="BROWSER_CONFIG_ERROR";constructor(X,Y,Z,$){super(`Failed to fetch configuration from "${X}": ${Y} ${Z}`,{endpoint:X,status:Y,statusText:Z,configName:$})}},yX=class extends d{code="PLUGIN_ERROR";constructor(X,Y,Z){super(`Plugin "${X}" failed during ${Y}: ${Z.message}`,{pluginName:X,operation:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},XQ={configNotFound(Q,X,Y){return new rQ(Q,X,Y)},configLoad(Q,X,Y){return new FQ(Q,X,Y)},configValidation(Q,X,Y){return new CX(Q,X,Y)},configMerge(Q,X,Y,Z){return new xX(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new aQ(Q,X,Y,Z)},fileSystem(Q,X,Y){return new kX(Q,X,Y)},typeGeneration(Q,X,Y){return new PX(Q,X,Y)},schemaValidation(Q,X,Y){return new MQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new bX(Q,X,Y,Z)},plugin(Q,X,Y){return new yX(Q,X,Y)}},JZ={replace:"replace",concat:"concat",smart:"smart"},GZ=/^https?:\/\//,l=new tQ("bunfig",{showTags:!0}),a=new cX,_Z=y($Q.cwd(),"config"),qZ=y($Q.cwd(),"src/generated")});function V8(Q,X={}){let Y=nQ.cwd();while(Y.includes("storage"))Y=LY(Y,"..");let Z=LY(Y,Q||"");if(X?.relative)return q0(nQ.cwd(),Z);return Z}var E8=nQ.env.CLARITY_LOG_DIR||_0(V8(),"logs"),AZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:E8,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},eQ={...AZ},z$=(async()=>{try{let{loadConfig:Q}=await S8().then(()=>sY),X=await Q({name:"clarity",alias:"logging",defaultConfig:AZ,cwd:nQ.cwd()});if(X)Object.assign(eQ,X)}catch{}return eQ})();function O(){if(r.env.NODE_ENV==="test"||r.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function T8(){if(r.env.NODE_ENV==="test"||r.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof r<"u"){let Q=r.type;if(Q==="renderer"||Q==="worker")return!1;return!!(r.versions&&(r.versions.node||r.versions.bun))}return!1}class WZ{async format(Q){let X=await T8(),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:RQ.pid,hostname:X(),environment:RQ.env.NODE_ENV||"development",platform:RQ.platform,version:RQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:RQ.env.NODE_ENV||RQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var N={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"},j=N,B$=N.red,O8=N.green,R$=N.yellow,N8=N.blue,w$=N.magenta,L$=N.cyan,yY=N.white,K$=N.gray,C8=N.bgRed,x8=N.bgYellow,j$=N.bgGray,vY=N.bold,I$=N.dim,F$=N.italic,M$=N.underline,D$=N.strikethrough,S$=N.reset,MX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},k8={debug:"\uD83D\uDD0D",info:N8("\u2139"),success:O8("\u2713"),warning:x8(yY(vY(" WARN "))),error:C8(yY(vY(" ERROR ")))};class $X{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={...eQ},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new WZ,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??L.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,level:this.options.level??"info"},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{...MX,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...MX};return{...MX,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:eQ.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!O()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await R0(this.config.logDirectory,FY.F_OK|FY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await w0(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:s.from(Q);try{if(!xQ(this.currentLogFile))await LX(this.currentLogFile,"",{mode:420});if($=IY(this.currentLogFile,"a",420),B0($,J,{flag:"a"}),jY($),$!==void 0)wX($),$=void 0;if((await zQ(this.currentLogFile)).size===0){if(await LX(this.currentLogFile,J,{flag:"w",mode:420}),(await zQ(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{wX($)}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 BQ(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 BQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return BQ(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,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 RX(16).toString("hex")}generateKey(){return RX(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=RX(16),Z=A0("aes-256-gcm",X,Y),$=s.isBuffer(Q)?Q:s.from(Q,"utf8"),H=Z.update($),U=Z.final(),G=H.length+U.length,J=Z.getAuthTag(),_=s.allocUnsafe(16+G+16);return Y.copy(_,0),H.copy(_,16),U.copy(_,16+H.length),J.copy(_,16+G),{encrypted:_,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=DY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(s.from(s.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(O())return;if(!this.shouldWriteToFile())return;let Q=await zQ(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 kQ(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 zQ(Y).catch(()=>null))try{if(await MY(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await PQ(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 LX(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 zQ(Y).catch(()=>null))await MY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await kQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await PQ(BQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=KY(Q),Z=z0(X),$=DY();await j0(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);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(X);console.log(X)}}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()})),xQ(this.currentLogFile))try{let Q=IY(this.currentLogFile,"r+");jY(Q),wX(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 X=(await kQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await PQ(BQ(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.shouldStyleConsole()?j.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||O())return!1;let Q=typeof L.env.NO_COLOR<"u",X=L.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}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=L.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${j.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 $}formatMarkdown(Q){if(!Q)return Q;let X=Q;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,$)=>{let H=j.underline(j.blue(Z)),U=this.toAbsoluteFilePath($);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let G=`file://${encodeURI(U)}`,J="\x1B]8;;",_="\x1B\\";return`\x1B]8;;${G}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),X=X.replace(/`([^`]+)`/g,(Y,Z)=>j.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>j.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>j.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>j.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>j.strikethrough(Z)),X}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 X=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let X=Q;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Y=L.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(L0(X)||X.startsWith("./")||X.startsWith("../"))X=K0(X);else return null;return xQ(X)?X:null}catch{return null}}buildOutputTexts(Q){let X=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Y=Q.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Y}}async log(Q,X,...Y){if(!this.shouldLog(Q))return;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);let{consoleText:J,fileText:_}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":k8[Q],z=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:j.gray(J),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:j.green(J),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.error(W),G){let I=G.split(`
|
|
41
|
+
`);for(let B of I)if(B.trim()&&!B.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:j.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!O()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}let q=`${H} ${this.environment}.${Q.toUpperCase()}: ${_}
|
|
42
|
+
`;if(G)q+=`${G}
|
|
43
|
+
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,X=""){let Y={update:(G,J)=>{},finish:(G)=>{},interrupt:(G,J)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:X||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(G,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,G),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(G)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,G)},interrupt:(G,J="info")=>{if(!O()&&L.stdout.isTTY)L.stdout.write(`
|
|
44
|
+
`);if(this[J==="warning"?"warn":J](G),this.activeProgressBar&&this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":j.blue("\u25D0"),tag:Y,message:`${j.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(_+=`
|
|
45
|
+
`,_=_.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":j.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!O())console.error(_.trim());if(this.shouldWriteToFile())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 $X(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(O())throw Error("createReadStream is not supported in browser environments");if(!xQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return KY(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=s.isBuffer(Q)?Q:s.from(Q,"base64"),$=Z.subarray(0,16),H=Z.subarray(Z.length-16),U=Z.subarray(16,Z.length-16),G=W0("aes-256-gcm",Y,$);G.setAuthTag(H);let J=G.update(U),_=G.final(),q=J.length+_.length,A=s.allocUnsafe(q);return J.copy(A,0),_.copy(A,J.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,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),{consoleText:$,fileText:H}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let G=$.split(`
|
|
46
|
+
`),J=Math.max(...G.map((z)=>z.length))+2,_=`\u250C${"\u2500".repeat(J)}\u2510`,q=`\u2514${"\u2500".repeat(J)}\u2518`,A=G.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:j.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(_),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(q),showTimestamp:!1}))}else if(!O())console.error(`${Z} ${this.environment}.INFO: [BOX] ${H}`);let U=`${Z} ${this.environment}.INFO: [BOX] ${H}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Q){if(O())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${j.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();L.stdin.removeListener("data",Y);try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!1)}catch{}L.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!0)}catch{}L.stdin.resume(),L.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 J=/%([sdijfo%])/g,_=0;if(Y=Q.replace(J,(q,A)=>{if(A==="%")return"%";if(_>=X.length)return q;let z=X[_++];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}}),_<X.length)Y+=` ${X.slice(_).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",_=this.options.showIcons===!1?"":`${j.blue("\u25D0")} `;console.error(`${_}${J} ${j.cyan(Z)}`)}let G=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
48
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!L.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=j.green("\u2501".repeat(Z)),U=j.gray("\u2501".repeat($)),G=`[${H}${U}]`,J=`${Y}%`.padStart(4),_=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":X||Y===100?j.green("\u2713"):j.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${G} ${J}${_}`,W=L.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,L.stdout.write(Q.lastRenderedLine),X)L.stdout.write(`
|
|
49
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||O()||!L.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(O()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await kQ(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=BQ(this.config.logDirectory,Z);if(Q.before)try{if((await zQ(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 PQ(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)}}}var V$=new $X("stacks");class u extends Error{timestamp;context;constructor(Q,X={}){super(Q);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 Q=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,Y])=>`${X}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Q}`}}class lX extends u{code="CONFIG_NOT_FOUND";constructor(Q,X,Y){let Z=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],$="";if(Z.length===1)$=` or alias "${Z[0]}"`;else if(Z.length>1)$=` or aliases ${Z.map((H)=>`"${H}"`).join(", ")}`;super(`Configuration "${Q}"${$} not found`,{configName:Q,alias:Y,searchPaths:X,searchPathCount:X.length})}}class QX extends u{code="CONFIG_LOAD_ERROR";constructor(Q,X,Y){super(`Failed to load configuration from "${Q}": ${X.message}`,{configPath:Q,configName:Y,originalError:X.name,originalMessage:X.message});this.cause=X}}class zZ extends u{code="CONFIG_VALIDATION_ERROR";constructor(Q,X,Y){super(`Configuration validation failed for "${Q}"`,{configPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class BZ extends u{code="CONFIG_MERGE_ERROR";constructor(Q,X,Y,Z){super(`Failed to merge configuration from "${Q}" with "${X}": ${Y.message}`,{sourcePath:Q,targetPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class nX extends u{code="ENV_VAR_ERROR";constructor(Q,X,Y,Z){super(`Failed to parse environment variable "${Q}" with value "${X}" as ${Y}`,{envKey:Q,envValue:X,expectedType:Y,configName:Z})}}class RZ extends u{code="FILE_SYSTEM_ERROR";constructor(Q,X,Y){super(`File system ${Q} failed for "${X}": ${Y.message}`,{operation:Q,path:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class wZ extends u{code="TYPE_GENERATION_ERROR";constructor(Q,X,Y){super(`Failed to generate types from "${Q}" to "${X}": ${Y.message}`,{configDir:Q,outputPath:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class XX extends u{code="SCHEMA_VALIDATION_ERROR";constructor(Q,X,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class LZ extends u{code="BROWSER_CONFIG_ERROR";constructor(Q,X,Y,Z){super(`Failed to fetch configuration from "${Q}": ${X} ${Y}`,{endpoint:Q,status:X,statusText:Y,configName:Z})}}class KZ extends u{code="PLUGIN_ERROR";constructor(Q,X,Y){super(`Plugin "${Q}" failed during ${X}: ${Y.message}`,{pluginName:Q,operation:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}var YQ={configNotFound(Q,X,Y){return new lX(Q,X,Y)},configLoad(Q,X,Y){return new QX(Q,X,Y)},configValidation(Q,X,Y){return new zZ(Q,X,Y)},configMerge(Q,X,Y,Z){return new BZ(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new nX(Q,X,Y,Z)},fileSystem(Q,X,Y){return new RZ(Q,X,Y)},typeGeneration(Q,X,Y){return new wZ(Q,X,Y)},schemaValidation(Q,X,Y){return new XX(Q,X,Y)},browserConfig(Q,X,Y,Z){return new LZ(Q,X,Y,Z)},plugin(Q,X,Y){return new KZ(Q,X,Y)}};async function P8(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,U=Error("Unknown error occurred");for(let G=0;G<=Y;G++)try{return await Q()}catch(J){if(U=J instanceof Error?J:Error(String(J)),G===Y||!$(U))break;if(Z>0)await new Promise((_)=>setTimeout(_,Z))}if(H!==void 0)return H;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function b8(Q){return Q instanceof u}function E$(Q){return Q instanceof lX}function T$(Q){if(b8(Q))return Q.code==="FILE_SYSTEM_ERROR"||Q.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>Q.message.toLowerCase().includes(Y.toLowerCase()))}class iX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,X)=>X==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let X=Q.toLowerCase();return["true","1","yes"].includes(X)}},{name:"number",canParse:(Q,X)=>X==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let X=Number(Q);if(Number.isNaN(X))throw TypeError(`Cannot parse "${Q}" as number`);return X}},{name:"array",canParse:(Q,X)=>X==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let X=JSON.parse(Q);if(Array.isArray(X))return X}catch{}return Q.split(",").map((X)=>X.trim())}},{name:"json",canParse:(Q,X)=>X==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(X){throw Error(`Cannot parse "${Q}" as JSON: ${X}`)}}}]}async applyEnvironmentVariables(Q,X,Y={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:H=!0,customParsers:U={},verbose:G=!1,trackPerformance:J=!0}=Y,_=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let q=Z||this.generateEnvPrefix(Q),A={...X};return this.processObject(A,[],q,{useCamelCase:$,useBackwardCompatibility:H,customParsers:U,verbose:G,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return dX.track("applyEnvironmentVariables",_,{configName:Q});return _()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,X){if(!X)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],G=U.map((q)=>this.formatEnvKey(q,Z.useCamelCase)),J=`${Y}_${G.join("_")}`,_=Z.useBackwardCompatibility?`${Y}_${U.map((q)=>q.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,U,Y,Z);else{let q=yQ.env[J]||(_?yQ.env[_]:void 0);if(q!==void 0){if(Z.verbose){let A=yQ.env[J]?J:_}try{Q[$]=this.parseEnvironmentValue(q,typeof H,J,Z.customParsers,Z.configName)}catch(A){if(A instanceof nX)throw A;throw YQ.envVar(J,q,typeof H,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[H,U]of Object.entries(Z))try{return U(Q)}catch{continue}for(let H of this.defaultParsers)if(H.canParse(Q,X))try{return H.parse(Q)}catch{throw YQ.envVar(Y,Q,`${X} (via ${H.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(yQ.env))if(Z.startsWith(Y)&&$!==void 0)X[Z]=$;return X}validateEnvironmentVariable(Q,X,Y){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(Y)try{this.parseEnvironmentValue(Q,X,Y,{})}catch($){Z.push(`Cannot parse value "${X}" as ${Y}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,X,Y={}){let{prefix:Z,format:$="text"}=Y,H=Z||this.generateEnvPrefix(Q),U=[];switch(this.extractEnvVarInfo(X,[],H,U),$){case"markdown":return this.formatAsMarkdown(U,Q);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],G=`${Y}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,U,Y,Z);else Z.push({key:G,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${U.join(".")}`,example:this.generateExample(H)})}}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,X){let Y=`Environment Variables for ${X}:
|
|
50
|
+
|
|
51
|
+
`;for(let Z of Q)Y+=`${Z.key}
|
|
52
|
+
`,Y+=` Type: ${Z.type}
|
|
53
|
+
`,Y+=` Description: ${Z.description}
|
|
54
|
+
`,Y+=` Example: ${Z.example}
|
|
55
|
+
|
|
56
|
+
`;return Y}formatAsMarkdown(Q,X){let Y=`# Environment Variables for ${X}
|
|
57
|
+
|
|
58
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
59
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
60
|
+
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
61
|
+
`;return Y}}function x$(Q,X){let Y=SZ("process");if(typeof Y>"u"||!Y.env)return X;let Z=Y.env[Q];return Z!==void 0?Z:X}var k$={replace:"replace",concat:"concat",smart:"smart"};function y8(Q,X,Y={}){return jZ(Q,X,Y,new WeakMap)}function jZ(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:U}=Y;if(X===null||X===void 0)return H?Q:X;if(U){let G=U(Q,X);if(G!==void 0)return G}if(Array.isArray(X)||Array.isArray(Q))return IZ(Q,X,$,Z);if(!m(X)||!m(Q))return X;return f8(Q,X,Y,Z)}function IZ(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return v8(Q,X);case"smart":return d8(Q,X,Z);default:return X}return X}function v8(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>vX($,Z)))Y.push(Z);return Y}function d8(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(m(X[0])&&m(Q[0]))return h8(Q,X,Y);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}function h8(Q,X,Y){let Z=[...X];for(let $ of Q){if(!m($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let G of H)if(G in $){if(Z.find((_)=>m(_)&&(G in _)&&_[G]===$[G])){U=!0;break}}if(!U)Z.push($)}return Z}function f8(Q,X,Y,Z){let $=X;if(m($)&&Z.has($))return Z.get($);let H={...Q};if(m($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let G=$[U],J=H[U];if(Y.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){H[U]=G;continue}if(m(G)&&m(J))H[U]=jZ(J,G,Y,Z);else if(Array.isArray(G)||Array.isArray(J))H[U]=IZ(J,G,Y.arrayMergeMode||"smart",Z);else H[U]=G}return H}function FZ(Q,X,Y="replace"){return y8(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function vX(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(!vX(Q[Y],X[Y]))return!1;return!0}if(m(Q)&&m(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(!vX(Q[$],X[$]))return!1}return!0}return!1}function m(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class sX{extensions=uY;async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:U=!0,verbose:G=!1}=Y;if($){let _=uQ.getWithFileCheck("file",Q);if(_){if(G)console.log(`Configuration loaded from cache: ${Q}`);return _}}let J=async()=>{if(!vQ(Q))return null;try{let _=`?t=${Date.now()}`,q=await import(Q+_),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new QX(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new QX(Q,Error("Configuration must export a valid object"),"unknown");let R={config:FZ(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)uQ.setWithFileCheck("file",R,Q,H);return R}catch(_){throw _ instanceof Error?YQ.configLoad(Q,_):YQ.configLoad(Q,Error(String(_)))}};if(U)return dX.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){return cY({name:Q,directory:X,alias:Y})}generateNamePatterns(Q,X){return gY({name:Q,alias:X})}checkFileAccess(Q){return P8(async()=>{return vQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!vQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let G=dY(Q,`${H}${U}`);if(await this.checkFileAccess(G))Z.push(G)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let G=dY(Q,U);if(await this.checkFileAccess(G))Z.push(G)}}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((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!vQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),H=$(Q,"utf8");JSON.parse(H)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}var m8=/^https?:\/\//;class MZ{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:G=!0,verbose:J=!1}=Y,_=async()=>{let q=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:G,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...U],z);else return this.validateWithJSONSchema(Q,X,z)}catch(W){return q.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:q,warnings:A}}};if(G)return await dX.track("validateConfiguration",_);return _()}async validateWithSchemaFile(Q,X,Y){try{if(!p8(X))throw new XX(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new XX(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,H){if(H.validateTypes&&X.type){let U=Array.isArray(Q)?"array":typeof Q,G=Array.isArray(X.type)?X.type:[X.type];if(!G.includes(U)){if(Z.push({path:Y,message:`Expected type ${G.join(" or ")}, got ${U}`,expected:G.join(" or "),actual:U,rule:"type"}),H.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),H.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let U=0;U<Q.length;U++){let G=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let U=Q;if(H.validateRequired&&X.required){for(let G of X.required)if(!(G in U)){if(Z.push({path:Y?`${Y}.${G}`:G,message:`Missing required property '${G}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[G,J]of Object.entries(X.properties))if(G in U){let _=Y?`${Y}.${G}`:G;if(this.validateObjectAgainstSchema(U[G],J,_,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let G=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!G.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let U=this.getValueByPath(Q,H.path),G=this.validateWithRule(U,H,H.path);if(Z.push(...G),Y.stopOnFirstError&&Z.length>0)break}catch(U){Z.push({path:H.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,H,U]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(U)})}return X}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:m8},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var u8="0.15.17",f=new $X("bunfig",{showTags:!0});function g8(Q){if(!Q)return"";let X=Array.isArray(Q)?Q.filter(Boolean):[Q];if(X.length===0)return"";if(X.length===1)return` or alias "${X[0]}"`;return` or aliases ${X.map((Y)=>`"${Y}"`).join(", ")}`}class DZ{fileLoader=new sX;envProcessor=new iX;validator=new MZ;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...U}=Q;try{if(Y?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let G;try{G=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){if(U.configFile)throw J;let _=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(_)throw J;G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let q=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!q&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),z=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(_&&(z||q))throw J;if(A&&(!_||!z))G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!_)G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||H)await this.validateConfiguration(G.config,$,H,U.name);if(Y?.enabled&&G)this.cacheResult(U.name||"",G,Y,U);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:U.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)f.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);G.metrics=J}return G}catch(G){if(G instanceof Error&&G.name==="ConfigNotFoundError")throw G;let J=Date.now()-X;throw f.error(`Configuration loading failed after ${J}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,configFile:H,cwd:U,configDir:G,defaultConfig:J,checkEnv:_=!0,arrayStrategy:q="replace",verbose:A=!1}=Q,z=U||ZQ.cwd(),W=[];if(H){let V=h(z,H);W.push(V);let g=_?LQ(Z,J,A):J,v=await this.fileLoader.tryLoadFromPaths([V],g,{arrayStrategy:q,verbose:A,cacheTtl:Y?.ttl,useCache:!Y?.ttl||Y.ttl>100});if(!v)throw YQ.configNotFound(Z||H,W,$);if(A)f.success(`Configuration loaded from explicit path: ${V}`);return this.finalizeResult(v,W,_,Z,A)}let I=await this.loadLocalConfiguration(Z,$,z,G,J,q,A,_,Y);if(I)return W.push(...this.getLocalSearchPaths(Z,$,z,G)),this.finalizeResult(I,W,_,Z,A);let B=await this.loadHomeConfiguration(Z,$,J,q,A,_);if(B)return W.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(B,W,_,Z,A);let R=await this.loadPackageJsonConfiguration(Z,$,z,J,q,A,_);if(R)return W.push(h(z,"package.json")),this.finalizeResult(R,W,_,Z,A);if(W.push(...this.getAllSearchPaths(Z,$,z,G)),X)throw YQ.configNotFound(Z,W,$);return{...await this.applyEnvironmentVariables(Z,J,_,A),warnings:[`No configuration file found for "${Z}"${g8($)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,G,J){let _=G?LQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let A of q){if(U)f.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,_,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(W){if(U)f.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let U=H?LQ(Q,Y,$):Y,G=[h(HQ(),".config",Q),h(HQ(),".config"),HQ()];for(let J of G){if($)f.info(`Checking home directory: ${J}`);let _=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(_,U,{arrayStrategy:Z,verbose:$});if(q){if($)f.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let G=U?LQ(Q,Z,H):Z;try{let J=h(Y,"package.json");if(!SX(J))return null;let _={};try{_=JSON.parse(bZ(J,"utf8"))}catch(z){if(H)f.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let q=_[Q],A=Q;if(!q&&X){let z=Array.isArray(X)?X:[X];for(let W of z){if(!W)continue;if(_[W]){q=_[W],A=W;break}}}if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)f.success(`Configuration loaded from package.json: ${A}`);return{config:FZ(G,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)f.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:LQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let H=Y(Q);if(H)$.push(...H)}if(X){let H=await this.validator.validateConfiguration(Q,X);if(!H.isValid)$.push(...H.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if($.length>0)throw YQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return uQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);uQ.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias){let Z=Array.isArray(X.alias)?X.alias.join(","):X.alias;Y.push(`alias:${Z}`)}if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configFile)Y.push(`configFile:${X.configFile}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return lY({cwd:Q,configDir:X})}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(h(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),H=[];for(let U of $)H.push(...this.fileLoader.generateConfigPaths(Q,U,X));return H}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[h(HQ(),".config",Q),h(HQ(),".config"),HQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var QQ=new DZ;function hY(Q){let Y=!(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 Y||Z}async function b$(Q){return QQ.loadConfig({...Q,__strictErrorHandling:!0})}async function c8(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await QQ.loadConfig(Q);else Z=await QQ.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){if(Q.configFile)throw Z;let $=Z instanceof Error?Z.name:"UnknownError",H=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||H.includes("config"))&&Q.verbose)f.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let G=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await QQ.applyEnvironmentVariables(G.name||"",X,!0,G.verbose||!1))?.config??X;return X}}async function y$(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:X}=await import("process");try{return(await QQ.loadConfig({name:Q,cwd:X(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&hY(Y)))return(await QQ.applyEnvironmentVariables(Q,{},!0,!1)).config;throw Y}}try{return(await QQ.loadConfig({...Q,cwd:Q.cwd||ZQ.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&hY(X)))return(await QQ.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw X}}async function v$(Q,X,Y="replace"){let Z=new sX;try{let $=await Z.loadFromPath(Q,X,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return $?$.config:null}catch{return null}}function LQ(Q,X,Y=!1){let Z=new iX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let A=[...G,_],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,I;for(let B of z)if(W=ZQ.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof q==="boolean")J[_]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))J[_]=B}else if(Array.isArray(q))try{J[_]=JSON.parse(W)}catch{J[_]=W.split(",").map((B)=>B.trim())}else J[_]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))J[_]=H(q,A)}return J}return H(X)}var d$=h(ZQ.cwd(),"config"),h$=h(ZQ.cwd(),"src/generated");function f$(Q){let X=h(ZQ.cwd(),Q.configDir),Y=h(ZQ.cwd(),Q.generatedDir),Z=h(Y,"config-types.ts");if(!SX(aX(Z)))kZ(aX(Z),{recursive:!0,mode:511});let $=SX(X)?PZ(X).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],H=`// Generated by bunfig v${u8}
|
|
62
|
+
export type ConfigNames = ${$.length?`'${$.join("' | '")}'`:"string"}
|
|
63
|
+
`;yZ(Z,H,{mode:438})}function p$(Q){let X="defaultConfig"in Q?Q.defaultConfig:{},Y={...X},Z=new Map,$=new Set,H=null,U=(J)=>{let _={...J};for(let[q,A]of Z)_[q]=A;for(let q of $)delete _[q];return _};return(()=>{if(!H)H=c8(Q).then((J)=>{return Y=U(J),Y},(J)=>{if(Y=U({...X}),"verbose"in Q&&Q.verbose)f.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return Y});return H})(),new Proxy({},{get(J,_){return Y[_]},has(J,_){return _ in Y},ownKeys(){return Reflect.ownKeys(Y)},getOwnPropertyDescriptor(J,_){let q=Object.getOwnPropertyDescriptor(Y,_);if(q)q.configurable=!0;return q},set(J,_,q){return Z.set(_,q),$.delete(_),Y[_]=q,!0},deleteProperty(J,_){return $.add(_),Z.delete(_),delete Y[_],!0}})}function c$(Q){let X=fY(i8.cwd(),Q?.configDir||"./config");function Y(){if(!l8(X))return[];let $=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),H=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=n8(X).filter((J)=>$.has(DX(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),G=new Map;for(let{base:J,file:_}of U){let q=DX(_).toLowerCase(),A=G.get(J);if(!A){G.set(J,_);continue}let z=DX(A).toLowerCase();if(H.indexOf(q)<H.indexOf(z))G.set(J,_)}return Array.from(G.entries()).map(([J,_])=>({base:J,file:_})).sort((J,_)=>J.base.localeCompare(_.base))}function Z(){let $=Y(),H=$.map((_)=>_.base),U=H.length?H.map((_)=>`'${_}'`).join(" | "):"string",G=$.length?`{
|
|
64
|
+
${$.map((_)=>{let q=fY(X,_.file).replace(/\\/g,"/");return` '${_.base}': typeof import('${q}').default`}).join(`,
|
|
65
|
+
`)}
|
|
66
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
67
|
+
export type ConfigByName = ${G}
|
|
68
|
+
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
69
|
+
export type ConfigOf = Config
|
|
70
|
+
`}return{name:"bunfig-plugin",setup($){$.onResolve({filter:/^virtual:bunfig-types$/},(H)=>{return{path:H.path,namespace:"bunfig-virtual"}}),$.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}export{pY as Oo,mY as Po,uQ as Qo,dX as Ro,o8 as So,uY as To,gY as Uo,cY as Vo,lY as Wo,CZ as Xo,xZ as Yo,e8 as Zo,u as _o,lX as $o,QX as ap,zZ as bp,BZ as cp,nX as dp,RZ as ep,wZ as fp,XX as gp,LZ as hp,KZ as ip,YQ as jp,P8 as kp,b8 as lp,E$ as mp,T$ as np,iX as op,x$ as pp,k$ as qp,y8 as rp,FZ as sp,sX as tp,MZ as up,DZ as vp,b$ as wp,c8 as xp,y$ as yp,v$ as zp,LQ as Ap,d$ as Bp,h$ as Cp,f$ as Dp,p$ as Ep,c$ as Fp};
|