@stacksjs/ts-css 0.1.3 → 0.3.1
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/CHANGELOG.md +14 -0
- package/ENGINE.md +677 -0
- package/PLUGIN.md +217 -0
- package/dist/bin/cli.js +33 -0
- package/dist/bin/cssx.js +405 -0
- package/dist/chunk-0h48763m.js +2 -0
- package/dist/chunk-br9jax0b.js +2 -0
- package/dist/chunk-f9gzb0a5.js +3 -0
- package/dist/chunk-genwkevp.js +3 -0
- package/dist/chunk-jj3s4ctf.js +62 -0
- package/dist/chunk-mz87cw2e.js +2 -0
- package/dist/engine/build.d.ts +26 -0
- package/dist/engine/color-modifier.d.ts +8 -0
- package/dist/engine/config.d.ts +5 -0
- package/dist/engine/format.d.ts +20 -0
- package/dist/engine/generator.d.ts +14 -0
- package/dist/engine/index.d.ts +13 -0
- package/dist/engine/index.js +653 -0
- package/dist/engine/parser.d.ts +68 -0
- package/dist/engine/plugin.d.ts +22 -0
- package/dist/engine/preflight-forms.d.ts +6 -0
- package/dist/engine/preflight.d.ts +3 -0
- package/dist/engine/rules-advanced.d.ts +27 -0
- package/dist/engine/rules-effects.d.ts +35 -0
- package/dist/engine/rules-forms.d.ts +8 -0
- package/dist/engine/rules-grid.d.ts +13 -0
- package/dist/engine/rules-icons.d.ts +2 -0
- package/dist/engine/rules-interactivity.d.ts +41 -0
- package/dist/engine/rules-layout.d.ts +28 -0
- package/dist/engine/rules-transforms.d.ts +35 -0
- package/dist/engine/rules-typography.d.ts +47 -0
- package/dist/engine/rules.d.ts +56 -0
- package/dist/engine/scanner.d.ts +16 -0
- package/dist/engine/style/api.d.ts +95 -0
- package/dist/engine/style/collect.d.ts +10 -0
- package/dist/engine/style/evaluate.d.ts +11 -0
- package/dist/engine/style/hash.d.ts +15 -0
- package/dist/engine/style/index.d.ts +56 -0
- package/dist/engine/style/plugin.d.ts +27 -0
- package/dist/engine/style/priority.d.ts +12 -0
- package/dist/engine/style/registry.d.ts +56 -0
- package/dist/engine/style/types.d.ts +54 -0
- package/dist/engine/style/value.d.ts +15 -0
- package/dist/engine/transformer-compile-class.d.ts +34 -0
- package/dist/engine/types.d.ts +156 -0
- package/dist/index.js +1 -60
- package/dist/optimize/index.js +1 -1
- package/dist/parse/index.js +1 -1
- package/dist/parse/list.d.ts +1 -1
- package/dist/select/index.js +1 -1
- package/dist/what/index.js +1 -1
- package/package.json +35 -19
- package/dist/chunk-1kmkypmr.js +0 -3
- package/dist/chunk-2wsah70r.js +0 -2
- package/dist/chunk-9ep6bwwb.js +0 -2
- package/dist/chunk-edwg811g.js +0 -2
- package/dist/chunk-thy3p95k.js +0 -3
package/dist/index.js
CHANGED
|
@@ -1,61 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{d as y8,e as v8,f as d8,g as h8}from"./chunk-edwg811g.js";import{k as f8,l as p8,m as m8,o as u8,p as g8}from"./chunk-thy3p95k.js";import{q as V8,s as E8,t as T8,x as O8,y as N8,z as C8}from"./chunk-9ep6bwwb.js";import{A as x8,B as k8,C as P8,E as b8}from"./chunk-2wsah70r.js";import{G as l}from"./chunk-1kmkypmr.js";import{existsSync as iX,statSync as sX}from"fs";import{existsSync as LZ,mkdirSync as n8,readdirSync as i8,readFileSync as KZ,writeFileSync as s8}from"fs";import{homedir as YQ}from"os";import{dirname as r8,resolve as d}from"path";import eQ from"process";import{existsSync as oX,statSync as tX}from"fs";import{existsSync as DX,mkdirSync as jZ,readdirSync as IZ,writeFileSync as FZ}from"fs";import{homedir as ZQ}from"os";import{dirname as rX,resolve as y}from"path";import XQ from"process";import{join as MZ,relative as DZ,resolve as aX}from"path";import pQ from"process";import{existsSync as yY,mkdirSync as J9,readdirSync as _9,writeFileSync as G9}from"fs";import{homedir as ZX}from"os";import{dirname as W9,resolve as b}from"path";import wQ from"process";import{join as SZ,relative as VZ,resolve as eX}from"path";import mQ from"process";import{existsSync as vY,mkdirSync as L9,readdirSync as K9,writeFileSync as j9}from"fs";import{dirname as F9,resolve as uQ}from"path";import SX from"process";import{Buffer as e}from"buffer";import{createCipheriv as EZ,createDecipheriv as TZ,randomBytes as $X}from"crypto";import{closeSync as HX,createReadStream as QY,createWriteStream as OZ,existsSync as UX,fsyncSync as XY,openSync as YY,writeFileSync as NZ}from"fs";import{access as CZ,constants as ZY,mkdir as xZ,readdir as IQ,rename as $Y,stat as $Q,unlink as FQ,writeFile as JX}from"fs/promises";import{join as HQ}from"path";import N from"process";import{pipeline as kZ}from"stream/promises";import{createGzip as HY}from"zlib";import UQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as PZ,createDecipheriv as bZ,randomBytes as _X}from"crypto";import{closeSync as GX,createReadStream as UY,createWriteStream as yZ,existsSync as MQ,fsyncSync as JY,openSync as _Y,writeFileSync as vZ}from"fs";import{access as dZ,constants as GY,mkdir as hZ,readdir as DQ,rename as qY,stat as JQ,unlink as SQ,writeFile as qX}from"fs/promises";import{isAbsolute as fZ,join as _Q,resolve as pZ}from"path";import R from"process";import{pipeline as mZ}from"stream/promises";import{createGzip as AY}from"zlib";import GQ from"process";import t from"process";import VQ from"process";import{existsSync as EQ}from"fs";import{resolve as AX}from"path";import{existsSync as uZ}from"fs";import{existsSync as gZ,readdirSync as cZ}from"fs";import{extname as WX,resolve as WY}from"path";import lZ from"process";import{join as nZ,relative as iZ,resolve as zY}from"path";import gQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as sZ,createDecipheriv as oZ,randomBytes as zX}from"crypto";import{closeSync as BX,createReadStream as BY,createWriteStream as tZ,existsSync as TQ,fsyncSync as RY,openSync as wY,writeFileSync as rZ}from"fs";import{access as aZ,constants as LY,mkdir as eZ,readdir as OQ,rename as KY,stat as qQ,unlink as NQ,writeFile as RX}from"fs/promises";import{isAbsolute as Q0,join as AQ,resolve as X0}from"path";import w from"process";import{pipeline as Y0}from"stream/promises";import{createGzip as jY}from"zlib";import WQ from"process";import r from"process";import xQ from"process";import{existsSync as kQ}from"fs";import{resolve as FX}from"path";import{existsSync as M8}from"fs";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(!iX(Q))return!0;return sX(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 $=iX(Y)?sX(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 bY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var fQ=new PY,yX=new bY;var Z0=Object.defineProperty,$0=(Q)=>Q;function H0(Q,X){this[Q]=$0.bind(null,X)}var U0=(Q,X)=>{for(var Y in X)Z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:H0.bind(X,Y)})},J0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),dY={};U0(dY,{withErrorRecovery:()=>pY,tryLoadConfig:()=>C0,loadConfigWithResult:()=>O0,loadConfig:()=>lY,isRetryableError:()=>M0,isConfigNotFoundError:()=>F0,isBunfigError:()=>mY,globalPerformanceMonitor:()=>jQ,globalCache:()=>zQ,getEnvOrDefault:()=>D0,generateConfigTypes:()=>x0,defaultGeneratedDir:()=>eY,defaultConfigDir:()=>aY,deepMergeWithArrayStrategy:()=>pX,deepMerge:()=>uY,createLibraryConfig:()=>k0,config:()=>N0,bunfigPlugin:()=>P0,applyEnvVarsToConfig:()=>RQ,TypeGenerationError:()=>xX,SchemaValidationError:()=>KQ,PluginError:()=>PX,PerformanceMonitor:()=>dX,FileSystemError:()=>CX,ErrorFactory:()=>QQ,EnvVarError:()=>oQ,EnvProcessor:()=>QX,ConfigValidator:()=>mX,ConfigValidationError:()=>OX,ConfigNotFoundError:()=>sQ,ConfigMergeError:()=>NX,ConfigLoader:()=>uX,ConfigLoadError:()=>LQ,ConfigFileLoader:()=>XX,ConfigCache:()=>vX,CacheUtils:()=>iY,BunfigError:()=>v,BrowserConfigError:()=>kX,ArrayMergeStrategies:()=>tY});class vX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!oX(Q))return!0;return tX(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 $=oX(Y)?tX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function _0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function G0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function q0(Q){return Q.getStats().size*2}function hX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>cQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=hX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((_)=>cQ(_,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function cQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!cQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!cQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function A0(Q,X){if(!vY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return hX(X,Z)}catch{return null}}catch{return null}}async function W0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||SX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let _ of $){let J=uQ(Z,`${U}${_}`),G=await A0(J,Y);if(G!==null)return G}try{let U=uQ(Z,"package.json");if(vY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return hX(Y,J)}catch{}}}catch{}return Y}function z0(Q,X={}){let Y=mQ.cwd();while(Y.includes("storage"))Y=eX(Y,"..");let Z=eX(Y,Q||"");if(X?.relative)return VZ(mQ.cwd(),Z);return Z}async function B0(){try{let Q=await W0({name:"clarity",defaultConfig:yQ,cwd:mQ.cwd(),endpoint:"",headers:{}});return{...yQ,...Q}}catch{return yQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function R0(){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 hY{async format(Q){let X=await R0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:UQ.pid,hostname:X(),environment:UQ.env.NODE_ENV||"development",platform:UQ.platform,version:UQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:UQ.env.NODE_ENV||UQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class lQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...EX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new hY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...vQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...vQ};return{...vQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:EX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,_=1000;while(H<U)try{try{try{await CZ(this.config.logDirectory,ZY.F_OK|ZY.W_OK)}catch(G){if(G instanceof Error&&"code"in G)if(G.code==="ENOENT")await xZ(this.config.logDirectory,{recursive:!0,mode:493});else if(G.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw G;else throw G}}catch(G){throw console.error("Debug: [writeToFile] Failed to create log directory:",G),G}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!UX(this.currentLogFile))await JX(this.currentLogFile,"",{mode:420});if($=YY(this.currentLogFile,"a",420),NZ($,J,{flag:"a"}),XY($),$!==void 0)HX($),$=void 0;if((await $Q(this.currentLogFile)).size===0){if(await JX(this.currentLogFile,J,{flag:"w",mode:420}),(await $Q(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(G){let q=G;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=_*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{HX($)}catch(G){console.error("Debug: [writeToFile] Error closing file descriptor:",G)}}}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,G))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return HQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return HQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return HQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,_],[,J])=>J.createdAt.getTime()-_.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[_]of $.slice(U))this.encryptionKeys.delete(_),this.keys.delete(_)}generateKeyId(){return $X(16).toString("hex")}generateKey(){return $X(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=$X(16),Z=EZ("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=HY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await $Q(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await IQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,G)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(G.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,_=`${Y}.${U}`;if(await $Q(Y).catch(()=>null))try{if(await $Y(Y,_),X.compress)try{let J=`${_}.gz`;await this.compressLogFile(_,J),await FQ(_)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await JX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await $Q(Y).catch(()=>null))await $Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await IQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,_)=>_.localeCompare(U));for(let U of H.slice(X.maxFiles))await FQ(HQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=QY(Q),Z=OZ(X),$=HY();await kZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),UX(this.currentLogFile))try{let Q=YY(this.currentLogFile,"r+");XY(Q),HX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await IQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await FQ(HQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,_=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=N.stdout.columns||120,G="";if(H==="warning"||H==="error")G=`${Y} ${$}`;else if(H==="info"||H==="success")G=`${Y} ${Z} ${$}`;else G=`${Y} ${Z} ${M.cyan($)}`;if(!U)return G.trim();let q=_(G).trim().length,A=_(X).length,z=Math.max(1,J-2-q-A);return`${G.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let _=Number.parseInt(U,10);return _<X[0].length?String(X[0][_]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let _=X[Z++];switch(U){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,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,_;if(X instanceof Error)U=X.message,_=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let G=sY[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:G,tag:q,message:U,level:Q}),console.error(A),_){let z=_.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}`),_)console.error(_)}if(!this.shouldLog(Q))return;let J=`${H} ${this.environment}.${Q.toUpperCase()}: ${U}
|
|
4
|
-
`;if(_)J+=`${_}
|
|
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,_=this.formatConsoleTimestamp(U),G=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)G+=` ${JSON.stringify(Y)}`;if(G+=`
|
|
6
|
-
`,G=G.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:_,icon:M.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!S())console.error(G.trim());await this.writeToFile(G)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new lQ(X,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(S())throw Error("createReadStream is not supported in browser environments");if(!UX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return 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=e.isBuffer(Q)?Q:e.from(Q,"base64"),$=Z.slice(0,16),H=Z.slice(-16),U=Z.slice(16,-16),_=TZ("aes-256-gcm",Y,$);return _.setAuthTag(H),e.concat([_.update(U),_.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,_=`\u250C${"\u2500".repeat(U)}\u2510`,J=`\u2514${"\u2500".repeat(U)}\u2518`,G=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();N.stdin.removeListener("data",Y);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let U=/%([sdijfo%])/g,_=0;if(Y=Q.replace(U,(J,G)=>{if(G==="%")return"%";if(_>=X.length)return J;let q=X[_++];switch(G){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}}),_<X.length)Y+=` ${X.slice(_).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)):"",_=M.blue("\u25D0");console.error(`${_} ${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,_)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,U)),_!==void 0)this.activeProgressBar.message=_;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,_="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(_,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,X=!1){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=M.green("\u2501".repeat(Z)),U=M.gray("\u2501".repeat($)),_=`[${H}${U}]`,J=`${Y}%`.padStart(4),G=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} ${_} ${J}${G}`,W=N.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,N.stdout.write(Q.lastRenderedLine),X)N.stdout.write(`
|
|
10
|
-
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await IQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=HQ(this.config.logDirectory,Z);if(Q.before)try{if((await $Q(H)).mtime>=Q.before)continue}catch(U){console.error(`Failed to get stats for file ${H}:`,U);continue}Y.push(H)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await FQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}function bQ(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&F(X[0])&&"id"in X[0]&&X[0].id===3&&F(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(F(X)&&F(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(F(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&F(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&F(X[0])&&F(Q[0])){let Z=[...X];for(let $ of Q)if(F($)&&"name"in $){if(!Z.find((U)=>F(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(F($)&&"path"in $){if(!Z.find((U)=>F(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>nQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!F(X)||!F(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(F($)&&F(Y[Z]))Y[Z]=bQ(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&F($[0])&&F(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(F(U)&&"name"in U){if(!H.find((J)=>F(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(F(U)&&"path"in U){if(!H.find((J)=>F(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((_)=>nQ(_,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function fX(Q,X,Y="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return Y==="replace"?X:bQ(Q,X);if(Array.isArray(Q))return Y==="replace"?X:bQ(Q,X);if(!F(X)||!F(Q))return X;let Z={...Q};for(let $ of Object.keys(X)){if(!Object.prototype.hasOwnProperty.call(X,$))continue;let H=X[$],U=Z[$];if(H===null||H===void 0)continue;if(Array.isArray(H)||Array.isArray(U))if(Y==="replace")Z[$]=H;else Z[$]=bQ(U,H);else if(F(H)&&F(U))Z[$]=fX(U,H,Y);else Z[$]=H}return Z}function nQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!nQ(Q[Y],X[Y]))return!1;return!0}if(F(Q)&&F(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!nQ(Q[$],X[$]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function CQ(Q,X,Y="replace"){if(!yY(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return fX(X,$,Y)}catch{return null}}catch{return null}}function w0(Q,X,Y=!1){if(!Q)return X;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...X};function H(U,_=[]){let J={...U};for(let[G,q]of Object.entries(U)){let A=[..._,G],z=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${Z}_${A.map(z).join("_")}`,I=`${Z}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(Y)x.info(`Checking environment variable ${W} for config ${Q}.${A.join(".")}`);if(typeof q==="object"&&q!==null&&!Array.isArray(q))J[G]=H(q,A);else{let B=wQ.env[W]||wQ.env[I];if(B!==void 0){if(Y)x.info(`Using environment variable ${B?W:I} for config ${Q}.${A.join(".")}`);if(typeof q==="number")J[G]=Number(B);else if(typeof q==="boolean")J[G]=B.toLowerCase()==="true";else if(Array.isArray(q))try{let K=JSON.parse(B);if(Array.isArray(K))J[G]=K;else J[G]=B.split(",").map((k)=>k.trim())}catch{J[G]=B.split(",").map((K)=>K.trim())}else J[G]=B}}}return J}return H($)}async function L0({name:Q="",alias:X,cwd:Y,configDir:Z,defaultConfig:$,verbose:H=!1,checkEnv:U=!0,arrayStrategy:_="replace"}){let J=U&&typeof $==="object"&&$!==null&&!Array.isArray($)?w0(Q,$,H):$,G=Y||wQ.cwd(),q=[".ts",".js",".mjs",".cjs",".json"];if(H)x.info(`Loading configuration for "${Q}"${X?` (alias: "${X}")`:""} from ${G}`);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([G,b(G,"config"),b(G,".config"),Z?b(G,Z):void 0].filter(Boolean)));for(let K of B){if(H)x.info(`Searching for configuration in: ${K}`);let P=[b(G,"config"),b(G,".config")].concat(Z?[b(G,Z)]:[]).includes(K)?[...A,...z,...W,...I]:[...z,...A,...I,...W];for(let n of P)for(let g of q){let p=b(K,`${n}${g}`),nX=await CQ(p,J,_);if(nX!==null){if(H)x.success(`Configuration loaded from: ${p}`);return nX}}}if(Q){let K=b(ZX(),".config",Q),k=["config",`${Q}.config`];if(X)k.push(`${X}.config`);if(H)x.info(`Checking user config directory: ${K}`);for(let P of k)for(let n of q){let g=b(K,`${P}${n}`),p=await CQ(g,J,_);if(p!==null){if(H)x.success(`Configuration loaded from user config directory: ${g}`);return p}}}if(Q){let K=b(ZX(),".config"),k=[`.${Q}.config`];if(X)k.push(`.${X}.config`);if(H)x.info(`Checking user config directory for dotfile configs: ${K}`);for(let P of k)for(let n of q){let g=b(K,`${P}${n}`),p=await CQ(g,J,_);if(p!==null){if(H)x.success(`Configuration loaded from user config directory dotfile: ${g}`);return p}}}if(Q){let K=ZX(),k=[`.${Q}.config`,`.${Q}`];if(X)k.push(`.${X}.config`),k.push(`.${X}`);if(H)x.info(`Checking user home directory for dotfile configs: ${K}`);for(let P of k)for(let n of q){let g=b(K,`${P}${n}`),p=await CQ(g,J,_);if(p!==null){if(H)x.success(`Configuration loaded from user home directory: ${g}`);return p}}}try{let K=b(G,"package.json");if(yY(K)){let k=await import(K),P=k[Q];if(!P&&X){if(P=k[X],P&&H)x.success(`Using alias "${X}" configuration from package.json`)}if(P&&typeof P==="object"&&!Array.isArray(P))try{if(H)x.success(`Configuration loaded from package.json: ${P===k[Q]?Q:X}`);return fX(J,P,_)}catch(n){if(H)x.warn("Failed to merge package.json config:",n)}}}catch(K){if(H)x.warn("Failed to load package.json:",K)}if(H)x.info(`No configuration found for "${Q}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return J}function K0(Q,X={}){let Y=pQ.cwd();while(Y.includes("storage"))Y=aX(Y,"..");let Z=aX(Y,Q||"");if(X?.relative)return DZ(pQ.cwd(),Z);return Z}async function j0(){try{let Q=await L0({name:"clarity",alias:"logging",defaultConfig:dQ,cwd:pQ.cwd()});return{...dQ,...Q||{}}}catch{return dQ}}function V(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function I0(){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 fY{async format(Q){let X=await I0(),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:GQ.pid,hostname:X(),environment:GQ.env.NODE_ENV||"development",platform:GQ.platform,version:GQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:GQ.env.NODE_ENV||GQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class iQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new fY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return X[Q]>=X[Y]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}shouldWriteToFile(){return!V()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,_=1000;while(H<U)try{try{try{await dZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(G){if(G instanceof Error&&"code"in G)if(G.code==="ENOENT")await hZ(this.config.logDirectory,{recursive:!0,mode:493});else if(G.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw G;else throw G}}catch(G){throw console.error("Debug: [writeToFile] Failed to create log directory:",G),G}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:i.from(Q);try{if(!MQ(this.currentLogFile))await qX(this.currentLogFile,"",{mode:420});if($=_Y(this.currentLogFile,"a",420),vZ($,J,{flag:"a"}),JY($),$!==void 0)GX($),$=void 0;if((await JQ(this.currentLogFile)).size===0){if(await qX(this.currentLogFile,J,{flag:"w",mode:420}),(await JQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(G){let q=G;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=_*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{GX($)}catch(G){console.error("Debug: [writeToFile] Error closing file descriptor:",G)}}}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,G))}})();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 _Q(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 _Q(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return _Q(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(V())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async 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(([,_],[,J])=>J.createdAt.getTime()-_.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[_]of $.slice(U))this.encryptionKeys.delete(_),this.keys.delete(_)}generateKeyId(){return _X(16).toString("hex")}generateKey(){return _X(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=_X(16),Z=PZ("aes-256-gcm",X,Y),$=i.isBuffer(Q)?Q:i.from(Q,"utf8"),H=Z.update($),U=Z.final(),_=H.length+U.length,J=Z.getAuthTag(),G=i.allocUnsafe(16+_+16);return Y.copy(G,0),H.copy(G,16),U.copy(G,16+H.length),J.copy(G,16+_),{encrypted:G,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=AY(),$=[];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(V())return;if(!this.shouldWriteToFile())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 DQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,G)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(G.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,_=`${Y}.${U}`;if(await JQ(Y).catch(()=>null))try{if(await qY(Y,_),X.compress)try{let J=`${_}.gz`;await this.compressLogFile(_,J),await SQ(_)}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 qX(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 qY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await DQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,_)=>_.localeCompare(U));for(let U of H.slice(X.maxFiles))await SQ(_Q(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=UY(Q),Z=yZ(X),$=AY();await mZ(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()})),MQ(this.currentLogFile))try{let Q=_Y(this.currentLogFile,"r+");JY(Q),GX(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(!V()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await DQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await SQ(_Q(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()?L.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||V())return!1;let Q=typeof R.env.NO_COLOR<"u",X=R.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,_=(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=R.stdout.columns||120,G="";if(H==="warning"||H==="error")G=`${Y} ${$}`;else if(H==="info"||H==="success")G=`${Y} ${Z} ${$}`;else G=`${Y} ${Z} ${L.cyan($)}`;if(!U)return G.trim();let q=_(G).trim().length,A=_(X).length,z=Math.max(1,J-2-q-A);return`${G.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let _=Number.parseInt(U,10);return _<X[0].length?String(X[0][_]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let _=X[Z++];switch(U){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,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=L.underline(L.blue(Z)),U=this.toAbsoluteFilePath($);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let _=`file://${encodeURI(U)}`,J="\x1B]8;;",G="\x1B\\";return`\x1B]8;;${_}\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)=>L.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>L.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>L.strikethrough(Z)),X}supportsHyperlinks(){if(V())return!1;let Q=R.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let 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=R.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(fZ(X)||X.startsWith("./")||X.startsWith("../"))X=pZ(X);else return null;return MQ(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,_;if(X instanceof Error)U=X.message,_=X.stack;else U=this.formatMessage(X,Y);let{consoleText:J,fileText:G}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":oY[Q],z=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:L.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:L.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),_){let I=_.split(`
|
|
11
|
-
`);for(let B of I)if(B.trim()&&!B.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:L.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!V()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),_)console.error(_)}if(!this.shouldLog(Q))return;let q=`${H} ${this.environment}.${Q.toUpperCase()}: ${G}
|
|
12
|
-
`;if(_)q+=`${_}
|
|
13
|
-
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,X=""){let Y={update:(_,J)=>{},finish:(_)=>{},interrupt:(_,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()&&!V()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(_,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,_),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!V()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(_)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,_)},interrupt:(_,J="info")=>{if(!V()&&R.stdout.isTTY)R.stdout.write(`
|
|
14
|
-
`);if(this[J==="warning"?"warn":J](_),this.activeProgressBar&&this.shouldStyleConsole()&&!V()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":L.blue("\u25D0"),tag:Y,message:`${L.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,_=this.formatConsoleTimestamp(U),G=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)G+=` ${JSON.stringify(Y)}`;if(G+=`
|
|
15
|
-
`,G=G.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:_,icon:this.options.showIcons===!1?"":L.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!V())console.error(G.trim());if(this.shouldWriteToFile())await this.writeToFile(G)}}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 iQ(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(V())throw Error("createReadStream is not supported in browser environments");if(!MQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return UY(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),_=bZ("aes-256-gcm",Y,$);_.setAuthTag(H);let J=_.update(U),G=_.final(),q=J.length+G.length,A=i.allocUnsafe(q);return J.copy(A,0),G.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 V()}isServerMode(){return!V()}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 _=$.split(`
|
|
16
|
-
`),J=Math.max(..._.map((z)=>z.length))+2,G=`\u250C${"\u2500".repeat(J)}\u2510`,q=`\u2514${"\u2500".repeat(J)}\u2518`,A=_.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:L.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(G),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(q),showTimestamp:!1}))}else if(!V())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(V())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${L.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();R.stdin.removeListener("data",Y);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.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,G=0;if(Y=Q.replace(J,(q,A)=>{if(A==="%")return"%";if(G>=X.length)return q;let z=X[G++];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}}),G<X.length)Y+=` ${X.slice(G).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?L.gray(this.formatTag(this.name)):"",G=this.options.showIcons===!1?"":`${L.blue("\u25D0")} `;console.error(`${G}${J} ${L.cyan(Z)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
18
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(_)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.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=L.green("\u2501".repeat(Z)),U=L.gray("\u2501".repeat($)),_=`[${H}${U}]`,J=`${Y}%`.padStart(4),G=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":X||Y===100?L.green("\u2713"):L.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${_} ${J}${G}`,W=R.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,R.stdout.write(Q.lastRenderedLine),X)R.stdout.write(`
|
|
19
|
-
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||V()||!R.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(V()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await DQ(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=_Q(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 SQ(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 pY(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,U=Error("Unknown error occurred");for(let _=0;_<=Y;_++)try{return await Q()}catch(J){if(U=J instanceof Error?J:Error(String(J)),_===Y||!$(U))break;if(Z>0)await new Promise((G)=>setTimeout(G,Z))}if(H!==void 0)return H;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function mY(Q){return Q instanceof v}function F0(Q){return Q instanceof sQ}function M0(Q){if(mY(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 QX{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:_=!1,trackPerformance:J=!0}=Y,G=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:_,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return jQ.track("applyEnvironmentVariables",G,{configName:Q});return G()}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,$],_=U.map((q)=>this.formatEnvKey(q,Z.useCamelCase)),J=`${Y}_${_.join("_")}`,G=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=VQ.env[J]||(G?VQ.env[G]:void 0);if(q!==void 0){if(Z.verbose){let A=VQ.env[J]?J:G}try{Q[$]=this.parseEnvironmentValue(q,typeof H,J,Z.customParsers,Z.configName)}catch(A){if(A instanceof oQ)throw A;throw QQ.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 QQ.envVar(Y,Q,`${X} (via ${H.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(VQ.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,$],_=`${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:_,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 D0(Q,X){let Y=nY("process");if(typeof Y>"u"||!Y.env)return X;let Z=Y.env[Q];return Z!==void 0?Z:X}function uY(Q,X,Y={}){return gY(Q,X,Y,new WeakMap)}function gY(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 _=U(Q,X);if(_!==void 0)return _}if(Array.isArray(X)||Array.isArray(Q))return cY(Q,X,$,Z);if(!h(X)||!h(Q))return X;return T0(Q,X,Y,Z)}function cY(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 S0(Q,X);case"smart":return V0(Q,X,Z);default:return X}return X}function S0(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>VX($,Z)))Y.push(Z);return Y}function V0(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(h(X[0])&&h(Q[0]))return E0(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 E0(Q,X,Y){let Z=[...X];for(let $ of Q){if(!h($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let _ of H)if(_ in $){if(Z.find((G)=>h(G)&&(_ in G)&&G[_]===$[_])){U=!0;break}}if(!U)Z.push($)}return Z}function T0(Q,X,Y,Z){let $=X;if(h($)&&Z.has($))return Z.get($);let H={...Q};if(h($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let _=$[U],J=H[U];if(Y.skipNullish&&(_===null||_===void 0))continue;if(_===null||_===void 0){H[U]=_;continue}if(h(_)&&h(J))H[U]=gY(J,_,Y,Z);else if(Array.isArray(_)||Array.isArray(J))H[U]=cY(J,_,Y.arrayMergeMode||"smart",Z);else H[U]=_}return H}function pX(Q,X,Y="replace"){return uY(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(h(Q)&&h(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 h(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class XX{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:_=!1}=Y;if($){let G=zQ.getWithFileCheck("file",Q);if(G){if(_)console.log(`Configuration loaded from cache: ${Q}`);return G}}let J=async()=>{if(!EQ(Q))return null;try{let G=`?t=${Date.now()}`,q=await import(Q+G),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new LQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new LQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:pX(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)zQ.setWithFileCheck("file",K,Q,H);return K}catch(G){throw G instanceof Error?QQ.configLoad(Q,G):QQ.configLoad(Q,Error(String(G)))}};if(U)return jQ.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(AX(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 pY(async()=>{return EQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!EQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let _=AX(Q,`${H}${U}`);if(await this.checkFileAccess(_))Z.push(_)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let _=AX(Q,U);if(await this.checkFileAccess(_))Z.push(_)}}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(!EQ(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 mX{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:_=!0,verbose:J=!1}=Y,G=async()=>{let q=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:_,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(_)return await jQ.track("validateConfiguration",G);return G()}async validateWithSchemaFile(Q,X,Y){try{if(!uZ(X))throw new KQ(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 KQ(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,_=Array.isArray(X.type)?X.type:[X.type];if(!_.includes(U)){if(Z.push({path:Y,message:`Expected type ${_.join(" or ")}, got ${U}`,expected:_.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 _=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,_,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 _ of X.required)if(!(_ in U)){if(Z.push({path:Y?`${Y}.${_}`:_,message:`Missing required property '${_}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[_,J]of Object.entries(X.properties))if(_ in U){let G=Y?`${Y}.${_}`:_;if(this.validateObjectAgainstSchema(U[_],J,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let _=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!_.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),_=this.validateWithRule(U,H,H.path);if(Z.push(..._),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:rY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class uX{fileLoader=new XX;envProcessor=new QX;validator=new mX;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 _;try{_=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){let G=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(G)throw J;_={...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(G&&(z||q))throw J;if(A&&(!G||!z))_={...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 _={...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(_.config,$,H,U.name);if(Y?.enabled&&_)this.cacheResult(U.name||"",_,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)m.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);_.metrics=J}return _}catch(_){let J=Date.now()-X;throw m.error(`Configuration loading failed after ${J}ms:`,[_ instanceof Error?_:Error(String(_))]),_}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:U,defaultConfig:_,checkEnv:J=!0,arrayStrategy:G="replace",verbose:q=!1}=Q,A=H||XQ.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 QQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,_,J,q),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,_,J){let G=_?RQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let A of q){if(U)m.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,G,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(W){if(U)m.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?RQ(Q,Y,$):Y,_=[y(ZQ(),".config",Q),y(ZQ(),".config"),ZQ()];for(let J of _){if($)m.info(`Checking home directory: ${J}`);let G=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(G,U,{arrayStrategy:Z,verbose:$});if(q){if($)m.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let _=U?RQ(Q,Z,H):Z;try{let J=y(Y,"package.json");if(!DX(J))return null;let G=await import(J),q=G[Q],A=Q;if(!q&&X)q=G[X],A=X;if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)m.success(`Configuration loaded from package.json: ${A}`);return{config:pX(_,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)m.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:RQ(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 QQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return zQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);zQ.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(ZQ(),".config",Q),y(ZQ(),".config"),ZQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function IY(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 O0(Q){return a.loadConfig({...Q,__strictErrorHandling:!0})}async function lY(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)m.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let _=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(_.name||"",X,!0,_.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"&&IY(Y)))return(await a.applyEnvironmentVariables(Q,{},!0,!1)).config;throw Y}}try{return(await a.loadConfig({...Q,cwd:Q.cwd||XQ.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&IY(X)))return(await a.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw X}}async function C0(Q,X,Y="replace"){let Z=new XX;try{let $=await Z.loadFromPath(Q,X,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return $?$.config:null}catch{return null}}function RQ(Q,X,Y=!1){let Z=new QX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,_=[]){let J={...U};for(let[G,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=XQ.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof q==="boolean")J[G]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))J[G]=B}else if(Array.isArray(q))try{J[G]=JSON.parse(W)}catch{J[G]=W.split(",").map((B)=>B.trim())}else J[G]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))J[G]=H(q,A)}return J}return H(X)}function x0(Q){let X=y(XQ.cwd(),Q.configDir),Y=y(XQ.cwd(),Q.generatedDir),Z=y(Y,"config-types.ts");if(!DX(rX(Z)))jZ(rX(Z),{recursive:!0,mode:511});let $=DX(X)?IZ(X).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],H=`// Generated by bunfig v${U8}
|
|
32
|
-
export type ConfigNames = ${$.length?`'${$.join("' | '")}'`:"string"}
|
|
33
|
-
`;FZ(Z,H,{mode:438})}function k0(Q){let X=null,Y=null,Z=()=>{if(!Y)Y=lY(Q).then((H)=>{return X=H,H},(H)=>{let U="defaultConfig"in Q?Q.defaultConfig:{};if(X=U,"verbose"in Q&&Q.verbose)m.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 _=$[U];return Z(),_},has(H,U){return U in(X||$)},ownKeys(){return Object.keys(X||$)},getOwnPropertyDescriptor(H,U){return Object.getOwnPropertyDescriptor(X||$,U)},set(H,U,_){if(!X)X={...$};return X[U]=_,!0}})}function P0(Q){let X=WY(lZ.cwd(),Q?.configDir||"./config");function Y(){if(!gZ(X))return[];let $=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),H=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=cZ(X).filter((J)=>$.has(WX(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),_=new Map;for(let{base:J,file:G}of U){let q=WX(G).toLowerCase(),A=_.get(J);if(!A){_.set(J,G);continue}let z=WX(A).toLowerCase();if(H.indexOf(q)<H.indexOf(z))_.set(J,G)}return Array.from(_.entries()).map(([J,G])=>({base:J,file:G})).sort((J,G)=>J.base.localeCompare(G.base))}function Z(){let $=Y(),H=$.map((G)=>G.base),U=H.length?H.map((G)=>`'${G}'`).join(" | "):"string",_=$.length?`{
|
|
34
|
-
${$.map((G)=>{let q=WY(X,G.file).replace(/\\/g,"/");return` '${G.base}': typeof import('${q}').default`}).join(`,
|
|
35
|
-
`)}
|
|
36
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
37
|
-
export type ConfigByName = ${_}
|
|
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 nY,zQ,jQ,iY,b0,y0,FY,yQ,EX,C,M,v0,MY,d0,DY,h0,f0,wX,p0,SY,VY,LX,m0,u0,g0,c0,vQ,sY,l0,x,n0,i0,EY,dQ,TX,E,L,s0,TY,o0,OY,t0,r0,KX,a0,NY,CY,e0,jX,Q8,X8,Y8,Z8,$8,hQ,oY,H8,U8="0.15.6",v,sQ,LQ,OX,NX,oQ,CX,xX,KQ,kX,PX,QQ,tY,rY,m,a,aY,eY,J8=J0(async()=>{nY=import.meta.require,zQ=new vX,jQ=new dX,iY={createKey:_0,isEquivalent:G0,estimateMemoryUsage:q0},b0=uQ(SX.cwd(),"config"),y0=uQ(SX.cwd(),"src/generated"),FY=mQ.env.CLARITY_LOG_DIR||SZ(z0(),"logs"),yQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:FY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},EX=await B0(),C={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},M=C,v0=C.red,MY=C.green,d0=C.yellow,DY=C.blue,h0=C.magenta,f0=C.cyan,wX=C.white,p0=C.gray,SY=C.bgRed,VY=C.bgYellow,LX=C.bold,m0=C.dim,u0=C.italic,g0=C.underline,c0=C.reset,vQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sY={debug:"\uD83D\uDD0D",info:DY("\u2139"),success:MY("\u2713"),warning:VY(wX(LX(" WARN "))),error:SY(wX(LX(" ERROR ")))},l0=new lQ("stacks"),x=new lQ("bunfig",{showTags:!0}),n0=b(wQ.cwd(),"config"),i0=b(wQ.cwd(),"src/generated"),EY=pQ.env.CLARITY_LOG_DIR||MZ(K0(),"logs"),dQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:EY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},TX=await j0(),E={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},L=E,s0=E.red,TY=E.green,o0=E.yellow,OY=E.blue,t0=E.magenta,r0=E.cyan,KX=E.white,a0=E.gray,NY=E.bgRed,CY=E.bgYellow,e0=E.bgGray,jX=E.bold,Q8=E.dim,X8=E.italic,Y8=E.underline,Z8=E.strikethrough,$8=E.reset,hQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oY={debug:"\uD83D\uDD0D",info:OY("\u2139"),success:TY("\u2713"),warning:CY(KX(jX(" WARN "))),error:NY(KX(jX(" ERROR ")))},H8=new iQ("stacks"),v=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}`}},sQ=class extends v{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})}},LQ=class extends v{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}},OX=class extends v{code="CONFIG_VALIDATION_ERROR";constructor(X,Y,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:Y,errorCount:Y.length})}},NX=class extends v{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}},oQ=class extends v{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:$})}},CX=class extends v{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}},xX=class extends v{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}},KQ=class extends v{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})}},kX=class extends v{code="BROWSER_CONFIG_ERROR";constructor(X,Y,Z,$){super(`Failed to fetch configuration from "${X}": ${Y} ${Z}`,{endpoint:X,status:Y,statusText:Z,configName:$})}},PX=class extends v{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}},QQ={configNotFound(Q,X,Y){return new sQ(Q,X,Y)},configLoad(Q,X,Y){return new LQ(Q,X,Y)},configValidation(Q,X,Y){return new OX(Q,X,Y)},configMerge(Q,X,Y,Z){return new NX(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new oQ(Q,X,Y,Z)},fileSystem(Q,X,Y){return new CX(Q,X,Y)},typeGeneration(Q,X,Y){return new xX(Q,X,Y)},schemaValidation(Q,X,Y){return new KQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new kX(Q,X,Y,Z)},plugin(Q,X,Y){return new PX(Q,X,Y)}},tY={replace:"replace",concat:"concat",smart:"smart"},rY=/^https?:\/\//,m=new iQ("bunfig",{showTags:!0}),a=new uX,aY=y(XQ.cwd(),"config"),eY=y(XQ.cwd(),"src/generated")});function _8(Q,X={}){let Y=gQ.cwd();while(Y.includes("storage"))Y=zY(Y,"..");let Z=zY(Y,Q||"");if(X?.relative)return iZ(gQ.cwd(),Z);return Z}var G8=gQ.env.CLARITY_LOG_DIR||nZ(_8(),"logs"),QZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:G8,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},tQ={...QZ},_$=(async()=>{try{let{loadConfig:Q}=await J8().then(()=>dY),X=await Q({name:"clarity",alias:"logging",defaultConfig:QZ,cwd:gQ.cwd()});if(X)Object.assign(tQ,X)}catch{}return tQ})();function T(){if(r.env.NODE_ENV==="test"||r.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function q8(){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 XZ{async format(Q){let X=await q8(),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}}}var O={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=O,G$=O.red,A8=O.green,q$=O.yellow,W8=O.blue,A$=O.magenta,W$=O.cyan,xY=O.white,z$=O.gray,z8=O.bgRed,B8=O.bgYellow,B$=O.bgGray,kY=O.bold,R$=O.dim,w$=O.italic,L$=O.underline,K$=O.strikethrough,j$=O.reset,IX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},R8={debug:"\uD83D\uDD0D",info:W8("\u2139"),success:A8("\u2713"),warning:B8(xY(kY(" WARN "))),error:z8(xY(kY(" ERROR ")))};class YX{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={...tQ},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new XZ,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,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{...IX,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...IX};return{...IX,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:tQ.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!T()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,_=1000;while(H<U)try{try{try{await aZ(this.config.logDirectory,LY.F_OK|LY.W_OK)}catch(G){if(G instanceof Error&&"code"in G)if(G.code==="ENOENT")await eZ(this.config.logDirectory,{recursive:!0,mode:493});else if(G.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw G;else throw G}}catch(G){throw console.error("Debug: [writeToFile] Failed to create log directory:",G),G}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:s.from(Q);try{if(!TQ(this.currentLogFile))await RX(this.currentLogFile,"",{mode:420});if($=wY(this.currentLogFile,"a",420),rZ($,J,{flag:"a"}),RY($),$!==void 0)BX($),$=void 0;if((await qQ(this.currentLogFile)).size===0){if(await RX(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(G){let q=G;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=_*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{BX($)}catch(G){console.error("Debug: [writeToFile] Error closing file descriptor:",G)}}}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,G))}})();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(T())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(([,_],[,J])=>J.createdAt.getTime()-_.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[_]of $.slice(U))this.encryptionKeys.delete(_),this.keys.delete(_)}generateKeyId(){return zX(16).toString("hex")}generateKey(){return zX(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=zX(16),Z=sZ("aes-256-gcm",X,Y),$=s.isBuffer(Q)?Q:s.from(Q,"utf8"),H=Z.update($),U=Z.final(),_=H.length+U.length,J=Z.getAuthTag(),G=s.allocUnsafe(16+_+16);return Y.copy(G,0),H.copy(G,16),U.copy(G,16+H.length),J.copy(G,16+_),{encrypted:G,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=jY(),$=[];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(T())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 OQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,G)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(G.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,_=`${Y}.${U}`;if(await qQ(Y).catch(()=>null))try{if(await KY(Y,_),X.compress)try{let J=`${_}.gz`;await this.compressLogFile(_,J),await NQ(_)}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 RX(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 KY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await OQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,_)=>_.localeCompare(U));for(let U of H.slice(X.maxFiles))await NQ(AQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=BY(Q),Z=tZ(X),$=jY();await Y0(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()})),TQ(this.currentLogFile))try{let Q=wY(this.currentLogFile,"r+");RY(Q),BX(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(!T()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await OQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await NQ(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()?j.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T())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,_=(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,G="";if(H==="warning"||H==="error")G=`${Y} ${$}`;else if(H==="info"||H==="success")G=`${Y} ${Z} ${$}`;else G=`${Y} ${Z} ${j.cyan($)}`;if(!U)return G.trim();let q=_(G).trim().length,A=_(X).length,z=Math.max(1,J-2-q-A);return`${G.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let _=Number.parseInt(U,10);return _<X[0].length?String(X[0][_]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let _=X[Z++];switch(U){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,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 _=`file://${encodeURI(U)}`,J="\x1B]8;;",G="\x1B\\";return`\x1B]8;;${_}\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(T())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(Q0(X)||X.startsWith("./")||X.startsWith("../"))X=X0(X);else return null;return TQ(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,_;if(X instanceof Error)U=X.message,_=X.stack;else U=this.formatMessage(X,Y);let{consoleText:J,fileText:G}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":R8[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),_){let I=_.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(!T()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),_)console.error(_)}let q=`${H} ${this.environment}.${Q.toUpperCase()}: ${G}
|
|
42
|
-
`;if(_)q+=`${_}
|
|
43
|
-
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,X=""){let Y={update:(_,J)=>{},finish:(_)=>{},interrupt:(_,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()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(_,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,_),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(_)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,_)},interrupt:(_,J="info")=>{if(!T()&&w.stdout.isTTY)w.stdout.write(`
|
|
44
|
-
`);if(this[J==="warning"?"warn":J](_),this.activeProgressBar&&this.shouldStyleConsole()&&!T()&&w.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,_=this.formatConsoleTimestamp(U),G=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)G+=` ${JSON.stringify(Y)}`;if(G+=`
|
|
45
|
-
`,G=G.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:_,icon:this.options.showIcons===!1?"":j.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T())console.error(G.trim());if(this.shouldWriteToFile())await this.writeToFile(G)}}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 YX(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(T())throw Error("createReadStream is not supported in browser environments");if(!TQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return BY(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),_=oZ("aes-256-gcm",Y,$);_.setAuthTag(H);let J=_.update(U),G=_.final(),q=J.length+G.length,A=s.allocUnsafe(q);return J.copy(A,0),G.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 T()}isServerMode(){return!T()}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 _=$.split(`
|
|
46
|
-
`),J=Math.max(..._.map((z)=>z.length))+2,G=`\u250C${"\u2500".repeat(J)}\u2510`,q=`\u2514${"\u2500".repeat(J)}\u2518`,A=_.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:j.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(G),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(q),showTimestamp:!1}))}else if(!T())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(T())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${j.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,G=0;if(Y=Q.replace(J,(q,A)=>{if(A==="%")return"%";if(G>=X.length)return q;let z=X[G++];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}}),G<X.length)Y+=` ${X.slice(G).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)):"",G=this.options.showIcons===!1?"":`${j.blue("\u25D0")} `;console.error(`${G}${J} ${j.cyan(Z)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
48
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(_)}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=j.green("\u2501".repeat(Z)),U=j.gray("\u2501".repeat($)),_=`[${H}${U}]`,J=`${Y}%`.padStart(4),G=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} ${_} ${J}${G}`,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(`
|
|
49
|
-
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||T()||!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(T()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await OQ(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 NQ(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 I$=new YX("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 YZ 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 rQ 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 $Z 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 gX 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 HZ 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 UZ 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 aQ 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 JZ 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 _Z 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 BQ={configNotFound(Q,X,Y){return new YZ(Q,X,Y)},configLoad(Q,X,Y){return new rQ(Q,X,Y)},configValidation(Q,X,Y){return new ZZ(Q,X,Y)},configMerge(Q,X,Y,Z){return new $Z(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new gX(Q,X,Y,Z)},fileSystem(Q,X,Y){return new HZ(Q,X,Y)},typeGeneration(Q,X,Y){return new UZ(Q,X,Y)},schemaValidation(Q,X,Y){return new aQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new JZ(Q,X,Y,Z)},plugin(Q,X,Y){return new _Z(Q,X,Y)}};async function w8(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,U=Error("Unknown error occurred");for(let _=0;_<=Y;_++)try{return await Q()}catch(J){if(U=J instanceof Error?J:Error(String(J)),_===Y||!$(U))break;if(Z>0)await new Promise((G)=>setTimeout(G,Z))}if(H!==void 0)return H;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class cX{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:_=!1,trackPerformance:J=!0}=Y,G=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:_,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return yX.track("applyEnvironmentVariables",G,{configName:Q});return G()}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,$],_=U.map((q)=>this.formatEnvKey(q,Z.useCamelCase)),J=`${Y}_${_.join("_")}`,G=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=xQ.env[J]||(G?xQ.env[G]:void 0);if(q!==void 0){if(Z.verbose){let A=xQ.env[J]?J:G}try{Q[$]=this.parseEnvironmentValue(q,typeof H,J,Z.customParsers,Z.configName)}catch(A){if(A instanceof gX)throw A;throw BQ.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 BQ.envVar(Y,Q,`${X} (via ${H.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(xQ.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,$],_=`${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:_,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 L8(Q,X,Y={}){return GZ(Q,X,Y,new WeakMap)}function GZ(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 _=U(Q,X);if(_!==void 0)return _}if(Array.isArray(X)||Array.isArray(Q))return qZ(Q,X,$,Z);if(!f(X)||!f(Q))return X;return F8(Q,X,Y,Z)}function qZ(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 K8(Q,X);case"smart":return j8(Q,X,Z);default:return X}return X}function K8(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>bX($,Z)))Y.push(Z);return Y}function j8(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(f(X[0])&&f(Q[0]))return I8(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 I8(Q,X,Y){let Z=[...X];for(let $ of Q){if(!f($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let _ of H)if(_ in $){if(Z.find((G)=>f(G)&&(_ in G)&&G[_]===$[_])){U=!0;break}}if(!U)Z.push($)}return Z}function F8(Q,X,Y,Z){let $=X;if(f($)&&Z.has($))return Z.get($);let H={...Q};if(f($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let _=$[U],J=H[U];if(Y.skipNullish&&(_===null||_===void 0))continue;if(_===null||_===void 0){H[U]=_;continue}if(f(_)&&f(J))H[U]=GZ(J,_,Y,Z);else if(Array.isArray(_)||Array.isArray(J))H[U]=qZ(J,_,Y.arrayMergeMode||"smart",Z);else H[U]=_}return H}function AZ(Q,X,Y="replace"){return L8(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function bX(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(!bX(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(!bX(Q[$],X[$]))return!1}return!0}return!1}function f(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class WZ{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:_=!1}=Y;if($){let G=fQ.getWithFileCheck("file",Q);if(G){if(_)console.log(`Configuration loaded from cache: ${Q}`);return G}}let J=async()=>{if(!kQ(Q))return null;try{let G=`?t=${Date.now()}`,q=await import(Q+G),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new rQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new rQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:AZ(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)fQ.setWithFileCheck("file",K,Q,H);return K}catch(G){throw G instanceof Error?BQ.configLoad(Q,G):BQ.configLoad(Q,Error(String(G)))}};if(U)return yX.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(FX(X,`${H}${U}`));return $}generateNamePatterns(Q,X){let Y=[];if(Y.push("config",".config"),Q)Y.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);let Z=X===void 0?[]:Array.isArray(X)?X:[X];for(let H of Z){if(!H)continue;if(Y.push(H,`.${H}.config`,`${H}.config`,`.${H}`),Q)Y.push(`${Q}.${H}.config`,`.${Q}.${H}.config`)}let $=new Set;return Y.filter((H)=>{if(!H||$.has(H))return!1;return $.add(H),!0})}checkFileAccess(Q){return w8(async()=>{return kQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!kQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let _=FX(Q,`${H}${U}`);if(await this.checkFileAccess(_))Z.push(_)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let _=FX(Q,U);if(await this.checkFileAccess(_))Z.push(_)}}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(!kQ(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 D8=/^https?:\/\//;class zZ{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:_=!0,verbose:J=!1}=Y,G=async()=>{let q=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:_,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(_)return await yX.track("validateConfiguration",G);return G()}async validateWithSchemaFile(Q,X,Y){try{if(!M8(X))throw new aQ(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 aQ(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,_=Array.isArray(X.type)?X.type:[X.type];if(!_.includes(U)){if(Z.push({path:Y,message:`Expected type ${_.join(" or ")}, got ${U}`,expected:_.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 _=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,_,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 _ of X.required)if(!(_ in U)){if(Z.push({path:Y?`${Y}.${_}`:_,message:`Missing required property '${_}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[_,J]of Object.entries(X.properties))if(_ in U){let G=Y?`${Y}.${_}`:_;if(this.validateObjectAgainstSchema(U[_],J,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let _=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!_.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),_=this.validateWithRule(U,H,H.path);if(Z.push(..._),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:D8},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var c=new YX("bunfig",{showTags:!0});function S8(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 BZ{fileLoader=new WZ;envProcessor=new cX;validator=new zZ;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 _;try{_=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){let G=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(G)throw J;_={...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(G&&(z||q))throw J;if(A&&(!G||!z))_={...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 _={...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(_.config,$,H,U.name);if(Y?.enabled&&_)this.cacheResult(U.name||"",_,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)c.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);_.metrics=J}return _}catch(_){if(_ instanceof Error&&_.name==="ConfigNotFoundError")throw _;let J=Date.now()-X;throw c.error(`Configuration loading failed after ${J}ms:`,[_ instanceof Error?_:Error(String(_))]),_}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:U,defaultConfig:_,checkEnv:J=!0,arrayStrategy:G="replace",verbose:q=!1}=Q,A=H||eQ.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(d(A,"package.json")),this.finalizeResult(B,z,J,Z,q);if(z.push(...this.getAllSearchPaths(Z,$,A,U)),X)throw BQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,_,J,q),warnings:[`No configuration file found for "${Z}"${S8($)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,_,J){let G=_?PQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let A of q){if(U)c.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,G,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(W){if(U)c.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?PQ(Q,Y,$):Y,_=[d(YQ(),".config",Q),d(YQ(),".config"),YQ()];for(let J of _){if($)c.info(`Checking home directory: ${J}`);let G=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(G,U,{arrayStrategy:Z,verbose:$});if(q){if($)c.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let _=U?PQ(Q,Z,H):Z;try{let J=d(Y,"package.json");if(!LZ(J))return null;let G={};try{G=JSON.parse(KZ(J,"utf8"))}catch(z){if(H)c.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let q=G[Q],A=Q;if(!q&&X){let z=Array.isArray(X)?X:[X];for(let W of z){if(!W)continue;if(G[W]){q=G[W],A=W;break}}}if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)c.success(`Configuration loaded from package.json: ${A}`);return{config:AZ(_,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)c.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:PQ(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 BQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return fQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);fQ.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.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,d(Q,"config"),d(Q,".config"),X?d(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(d(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=[d(YQ(),".config",Q),d(YQ(),".config"),YQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var MX=new BZ;async function RZ(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 MX.loadConfig(Q);else Z=await MX.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)c.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let _=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await MX.applyEnvironmentVariables(_.name||"",X,!0,_.verbose||!1))?.config??X;return X}}function PQ(Q,X,Y=!1){let Z=new cX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,_=[]){let J={...U};for(let[G,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=eQ.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof q==="boolean")J[G]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))J[G]=B}else if(Array.isArray(q))try{J[G]=JSON.parse(W)}catch{J[G]=W.split(",").map((B)=>B.trim())}else J[G]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))J[G]=H(q,A)}return J}return H(X)}var V$=d(eQ.cwd(),"config"),E$=d(eQ.cwd(),"src/generated");var wZ={floatPrecision:3,verbose:!1},lX=null;async function N$(){if(!lX)lX=await RZ({name:"css",defaultConfig:wZ});return lX}var C$=wZ;export{N8 as walk,u8 as syntax,k8 as stringifySelector,m8 as specificity,v8 as selectOne,y8 as selectAll,x8 as parseSelector,O8 as parse,p8 as minifyBlock,f8 as minify,P8 as isTraversal,d8 as is,N$ as getConfig,T8 as generate,wZ as defaultConfig,C8 as csstree,g8 as csso,b8 as cssWhat,h8 as cssSelect,C$ as config,E8 as clone,V8 as List};
|
|
2
|
+
import{s}from"./chunk-jj3s4ctf.js";import{t,y,e,o,n,N}from"./chunk-mz87cw2e.js";import{r,g,w,P}from"./chunk-br9jax0b.js";import{v,C,R,S}from"./chunk-0h48763m.js";import{m,l,c,k,A}from"./chunk-f9gzb0a5.js";var f={floatPrecision:3,verbose:!1},i=null;async function a(){if(!i)i=await s({name:"ts-css",defaultConfig:f});return i}var x=f;export{t as List,y as clone,x as config,S as cssSelect,P as cssWhat,A as csso,N as csstree,f as defaultConfig,e as generate,a as getConfig,R as is,w as isTraversal,m as minify,l as minifyBlock,o as parse,r as parseSelector,v as selectAll,C as selectOne,c as specificity,g as stringifySelector,k as syntax,n as walk};
|
package/dist/optimize/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{a,f,p,m,l,c,E,k}from"../chunk-f9gzb0a5.js";import"../chunk-mz87cw2e.js";import"../chunk-br9jax0b.js";export{p as compressTree,f as dedupeDeclarations,m as minify,l as minifyBlock,a as removeComments,c as specificity,E as specificityToString,k as syntax};
|
package/dist/parse/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{t,T,y,e,b,d,x,o,n}from"../chunk-mz87cw2e.js";export{t as List,b as TokenType,d as Tokenizer,y as clone,x as decodeName,e as generate,T as makeList,o as parse,n as walk};
|
package/dist/parse/list.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ export declare class CssList<T> {
|
|
|
24
24
|
get isEmpty(): boolean;
|
|
25
25
|
get first(): T | null;
|
|
26
26
|
get last(): T | null;
|
|
27
|
-
|
|
27
|
+
[Symbol.iterator](): Iterator<T>;
|
|
28
28
|
fromArray(items: ReadonlyArray<T>): this;
|
|
29
29
|
toArray(): T[];
|
|
30
30
|
toJSON(): T[];
|
package/dist/select/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{i,h,L,v,C,R}from"../chunk-0h48763m.js";import"../chunk-br9jax0b.js";export{L as clearSelectorCache,h as compile,R as is,i as parseAndCompile,v as selectAll,C as selectOne};
|
package/dist/what/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{r,g,w,O}from"../chunk-br9jax0b.js";export{O as IgnoreCaseMode,w as isTraversal,r as parse,g as stringify};
|
package/package.json
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/ts-css",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.1
|
|
5
|
-
"description": "Pure-TypeScript CSS toolkit for Bun/Node — parser, walker, generator, selector engine, and
|
|
4
|
+
"version": "0.3.1",
|
|
5
|
+
"description": "Pure-TypeScript CSS toolkit and utility-first CSS engine for Bun/Node — parser, walker, generator, selector engine, minifier, and a Tailwind-compatible utility engine. Zero runtime deps.",
|
|
6
6
|
"author": "Chris Breuer <chris@stacksjs.org>",
|
|
7
7
|
"license": "MIT",
|
|
8
|
-
"homepage": "https://github.com/
|
|
8
|
+
"homepage": "https://github.com/cwcss/crosswind/tree/main/packages/toolkit#readme",
|
|
9
9
|
"repository": {
|
|
10
10
|
"type": "git",
|
|
11
|
-
"url": "git+https://github.com/
|
|
11
|
+
"url": "git+https://github.com/cwcss/crosswind.git",
|
|
12
|
+
"directory": "packages/toolkit"
|
|
12
13
|
},
|
|
13
14
|
"bugs": {
|
|
14
|
-
"url": "https://github.com/
|
|
15
|
+
"url": "https://github.com/cwcss/crosswind/issues"
|
|
15
16
|
},
|
|
16
17
|
"keywords": [
|
|
17
18
|
"typescript",
|
|
@@ -26,7 +27,13 @@
|
|
|
26
27
|
"csso",
|
|
27
28
|
"css-tree",
|
|
28
29
|
"css-select",
|
|
29
|
-
"css-what"
|
|
30
|
+
"css-what",
|
|
31
|
+
"utility-first",
|
|
32
|
+
"tailwind",
|
|
33
|
+
"atomic-css",
|
|
34
|
+
"css-in-ts",
|
|
35
|
+
"stylex",
|
|
36
|
+
"crosswind"
|
|
30
37
|
],
|
|
31
38
|
"exports": {
|
|
32
39
|
".": {
|
|
@@ -49,6 +56,10 @@
|
|
|
49
56
|
"types": "./dist/optimize/index.d.ts",
|
|
50
57
|
"import": "./dist/optimize/index.js"
|
|
51
58
|
},
|
|
59
|
+
"./engine": {
|
|
60
|
+
"types": "./dist/engine/index.d.ts",
|
|
61
|
+
"import": "./dist/engine/index.js"
|
|
62
|
+
},
|
|
52
63
|
"./*": {
|
|
53
64
|
"import": "./dist/*"
|
|
54
65
|
}
|
|
@@ -56,28 +67,31 @@
|
|
|
56
67
|
"module": "./dist/index.js",
|
|
57
68
|
"types": "./dist/index.d.ts",
|
|
58
69
|
"bin": {
|
|
59
|
-
"ts-css": "./dist/bin/cli.js"
|
|
70
|
+
"ts-css": "./dist/bin/cli.js",
|
|
71
|
+
"cssx": "./dist/bin/cssx.js"
|
|
60
72
|
},
|
|
61
73
|
"files": [
|
|
62
74
|
"README.md",
|
|
75
|
+
"ENGINE.md",
|
|
76
|
+
"PLUGIN.md",
|
|
63
77
|
"dist"
|
|
64
78
|
],
|
|
65
79
|
"scripts": {
|
|
66
80
|
"build": "bun --bun build.ts && bun run compile",
|
|
67
81
|
"compile": "bun build ./bin/cli.ts --compile --minify --outfile bin/ts-css",
|
|
68
82
|
"compile:all": "bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64",
|
|
69
|
-
"compile:linux-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/ts-css-linux-x64",
|
|
70
|
-
"compile:linux-arm64": "bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/ts-css-linux-arm64",
|
|
71
|
-
"compile:windows-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/ts-css-windows-x64.exe",
|
|
72
|
-
"compile:darwin-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/ts-css-darwin-x64",
|
|
73
|
-
"compile:darwin-arm64": "bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/ts-css-darwin-arm64",
|
|
83
|
+
"compile:linux-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/ts-css-linux-x64 && bun build ./bin/cssx.ts --compile --minify --target=bun-linux-x64 --outfile bin/cssx-linux-x64",
|
|
84
|
+
"compile:linux-arm64": "bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/ts-css-linux-arm64 && bun build ./bin/cssx.ts --compile --minify --target=bun-linux-arm64 --outfile bin/cssx-linux-arm64",
|
|
85
|
+
"compile:windows-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/ts-css-windows-x64.exe && bun build ./bin/cssx.ts --compile --minify --target=bun-windows-x64 --outfile bin/cssx-windows-x64.exe",
|
|
86
|
+
"compile:darwin-x64": "bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/ts-css-darwin-x64 && bun build ./bin/cssx.ts --compile --minify --target=bun-darwin-x64 --outfile bin/cssx-darwin-x64",
|
|
87
|
+
"compile:darwin-arm64": "bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/ts-css-darwin-arm64 && bun build ./bin/cssx.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/cssx-darwin-arm64",
|
|
74
88
|
"zip": "bun run zip:all",
|
|
75
89
|
"zip:all": "bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64",
|
|
76
|
-
"zip:linux-x64": "zip -j bin/ts-css-linux-x64.zip bin/ts-css-linux-x64",
|
|
77
|
-
"zip:linux-arm64": "zip -j bin/ts-css-linux-arm64.zip bin/ts-css-linux-arm64",
|
|
78
|
-
"zip:windows-x64": "zip -j bin/ts-css-windows-x64.zip bin/ts-css-windows-x64.exe",
|
|
79
|
-
"zip:darwin-x64": "zip -j bin/ts-css-darwin-x64.zip bin/ts-css-darwin-x64",
|
|
80
|
-
"zip:darwin-arm64": "zip -j bin/ts-css-darwin-arm64.zip bin/ts-css-darwin-arm64",
|
|
90
|
+
"zip:linux-x64": "zip -j bin/ts-css-linux-x64.zip bin/ts-css-linux-x64 && zip -j bin/cssx-linux-x64.zip bin/cssx-linux-x64",
|
|
91
|
+
"zip:linux-arm64": "zip -j bin/ts-css-linux-arm64.zip bin/ts-css-linux-arm64 && zip -j bin/cssx-linux-arm64.zip bin/cssx-linux-arm64",
|
|
92
|
+
"zip:windows-x64": "zip -j bin/ts-css-windows-x64.zip bin/ts-css-windows-x64.exe && zip -j bin/cssx-windows-x64.zip bin/cssx-windows-x64.exe",
|
|
93
|
+
"zip:darwin-x64": "zip -j bin/ts-css-darwin-x64.zip bin/ts-css-darwin-x64 && zip -j bin/cssx-darwin-x64.zip bin/cssx-darwin-x64",
|
|
94
|
+
"zip:darwin-arm64": "zip -j bin/ts-css-darwin-arm64.zip bin/ts-css-darwin-arm64 && zip -j bin/cssx-darwin-arm64.zip bin/cssx-darwin-arm64",
|
|
81
95
|
"fresh": "bunx rimraf node_modules/ bun.lock && bun i",
|
|
82
96
|
"prepublishOnly": "bun --bun run build && bun run compile:all && bun run zip",
|
|
83
97
|
"test": "bun test",
|
|
@@ -94,10 +108,12 @@
|
|
|
94
108
|
"preview:docs": "bun --bun bunpress preview docs",
|
|
95
109
|
"typecheck": "bun --bun tsc --noEmit",
|
|
96
110
|
"format": "bunx --bun pickier . --format",
|
|
97
|
-
"format:fix": "bunx --bun pickier . --format --write"
|
|
111
|
+
"format:fix": "bunx --bun pickier . --format --write",
|
|
112
|
+
"benchmark": "bun run ../../benchmark/framework-comparison.bench.ts"
|
|
98
113
|
},
|
|
99
114
|
"dependencies": {
|
|
100
|
-
"
|
|
115
|
+
"@stacksjs/clapp": "^0.2.0",
|
|
116
|
+
"bunfig": "^0.15.17"
|
|
101
117
|
},
|
|
102
118
|
"devDependencies": {
|
|
103
119
|
"@types/bun": "latest",
|