@stacksjs/rpx 0.11.45 → 0.11.46
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 +231 -239
- package/dist/chunk-086aa2f7.js +1 -0
- package/dist/chunk-nnnptjfw.js +49 -0
- package/dist/chunk-t3s94va5.js +1 -0
- package/dist/chunk-z0swphpg.js +253 -0
- package/dist/index.js +2 -2
- package/dist/proxy-handler.d.ts +2 -1
- package/dist/proxy-pool.d.ts +1 -0
- package/package.json +1 -1
- package/dist/chunk-bvq3wmhm.js +0 -1
- package/dist/chunk-t6pzd7ec.js +0 -252
- package/dist/chunk-vce43wgr.js +0 -1
- package/dist/chunk-w4t1nar9.js +0 -49
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ab as a,bb as b,cb as c,db as d,eb as e,fb as f,gb as g,hb as h,ib as i,jb as j,kb as k,lb as l,mb as m,nb as n,ob as o}from"./chunk-z0swphpg.js";import"./chunk-nnnptjfw.js";export{a as DNS_PORT,b as RPX_RESOLVER_MARKER,h as contentLooksLikeRpxResolver,e as isDnsServerRunning,f as isRpxDevelopmentDnsAnswering,o as reconcileStaleDevelopmentDns,j as removeLegacyTldResolvers,n as removeResolver,g as resolverFilePath,k as setupDevelopmentDns,i as setupResolver,c as startDnsServer,d as stopDnsServer,l as syncDevelopmentDnsFromRegistry,m as tearDownDevelopmentDns};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import{createRequire as Wr}from"node:module";var Z=Wr(import.meta.url);import{execSync as Ue}from"node:child_process";import*as Lr from"node:fs/promises";import{existsSync as Ot,statSync as Pt}from"fs";import{existsSync as ft,mkdirSync as Jr,readdirSync as Hr,writeFileSync as qr}from"fs";import{homedir as Q}from"os";import{dirname as Rt,resolve as M}from"path";import X from"process";import{join as Zr,relative as Xr,resolve as Nt}from"path";import Re from"process";import{existsSync as dr,mkdirSync as ts,readdirSync as rs,writeFileSync as ns}from"fs";import{homedir as Ye}from"os";import{dirname as os,resolve as D}from"path";import ue from"process";import{join as Qr,relative as en,resolve as Bt}from"path";import Ne from"process";import{existsSync as pr,mkdirSync as us,readdirSync as gs,writeFileSync as hs}from"fs";import{dirname as ds,resolve as Be}from"path";import ut from"process";import{Buffer as H}from"buffer";import{createCipheriv as tn,createDecipheriv as rn,randomBytes as Ge}from"crypto";import{closeSync as Je,createReadStream as Dt,createWriteStream as nn,existsSync as He,fsyncSync as Mt,openSync as Lt,writeFileSync as sn}from"fs";import{access as on,constants as It,mkdir as an,readdir as pe,rename as jt,stat as ee,unlink as ye,writeFile as qe}from"fs/promises";import{join as te}from"path";import O from"process";import{pipeline as cn}from"stream/promises";import{createGzip as _t}from"zlib";import re from"process";import U from"process";import{Buffer as V}from"buffer";import{createCipheriv as ln,createDecipheriv as fn,randomBytes as Ze}from"crypto";import{closeSync as Xe,createReadStream as Kt,createWriteStream as un,existsSync as we,fsyncSync as Wt,openSync as Vt,writeFileSync as gn}from"fs";import{access as hn,constants as zt,mkdir as mn,readdir as $e,rename as Ut,stat as ne,unlink as ve,writeFile as Qe}from"fs/promises";import{isAbsolute as dn,join as ie,resolve as pn}from"path";import d from"process";import{pipeline as yn}from"stream/promises";import{createGzip as Yt}from"zlib";import se from"process";import Y from"process";import Ce from"process";import{existsSync as Ee}from"fs";import{resolve as et}from"path";import{existsSync as wn}from"fs";import{existsSync as $n,readdirSync as vn}from"fs";import{extname as tt,resolve as Gt}from"path";import Cn from"process";import{join as Ei,relative as bi,resolve as sr}from"path";import Ke from"process";import{Buffer as z}from"buffer";import{createCipheriv as Si,createDecipheriv as ki,randomBytes as ot}from"crypto";import{closeSync as at,createReadStream as or,createWriteStream as Ai,existsSync as xe,fsyncSync as ar,openSync as cr,writeFileSync as Fi}from"fs";import{access as Oi,constants as lr,mkdir as Pi,readdir as Te,rename as fr,stat as oe,unlink as Se,writeFile as ct}from"fs/promises";import{isAbsolute as Ri,join as ae,resolve as Ni}from"path";import p from"process";import{pipeline as Bi}from"stream/promises";import{createGzip as ur}from"zlib";import ce from"process";import G from"process";var Vr=Object.defineProperty;var zr=(e)=>e;function Ur(e,t){this[e]=zr.bind(null,t)}var Yr=(e,t)=>{for(var r in t)Vr(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ur.bind(t,r)})},Gr=(e,t)=>()=>(e&&(t=e(e=0)),t);var mr={};Yr(mr,{withErrorRecovery:()=>$r,tryLoadConfig:()=>zn,loadConfigWithResult:()=>Wn,loadConfig:()=>xr,isRetryableError:()=>Mn,isConfigNotFoundError:()=>Dn,isBunfigError:()=>vr,globalPerformanceMonitor:()=>me,globalCache:()=>le,getEnvOrDefault:()=>Ln,generateConfigTypes:()=>Un,defaultGeneratedDir:()=>Rr,defaultConfigDir:()=>Pr,deepMergeWithArrayStrategy:()=>Tt,deepMerge:()=>Cr,createLibraryConfig:()=>Yn,config:()=>Vn,bunfigPlugin:()=>Gn,applyEnvVarsToConfig:()=>fe,TypeGenerationError:()=>wt,SchemaValidationError:()=>he,PluginError:()=>vt,PerformanceMonitor:()=>Et,FileSystemError:()=>yt,ErrorFactory:()=>q,EnvVarError:()=>_e,EnvProcessor:()=>Ve,ConfigValidator:()=>St,ConfigValidationError:()=>dt,ConfigNotFoundError:()=>je,ConfigMergeError:()=>pt,ConfigLoader:()=>kt,ConfigLoadError:()=>ge,ConfigFileLoader:()=>ze,ConfigCache:()=>Ct,CacheUtils:()=>Sr,BunfigError:()=>L,BrowserConfigError:()=>$t,ArrayMergeStrategies:()=>Fr});class Ct{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Ot(e))return!0;return Pt(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Ot(r)?Pt(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Et{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function En(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function bn(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function xn(e){return e.getStats().size*2}function bt(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&b(t[0])&&"id"in t[0]&&t[0].id===3&&b(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(b(t)&&b(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(b(e)&&"arr"in e&&Array.isArray(e.arr)&&b(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&b(t[0])&&b(e[0])){let n=[...t];for(let i of e)if(b(i)&&"name"in i){if(!n.find((o)=>b(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(b(i)&&"path"in i){if(!n.find((o)=>b(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>De(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!b(t)||!b(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(b(i)&&b(r[n]))r[n]=bt(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&b(i[0])&&b(r[n][0])){let s=[...i];for(let o of r[n])if(b(o)&&"name"in o){if(!s.find((a)=>b(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(b(o)&&"path"in o){if(!s.find((a)=>b(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>De(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function De(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!De(e[r],t[r]))return!1;return!0}if(b(e)&&b(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!De(e[i],t[i]))return!1}return!0}return!1}function b(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Tn(e,t){if(!pr(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return bt(t,n)}catch{return null}}catch{return null}}async function Sn({name:e="",cwd:t,defaultConfig:r}){let n=t||ut.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=Be(n,`${o}${c}`),l=await Tn(a,r);if(l!==null)return l}try{let o=Be(n,"package.json");if(pr(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return bt(r,a)}catch{}}}catch{}return r}function kn(e,t={}){let r=Ne.cwd();while(r.includes("storage"))r=Bt(r,"..");let n=Bt(r,e||"");if(t?.relative)return en(Ne.cwd(),n);return n}async function An(){try{let e=await Sn({name:"clarity",defaultConfig:Ae,cwd:Ne.cwd(),endpoint:"",headers:{}});return{...Ae,...e}}catch{return Ae}}function T(){if(U.env.NODE_ENV==="test"||U.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Fn(){if(U.env.NODE_ENV==="test"||U.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof U<"u"){let e=U.type;if(e==="renderer"||e==="worker")return!1;return!!(U.versions&&(U.versions.node||U.versions.bun))}return!1}class yr{async format(e){let t=await Fn(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:re.pid,hostname:t(),environment:re.env.NODE_ENV||"development",platform:re.platform,version:re.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:re.env.NODE_ENV||re.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Me{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(e,t={}){this.name=e,this.config={...ht},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new yr,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Fe,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Fe};return{...Fe,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ht.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await on(this.config.logDirectory,It.F_OK|It.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await an(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:H.from(e);try{if(!He(this.currentLogFile))await qe(this.currentLogFile,"",{mode:420});if(i=Lt(this.currentLogFile,"a",420),sn(i,a,{flag:"a"}),Mt(i),i!==void 0)Je(i),i=void 0;if((await ee(this.currentLogFile)).size===0){if(await qe(this.currentLogFile,a,{flag:"w",mode:420}),(await ee(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{Je(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 te(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 te(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return te(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(T())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ge(16).toString("hex")}generateKey(){return Ge(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Ge(16),n=tn("aes-256-gcm",t,r),i=H.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:H.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=_t(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(H.from(H.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(T())return;let e=await ee(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await pe(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ee(r).catch(()=>null))try{if(await jt(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await ye(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await qe(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ee(r).catch(()=>null))await jt(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await pe(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await ye(te(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Dt(e),n=nn(t),i=_t();await cn(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),He(this.currentLogFile))try{let e=Lt(this.currentLogFile,"r+");Mt(e),Je(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!T()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await pe(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ye(te(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?E.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=O.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${E.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!T()){let l=kr[e],f=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:E.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:E.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.error(u),c){let h=c.split(`
|
|
2
|
+
`);for(let g of h)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:E.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!T()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
3
|
+
`;if(c)a+=`${c}
|
|
4
|
+
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!T()){let r=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:E.blue("◐"),tag:r,message:`${E.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
5
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!T()){let f=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:E.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!T())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Me(t,{...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(r),r}createReadStream(){if(T())throw Error("createReadStream is not supported in browser environments");if(!He(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Dt(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=H.isBuffer(e)?e:H.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=rn("aes-256-gcm",r,i);return c.setAuthTag(s),H.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T()}isServerMode(){return!T()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!T()){let s=e.split(`
|
|
6
|
+
`),o=Math.max(...s.map((f)=>f.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((f)=>{let u=" ".repeat(o-f.length-2);return`│ ${f}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:E.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:E.cyan(c)})),l.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:r,message:E.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:E.cyan(a),showTimestamp:!1}))}else if(!T())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
7
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(T())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${E.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();O.stdin.removeListener("data",r);try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!1)}catch{}O.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!0)}catch{}O.stdin.resume(),O.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let f=t[c++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!T()){let o=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",c=E.blue("◐");console.error(`${c} ${o} ${E.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||T()||e<=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 r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;O.stdout.write(`${"\r".padEnd(O.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||T()||!O.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=E.green("━".repeat(n)),o=E.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=t||r===100?E.green("✓"):E.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${E.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=O.stdout.columns||80,x=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${x}`,O.stdout.write(e.lastRenderedLine),t)O.stdout.write(`
|
|
9
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||T()||!O.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(T()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await pe(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=te(this.config.logDirectory,n);if(e.before)try{if((await ee(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ye(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ke(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&v(t[0])&&"id"in t[0]&&t[0].id===3&&v(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(v(t)&&v(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(v(e)&&"arr"in e&&Array.isArray(e.arr)&&v(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&v(t[0])&&v(e[0])){let n=[...t];for(let i of e)if(v(i)&&"name"in i){if(!n.find((o)=>v(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(v(i)&&"path"in i){if(!n.find((o)=>v(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>Le(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!v(t)||!v(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(v(i)&&v(r[n]))r[n]=ke(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&v(i[0])&&v(r[n][0])){let s=[...i];for(let o of r[n])if(v(o)&&"name"in o){if(!s.find((a)=>v(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(v(o)&&"path"in o){if(!s.find((a)=>v(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Le(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function xt(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ke(e,t);if(Array.isArray(e))return r==="replace"?t:ke(e,t);if(!v(t)||!v(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=ke(o,s);else if(v(s)&&v(o))n[i]=xt(o,s,r);else n[i]=s}return n}function Le(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Le(e[r],t[r]))return!1;return!0}if(v(e)&&v(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Le(e[i],t[i]))return!1}return!0}return!1}function v(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function be(e,t,r="replace"){if(!dr(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return xt(t,i,r)}catch{return null}}catch{return null}}function On(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=(m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase(),g=`${n}_${u.map(h).join("_")}`,x=`${n}_${u.map((m)=>m.toUpperCase()).join("_")}`;if(r)R.info(`Checking environment variable ${g} for config ${e}.${u.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))a[l]=s(f,u);else{let m=ue.env[g]||ue.env[x];if(m!==void 0){if(r)R.info(`Using environment variable ${m?g:x} for config ${e}.${u.join(".")}`);if(typeof f==="number")a[l]=Number(m);else if(typeof f==="boolean")a[l]=m.toLowerCase()==="true";else if(Array.isArray(f))try{let C=JSON.parse(m);if(Array.isArray(C))a[l]=C;else a[l]=m.split(",").map((N)=>N.trim())}catch{a[l]=m.split(",").map((C)=>C.trim())}else a[l]=m}}}return a}return s(i)}async function Pn({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?On(e,i,s):i,l=r||ue.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(s)R.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let u=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),g=t?[t,`.${t}`]:[],x=t?[`${t}.config`,`.${t}.config`]:[],m=Array.from(new Set([l,D(l,"config"),D(l,".config"),n?D(l,n):void 0].filter(Boolean)));for(let C of m){if(s)R.info(`Searching for configuration in: ${C}`);let B=[D(l,"config"),D(l,".config")].concat(n?[D(l,n)]:[]).includes(C)?[...u,...h,...g,...x]:[...h,...u,...x,...g];for(let W of B)for(let K of f){let j=D(C,`${W}${K}`),Ft=await be(j,a,c);if(Ft!==null){if(s)R.success(`Configuration loaded from: ${j}`);return Ft}}}if(e){let C=D(Ye(),".config",e),N=["config",`${e}.config`];if(t)N.push(`${t}.config`);if(s)R.info(`Checking user config directory: ${C}`);for(let B of N)for(let W of f){let K=D(C,`${B}${W}`),j=await be(K,a,c);if(j!==null){if(s)R.success(`Configuration loaded from user config directory: ${K}`);return j}}}if(e){let C=D(Ye(),".config"),N=[`.${e}.config`];if(t)N.push(`.${t}.config`);if(s)R.info(`Checking user config directory for dotfile configs: ${C}`);for(let B of N)for(let W of f){let K=D(C,`${B}${W}`),j=await be(K,a,c);if(j!==null){if(s)R.success(`Configuration loaded from user config directory dotfile: ${K}`);return j}}}if(e){let C=Ye(),N=[`.${e}.config`,`.${e}`];if(t)N.push(`.${t}.config`),N.push(`.${t}`);if(s)R.info(`Checking user home directory for dotfile configs: ${C}`);for(let B of N)for(let W of f){let K=D(C,`${B}${W}`),j=await be(K,a,c);if(j!==null){if(s)R.success(`Configuration loaded from user home directory: ${K}`);return j}}}try{let C=D(l,"package.json");if(dr(C)){let N=await import(C),B=N[e];if(!B&&t){if(B=N[t],B&&s)R.success(`Using alias "${t}" configuration from package.json`)}if(B&&typeof B==="object"&&!Array.isArray(B))try{if(s)R.success(`Configuration loaded from package.json: ${B===N[e]?e:t}`);return xt(a,B,c)}catch(W){if(s)R.warn("Failed to merge package.json config:",W)}}}catch(C){if(s)R.warn("Failed to load package.json:",C)}if(s)R.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function Rn(e,t={}){let r=Re.cwd();while(r.includes("storage"))r=Nt(r,"..");let n=Nt(r,e||"");if(t?.relative)return Xr(Re.cwd(),n);return n}async function Nn(){try{let e=await Pn({name:"clarity",alias:"logging",defaultConfig:Oe,cwd:Re.cwd()});return{...Oe,...e||{}}}catch{return Oe}}function S(){if(Y.env.NODE_ENV==="test"||Y.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Bn(){if(Y.env.NODE_ENV==="test"||Y.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Y<"u"){let e=Y.type;if(e==="renderer"||e==="worker")return!1;return!!(Y.versions&&(Y.versions.node||Y.versions.bun))}return!1}class wr{async format(e){let t=await Bn(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:se.pid,hostname:t(),environment:se.env.NODE_ENV||"development",platform:se.platform,version:se.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:se.env.NODE_ENV||se.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ie{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(e,t={}){this.name=e,this.config={...mt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new wr,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??d.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Pe,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Pe};return{...Pe,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:mt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!S()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await hn(this.config.logDirectory,zt.F_OK|zt.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await mn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:V.from(e);try{if(!we(this.currentLogFile))await Qe(this.currentLogFile,"",{mode:420});if(i=Vt(this.currentLogFile,"a",420),gn(i,a,{flag:"a"}),Wt(i),i!==void 0)Xe(i),i=void 0;if((await ne(this.currentLogFile)).size===0){if(await Qe(this.currentLogFile,a,{flag:"w",mode:420}),(await ne(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{Xe(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 ie(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 ie(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ie(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(S())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ze(16).toString("hex")}generateKey(){return Ze(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Ze(16),n=ln("aes-256-gcm",t,r),i=V.isBuffer(e)?e:V.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=V.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Yt(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(V.from(V.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(S())return;if(!this.shouldWriteToFile())return;let e=await ne(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await $e(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ne(r).catch(()=>null))try{if(await Ut(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await ve(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Qe(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ne(r).catch(()=>null))await Ut(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await $e(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await ve(ie(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Kt(e),n=un(t),i=Yt();await yn(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),we(this.currentLogFile))try{let e=Vt(this.currentLogFile,"r+");Wt(e),Xe(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await $e(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ve(ie(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?y.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||S())return!1;let e=typeof d.env.NO_COLOR<"u",t=d.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof d.stderr<"u"&&d.stderr.isTTY||typeof d.stdout<"u"&&d.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=d.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${y.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=y.underline(y.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>y.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>y.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>y.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>y.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>y.strikethrough(n)),t}supportsHyperlinks(){if(S())return!1;let e=d.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=d.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(dn(t)||t.startsWith("./")||t.startsWith("../"))t=pn(t);else return null;return we(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Ar[e],h=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:y.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:y.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.error(g),c){let x=c.split(`
|
|
10
|
+
`);for(let m of x)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:y.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
11
|
+
`;if(c)f+=`${c}
|
|
12
|
+
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!S()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!S()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!S()&&d.stdout.isTTY)d.stdout.write(`
|
|
13
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!S()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":y.blue("◐"),tag:r,message:`${y.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
14
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":y.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!S())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ie(t,{...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(r),r}createReadStream(){if(S())throw Error("createReadStream is not supported in browser environments");if(!we(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Kt(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=V.isBuffer(e)?e:V.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=fn("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),f=a.length+l.length,u=V.allocUnsafe(f);return a.copy(u,0),l.copy(u,a.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S()}isServerMode(){return!S()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
15
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,f=`└${"─".repeat(a)}┘`,u=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:y.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(f),showTimestamp:!1}))}else if(!S())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
16
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(S())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${y.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();d.stdin.removeListener("data",r);try{if(typeof d.stdin.setRawMode==="function")d.stdin.setRawMode(!1)}catch{}d.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof d.stdin.setRawMode==="function")d.stdin.setRawMode(!0)}catch{}d.stdin.resume(),d.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${y.blue("◐")} `;console.error(`${l}${a} ${y.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!d.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=y.green("━".repeat(n)),o=y.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?y.green("✓"):y.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${y.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=d.stdout.columns||80,x=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${x}`,d.stdout.write(e.lastRenderedLine),t)d.stdout.write(`
|
|
18
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||S()||!d.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await $e(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=ie(this.config.logDirectory,n);if(e.before)try{if((await ne(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await ve(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function $r(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function vr(e){return e instanceof L}function Dn(e){return e instanceof je}function Mn(e){if(vr(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class Ve{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=n||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return me.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((f)=>this.formatEnvKey(f,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let f=Ce.env[a]||(l?Ce.env[l]:void 0);if(f!==void 0){if(n.verbose){let u=Ce.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(f,typeof s,a,n.customParsers,n.configName)}catch(u){if(u instanceof _e)throw u;throw q.envVar(a,f,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw q.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Ce.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
19
|
+
|
|
20
|
+
`;for(let n of e)r+=`${n.key}
|
|
21
|
+
`,r+=` Type: ${n.type}
|
|
22
|
+
`,r+=` Description: ${n.description}
|
|
23
|
+
`,r+=` Example: ${n.example}
|
|
24
|
+
|
|
25
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
26
|
+
|
|
27
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
28
|
+
`,r+=`|----------|------|-------------|----------|
|
|
29
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
30
|
+
`;return r}}function Ln(e,t){let r=Tr("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Cr(e,t,r={}){return Er(e,t,r,new WeakMap)}function Er(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return br(e,t,i,n);if(!I(t)||!I(e))return t;return Kn(e,t,r,n)}function br(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return In(e,t);case"smart":return jn(e,t,n);default:return t}return t}function In(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>gt(i,n)))r.push(n);return r}function jn(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(I(t[0])&&I(e[0]))return _n(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function _n(e,t,r){let n=[...t];for(let i of e){if(!I(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>I(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function Kn(e,t,r,n){let i=t;if(I(i)&&n.has(i))return n.get(i);let s={...e};if(I(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(I(c)&&I(a))s[o]=Er(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=br(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function Tt(e,t,r="replace"){return Cr(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function gt(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!gt(e[r],t[r]))return!1;return!0}if(I(e)&&I(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!gt(e[i],t[i]))return!1}return!0}return!1}function I(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ze{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=le.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Ee(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,g=Object.keys(f).length>0;if(!h&&!g)throw new ge(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new ge(e,Error("Configuration must export a valid object"),"unknown");let C={config:Tt(t,u,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)le.setWithFileCheck("file",C,e,s);return C}catch(l){throw l instanceof Error?q.configLoad(e,l):q.configLoad(e,Error(String(l)))}};if(o)return me.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(et(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return $r(async()=>Ee(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Ee(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=et(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=et(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Ee(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class St{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(g){return f.push({path:"",message:`Validation failed: ${g}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(c)return await me.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!wn(t))throw new he(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new he(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Or},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class kt{fileLoader=new ze;envProcessor=new Ve;validator=new St;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let f=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),u=!f&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw a;if(u&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)_.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw _.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||X.cwd(),h=[],g=await this.loadLocalConfiguration(n,i,u,o,c,l,f,a,r);if(g)return h.push(...this.getLocalSearchPaths(n,i,u,o)),this.finalizeResult(g,h,a,n,f);let x=await this.loadHomeConfiguration(n,i,c,l,f,a);if(x)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(x,h,a,n,f);let m=await this.loadPackageJsonConfiguration(n,i,u,c,l,f,a);if(m)return h.push(M(u,"package.json")),this.finalizeResult(m,h,a,n,f);if(h.push(...this.getAllSearchPaths(n,i,u,o)),t)throw q.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,f),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?fe(e,i,o):i,f=this.getLocalDirectories(r,n);for(let u of f){if(o)_.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(g){if(o)_.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?fe(e,r,i):r,c=[M(Q(),".config",e),M(Q(),".config"),Q()];for(let a of c){if(i)_.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(f){if(i)_.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?fe(e,n,s):n;try{let a=M(r,"package.json");if(!ft(a))return null;let l=await import(a),f=l[e],u=e;if(!f&&t)f=l[t],u=t;if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)_.success(`Configuration loaded from package.json: ${u}`);return{config:Tt(c,f,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)_.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:fe(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw q.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return le.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);le.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,M(e,"config"),M(e,".config"),t?M(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(M(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[M(Q(),".config",e),M(Q(),".config"),Q()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Jt(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function Wn(e){return J.loadConfig({...e,__strictErrorHandling:!0})}async function xr(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await J.loadConfig(e);else n=await J.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)_.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await J.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Vn(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await J.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Jt(r)))return(await J.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await J.loadConfig({...e,cwd:e.cwd||X.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Jt(t)))return(await J.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function zn(e,t,r="replace"){let n=new ze;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function fe(e,t,r=!1){let n=new Ve,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=[`${i}_${u.join("_").toUpperCase()}`,`${i}_${u.map((m)=>m.toUpperCase()).join("")}`,`${i}_${u.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,x;for(let m of h)if(g=X.env[m],g!==void 0){x=m;break}if(g!==void 0&&x)if(typeof f==="boolean")a[l]=["true","1","yes"].includes(g.toLowerCase());else if(typeof f==="number"){let m=Number(g);if(!Number.isNaN(m))a[l]=m}else if(Array.isArray(f))try{a[l]=JSON.parse(g)}catch{a[l]=g.split(",").map((m)=>m.trim())}else a[l]=g;else if(f&&typeof f==="object"&&!Array.isArray(f))a[l]=s(f,u)}return a}return s(t)}function Un(e){let t=M(X.cwd(),e.configDir),r=M(X.cwd(),e.generatedDir),n=M(r,"config-types.ts");if(!ft(Rt(n)))Jr(Rt(n),{recursive:!0,mode:511});let i=ft(t)?Hr(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${vi}
|
|
31
|
+
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
32
|
+
`;qr(n,s,{mode:438})}function Yn(e){let t=null,r=null,n=()=>{if(!r)r=xr(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)_.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function Gn(e){let t=Gt(Cn.cwd(),e?.configDir||"./config");function r(){if(!$n(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=vn(t).filter((a)=>i.has(tt(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let f=tt(l).toLowerCase(),u=c.get(a);if(!u){c.set(a,l);continue}let h=tt(u).toLowerCase();if(s.indexOf(f)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=i.length?`{
|
|
33
|
+
${i.map((l)=>{let f=Gt(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
|
|
34
|
+
`)}
|
|
35
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
36
|
+
export type ConfigByName = ${c}
|
|
37
|
+
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
38
|
+
export type ConfigOf = Config
|
|
39
|
+
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}var Tr,le,me,Sr,Jn,Hn,Ht,Ae,ht,P,E,qn,qt,Zn,Zt,Xn,Qn,rt,ei,Xt,Qt,nt,ti,ri,ni,ii,Fe,kr,si,R,oi,ai,er,Oe,mt,k,y,ci,tr,li,rr,fi,ui,it,gi,nr,ir,hi,st,mi,di,pi,yi,wi,Pe,Ar,$i,vi="0.15.6",L,je,ge,dt,pt,_e,yt,wt,he,$t,vt,q,Fr,Or,_,J,Pr,Rr,Ci=Gr(async()=>{Tr=import.meta.require,le=new Ct,me=new Et,Sr={createKey:En,isEquivalent:bn,estimateMemoryUsage:xn},Jn=Be(ut.cwd(),"config"),Hn=Be(ut.cwd(),"src/generated"),Ht=Ne.env.CLARITY_LOG_DIR||Qr(kn(),"logs"),Ae={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ht,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},ht=await An(),P={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},E=P,qn=P.red,qt=P.green,Zn=P.yellow,Zt=P.blue,Xn=P.magenta,Qn=P.cyan,rt=P.white,ei=P.gray,Xt=P.bgRed,Qt=P.bgYellow,nt=P.bold,ti=P.dim,ri=P.italic,ni=P.underline,ii=P.reset,Fe={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},kr={debug:"\uD83D\uDD0D",info:Zt("ℹ"),success:qt("✓"),warning:Qt(rt(nt(" WARN "))),error:Xt(rt(nt(" ERROR ")))},si=new Me("stacks"),R=new Me("bunfig",{showTags:!0}),oi=D(ue.cwd(),"config"),ai=D(ue.cwd(),"src/generated"),er=Re.env.CLARITY_LOG_DIR||Zr(Rn(),"logs"),Oe={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:er,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mt=await Nn(),k={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},y=k,ci=k.red,tr=k.green,li=k.yellow,rr=k.blue,fi=k.magenta,ui=k.cyan,it=k.white,gi=k.gray,nr=k.bgRed,ir=k.bgYellow,hi=k.bgGray,st=k.bold,mi=k.dim,di=k.italic,pi=k.underline,yi=k.strikethrough,wi=k.reset,Pe={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ar={debug:"\uD83D\uDD0D",info:rr("ℹ"),success:tr("✓"),warning:ir(it(st(" WARN "))),error:nr(it(st(" ERROR ")))},$i=new Ie("stacks"),L=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,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 t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},je=class extends L{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},ge=class extends L{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},dt=class extends L{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},pt=class extends L{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},_e=class extends L{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},yt=class extends L{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},wt=class extends L{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},he=class extends L{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},$t=class extends L{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},vt=class extends L{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},q={configNotFound(e,t,r){return new je(e,t,r)},configLoad(e,t,r){return new ge(e,t,r)},configValidation(e,t,r){return new dt(e,t,r)},configMerge(e,t,r,n){return new pt(e,t,r,n)},envVar(e,t,r,n){return new _e(e,t,r,n)},fileSystem(e,t,r){return new yt(e,t,r)},typeGeneration(e,t,r){return new wt(e,t,r)},schemaValidation(e,t,r){return new he(e,t,r)},browserConfig(e,t,r,n){return new $t(e,t,r,n)},plugin(e,t,r){return new vt(e,t,r)}},Fr={replace:"replace",concat:"concat",smart:"smart"},Or=/^https?:\/\//,_=new Ie("bunfig",{showTags:!0}),J=new kt,Pr=M(X.cwd(),"config"),Rr=M(X.cwd(),"src/generated")});function xi(e,t={}){let r=Ke.cwd();while(r.includes("storage"))r=sr(r,"..");let n=sr(r,e||"");if(t?.relative)return bi(Ke.cwd(),n);return n}var Ti=Ke.env.CLARITY_LOG_DIR||Ei(xi(),"logs"),Nr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ti,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},We={...Nr},Ys=(async()=>{try{let{loadConfig:e}=await Ci().then(()=>mr),t=await e({name:"clarity",alias:"logging",defaultConfig:Nr,cwd:Ke.cwd()});if(t)Object.assign(We,t)}catch{}return We})();function A(){if(G.env.NODE_ENV==="test"||G.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Di(){if(G.env.NODE_ENV==="test"||G.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof G<"u"){let e=G.type;if(e==="renderer"||e==="worker")return!1;return!!(G.versions&&(G.versions.node||G.versions.bun))}return!1}class Br{async format(e){let t=await Di(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ce.pid,hostname:t(),environment:ce.env.NODE_ENV||"development",platform:ce.platform,version:ce.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ce.env.NODE_ENV||ce.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var F={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},w=F,no=F.red,Mi=F.green,io=F.yellow,Li=F.blue,so=F.magenta,oo=F.cyan,gr=F.white,ao=F.gray,Ii=F.bgRed,ji=F.bgYellow,co=F.bgGray,hr=F.bold,lo=F.dim,fo=F.italic,uo=F.underline,go=F.strikethrough,ho=F.reset,lt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_i={debug:"\uD83D\uDD0D",info:Li("ℹ"),success:Mi("✓"),warning:ji(gr(hr(" WARN "))),error:Ii(gr(hr(" ERROR ")))};class de{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(e,t={}){this.name=e,this.config={...We},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Br,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??p.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...lt,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...lt};return{...lt,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:We.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!A()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await Oi(this.config.logDirectory,lr.F_OK|lr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Pi(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:z.from(e);try{if(!xe(this.currentLogFile))await ct(this.currentLogFile,"",{mode:420});if(i=cr(this.currentLogFile,"a",420),Fi(i,a,{flag:"a"}),ar(i),i!==void 0)at(i),i=void 0;if((await oe(this.currentLogFile)).size===0){if(await ct(this.currentLogFile,a,{flag:"w",mode:420}),(await oe(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{at(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 ae(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 ae(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ae(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(A())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ot(16).toString("hex")}generateKey(){return ot(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=ot(16),n=Si("aes-256-gcm",t,r),i=z.isBuffer(e)?e:z.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=z.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ur(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(z.from(z.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(A())return;if(!this.shouldWriteToFile())return;let e=await oe(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Te(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await oe(r).catch(()=>null))try{if(await fr(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Se(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ct(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await oe(r).catch(()=>null))await fr(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Te(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Se(ae(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=or(e),n=Ai(t),i=ur();await Bi(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),xe(this.currentLogFile))try{let e=cr(this.currentLogFile,"r+");ar(e),at(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!A()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Te(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Se(ae(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?w.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||A())return!1;let e=typeof p.env.NO_COLOR<"u",t=p.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof p.stderr<"u"&&p.stderr.isTTY||typeof p.stdout<"u"&&p.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=p.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${w.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=w.underline(w.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>w.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>w.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>w.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>w.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>w.strikethrough(n)),t}supportsHyperlinks(){if(A())return!1;let e=p.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=p.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Ri(t)||t.startsWith("./")||t.startsWith("../"))t=Ni(t);else return null;return xe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":_i[e],h=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:w.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:w.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.error(g),c){let x=c.split(`
|
|
40
|
+
`);for(let m of x)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:w.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!A()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
41
|
+
`;if(c)f+=`${c}
|
|
42
|
+
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!A()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!A()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!A()&&p.stdout.isTTY)p.stdout.write(`
|
|
43
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!A()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":w.blue("◐"),tag:r,message:`${w.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
44
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":w.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!A())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new de(t,{...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(r),r}createReadStream(){if(A())throw Error("createReadStream is not supported in browser environments");if(!xe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return or(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=z.isBuffer(e)?e:z.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=ki("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),f=a.length+l.length,u=z.allocUnsafe(f);return a.copy(u,0),l.copy(u,a.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return A()}isServerMode(){return!A()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
45
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,f=`└${"─".repeat(a)}┘`,u=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:w.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:w.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:w.cyan(f),showTimestamp:!1}))}else if(!A())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
46
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(A())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${w.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();p.stdin.removeListener("data",r);try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!1)}catch{}p.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!0)}catch{}p.stdin.resume(),p.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${w.blue("◐")} `;console.error(`${l}${a} ${w.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!p.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=w.green("━".repeat(n)),o=w.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?w.green("✓"):w.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=p.stdout.columns||80,x=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${x}`,p.stdout.write(e.lastRenderedLine),t)p.stdout.write(`
|
|
48
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||A()||!p.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(A()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Te(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=ae(this.config.logDirectory,n);if(e.before)try{if((await oe(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Se(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var mo=new de("stacks");var Ki=new de("rpx",{showTags:!1});function Ir(){return process.env.SUDO_PASSWORD}function jr(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function $o(e={}){if(process.platform==="win32")return!0;if(jr()||!!Ir())return!0;let t=e.exec??Ue;try{return t("sudo -n true",{stdio:"ignore"}),!0}catch{if(!e.interactive)return!1}try{return t("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function vo(e){if(jr())return Ue(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let t=Ir(),r=e.replace(/'/g,"'\\''");if(t)return Ue(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return Ue(`sudo -n sh -c '${r}'`,{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 Dr(e,t,r){if(r)Ki.debug(`[rpx:${e}] ${t}`)}function Co(){let e=process.env.RPX_REUSE_PORT;return e==="1"||e==="true"}var Mr="[redacted]",Wi=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Vi=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function zi(e){let t=e.toLowerCase();return Wi.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function At(e){if(Array.isArray(e))return e.map((r)=>At(r));if(typeof e==="string")return Vi.test(e)?Mr:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e)){if(zi(r)){t[r]=Mr;continue}t[r]=At(n)}return t}function Eo(e,t){return JSON.stringify(At(e),null,t)}function bo(e){if(_r(e))return e.proxies.map((t)=>{let r=t.to||"stacks.localhost";return r.startsWith("http")?new URL(r).hostname:r});if(Kr(e)){let t=e.to||"stacks.localhost";return[t.startsWith("http")?new URL(t).hostname:t]}return["stacks.localhost"]}function xo(e){return typeof e==="object"&&e!==null&&"certificate"in e&&"privateKey"in e&&typeof e.certificate==="string"&&typeof e.privateKey==="string"}function To(e){if(!e)return"stacks.localhost";if(_r(e)&&e.proxies.length>0)return e.proxies[0].to||"stacks.localhost";if(Kr(e))return e.to||"stacks.localhost";return"stacks.localhost"}function So(e){return!!(e&&("proxies"in e)&&Array.isArray(e.proxies))}function _r(e){return"proxies"in e&&Array.isArray(e.proxies)}function Kr(e){return"to"in e&&typeof e.to==="string"}function ko(e){return!!(e&&("to"in e)&&!("proxies"in e))}function Ao(e,t){if(!t||t.length===0)return null;for(let r of t)if(e===r.from||e.startsWith(`${r.from}/`)){let n=r.to.startsWith("http")?new URL(r.to).host:r.to,i=r.stripPrefix===!0?e.slice(r.from.length)||"/":e;return{targetHost:n,targetPath:i}}return null}async function Fo(e,t){try{await Lr.unlink(e),Dr("certificates",`Successfully deleted: ${e}`,t)}catch(r){if(r.code!=="ENOENT")Dr("certificates",`Warning: Could not delete ${e}: ${r}`,t)}}
|
|
49
|
+
export{Z as Ab,Ir as Bb,jr as Cb,$o as Db,vo as Eb,Dr as Fb,Co as Gb,At as Hb,Eo as Ib,bo as Jb,xo as Kb,To as Lb,So as Mb,_r as Nb,Kr as Ob,ko as Pb,Ao as Qb,Fo as Rb};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Bb as a,Cb as b,Db as c,Eb as d,Fb as e,Gb as f,Hb as g,Ib as h,Jb as i,Kb as j,Lb as k,Mb as l,Nb as m,Ob as n,Pb as o,Qb as p,Rb as q}from"./chunk-nnnptjfw.js";export{c as authorizeSystemAccess,e as debugLog,d as execSudoSync,i as extractHostname,k as getPrimaryDomain,a as getSudoPassword,l as isMultiProxyConfig,m as isMultiProxyOptions,b as isProcessElevated,o as isSingleProxyConfig,n as isSingleProxyOptions,j as isValidRootCA,g as redactSensitive,p as resolvePathRewrite,q as safeDeleteFile,h as safeStringify,f as shouldReusePort};
|