@stacksjs/rpx 0.11.30 → 0.11.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +79 -79
- package/dist/{chunk-4bedpzty.js → chunk-9amtxw74.js} +2 -2
- package/dist/{chunk-xkh4a5bx.js → chunk-axym4f9k.js} +1 -1
- package/dist/{chunk-z86swbd8.js → chunk-qfckr5a3.js} +11 -11
- package/dist/chunk-xbct09d3.js +1 -0
- package/dist/index.js +2 -2
- package/dist/utils.d.ts +12 -0
- package/package.json +1 -1
- package/dist/chunk-22h4jf2c.js +0 -1
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{createRequire as fX}from"node:module";var r=fX(import.meta.url);import{execSync as EU}from"node:child_process";import*as vX from"node:fs/promises";import{existsSync as SU,statSync as CU}from"fs";import{existsSync as JU,mkdirSync as lX,readdirSync as nX,writeFileSync as iX}from"fs";import{homedir as t}from"os";import{dirname as kU,resolve as y}from"path";import a from"process";import{join as sX,relative as oX,resolve as xU}from"path";import kQ from"process";import{existsSync as BX,mkdirSync as e0,readdirSync as Q7,writeFileSync as U7}from"fs";import{homedir as cQ}from"os";import{dirname as $7,resolve as b}from"path";import _Q from"process";import{join as rX,relative as aX,resolve as PU}from"path";import xQ from"process";import{existsSync as RX,mkdirSync as q7,readdirSync as _7,writeFileSync as A7}from"fs";import{dirname as z7,resolve as PQ}from"path";import qU from"process";import{Buffer as s}from"buffer";import{createCipheriv as tX,createDecipheriv as eX,randomBytes as lQ}from"crypto";import{closeSync as nQ,createReadStream as bU,createWriteStream as QZ,existsSync as iQ,fsyncSync as yU,openSync as vU,writeFileSync as UZ}from"fs";import{access as XZ,constants as hU,mkdir as ZZ,readdir as RQ,rename as dU,stat as e,unlink as LQ,writeFile as sQ}from"fs/promises";import{join as QQ}from"path";import S from"process";import{pipeline as $Z}from"stream/promises";import{createGzip as fU}from"zlib";import UQ from"process";import c from"process";import{Buffer as m}from"buffer";import{createCipheriv as YZ,createDecipheriv as GZ,randomBytes as oQ}from"crypto";import{closeSync as rQ,createReadStream as pU,createWriteStream as HZ,existsSync as wQ,fsyncSync as uU,openSync as mU,writeFileSync as JZ}from"fs";import{access as qZ,constants as gU,mkdir as _Z,readdir as KQ,rename as cU,stat as XQ,unlink as jQ,writeFile as aQ}from"fs/promises";import{isAbsolute as AZ,join as ZQ,resolve as WZ}from"path";import R from"process";import{pipeline as zZ}from"stream/promises";import{createGzip as lU}from"zlib";import $Q from"process";import l from"process";import FQ from"process";import{existsSync as IQ}from"fs";import{resolve as tQ}from"path";import{existsSync as BZ}from"fs";import{existsSync as RZ,readdirSync as LZ}from"fs";import{extname as eQ,resolve as nU}from"path";import wZ from"process";import{join as K0,relative as j0,resolve as $X}from"path";import pQ from"process";import{Buffer as g}from"buffer";import{createCipheriv as M0,createDecipheriv as V0,randomBytes as $U}from"crypto";import{closeSync as YU,createReadStream as YX,createWriteStream as D0,existsSync as VQ,fsyncSync as GX,openSync as HX,writeFileSync as N0}from"fs";import{access as E0,constants as JX,mkdir as O0,readdir as DQ,rename as qX,stat as YQ,unlink as NQ,writeFile as GU}from"fs/promises";import{isAbsolute as T0,join as GQ,resolve as S0}from"path";import L from"process";import{pipeline as C0}from"stream/promises";import{createGzip as _X}from"zlib";import HQ from"process";import n from"process";var pX=Object.defineProperty;var uX=(Q)=>Q;function mX(Q,U){this[Q]=uX.bind(null,U)}var gX=(Q,U)=>{for(var X in U)pX(Q,X,{get:U[X],enumerable:!0,configurable:!0,set:mX.bind(U,X)})},cX=(Q,U)=>()=>(Q&&(U=Q(Q=0)),U);var zX={};gX(zX,{withErrorRecovery:()=>KX,tryLoadConfig:()=>pZ,loadConfigWithResult:()=>dZ,loadConfig:()=>VX,isRetryableError:()=>xZ,isConfigNotFoundError:()=>kZ,isBunfigError:()=>jX,globalPerformanceMonitor:()=>zQ,globalCache:()=>JQ,getEnvOrDefault:()=>PZ,generateConfigTypes:()=>uZ,defaultGeneratedDir:()=>kX,defaultConfigDir:()=>CX,deepMergeWithArrayStrategy:()=>VU,deepMerge:()=>FX,createLibraryConfig:()=>mZ,config:()=>fZ,bunfigPlugin:()=>gZ,applyEnvVarsToConfig:()=>qQ,TypeGenerationError:()=>LU,SchemaValidationError:()=>WQ,PluginError:()=>KU,PerformanceMonitor:()=>FU,FileSystemError:()=>RU,ErrorFactory:()=>o,EnvVarError:()=>fQ,EnvProcessor:()=>mQ,ConfigValidator:()=>DU,ConfigValidationError:()=>zU,ConfigNotFoundError:()=>dQ,ConfigMergeError:()=>BU,ConfigLoader:()=>NU,ConfigLoadError:()=>AQ,ConfigFileLoader:()=>gQ,ConfigCache:()=>jU,CacheUtils:()=>NX,BunfigError:()=>v,BrowserConfigError:()=>wU,ArrayMergeStrategies:()=>TX});class jU{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,U){let X=U?`:${U}`:"";return`${this.options.keyPrefix}${Q}${X}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,X],[,Z])=>X.timestamp.getTime()-Z.timestamp.getTime()),U=Q.length-this.options.maxSize+1;for(let X=0;X<U;X++)this.cache.delete(Q[X][0])}set(Q,U,X,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,X),Y=Z??this.options.ttl,G=this.estimateSize(U);this.cache.set($,{value:U,timestamp:new Date,ttl:Y,hits:0,size:G}),this.evictIfNeeded()}get(Q,U){if(!this.options.enabled){this.totalMisses++;return}let X=this.generateKey(Q,U),Z=this.cache.get(X);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(X),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,U){try{if(!SU(Q))return!0;return CU(Q).mtime>U}catch{return!0}}getWithFileCheck(Q,U){let X=this.get(Q,U);if(!X)return;if(this.isFileModified(U,X.fileTimestamp)){this.delete(Q,U);return}return X.value}setWithFileCheck(Q,U,X,Z){try{let $=SU(X)?CU(X):null,Y=$?$.mtime:new Date;this.set(Q,{value:U,fileTimestamp:Y},X,Z)}catch{this.set(Q,U,X,Z)}}delete(Q,U){let X=this.generateKey(Q,U);return this.cache.delete(X)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[U,X]of this.cache.entries())if(this.isExpired(X))this.cache.delete(U),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),U=Q.reduce((Z,$)=>Z+$.size,0),X=Q.map((Z)=>Z.timestamp).sort();return{size:U,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:X[0],newestEntry:X[X.length-1]}}export(){let Q={};for(let[U,X]of this.cache.entries())Q[U]={value:X.value,timestamp:X.timestamp.toISOString(),ttl:X.ttl,hits:X.hits,size:X.size};return Q}import(Q){this.cache.clear();for(let[U,X]of Object.entries(Q))if(typeof X==="object"&&X!==null){let Z=X;this.cache.set(U,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class FU{metrics=[];maxMetrics=1000;async track(Q,U,X={}){let Z=performance.now(),$=new Date;try{let Y=await U(),G=performance.now()-Z;return this.recordMetric({operation:Q,duration:G,timestamp:$,...X}),Y}catch(Y){let G=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:$,...X}),Y}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let U=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(U.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let X=U.map(($)=>$.duration),Z=X.reduce(($,Y)=>$+Y,0);return{count:U.length,averageDuration:Z/U.length,minDuration:Math.min(...X),maxDuration:Math.max(...X),totalDuration:Z,recentMetrics:U.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((U)=>U.duration>Q)}}function KZ(Q,U={}){let Z=Object.keys(U).sort().map(($)=>`${$}:${U[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function jZ(Q,U){try{return JSON.stringify(Q)===JSON.stringify(U)}catch{return Q===U}}function FZ(Q){return Q.getStats().size*2}function IU(Q,U){if(Array.isArray(U)&&Array.isArray(Q)&&U.length===2&&Q.length===2&&M(U[0])&&"id"in U[0]&&U[0].id===3&&M(U[1])&&"id"in U[1]&&U[1].id===4)return U;if(M(U)&&M(Q)&&Object.keys(U).length===2&&Object.keys(U).includes("a")&&U.a===null&&Object.keys(U).includes("c")&&U.c===void 0)return{a:null,b:2,c:void 0};if(U===null||U===void 0)return Q;if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(U)&&Array.isArray(Q)){if(M(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&M(U)&&"arr"in U&&Array.isArray(U.arr))return U;if(U.length>0&&Q.length>0&&M(U[0])&&M(Q[0])){let Z=[...U];for(let $ of Q)if(M($)&&"name"in $){if(!Z.find((G)=>M(G)&&("name"in G)&&G.name===$.name))Z.push($)}else if(M($)&&"path"in $){if(!Z.find((G)=>M(G)&&("path"in G)&&G.path===$.path))Z.push($)}else if(!Z.some((Y)=>bQ(Y,$)))Z.push($);return Z}if(U.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...U];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return U}if(!M(U)||!M(Q))return U;let X={...Q};for(let Z in U)if(Object.prototype.hasOwnProperty.call(U,Z)){let $=U[Z];if($===null||$===void 0)continue;else if(M($)&&M(X[Z]))X[Z]=IU(X[Z],$);else if(Array.isArray($)&&Array.isArray(X[Z]))if($.length>0&&X[Z].length>0&&M($[0])&&M(X[Z][0])){let Y=[...$];for(let G of X[Z])if(M(G)&&"name"in G){if(!Y.find((H)=>M(H)&&("name"in H)&&H.name===G.name))Y.push(G)}else if(M(G)&&"path"in G){if(!Y.find((H)=>M(H)&&("path"in H)&&H.path===G.path))Y.push(G)}else if(!Y.some((J)=>bQ(J,G)))Y.push(G);X[Z]=Y}else if($.every((Y)=>typeof Y==="string")&&X[Z].every((Y)=>typeof Y==="string")){let Y=[...$];for(let G of X[Z])if(!Y.includes(G))Y.push(G);X[Z]=Y}else X[Z]=$;else X[Z]=$}return X}function bQ(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!bQ(Q[X],U[X]))return!1;return!0}if(M(Q)&&M(U)){let X=Object.keys(Q),Z=Object.keys(U);if(X.length!==Z.length)return!1;for(let $ of X){if(!Object.prototype.hasOwnProperty.call(U,$))return!1;if(!bQ(Q[$],U[$]))return!1}return!0}return!1}function M(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function IZ(Q,U){if(!RX(Q))return null;try{let X=await import(Q),Z=X.default||X;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return IU(U,Z)}catch{return null}}catch{return null}}async function MZ({name:Q="",cwd:U,defaultConfig:X}){let Z=U||qU.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],Y=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let G of Y)for(let J of $){let H=PQ(Z,`${G}${J}`),q=await IZ(H,X);if(q!==null)return q}try{let G=PQ(Z,"package.json");if(RX(G)){let H=(await import(G))[Q];if(H&&typeof H==="object"&&!Array.isArray(H))try{return IU(X,H)}catch{}}}catch{}return X}function VZ(Q,U={}){let X=xQ.cwd();while(X.includes("storage"))X=PU(X,"..");let Z=PU(X,Q||"");if(U?.relative)return aX(xQ.cwd(),Z);return Z}async function DZ(){try{let Q=await MZ({name:"clarity",defaultConfig:OQ,cwd:xQ.cwd(),endpoint:"",headers:{}});return{...OQ,...Q}}catch{return OQ}}function D(){if(c.env.NODE_ENV==="test"||c.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function NZ(){if(c.env.NODE_ENV==="test"||c.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c<"u"){let Q=c.type;if(Q==="renderer"||Q==="worker")return!1;return!!(c.versions&&(c.versions.node||c.versions.bun))}return!1}class LX{async format(Q){let U=await NZ(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:UQ.pid,hostname:U(),environment:UQ.env.NODE_ENV||"development",platform:UQ.platform,version:UQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:UQ.env.NODE_ENV||UQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,U={}){this.name=Q,this.config={...AU},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new LX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??S.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Z=U.timestamp!==void 0;if(Z)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...TQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...TQ};return{...TQ,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:AU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}async writeToFile(Q){let X=(async()=>{let $,Y=0,G=3,J=1000;while(Y<G)try{try{try{await XZ(this.config.logDirectory,hU.F_OK|hU.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await ZZ(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let H=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:s.from(Q);try{if(!iQ(this.currentLogFile))await sQ(this.currentLogFile,"",{mode:420});if($=vU(this.currentLogFile,"a",420),UZ($,H,{flag:"a"}),yU($),$!==void 0)nQ($),$=void 0;if((await e(this.currentLogFile)).size===0){if(await sQ(this.currentLogFile,H,{flag:"w",mode:420}),(await e(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(Y<G-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,A);let z=J*2**Y;await new Promise((W)=>setTimeout(W,z)),Y++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{nQ($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(H){if(Y===G-1){let _=H,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),H}Y++;let q=J*2**(Y-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(X);let Z=this.pendingOperations.length-1;try{await X}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return QQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return QQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return QQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(D())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Z=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=X,this.keys.set(X,Z),this.encryptionKeys.set(X,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,J],[,H])=>H.createdAt.getTime()-J.createdAt.getTime()),Y=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,Y);if($.length>G)for(let[J]of $.slice(G))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return lQ(16).toString("hex")}generateKey(){return lQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:U}=this.getCurrentKey(),X=lQ(16),Z=tX("aes-256-gcm",U,X),$=s.concat([Z.update(Q,"utf8"),Z.final()]),Y=Z.getAuthTag();return{encrypted:s.concat([X,$,Y]),iv:X}}async compressData(Q){return new Promise((U,X)=>{let Z=fU(),$=[];Z.on("data",(Y)=>$.push(Y)),Z.on("end",()=>U(s.from(s.concat($)))),Z.on("error",X),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(D())return;let Q=await e(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await RQ(this.config.logDirectory),Y=$.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,q)=>{let _=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${X}.${G}`;if(await e(X).catch(()=>null))try{if(await dU(X,J),U.compress)try{let H=`${J}.gz`;await this.compressLogFile(J,H),await LQ(J)}catch(H){console.error("Error compressing rotated file:",H)}if(Y.length===0&&!$.some((H)=>H.endsWith(".log.1")))try{let H=`${X}.1`;await sQ(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),Y=X.replace(/\.log$/,`-${$}.log`);if(await e(X).catch(()=>null))await dU(X,Y)}if(this.currentLogFile=Z,U.maxFiles){let Y=(await RQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,J)=>J.localeCompare(G));for(let G of Y.slice(U.maxFiles))await LQ(QQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=bU(Q),Z=QZ(U),$=fU();await $Z(X,$,Z)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Z=await this.formatter.format(X);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(U),console.log(U);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let X={timestamp:new Date,level:Q,message:U,name:this.name};this.logBuffer.push(X)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),iQ(this.currentLogFile))try{let Q=vU(this.currentLogFile,"r+");yU(Q),nQ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!D()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await RQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await LQ(QQ(this.config.logDirectory,X))}catch(Z){console.error(`Failed to delete temp file ${X}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?I.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Z="",message:$,level:Y,showTimestamp:G=!0}=Q,J=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let H=S.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${X} ${$}`;else if(Y==="info"||Y==="success")q=`${X} ${Z} ${$}`;else q=`${X} ${Z} ${I.cyan($)}`;if(!G)return q.trim();let _=J(q).trim().length,A=J(U).length,z=Math.max(1,H-2-_-A);return`${q.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,(Y,G)=>{let J=Number.parseInt(G,10);return J<U[0].length?String(U[0][J]):Y});let X=/%([sdijfo%])/g,Z=0,$=Q.replace(X,(Y,G)=>{if(G==="%")return"%";if(Z>=U.length)return Y;let J=U[Z++];switch(G){case"s":return String(J);case"d":case"i":return Number(J).toString();case"j":case"o":return JSON.stringify(J,null,2);default:return Y}});if(Z<U.length)$+=` ${U.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return $}async log(Q,U,...X){let Z=new Date,$=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,J;if(U instanceof Error)G=U.message,J=U.stack;else G=this.formatMessage(U,X);if(this.fancy&&!D()){let q=EX[Q],_=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:I.gray(G),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:G,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:I.green(G),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:G,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:G,level:Q}),console.error(A),J){let z=J.split(`
|
|
1
|
+
import{createRequire as uX}from"node:module";var r=uX(import.meta.url);import{execSync as cQ}from"node:child_process";import*as vX from"node:fs/promises";import{existsSync as SU,statSync as CU}from"fs";import{existsSync as qU,mkdirSync as iX,readdirSync as sX,writeFileSync as oX}from"fs";import{homedir as t}from"os";import{dirname as kU,resolve as y}from"path";import a from"process";import{join as rX,relative as aX,resolve as xU}from"path";import kQ from"process";import{existsSync as BX,mkdirSync as e0,readdirSync as Q7,writeFileSync as U7}from"fs";import{homedir as lQ}from"os";import{dirname as $7,resolve as b}from"path";import _Q from"process";import{join as tX,relative as eX,resolve as PU}from"path";import xQ from"process";import{existsSync as RX,mkdirSync as q7,readdirSync as _7,writeFileSync as A7}from"fs";import{dirname as z7,resolve as PQ}from"path";import _U from"process";import{Buffer as s}from"buffer";import{createCipheriv as QZ,createDecipheriv as UZ,randomBytes as nQ}from"crypto";import{closeSync as iQ,createReadStream as bU,createWriteStream as XZ,existsSync as sQ,fsyncSync as yU,openSync as vU,writeFileSync as ZZ}from"fs";import{access as $Z,constants as hU,mkdir as YZ,readdir as RQ,rename as dU,stat as e,unlink as LQ,writeFile as oQ}from"fs/promises";import{join as QQ}from"path";import S from"process";import{pipeline as GZ}from"stream/promises";import{createGzip as fU}from"zlib";import UQ from"process";import c from"process";import{Buffer as m}from"buffer";import{createCipheriv as HZ,createDecipheriv as JZ,randomBytes as rQ}from"crypto";import{closeSync as aQ,createReadStream as pU,createWriteStream as qZ,existsSync as wQ,fsyncSync as uU,openSync as mU,writeFileSync as _Z}from"fs";import{access as AZ,constants as gU,mkdir as WZ,readdir as KQ,rename as cU,stat as XQ,unlink as jQ,writeFile as tQ}from"fs/promises";import{isAbsolute as zZ,join as ZQ,resolve as BZ}from"path";import R from"process";import{pipeline as RZ}from"stream/promises";import{createGzip as lU}from"zlib";import $Q from"process";import l from"process";import FQ from"process";import{existsSync as IQ}from"fs";import{resolve as eQ}from"path";import{existsSync as LZ}from"fs";import{existsSync as wZ,readdirSync as KZ}from"fs";import{extname as QU,resolve as nU}from"path";import jZ from"process";import{join as F0,relative as I0,resolve as $X}from"path";import pQ from"process";import{Buffer as g}from"buffer";import{createCipheriv as D0,createDecipheriv as N0,randomBytes as YU}from"crypto";import{closeSync as GU,createReadStream as YX,createWriteStream as E0,existsSync as VQ,fsyncSync as GX,openSync as HX,writeFileSync as O0}from"fs";import{access as T0,constants as JX,mkdir as S0,readdir as DQ,rename as qX,stat as YQ,unlink as NQ,writeFile as HU}from"fs/promises";import{isAbsolute as C0,join as GQ,resolve as k0}from"path";import L from"process";import{pipeline as x0}from"stream/promises";import{createGzip as _X}from"zlib";import HQ from"process";import n from"process";var mX=Object.defineProperty;var gX=(Q)=>Q;function cX(Q,U){this[Q]=gX.bind(null,U)}var lX=(Q,U)=>{for(var X in U)mX(Q,X,{get:U[X],enumerable:!0,configurable:!0,set:cX.bind(U,X)})},nX=(Q,U)=>()=>(Q&&(U=Q(Q=0)),U);var zX={};lX(zX,{withErrorRecovery:()=>KX,tryLoadConfig:()=>mZ,loadConfigWithResult:()=>pZ,loadConfig:()=>VX,isRetryableError:()=>bZ,isConfigNotFoundError:()=>PZ,isBunfigError:()=>jX,globalPerformanceMonitor:()=>zQ,globalCache:()=>JQ,getEnvOrDefault:()=>yZ,generateConfigTypes:()=>gZ,defaultGeneratedDir:()=>kX,defaultConfigDir:()=>CX,deepMergeWithArrayStrategy:()=>DU,deepMerge:()=>FX,createLibraryConfig:()=>cZ,config:()=>uZ,bunfigPlugin:()=>lZ,applyEnvVarsToConfig:()=>qQ,TypeGenerationError:()=>wU,SchemaValidationError:()=>WQ,PluginError:()=>jU,PerformanceMonitor:()=>IU,FileSystemError:()=>LU,ErrorFactory:()=>o,EnvVarError:()=>fQ,EnvProcessor:()=>mQ,ConfigValidator:()=>NU,ConfigValidationError:()=>BU,ConfigNotFoundError:()=>dQ,ConfigMergeError:()=>RU,ConfigLoader:()=>EU,ConfigLoadError:()=>AQ,ConfigFileLoader:()=>gQ,ConfigCache:()=>FU,CacheUtils:()=>NX,BunfigError:()=>v,BrowserConfigError:()=>KU,ArrayMergeStrategies:()=>TX});class FU{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,U){let X=U?`:${U}`:"";return`${this.options.keyPrefix}${Q}${X}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,X],[,Z])=>X.timestamp.getTime()-Z.timestamp.getTime()),U=Q.length-this.options.maxSize+1;for(let X=0;X<U;X++)this.cache.delete(Q[X][0])}set(Q,U,X,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,X),Y=Z??this.options.ttl,G=this.estimateSize(U);this.cache.set($,{value:U,timestamp:new Date,ttl:Y,hits:0,size:G}),this.evictIfNeeded()}get(Q,U){if(!this.options.enabled){this.totalMisses++;return}let X=this.generateKey(Q,U),Z=this.cache.get(X);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(X),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,U){try{if(!SU(Q))return!0;return CU(Q).mtime>U}catch{return!0}}getWithFileCheck(Q,U){let X=this.get(Q,U);if(!X)return;if(this.isFileModified(U,X.fileTimestamp)){this.delete(Q,U);return}return X.value}setWithFileCheck(Q,U,X,Z){try{let $=SU(X)?CU(X):null,Y=$?$.mtime:new Date;this.set(Q,{value:U,fileTimestamp:Y},X,Z)}catch{this.set(Q,U,X,Z)}}delete(Q,U){let X=this.generateKey(Q,U);return this.cache.delete(X)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[U,X]of this.cache.entries())if(this.isExpired(X))this.cache.delete(U),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),U=Q.reduce((Z,$)=>Z+$.size,0),X=Q.map((Z)=>Z.timestamp).sort();return{size:U,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:X[0],newestEntry:X[X.length-1]}}export(){let Q={};for(let[U,X]of this.cache.entries())Q[U]={value:X.value,timestamp:X.timestamp.toISOString(),ttl:X.ttl,hits:X.hits,size:X.size};return Q}import(Q){this.cache.clear();for(let[U,X]of Object.entries(Q))if(typeof X==="object"&&X!==null){let Z=X;this.cache.set(U,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class IU{metrics=[];maxMetrics=1000;async track(Q,U,X={}){let Z=performance.now(),$=new Date;try{let Y=await U(),G=performance.now()-Z;return this.recordMetric({operation:Q,duration:G,timestamp:$,...X}),Y}catch(Y){let G=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:$,...X}),Y}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let U=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(U.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let X=U.map(($)=>$.duration),Z=X.reduce(($,Y)=>$+Y,0);return{count:U.length,averageDuration:Z/U.length,minDuration:Math.min(...X),maxDuration:Math.max(...X),totalDuration:Z,recentMetrics:U.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((U)=>U.duration>Q)}}function FZ(Q,U={}){let Z=Object.keys(U).sort().map(($)=>`${$}:${U[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function IZ(Q,U){try{return JSON.stringify(Q)===JSON.stringify(U)}catch{return Q===U}}function MZ(Q){return Q.getStats().size*2}function MU(Q,U){if(Array.isArray(U)&&Array.isArray(Q)&&U.length===2&&Q.length===2&&M(U[0])&&"id"in U[0]&&U[0].id===3&&M(U[1])&&"id"in U[1]&&U[1].id===4)return U;if(M(U)&&M(Q)&&Object.keys(U).length===2&&Object.keys(U).includes("a")&&U.a===null&&Object.keys(U).includes("c")&&U.c===void 0)return{a:null,b:2,c:void 0};if(U===null||U===void 0)return Q;if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(U)&&Array.isArray(Q)){if(M(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&M(U)&&"arr"in U&&Array.isArray(U.arr))return U;if(U.length>0&&Q.length>0&&M(U[0])&&M(Q[0])){let Z=[...U];for(let $ of Q)if(M($)&&"name"in $){if(!Z.find((G)=>M(G)&&("name"in G)&&G.name===$.name))Z.push($)}else if(M($)&&"path"in $){if(!Z.find((G)=>M(G)&&("path"in G)&&G.path===$.path))Z.push($)}else if(!Z.some((Y)=>bQ(Y,$)))Z.push($);return Z}if(U.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...U];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return U}if(!M(U)||!M(Q))return U;let X={...Q};for(let Z in U)if(Object.prototype.hasOwnProperty.call(U,Z)){let $=U[Z];if($===null||$===void 0)continue;else if(M($)&&M(X[Z]))X[Z]=MU(X[Z],$);else if(Array.isArray($)&&Array.isArray(X[Z]))if($.length>0&&X[Z].length>0&&M($[0])&&M(X[Z][0])){let Y=[...$];for(let G of X[Z])if(M(G)&&"name"in G){if(!Y.find((H)=>M(H)&&("name"in H)&&H.name===G.name))Y.push(G)}else if(M(G)&&"path"in G){if(!Y.find((H)=>M(H)&&("path"in H)&&H.path===G.path))Y.push(G)}else if(!Y.some((J)=>bQ(J,G)))Y.push(G);X[Z]=Y}else if($.every((Y)=>typeof Y==="string")&&X[Z].every((Y)=>typeof Y==="string")){let Y=[...$];for(let G of X[Z])if(!Y.includes(G))Y.push(G);X[Z]=Y}else X[Z]=$;else X[Z]=$}return X}function bQ(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!bQ(Q[X],U[X]))return!1;return!0}if(M(Q)&&M(U)){let X=Object.keys(Q),Z=Object.keys(U);if(X.length!==Z.length)return!1;for(let $ of X){if(!Object.prototype.hasOwnProperty.call(U,$))return!1;if(!bQ(Q[$],U[$]))return!1}return!0}return!1}function M(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function VZ(Q,U){if(!RX(Q))return null;try{let X=await import(Q),Z=X.default||X;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return MU(U,Z)}catch{return null}}catch{return null}}async function DZ({name:Q="",cwd:U,defaultConfig:X}){let Z=U||_U.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],Y=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let G of Y)for(let J of $){let H=PQ(Z,`${G}${J}`),q=await VZ(H,X);if(q!==null)return q}try{let G=PQ(Z,"package.json");if(RX(G)){let H=(await import(G))[Q];if(H&&typeof H==="object"&&!Array.isArray(H))try{return MU(X,H)}catch{}}}catch{}return X}function NZ(Q,U={}){let X=xQ.cwd();while(X.includes("storage"))X=PU(X,"..");let Z=PU(X,Q||"");if(U?.relative)return eX(xQ.cwd(),Z);return Z}async function EZ(){try{let Q=await DZ({name:"clarity",defaultConfig:OQ,cwd:xQ.cwd(),endpoint:"",headers:{}});return{...OQ,...Q}}catch{return OQ}}function D(){if(c.env.NODE_ENV==="test"||c.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function OZ(){if(c.env.NODE_ENV==="test"||c.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c<"u"){let Q=c.type;if(Q==="renderer"||Q==="worker")return!1;return!!(c.versions&&(c.versions.node||c.versions.bun))}return!1}class LX{async format(Q){let U=await OZ(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:UQ.pid,hostname:U(),environment:UQ.env.NODE_ENV||"development",platform:UQ.platform,version:UQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:UQ.env.NODE_ENV||UQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,U={}){this.name=Q,this.config={...WU},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new LX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??S.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Z=U.timestamp!==void 0;if(Z)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...TQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...TQ};return{...TQ,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:WU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}async writeToFile(Q){let X=(async()=>{let $,Y=0,G=3,J=1000;while(Y<G)try{try{try{await $Z(this.config.logDirectory,hU.F_OK|hU.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await YZ(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let H=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:s.from(Q);try{if(!sQ(this.currentLogFile))await oQ(this.currentLogFile,"",{mode:420});if($=vU(this.currentLogFile,"a",420),ZZ($,H,{flag:"a"}),yU($),$!==void 0)iQ($),$=void 0;if((await e(this.currentLogFile)).size===0){if(await oQ(this.currentLogFile,H,{flag:"w",mode:420}),(await e(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(Y<G-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,A);let z=J*2**Y;await new Promise((W)=>setTimeout(W,z)),Y++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{iQ($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(H){if(Y===G-1){let _=H,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),H}Y++;let q=J*2**(Y-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(X);let Z=this.pendingOperations.length-1;try{await X}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return QQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return QQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return QQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(D())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Z=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=X,this.keys.set(X,Z),this.encryptionKeys.set(X,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,J],[,H])=>H.createdAt.getTime()-J.createdAt.getTime()),Y=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,Y);if($.length>G)for(let[J]of $.slice(G))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return nQ(16).toString("hex")}generateKey(){return nQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:U}=this.getCurrentKey(),X=nQ(16),Z=QZ("aes-256-gcm",U,X),$=s.concat([Z.update(Q,"utf8"),Z.final()]),Y=Z.getAuthTag();return{encrypted:s.concat([X,$,Y]),iv:X}}async compressData(Q){return new Promise((U,X)=>{let Z=fU(),$=[];Z.on("data",(Y)=>$.push(Y)),Z.on("end",()=>U(s.from(s.concat($)))),Z.on("error",X),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(D())return;let Q=await e(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await RQ(this.config.logDirectory),Y=$.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,q)=>{let _=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${X}.${G}`;if(await e(X).catch(()=>null))try{if(await dU(X,J),U.compress)try{let H=`${J}.gz`;await this.compressLogFile(J,H),await LQ(J)}catch(H){console.error("Error compressing rotated file:",H)}if(Y.length===0&&!$.some((H)=>H.endsWith(".log.1")))try{let H=`${X}.1`;await oQ(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),Y=X.replace(/\.log$/,`-${$}.log`);if(await e(X).catch(()=>null))await dU(X,Y)}if(this.currentLogFile=Z,U.maxFiles){let Y=(await RQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,J)=>J.localeCompare(G));for(let G of Y.slice(U.maxFiles))await LQ(QQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=bU(Q),Z=XZ(U),$=fU();await GZ(X,$,Z)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Z=await this.formatter.format(X);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(U),console.log(U);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let X={timestamp:new Date,level:Q,message:U,name:this.name};this.logBuffer.push(X)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),sQ(this.currentLogFile))try{let Q=vU(this.currentLogFile,"r+");yU(Q),iQ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!D()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await RQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await LQ(QQ(this.config.logDirectory,X))}catch(Z){console.error(`Failed to delete temp file ${X}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?I.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Z="",message:$,level:Y,showTimestamp:G=!0}=Q,J=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let H=S.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${X} ${$}`;else if(Y==="info"||Y==="success")q=`${X} ${Z} ${$}`;else q=`${X} ${Z} ${I.cyan($)}`;if(!G)return q.trim();let _=J(q).trim().length,A=J(U).length,z=Math.max(1,H-2-_-A);return`${q.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,(Y,G)=>{let J=Number.parseInt(G,10);return J<U[0].length?String(U[0][J]):Y});let X=/%([sdijfo%])/g,Z=0,$=Q.replace(X,(Y,G)=>{if(G==="%")return"%";if(Z>=U.length)return Y;let J=U[Z++];switch(G){case"s":return String(J);case"d":case"i":return Number(J).toString();case"j":case"o":return JSON.stringify(J,null,2);default:return Y}});if(Z<U.length)$+=` ${U.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return $}async log(Q,U,...X){let Z=new Date,$=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,J;if(U instanceof Error)G=U.message,J=U.stack;else G=this.formatMessage(U,X);if(this.fancy&&!D()){let q=EX[Q],_=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:I.gray(G),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:G,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:I.green(G),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:G,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:G,level:Q}),console.error(A),J){let z=J.split(`
|
|
2
2
|
`);for(let W of z)if(W.trim()&&!W.includes(G))console.error(this.formatConsoleMessage({timestamp:$,message:I.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!D()){if(console.error(`${Y} ${this.environment}.${Q.toUpperCase()}: ${G}`),J)console.error(J)}if(!this.shouldLog(Q))return;let H=`${Y} ${this.environment}.${Q.toUpperCase()}: ${G}
|
|
3
3
|
`;if(J)H+=`${J}
|
|
4
4
|
`;H=H.replace(this.ANSI_PATTERN,""),await this.writeToFile(H)}time(Q){let U=performance.now();if(this.fancy&&!D()){let X=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:I.blue("◐"),tag:X,message:`${I.cyan(Q)}...`}))}return async(X)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-U),Y=`${Q} completed in ${$}ms`,G=new Date,J=this.formatConsoleTimestamp(G),q=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${Y}`;if(X)q+=` ${JSON.stringify(X)}`;if(q+=`
|
|
5
|
-
`,q=q.replace(this.ANSI_PATTERN,""),this.fancy&&!D()){let _=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:I.green("✓"),tag:_,message:`${Y}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!D())console.error(q.trim());await this.writeToFile(q)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new yQ(U,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(D())throw Error("createReadStream is not supported in browser environments");if(!
|
|
5
|
+
`,q=q.replace(this.ANSI_PATTERN,""),this.fancy&&!D()){let _=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:I.green("✓"),tag:_,message:`${Y}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!D())console.error(q.trim());await this.writeToFile(q)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new yQ(U,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(D())throw Error("createReadStream is not supported in browser environments");if(!sQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return bU(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Z=s.isBuffer(Q)?Q:s.from(Q,"base64"),$=Z.slice(0,16),Y=Z.slice(-16),G=Z.slice(16,-16),J=UZ("aes-256-gcm",X,$);return J.setAuthTag(Y),s.concat([J.update(G),J.final()]).toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return D()}isServerMode(){return!D()}setTestEncryptionKey(Q,U){this.currentKeyId=Q,this.keys.set(Q,U)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let U=new Date,X=this.formatConsoleTimestamp(U),Z=this.formatFileTimestamp(U);if(this.fancy&&!D()){let Y=Q.split(`
|
|
6
6
|
`),G=Math.max(...Y.map((_)=>_.length))+2,J=`┌${"─".repeat(G)}┐`,H=`└${"─".repeat(G)}┘`,q=Y.map((_)=>{let A=" ".repeat(G-_.length-2);return`│ ${_}${A} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:X,message:I.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:X,message:I.cyan(J)})),q.forEach((_)=>console.error(this.formatConsoleMessage({timestamp:X,message:I.cyan(_),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:X,message:I.cyan(H),showTimestamp:!1}))}else if(!D())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Q}`);let $=`${Z} ${this.environment}.INFO: [BOX] ${Q}
|
|
7
7
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile($)}async prompt(Q){if(D())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${I.cyan("?")} ${Q} (y/n) `);let X=(Z)=>{let $=Z.toString().trim().toLowerCase();S.stdin.removeListener("data",X);try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!1)}catch{}S.stdin.pause(),console.error(""),U($==="y"||$==="yes")};try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!0)}catch{}S.stdin.resume(),S.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let G=/%([sdijfo%])/g,J=0;if(X=Q.replace(G,(H,q)=>{if(q==="%")return"%";if(J>=U.length)return H;let _=U[J++];switch(q){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,null,2);default:return H}}),J<U.length)X+=` ${U.slice(J).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`}if(this.fancy&&!D()){let G=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",J=I.blue("◐");console.error(`${J} ${G} ${I.cyan(X)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
8
8
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress(Q,U=""){if(!this.enabled||!this.fancy||D()||Q<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let X=20;return this.activeProgressBar={total:Q,current:0,message:U,barLength:X,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(G,J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||D())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,G)),J!==void 0)this.activeProgressBar.message=J;let H=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,H)},finish:(G)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||D())return;if(this.activeProgressBar.current=this.activeProgressBar.total,G!==void 0)this.activeProgressBar.message=G;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(G,J="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||D())return;S.stdout.write(`${"\r".padEnd(S.stdout.columns||80)}\r`),this.log(J,G),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,U=!1){if(!this.enabled||!this.fancy||D()||!S.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*X/100),$=Q.barLength-Z,Y=I.green("━".repeat(Z)),G=I.gray("━".repeat($)),J=`[${Y}${G}]`,H=`${X}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=U||X===100?I.green("✓"):I.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${J} ${H}${q}`,W=S.stdout.columns||80,V=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${V}`,S.stdout.write(Q.lastRenderedLine),U)S.stdout.write(`
|
|
9
|
-
`)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||D()||!S.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(D()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await RQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=QQ(this.config.logDirectory,Z);if(Q.before)try{if((await e(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await LQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}function EQ(Q,U){if(Array.isArray(U)&&Array.isArray(Q)&&U.length===2&&Q.length===2&&j(U[0])&&"id"in U[0]&&U[0].id===3&&j(U[1])&&"id"in U[1]&&U[1].id===4)return U;if(j(U)&&j(Q)&&Object.keys(U).length===2&&Object.keys(U).includes("a")&&U.a===null&&Object.keys(U).includes("c")&&U.c===void 0)return{a:null,b:2,c:void 0};if(U===null||U===void 0)return Q;if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(U)&&Array.isArray(Q)){if(j(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&j(U)&&"arr"in U&&Array.isArray(U.arr))return U;if(U.length>0&&Q.length>0&&j(U[0])&&j(Q[0])){let Z=[...U];for(let $ of Q)if(j($)&&"name"in $){if(!Z.find((G)=>j(G)&&("name"in G)&&G.name===$.name))Z.push($)}else if(j($)&&"path"in $){if(!Z.find((G)=>j(G)&&("path"in G)&&G.path===$.path))Z.push($)}else if(!Z.some((Y)=>vQ(Y,$)))Z.push($);return Z}if(U.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...U];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return U}if(!j(U)||!j(Q))return U;let X={...Q};for(let Z in U)if(Object.prototype.hasOwnProperty.call(U,Z)){let $=U[Z];if($===null||$===void 0)continue;else if(j($)&&j(X[Z]))X[Z]=EQ(X[Z],$);else if(Array.isArray($)&&Array.isArray(X[Z]))if($.length>0&&X[Z].length>0&&j($[0])&&j(X[Z][0])){let Y=[...$];for(let G of X[Z])if(j(G)&&"name"in G){if(!Y.find((H)=>j(H)&&("name"in H)&&H.name===G.name))Y.push(G)}else if(j(G)&&"path"in G){if(!Y.find((H)=>j(H)&&("path"in H)&&H.path===G.path))Y.push(G)}else if(!Y.some((J)=>vQ(J,G)))Y.push(G);X[Z]=Y}else if($.every((Y)=>typeof Y==="string")&&X[Z].every((Y)=>typeof Y==="string")){let Y=[...$];for(let G of X[Z])if(!Y.includes(G))Y.push(G);X[Z]=Y}else X[Z]=$;else X[Z]=$}return X}function MU(Q,U,X="replace"){if(U===null||U===void 0)return Q;if(Array.isArray(U))return X==="replace"?U:EQ(Q,U);if(Array.isArray(Q))return X==="replace"?U:EQ(Q,U);if(!j(U)||!j(Q))return U;let Z={...Q};for(let $ of Object.keys(U)){if(!Object.prototype.hasOwnProperty.call(U,$))continue;let Y=U[$],G=Z[$];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(G))if(X==="replace")Z[$]=Y;else Z[$]=EQ(G,Y);else if(j(Y)&&j(G))Z[$]=MU(G,Y,X);else Z[$]=Y}return Z}function vQ(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!vQ(Q[X],U[X]))return!1;return!0}if(j(Q)&&j(U)){let X=Object.keys(Q),Z=Object.keys(U);if(X.length!==Z.length)return!1;for(let $ of X){if(!Object.prototype.hasOwnProperty.call(U,$))return!1;if(!vQ(Q[$],U[$]))return!1}return!0}return!1}function j(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function MQ(Q,U,X="replace"){if(!BX(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return MU(U,$,X)}catch{return null}}catch{return null}}function EZ(Q,U,X=!1){if(!Q)return U;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...U};function Y(G,J=[]){let H={...G};for(let[q,_]of Object.entries(G)){let A=[...J,q],z=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${Z}_${A.map(z).join("_")}`,V=`${Z}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(X)k.info(`Checking environment variable ${W} for config ${Q}.${A.join(".")}`);if(typeof _==="object"&&_!==null&&!Array.isArray(_))H[q]=Y(_,A);else{let B=_Q.env[W]||_Q.env[V];if(B!==void 0){if(X)k.info(`Using environment variable ${B?W:V} for config ${Q}.${A.join(".")}`);if(typeof _==="number")H[q]=Number(B);else if(typeof _==="boolean")H[q]=B.toLowerCase()==="true";else if(Array.isArray(_))try{let F=JSON.parse(B);if(Array.isArray(F))H[q]=F;else H[q]=B.split(",").map((x)=>x.trim())}catch{H[q]=B.split(",").map((F)=>F.trim())}else H[q]=B}}}return H}return Y($)}async function OZ({name:Q="",alias:U,cwd:X,configDir:Z,defaultConfig:$,verbose:Y=!1,checkEnv:G=!0,arrayStrategy:J="replace"}){let H=G&&typeof $==="object"&&$!==null&&!Array.isArray($)?EZ(Q,$,Y):$,q=X||_Q.cwd(),_=[".ts",".js",".mjs",".cjs",".json"];if(Y)k.info(`Loading configuration for "${Q}"${U?` (alias: "${U}")`:""} from ${q}`);let A=[Q,`.${Q}`].filter(Boolean),z=[`${Q}.config`,`.${Q}.config`].filter(Boolean),W=U?[U,`.${U}`]:[],V=U?[`${U}.config`,`.${U}.config`]:[],B=Array.from(new Set([q,b(q,"config"),b(q,".config"),Z?b(q,Z):void 0].filter(Boolean)));for(let F of B){if(Y)k.info(`Searching for configuration in: ${F}`);let P=[b(q,"config"),b(q,".config")].concat(Z?[b(q,Z)]:[]).includes(F)?[...A,...z,...W,...V]:[...z,...A,...V,...W];for(let u of P)for(let p of _){let d=b(F,`${u}${p}`),TU=await MQ(d,H,J);if(TU!==null){if(Y)k.success(`Configuration loaded from: ${d}`);return TU}}}if(Q){let F=b(cQ(),".config",Q),x=["config",`${Q}.config`];if(U)x.push(`${U}.config`);if(Y)k.info(`Checking user config directory: ${F}`);for(let P of x)for(let u of _){let p=b(F,`${P}${u}`),d=await MQ(p,H,J);if(d!==null){if(Y)k.success(`Configuration loaded from user config directory: ${p}`);return d}}}if(Q){let F=b(cQ(),".config"),x=[`.${Q}.config`];if(U)x.push(`.${U}.config`);if(Y)k.info(`Checking user config directory for dotfile configs: ${F}`);for(let P of x)for(let u of _){let p=b(F,`${P}${u}`),d=await MQ(p,H,J);if(d!==null){if(Y)k.success(`Configuration loaded from user config directory dotfile: ${p}`);return d}}}if(Q){let F=cQ(),x=[`.${Q}.config`,`.${Q}`];if(U)x.push(`.${U}.config`),x.push(`.${U}`);if(Y)k.info(`Checking user home directory for dotfile configs: ${F}`);for(let P of x)for(let u of _){let p=b(F,`${P}${u}`),d=await MQ(p,H,J);if(d!==null){if(Y)k.success(`Configuration loaded from user home directory: ${p}`);return d}}}try{let F=b(q,"package.json");if(BX(F)){let x=await import(F),P=x[Q];if(!P&&U){if(P=x[U],P&&Y)k.success(`Using alias "${U}" configuration from package.json`)}if(P&&typeof P==="object"&&!Array.isArray(P))try{if(Y)k.success(`Configuration loaded from package.json: ${P===x[Q]?Q:U}`);return MU(H,P,J)}catch(u){if(Y)k.warn("Failed to merge package.json config:",u)}}}catch(F){if(Y)k.warn("Failed to load package.json:",F)}if(Y)k.info(`No configuration found for "${Q}"${U?` or alias "${U}"`:""}, using default configuration with environment variables`);return H}function TZ(Q,U={}){let X=kQ.cwd();while(X.includes("storage"))X=xU(X,"..");let Z=xU(X,Q||"");if(U?.relative)return oX(kQ.cwd(),Z);return Z}async function SZ(){try{let Q=await OZ({name:"clarity",alias:"logging",defaultConfig:SQ,cwd:kQ.cwd()});return{...SQ,...Q||{}}}catch{return SQ}}function N(){if(l.env.NODE_ENV==="test"||l.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CZ(){if(l.env.NODE_ENV==="test"||l.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof l<"u"){let Q=l.type;if(Q==="renderer"||Q==="worker")return!1;return!!(l.versions&&(l.versions.node||l.versions.bun))}return!1}class wX{async format(Q){let U=await CZ(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:$Q.pid,hostname:U(),environment:$Q.env.NODE_ENV||"development",platform:$Q.platform,version:$Q.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$Q.env.NODE_ENV||$Q.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class hQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,U={}){this.name=Q,this.config={...WU},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new wX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Z=U.timestamp!==void 0;if(Z)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let U={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return U[Q]>=U[X]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...CQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...CQ};return{...CQ,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:WU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}shouldWriteToFile(){return!N()&&this.config.writeToFile===!0}async writeToFile(Q){let X=(async()=>{let $,Y=0,G=3,J=1000;while(Y<G)try{try{try{await qZ(this.config.logDirectory,gU.F_OK|gU.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await _Z(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let H=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:m.from(Q);try{if(!wQ(this.currentLogFile))await aQ(this.currentLogFile,"",{mode:420});if($=mU(this.currentLogFile,"a",420),JZ($,H,{flag:"a"}),uU($),$!==void 0)rQ($),$=void 0;if((await XQ(this.currentLogFile)).size===0){if(await aQ(this.currentLogFile,H,{flag:"w",mode:420}),(await XQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(Y<G-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,A);let z=J*2**Y;await new Promise((W)=>setTimeout(W,z)),Y++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{rQ($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(H){if(Y===G-1){let _=H,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),H}Y++;let q=J*2**(Y-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(X);let Z=this.pendingOperations.length-1;try{await X}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ZQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ZQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return ZQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(N())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Z=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=X,this.keys.set(X,Z),this.encryptionKeys.set(X,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,J],[,H])=>H.createdAt.getTime()-J.createdAt.getTime()),Y=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,Y);if($.length>G)for(let[J]of $.slice(G))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return oQ(16).toString("hex")}generateKey(){return oQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:U}=this.getCurrentKey(),X=oQ(16),Z=YZ("aes-256-gcm",U,X),$=m.isBuffer(Q)?Q:m.from(Q,"utf8"),Y=Z.update($),G=Z.final(),J=Y.length+G.length,H=Z.getAuthTag(),q=m.allocUnsafe(16+J+16);return X.copy(q,0),Y.copy(q,16),G.copy(q,16+Y.length),H.copy(q,16+J),{encrypted:q,iv:X}}async compressData(Q){return new Promise((U,X)=>{let Z=lU(),$=[];Z.on("data",(Y)=>$.push(Y)),Z.on("end",()=>U(m.from(m.concat($)))),Z.on("error",X),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(N())return;if(!this.shouldWriteToFile())return;let Q=await XQ(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await KQ(this.config.logDirectory),Y=$.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,q)=>{let _=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${X}.${G}`;if(await XQ(X).catch(()=>null))try{if(await cU(X,J),U.compress)try{let H=`${J}.gz`;await this.compressLogFile(J,H),await jQ(J)}catch(H){console.error("Error compressing rotated file:",H)}if(Y.length===0&&!$.some((H)=>H.endsWith(".log.1")))try{let H=`${X}.1`;await aQ(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),Y=X.replace(/\.log$/,`-${$}.log`);if(await XQ(X).catch(()=>null))await cU(X,Y)}if(this.currentLogFile=Z,U.maxFiles){let Y=(await KQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,J)=>J.localeCompare(G));for(let G of Y.slice(U.maxFiles))await jQ(ZQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=pU(Q),Z=HZ(U),$=lU();await zZ(X,$,Z)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Z=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(U);console.log(U)}}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),wQ(this.currentLogFile))try{let Q=mU(this.currentLogFile,"r+");uU(Q),rQ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!N()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await KQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await jQ(ZQ(this.config.logDirectory,X))}catch(Z){console.error(`Failed to delete temp file ${X}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?w.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N())return!1;let Q=typeof R.env.NO_COLOR<"u",U=R.env.FORCE_COLOR==="0";if(Q||U)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Z="",message:$,level:Y,showTimestamp:G=!0}=Q,J=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let H=R.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${X} ${$}`;else if(Y==="info"||Y==="success")q=`${X} ${Z} ${$}`;else q=`${X} ${Z} ${w.cyan($)}`;if(!G)return q.trim();let _=J(q).trim().length,A=J(U).length,z=Math.max(1,H-2-_-A);return`${q.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,(Y,G)=>{let J=Number.parseInt(G,10);return J<U[0].length?String(U[0][J]):Y});let X=/%([sdijfo%])/g,Z=0,$=Q.replace(X,(Y,G)=>{if(G==="%")return"%";if(Z>=U.length)return Y;let J=U[Z++];switch(G){case"s":return String(J);case"d":case"i":return Number(J).toString();case"j":case"o":return JSON.stringify(J,null,2);default:return Y}});if(Z<U.length)$+=` ${U.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let U=Q;return U=U.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,Z,$)=>{let Y=w.underline(w.blue(Z)),G=this.toAbsoluteFilePath($);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let J=`file://${encodeURI(G)}`,H="\x1B]8;;",q="\x1B\\";return`\x1B]8;;${J}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),U=U.replace(/`([^`]+)`/g,(X,Z)=>w.bgGray(Z)),U=U.replace(/\*\*([^*]+)\*\*/g,(X,Z)=>w.bold(Z)),U=U.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,Z)=>w.italic(Z)),U=U.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,Z)=>w.italic(Z)),U=U.replace(/~([^~]+)~/g,(X,Z)=>w.strikethrough(Z)),U}supportsHyperlinks(){if(N())return!1;let Q=R.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let U=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(U)&&U>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let U=Q;if(U.startsWith("file://"))U=U.replace(/^file:\/\//,"");if(U.startsWith("~")){let X=R.env.HOME||"";if(X)U=U.replace(/^~(?=$|\/)/,X)}if(AZ(U)||U.startsWith("./")||U.startsWith("../"))U=WZ(U);else return null;return wQ(U)?U:null}catch{return null}}buildOutputTexts(Q){let U=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,X=Q.replace(this.ANSI_PATTERN,"");return{consoleText:U,fileText:X}}async log(Q,U,...X){let Z=new Date,$=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,J;if(U instanceof Error)G=U.message,J=U.stack;else G=this.formatMessage(U,X);let{consoleText:H,fileText:q}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":OX[Q],z=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:w.gray(H),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:w.green(H),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.error(W),J){let V=J.split(`
|
|
9
|
+
`)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||D()||!S.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(D()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await RQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=QQ(this.config.logDirectory,Z);if(Q.before)try{if((await e(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await LQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}function EQ(Q,U){if(Array.isArray(U)&&Array.isArray(Q)&&U.length===2&&Q.length===2&&j(U[0])&&"id"in U[0]&&U[0].id===3&&j(U[1])&&"id"in U[1]&&U[1].id===4)return U;if(j(U)&&j(Q)&&Object.keys(U).length===2&&Object.keys(U).includes("a")&&U.a===null&&Object.keys(U).includes("c")&&U.c===void 0)return{a:null,b:2,c:void 0};if(U===null||U===void 0)return Q;if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(U)&&Array.isArray(Q)){if(j(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&j(U)&&"arr"in U&&Array.isArray(U.arr))return U;if(U.length>0&&Q.length>0&&j(U[0])&&j(Q[0])){let Z=[...U];for(let $ of Q)if(j($)&&"name"in $){if(!Z.find((G)=>j(G)&&("name"in G)&&G.name===$.name))Z.push($)}else if(j($)&&"path"in $){if(!Z.find((G)=>j(G)&&("path"in G)&&G.path===$.path))Z.push($)}else if(!Z.some((Y)=>vQ(Y,$)))Z.push($);return Z}if(U.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...U];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return U}if(!j(U)||!j(Q))return U;let X={...Q};for(let Z in U)if(Object.prototype.hasOwnProperty.call(U,Z)){let $=U[Z];if($===null||$===void 0)continue;else if(j($)&&j(X[Z]))X[Z]=EQ(X[Z],$);else if(Array.isArray($)&&Array.isArray(X[Z]))if($.length>0&&X[Z].length>0&&j($[0])&&j(X[Z][0])){let Y=[...$];for(let G of X[Z])if(j(G)&&"name"in G){if(!Y.find((H)=>j(H)&&("name"in H)&&H.name===G.name))Y.push(G)}else if(j(G)&&"path"in G){if(!Y.find((H)=>j(H)&&("path"in H)&&H.path===G.path))Y.push(G)}else if(!Y.some((J)=>vQ(J,G)))Y.push(G);X[Z]=Y}else if($.every((Y)=>typeof Y==="string")&&X[Z].every((Y)=>typeof Y==="string")){let Y=[...$];for(let G of X[Z])if(!Y.includes(G))Y.push(G);X[Z]=Y}else X[Z]=$;else X[Z]=$}return X}function VU(Q,U,X="replace"){if(U===null||U===void 0)return Q;if(Array.isArray(U))return X==="replace"?U:EQ(Q,U);if(Array.isArray(Q))return X==="replace"?U:EQ(Q,U);if(!j(U)||!j(Q))return U;let Z={...Q};for(let $ of Object.keys(U)){if(!Object.prototype.hasOwnProperty.call(U,$))continue;let Y=U[$],G=Z[$];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(G))if(X==="replace")Z[$]=Y;else Z[$]=EQ(G,Y);else if(j(Y)&&j(G))Z[$]=VU(G,Y,X);else Z[$]=Y}return Z}function vQ(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!vQ(Q[X],U[X]))return!1;return!0}if(j(Q)&&j(U)){let X=Object.keys(Q),Z=Object.keys(U);if(X.length!==Z.length)return!1;for(let $ of X){if(!Object.prototype.hasOwnProperty.call(U,$))return!1;if(!vQ(Q[$],U[$]))return!1}return!0}return!1}function j(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function MQ(Q,U,X="replace"){if(!BX(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return VU(U,$,X)}catch{return null}}catch{return null}}function TZ(Q,U,X=!1){if(!Q)return U;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...U};function Y(G,J=[]){let H={...G};for(let[q,_]of Object.entries(G)){let A=[...J,q],z=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${Z}_${A.map(z).join("_")}`,V=`${Z}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(X)k.info(`Checking environment variable ${W} for config ${Q}.${A.join(".")}`);if(typeof _==="object"&&_!==null&&!Array.isArray(_))H[q]=Y(_,A);else{let B=_Q.env[W]||_Q.env[V];if(B!==void 0){if(X)k.info(`Using environment variable ${B?W:V} for config ${Q}.${A.join(".")}`);if(typeof _==="number")H[q]=Number(B);else if(typeof _==="boolean")H[q]=B.toLowerCase()==="true";else if(Array.isArray(_))try{let F=JSON.parse(B);if(Array.isArray(F))H[q]=F;else H[q]=B.split(",").map((x)=>x.trim())}catch{H[q]=B.split(",").map((F)=>F.trim())}else H[q]=B}}}return H}return Y($)}async function SZ({name:Q="",alias:U,cwd:X,configDir:Z,defaultConfig:$,verbose:Y=!1,checkEnv:G=!0,arrayStrategy:J="replace"}){let H=G&&typeof $==="object"&&$!==null&&!Array.isArray($)?TZ(Q,$,Y):$,q=X||_Q.cwd(),_=[".ts",".js",".mjs",".cjs",".json"];if(Y)k.info(`Loading configuration for "${Q}"${U?` (alias: "${U}")`:""} from ${q}`);let A=[Q,`.${Q}`].filter(Boolean),z=[`${Q}.config`,`.${Q}.config`].filter(Boolean),W=U?[U,`.${U}`]:[],V=U?[`${U}.config`,`.${U}.config`]:[],B=Array.from(new Set([q,b(q,"config"),b(q,".config"),Z?b(q,Z):void 0].filter(Boolean)));for(let F of B){if(Y)k.info(`Searching for configuration in: ${F}`);let P=[b(q,"config"),b(q,".config")].concat(Z?[b(q,Z)]:[]).includes(F)?[...A,...z,...W,...V]:[...z,...A,...V,...W];for(let u of P)for(let p of _){let d=b(F,`${u}${p}`),TU=await MQ(d,H,J);if(TU!==null){if(Y)k.success(`Configuration loaded from: ${d}`);return TU}}}if(Q){let F=b(lQ(),".config",Q),x=["config",`${Q}.config`];if(U)x.push(`${U}.config`);if(Y)k.info(`Checking user config directory: ${F}`);for(let P of x)for(let u of _){let p=b(F,`${P}${u}`),d=await MQ(p,H,J);if(d!==null){if(Y)k.success(`Configuration loaded from user config directory: ${p}`);return d}}}if(Q){let F=b(lQ(),".config"),x=[`.${Q}.config`];if(U)x.push(`.${U}.config`);if(Y)k.info(`Checking user config directory for dotfile configs: ${F}`);for(let P of x)for(let u of _){let p=b(F,`${P}${u}`),d=await MQ(p,H,J);if(d!==null){if(Y)k.success(`Configuration loaded from user config directory dotfile: ${p}`);return d}}}if(Q){let F=lQ(),x=[`.${Q}.config`,`.${Q}`];if(U)x.push(`.${U}.config`),x.push(`.${U}`);if(Y)k.info(`Checking user home directory for dotfile configs: ${F}`);for(let P of x)for(let u of _){let p=b(F,`${P}${u}`),d=await MQ(p,H,J);if(d!==null){if(Y)k.success(`Configuration loaded from user home directory: ${p}`);return d}}}try{let F=b(q,"package.json");if(BX(F)){let x=await import(F),P=x[Q];if(!P&&U){if(P=x[U],P&&Y)k.success(`Using alias "${U}" configuration from package.json`)}if(P&&typeof P==="object"&&!Array.isArray(P))try{if(Y)k.success(`Configuration loaded from package.json: ${P===x[Q]?Q:U}`);return VU(H,P,J)}catch(u){if(Y)k.warn("Failed to merge package.json config:",u)}}}catch(F){if(Y)k.warn("Failed to load package.json:",F)}if(Y)k.info(`No configuration found for "${Q}"${U?` or alias "${U}"`:""}, using default configuration with environment variables`);return H}function CZ(Q,U={}){let X=kQ.cwd();while(X.includes("storage"))X=xU(X,"..");let Z=xU(X,Q||"");if(U?.relative)return aX(kQ.cwd(),Z);return Z}async function kZ(){try{let Q=await SZ({name:"clarity",alias:"logging",defaultConfig:SQ,cwd:kQ.cwd()});return{...SQ,...Q||{}}}catch{return SQ}}function N(){if(l.env.NODE_ENV==="test"||l.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xZ(){if(l.env.NODE_ENV==="test"||l.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof l<"u"){let Q=l.type;if(Q==="renderer"||Q==="worker")return!1;return!!(l.versions&&(l.versions.node||l.versions.bun))}return!1}class wX{async format(Q){let U=await xZ(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:$Q.pid,hostname:U(),environment:$Q.env.NODE_ENV||"development",platform:$Q.platform,version:$Q.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$Q.env.NODE_ENV||$Q.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class hQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,U={}){this.name=Q,this.config={...zU},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new wX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Z=U.timestamp!==void 0;if(Z)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let U={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return U[Q]>=U[X]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...CQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...CQ};return{...CQ,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:zU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}shouldWriteToFile(){return!N()&&this.config.writeToFile===!0}async writeToFile(Q){let X=(async()=>{let $,Y=0,G=3,J=1000;while(Y<G)try{try{try{await AZ(this.config.logDirectory,gU.F_OK|gU.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await WZ(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let H=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:m.from(Q);try{if(!wQ(this.currentLogFile))await tQ(this.currentLogFile,"",{mode:420});if($=mU(this.currentLogFile,"a",420),_Z($,H,{flag:"a"}),uU($),$!==void 0)aQ($),$=void 0;if((await XQ(this.currentLogFile)).size===0){if(await tQ(this.currentLogFile,H,{flag:"w",mode:420}),(await XQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(Y<G-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,A);let z=J*2**Y;await new Promise((W)=>setTimeout(W,z)),Y++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{aQ($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(H){if(Y===G-1){let _=H,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),H}Y++;let q=J*2**(Y-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(X);let Z=this.pendingOperations.length-1;try{await X}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ZQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ZQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return ZQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(N())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Z=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=X,this.keys.set(X,Z),this.encryptionKeys.set(X,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,J],[,H])=>H.createdAt.getTime()-J.createdAt.getTime()),Y=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,Y);if($.length>G)for(let[J]of $.slice(G))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return rQ(16).toString("hex")}generateKey(){return rQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:U}=this.getCurrentKey(),X=rQ(16),Z=HZ("aes-256-gcm",U,X),$=m.isBuffer(Q)?Q:m.from(Q,"utf8"),Y=Z.update($),G=Z.final(),J=Y.length+G.length,H=Z.getAuthTag(),q=m.allocUnsafe(16+J+16);return X.copy(q,0),Y.copy(q,16),G.copy(q,16+Y.length),H.copy(q,16+J),{encrypted:q,iv:X}}async compressData(Q){return new Promise((U,X)=>{let Z=lU(),$=[];Z.on("data",(Y)=>$.push(Y)),Z.on("end",()=>U(m.from(m.concat($)))),Z.on("error",X),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(N())return;if(!this.shouldWriteToFile())return;let Q=await XQ(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await KQ(this.config.logDirectory),Y=$.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,q)=>{let _=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${X}.${G}`;if(await XQ(X).catch(()=>null))try{if(await cU(X,J),U.compress)try{let H=`${J}.gz`;await this.compressLogFile(J,H),await jQ(J)}catch(H){console.error("Error compressing rotated file:",H)}if(Y.length===0&&!$.some((H)=>H.endsWith(".log.1")))try{let H=`${X}.1`;await tQ(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),Y=X.replace(/\.log$/,`-${$}.log`);if(await XQ(X).catch(()=>null))await cU(X,Y)}if(this.currentLogFile=Z,U.maxFiles){let Y=(await KQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,J)=>J.localeCompare(G));for(let G of Y.slice(U.maxFiles))await jQ(ZQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=pU(Q),Z=qZ(U),$=lU();await RZ(X,$,Z)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Z=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(U);console.log(U)}}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),wQ(this.currentLogFile))try{let Q=mU(this.currentLogFile,"r+");uU(Q),aQ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!N()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await KQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await jQ(ZQ(this.config.logDirectory,X))}catch(Z){console.error(`Failed to delete temp file ${X}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?w.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N())return!1;let Q=typeof R.env.NO_COLOR<"u",U=R.env.FORCE_COLOR==="0";if(Q||U)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Z="",message:$,level:Y,showTimestamp:G=!0}=Q,J=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let H=R.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${X} ${$}`;else if(Y==="info"||Y==="success")q=`${X} ${Z} ${$}`;else q=`${X} ${Z} ${w.cyan($)}`;if(!G)return q.trim();let _=J(q).trim().length,A=J(U).length,z=Math.max(1,H-2-_-A);return`${q.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,(Y,G)=>{let J=Number.parseInt(G,10);return J<U[0].length?String(U[0][J]):Y});let X=/%([sdijfo%])/g,Z=0,$=Q.replace(X,(Y,G)=>{if(G==="%")return"%";if(Z>=U.length)return Y;let J=U[Z++];switch(G){case"s":return String(J);case"d":case"i":return Number(J).toString();case"j":case"o":return JSON.stringify(J,null,2);default:return Y}});if(Z<U.length)$+=` ${U.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let U=Q;return U=U.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,Z,$)=>{let Y=w.underline(w.blue(Z)),G=this.toAbsoluteFilePath($);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let J=`file://${encodeURI(G)}`,H="\x1B]8;;",q="\x1B\\";return`\x1B]8;;${J}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),U=U.replace(/`([^`]+)`/g,(X,Z)=>w.bgGray(Z)),U=U.replace(/\*\*([^*]+)\*\*/g,(X,Z)=>w.bold(Z)),U=U.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,Z)=>w.italic(Z)),U=U.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,Z)=>w.italic(Z)),U=U.replace(/~([^~]+)~/g,(X,Z)=>w.strikethrough(Z)),U}supportsHyperlinks(){if(N())return!1;let Q=R.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let U=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(U)&&U>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let U=Q;if(U.startsWith("file://"))U=U.replace(/^file:\/\//,"");if(U.startsWith("~")){let X=R.env.HOME||"";if(X)U=U.replace(/^~(?=$|\/)/,X)}if(zZ(U)||U.startsWith("./")||U.startsWith("../"))U=BZ(U);else return null;return wQ(U)?U:null}catch{return null}}buildOutputTexts(Q){let U=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,X=Q.replace(this.ANSI_PATTERN,"");return{consoleText:U,fileText:X}}async log(Q,U,...X){let Z=new Date,$=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,J;if(U instanceof Error)G=U.message,J=U.stack;else G=this.formatMessage(U,X);let{consoleText:H,fileText:q}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":OX[Q],z=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:w.gray(H),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:w.green(H),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.error(W),J){let V=J.split(`
|
|
10
10
|
`);for(let B of V)if(B.trim()&&!B.includes(G))console.error(this.formatConsoleMessage({timestamp:$,message:w.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!N()){if(console.error(`${Y} ${this.environment}.${Q.toUpperCase()}: ${G}`),J)console.error(J)}if(!this.shouldLog(Q))return;let _=`${Y} ${this.environment}.${Q.toUpperCase()}: ${q}
|
|
11
11
|
`;if(J)_+=`${J}
|
|
12
12
|
`;if(_=_.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(_)}progress(Q,U=""){let X={update:(J,H)=>{},finish:(J)=>{},interrupt:(J,H)=>{}};if(!this.enabled)return X;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:U||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!N()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(J,H)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,J),this.activeProgressBar.total),H!==void 0)this.activeProgressBar.message=H;if(this.shouldStyleConsole()&&!N()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(J)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,J)},interrupt:(J,H="info")=>{if(!N()&&R.stdout.isTTY)R.stdout.write(`
|
|
13
13
|
`);if(this[H==="warning"?"warn":H](J),this.activeProgressBar&&this.shouldStyleConsole()&&!N()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let U=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":w.blue("◐"),tag:X,message:`${w.cyan(Q)}...`}))}return async(X)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-U),Y=`${Q} completed in ${$}ms`,G=new Date,J=this.formatConsoleTimestamp(G),q=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${Y}`;if(X)q+=` ${JSON.stringify(X)}`;if(q+=`
|
|
14
|
-
`,q=q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":w.green("✓"),tag:_,message:`${Y}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!N())console.error(q.trim());if(this.shouldWriteToFile())await this.writeToFile(q)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new hQ(U,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(N())throw Error("createReadStream is not supported in browser environments");if(!wQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return pU(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Z=m.isBuffer(Q)?Q:m.from(Q,"base64"),$=Z.subarray(0,16),Y=Z.subarray(Z.length-16),G=Z.subarray(16,Z.length-16),J=
|
|
14
|
+
`,q=q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":w.green("✓"),tag:_,message:`${Y}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!N())console.error(q.trim());if(this.shouldWriteToFile())await this.writeToFile(q)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new hQ(U,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(N())throw Error("createReadStream is not supported in browser environments");if(!wQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return pU(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Z=m.isBuffer(Q)?Q:m.from(Q,"base64"),$=Z.subarray(0,16),Y=Z.subarray(Z.length-16),G=Z.subarray(16,Z.length-16),J=JZ("aes-256-gcm",X,$);J.setAuthTag(Y);let H=J.update(G),q=J.final(),_=H.length+q.length,A=m.allocUnsafe(_);return H.copy(A,0),q.copy(A,H.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N()}isServerMode(){return!N()}setTestEncryptionKey(Q,U){this.currentKeyId=Q,this.keys.set(Q,U)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let U=new Date,X=this.formatConsoleTimestamp(U),Z=this.formatFileTimestamp(U),{consoleText:$,fileText:Y}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let J=$.split(`
|
|
15
15
|
`),H=Math.max(...J.map((z)=>z.length))+2,q=`┌${"─".repeat(H)}┐`,_=`└${"─".repeat(H)}┘`,A=J.map((z)=>{return this.formatConsoleMessage({timestamp:X,message:w.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:w.cyan(q),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:X,message:w.cyan(_),showTimestamp:!1}))}else if(!N())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Y}`);let G=`${Z} ${this.environment}.INFO: [BOX] ${Y}
|
|
16
16
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(N())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${w.cyan("?")} ${Q} (y/n) `);let X=(Z)=>{let $=Z.toString().trim().toLowerCase();R.stdin.removeListener("data",X);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),U($==="y"||$==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let H=/%([sdijfo%])/g,q=0;if(X=Q.replace(H,(_,A)=>{if(A==="%")return"%";if(q>=U.length)return _;let z=U[q++];switch(A){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return _}}),q<U.length)X+=` ${U.slice(q).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let H=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",q=this.options.showIcons===!1?"":`${w.blue("◐")} `;console.error(`${q}${H} ${w.cyan(Z)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
17
17
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(Q,U=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*X/100),$=Q.barLength-Z,Y=w.green("━".repeat(Z)),G=w.gray("━".repeat($)),J=`[${Y}${G}]`,H=`${X}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=this.options.showIcons===!1?"":U||X===100?w.green("✓"):w.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${J} ${H}${q}`,W=R.stdout.columns||80,V=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${V}`,R.stdout.write(Q.lastRenderedLine),U)R.stdout.write(`
|
|
18
|
-
`)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||N()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(N()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await KQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=ZQ(this.config.logDirectory,Z);if(Q.before)try{if((await XQ(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await jQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}async function KX(Q,U={}){let{maxRetries:X=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:Y}=U,G=Error("Unknown error occurred");for(let J=0;J<=X;J++)try{return await Q()}catch(H){if(G=H instanceof Error?H:Error(String(H)),J===X||!$(G))break;if(Z>0)await new Promise((q)=>setTimeout(q,Z))}if(Y!==void 0)return Y;throw G instanceof Error?G:Error(`Unknown error: ${String(G)}`)}function jX(Q){return Q instanceof v}function
|
|
18
|
+
`)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||N()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(N()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await KQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=ZQ(this.config.logDirectory,Z);if(Q.before)try{if((await XQ(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await jQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}async function KX(Q,U={}){let{maxRetries:X=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:Y}=U,G=Error("Unknown error occurred");for(let J=0;J<=X;J++)try{return await Q()}catch(H){if(G=H instanceof Error?H:Error(String(H)),J===X||!$(G))break;if(Z>0)await new Promise((q)=>setTimeout(q,Z))}if(Y!==void 0)return Y;throw G instanceof Error?G:Error(`Unknown error: ${String(G)}`)}function jX(Q){return Q instanceof v}function PZ(Q){return Q instanceof dQ}function bZ(Q){if(jX(Q))return Q.code==="FILE_SYSTEM_ERROR"||Q.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((X)=>Q.message.toLowerCase().includes(X.toLowerCase()))}class mQ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,U)=>U==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let U=Q.toLowerCase();return["true","1","yes"].includes(U)}},{name:"number",canParse:(Q,U)=>U==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let U=Number(Q);if(Number.isNaN(U))throw TypeError(`Cannot parse "${Q}" as number`);return U}},{name:"array",canParse:(Q,U)=>U==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let U=JSON.parse(Q);if(Array.isArray(U))return U}catch{}return Q.split(",").map((U)=>U.trim())}},{name:"json",canParse:(Q,U)=>U==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(U){throw Error(`Cannot parse "${Q}" as JSON: ${U}`)}}}]}async applyEnvironmentVariables(Q,U,X={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:Y=!0,customParsers:G={},verbose:J=!1,trackPerformance:H=!0}=X,q=async()=>{if(!Q)return{config:U,source:{type:"environment",priority:50,timestamp:new Date}};let _=Z||this.generateEnvPrefix(Q),A={...U};return this.processObject(A,[],_,{useCamelCase:$,useBackwardCompatibility:Y,customParsers:G,verbose:J,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(H)return zQ.track("applyEnvironmentVariables",q,{configName:Q});return q()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,U){if(!U)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,U,X,Z){for(let[$,Y]of Object.entries(Q)){let G=[...U,$],J=G.map((_)=>this.formatEnvKey(_,Z.useCamelCase)),H=`${X}_${J.join("_")}`,q=Z.useBackwardCompatibility?`${X}_${G.map((_)=>_.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,G,X,Z);else{let _=FQ.env[H]||(q?FQ.env[q]:void 0);if(_!==void 0){if(Z.verbose){let A=FQ.env[H]?H:q}try{Q[$]=this.parseEnvironmentValue(_,typeof Y,H,Z.customParsers,Z.configName)}catch(A){if(A instanceof fQ)throw A;throw o.envVar(H,_,typeof Y,Z.configName)}}}}}parseEnvironmentValue(Q,U,X,Z,$){for(let[Y,G]of Object.entries(Z))try{return G(Q)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse(Q,U))try{return Y.parse(Q)}catch{throw o.envVar(X,Q,`${U} (via ${Y.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let U={},X=Q.toUpperCase();for(let[Z,$]of Object.entries(FQ.env))if(Z.startsWith(X)&&$!==void 0)U[Z]=$;return U}validateEnvironmentVariable(Q,U,X){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Z.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(X)try{this.parseEnvironmentValue(Q,U,X,{})}catch($){Z.push(`Cannot parse value "${U}" as ${X}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,U,X={}){let{prefix:Z,format:$="text"}=X,Y=Z||this.generateEnvPrefix(Q),G=[];switch(this.extractEnvVarInfo(U,[],Y,G),$){case"markdown":return this.formatAsMarkdown(G,Q);case"json":return JSON.stringify(G,null,2);default:return this.formatAsText(G,Q)}}extractEnvVarInfo(Q,U,X,Z){for(let[$,Y]of Object.entries(Q)){let G=[...U,$],J=`${X}_${G.map((H)=>this.formatEnvKey(H,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,G,X,Z);else Z.push({key:J,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${G.join(".")}`,example:this.generateExample(Y)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,U){let X=`Environment Variables for ${U}:
|
|
19
19
|
|
|
20
20
|
`;for(let Z of Q)X+=`${Z.key}
|
|
21
21
|
`,X+=` Type: ${Z.type}
|
|
@@ -27,23 +27,23 @@ import{createRequire as fX}from"node:module";var r=fX(import.meta.url);import{ex
|
|
|
27
27
|
`;X+=`| Variable | Type | Description | Example |
|
|
28
28
|
`,X+=`|----------|------|-------------|----------|
|
|
29
29
|
`;for(let Z of Q)X+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
30
|
-
`;return X}}function PZ(Q,U){let X=DX("process");if(typeof X>"u"||!X.env)return U;let Z=X.env[Q];return Z!==void 0?Z:U}function FX(Q,U,X={}){return IX(Q,U,X,new WeakMap)}function IX(Q,U,X,Z){let{arrayMergeMode:$="replace",skipNullish:Y=!1,customMerger:G}=X;if(U===null||U===void 0)return Y?Q:U;if(G){let J=G(Q,U);if(J!==void 0)return J}if(Array.isArray(U)||Array.isArray(Q))return MX(Q,U,$,Z);if(!h(U)||!h(Q))return U;return hZ(Q,U,X,Z)}function MX(Q,U,X,Z){if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(Q)&&!Array.isArray(U))return U;if(Array.isArray(U)&&Array.isArray(Q))switch(X){case"replace":return U;case"concat":return bZ(Q,U);case"smart":return yZ(Q,U,Z);default:return U}return U}function bZ(Q,U){let X=[...U];for(let Z of Q)if(!X.some(($)=>_U($,Z)))X.push(Z);return X}function yZ(Q,U,X){if(U.length===0)return Q;if(Q.length===0)return U;if(h(U[0])&&h(Q[0]))return vZ(Q,U,X);if(U.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...U];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return U}function vZ(Q,U,X){let Z=[...U];for(let $ of Q){if(!h($)){Z.push($);continue}let Y=["id","name","key","path","type"],G=!1;for(let J of Y)if(J in $){if(Z.find((q)=>h(q)&&(J in q)&&q[J]===$[J])){G=!0;break}}if(!G)Z.push($)}return Z}function hZ(Q,U,X,Z){let $=U;if(h($)&&Z.has($))return Z.get($);let Y={...Q};if(h($))Z.set($,Y);for(let G in $){if(!Object.prototype.hasOwnProperty.call($,G))continue;let J=$[G],H=Y[G];if(X.skipNullish&&(J===null||J===void 0))continue;if(J===null||J===void 0){Y[G]=J;continue}if(h(J)&&h(H))Y[G]=IX(H,J,X,Z);else if(Array.isArray(J)||Array.isArray(H))Y[G]=MX(H,J,X.arrayMergeMode||"smart",Z);else Y[G]=J}return Y}function VU(Q,U,X="replace"){return FX(Q,U,{arrayMergeMode:X==="replace"?"replace":"smart",skipNullish:!0})}function _U(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!_U(Q[X],U[X]))return!1;return!0}if(h(Q)&&h(U)){let X=Object.keys(Q),Z=Object.keys(U);if(X.length!==Z.length)return!1;for(let $ of X){if(!Object.prototype.hasOwnProperty.call(U,$))return!1;if(!_U(Q[$],U[$]))return!1}return!0}return!1}function h(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class gQ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,U,X={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:Y,trackPerformance:G=!0,verbose:J=!1}=X;if($){let q=JQ.getWithFileCheck("file",Q);if(q){if(J)console.log(`Configuration loaded from cache: ${Q}`);return q}}let H=async()=>{if(!IQ(Q))return null;try{let q=`?t=${Date.now()}`,_=await import(Q+q),A=_.default||_,z="default"in _,W=Object.keys(_).length>0;if(!z&&!W)throw new AQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new AQ(Q,Error("Configuration must export a valid object"),"unknown");let F={config:VU(U,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)JQ.setWithFileCheck("file",F,Q,Y);return F}catch(q){throw q instanceof Error?o.configLoad(Q,q):o.configLoad(Q,Error(String(q)))}};if(G)return zQ.track("loadFromPath",H,{path:Q});return H()}async tryLoadFromPaths(Q,U,X={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,U,X);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(X.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,U,X){let Z=this.generateNamePatterns(Q,X),$=[];for(let Y of Z)for(let G of this.extensions)$.push(tQ(U,`${Y}${G}`));return $}generateNamePatterns(Q,U){let X=[];if(X.push("config",".config"),Q)X.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(U){if(X.push(U,`.${U}.config`,`${U}.config`,`.${U}`),Q)X.push(`${Q}.${U}.config`,`.${Q}.${U}.config`)}return X.filter(Boolean)}checkFileAccess(Q){return KX(async()=>{return IQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,U,X){let Z=[];if(!IQ(Q))return Z;if(U||X){let $=this.generateNamePatterns(U||"",X);for(let Y of $)for(let G of this.extensions){let J=tQ(Q,`${Y}${G}`);if(await this.checkFileAccess(J))Z.push(J)}}else try{let{readdirSync:$}=await import("fs"),Y=$(Q);for(let G of Y)if(this.looksLikeConfigFile(G)){let J=tQ(Q,G);if(await this.checkFileAccess(J))Z.push(J)}}catch{return[]}return Z}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((X)=>X.test(Q))}async validateConfigFile(Q){let U=[];try{if(!IQ(Q))return U.push("Configuration file does not exist"),U;let X=await import(Q),Z=X.default||X;if(Z===void 0)U.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)U.push("Configuration must be an object");else if(Array.isArray(Z))U.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),Y=$(Q,"utf8");JSON.parse(Y)}catch($){U.push(`Invalid JSON syntax: ${$}`)}}catch(X){U.push(`Failed to load configuration file: ${X}`)}return U}async getFileModificationTime(Q){try{let{statSync:U}=await import("fs");return U(Q).mtime}catch{return null}}async preloadConfigurations(Q,U={}){let X=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},U);if($)X.set(Z,$.config)}catch($){if(U.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),X}}class DU{async validateConfiguration(Q,U,X={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:Y=!0,customRules:G=[],trackPerformance:J=!0,verbose:H=!1}=X,q=async()=>{let _=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:Y,customRules:G,trackPerformance:J,verbose:H};try{if(typeof U==="string")return await this.validateWithSchemaFile(Q,U,z);else if(Array.isArray(U))return this.validateWithRules(Q,[...U,...G],z);else return this.validateWithJSONSchema(Q,U,z)}catch(W){return _.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:_,warnings:A}}};if(J)return await zQ.track("validateConfiguration",q);return q()}async validateWithSchemaFile(Q,U,X){try{if(!BZ(U))throw new WQ(U,[{path:"",message:"Schema file does not exist"}]);let Z=await import(U),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,X);else return this.validateWithJSONSchema(Q,$,X)}catch(Z){throw new WQ(U,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,U,X){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,U,"",Z,$,X),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,U,X,Z,$,Y){if(Y.validateTypes&&U.type){let G=Array.isArray(Q)?"array":typeof Q,J=Array.isArray(U.type)?U.type:[U.type];if(!J.includes(G)){if(Z.push({path:X,message:`Expected type ${J.join(" or ")}, got ${G}`,expected:J.join(" or "),actual:G,rule:"type"}),Y.stopOnFirstError)return}}if(U.enum&&!U.enum.includes(Q)){if(Z.push({path:X,message:`Value must be one of: ${U.enum.join(", ")}`,expected:U.enum.join(", "),actual:Q,rule:"enum"}),Y.stopOnFirstError)return}if(typeof Q==="string"){if(U.minLength!==void 0&&Q.length<U.minLength)Z.push({path:X,message:`String length must be at least ${U.minLength}`,expected:`>= ${U.minLength}`,actual:Q.length,rule:"minLength"});if(U.maxLength!==void 0&&Q.length>U.maxLength)Z.push({path:X,message:`String length must not exceed ${U.maxLength}`,expected:`<= ${U.maxLength}`,actual:Q.length,rule:"maxLength"});if(U.pattern){if(!new RegExp(U.pattern).test(Q))Z.push({path:X,message:`String does not match pattern ${U.pattern}`,expected:U.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(U.minimum!==void 0&&Q<U.minimum)Z.push({path:X,message:`Value must be at least ${U.minimum}`,expected:`>= ${U.minimum}`,actual:Q,rule:"minimum"});if(U.maximum!==void 0&&Q>U.maximum)Z.push({path:X,message:`Value must not exceed ${U.maximum}`,expected:`<= ${U.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&U.items)for(let G=0;G<Q.length;G++){let J=X?`${X}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema(Q[G],U.items,J,Z,$,Y),Y.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let G=Q;if(Y.validateRequired&&U.required){for(let J of U.required)if(!(J in G)){if(Z.push({path:X?`${X}.${J}`:J,message:`Missing required property '${J}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(U.properties){for(let[J,H]of Object.entries(U.properties))if(J in G){let q=X?`${X}.${J}`:J;if(this.validateObjectAgainstSchema(G[J],H,q,Z,$,Y),Y.stopOnFirstError&&Z.length>0)return}}if(U.additionalProperties===!1){let J=new Set(Object.keys(U.properties||{}));for(let H of Object.keys(G))if(!J.has(H))$.push({path:X?`${X}.${H}`:H,message:`Additional property '${H}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,U,X){let Z=[],$=[];for(let Y of U)try{let G=this.getValueByPath(Q,Y.path),J=this.validateWithRule(G,Y,Y.path);if(Z.push(...J),X.stopOnFirstError&&Z.length>0)break}catch(G){Z.push({path:Y.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,U,X){let Z=[];if(U.required&&(Q===void 0||Q===null))return Z.push({path:X,message:U.message||`Property '${X}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(U.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==U.type)Z.push({path:X,message:U.message||`Expected type ${U.type}, got ${$}`,expected:U.type,actual:$,rule:"type"})}if(U.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<U.min)Z.push({path:X,message:U.message||`Value must be at least ${U.min}`,expected:`>= ${U.min}`,actual:$,rule:"min"})}if(U.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>U.max)Z.push({path:X,message:U.message||`Value must not exceed ${U.max}`,expected:`<= ${U.max}`,actual:$,rule:"max"})}if(U.pattern&&typeof Q==="string"){if(!U.pattern.test(Q))Z.push({path:X,message:U.message||`Value does not match pattern ${U.pattern}`,expected:U.pattern.toString(),actual:Q,rule:"pattern"})}if(U.enum&&!U.enum.includes(Q))Z.push({path:X,message:U.message||`Value must be one of: ${U.enum.join(", ")}`,expected:U.enum.join(", "),actual:Q,rule:"enum"});if(U.validator){let $=U.validator(Q);if($)Z.push({path:X,message:U.message||$,rule:"custom"})}return Z}getValueByPath(Q,U){if(!U)return Q;let X=U.split("."),Z=Q;for(let $ of X)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let U=[],X=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of X){let[,$,Y,G]=Z;U.push({path:$,required:!Y,type:this.mapTypeScriptType(G)})}return U}mapTypeScriptType(Q){switch(Q.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:SX},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class NU{fileLoader=new gQ;envProcessor=new mQ;validator=new DU;async loadConfig(Q){let U=Date.now(),{cache:X,performance:Z,schema:$,validate:Y,...G}=Q;try{if(X?.enabled){let H=this.checkCache(G.name||"",G);if(H)return H}let J;try{J=await this.loadConfigurationStrategies(G,!0,X)}catch(H){let q=G.__strictErrorHandling;if(H instanceof Error&&H.name==="ConfigNotFoundError"){if(q)throw H;J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`No configuration file found for "${G.name||"config"}", using defaults with environment variables`]}}else if(H instanceof Error&&H.name==="ConfigLoadError"){let _=H.message.includes("EACCES")||H.message.includes("EPERM")||H.message.includes("permission denied"),A=!_&&(H.message.includes("syntax")||H.message.includes("Expected")||H.message.includes("Unexpected")||H.message.includes("BuildMessage")||H.message.includes("errors building")),z=H.message.includes("Configuration must export a valid object")||H.message.includes("Configuration file is empty and exports nothing");if(q&&(z||_))throw H;if(A&&(!q||!z))J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!q)J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${H.message}`]};else throw H}else J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${H instanceof Error?H.message:String(H)}`]}}if($||Y)await this.validateConfiguration(J.config,$,Y,G.name);if(X?.enabled&&J)this.cacheResult(G.name||"",J,X,G);if(Z?.enabled){let H={operation:"loadConfig",duration:Date.now()-U,configName:G.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(H);if(Z.slowThreshold&&H.duration>Z.slowThreshold)f.warn(`Slow configuration loading detected: ${H.duration}ms for ${G.name}`);J.metrics=H}return J}catch(J){let H=Date.now()-U;throw f.error(`Configuration loading failed after ${H}ms:`,[J instanceof Error?J:Error(String(J))]),J}}async loadConfigurationStrategies(Q,U=!1,X){let{name:Z="",alias:$,cwd:Y,configDir:G,defaultConfig:J,checkEnv:H=!0,arrayStrategy:q="replace",verbose:_=!1}=Q,A=Y||a.cwd(),z=[],W=await this.loadLocalConfiguration(Z,$,A,G,J,q,_,H,X);if(W)return z.push(...this.getLocalSearchPaths(Z,$,A,G)),this.finalizeResult(W,z,H,Z,_);let V=await this.loadHomeConfiguration(Z,$,J,q,_,H);if(V)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(V,z,H,Z,_);let B=await this.loadPackageJsonConfiguration(Z,$,A,J,q,_,H);if(B)return z.push(y(A,"package.json")),this.finalizeResult(B,z,H,Z,_);if(z.push(...this.getAllSearchPaths(Z,$,A,G)),U)throw o.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,J,H,_),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,U,X,Z,$,Y,G,J,H){let q=J?qQ(Q,$,G):$,_=this.getLocalDirectories(X,Z);for(let A of _){if(G)f.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,U),W=await this.fileLoader.tryLoadFromPaths(z,q,{arrayStrategy:Y,verbose:G,cacheTtl:H?.ttl,useCache:!H?.ttl||H.ttl>100});if(W){if(G)f.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,U,X,Z,$,Y){if(!Q)return null;let G=Y?qQ(Q,X,$):X,J=[y(t(),".config",Q),y(t(),".config"),t()];for(let H of J){if($)f.info(`Checking home directory: ${H}`);let q=this.fileLoader.generateConfigPaths(Q,H,U),_=await this.fileLoader.tryLoadFromPaths(q,G,{arrayStrategy:Z,verbose:$});if(_){if($)f.success(`Configuration loaded from home directory: ${_.source.path}`);return _}}return null}async loadPackageJsonConfiguration(Q,U,X,Z,$,Y,G){let J=G?qQ(Q,Z,Y):Z;try{let H=y(X,"package.json");if(!JU(H))return null;let q=await import(H),_=q[Q],A=Q;if(!_&&U)_=q[U],A=U;if(_&&typeof _==="object"&&!Array.isArray(_)){if(Y)f.success(`Configuration loaded from package.json: ${A}`);return{config:VU(J,_,$),source:{type:"package.json",path:H,priority:30,timestamp:new Date}}}}catch(H){if(Y)f.warn("Failed to load package.json:",[H instanceof Error?H:Error(String(H))])}return null}async applyEnvironmentVariables(Q,U,X,Z){if(!X||!Q||typeof U!=="object"||U===null||Array.isArray(U))return{config:U,source:{type:"default",priority:10,timestamp:new Date}};return{config:qQ(Q,U,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,U,X,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,U,X,Z){let $=[];if(X){let Y=X(Q);if(Y)$.push(...Y)}if(U){let Y=await this.validator.validateConfiguration(Q,U);if(!Y.isValid)$.push(...Y.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if($.length>0)throw o.configValidation(Z||"unknown",$,Z)}checkCache(Q,U){let X=this.generateCacheKey(Q,U);return JQ.get(X)||null}cacheResult(Q,U,X,Z){let $=this.generateCacheKey(Q,Z);JQ.set($,U,void 0,X.ttl)}generateCacheKey(Q,U){let X=[Q];if(U.alias)X.push(`alias:${U.alias}`);if(U.cwd)X.push(`cwd:${U.cwd}`);if(U.configDir)X.push(`configDir:${U.configDir}`);if("checkEnv"in U)X.push(`checkEnv:${U.checkEnv}`);return X.join("|")}getLocalDirectories(Q,U){return Array.from(new Set([Q,y(Q,"config"),y(Q,".config"),U?y(Q,U):void 0].filter(Boolean)))}getAllSearchPaths(Q,U,X,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,U,X,Z)),$.push(...this.getHomeSearchPaths(Q,U)),$.push(y(X,"package.json")),$}getLocalSearchPaths(Q,U,X,Z){let $=this.getLocalDirectories(X,Z),Y=[];for(let G of $)Y.push(...this.fileLoader.generateConfigPaths(Q,G,U));return Y}getHomeSearchPaths(Q,U){if(!Q)return[];let X=[y(t(),".config",Q),y(t(),".config"),t()],Z=[];for(let $ of X)Z.push(...this.fileLoader.generateConfigPaths(Q,$,U));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function iU(Q){let X=!(Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"))&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")),Z=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");return X||Z}async function dZ(Q){return i.loadConfig({...Q,__strictErrorHandling:!0})}async function VX(Q){let U="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},X="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(X)Z=await i.loadConfig(Q);else Z=await i.loadConfig({...Q,defaultConfig:U,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??U}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",Y=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||Y.includes("config"))&&Q.verbose)f.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let J=X?{...Q,defaultConfig:U}:{...Q,defaultConfig:U,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await i.applyEnvironmentVariables(J.name||"",U,!0,J.verbose||!1))?.config??U;return U}}async function fZ(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:U}=await import("process");try{return(await i.loadConfig({name:Q,cwd:U(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&iU(X)))return(await i.applyEnvironmentVariables(Q,{},!0,!1)).config;throw X}}try{return(await i.loadConfig({...Q,cwd:Q.cwd||a.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(U){if(U instanceof Error&&(U.name==="ConfigNotFoundError"||U.name==="ConfigLoadError"&&iU(U)))return(await i.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw U}}async function pZ(Q,U,X="replace"){let Z=new gQ;try{let $=await Z.loadFromPath(Q,U,{arrayStrategy:X,useCache:!1,trackPerformance:!1});return $?$.config:null}catch{return null}}function qQ(Q,U,X=!1){let Z=new mQ,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(G,J=[]){let H={...G};for(let[q,_]of Object.entries(G)){let A=[...J,q],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,V;for(let B of z)if(W=a.env[B],W!==void 0){V=B;break}if(W!==void 0&&V)if(typeof _==="boolean")H[q]=["true","1","yes"].includes(W.toLowerCase());else if(typeof _==="number"){let B=Number(W);if(!Number.isNaN(B))H[q]=B}else if(Array.isArray(_))try{H[q]=JSON.parse(W)}catch{H[q]=W.split(",").map((B)=>B.trim())}else H[q]=W;else if(_&&typeof _==="object"&&!Array.isArray(_))H[q]=Y(_,A)}return H}return Y(U)}function uZ(Q){let U=y(a.cwd(),Q.configDir),X=y(a.cwd(),Q.generatedDir),Z=y(X,"config-types.ts");if(!JU(kU(Z)))lX(kU(Z),{recursive:!0,mode:511});let $=JU(U)?nX(U).map((G)=>G.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${L0}
|
|
30
|
+
`;return X}}function yZ(Q,U){let X=DX("process");if(typeof X>"u"||!X.env)return U;let Z=X.env[Q];return Z!==void 0?Z:U}function FX(Q,U,X={}){return IX(Q,U,X,new WeakMap)}function IX(Q,U,X,Z){let{arrayMergeMode:$="replace",skipNullish:Y=!1,customMerger:G}=X;if(U===null||U===void 0)return Y?Q:U;if(G){let J=G(Q,U);if(J!==void 0)return J}if(Array.isArray(U)||Array.isArray(Q))return MX(Q,U,$,Z);if(!h(U)||!h(Q))return U;return fZ(Q,U,X,Z)}function MX(Q,U,X,Z){if(Array.isArray(U)&&!Array.isArray(Q))return U;if(Array.isArray(Q)&&!Array.isArray(U))return U;if(Array.isArray(U)&&Array.isArray(Q))switch(X){case"replace":return U;case"concat":return vZ(Q,U);case"smart":return hZ(Q,U,Z);default:return U}return U}function vZ(Q,U){let X=[...U];for(let Z of Q)if(!X.some(($)=>AU($,Z)))X.push(Z);return X}function hZ(Q,U,X){if(U.length===0)return Q;if(Q.length===0)return U;if(h(U[0])&&h(Q[0]))return dZ(Q,U,X);if(U.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...U];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return U}function dZ(Q,U,X){let Z=[...U];for(let $ of Q){if(!h($)){Z.push($);continue}let Y=["id","name","key","path","type"],G=!1;for(let J of Y)if(J in $){if(Z.find((q)=>h(q)&&(J in q)&&q[J]===$[J])){G=!0;break}}if(!G)Z.push($)}return Z}function fZ(Q,U,X,Z){let $=U;if(h($)&&Z.has($))return Z.get($);let Y={...Q};if(h($))Z.set($,Y);for(let G in $){if(!Object.prototype.hasOwnProperty.call($,G))continue;let J=$[G],H=Y[G];if(X.skipNullish&&(J===null||J===void 0))continue;if(J===null||J===void 0){Y[G]=J;continue}if(h(J)&&h(H))Y[G]=IX(H,J,X,Z);else if(Array.isArray(J)||Array.isArray(H))Y[G]=MX(H,J,X.arrayMergeMode||"smart",Z);else Y[G]=J}return Y}function DU(Q,U,X="replace"){return FX(Q,U,{arrayMergeMode:X==="replace"?"replace":"smart",skipNullish:!0})}function AU(Q,U){if(Q===U)return!0;if(Array.isArray(Q)&&Array.isArray(U)){if(Q.length!==U.length)return!1;for(let X=0;X<Q.length;X++)if(!AU(Q[X],U[X]))return!1;return!0}if(h(Q)&&h(U)){let X=Object.keys(Q),Z=Object.keys(U);if(X.length!==Z.length)return!1;for(let $ of X){if(!Object.prototype.hasOwnProperty.call(U,$))return!1;if(!AU(Q[$],U[$]))return!1}return!0}return!1}function h(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class gQ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,U,X={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:Y,trackPerformance:G=!0,verbose:J=!1}=X;if($){let q=JQ.getWithFileCheck("file",Q);if(q){if(J)console.log(`Configuration loaded from cache: ${Q}`);return q}}let H=async()=>{if(!IQ(Q))return null;try{let q=`?t=${Date.now()}`,_=await import(Q+q),A=_.default||_,z="default"in _,W=Object.keys(_).length>0;if(!z&&!W)throw new AQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new AQ(Q,Error("Configuration must export a valid object"),"unknown");let F={config:DU(U,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)JQ.setWithFileCheck("file",F,Q,Y);return F}catch(q){throw q instanceof Error?o.configLoad(Q,q):o.configLoad(Q,Error(String(q)))}};if(G)return zQ.track("loadFromPath",H,{path:Q});return H()}async tryLoadFromPaths(Q,U,X={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,U,X);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(X.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,U,X){let Z=this.generateNamePatterns(Q,X),$=[];for(let Y of Z)for(let G of this.extensions)$.push(eQ(U,`${Y}${G}`));return $}generateNamePatterns(Q,U){let X=[];if(X.push("config",".config"),Q)X.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(U){if(X.push(U,`.${U}.config`,`${U}.config`,`.${U}`),Q)X.push(`${Q}.${U}.config`,`.${Q}.${U}.config`)}return X.filter(Boolean)}checkFileAccess(Q){return KX(async()=>{return IQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,U,X){let Z=[];if(!IQ(Q))return Z;if(U||X){let $=this.generateNamePatterns(U||"",X);for(let Y of $)for(let G of this.extensions){let J=eQ(Q,`${Y}${G}`);if(await this.checkFileAccess(J))Z.push(J)}}else try{let{readdirSync:$}=await import("fs"),Y=$(Q);for(let G of Y)if(this.looksLikeConfigFile(G)){let J=eQ(Q,G);if(await this.checkFileAccess(J))Z.push(J)}}catch{return[]}return Z}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((X)=>X.test(Q))}async validateConfigFile(Q){let U=[];try{if(!IQ(Q))return U.push("Configuration file does not exist"),U;let X=await import(Q),Z=X.default||X;if(Z===void 0)U.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)U.push("Configuration must be an object");else if(Array.isArray(Z))U.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),Y=$(Q,"utf8");JSON.parse(Y)}catch($){U.push(`Invalid JSON syntax: ${$}`)}}catch(X){U.push(`Failed to load configuration file: ${X}`)}return U}async getFileModificationTime(Q){try{let{statSync:U}=await import("fs");return U(Q).mtime}catch{return null}}async preloadConfigurations(Q,U={}){let X=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},U);if($)X.set(Z,$.config)}catch($){if(U.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),X}}class NU{async validateConfiguration(Q,U,X={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:Y=!0,customRules:G=[],trackPerformance:J=!0,verbose:H=!1}=X,q=async()=>{let _=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:Y,customRules:G,trackPerformance:J,verbose:H};try{if(typeof U==="string")return await this.validateWithSchemaFile(Q,U,z);else if(Array.isArray(U))return this.validateWithRules(Q,[...U,...G],z);else return this.validateWithJSONSchema(Q,U,z)}catch(W){return _.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:_,warnings:A}}};if(J)return await zQ.track("validateConfiguration",q);return q()}async validateWithSchemaFile(Q,U,X){try{if(!LZ(U))throw new WQ(U,[{path:"",message:"Schema file does not exist"}]);let Z=await import(U),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,X);else return this.validateWithJSONSchema(Q,$,X)}catch(Z){throw new WQ(U,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,U,X){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,U,"",Z,$,X),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,U,X,Z,$,Y){if(Y.validateTypes&&U.type){let G=Array.isArray(Q)?"array":typeof Q,J=Array.isArray(U.type)?U.type:[U.type];if(!J.includes(G)){if(Z.push({path:X,message:`Expected type ${J.join(" or ")}, got ${G}`,expected:J.join(" or "),actual:G,rule:"type"}),Y.stopOnFirstError)return}}if(U.enum&&!U.enum.includes(Q)){if(Z.push({path:X,message:`Value must be one of: ${U.enum.join(", ")}`,expected:U.enum.join(", "),actual:Q,rule:"enum"}),Y.stopOnFirstError)return}if(typeof Q==="string"){if(U.minLength!==void 0&&Q.length<U.minLength)Z.push({path:X,message:`String length must be at least ${U.minLength}`,expected:`>= ${U.minLength}`,actual:Q.length,rule:"minLength"});if(U.maxLength!==void 0&&Q.length>U.maxLength)Z.push({path:X,message:`String length must not exceed ${U.maxLength}`,expected:`<= ${U.maxLength}`,actual:Q.length,rule:"maxLength"});if(U.pattern){if(!new RegExp(U.pattern).test(Q))Z.push({path:X,message:`String does not match pattern ${U.pattern}`,expected:U.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(U.minimum!==void 0&&Q<U.minimum)Z.push({path:X,message:`Value must be at least ${U.minimum}`,expected:`>= ${U.minimum}`,actual:Q,rule:"minimum"});if(U.maximum!==void 0&&Q>U.maximum)Z.push({path:X,message:`Value must not exceed ${U.maximum}`,expected:`<= ${U.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&U.items)for(let G=0;G<Q.length;G++){let J=X?`${X}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema(Q[G],U.items,J,Z,$,Y),Y.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let G=Q;if(Y.validateRequired&&U.required){for(let J of U.required)if(!(J in G)){if(Z.push({path:X?`${X}.${J}`:J,message:`Missing required property '${J}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(U.properties){for(let[J,H]of Object.entries(U.properties))if(J in G){let q=X?`${X}.${J}`:J;if(this.validateObjectAgainstSchema(G[J],H,q,Z,$,Y),Y.stopOnFirstError&&Z.length>0)return}}if(U.additionalProperties===!1){let J=new Set(Object.keys(U.properties||{}));for(let H of Object.keys(G))if(!J.has(H))$.push({path:X?`${X}.${H}`:H,message:`Additional property '${H}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,U,X){let Z=[],$=[];for(let Y of U)try{let G=this.getValueByPath(Q,Y.path),J=this.validateWithRule(G,Y,Y.path);if(Z.push(...J),X.stopOnFirstError&&Z.length>0)break}catch(G){Z.push({path:Y.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,U,X){let Z=[];if(U.required&&(Q===void 0||Q===null))return Z.push({path:X,message:U.message||`Property '${X}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(U.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==U.type)Z.push({path:X,message:U.message||`Expected type ${U.type}, got ${$}`,expected:U.type,actual:$,rule:"type"})}if(U.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<U.min)Z.push({path:X,message:U.message||`Value must be at least ${U.min}`,expected:`>= ${U.min}`,actual:$,rule:"min"})}if(U.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>U.max)Z.push({path:X,message:U.message||`Value must not exceed ${U.max}`,expected:`<= ${U.max}`,actual:$,rule:"max"})}if(U.pattern&&typeof Q==="string"){if(!U.pattern.test(Q))Z.push({path:X,message:U.message||`Value does not match pattern ${U.pattern}`,expected:U.pattern.toString(),actual:Q,rule:"pattern"})}if(U.enum&&!U.enum.includes(Q))Z.push({path:X,message:U.message||`Value must be one of: ${U.enum.join(", ")}`,expected:U.enum.join(", "),actual:Q,rule:"enum"});if(U.validator){let $=U.validator(Q);if($)Z.push({path:X,message:U.message||$,rule:"custom"})}return Z}getValueByPath(Q,U){if(!U)return Q;let X=U.split("."),Z=Q;for(let $ of X)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let U=[],X=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of X){let[,$,Y,G]=Z;U.push({path:$,required:!Y,type:this.mapTypeScriptType(G)})}return U}mapTypeScriptType(Q){switch(Q.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:SX},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class EU{fileLoader=new gQ;envProcessor=new mQ;validator=new NU;async loadConfig(Q){let U=Date.now(),{cache:X,performance:Z,schema:$,validate:Y,...G}=Q;try{if(X?.enabled){let H=this.checkCache(G.name||"",G);if(H)return H}let J;try{J=await this.loadConfigurationStrategies(G,!0,X)}catch(H){let q=G.__strictErrorHandling;if(H instanceof Error&&H.name==="ConfigNotFoundError"){if(q)throw H;J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`No configuration file found for "${G.name||"config"}", using defaults with environment variables`]}}else if(H instanceof Error&&H.name==="ConfigLoadError"){let _=H.message.includes("EACCES")||H.message.includes("EPERM")||H.message.includes("permission denied"),A=!_&&(H.message.includes("syntax")||H.message.includes("Expected")||H.message.includes("Unexpected")||H.message.includes("BuildMessage")||H.message.includes("errors building")),z=H.message.includes("Configuration must export a valid object")||H.message.includes("Configuration file is empty and exports nothing");if(q&&(z||_))throw H;if(A&&(!q||!z))J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!q)J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${H.message}`]};else throw H}else J={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${H instanceof Error?H.message:String(H)}`]}}if($||Y)await this.validateConfiguration(J.config,$,Y,G.name);if(X?.enabled&&J)this.cacheResult(G.name||"",J,X,G);if(Z?.enabled){let H={operation:"loadConfig",duration:Date.now()-U,configName:G.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(H);if(Z.slowThreshold&&H.duration>Z.slowThreshold)f.warn(`Slow configuration loading detected: ${H.duration}ms for ${G.name}`);J.metrics=H}return J}catch(J){let H=Date.now()-U;throw f.error(`Configuration loading failed after ${H}ms:`,[J instanceof Error?J:Error(String(J))]),J}}async loadConfigurationStrategies(Q,U=!1,X){let{name:Z="",alias:$,cwd:Y,configDir:G,defaultConfig:J,checkEnv:H=!0,arrayStrategy:q="replace",verbose:_=!1}=Q,A=Y||a.cwd(),z=[],W=await this.loadLocalConfiguration(Z,$,A,G,J,q,_,H,X);if(W)return z.push(...this.getLocalSearchPaths(Z,$,A,G)),this.finalizeResult(W,z,H,Z,_);let V=await this.loadHomeConfiguration(Z,$,J,q,_,H);if(V)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(V,z,H,Z,_);let B=await this.loadPackageJsonConfiguration(Z,$,A,J,q,_,H);if(B)return z.push(y(A,"package.json")),this.finalizeResult(B,z,H,Z,_);if(z.push(...this.getAllSearchPaths(Z,$,A,G)),U)throw o.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,J,H,_),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,U,X,Z,$,Y,G,J,H){let q=J?qQ(Q,$,G):$,_=this.getLocalDirectories(X,Z);for(let A of _){if(G)f.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,U),W=await this.fileLoader.tryLoadFromPaths(z,q,{arrayStrategy:Y,verbose:G,cacheTtl:H?.ttl,useCache:!H?.ttl||H.ttl>100});if(W){if(G)f.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,U,X,Z,$,Y){if(!Q)return null;let G=Y?qQ(Q,X,$):X,J=[y(t(),".config",Q),y(t(),".config"),t()];for(let H of J){if($)f.info(`Checking home directory: ${H}`);let q=this.fileLoader.generateConfigPaths(Q,H,U),_=await this.fileLoader.tryLoadFromPaths(q,G,{arrayStrategy:Z,verbose:$});if(_){if($)f.success(`Configuration loaded from home directory: ${_.source.path}`);return _}}return null}async loadPackageJsonConfiguration(Q,U,X,Z,$,Y,G){let J=G?qQ(Q,Z,Y):Z;try{let H=y(X,"package.json");if(!qU(H))return null;let q=await import(H),_=q[Q],A=Q;if(!_&&U)_=q[U],A=U;if(_&&typeof _==="object"&&!Array.isArray(_)){if(Y)f.success(`Configuration loaded from package.json: ${A}`);return{config:DU(J,_,$),source:{type:"package.json",path:H,priority:30,timestamp:new Date}}}}catch(H){if(Y)f.warn("Failed to load package.json:",[H instanceof Error?H:Error(String(H))])}return null}async applyEnvironmentVariables(Q,U,X,Z){if(!X||!Q||typeof U!=="object"||U===null||Array.isArray(U))return{config:U,source:{type:"default",priority:10,timestamp:new Date}};return{config:qQ(Q,U,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,U,X,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,U,X,Z){let $=[];if(X){let Y=X(Q);if(Y)$.push(...Y)}if(U){let Y=await this.validator.validateConfiguration(Q,U);if(!Y.isValid)$.push(...Y.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if($.length>0)throw o.configValidation(Z||"unknown",$,Z)}checkCache(Q,U){let X=this.generateCacheKey(Q,U);return JQ.get(X)||null}cacheResult(Q,U,X,Z){let $=this.generateCacheKey(Q,Z);JQ.set($,U,void 0,X.ttl)}generateCacheKey(Q,U){let X=[Q];if(U.alias)X.push(`alias:${U.alias}`);if(U.cwd)X.push(`cwd:${U.cwd}`);if(U.configDir)X.push(`configDir:${U.configDir}`);if("checkEnv"in U)X.push(`checkEnv:${U.checkEnv}`);return X.join("|")}getLocalDirectories(Q,U){return Array.from(new Set([Q,y(Q,"config"),y(Q,".config"),U?y(Q,U):void 0].filter(Boolean)))}getAllSearchPaths(Q,U,X,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,U,X,Z)),$.push(...this.getHomeSearchPaths(Q,U)),$.push(y(X,"package.json")),$}getLocalSearchPaths(Q,U,X,Z){let $=this.getLocalDirectories(X,Z),Y=[];for(let G of $)Y.push(...this.fileLoader.generateConfigPaths(Q,G,U));return Y}getHomeSearchPaths(Q,U){if(!Q)return[];let X=[y(t(),".config",Q),y(t(),".config"),t()],Z=[];for(let $ of X)Z.push(...this.fileLoader.generateConfigPaths(Q,$,U));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function iU(Q){let X=!(Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"))&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")),Z=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");return X||Z}async function pZ(Q){return i.loadConfig({...Q,__strictErrorHandling:!0})}async function VX(Q){let U="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},X="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(X)Z=await i.loadConfig(Q);else Z=await i.loadConfig({...Q,defaultConfig:U,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??U}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",Y=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||Y.includes("config"))&&Q.verbose)f.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let J=X?{...Q,defaultConfig:U}:{...Q,defaultConfig:U,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await i.applyEnvironmentVariables(J.name||"",U,!0,J.verbose||!1))?.config??U;return U}}async function uZ(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:U}=await import("process");try{return(await i.loadConfig({name:Q,cwd:U(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&iU(X)))return(await i.applyEnvironmentVariables(Q,{},!0,!1)).config;throw X}}try{return(await i.loadConfig({...Q,cwd:Q.cwd||a.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(U){if(U instanceof Error&&(U.name==="ConfigNotFoundError"||U.name==="ConfigLoadError"&&iU(U)))return(await i.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw U}}async function mZ(Q,U,X="replace"){let Z=new gQ;try{let $=await Z.loadFromPath(Q,U,{arrayStrategy:X,useCache:!1,trackPerformance:!1});return $?$.config:null}catch{return null}}function qQ(Q,U,X=!1){let Z=new mQ,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(G,J=[]){let H={...G};for(let[q,_]of Object.entries(G)){let A=[...J,q],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,V;for(let B of z)if(W=a.env[B],W!==void 0){V=B;break}if(W!==void 0&&V)if(typeof _==="boolean")H[q]=["true","1","yes"].includes(W.toLowerCase());else if(typeof _==="number"){let B=Number(W);if(!Number.isNaN(B))H[q]=B}else if(Array.isArray(_))try{H[q]=JSON.parse(W)}catch{H[q]=W.split(",").map((B)=>B.trim())}else H[q]=W;else if(_&&typeof _==="object"&&!Array.isArray(_))H[q]=Y(_,A)}return H}return Y(U)}function gZ(Q){let U=y(a.cwd(),Q.configDir),X=y(a.cwd(),Q.generatedDir),Z=y(X,"config-types.ts");if(!qU(kU(Z)))iX(kU(Z),{recursive:!0,mode:511});let $=qU(U)?sX(U).map((G)=>G.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${K0}
|
|
31
31
|
export type ConfigNames = ${$.length?`'${$.join("' | '")}'`:"string"}
|
|
32
|
-
`;
|
|
32
|
+
`;oX(Z,Y,{mode:438})}function cZ(Q){let U=null,X=null,Z=()=>{if(!X)X=VX(Q).then((Y)=>{return U=Y,Y},(Y)=>{let G="defaultConfig"in Q?Q.defaultConfig:{};if(U=G,"verbose"in Q&&Q.verbose)f.warn("Config loading failed, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);return G});return X},$="defaultConfig"in Q?Q.defaultConfig:{};return U=$,Z(),new Proxy({},{get(Y,G){if(U)return U[G];let J=$[G];return Z(),J},has(Y,G){return G in(U||$)},ownKeys(){return Object.keys(U||$)},getOwnPropertyDescriptor(Y,G){return Object.getOwnPropertyDescriptor(U||$,G)},set(Y,G,J){if(!U)U={...$};return U[G]=J,!0}})}function lZ(Q){let U=nU(jZ.cwd(),Q?.configDir||"./config");function X(){if(!wZ(U))return[];let $=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),Y=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],G=KZ(U).filter((H)=>$.has(QU(H))).map((H)=>({base:H.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:H})),J=new Map;for(let{base:H,file:q}of G){let _=QU(q).toLowerCase(),A=J.get(H);if(!A){J.set(H,q);continue}let z=QU(A).toLowerCase();if(Y.indexOf(_)<Y.indexOf(z))J.set(H,q)}return Array.from(J.entries()).map(([H,q])=>({base:H,file:q})).sort((H,q)=>H.base.localeCompare(q.base))}function Z(){let $=X(),Y=$.map((q)=>q.base),G=Y.length?Y.map((q)=>`'${q}'`).join(" | "):"string",J=$.length?`{
|
|
33
33
|
${$.map((q)=>{let _=nU(U,q.file).replace(/\\/g,"/");return` '${q.base}': typeof import('${_}').default`}).join(`,
|
|
34
34
|
`)}
|
|
35
35
|
}`:"Record<string, any>";return`export type ConfigNames = ${G}
|
|
36
36
|
export type ConfigByName = ${J}
|
|
37
37
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
38
38
|
export type ConfigOf = Config
|
|
39
|
-
`}return{name:"bunfig-plugin",setup($){$.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),$.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var DX,JQ,zQ,NX,cZ,lZ,sU,OQ,AU,C,I,nZ,oU,iZ,rU,sZ,oZ,QU,rZ,aU,tU,UU,aZ,tZ,eZ,Q0,TQ,EX,U0,k,X0,Z0,eU,SQ,WU,E,w,$0,QX,Y0,UX,G0,H0,XU,J0,XX,ZX,q0,ZU,_0,A0,W0,z0,B0,CQ,OX,R0,L0="0.15.6",v,dQ,AQ,zU,BU,fQ,RU,LU,WQ,wU,KU,o,TX,SX,f,i,CX,kX,w0=cX(async()=>{DX=import.meta.require,JQ=new jU,zQ=new FU,NX={createKey:KZ,isEquivalent:jZ,estimateMemoryUsage:FZ},cZ=PQ(qU.cwd(),"config"),lZ=PQ(qU.cwd(),"src/generated"),sU=xQ.env.CLARITY_LOG_DIR||rX(VZ(),"logs"),OQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:sU,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},AU=await DZ(),C={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},I=C,nZ=C.red,oU=C.green,iZ=C.yellow,rU=C.blue,sZ=C.magenta,oZ=C.cyan,QU=C.white,rZ=C.gray,aU=C.bgRed,tU=C.bgYellow,UU=C.bold,aZ=C.dim,tZ=C.italic,eZ=C.underline,Q0=C.reset,TQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EX={debug:"\uD83D\uDD0D",info:rU("ℹ"),success:oU("✓"),warning:tU(QU(UU(" WARN "))),error:aU(QU(UU(" ERROR ")))},U0=new yQ("stacks"),k=new yQ("bunfig",{showTags:!0}),X0=b(_Q.cwd(),"config"),Z0=b(_Q.cwd(),"src/generated"),eU=kQ.env.CLARITY_LOG_DIR||sX(TZ(),"logs"),SQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:eU,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},WU=await SZ(),E={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},w=E,$0=E.red,QX=E.green,Y0=E.yellow,UX=E.blue,G0=E.magenta,H0=E.cyan,XU=E.white,J0=E.gray,XX=E.bgRed,ZX=E.bgYellow,q0=E.bgGray,ZU=E.bold,_0=E.dim,A0=E.italic,W0=E.underline,z0=E.strikethrough,B0=E.reset,CQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},OX={debug:"\uD83D\uDD0D",info:UX("ℹ"),success:QX("✓"),warning:ZX(XU(ZU(" WARN "))),error:XX(XU(ZU(" ERROR ")))},R0=new hQ("stacks"),v=class extends Error{timestamp;context;constructor(U,X={}){super(U);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let U=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,Z])=>`${X}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${U}`}},dQ=class extends v{code="CONFIG_NOT_FOUND";constructor(U,X,Z){let $=Z?` or alias "${Z}"`:"";super(`Configuration "${U}"${$} not found`,{configName:U,alias:Z,searchPaths:X,searchPathCount:X.length})}},AQ=class extends v{code="CONFIG_LOAD_ERROR";constructor(U,X,Z){super(`Failed to load configuration from "${U}": ${X.message}`,{configPath:U,configName:Z,originalError:X.name,originalMessage:X.message});this.cause=X}},zU=class extends v{code="CONFIG_VALIDATION_ERROR";constructor(U,X,Z){super(`Configuration validation failed for "${U}"`,{configPath:U,configName:Z,validationErrors:X,errorCount:X.length})}},BU=class extends v{code="CONFIG_MERGE_ERROR";constructor(U,X,Z,$){super(`Failed to merge configuration from "${U}" with "${X}": ${Z.message}`,{sourcePath:U,targetPath:X,configName:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},fQ=class extends v{code="ENV_VAR_ERROR";constructor(U,X,Z,$){super(`Failed to parse environment variable "${U}" with value "${X}" as ${Z}`,{envKey:U,envValue:X,expectedType:Z,configName:$})}},RU=class extends v{code="FILE_SYSTEM_ERROR";constructor(U,X,Z){super(`File system ${U} failed for "${X}": ${Z.message}`,{operation:U,path:X,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},LU=class extends v{code="TYPE_GENERATION_ERROR";constructor(U,X,Z){super(`Failed to generate types from "${U}" to "${X}": ${Z.message}`,{configDir:U,outputPath:X,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},WQ=class extends v{code="SCHEMA_VALIDATION_ERROR";constructor(U,X,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:U,configName:Z,validationErrors:X,errorCount:X.length})}},wU=class extends v{code="BROWSER_CONFIG_ERROR";constructor(U,X,Z,$){super(`Failed to fetch configuration from "${U}": ${X} ${Z}`,{endpoint:U,status:X,statusText:Z,configName:$})}},KU=class extends v{code="PLUGIN_ERROR";constructor(U,X,Z){super(`Plugin "${U}" failed during ${X}: ${Z.message}`,{pluginName:U,operation:X,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},o={configNotFound(Q,U,X){return new dQ(Q,U,X)},configLoad(Q,U,X){return new AQ(Q,U,X)},configValidation(Q,U,X){return new zU(Q,U,X)},configMerge(Q,U,X,Z){return new BU(Q,U,X,Z)},envVar(Q,U,X,Z){return new fQ(Q,U,X,Z)},fileSystem(Q,U,X){return new RU(Q,U,X)},typeGeneration(Q,U,X){return new LU(Q,U,X)},schemaValidation(Q,U,X){return new WQ(Q,U,X)},browserConfig(Q,U,X,Z){return new wU(Q,U,X,Z)},plugin(Q,U,X){return new KU(Q,U,X)}},TX={replace:"replace",concat:"concat",smart:"smart"},SX=/^https?:\/\//,f=new hQ("bunfig",{showTags:!0}),i=new NU,CX=y(a.cwd(),"config"),kX=y(a.cwd(),"src/generated")});function F0(Q,U={}){let X=pQ.cwd();while(X.includes("storage"))X=$X(X,"..");let Z=$X(X,Q||"");if(U?.relative)return j0(pQ.cwd(),Z);return Z}var I0=pQ.env.CLARITY_LOG_DIR||K0(F0(),"logs"),xX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:I0,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},uQ={...xX},c7=(async()=>{try{let{loadConfig:Q}=await w0().then(()=>zX),U=await Q({name:"clarity",alias:"logging",defaultConfig:xX,cwd:pQ.cwd()});if(U)Object.assign(uQ,U)}catch{}return uQ})();function O(){if(n.env.NODE_ENV==="test"||n.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function k0(){if(n.env.NODE_ENV==="test"||n.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n<"u"){let Q=n.type;if(Q==="renderer"||Q==="worker")return!1;return!!(n.versions&&(n.versions.node||n.versions.bun))}return!1}class PX{async format(Q){let U=await k0(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:HQ.pid,hostname:U(),environment:HQ.env.NODE_ENV||"development",platform:HQ.platform,version:HQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:HQ.env.NODE_ENV||HQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var T={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},K=T,U8=T.red,x0=T.green,X8=T.yellow,P0=T.blue,Z8=T.magenta,$8=T.cyan,AX=T.white,Y8=T.gray,b0=T.bgRed,y0=T.bgYellow,G8=T.bgGray,WX=T.bold,H8=T.dim,J8=T.italic,q8=T.underline,_8=T.strikethrough,A8=T.reset,HU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},v0={debug:"\uD83D\uDD0D",info:P0("ℹ"),success:x0("✓"),warning:y0(AX(WX(" WARN "))),error:b0(AX(WX(" ERROR ")))};class BQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,U={}){this.name=Q,this.config={...uQ},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new PX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??L.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Z=U.timestamp!==void 0;if(Z)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let U={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return U[Q]>=U[X]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...HU,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...HU};return{...HU,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:uQ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}shouldWriteToFile(){return!O()&&this.config.writeToFile===!0}async writeToFile(Q){let X=(async()=>{let $,Y=0,G=3,J=1000;while(Y<G)try{try{try{await E0(this.config.logDirectory,JX.F_OK|JX.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await O0(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let H=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:g.from(Q);try{if(!VQ(this.currentLogFile))await GU(this.currentLogFile,"",{mode:420});if($=HX(this.currentLogFile,"a",420),N0($,H,{flag:"a"}),GX($),$!==void 0)YU($),$=void 0;if((await YQ(this.currentLogFile)).size===0){if(await GU(this.currentLogFile,H,{flag:"w",mode:420}),(await YQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(Y<G-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,A);let z=J*2**Y;await new Promise((W)=>setTimeout(W,z)),Y++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{YU($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(H){if(Y===G-1){let _=H,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),H}Y++;let q=J*2**(Y-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(X);let Z=this.pendingOperations.length-1;try{await X}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return GQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return GQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return GQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(O())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Z=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=X,this.keys.set(X,Z),this.encryptionKeys.set(X,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,J],[,H])=>H.createdAt.getTime()-J.createdAt.getTime()),Y=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,Y);if($.length>G)for(let[J]of $.slice(G))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return $U(16).toString("hex")}generateKey(){return $U(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:U}=this.getCurrentKey(),X=$U(16),Z=M0("aes-256-gcm",U,X),$=g.isBuffer(Q)?Q:g.from(Q,"utf8"),Y=Z.update($),G=Z.final(),J=Y.length+G.length,H=Z.getAuthTag(),q=g.allocUnsafe(16+J+16);return X.copy(q,0),Y.copy(q,16),G.copy(q,16+Y.length),H.copy(q,16+J),{encrypted:q,iv:X}}async compressData(Q){return new Promise((U,X)=>{let Z=_X(),$=[];Z.on("data",(Y)=>$.push(Y)),Z.on("end",()=>U(g.from(g.concat($)))),Z.on("error",X),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(O())return;if(!this.shouldWriteToFile())return;let Q=await YQ(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await DQ(this.config.logDirectory),Y=$.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,q)=>{let _=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${X}.${G}`;if(await YQ(X).catch(()=>null))try{if(await qX(X,J),U.compress)try{let H=`${J}.gz`;await this.compressLogFile(J,H),await NQ(J)}catch(H){console.error("Error compressing rotated file:",H)}if(Y.length===0&&!$.some((H)=>H.endsWith(".log.1")))try{let H=`${X}.1`;await GU(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),Y=X.replace(/\.log$/,`-${$}.log`);if(await YQ(X).catch(()=>null))await qX(X,Y)}if(this.currentLogFile=Z,U.maxFiles){let Y=(await DQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,J)=>J.localeCompare(G));for(let G of Y.slice(U.maxFiles))await NQ(GQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=YX(Q),Z=D0(U),$=_X();await C0(X,$,Z)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Z=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(U);console.log(U)}}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),VQ(this.currentLogFile))try{let Q=HX(this.currentLogFile,"r+");GX(Q),YU(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!O()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await DQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await NQ(GQ(this.config.logDirectory,X))}catch(Z){console.error(`Failed to delete temp file ${X}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?K.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||O())return!1;let Q=typeof L.env.NO_COLOR<"u",U=L.env.FORCE_COLOR==="0";if(Q||U)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Z="",message:$,level:Y,showTimestamp:G=!0}=Q,J=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let H=L.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${X} ${$}`;else if(Y==="info"||Y==="success")q=`${X} ${Z} ${$}`;else q=`${X} ${Z} ${K.cyan($)}`;if(!G)return q.trim();let _=J(q).trim().length,A=J(U).length,z=Math.max(1,H-2-_-A);return`${q.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,(Y,G)=>{let J=Number.parseInt(G,10);return J<U[0].length?String(U[0][J]):Y});let X=/%([sdijfo%])/g,Z=0,$=Q.replace(X,(Y,G)=>{if(G==="%")return"%";if(Z>=U.length)return Y;let J=U[Z++];switch(G){case"s":return String(J);case"d":case"i":return Number(J).toString();case"j":case"o":return JSON.stringify(J,null,2);default:return Y}});if(Z<U.length)$+=` ${U.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let U=Q;return U=U.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,Z,$)=>{let Y=K.underline(K.blue(Z)),G=this.toAbsoluteFilePath($);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let J=`file://${encodeURI(G)}`,H="\x1B]8;;",q="\x1B\\";return`\x1B]8;;${J}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),U=U.replace(/`([^`]+)`/g,(X,Z)=>K.bgGray(Z)),U=U.replace(/\*\*([^*]+)\*\*/g,(X,Z)=>K.bold(Z)),U=U.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,Z)=>K.italic(Z)),U=U.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,Z)=>K.italic(Z)),U=U.replace(/~([^~]+)~/g,(X,Z)=>K.strikethrough(Z)),U}supportsHyperlinks(){if(O())return!1;let Q=L.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let U=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(U)&&U>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let U=Q;if(U.startsWith("file://"))U=U.replace(/^file:\/\//,"");if(U.startsWith("~")){let X=L.env.HOME||"";if(X)U=U.replace(/^~(?=$|\/)/,X)}if(T0(U)||U.startsWith("./")||U.startsWith("../"))U=S0(U);else return null;return VQ(U)?U:null}catch{return null}}buildOutputTexts(Q){let U=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,X=Q.replace(this.ANSI_PATTERN,"");return{consoleText:U,fileText:X}}async log(Q,U,...X){if(!this.shouldLog(Q))return;let Z=new Date,$=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,J;if(U instanceof Error)G=U.message,J=U.stack;else G=this.formatMessage(U,X);let{consoleText:H,fileText:q}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":v0[Q],z=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:K.gray(H),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:K.green(H),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.error(W),J){let V=J.split(`
|
|
39
|
+
`}return{name:"bunfig-plugin",setup($){$.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),$.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var DX,JQ,zQ,NX,nZ,iZ,sU,OQ,WU,C,I,sZ,oU,oZ,rU,rZ,aZ,UU,tZ,aU,tU,XU,eZ,Q0,U0,X0,TQ,EX,Z0,k,$0,Y0,eU,SQ,zU,E,w,G0,QX,H0,UX,J0,q0,ZU,_0,XX,ZX,A0,$U,W0,z0,B0,R0,L0,CQ,OX,w0,K0="0.15.6",v,dQ,AQ,BU,RU,fQ,LU,wU,WQ,KU,jU,o,TX,SX,f,i,CX,kX,j0=nX(async()=>{DX=import.meta.require,JQ=new FU,zQ=new IU,NX={createKey:FZ,isEquivalent:IZ,estimateMemoryUsage:MZ},nZ=PQ(_U.cwd(),"config"),iZ=PQ(_U.cwd(),"src/generated"),sU=xQ.env.CLARITY_LOG_DIR||tX(NZ(),"logs"),OQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:sU,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},WU=await EZ(),C={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},I=C,sZ=C.red,oU=C.green,oZ=C.yellow,rU=C.blue,rZ=C.magenta,aZ=C.cyan,UU=C.white,tZ=C.gray,aU=C.bgRed,tU=C.bgYellow,XU=C.bold,eZ=C.dim,Q0=C.italic,U0=C.underline,X0=C.reset,TQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EX={debug:"\uD83D\uDD0D",info:rU("ℹ"),success:oU("✓"),warning:tU(UU(XU(" WARN "))),error:aU(UU(XU(" ERROR ")))},Z0=new yQ("stacks"),k=new yQ("bunfig",{showTags:!0}),$0=b(_Q.cwd(),"config"),Y0=b(_Q.cwd(),"src/generated"),eU=kQ.env.CLARITY_LOG_DIR||rX(CZ(),"logs"),SQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:eU,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},zU=await kZ(),E={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},w=E,G0=E.red,QX=E.green,H0=E.yellow,UX=E.blue,J0=E.magenta,q0=E.cyan,ZU=E.white,_0=E.gray,XX=E.bgRed,ZX=E.bgYellow,A0=E.bgGray,$U=E.bold,W0=E.dim,z0=E.italic,B0=E.underline,R0=E.strikethrough,L0=E.reset,CQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},OX={debug:"\uD83D\uDD0D",info:UX("ℹ"),success:QX("✓"),warning:ZX(ZU($U(" WARN "))),error:XX(ZU($U(" ERROR ")))},w0=new hQ("stacks"),v=class extends Error{timestamp;context;constructor(U,X={}){super(U);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let U=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,Z])=>`${X}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${U}`}},dQ=class extends v{code="CONFIG_NOT_FOUND";constructor(U,X,Z){let $=Z?` or alias "${Z}"`:"";super(`Configuration "${U}"${$} not found`,{configName:U,alias:Z,searchPaths:X,searchPathCount:X.length})}},AQ=class extends v{code="CONFIG_LOAD_ERROR";constructor(U,X,Z){super(`Failed to load configuration from "${U}": ${X.message}`,{configPath:U,configName:Z,originalError:X.name,originalMessage:X.message});this.cause=X}},BU=class extends v{code="CONFIG_VALIDATION_ERROR";constructor(U,X,Z){super(`Configuration validation failed for "${U}"`,{configPath:U,configName:Z,validationErrors:X,errorCount:X.length})}},RU=class extends v{code="CONFIG_MERGE_ERROR";constructor(U,X,Z,$){super(`Failed to merge configuration from "${U}" with "${X}": ${Z.message}`,{sourcePath:U,targetPath:X,configName:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},fQ=class extends v{code="ENV_VAR_ERROR";constructor(U,X,Z,$){super(`Failed to parse environment variable "${U}" with value "${X}" as ${Z}`,{envKey:U,envValue:X,expectedType:Z,configName:$})}},LU=class extends v{code="FILE_SYSTEM_ERROR";constructor(U,X,Z){super(`File system ${U} failed for "${X}": ${Z.message}`,{operation:U,path:X,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},wU=class extends v{code="TYPE_GENERATION_ERROR";constructor(U,X,Z){super(`Failed to generate types from "${U}" to "${X}": ${Z.message}`,{configDir:U,outputPath:X,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},WQ=class extends v{code="SCHEMA_VALIDATION_ERROR";constructor(U,X,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:U,configName:Z,validationErrors:X,errorCount:X.length})}},KU=class extends v{code="BROWSER_CONFIG_ERROR";constructor(U,X,Z,$){super(`Failed to fetch configuration from "${U}": ${X} ${Z}`,{endpoint:U,status:X,statusText:Z,configName:$})}},jU=class extends v{code="PLUGIN_ERROR";constructor(U,X,Z){super(`Plugin "${U}" failed during ${X}: ${Z.message}`,{pluginName:U,operation:X,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},o={configNotFound(Q,U,X){return new dQ(Q,U,X)},configLoad(Q,U,X){return new AQ(Q,U,X)},configValidation(Q,U,X){return new BU(Q,U,X)},configMerge(Q,U,X,Z){return new RU(Q,U,X,Z)},envVar(Q,U,X,Z){return new fQ(Q,U,X,Z)},fileSystem(Q,U,X){return new LU(Q,U,X)},typeGeneration(Q,U,X){return new wU(Q,U,X)},schemaValidation(Q,U,X){return new WQ(Q,U,X)},browserConfig(Q,U,X,Z){return new KU(Q,U,X,Z)},plugin(Q,U,X){return new jU(Q,U,X)}},TX={replace:"replace",concat:"concat",smart:"smart"},SX=/^https?:\/\//,f=new hQ("bunfig",{showTags:!0}),i=new EU,CX=y(a.cwd(),"config"),kX=y(a.cwd(),"src/generated")});function M0(Q,U={}){let X=pQ.cwd();while(X.includes("storage"))X=$X(X,"..");let Z=$X(X,Q||"");if(U?.relative)return I0(pQ.cwd(),Z);return Z}var V0=pQ.env.CLARITY_LOG_DIR||F0(M0(),"logs"),xX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:V0,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},uQ={...xX},c7=(async()=>{try{let{loadConfig:Q}=await j0().then(()=>zX),U=await Q({name:"clarity",alias:"logging",defaultConfig:xX,cwd:pQ.cwd()});if(U)Object.assign(uQ,U)}catch{}return uQ})();function O(){if(n.env.NODE_ENV==="test"||n.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function P0(){if(n.env.NODE_ENV==="test"||n.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n<"u"){let Q=n.type;if(Q==="renderer"||Q==="worker")return!1;return!!(n.versions&&(n.versions.node||n.versions.bun))}return!1}class PX{async format(Q){let U=await P0(),X=await this.getMetadata(U);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:X})}async getMetadata(Q){if(Q){let{hostname:U}=await import("os");return{pid:HQ.pid,hostname:U(),environment:HQ.env.NODE_ENV||"development",platform:HQ.platform,version:HQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:HQ.env.NODE_ENV||HQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var T={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},K=T,U8=T.red,b0=T.green,X8=T.yellow,y0=T.blue,Z8=T.magenta,$8=T.cyan,AX=T.white,Y8=T.gray,v0=T.bgRed,h0=T.bgYellow,G8=T.bgGray,WX=T.bold,H8=T.dim,J8=T.italic,q8=T.underline,_8=T.strikethrough,A8=T.reset,JU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},d0={debug:"\uD83D\uDD0D",info:y0("ℹ"),success:b0("✓"),warning:h0(AX(WX(" WARN "))),error:v0(AX(WX(" ERROR ")))};class BQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,U={}){this.name=Q,this.config={...uQ},this.options=this.normalizeOptions(U),this.formatter=this.options.formatter||new PX,this.enabled=U.enabled??!0,this.fancy=U.fancy??!0,this.tagFormat=U.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=U.timestampPosition??"right",this.environment=U.environment??L.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(U);let X={...U},Z=U.timestamp!==void 0;if(Z)delete X.timestamp;if(this.config={...this.config,...X,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let U={debug:0,info:1,success:2,warning:3,error:4},X=this.fingersCrossedConfig.activationLevel??"error";return U[Q]>=U[X]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...JU,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...JU};return{...JU,...Q.fingersCrossed}}normalizeOptions(Q){let U={format:"json",level:"info",logDirectory:uQ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},X={...U,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!X.level||!["debug","info","success","warning","error"].includes(X.level))X.level=U.level;return X}shouldWriteToFile(){return!O()&&this.config.writeToFile===!0}async writeToFile(Q){let X=(async()=>{let $,Y=0,G=3,J=1000;while(Y<G)try{try{try{await T0(this.config.logDirectory,JX.F_OK|JX.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await S0(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let H=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:g.from(Q);try{if(!VQ(this.currentLogFile))await HU(this.currentLogFile,"",{mode:420});if($=HX(this.currentLogFile,"a",420),O0($,H,{flag:"a"}),GX($),$!==void 0)GU($),$=void 0;if((await YQ(this.currentLogFile)).size===0){if(await HU(this.currentLogFile,H,{flag:"w",mode:420}),(await YQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(Y<G-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${G}:`,A);let z=J*2**Y;await new Promise((W)=>setTimeout(W,z)),Y++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{GU($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(H){if(Y===G-1){let _=H,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),H}Y++;let q=J*2**(Y-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(X);let Z=this.pendingOperations.length-1;try{await X}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return GQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return GQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return GQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(O())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,U;switch(Q.frequency){case"daily":U=86400000;break;case"weekly":U=604800000;break;case"monthly":U=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},U)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let U=this.config.rotation.keyRotation;if(!U?.enabled)return;let X=typeof U.interval==="number"?U.interval:60,Z=Math.max(X,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let U=this.config.rotation.keyRotation,X=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=X,this.keys.set(X,Z),this.encryptionKeys.set(X,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,J],[,H])=>H.createdAt.getTime()-J.createdAt.getTime()),Y=typeof U.maxKeys==="number"?U.maxKeys:1,G=Math.max(1,Y);if($.length>G)for(let[J]of $.slice(G))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return YU(16).toString("hex")}generateKey(){return YU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:U}=this.getCurrentKey(),X=YU(16),Z=D0("aes-256-gcm",U,X),$=g.isBuffer(Q)?Q:g.from(Q,"utf8"),Y=Z.update($),G=Z.final(),J=Y.length+G.length,H=Z.getAuthTag(),q=g.allocUnsafe(16+J+16);return X.copy(q,0),Y.copy(q,16),G.copy(q,16+Y.length),H.copy(q,16+J),{encrypted:q,iv:X}}async compressData(Q){return new Promise((U,X)=>{let Z=_X(),$=[];Z.on("data",(Y)=>$.push(Y)),Z.on("end",()=>U(g.from(g.concat($)))),Z.on("error",X),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let U=this.config.rotation.encrypt;return{...Q,...U}}return Q}async rotateLog(){if(O())return;if(!this.shouldWriteToFile())return;let Q=await YQ(this.currentLogFile).catch(()=>null);if(!Q)return;let U=this.config.rotation;if(typeof U==="boolean")return;if(U.maxSize&&Q.size>=U.maxSize){let X=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await DQ(this.config.logDirectory),Y=$.filter((H)=>H.startsWith(this.name)&&/\.log\.\d+$/.test(H)).sort((H,q)=>{let _=Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),G=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,J=`${X}.${G}`;if(await YQ(X).catch(()=>null))try{if(await qX(X,J),U.compress)try{let H=`${J}.gz`;await this.compressLogFile(J,H),await NQ(J)}catch(H){console.error("Error compressing rotated file:",H)}if(Y.length===0&&!$.some((H)=>H.endsWith(".log.1")))try{let H=`${X}.1`;await HU(H,"")}catch(H){console.error("Error creating backup file:",H)}}catch(H){console.error(`Error during rotation: ${H instanceof Error?H.message:String(H)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),Y=X.replace(/\.log$/,`-${$}.log`);if(await YQ(X).catch(()=>null))await qX(X,Y)}if(this.currentLogFile=Z,U.maxFiles){let Y=(await DQ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,J)=>J.localeCompare(G));for(let G of Y.slice(U.maxFiles))await NQ(GQ(this.config.logDirectory,G))}}}async compressLogFile(Q,U){let X=YX(Q),Z=E0(U),$=_X();await x0(X,$,Z)}async handleFingersCrossedBuffer(Q,U){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let X of this.logBuffer){let Z=await this.formatter.format(X);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(U);console.log(U)}}shouldLog(Q){if(!this.enabled)return!1;let U={debug:0,info:1,success:2,warning:3,error:4};return U[Q]>=U[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((U)=>{console.error("Error in pending write operation:",U)});return Promise.resolve()})),VQ(this.currentLogFile))try{let Q=HX(this.currentLogFile,"r+");GX(Q),GU(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!O()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let U=(await DQ(this.config.logDirectory)).filter((X)=>(X.includes("temp")||X.includes(".tmp"))&&X.includes(this.name));for(let X of U)try{await NQ(GQ(this.config.logDirectory,X))}catch(Z){console.error(`Failed to delete temp file ${X}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?K.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||O())return!1;let Q=typeof L.env.NO_COLOR<"u",U=L.env.FORCE_COLOR==="0";if(Q||U)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:U,icon:X="",tag:Z="",message:$,level:Y,showTimestamp:G=!0}=Q,J=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(G)W.push(U);if(Y==="warning")W.push("WARN");else if(Y==="error")W.push("ERROR");else if(X)W.push(X.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let H=L.stdout.columns||120,q="";if(Y==="warning"||Y==="error")q=`${X} ${$}`;else if(Y==="info"||Y==="success")q=`${X} ${Z} ${$}`;else q=`${X} ${Z} ${K.cyan($)}`;if(!G)return q.trim();let _=J(q).trim().length,A=J(U).length,z=Math.max(1,H-2-_-A);return`${q.trim()}${" ".repeat(z)}${U}`}formatMessage(Q,U){if(U.length===1&&Array.isArray(U[0]))return Q.replace(/\{(\d+)\}/g,(Y,G)=>{let J=Number.parseInt(G,10);return J<U[0].length?String(U[0][J]):Y});let X=/%([sdijfo%])/g,Z=0,$=Q.replace(X,(Y,G)=>{if(G==="%")return"%";if(Z>=U.length)return Y;let J=U[Z++];switch(G){case"s":return String(J);case"d":case"i":return Number(J).toString();case"j":case"o":return JSON.stringify(J,null,2);default:return Y}});if(Z<U.length)$+=` ${U.slice(Z).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let U=Q;return U=U.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(X,Z,$)=>{let Y=K.underline(K.blue(Z)),G=this.toAbsoluteFilePath($);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let J=`file://${encodeURI(G)}`,H="\x1B]8;;",q="\x1B\\";return`\x1B]8;;${J}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),U=U.replace(/`([^`]+)`/g,(X,Z)=>K.bgGray(Z)),U=U.replace(/\*\*([^*]+)\*\*/g,(X,Z)=>K.bold(Z)),U=U.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(X,Z)=>K.italic(Z)),U=U.replace(/(?<!_)_([^_]+)_(?!_)/g,(X,Z)=>K.italic(Z)),U=U.replace(/~([^~]+)~/g,(X,Z)=>K.strikethrough(Z)),U}supportsHyperlinks(){if(O())return!1;let Q=L.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let U=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(U)&&U>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let U=Q;if(U.startsWith("file://"))U=U.replace(/^file:\/\//,"");if(U.startsWith("~")){let X=L.env.HOME||"";if(X)U=U.replace(/^~(?=$|\/)/,X)}if(C0(U)||U.startsWith("./")||U.startsWith("../"))U=k0(U);else return null;return VQ(U)?U:null}catch{return null}}buildOutputTexts(Q){let U=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,X=Q.replace(this.ANSI_PATTERN,"");return{consoleText:U,fileText:X}}async log(Q,U,...X){if(!this.shouldLog(Q))return;let Z=new Date,$=this.formatConsoleTimestamp(Z),Y=this.formatFileTimestamp(Z),G,J;if(U instanceof Error)G=U.message,J=U.stack;else G=this.formatMessage(U,X);let{consoleText:H,fileText:q}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":d0[Q],z=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:K.gray(H),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:K.green(H),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:H,level:Q}),console.error(W),J){let V=J.split(`
|
|
40
40
|
`);for(let B of V)if(B.trim()&&!B.includes(G))console.error(this.formatConsoleMessage({timestamp:$,message:K.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!O()){if(console.error(`${Y} ${this.environment}.${Q.toUpperCase()}: ${G}`),J)console.error(J)}let _=`${Y} ${this.environment}.${Q.toUpperCase()}: ${q}
|
|
41
41
|
`;if(J)_+=`${J}
|
|
42
42
|
`;if(_=_.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(_)}progress(Q,U=""){let X={update:(J,H)=>{},finish:(J)=>{},interrupt:(J,H)=>{}};if(!this.enabled)return X;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:U||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(J,H)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,J),this.activeProgressBar.total),H!==void 0)this.activeProgressBar.message=H;if(this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(J)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,J)},interrupt:(J,H="info")=>{if(!O()&&L.stdout.isTTY)L.stdout.write(`
|
|
43
43
|
`);if(this[H==="warning"?"warn":H](J),this.activeProgressBar&&this.shouldStyleConsole()&&!O()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let U=performance.now();if(this.shouldStyleConsole()){let X=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":K.blue("◐"),tag:X,message:`${K.cyan(Q)}...`}))}return async(X)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-U),Y=`${Q} completed in ${$}ms`,G=new Date,J=this.formatConsoleTimestamp(G),q=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${Y}`;if(X)q+=` ${JSON.stringify(X)}`;if(q+=`
|
|
44
|
-
`,q=q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":K.green("✓"),tag:_,message:`${Y}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!O())console.error(q.trim());if(this.shouldWriteToFile())await this.writeToFile(q)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new BQ(U,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(O())throw Error("createReadStream is not supported in browser environments");if(!VQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return YX(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Z=g.isBuffer(Q)?Q:g.from(Q,"base64"),$=Z.subarray(0,16),Y=Z.subarray(Z.length-16),G=Z.subarray(16,Z.length-16),J=
|
|
44
|
+
`,q=q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":K.green("✓"),tag:_,message:`${Y}${X?` ${JSON.stringify(X)}`:""}`}))}else if(!O())console.error(q.trim());if(this.shouldWriteToFile())await this.writeToFile(q)}}async debug(Q,...U){await this.log("debug",Q,...U)}async info(Q,...U){await this.log("info",Q,...U)}async success(Q,...U){await this.log("success",Q,...U)}async warn(Q,...U){await this.log("warning",Q,...U)}async error(Q,...U){await this.log("error",Q,...U)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:U}=Q;return!!U}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let U=`${this.name}:${Q}`,X=new BQ(U,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(X),X}createReadStream(){if(O())throw Error("createReadStream is not supported in browser environments");if(!VQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return YX(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let U=this.config.rotation;if(!U.encrypt||typeof U.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let X=this.keys.get(this.currentKeyId);try{let Z=g.isBuffer(Q)?Q:g.from(Q,"base64"),$=Z.subarray(0,16),Y=Z.subarray(Z.length-16),G=Z.subarray(16,Z.length-16),J=N0("aes-256-gcm",X,$);J.setAuthTag(Y);let H=J.update(G),q=J.final(),_=H.length+q.length,A=g.allocUnsafe(_);return H.copy(A,0),q.copy(A,H.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return O()}isServerMode(){return!O()}setTestEncryptionKey(Q,U){this.currentKeyId=Q,this.keys.set(Q,U)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let U=new Date,X=this.formatConsoleTimestamp(U),Z=this.formatFileTimestamp(U),{consoleText:$,fileText:Y}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let J=$.split(`
|
|
45
45
|
`),H=Math.max(...J.map((z)=>z.length))+2,q=`┌${"─".repeat(H)}┐`,_=`└${"─".repeat(H)}┘`,A=J.map((z)=>{return this.formatConsoleMessage({timestamp:X,message:K.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:X,message:K.cyan(q),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:X,message:K.cyan(_),showTimestamp:!1}))}else if(!O())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Y}`);let G=`${Z} ${this.environment}.INFO: [BOX] ${Y}
|
|
46
46
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(O())return Promise.resolve(!0);return new Promise((U)=>{console.error(`${K.cyan("?")} ${Q} (y/n) `);let X=(Z)=>{let $=Z.toString().trim().toLowerCase();L.stdin.removeListener("data",X);try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!1)}catch{}L.stdin.pause(),console.error(""),U($==="y"||$==="yes")};try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!0)}catch{}L.stdin.resume(),L.stdin.once("data",X)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...U){if(!this.enabled)return;let X=Q;if(U&&U.length>0){let H=/%([sdijfo%])/g,q=0;if(X=Q.replace(H,(_,A)=>{if(A==="%")return"%";if(q>=U.length)return _;let z=U[q++];switch(A){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return _}}),q<U.length)X+=` ${U.slice(q).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(X);if(this.shouldStyleConsole()){let H=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",q=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${q}${H} ${K.cyan(Z)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
47
47
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(Q,U=!1){if(!this.enabled||!this.shouldStyleConsole()||!L.stdout.isTTY)return;let X=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*X/100),$=Q.barLength-Z,Y=K.green("━".repeat(Z)),G=K.gray("━".repeat($)),J=`[${Y}${G}]`,H=`${X}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=this.options.showIcons===!1?"":U||X===100?K.green("✓"):K.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${J} ${H}${q}`,W=L.stdout.columns||80,V=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${V}`,L.stdout.write(Q.lastRenderedLine),U)L.stdout.write(`
|
|
48
|
-
`)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||O()||!L.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(O()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await DQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=GQ(this.config.logDirectory,Z);if(Q.before)try{if((await YQ(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await NQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}var W8=new BQ("stacks");var
|
|
49
|
-
export{r as yb,
|
|
48
|
+
`)}finishProgressBar(Q,U){if(!this.enabled||!this.fancy||O()||!L.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(U)Q.message=U;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(O()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let U=await DQ(this.config.logDirectory),X=[];for(let Z of U){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let Y=GQ(this.config.logDirectory,Z);if(Q.before)try{if((await YQ(Y)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${Y}:`,G);continue}X.push(Y)}if(X.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${X.length} log file(s)...`);for(let Z of X)try{await NQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(U){console.error("Error during log clearing process:",U)}}}var W8=new BQ("stacks");var f0=new BQ("rpx",{showTags:!1});function hX(){return process.env.SUDO_PASSWORD}function dX(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function L8(Q={}){if(process.platform==="win32")return!0;if(dX()||!!hX())return!0;let U=Q.exec??cQ;try{return U("sudo -n true",{stdio:"ignore"}),!0}catch{if(!Q.interactive)return!1}try{return U("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function w8(Q){if(dX())return cQ(Q,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let U=hX(),X=Q.replace(/'/g,"'\\''");if(U)return cQ(`echo '${U}' | sudo -S sh -c '${X}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return cQ(`sudo -n sh -c '${X}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function bX(Q,U,X){if(X)f0.debug(`[rpx:${Q}] ${U}`)}function K8(){let Q=process.env.RPX_REUSE_PORT;return Q==="1"||Q==="true"}var yX="[redacted]",p0=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),u0=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function m0(Q){let U=Q.toLowerCase();return p0.has(U)||U.endsWith("password")||U.includes("secret")||U.includes("token")}function OU(Q){if(Array.isArray(Q))return Q.map((X)=>OU(X));if(typeof Q==="string")return u0.test(Q)?yX:Q;if(!Q||typeof Q!=="object")return Q;let U={};for(let[X,Z]of Object.entries(Q)){if(m0(X)){U[X]=yX;continue}U[X]=OU(Z)}return U}function j8(Q,U){return JSON.stringify(OU(Q),null,U)}function F8(Q){if(fX(Q))return Q.proxies.map((U)=>{let X=U.to||"stacks.localhost";return X.startsWith("http")?new URL(X).hostname:X});if(pX(Q)){let U=Q.to||"stacks.localhost";return[U.startsWith("http")?new URL(U).hostname:U]}return["stacks.localhost"]}function I8(Q){return typeof Q==="object"&&Q!==null&&"certificate"in Q&&"privateKey"in Q&&typeof Q.certificate==="string"&&typeof Q.privateKey==="string"}function M8(Q){if(!Q)return"stacks.localhost";if(fX(Q)&&Q.proxies.length>0)return Q.proxies[0].to||"stacks.localhost";if(pX(Q))return Q.to||"stacks.localhost";return"stacks.localhost"}function V8(Q){return!!(Q&&("proxies"in Q)&&Array.isArray(Q.proxies))}function fX(Q){return"proxies"in Q&&Array.isArray(Q.proxies)}function pX(Q){return"to"in Q&&typeof Q.to==="string"}function D8(Q){return!!(Q&&("to"in Q)&&!("proxies"in Q))}function N8(Q,U){if(!U||U.length===0)return null;for(let X of U)if(Q===X.from||Q.startsWith(`${X.from}/`)){let Z=X.to.startsWith("http")?new URL(X.to).host:X.to,$=X.stripPrefix===!0?Q.slice(X.from.length)||"/":Q;return{targetHost:Z,targetPath:$}}return null}async function E8(Q,U){try{await vX.unlink(Q),bX("certificates",`Successfully deleted: ${Q}`,U)}catch(X){if(X.code!=="ENOENT")bX("certificates",`Warning: Could not delete ${Q}: ${X}`,U)}}
|
|
49
|
+
export{r as yb,hX as zb,dX as Ab,L8 as Bb,w8 as Cb,bX as Db,K8 as Eb,OU as Fb,j8 as Gb,F8 as Hb,I8 as Ib,M8 as Jb,V8 as Kb,fX as Lb,pX as Mb,D8 as Nb,N8 as Ob,E8 as Pb};
|