pickier 0.1.64 → 0.1.66

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.
@@ -1,62 +0,0 @@
1
- // @bun
2
- import{Q as q}from"./chunk-awmb5sg5.js";import{existsSync as Gt,statSync as Yt}from"fs";import{existsSync as vn,mkdirSync as Oi,readdirSync as Ri,readFileSync as $n,writeFileSync as Ni}from"fs";import{homedir as ne}from"os";import{dirname as Mi,resolve as B}from"path";import et from"process";import{existsSync as Ht,statSync as Zt}from"fs";import{existsSync as xt,mkdirSync as bn,readdirSync as Cn,writeFileSync as En}from"fs";import{homedir as se}from"os";import{dirname as Xt,resolve as j}from"path";import re from"process";import{join as xn,relative as kn,resolve as Qt}from"path";import Ke from"process";import{existsSync as jr,mkdirSync as Ui,readdirSync as qi,writeFileSync as Ji}from"fs";import{homedir as st}from"os";import{dirname as Hi,resolve as M}from"path";import ye from"process";import{join as Sn,relative as Tn,resolve as er}from"path";import Ve from"process";import{existsSync as Lr,mkdirSync as to,readdirSync as ro,writeFileSync as no}from"fs";import{dirname as io,resolve as We}from"path";import kt from"process";import{Buffer as ee}from"buffer";import{createCipheriv as An,createDecipheriv as Fn,randomBytes as it}from"crypto";import{closeSync as ot,createReadStream as tr,createWriteStream as On,existsSync as at,fsyncSync as rr,openSync as nr,writeFileSync as Rn}from"fs";import{access as Nn,constants as sr,mkdir as Pn,readdir as be,rename as ir,stat as ie,unlink as Ce,writeFile as ct}from"fs/promises";import{join as oe}from"path";import O from"process";import{pipeline as Dn}from"stream/promises";import{createGzip as or}from"zlib";import ae from"process";import H from"process";import{Buffer as G}from"buffer";import{createCipheriv as Mn,createDecipheriv as jn,randomBytes as lt}from"crypto";import{closeSync as ft,createReadStream as ar,createWriteStream as Ln,existsSync as Ee,fsyncSync as cr,openSync as lr,writeFileSync as Bn}from"fs";import{access as In,constants as fr,mkdir as _n,readdir as xe,rename as ur,stat as ce,unlink as ke,writeFile as ut}from"fs/promises";import{isAbsolute as Kn,join as le,resolve as Vn}from"path";import d from"process";import{pipeline as Wn}from"stream/promises";import{createGzip as gr}from"zlib";import fe from"process";import Z from"process";import Se from"process";import{existsSync as Te}from"fs";import{resolve as gt}from"path";import{existsSync as zn}from"fs";import{existsSync as Un,readdirSync as qn}from"fs";import{extname as ht,resolve as hr}from"path";import Jn from"process";import{join as Gn,relative as Yn,resolve as mr}from"path";import ze from"process";import{Buffer as Y}from"buffer";import{createCipheriv as Hn,createDecipheriv as Zn,randomBytes as mt}from"crypto";import{closeSync as dt,createReadStream as dr,createWriteStream as Xn,existsSync as Ae,fsyncSync as pr,openSync as yr,writeFileSync as Qn}from"fs";import{access as es,constants as wr,mkdir as ts,readdir as Fe,rename as vr,stat as ue,unlink as Oe,writeFile as pt}from"fs/promises";import{isAbsolute as rs,join as ge,resolve as ns}from"path";import p from"process";import{pipeline as ss}from"stream/promises";import{createGzip as $r}from"zlib";import he from"process";import X from"process";import Ne from"process";import{existsSync as Pe}from"fs";import{resolve as Ct}from"path";import{existsSync as xi}from"fs";class Dr{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 s=this.generateKey(e,r),i=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:i,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(!Gt(e))return!0;return Yt(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 s=Gt(r)?Yt(r):null,i=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},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,s)=>n+s.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 Mr{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),s=new Date;try{let i=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:s,...r}),i}catch(i){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:s,...r}),i}}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((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((s)=>s.duration),n=r.reduce((s,i)=>s+i,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)}}var _e=new Dr,jt=new Mr;var is=Object.defineProperty,os=(e)=>e;function as(e,t){this[e]=os.bind(null,t)}var cs=(e,t)=>{for(var r in t)is(e,r,{get:t[r],enumerable:!0,configurable:!0,set:as.bind(t,r)})},ls=(e,t)=>()=>(e&&(t=e(e=0)),t),Br={};cs(Br,{withErrorRecovery:()=>Kr,tryLoadConfig:()=>Ns,loadConfigWithResult:()=>Os,loadConfig:()=>qr,isRetryableError:()=>xs,isConfigNotFoundError:()=>Es,isBunfigError:()=>Vr,globalPerformanceMonitor:()=>$e,globalCache:()=>me,getEnvOrDefault:()=>ks,generateConfigTypes:()=>Ps,defaultGeneratedDir:()=>en,defaultConfigDir:()=>Qr,deepMergeWithArrayStrategy:()=>Kt,deepMerge:()=>Wr,createLibraryConfig:()=>Ds,config:()=>Rs,bunfigPlugin:()=>Ms,applyEnvVarsToConfig:()=>pe,TypeGenerationError:()=>Nt,SchemaValidationError:()=>ve,PluginError:()=>Dt,PerformanceMonitor:()=>Bt,FileSystemError:()=>Rt,ErrorFactory:()=>te,EnvVarError:()=>He,EnvProcessor:()=>tt,ConfigValidator:()=>Vt,ConfigValidationError:()=>Ft,ConfigNotFoundError:()=>Ye,ConfigMergeError:()=>Ot,ConfigLoader:()=>Wt,ConfigLoadError:()=>we,ConfigFileLoader:()=>rt,ConfigCache:()=>Lt,CacheUtils:()=>Gr,BunfigError:()=>L,BrowserConfigError:()=>Pt,ArrayMergeStrategies:()=>Zr});class Lt{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 s=this.generateKey(e,r),i=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:i,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(!Ht(e))return!0;return Zt(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 s=Ht(r)?Zt(r):null,i=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},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,s)=>n+s.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 Bt{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),s=new Date;try{let i=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:s,...r}),i}catch(i){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:s,...r}),i}}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((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((s)=>s.duration),n=r.reduce((s,i)=>s+i,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 fs(e,t={}){let n=Object.keys(t).sort().map((s)=>`${s}:${t[s]}`).join("|");return n?`${e}:${n}`:e}function us(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function gs(e){return e.getStats().size*2}function It(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&x(t[0])&&"id"in t[0]&&t[0].id===3&&x(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(x(t)&&x(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(x(e)&&"arr"in e&&Array.isArray(e.arr)&&x(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&x(t[0])&&x(e[0])){let n=[...t];for(let s of e)if(x(s)&&"name"in s){if(!n.find((o)=>x(o)&&("name"in o)&&o.name===s.name))n.push(s)}else if(x(s)&&"path"in s){if(!n.find((o)=>x(o)&&("path"in o)&&o.path===s.path))n.push(s)}else if(!n.some((i)=>Ue(i,s)))n.push(s);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let s of e)if(!n.includes(s))n.push(s);return n}return t}if(!x(t)||!x(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let s=t[n];if(s===null||s===void 0)continue;else if(x(s)&&x(r[n]))r[n]=It(r[n],s);else if(Array.isArray(s)&&Array.isArray(r[n]))if(s.length>0&&r[n].length>0&&x(s[0])&&x(r[n][0])){let i=[...s];for(let o of r[n])if(x(o)&&"name"in o){if(!i.find((a)=>x(a)&&("name"in a)&&a.name===o.name))i.push(o)}else if(x(o)&&"path"in o){if(!i.find((a)=>x(a)&&("path"in a)&&a.path===o.path))i.push(o)}else if(!i.some((c)=>Ue(c,o)))i.push(o);r[n]=i}else if(s.every((i)=>typeof i==="string")&&r[n].every((i)=>typeof i==="string")){let i=[...s];for(let o of r[n])if(!i.includes(o))i.push(o);r[n]=i}else r[n]=s;else r[n]=s}return r}function Ue(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(!Ue(e[r],t[r]))return!1;return!0}if(x(e)&&x(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Ue(e[s],t[s]))return!1}return!0}return!1}function x(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function hs(e,t){if(!Lr(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 It(t,n)}catch{return null}}catch{return null}}async function ms({name:e="",cwd:t,defaultConfig:r}){let n=t||kt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],i=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of i)for(let c of s){let a=We(n,`${o}${c}`),l=await hs(a,r);if(l!==null)return l}try{let o=We(n,"package.json");if(Lr(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return It(r,a)}catch{}}}catch{}return r}function ds(e,t={}){let r=Ve.cwd();while(r.includes("storage"))r=er(r,"..");let n=er(r,e||"");if(t?.relative)return Tn(Ve.cwd(),n);return n}async function ps(){try{let e=await ms({name:"clarity",defaultConfig:je,cwd:Ve.cwd(),endpoint:"",headers:{}});return{...je,...e}}catch{return je}}function k(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ys(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof H<"u"){let e=H.type;if(e==="renderer"||e==="worker")return!1;return!!(H.versions&&(H.versions.node||H.versions.bun))}return!1}class Ir{async format(e){let t=await ys(),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:ae.pid,hostname:t(),environment:ae.env.NODE_ENV||"development",platform:ae.platform,version:ae.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ae.env.NODE_ENV||ae.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qe{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={...Tt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ir,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 s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Le,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Le};return{...Le,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Tt.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 s,i=0,o=3,c=1000;while(i<o)try{try{try{await Nn(this.config.logDirectory,sr.F_OK|sr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Pn(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:ee.from(e);try{if(!at(this.currentLogFile))await ct(this.currentLogFile,"",{mode:420});if(s=nr(this.currentLogFile,"a",420),Rn(s,a,{flag:"a"}),rr(s),s!==void 0)ot(s),s=void 0;if((await ie(this.currentLogFile)).size===0){if(await ct(this.currentLogFile,a,{flag:"w",mode:420}),(await ie(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(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=c*2**i;await new Promise((g)=>setTimeout(g,h)),i++;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(s!==void 0)try{ot(s)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(i===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}i++;let l=c*2**(i-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}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 oe(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 oe(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return oe(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(k())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((s)=>{console.error("Error rotating keys:",s)})},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 s=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[c]of s.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return it(16).toString("hex")}generateKey(){return it(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=it(16),n=An("aes-256-gcm",t,r),s=ee.concat([n.update(e,"utf8"),n.final()]),i=n.getAuthTag();return{encrypted:ee.concat([r,s,i]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=or(),s=[];n.on("data",(i)=>s.push(i)),n.on("end",()=>t(ee.from(ee.concat(s)))),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(k())return;let e=await ie(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 s=await be(this.config.logDirectory),i=s.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=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ie(r).catch(()=>null))try{if(await ir(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ce(c)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.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 s=new Date().toISOString().replace(/[:.]/g,"-"),i=r.replace(/\.log$/,`-${s}.log`);if(await ie(r).catch(()=>null))await ir(r,i)}if(this.currentLogFile=n,t.maxFiles){let i=(await be(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of i.slice(t.maxFiles))await Ce(oe(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=tr(e),n=On(t),s=or();await Dn(r,s,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()})),at(this.currentLogFile))try{let e=nr(this.currentLogFile,"r+");rr(e),ot(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(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await be(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ce(oe(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:s,level:i,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(i==="warning")g.push("WARN");else if(i==="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(s),g.join(" ")}let a=O.stdout.columns||120,l="";if(i==="warning"||i==="error")l=`${r} ${s}`;else if(i==="info"||i==="success")l=`${r} ${n} ${s}`;else l=`${r} ${n} ${E.cyan(s)}`;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,(i,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):i});let r=/%([sdijfo%])/g,n=0,s=e.replace(r,(i,o)=>{if(o==="%")return"%";if(n>=t.length)return i;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 i}});if(n<t.length)s+=` ${t.slice(n).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}async log(e,t,...r){let n=new Date,s=this.formatConsoleTimestamp(n),i=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!k()){let l=Yr[e],f=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:E.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:E.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:s,icon:l,tag:f,message:o,level:e}),console.error(u),c){let h=c.split(`
3
- `);for(let g of h)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:s,message:E.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${i} ${this.environment}.${e.toUpperCase()}: ${o}
4
- `;if(c)a+=`${c}
5
- `;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!k()){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("\u25D0"),tag:r,message:`${E.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),s=Math.round(n-t),i=`${e} completed in ${s}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
6
- `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!k()){let f=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:E.green("\u2713"),tag:f,message:`${i}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!k())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 qe(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(k())throw Error("createReadStream is not supported in browser environments");if(!at(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return tr(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=ee.isBuffer(e)?e:ee.from(e,"base64"),s=n.slice(0,16),i=n.slice(-16),o=n.slice(16,-16),c=Fn("aes-256-gcm",r,s);return c.setAuthTag(i),ee.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 k()}isServerMode(){return!k()}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&&!k()){let i=e.split(`
7
- `),o=Math.max(...i.map((f)=>f.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,a=`\u2514${"\u2500".repeat(o)}\u2518`,l=i.map((f)=>{let u=" ".repeat(o-f.length-2);return`\u2502 ${f}${u} \u2502`});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(!k())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let s=`${n} ${this.environment}.INFO: [BOX] ${e}
8
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}async prompt(e){if(k())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${E.cyan("?")} ${e} (y/n) `);let r=(n)=>{let s=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(s==="y"||s==="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&&!k()){let o=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",c=E.blue("\u25D0");console.error(`${c} ${o} ${E.cyan(r)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
9
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||k()||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||k())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||k())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||k())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||k()||!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),s=e.barLength-n,i=E.green("\u2501".repeat(n)),o=E.gray("\u2501".repeat(s)),c=`[${i}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=t||r===100?E.green("\u2713"):E.blue("\u25B6"),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,b=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${b}`,O.stdout.write(e.lastRenderedLine),t)O.stdout.write(`
10
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||k()||!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(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await be(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 i=oe(this.config.logDirectory,n);if(e.before)try{if((await ie(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}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 Ce(n),console.warn(`Deleted log file: ${n}`)}catch(s){console.error(`Failed to delete log file ${n}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Me(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&C(t[0])&&"id"in t[0]&&t[0].id===3&&C(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(C(t)&&C(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(C(e)&&"arr"in e&&Array.isArray(e.arr)&&C(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&C(t[0])&&C(e[0])){let n=[...t];for(let s of e)if(C(s)&&"name"in s){if(!n.find((o)=>C(o)&&("name"in o)&&o.name===s.name))n.push(s)}else if(C(s)&&"path"in s){if(!n.find((o)=>C(o)&&("path"in o)&&o.path===s.path))n.push(s)}else if(!n.some((i)=>Je(i,s)))n.push(s);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let s of e)if(!n.includes(s))n.push(s);return n}return t}if(!C(t)||!C(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let s=t[n];if(s===null||s===void 0)continue;else if(C(s)&&C(r[n]))r[n]=Me(r[n],s);else if(Array.isArray(s)&&Array.isArray(r[n]))if(s.length>0&&r[n].length>0&&C(s[0])&&C(r[n][0])){let i=[...s];for(let o of r[n])if(C(o)&&"name"in o){if(!i.find((a)=>C(a)&&("name"in a)&&a.name===o.name))i.push(o)}else if(C(o)&&"path"in o){if(!i.find((a)=>C(a)&&("path"in a)&&a.path===o.path))i.push(o)}else if(!i.some((c)=>Je(c,o)))i.push(o);r[n]=i}else if(s.every((i)=>typeof i==="string")&&r[n].every((i)=>typeof i==="string")){let i=[...s];for(let o of r[n])if(!i.includes(o))i.push(o);r[n]=i}else r[n]=s;else r[n]=s}return r}function _t(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Me(e,t);if(Array.isArray(e))return r==="replace"?t:Me(e,t);if(!C(t)||!C(e))return t;let n={...e};for(let s of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let i=t[s],o=n[s];if(i===null||i===void 0)continue;if(Array.isArray(i)||Array.isArray(o))if(r==="replace")n[s]=i;else n[s]=Me(o,i);else if(C(i)&&C(o))n[s]=_t(o,i,r);else n[s]=i}return n}function Je(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(!Je(e[r],t[r]))return!1;return!0}if(C(e)&&C(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Je(e[s],t[s]))return!1}return!0}return!1}function C(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Re(e,t,r="replace"){if(!jr(e))return null;try{let n=await import(e),s=n.default||n;if(typeof s!=="object"||s===null||Array.isArray(s))return null;try{return _t(t,s,r)}catch{return null}}catch{return null}}function ws(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),s={...t};function i(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("_")}`,b=`${n}_${u.map((m)=>m.toUpperCase()).join("_")}`;if(r)N.info(`Checking environment variable ${g} for config ${e}.${u.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))a[l]=i(f,u);else{let m=ye.env[g]||ye.env[b];if(m!==void 0){if(r)N.info(`Using environment variable ${m?g:b} 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 w=JSON.parse(m);if(Array.isArray(w))a[l]=w;else a[l]=m.split(",").map((P)=>P.trim())}catch{a[l]=m.split(",").map((w)=>w.trim())}else a[l]=m}}}return a}return i(s)}async function vs({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:s,verbose:i=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof s==="object"&&s!==null&&!Array.isArray(s)?ws(e,s,i):s,l=r||ye.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(i)N.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}`]:[],b=t?[`${t}.config`,`.${t}.config`]:[],m=Array.from(new Set([l,M(l,"config"),M(l,".config"),n?M(l,n):void 0].filter(Boolean)));for(let w of m){if(i)N.info(`Searching for configuration in: ${w}`);let D=[M(l,"config"),M(l,".config")].concat(n?[M(l,n)]:[]).includes(w)?[...u,...h,...g,...b]:[...h,...u,...b,...g];for(let J of D)for(let z of f){let K=M(w,`${J}${z}`),Jt=await Re(K,a,c);if(Jt!==null){if(i)N.success(`Configuration loaded from: ${K}`);return Jt}}}if(e){let w=M(st(),".config",e),P=["config",`${e}.config`];if(t)P.push(`${t}.config`);if(i)N.info(`Checking user config directory: ${w}`);for(let D of P)for(let J of f){let z=M(w,`${D}${J}`),K=await Re(z,a,c);if(K!==null){if(i)N.success(`Configuration loaded from user config directory: ${z}`);return K}}}if(e){let w=M(st(),".config"),P=[`.${e}.config`];if(t)P.push(`.${t}.config`);if(i)N.info(`Checking user config directory for dotfile configs: ${w}`);for(let D of P)for(let J of f){let z=M(w,`${D}${J}`),K=await Re(z,a,c);if(K!==null){if(i)N.success(`Configuration loaded from user config directory dotfile: ${z}`);return K}}}if(e){let w=st(),P=[`.${e}.config`,`.${e}`];if(t)P.push(`.${t}.config`),P.push(`.${t}`);if(i)N.info(`Checking user home directory for dotfile configs: ${w}`);for(let D of P)for(let J of f){let z=M(w,`${D}${J}`),K=await Re(z,a,c);if(K!==null){if(i)N.success(`Configuration loaded from user home directory: ${z}`);return K}}}try{let w=M(l,"package.json");if(jr(w)){let P=await import(w),D=P[e];if(!D&&t){if(D=P[t],D&&i)N.success(`Using alias "${t}" configuration from package.json`)}if(D&&typeof D==="object"&&!Array.isArray(D))try{if(i)N.success(`Configuration loaded from package.json: ${D===P[e]?e:t}`);return _t(a,D,c)}catch(J){if(i)N.warn("Failed to merge package.json config:",J)}}}catch(w){if(i)N.warn("Failed to load package.json:",w)}if(i)N.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function $s(e,t={}){let r=Ke.cwd();while(r.includes("storage"))r=Qt(r,"..");let n=Qt(r,e||"");if(t?.relative)return kn(Ke.cwd(),n);return n}async function bs(){try{let e=await vs({name:"clarity",alias:"logging",defaultConfig:Be,cwd:Ke.cwd()});return{...Be,...e||{}}}catch{return Be}}function S(){if(Z.env.NODE_ENV==="test"||Z.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Cs(){if(Z.env.NODE_ENV==="test"||Z.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z<"u"){let e=Z.type;if(e==="renderer"||e==="worker")return!1;return!!(Z.versions&&(Z.versions.node||Z.versions.bun))}return!1}class _r{async format(e){let t=await Cs(),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:fe.pid,hostname:t(),environment:fe.env.NODE_ENV||"development",platform:fe.platform,version:fe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:fe.env.NODE_ENV||fe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ge{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={...At},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new _r,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 s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,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{...Ie,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ie};return{...Ie,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:At.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 s,i=0,o=3,c=1000;while(i<o)try{try{try{await In(this.config.logDirectory,fr.F_OK|fr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await _n(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:G.from(e);try{if(!Ee(this.currentLogFile))await ut(this.currentLogFile,"",{mode:420});if(s=lr(this.currentLogFile,"a",420),Bn(s,a,{flag:"a"}),cr(s),s!==void 0)ft(s),s=void 0;if((await ce(this.currentLogFile)).size===0){if(await ut(this.currentLogFile,a,{flag:"w",mode:420}),(await ce(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(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=c*2**i;await new Promise((g)=>setTimeout(g,h)),i++;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(s!==void 0)try{ft(s)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(i===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}i++;let l=c*2**(i-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}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 le(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 le(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return le(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((s)=>{console.error("Error rotating keys:",s)})},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 s=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[c]of s.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return lt(16).toString("hex")}generateKey(){return lt(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=lt(16),n=Mn("aes-256-gcm",t,r),s=G.isBuffer(e)?e:G.from(e,"utf8"),i=n.update(s),o=n.final(),c=i.length+o.length,a=n.getAuthTag(),l=G.allocUnsafe(16+c+16);return r.copy(l,0),i.copy(l,16),o.copy(l,16+i.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=gr(),s=[];n.on("data",(i)=>s.push(i)),n.on("end",()=>t(G.from(G.concat(s)))),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 ce(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 s=await xe(this.config.logDirectory),i=s.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=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ce(r).catch(()=>null))try{if(await ur(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await ke(c)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ut(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 s=new Date().toISOString().replace(/[:.]/g,"-"),i=r.replace(/\.log$/,`-${s}.log`);if(await ce(r).catch(()=>null))await ur(r,i)}if(this.currentLogFile=n,t.maxFiles){let i=(await xe(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of i.slice(t.maxFiles))await ke(le(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=ar(e),n=Ln(t),s=gr();await Wn(r,s,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()})),Ee(this.currentLogFile))try{let e=lr(this.currentLogFile,"r+");cr(e),ft(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 xe(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ke(le(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:s,level:i,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(i==="warning")g.push("WARN");else if(i==="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(s),g.join(" ")}let a=d.stdout.columns||120,l="";if(i==="warning"||i==="error")l=`${r} ${s}`;else if(i==="info"||i==="success")l=`${r} ${n} ${s}`;else l=`${r} ${n} ${y.cyan(s)}`;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,(i,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):i});let r=/%([sdijfo%])/g,n=0,s=e.replace(r,(i,o)=>{if(o==="%")return"%";if(n>=t.length)return i;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 i}});if(n<t.length)s+=` ${t.slice(n).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,s)=>{let i=y.underline(y.blue(n)),o=this.toAbsoluteFilePath(s);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${i}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${i}\x1B]8;;\x1B\\`;return i}),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(Kn(t)||t.startsWith("./")||t.startsWith("../"))t=Vn(t);else return null;return Ee(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,s=this.formatConsoleTimestamp(n),i=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?"":Hr[e],h=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:s,icon:u,tag:h,message:y.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:s,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:s,icon:u,tag:h,message:y.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:s,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:s,icon:u,tag:h,message:a,level:e}),console.error(g),c){let b=c.split(`
11
- `);for(let m of b)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:s,message:y.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let f=`${i} ${this.environment}.${e.toUpperCase()}: ${l}
12
- `;if(c)f+=`${c}
13
- `;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(`
14
- `);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("\u25D0"),tag:r,message:`${y.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),s=Math.round(n-t),i=`${e} completed in ${s}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
15
- `,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("\u2713"),tag:f,message:`${i}${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 Ge(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(!Ee(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ar(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=G.isBuffer(e)?e:G.from(e,"base64"),s=n.subarray(0,16),i=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=jn("aes-256-gcm",r,s);c.setAuthTag(i);let a=c.update(o),l=c.final(),f=a.length+l.length,u=G.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:s,fileText:i}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=s.split(`
16
- `),a=Math.max(...c.map((h)=>h.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,f=`\u2514${"\u2500".repeat(a)}\u2518`,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] ${i}`);let o=`${n} ${this.environment}.INFO: [BOX] ${i}
17
- `.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 s=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(s==="y"||s==="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:s}=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("\u25D0")} `;console.error(`${l}${a} ${y.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
18
- `.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),s=e.barLength-n,i=y.green("\u2501".repeat(n)),o=y.gray("\u2501".repeat(s)),c=`[${i}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?y.green("\u2713"):y.blue("\u25B6"),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,b=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${b}`,d.stdout.write(e.lastRenderedLine),t)d.stdout.write(`
19
- `)}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 xe(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 i=le(this.config.logDirectory,n);if(e.before)try{if((await ce(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}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 ke(n),console.warn(`Deleted log file: ${n}`)}catch(s){console.error(`Failed to delete log file ${n}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Kr(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:s=()=>!0,fallback:i}=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||!s(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(i!==void 0)return i;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Vr(e){return e instanceof L}function Es(e){return e instanceof Ye}function xs(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 tt{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:s=!0,useBackwardCompatibility:i=!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:s,useBackwardCompatibility:i,customParsers:o,verbose:c,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return $e.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[s,i]of Object.entries(e)){let o=[...t,s],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 i==="object"&&i!==null&&!Array.isArray(i))this.processObject(i,o,r,n);else{let f=Se.env[a]||(l?Se.env[l]:void 0);if(f!==void 0){if(n.verbose){let u=Se.env[a]?a:l}try{e[s]=this.parseEnvironmentValue(f,typeof i,a,n.customParsers,n.configName)}catch(u){if(u instanceof He)throw u;throw te.envVar(a,f,typeof i,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,s){for(let[i,o]of Object.entries(n))try{return o(e)}catch{continue}for(let i of this.defaultParsers)if(i.canParse(e,t))try{return i.parse(e)}catch{throw te.envVar(r,e,`${t} (via ${i.name} parser)`,s)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,s]of Object.entries(Se.env))if(n.startsWith(r)&&s!==void 0)t[n]=s;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(s){n.push(`Cannot parse value "${t}" as ${r}: ${s}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:s="text"}=r,i=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],i,o),s){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[s,i]of Object.entries(e)){let o=[...t,s],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.extractEnvVarInfo(i,o,r,n);else n.push({key:c,type:Array.isArray(i)?"array":typeof i,description:`Configuration for ${o.join(".")}`,example:this.generateExample(i)})}}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}:
20
-
21
- `;for(let n of e)r+=`${n.key}
22
- `,r+=` Type: ${n.type}
23
- `,r+=` Description: ${n.description}
24
- `,r+=` Example: ${n.example}
25
-
26
- `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
27
-
28
- `;r+=`| Variable | Type | Description | Example |
29
- `,r+=`|----------|------|-------------|----------|
30
- `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
31
- `;return r}}function ks(e,t){let r=Jr("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Wr(e,t,r={}){return zr(e,t,r,new WeakMap)}function zr(e,t,r,n){let{arrayMergeMode:s="replace",skipNullish:i=!1,customMerger:o}=r;if(t===null||t===void 0)return i?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Ur(e,t,s,n);if(!I(t)||!I(e))return t;return Fs(e,t,r,n)}function Ur(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 Ss(e,t);case"smart":return Ts(e,t,n);default:return t}return t}function Ss(e,t){let r=[...t];for(let n of e)if(!r.some((s)=>St(s,n)))r.push(n);return r}function Ts(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(I(t[0])&&I(e[0]))return As(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let s of e)if(!n.includes(s))n.push(s);return n}return t}function As(e,t,r){let n=[...t];for(let s of e){if(!I(s)){n.push(s);continue}let i=["id","name","key","path","type"],o=!1;for(let c of i)if(c in s){if(n.find((l)=>I(l)&&(c in l)&&l[c]===s[c])){o=!0;break}}if(!o)n.push(s)}return n}function Fs(e,t,r,n){let s=t;if(I(s)&&n.has(s))return n.get(s);let i={...e};if(I(s))n.set(s,i);for(let o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;let c=s[o],a=i[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){i[o]=c;continue}if(I(c)&&I(a))i[o]=zr(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))i[o]=Ur(a,c,r.arrayMergeMode||"smart",n);else i[o]=c}return i}function Kt(e,t,r="replace"){return Wr(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function St(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(!St(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 s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!St(e[s],t[s]))return!1}return!0}return!1}function I(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class rt{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:s=!0,cacheTtl:i,trackPerformance:o=!0,verbose:c=!1}=r;if(s){let l=me.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Te(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 we(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new we(e,Error("Configuration must export a valid object"),"unknown");let w={config:Kt(t,u,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)me.setWithFileCheck("file",w,e,i);return w}catch(l){throw l instanceof Error?te.configLoad(e,l):te.configLoad(e,Error(String(l)))}};if(o)return $e.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let s=await this.loadFromPath(n,t,r);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(r.verbose)console.warn(`Failed to load config from ${n}:`,s)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),s=[];for(let i of n)for(let o of this.extensions)s.push(gt(t,`${i}${o}`));return s}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 Kr(async()=>Te(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Te(e))return n;if(t||r){let s=this.generateNamePatterns(t||"",r);for(let i of s)for(let o of this.extensions){let c=gt(e,`${i}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:s}=await import("fs"),i=s(e);for(let o of i)if(this.looksLikeConfigFile(o)){let c=gt(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(!Te(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:s}=await import("fs"),i=s(e,"utf8");JSON.parse(i)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}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 s=await this.loadFromPath(n,{},t);if(s)r.set(n,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${n}:`,s)}})),r}}class Vt{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:s=!0,validateTypes:i=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:n,validateRequired:s,validateTypes:i,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 $e.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!zn(t))throw new ve(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),s=n.default||n;if(Array.isArray(s))return this.validateWithRules(e,s,r);else return this.validateWithJSONSchema(e,s,r)}catch(n){throw new ve(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],s=[];return this.validateObjectAgainstSchema(e,t,"",n,s,r),{isValid:n.length===0,errors:n,warnings:s}}validateObjectAgainstSchema(e,t,r,n,s,i){if(i.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"}),i.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"}),i.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,s,i),i.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(i.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"}),i.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,s,i),i.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))s.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],s=[];for(let i of t)try{let o=this.getValueByPath(e,i.path),c=this.validateWithRule(o,i,i.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:i.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:s}}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 s=Array.isArray(e)?"array":typeof e;if(s!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,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 s=t.validator(e);if(s)n.push({path:r,message:t.message||s,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let s of r)if(n&&typeof n==="object"&&s in n)n=n[s];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,s,i,o]=n;t.push({path:s,required:!i,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:Xr},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Wt{fileLoader=new rt;envProcessor=new tt;validator=new Vt;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:s,validate:i,...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(s||i)await this.validateConfiguration(c.config,s,i,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)V.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw V.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:s,cwd:i,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=i||re.cwd(),h=[],g=await this.loadLocalConfiguration(n,s,u,o,c,l,f,a,r);if(g)return h.push(...this.getLocalSearchPaths(n,s,u,o)),this.finalizeResult(g,h,a,n,f);let b=await this.loadHomeConfiguration(n,s,c,l,f,a);if(b)return h.push(...this.getHomeSearchPaths(n,s)),this.finalizeResult(b,h,a,n,f);let m=await this.loadPackageJsonConfiguration(n,s,u,c,l,f,a);if(m)return h.push(j(u,"package.json")),this.finalizeResult(m,h,a,n,f);if(h.push(...this.getAllSearchPaths(n,s,u,o)),t)throw te.configNotFound(n,h,s);return{...await this.applyEnvironmentVariables(n,c,a,f),warnings:[`No configuration file found for "${n}"${s?` or alias "${s}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,s,i,o,c,a){let l=c?pe(e,s,o):s,f=this.getLocalDirectories(r,n);for(let u of f){if(o)V.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:i,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(g){if(o)V.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,n,s,i){if(!e)return null;let o=i?pe(e,r,s):r,c=[j(se(),".config",e),j(se(),".config"),se()];for(let a of c){if(s)V.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:s});if(f){if(s)V.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,s,i,o){let c=o?pe(e,n,i):n;try{let a=j(r,"package.json");if(!xt(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(i)V.success(`Configuration loaded from package.json: ${u}`);return{config:Kt(c,f,s),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(i)V.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:pe(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let s=[];if(r){let i=r(e);if(i)s.push(...i)}if(t){let i=await this.validator.validateConfiguration(e,t);if(!i.isValid)s.push(...i.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(s.length>0)throw te.configValidation(n||"unknown",s,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return me.get(r)||null}cacheResult(e,t,r,n){let s=this.generateCacheKey(e,n);me.set(s,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,j(e,"config"),j(e,".config"),t?j(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let s=[];return s.push(...this.getLocalSearchPaths(e,t,r,n)),s.push(...this.getHomeSearchPaths(e,t)),s.push(j(r,"package.json")),s}getLocalSearchPaths(e,t,r,n){let s=this.getLocalDirectories(r,n),i=[];for(let o of s)i.push(...this.fileLoader.generateConfigPaths(e,o,t));return i}getHomeSearchPaths(e,t){if(!e)return[];let r=[j(se(),".config",e),j(se(),".config"),se()],n=[];for(let s of r)n.push(...this.fileLoader.generateConfigPaths(e,s,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function br(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 Os(e){return Q.loadConfig({...e,__strictErrorHandling:!0})}async function qr(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 Q.loadConfig(e);else n=await Q.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let s=n instanceof Error?n.name:"UnknownError",i=n instanceof Error?n.message:String(n);if(!(s==="ConfigNotFoundError"||s==="ConfigLoadError"||s==="ConfigValidationError"||i.includes("config"))&&e.verbose)V.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 Q.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Rs(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Q.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"&&br(r)))return(await Q.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Q.loadConfig({...e,cwd:e.cwd||re.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&br(t)))return(await Q.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Ns(e,t,r="replace"){let n=new rt;try{let s=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return s?s.config:null}catch{return null}}function pe(e,t,r=!1){let n=new tt,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function i(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=[`${s}_${u.join("_").toUpperCase()}`,`${s}_${u.map((m)=>m.toUpperCase()).join("")}`,`${s}_${u.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,b;for(let m of h)if(g=re.env[m],g!==void 0){b=m;break}if(g!==void 0&&b)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]=i(f,u)}return a}return i(t)}function Ps(e){let t=j(re.cwd(),e.configDir),r=j(re.cwd(),e.generatedDir),n=j(r,"config-types.ts");if(!xt(Xt(n)))bn(Xt(n),{recursive:!0,mode:511});let s=xt(t)?Cn(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],i=`// Generated by bunfig v${ci}
32
- export type ConfigNames = ${s.length?`'${s.join("' | '")}'`:"string"}
33
- `;En(n,i,{mode:438})}function Ds(e){let t=null,r=null,n=()=>{if(!r)r=qr(e).then((i)=>(t=i,i),(i)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)V.warn("Config loading failed, using defaults:",[i instanceof Error?i:Error(String(i))]);return o});return r},s="defaultConfig"in e?e.defaultConfig:{};return t=s,n(),new Proxy({},{get(i,o){if(t)return t[o];let c=s[o];return n(),c},has(i,o){return o in(t||s)},ownKeys(){return Object.keys(t||s)},getOwnPropertyDescriptor(i,o){return Object.getOwnPropertyDescriptor(t||s,o)},set(i,o,c){if(!t)t={...s};return t[o]=c,!0}})}function Ms(e){let t=hr(Jn.cwd(),e?.configDir||"./config");function r(){if(!Un(t))return[];let s=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),i=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=qn(t).filter((a)=>s.has(ht(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=ht(l).toLowerCase(),u=c.get(a);if(!u){c.set(a,l);continue}let h=ht(u).toLowerCase();if(i.indexOf(f)<i.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 s=r(),i=s.map((l)=>l.base),o=i.length?i.map((l)=>`'${l}'`).join(" | "):"string",c=s.length?`{
34
- ${s.map((l)=>{let f=hr(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
35
- `)}
36
- }`:"Record<string, any>";return`export type ConfigNames = ${o}
37
- export type ConfigByName = ${c}
38
- export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
- export type ConfigOf = Config
40
- `}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(i)=>({path:i.path,namespace:"bunfig-virtual"})),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}var Jr,me,$e,Gr,js,Ls,Cr,je,Tt,R,E,Bs,Er,Is,xr,_s,Ks,yt,Vs,kr,Sr,wt,Ws,zs,Us,qs,Le,Yr,Js,N,Gs,Ys,Tr,Be,At,T,y,Hs,Ar,Zs,Fr,Xs,Qs,vt,ei,Or,Rr,ti,$t,ri,ni,si,ii,oi,Ie,Hr,ai,ci="0.15.6",L,Ye,we,Ft,Ot,He,Rt,Nt,ve,Pt,Dt,te,Zr,Xr,V,Q,Qr,en,li=ls(async()=>{Jr=import.meta.require,me=new Lt,$e=new Bt,Gr={createKey:fs,isEquivalent:us,estimateMemoryUsage:gs},js=We(kt.cwd(),"config"),Ls=We(kt.cwd(),"src/generated"),Cr=Ve.env.CLARITY_LOG_DIR||Sn(ds(),"logs"),je={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Cr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Tt=await ps(),R={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=R,Bs=R.red,Er=R.green,Is=R.yellow,xr=R.blue,_s=R.magenta,Ks=R.cyan,yt=R.white,Vs=R.gray,kr=R.bgRed,Sr=R.bgYellow,wt=R.bold,Ws=R.dim,zs=R.italic,Us=R.underline,qs=R.reset,Le={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Yr={debug:"\uD83D\uDD0D",info:xr("\u2139"),success:Er("\u2713"),warning:Sr(yt(wt(" WARN "))),error:kr(yt(wt(" ERROR ")))},Js=new qe("stacks"),N=new qe("bunfig",{showTags:!0}),Gs=M(ye.cwd(),"config"),Ys=M(ye.cwd(),"src/generated"),Tr=Ke.env.CLARITY_LOG_DIR||xn($s(),"logs"),Be={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Tr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},At=await bs(),T={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=T,Hs=T.red,Ar=T.green,Zs=T.yellow,Fr=T.blue,Xs=T.magenta,Qs=T.cyan,vt=T.white,ei=T.gray,Or=T.bgRed,Rr=T.bgYellow,ti=T.bgGray,$t=T.bold,ri=T.dim,ni=T.italic,si=T.underline,ii=T.strikethrough,oi=T.reset,Ie={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Hr={debug:"\uD83D\uDD0D",info:Fr("\u2139"),success:Ar("\u2713"),warning:Rr(vt($t(" WARN "))),error:Or(vt($t(" ERROR ")))},ai=new Ge("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}`}},Ye=class extends L{code="CONFIG_NOT_FOUND";constructor(t,r,n){let s=n?` or alias "${n}"`:"";super(`Configuration "${t}"${s} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},we=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}},Ft=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})}},Ot=class extends L{code="CONFIG_MERGE_ERROR";constructor(t,r,n,s){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:s,originalError:n.name,originalMessage:n.message});this.cause=n}},He=class extends L{code="ENV_VAR_ERROR";constructor(t,r,n,s){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:s})}},Rt=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}},Nt=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}},ve=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})}},Pt=class extends L{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,s){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:s})}},Dt=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}},te={configNotFound(e,t,r){return new Ye(e,t,r)},configLoad(e,t,r){return new we(e,t,r)},configValidation(e,t,r){return new Ft(e,t,r)},configMerge(e,t,r,n){return new Ot(e,t,r,n)},envVar(e,t,r,n){return new He(e,t,r,n)},fileSystem(e,t,r){return new Rt(e,t,r)},typeGeneration(e,t,r){return new Nt(e,t,r)},schemaValidation(e,t,r){return new ve(e,t,r)},browserConfig(e,t,r,n){return new Pt(e,t,r,n)},plugin(e,t,r){return new Dt(e,t,r)}},Zr={replace:"replace",concat:"concat",smart:"smart"},Xr=/^https?:\/\//,V=new Ge("bunfig",{showTags:!0}),Q=new Wt,Qr=j(re.cwd(),"config"),en=j(re.cwd(),"src/generated")});function fi(e,t={}){let r=ze.cwd();while(r.includes("storage"))r=mr(r,"..");let n=mr(r,e||"");if(t?.relative)return Yn(ze.cwd(),n);return n}var ui=ze.env.CLARITY_LOG_DIR||Gn(fi(),"logs"),tn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ui,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ze={...tn},Jo=(async()=>{try{let{loadConfig:e}=await li().then(()=>Br),t=await e({name:"clarity",alias:"logging",defaultConfig:tn,cwd:ze.cwd()});if(t)Object.assign(Ze,t)}catch{}return Ze})();function A(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gi(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X<"u"){let e=X.type;if(e==="renderer"||e==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class rn{async format(e){let t=await gi(),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:he.pid,hostname:t(),environment:he.env.NODE_ENV||"development",platform:he.platform,version:he.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:he.env.NODE_ENV||he.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"},v=F,Go=F.red,hi=F.green,Yo=F.yellow,mi=F.blue,Ho=F.magenta,Zo=F.cyan,Nr=F.white,Xo=F.gray,di=F.bgRed,pi=F.bgYellow,Qo=F.bgGray,Pr=F.bold,ea=F.dim,ta=F.italic,ra=F.underline,na=F.strikethrough,sa=F.reset,bt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},yi={debug:"\uD83D\uDD0D",info:mi("\u2139"),success:hi("\u2713"),warning:pi(Nr(Pr(" WARN "))),error:di(Nr(Pr(" ERROR ")))};class nt{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={...Ze},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new rn,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 s=this.generateKeyId(),i=this.generateKey();this.currentKeyId=s,this.keys.set(s,i),this.encryptionKeys.set(s,{key:i,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{...bt,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...bt};return{...bt,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ze.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 s,i=0,o=3,c=1000;while(i<o)try{try{try{await es(this.config.logDirectory,wr.F_OK|wr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await ts(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:Y.from(e);try{if(!Ae(this.currentLogFile))await pt(this.currentLogFile,"",{mode:420});if(s=yr(this.currentLogFile,"a",420),Qn(s,a,{flag:"a"}),pr(s),s!==void 0)dt(s),s=void 0;if((await ue(this.currentLogFile)).size===0){if(await pt(this.currentLogFile,a,{flag:"w",mode:420}),(await ue(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(i<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,u);let h=c*2**i;await new Promise((g)=>setTimeout(g,h)),i++;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(s!==void 0)try{dt(s)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(i===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}i++;let l=c*2**(i-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}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 ge(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 ge(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ge(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((s)=>{console.error("Error rotating keys:",s)})},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 s=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(s.length>o)for(let[c]of s.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return mt(16).toString("hex")}generateKey(){return mt(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=mt(16),n=Hn("aes-256-gcm",t,r),s=Y.isBuffer(e)?e:Y.from(e,"utf8"),i=n.update(s),o=n.final(),c=i.length+o.length,a=n.getAuthTag(),l=Y.allocUnsafe(16+c+16);return r.copy(l,0),i.copy(l,16),o.copy(l,16+i.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=$r(),s=[];n.on("data",(i)=>s.push(i)),n.on("end",()=>t(Y.from(Y.concat(s)))),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 ue(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 s=await Fe(this.config.logDirectory),i=s.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=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ue(r).catch(()=>null))try{if(await vr(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Oe(c)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!s.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await pt(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 s=new Date().toISOString().replace(/[:.]/g,"-"),i=r.replace(/\.log$/,`-${s}.log`);if(await ue(r).catch(()=>null))await vr(r,i)}if(this.currentLogFile=n,t.maxFiles){let i=(await Fe(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of i.slice(t.maxFiles))await Oe(ge(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=dr(e),n=Xn(t),s=$r();await ss(r,s,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()})),Ae(this.currentLogFile))try{let e=yr(this.currentLogFile,"r+");pr(e),dt(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 Fe(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Oe(ge(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()?v.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:s,level:i,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(i==="warning")g.push("WARN");else if(i==="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(s),g.join(" ")}let a=p.stdout.columns||120,l="";if(i==="warning"||i==="error")l=`${r} ${s}`;else if(i==="info"||i==="success")l=`${r} ${n} ${s}`;else l=`${r} ${n} ${v.cyan(s)}`;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,(i,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):i});let r=/%([sdijfo%])/g,n=0,s=e.replace(r,(i,o)=>{if(o==="%")return"%";if(n>=t.length)return i;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 i}});if(n<t.length)s+=` ${t.slice(n).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return s}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,s)=>{let i=v.underline(v.blue(n)),o=this.toAbsoluteFilePath(s);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${i}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${i}\x1B]8;;\x1B\\`;return i}),t=t.replace(/`([^`]+)`/g,(r,n)=>v.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>v.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>v.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>v.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>v.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(rs(t)||t.startsWith("./")||t.startsWith("../"))t=ns(t);else return null;return Ae(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,s=this.formatConsoleTimestamp(n),i=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?"":yi[e],h=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:s,icon:u,tag:h,message:v.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:s,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:s,icon:u,tag:h,message:v.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:s,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:s,icon:u,tag:h,message:a,level:e}),console.error(g),c){let b=c.split(`
41
- `);for(let m of b)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:s,message:v.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!A()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let f=`${i} ${this.environment}.${e.toUpperCase()}: ${l}
42
- `;if(c)f+=`${c}
43
- `;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(`
44
- `);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?v.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":v.blue("\u25D0"),tag:r,message:`${v.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),s=Math.round(n-t),i=`${e} completed in ${s}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
45
- `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":v.green("\u2713"),tag:f,message:`${i}${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 nt(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(!Ae(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return dr(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=Y.isBuffer(e)?e:Y.from(e,"base64"),s=n.subarray(0,16),i=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=Zn("aes-256-gcm",r,s);c.setAuthTag(i);let a=c.update(o),l=c.final(),f=a.length+l.length,u=Y.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:s,fileText:i}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=s.split(`
46
- `),a=Math.max(...c.map((h)=>h.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,f=`\u2514${"\u2500".repeat(a)}\u2518`,u=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:v.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:v.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:v.cyan(f),showTimestamp:!1}))}else if(!A())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let o=`${n} ${this.environment}.INFO: [BOX] ${i}
47
- `.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(`${v.cyan("?")} ${e} (y/n) `);let r=(n)=>{let s=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(s==="y"||s==="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:s}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${v.blue("\u25D0")} `;console.error(`${l}${a} ${v.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
48
- `.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),s=e.barLength-n,i=v.green("\u2501".repeat(n)),o=v.gray("\u2501".repeat(s)),c=`[${i}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?v.green("\u2713"):v.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=p.stdout.columns||80,b=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${b}`,p.stdout.write(e.lastRenderedLine),t)p.stdout.write(`
49
- `)}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 Fe(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 i=ge(this.config.logDirectory,n);if(e.before)try{if((await ue(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}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 Oe(n),console.warn(`Deleted log file: ${n}`)}catch(s){console.error(`Failed to delete log file ${n}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var ia=new nt("stacks");class W extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class nn extends W{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],s="";if(n.length===1)s=` or alias "${n[0]}"`;else if(n.length>1)s=` or aliases ${n.map((i)=>`"${i}"`).join(", ")}`;super(`Configuration "${e}"${s} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class Xe extends W{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class sn extends W{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class on extends W{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class zt extends W{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}}class an extends W{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class cn extends W{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Qe extends W{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class ln extends W{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}}class fn extends W{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var de={configNotFound(e,t,r){return new nn(e,t,r)},configLoad(e,t,r){return new Xe(e,t,r)},configValidation(e,t,r){return new sn(e,t,r)},configMerge(e,t,r,n){return new on(e,t,r,n)},envVar(e,t,r,n){return new zt(e,t,r,n)},fileSystem(e,t,r){return new an(e,t,r)},typeGeneration(e,t,r){return new cn(e,t,r)},schemaValidation(e,t,r){return new Qe(e,t,r)},browserConfig(e,t,r,n){return new ln(e,t,r,n)},plugin(e,t,r){return new fn(e,t,r)}};async function wi(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:s=()=>!0,fallback:i}=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||!s(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(i!==void 0)return i;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class Ut{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:s=!0,useBackwardCompatibility:i=!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:s,useBackwardCompatibility:i,customParsers:o,verbose:c,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return jt.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[s,i]of Object.entries(e)){let o=[...t,s],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 i==="object"&&i!==null&&!Array.isArray(i))this.processObject(i,o,r,n);else{let f=Ne.env[a]||(l?Ne.env[l]:void 0);if(f!==void 0){if(n.verbose){let u=Ne.env[a]?a:l}try{e[s]=this.parseEnvironmentValue(f,typeof i,a,n.customParsers,n.configName)}catch(u){if(u instanceof zt)throw u;throw de.envVar(a,f,typeof i,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,s){for(let[i,o]of Object.entries(n))try{return o(e)}catch{continue}for(let i of this.defaultParsers)if(i.canParse(e,t))try{return i.parse(e)}catch{throw de.envVar(r,e,`${t} (via ${i.name} parser)`,s)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,s]of Object.entries(Ne.env))if(n.startsWith(r)&&s!==void 0)t[n]=s;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(s){n.push(`Cannot parse value "${t}" as ${r}: ${s}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:s="text"}=r,i=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],i,o),s){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[s,i]of Object.entries(e)){let o=[...t,s],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.extractEnvVarInfo(i,o,r,n);else n.push({key:c,type:Array.isArray(i)?"array":typeof i,description:`Configuration for ${o.join(".")}`,example:this.generateExample(i)})}}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}:
50
-
51
- `;for(let n of e)r+=`${n.key}
52
- `,r+=` Type: ${n.type}
53
- `,r+=` Description: ${n.description}
54
- `,r+=` Example: ${n.example}
55
-
56
- `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
57
-
58
- `;r+=`| Variable | Type | Description | Example |
59
- `,r+=`|----------|------|-------------|----------|
60
- `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
61
- `;return r}}function vi(e,t,r={}){return un(e,t,r,new WeakMap)}function un(e,t,r,n){let{arrayMergeMode:s="replace",skipNullish:i=!1,customMerger:o}=r;if(t===null||t===void 0)return i?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return gn(e,t,s,n);if(!_(t)||!_(e))return t;return Ei(e,t,r,n)}function gn(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 $i(e,t);case"smart":return bi(e,t,n);default:return t}return t}function $i(e,t){let r=[...t];for(let n of e)if(!r.some((s)=>Mt(s,n)))r.push(n);return r}function bi(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(_(t[0])&&_(e[0]))return Ci(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let s of e)if(!n.includes(s))n.push(s);return n}return t}function Ci(e,t,r){let n=[...t];for(let s of e){if(!_(s)){n.push(s);continue}let i=["id","name","key","path","type"],o=!1;for(let c of i)if(c in s){if(n.find((l)=>_(l)&&(c in l)&&l[c]===s[c])){o=!0;break}}if(!o)n.push(s)}return n}function Ei(e,t,r,n){let s=t;if(_(s)&&n.has(s))return n.get(s);let i={...e};if(_(s))n.set(s,i);for(let o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;let c=s[o],a=i[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){i[o]=c;continue}if(_(c)&&_(a))i[o]=un(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))i[o]=gn(a,c,r.arrayMergeMode||"smart",n);else i[o]=c}return i}function hn(e,t,r="replace"){return vi(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Mt(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(!Mt(e[r],t[r]))return!1;return!0}if(_(e)&&_(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Mt(e[s],t[s]))return!1}return!0}return!1}function _(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class mn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:s=!0,cacheTtl:i,trackPerformance:o=!0,verbose:c=!1}=r;if(s){let l=_e.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Pe(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 Xe(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Xe(e,Error("Configuration must export a valid object"),"unknown");let w={config:hn(t,u,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)_e.setWithFileCheck("file",w,e,i);return w}catch(l){throw l instanceof Error?de.configLoad(e,l):de.configLoad(e,Error(String(l)))}};if(o)return jt.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let s=await this.loadFromPath(n,t,r);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(r.verbose)console.warn(`Failed to load config from ${n}:`,s)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),s=[];for(let i of n)for(let o of this.extensions)s.push(Ct(t,`${i}${o}`));return s}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let i of n){if(!i)continue;if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),e)r.push(`${e}.${i}.config`,`.${e}.${i}.config`)}let s=new Set;return r.filter((i)=>{if(!i||s.has(i))return!1;return s.add(i),!0})}checkFileAccess(e){return wi(async()=>Pe(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Pe(e))return n;if(t||r){let s=this.generateNamePatterns(t||"",r);for(let i of s)for(let o of this.extensions){let c=Ct(e,`${i}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:s}=await import("fs"),i=s(e);for(let o of i)if(this.looksLikeConfigFile(o)){let c=Ct(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(!Pe(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:s}=await import("fs"),i=s(e,"utf8");JSON.parse(i)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}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 s=await this.loadFromPath(n,{},t);if(s)r.set(n,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${n}:`,s)}})),r}}var ki=/^https?:\/\//;class dn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:s=!0,validateTypes:i=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:n,validateRequired:s,validateTypes:i,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 jt.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!xi(t))throw new Qe(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),s=n.default||n;if(Array.isArray(s))return this.validateWithRules(e,s,r);else return this.validateWithJSONSchema(e,s,r)}catch(n){throw new Qe(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],s=[];return this.validateObjectAgainstSchema(e,t,"",n,s,r),{isValid:n.length===0,errors:n,warnings:s}}validateObjectAgainstSchema(e,t,r,n,s,i){if(i.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"}),i.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"}),i.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,s,i),i.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(i.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"}),i.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,s,i),i.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))s.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],s=[];for(let i of t)try{let o=this.getValueByPath(e,i.path),c=this.validateWithRule(o,i,i.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:i.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:s}}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 s=Array.isArray(e)?"array":typeof e;if(s!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,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 s=t.validator(e);if(s)n.push({path:r,message:t.message||s,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let s of r)if(n&&typeof n==="object"&&s in n)n=n[s];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,s,i,o]=n;t.push({path:s,required:!i,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:ki},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var U=new nt("bunfig",{showTags:!0});function Si(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class pn{fileLoader=new mn;envProcessor=new Ut;validator=new dn;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:s,validate:i,...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(s||i)await this.validateConfiguration(c.config,s,i,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)U.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw U.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:s,cwd:i,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=i||et.cwd(),h=[],g=await this.loadLocalConfiguration(n,s,u,o,c,l,f,a,r);if(g)return h.push(...this.getLocalSearchPaths(n,s,u,o)),this.finalizeResult(g,h,a,n,f);let b=await this.loadHomeConfiguration(n,s,c,l,f,a);if(b)return h.push(...this.getHomeSearchPaths(n,s)),this.finalizeResult(b,h,a,n,f);let m=await this.loadPackageJsonConfiguration(n,s,u,c,l,f,a);if(m)return h.push(B(u,"package.json")),this.finalizeResult(m,h,a,n,f);if(h.push(...this.getAllSearchPaths(n,s,u,o)),t)throw de.configNotFound(n,h,s);return{...await this.applyEnvironmentVariables(n,c,a,f),warnings:[`No configuration file found for "${n}"${Si(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,s,i,o,c,a){let l=c?De(e,s,o):s,f=this.getLocalDirectories(r,n);for(let u of f){if(o)U.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:i,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(g){if(o)U.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,n,s,i){if(!e)return null;let o=i?De(e,r,s):r,c=[B(ne(),".config",e),B(ne(),".config"),ne()];for(let a of c){if(s)U.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:s});if(f){if(s)U.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,s,i,o){let c=o?De(e,n,i):n;try{let a=B(r,"package.json");if(!vn(a))return null;let l={};try{l=JSON.parse($n(a,"utf8"))}catch(h){if(i)U.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let f=l[e],u=e;if(!f&&t){let h=Array.isArray(t)?t:[t];for(let g of h){if(!g)continue;if(l[g]){f=l[g],u=g;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(i)U.success(`Configuration loaded from package.json: ${u}`);return{config:hn(c,f,s),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(i)U.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:De(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let s=[];if(r){let i=r(e);if(i)s.push(...i)}if(t){let i=await this.validator.validateConfiguration(e,t);if(!i.isValid)s.push(...i.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(s.length>0)throw de.configValidation(n||"unknown",s,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return _e.get(r)||null}cacheResult(e,t,r,n){let s=this.generateCacheKey(e,n);_e.set(s,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}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,B(e,"config"),B(e,".config"),t?B(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let s=[];return s.push(...this.getLocalSearchPaths(e,t,r,n)),s.push(...this.getHomeSearchPaths(e,t)),s.push(B(r,"package.json")),s}getLocalSearchPaths(e,t,r,n){let s=this.getLocalDirectories(r,n),i=[];for(let o of s)i.push(...this.fileLoader.generateConfigPaths(e,o,t));return i}getHomeSearchPaths(e,t){if(!e)return[];let r=[B(ne(),".config",e),B(ne(),".config"),ne()],n=[];for(let s of r)n.push(...this.fileLoader.generateConfigPaths(e,s,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}var Et=new pn;async function yn(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 Et.loadConfig(e);else n=await Et.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let s=n instanceof Error?n.name:"UnknownError",i=n instanceof Error?n.message:String(n);if(!(s==="ConfigNotFoundError"||s==="ConfigLoadError"||s==="ConfigValidationError"||i.includes("config"))&&e.verbose)U.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 Et.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function De(e,t,r=!1){let n=new Ut,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function i(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=[`${s}_${u.join("_").toUpperCase()}`,`${s}_${u.map((m)=>m.toUpperCase()).join("")}`,`${s}_${u.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,b;for(let m of h)if(g=et.env[m],g!==void 0){b=m;break}if(g!==void 0&&b)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]=i(f,u)}return a}return i(t)}var fa=B(et.cwd(),"config"),ua=B(et.cwd(),"src/generated");var Ti=["code-style","lint"],wn={ignores:["**/node_modules/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/.output/**","**/.next/**","**/.nuxt/**","**/.vite/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/vendor/**","**/pantry/**","**/tmp/**","**/.git/**","**/.idea/**","**/.vscode/**","**/.zed/**","**/.cursor/**","**/.claude/**","**/.github/**","**/*.test.ts","**/*.spec.ts","**/.bunpress/**","**/.vitepress/cache/**","**/storage/framework/stx/**","**/storage/framework/runtime/**","**/storage/cloud/**","**/*.lock","**/package-lock.json","**/pnpm-lock.yaml"],lint:{extensions:["ts","js","html","css","json","jsonc","md","yaml","yml","stx","sh","bash","zsh"],reporter:"stylish",cache:!1,maxWarnings:-1},format:{extensions:["ts","js","html","css","json","jsonc","md","yaml","yml","stx","sh","bash","zsh"],trimTrailingWhitespace:!0,maxConsecutiveBlankLines:1,finalNewline:"one",indent:2,indentStyle:"spaces",preserveCodeIndentation:!1,quotes:"single",semi:!1},rules:{noDebugger:"error",noConsole:"warn"},pluginRules:{"style/brace-style":"warn","style/curly":"off","style/if-newline":"off","style/max-statements-per-line":"warn","pickier/import-dedupe":"warn","pickier/no-import-node-modules-by-path":"error","pickier/no-import-dist":"error","pickier/prefer-const":"error","pickier/prefer-template":"warn","pickier/no-unused-vars":"error","pickier/no-unused-imports":"error","pickier/sort-tailwind-classes":"warn","regexp/no-unused-capturing-group":"error","regexp/no-super-linear-backtracking":"error","regexp/no-useless-lazy":"error","ts/no-top-level-await":"error","ts/member-delimiter-style":"off","ts/type-annotation-spacing":"off","style/comma-dangle":"off","style/keyword-spacing":"off","style/arrow-spacing":"off","style/space-infix-ops":"off","style/object-curly-spacing":"off","style/spaced-comment":"off","style/block-spacing":"off","style/space-before-blocks":"off","style/comma-spacing":"off","style/semi-spacing":"off","style/rest-spread-spacing":"off","style/key-spacing":"off","style/computed-property-spacing":"off","style/array-bracket-spacing":"off","style/space-in-parens":"off","style/template-curly-spacing":"off","style/space-unary-ops":"off","style/switch-colon-spacing":"off","style/arrow-parens":"off","style/space-before-function-paren":"off","style/quote-props":"off","style/no-floating-decimal":"off","style/new-parens":"off","style/no-extra-parens":"off","style/wrap-iife":"off","style/comma-style":"off","style/dot-location":"off","style/operator-linebreak":"off","style/multiline-ternary":"off","style/padded-blocks":"off","style/lines-between-class-members":"off","style/no-tabs":"off","style/no-mixed-spaces-and-tabs":"off","style/generator-star-spacing":"off","style/yield-star-spacing":"off","style/function-call-spacing":"off","style/template-tag-spacing":"off","style/no-whitespace-before-property":"off","style/no-mixed-operators":"off","style/indent-binary-ops":"off","ts/type-generic-spacing":"off","ts/type-named-tuple-spacing":"off","markdown/heading-increment":"warn","markdown/heading-style":"warn","markdown/no-missing-space-atx":"error","markdown/no-multiple-space-atx":"error","markdown/no-missing-space-closed-atx":"error","markdown/no-multiple-space-closed-atx":"error","markdown/blanks-around-headings":"warn","markdown/heading-start-left":"warn","markdown/no-duplicate-heading":"warn","markdown/single-title":"warn","markdown/no-trailing-punctuation":"warn","markdown/ul-style":"warn","markdown/list-indent":"error","markdown/ul-indent":"warn","markdown/ol-prefix":"warn","markdown/list-marker-space":"error","markdown/blanks-around-lists":"warn","markdown/no-trailing-spaces":"error","markdown/no-hard-tabs":"error","markdown/no-multiple-blanks":"warn","markdown/no-multiple-space-blockquote":"error","markdown/no-blanks-blockquote":"warn","markdown/blanks-around-fences":"warn","markdown/single-trailing-newline":"error","markdown/blanks-around-tables":"warn","markdown/no-reversed-links":"error","markdown/no-bare-urls":"warn","markdown/no-space-in-links":"error","markdown/no-empty-links":"error","markdown/link-fragments":"warn","markdown/reference-links-images":"warn","markdown/link-image-reference-definitions":"warn","markdown/link-image-style":"warn","markdown/descriptive-link-text":"warn","markdown/line-length":"off","markdown/commands-show-output":"warn","markdown/fenced-code-language":"warn","markdown/code-block-style":"off","markdown/code-fence-style":"warn","markdown/no-emphasis-as-heading":"warn","markdown/no-space-in-emphasis":"warn","markdown/no-space-in-code":"warn","markdown/emphasis-style":"warn","markdown/strong-style":"warn","markdown/no-inline-html":"off","markdown/hr-style":"warn","markdown/first-line-heading":"off","markdown/required-headings":"off","markdown/proper-names":"off","markdown/no-alt-text":"warn","markdown/table-pipe-style":"warn","markdown/table-column-count":"warn","markdown/table-column-style":"warn","lockfile/validate-host":["warn",{allowedHosts:["npm","yarn"]}],"lockfile/validate-https":"error","lockfile/validate-integrity":["warn",{requiredAlgorithm:"sha512"}],"lockfile/validate-package-names":"error","lockfile/validate-scheme":["error",{allowedSchemes:["https:","git+https:","git+ssh:"]}],"publint/exports-types-should-be-first":"error","publint/exports-default-should-be-last":"error","publint/exports-module-should-precede-require":"error","publint/exports-value-invalid":"error","publint/imports-key-invalid":"error","publint/imports-value-invalid":"error","publint/imports-default-should-be-last":"error","publint/imports-module-should-precede-require":"error","publint/use-type":"warn","publint/deprecated-field-jsnext":"warn","publint/field-invalid-value-type":"error","publint/local-dependency":"error","publint/has-module-but-no-exports":"warn","publint/exports-missing-root-entrypoint":"warn","publint/exports-fallback-array-use":"warn","publint/file-does-not-exist":"warn","publint/file-invalid-format":"warn","publint/module-should-be-esm":"error","publint/bin-file-not-executable":"error","publint/exports-module-should-be-esm":"error","shell/command-substitution":"error","shell/quote-variables":"warn","shell/no-cd-without-check":"warn","shell/no-eval":"error","shell/no-useless-cat":"warn","shell/shebang":"warn","shell/indent":"warn","shell/function-style":"warn","shell/operator-spacing":"warn","shell/keyword-spacing":"warn","shell/no-trailing-semicolons":"warn","shell/no-trailing-whitespace":"error","shell/prefer-double-brackets":"warn","shell/set-options":"off","shell/prefer-printf":"warn","shell/consistent-case-terminators":"warn","shell/no-broken-redirect":"error","shell/heredoc-indent":"warn","shell/no-ls-parsing":"warn","shell/no-variable-in-single-quotes":"warn","shell/no-exit-in-subshell":"warn","spell/check":"off","spell/check-comments":"off","spell/check-markdown":"off"},verbose:!0},qt=null;async function ma(){if(!qt)qt=await yn({name:"pickier",alias:[...Ti],defaultConfig:wn});return qt}var da=wn;
62
- export{wn as N,ma as O,da as P};