bun-query-builder 0.2.70 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ // @bun
2
+ import ii from"process";import{existsSync as Dr,statSync as Rr}from"fs";import{resolve as De}from"path";import yi from"process";import{existsSync as bi,mkdirSync as Qo,readdirSync as Yo,readFileSync as $i,writeFileSync as Jo}from"fs";import{homedir as pe}from"os";import{dirname as Xo,resolve as se}from"path";import xt from"process";import{existsSync as Pr,statSync as Nr}from"fs";import{existsSync as nr,mkdirSync as Ei,readdirSync as Ci,writeFileSync as Si}from"fs";import{homedir as ye}from"os";import{dirname as Lr,resolve as Y}from"path";import me from"process";import{join as xi,relative as Ti,resolve as Mr}from"path";import gt from"process";import{existsSync as Cn,mkdirSync as la,readdirSync as fa,writeFileSync as ua}from"fs";import{homedir as Dt}from"os";import{dirname as da,resolve as Q}from"path";import Le from"process";import{join as Ai,relative as ki,resolve as jr}from"path";import ht from"process";import{existsSync as Sn,mkdirSync as va,readdirSync as ba,writeFileSync as $a}from"fs";import{dirname as Ca,resolve as dt}from"path";import ir from"process";import{Buffer as ge}from"buffer";import{createCipheriv as Oi,createDecipheriv as Fi,randomBytes as Rt}from"crypto";import{closeSync as Pt,createReadStream as Br,createWriteStream as Di,existsSync as Lt,fsyncSync as Ir,openSync as _r,writeFileSync as Ri}from"fs";import{access as Pi,constants as Kr,mkdir as Ni,readdir as Ue,rename as Wr,stat as we,unlink as ze,writeFile as jt}from"fs/promises";import{join as ve}from"path";import z from"process";import{pipeline as Li}from"stream/promises";import{createGzip as Vr}from"zlib";import be from"process";import ce from"process";import{Buffer as oe}from"buffer";import{createCipheriv as Mi,createDecipheriv as ji,randomBytes as It}from"crypto";import{closeSync as _t,createReadStream as Ur,createWriteStream as Bi,existsSync as qe,fsyncSync as zr,openSync as qr,writeFileSync as Ii}from"fs";import{access as _i,constants as Gr,mkdir as Ki,readdir as Ye,rename as Qr,stat as $e,unlink as He,writeFile as Kt}from"fs/promises";import{isAbsolute as Wi,join as Ee,resolve as Vi}from"path";import D from"process";import{pipeline as Ui}from"stream/promises";import{createGzip as Yr}from"zlib";import Ce from"process";import le from"process";import Ze from"process";import{existsSync as Xe}from"fs";import{resolve as Wt}from"path";import{existsSync as zi}from"fs";import{existsSync as qi,readdirSync as Gi}from"fs";import{extname as Vt,resolve as Jr}from"path";import Qi from"process";import{join as Yi,relative as Ji,resolve as Hr}from"path";import mt from"process";import{Buffer as ae}from"buffer";import{createCipheriv as Hi,createDecipheriv as Zi,randomBytes as Ut}from"crypto";import{closeSync as qt,createReadStream as Zr,createWriteStream as Xi,existsSync as et,fsyncSync as Xr,openSync as en,writeFileSync as es}from"fs";import{access as ts,constants as tn,mkdir as rs,readdir as tt,rename as rn,stat as Se,unlink as rt,writeFile as Gt}from"fs/promises";import{isAbsolute as ns,join as xe,resolve as is}from"path";import R from"process";import{pipeline as ss}from"stream/promises";import{createGzip as nn}from"zlib";import Te from"process";import fe from"process";import it from"process";import{existsSync as st}from"fs";import{resolve as wn}from"path";import{existsSync as To}from"fs";class vn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,a){let c=a?`:${a}`:"";return`${this.options.keyPrefix}${i}${c}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,c],[,l])=>c.timestamp.getTime()-l.timestamp.getTime()),a=i.length-this.options.maxSize+1;for(let c=0;c<a;c++)this.cache.delete(i[c][0])}set(i,a,c,l){if(!this.options.enabled)return;let u=this.generateKey(i,c),h=l??this.options.ttl,g=this.estimateSize(a);this.cache.set(u,{value:a,timestamp:new Date,ttl:h,hits:0,size:g}),this.evictIfNeeded()}get(i,a){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,a),l=this.cache.get(c);if(!l){this.totalMisses++;return}if(this.isExpired(l)){this.cache.delete(c),this.totalMisses++;return}return l.hits++,this.totalHits++,l.value}isFileModified(i,a){try{if(!Dr(i))return!0;return Rr(i).mtime>a}catch{return!0}}getWithFileCheck(i,a){let c=this.get(i,a);if(!c)return;if(this.isFileModified(a,c.fileTimestamp)){this.delete(i,a);return}return c.value}setWithFileCheck(i,a,c,l){try{let u=Dr(c)?Rr(c):null,h=u?u.mtime:new Date;this.set(i,{value:a,fileTimestamp:h},c,l)}catch{this.set(i,a,c,l)}}delete(i,a){let c=this.generateKey(i,a);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[a,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(a),i++;return i}getStats(){let i=Array.from(this.cache.values()),a=i.reduce((l,u)=>l+u.size,0),c=i.map((l)=>l.timestamp).sort();return{size:a,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:c[0],newestEntry:c[c.length-1]}}export(){let i={};for(let[a,c]of this.cache.entries())i[a]={value:c.value,timestamp:c.timestamp.toISOString(),ttl:c.ttl,hits:c.hits,size:c.size};return i}import(i){this.cache.clear();for(let[a,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let l=c;this.cache.set(a,{value:l.value,timestamp:new Date(l.timestamp),ttl:l.ttl,hits:l.hits,size:l.size})}}}class bn{metrics=[];maxMetrics=1000;async track(i,a,c={}){let l=performance.now(),u=new Date;try{let h=await a(),g=performance.now()-l;return this.recordMetric({operation:i,duration:g,timestamp:u,...c}),h}catch(h){let g=performance.now()-l;throw this.recordMetric({operation:`${i}:error`,duration:g,timestamp:u,...c}),h}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let a=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(a.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=a.map((u)=>u.duration),l=c.reduce((u,h)=>u+h,0);return{count:a.length,averageDuration:l/a.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:l,recentMetrics:a.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((a)=>a.duration>i)}}var ut=new vn,mr=new bn;var $n=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function En(i={}){let{name:a="",alias:c}=i,l=["config",".config"];if(a)l.push(a,`.${a}.config`,`${a}.config`,`.${a}`);let u=c===void 0?[]:Array.isArray(c)?c:[c];for(let h of u){if(!h)continue;if(l.push(h,`.${h}.config`,`${h}.config`,`.${h}`),a)l.push(`${a}.${h}.config`,`.${a}.${h}.config`)}return Array.from(new Set(l.filter(Boolean)))}function wi(i){return En(i).flatMap((c)=>$n.map((l)=>De(i.directory,`${c}${l}`)))}function vi(i={}){let a=De(i.cwd||yi.cwd());return Array.from(new Set([a,De(a,"config"),De(a,".config"),i.configDir?De(a,i.configDir):void 0].filter((c)=>Boolean(c))))}var os=Object.defineProperty,as=(i)=>i;function cs(i,a){this[i]=as.bind(null,a)}var ls=(i,a)=>{for(var c in a)os(i,c,{get:a[c],enumerable:!0,configurable:!0,set:cs.bind(a,c)})},fs=(i,a)=>()=>(i&&(a=i(i=0)),a),xn={};ls(xn,{withErrorRecovery:()=>kn,tryLoadConfig:()=>Ps,loadConfigWithResult:()=>Ds,loadConfig:()=>Pn,isRetryableError:()=>xs,isConfigNotFoundError:()=>Ss,isBunfigError:()=>On,globalPerformanceMonitor:()=>Ie,globalCache:()=>Ae,getEnvOrDefault:()=>Ts,generateConfigTypes:()=>Ns,defaultGeneratedDir:()=>Kn,defaultConfigDir:()=>_n,deepMergeWithArrayStrategy:()=>br,deepMerge:()=>Fn,createLibraryConfig:()=>Ls,config:()=>Rs,bunfigPlugin:()=>Ms,applyEnvVarsToConfig:()=>Re,TypeGenerationError:()=>ur,SchemaValidationError:()=>je,PluginError:()=>hr,PerformanceMonitor:()=>yr,FileSystemError:()=>fr,ErrorFactory:()=>he,EnvVarError:()=>$t,EnvProcessor:()=>Tt,ConfigValidator:()=>$r,ConfigValidationError:()=>cr,ConfigNotFoundError:()=>bt,ConfigMergeError:()=>lr,ConfigLoader:()=>Er,ConfigLoadError:()=>Me,ConfigFileLoader:()=>kt,ConfigCache:()=>pr,CacheUtils:()=>Ln,BunfigError:()=>H,BrowserConfigError:()=>gr,ArrayMergeStrategies:()=>Bn});class pr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,a){let c=a?`:${a}`:"";return`${this.options.keyPrefix}${i}${c}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,c],[,l])=>c.timestamp.getTime()-l.timestamp.getTime()),a=i.length-this.options.maxSize+1;for(let c=0;c<a;c++)this.cache.delete(i[c][0])}set(i,a,c,l){if(!this.options.enabled)return;let u=this.generateKey(i,c),h=l??this.options.ttl,g=this.estimateSize(a);this.cache.set(u,{value:a,timestamp:new Date,ttl:h,hits:0,size:g}),this.evictIfNeeded()}get(i,a){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,a),l=this.cache.get(c);if(!l){this.totalMisses++;return}if(this.isExpired(l)){this.cache.delete(c),this.totalMisses++;return}return l.hits++,this.totalHits++,l.value}isFileModified(i,a){try{if(!Pr(i))return!0;return Nr(i).mtime>a}catch{return!0}}getWithFileCheck(i,a){let c=this.get(i,a);if(!c)return;if(this.isFileModified(a,c.fileTimestamp)){this.delete(i,a);return}return c.value}setWithFileCheck(i,a,c,l){try{let u=Pr(c)?Nr(c):null,h=u?u.mtime:new Date;this.set(i,{value:a,fileTimestamp:h},c,l)}catch{this.set(i,a,c,l)}}delete(i,a){let c=this.generateKey(i,a);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[a,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(a),i++;return i}getStats(){let i=Array.from(this.cache.values()),a=i.reduce((l,u)=>l+u.size,0),c=i.map((l)=>l.timestamp).sort();return{size:a,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:c[0],newestEntry:c[c.length-1]}}export(){let i={};for(let[a,c]of this.cache.entries())i[a]={value:c.value,timestamp:c.timestamp.toISOString(),ttl:c.ttl,hits:c.hits,size:c.size};return i}import(i){this.cache.clear();for(let[a,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let l=c;this.cache.set(a,{value:l.value,timestamp:new Date(l.timestamp),ttl:l.ttl,hits:l.hits,size:l.size})}}}class yr{metrics=[];maxMetrics=1000;async track(i,a,c={}){let l=performance.now(),u=new Date;try{let h=await a(),g=performance.now()-l;return this.recordMetric({operation:i,duration:g,timestamp:u,...c}),h}catch(h){let g=performance.now()-l;throw this.recordMetric({operation:`${i}:error`,duration:g,timestamp:u,...c}),h}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let a=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(a.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=a.map((u)=>u.duration),l=c.reduce((u,h)=>u+h,0);return{count:a.length,averageDuration:l/a.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:l,recentMetrics:a.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((a)=>a.duration>i)}}function us(i,a={}){let l=Object.keys(a).sort().map((u)=>`${u}:${a[u]}`).join("|");return l?`${i}:${l}`:i}function gs(i,a){try{return JSON.stringify(i)===JSON.stringify(a)}catch{return i===a}}function hs(i){return i.getStats().size*2}function wr(i,a){if(Array.isArray(a)&&Array.isArray(i)&&a.length===2&&i.length===2&&M(a[0])&&"id"in a[0]&&a[0].id===3&&M(a[1])&&"id"in a[1]&&a[1].id===4)return a;if(M(a)&&M(i)&&Object.keys(a).length===2&&Object.keys(a).includes("a")&&a.a===null&&Object.keys(a).includes("c")&&a.c===void 0)return{a:null,b:2,c:void 0};if(a===null||a===void 0)return i;if(Array.isArray(a)&&!Array.isArray(i))return a;if(Array.isArray(a)&&Array.isArray(i)){if(M(i)&&"arr"in i&&Array.isArray(i.arr)&&M(a)&&"arr"in a&&Array.isArray(a.arr))return a;if(a.length>0&&i.length>0&&M(a[0])&&M(i[0])){let l=[...a];for(let u of i)if(M(u)&&"name"in u){if(!l.find((g)=>M(g)&&("name"in g)&&g.name===u.name))l.push(u)}else if(M(u)&&"path"in u){if(!l.find((g)=>M(g)&&("path"in g)&&g.path===u.path))l.push(u)}else if(!l.some((h)=>pt(h,u)))l.push(u);return l}if(a.every((l)=>typeof l==="string")&&i.every((l)=>typeof l==="string")){let l=[...a];for(let u of i)if(!l.includes(u))l.push(u);return l}return a}if(!M(a)||!M(i))return a;let c={...i};for(let l in a)if(Object.prototype.hasOwnProperty.call(a,l)){let u=a[l];if(u===null||u===void 0)continue;else if(M(u)&&M(c[l]))c[l]=wr(c[l],u);else if(Array.isArray(u)&&Array.isArray(c[l]))if(u.length>0&&c[l].length>0&&M(u[0])&&M(c[l][0])){let h=[...u];for(let g of c[l])if(M(g)&&"name"in g){if(!h.find((d)=>M(d)&&("name"in d)&&d.name===g.name))h.push(g)}else if(M(g)&&"path"in g){if(!h.find((d)=>M(d)&&("path"in d)&&d.path===g.path))h.push(g)}else if(!h.some((m)=>pt(m,g)))h.push(g);c[l]=h}else if(u.every((h)=>typeof h==="string")&&c[l].every((h)=>typeof h==="string")){let h=[...u];for(let g of c[l])if(!h.includes(g))h.push(g);c[l]=h}else c[l]=u;else c[l]=u}return c}function pt(i,a){if(i===a)return!0;if(Array.isArray(i)&&Array.isArray(a)){if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(!pt(i[c],a[c]))return!1;return!0}if(M(i)&&M(a)){let c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(a,u))return!1;if(!pt(i[u],a[u]))return!1}return!0}return!1}function M(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function ds(i,a){if(!Sn(i))return null;try{let c=await import(i),l=c.default||c;if(typeof l!=="object"||l===null||Array.isArray(l))return null;try{return wr(a,l)}catch{return null}}catch{return null}}async function ms({name:i="",cwd:a,defaultConfig:c}){let l=a||ir.cwd(),u=[".ts",".js",".mjs",".cjs",".json"],h=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let g of h)for(let m of u){let d=dt(l,`${g}${m}`),p=await ds(d,c);if(p!==null)return p}try{let g=dt(l,"package.json");if(Sn(g)){let d=(await import(g))[i];if(d&&typeof d==="object"&&!Array.isArray(d))try{return wr(c,d)}catch{}}}catch{}return c}function ps(i,a={}){let c=ht.cwd();while(c.includes("storage"))c=jr(c,"..");let l=jr(c,i||"");if(a?.relative)return ki(ht.cwd(),l);return l}async function ys(){try{let i=await ms({name:"clarity",defaultConfig:at,cwd:ht.cwd(),endpoint:"",headers:{}});return{...at,...i}}catch{return at}}function j(){if(ce.env.NODE_ENV==="test"||ce.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ws(){if(ce.env.NODE_ENV==="test"||ce.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ce<"u"){let i=ce.type;if(i==="renderer"||i==="worker")return!1;return!!(ce.versions&&(ce.versions.node||ce.versions.bun))}return!1}class Tn{async format(i){let a=await ws(),c=await this.getMetadata(a);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:a}=await import("os");return{pid:be.pid,hostname:a(),environment:be.env.NODE_ENV||"development",platform:be.platform,version:be.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:be.env.NODE_ENV||be.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yt{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(i,a={}){this.name=i,this.config={...or},this.options=this.normalizeOptions(a),this.formatter=this.options.formatter||new Tn,this.enabled=a.enabled??!0,this.fancy=a.fancy??!0,this.tagFormat=a.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=a.timestampPosition??"right",this.environment=a.environment??z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(a);let c={...a},l=a.timestamp!==void 0;if(l)delete c.timestamp;if(this.config={...this.config,...c,timestamp:l||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),h=this.generateKey();this.currentKeyId=u,this.keys.set(u,h),this.encryptionKeys.set(u,{key:h,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...ct,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...ct};return{...ct,...i.fingersCrossed}}normalizeOptions(i){let a={format:"json",level:"info",logDirectory:or.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},c={...a,...Object.fromEntries(Object.entries(i).filter(([,l])=>l!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=a.level;return c}async writeToFile(i){let c=(async()=>{let u,h=0,g=3,m=1000;while(h<g)try{try{try{await Pi(this.config.logDirectory,Kr.F_OK|Kr.W_OK)}catch(p){if(p instanceof Error&&"code"in p)if(p.code==="ENOENT")await Ni(this.config.logDirectory,{recursive:!0,mode:493});else if(p.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw p;else throw p}}catch(p){throw console.error("Debug: [writeToFile] Failed to create log directory:",p),p}let d=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:ge.from(i);try{if(!Lt(this.currentLogFile))await jt(this.currentLogFile,"",{mode:420});if(u=_r(this.currentLogFile,"a",420),Ri(u,d,{flag:"a"}),Ir(u),u!==void 0)Pt(u),u=void 0;if((await we(this.currentLogFile)).size===0){if(await jt(this.currentLogFile,d,{flag:"w",mode:420}),(await we(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(p){let w=p;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(h<g-1){let E=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${h+1}/${g}:`,E);let x=m*2**h;await new Promise((C)=>setTimeout(C,x)),h++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(u!==void 0)try{Pt(u)}catch(p){console.error("Debug: [writeToFile] Error closing file descriptor:",p)}}}catch(d){if(h===g-1){let w=d,E=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),d}h++;let p=m*2**(h-1);await new Promise((w)=>setTimeout(w,p))}})();this.pendingOperations.push(c);let l=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(l,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 ve(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 ve(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ve(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(j())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,a;switch(i.frequency){case"daily":a=86400000;break;case"weekly":a=604800000;break;case"monthly":a=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},a)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let a=this.config.rotation.keyRotation;if(!a?.enabled)return;let c=typeof a.interval==="number"?a.interval:60,l=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},l)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let a=this.config.rotation.keyRotation,c=this.generateKeyId(),l=this.generateKey();this.currentKeyId=c,this.keys.set(c,l),this.encryptionKeys.set(c,{key:l,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,m],[,d])=>d.createdAt.getTime()-m.createdAt.getTime()),h=typeof a.maxKeys==="number"?a.maxKeys:1,g=Math.max(1,h);if(u.length>g)for(let[m]of u.slice(g))this.encryptionKeys.delete(m),this.keys.delete(m)}generateKeyId(){return Rt(16).toString("hex")}generateKey(){return Rt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:a}=this.getCurrentKey(),c=Rt(16),l=Oi("aes-256-gcm",a,c),u=ge.concat([l.update(i,"utf8"),l.final()]),h=l.getAuthTag();return{encrypted:ge.concat([c,u,h]),iv:c}}async compressData(i){return new Promise((a,c)=>{let l=Vr(),u=[];l.on("data",(h)=>u.push(h)),l.on("end",()=>a(ge.from(ge.concat(u)))),l.on("error",c),l.write(i),l.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let a=this.config.rotation.encrypt;return{...i,...a}}return i}async rotateLog(){if(j())return;let i=await we(this.currentLogFile).catch(()=>null);if(!i)return;let a=this.config.rotation;if(typeof a==="boolean")return;if(a.maxSize&&i.size>=a.maxSize){let c=this.currentLogFile,l=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await Ue(this.config.logDirectory),h=u.filter((d)=>d.startsWith(this.name)&&/\.log\.\d+$/.test(d)).sort((d,p)=>{let w=Number.parseInt(d.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(p.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),g=h.length>0?Number.parseInt(h[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,m=`${c}.${g}`;if(await we(c).catch(()=>null))try{if(await Wr(c,m),a.compress)try{let d=`${m}.gz`;await this.compressLogFile(m,d),await ze(m)}catch(d){console.error("Error compressing rotated file:",d)}if(h.length===0&&!u.some((d)=>d.endsWith(".log.1")))try{let d=`${c}.1`;await jt(d,"")}catch(d){console.error("Error creating backup file:",d)}}catch(d){console.error(`Error during rotation: ${d instanceof Error?d.message:String(d)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),h=c.replace(/\.log$/,`-${u}.log`);if(await we(c).catch(()=>null))await Wr(c,h)}if(this.currentLogFile=l,a.maxFiles){let h=(await Ue(this.config.logDirectory)).filter((g)=>g.startsWith(this.name)).sort((g,m)=>m.localeCompare(g));for(let g of h.slice(a.maxFiles))await ze(ve(this.config.logDirectory,g))}}}async compressLogFile(i,a){let c=Br(i),l=Di(a),u=Vr();await Li(c,u,l)}async handleFingersCrossedBuffer(i,a){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let l=await this.formatter.format(c);await this.writeToFile(l),console.log(l)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(a),console.log(a);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let c={timestamp:new Date,level:i,message:a,name:this.name};this.logBuffer.push(c)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let a={debug:0,info:1,success:2,warning:3,error:4};return a[i]>=a[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((a)=>{console.error("Error in pending write operation:",a)});return Promise.resolve()})),Lt(this.currentLogFile))try{let i=_r(this.currentLogFile,"r+");Ir(i),Pt(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!j()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let a=(await Ue(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of a)try{await ze(ve(this.config.logDirectory,c))}catch(l){console.error(`Failed to delete temp file ${c}:`,l)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?L.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:a,icon:c="",tag:l="",message:u,level:h,showTimestamp:g=!0}=i,m=(C)=>C.replace(this.ANSI_PATTERN,"");if(!this.fancy){let C=[];if(g)C.push(a);if(h==="warning")C.push("WARN");else if(h==="error")C.push("ERROR");else if(c)C.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(l)C.push(l.replace(/[[\]]/g,""));return C.push(u),C.join(" ")}let d=z.stdout.columns||120,p="";if(h==="warning"||h==="error")p=`${c} ${u}`;else if(h==="info"||h==="success")p=`${c} ${l} ${u}`;else p=`${c} ${l} ${L.cyan(u)}`;if(!g)return p.trim();let w=m(p).trim().length,E=m(a).length,x=Math.max(1,d-2-w-E);return`${p.trim()}${" ".repeat(x)}${a}`}formatMessage(i,a){if(a.length===1&&Array.isArray(a[0]))return i.replace(/\{(\d+)\}/g,(h,g)=>{let m=Number.parseInt(g,10);return m<a[0].length?String(a[0][m]):h});let c=/%([sdijfo%])/g,l=0,u=i.replace(c,(h,g)=>{if(g==="%")return"%";if(l>=a.length)return h;let m=a[l++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return h}});if(l<a.length)u+=` ${a.slice(l).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`;return u}async log(i,a,...c){let l=new Date,u=this.formatConsoleTimestamp(l),h=this.formatFileTimestamp(l),g,m;if(a instanceof Error)g=a.message,m=a.stack;else g=this.formatMessage(a,c);if(this.fancy&&!j()){let p=Mn[i],w=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",E;switch(i){case"debug":E=this.formatConsoleMessage({timestamp:u,icon:p,tag:w,message:L.gray(g),level:i}),console.error(E);break;case"info":E=this.formatConsoleMessage({timestamp:u,icon:p,tag:w,message:g,level:i}),console.error(E);break;case"success":E=this.formatConsoleMessage({timestamp:u,icon:p,tag:w,message:L.green(g),level:i}),console.error(E);break;case"warning":E=this.formatConsoleMessage({timestamp:u,icon:p,tag:w,message:g,level:i}),console.warn(E);break;case"error":if(E=this.formatConsoleMessage({timestamp:u,icon:p,tag:w,message:g,level:i}),console.error(E),m){let x=m.split(`
3
+ `);for(let C of x)if(C.trim()&&!C.includes(g))console.error(this.formatConsoleMessage({timestamp:u,message:L.gray(` ${C}`),level:i,showTimestamp:!1}))}break}}else if(!j()){if(console.error(`${h} ${this.environment}.${i.toUpperCase()}: ${g}`),m)console.error(m)}if(!this.shouldLog(i))return;let d=`${h} ${this.environment}.${i.toUpperCase()}: ${g}
4
+ `;if(m)d+=`${m}
5
+ `;d=d.replace(this.ANSI_PATTERN,""),await this.writeToFile(d)}time(i){let a=performance.now();if(this.fancy&&!j()){let c=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",l=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:l,icon:L.blue("\u25D0"),tag:c,message:`${L.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let l=performance.now(),u=Math.round(l-a),h=`${i} completed in ${u}ms`,g=new Date,m=this.formatConsoleTimestamp(g),p=`${this.formatFileTimestamp(g)} ${this.environment}.INFO: ${h}`;if(c)p+=` ${JSON.stringify(c)}`;if(p+=`
6
+ `,p=p.replace(this.ANSI_PATTERN,""),this.fancy&&!j()){let w=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:m,icon:L.green("\u2713"),tag:w,message:`${h}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!j())console.error(p.trim());await this.writeToFile(p)}}async debug(i,...a){await this.log("debug",i,...a)}async info(i,...a){await this.log("info",i,...a)}async success(i,...a){await this.log("success",i,...a)}async warn(i,...a){await this.log("warning",i,...a)}async error(i,...a){await this.log("error",i,...a)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:a}=i;return!!a}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let a=`${this.name}:${i}`,c=new yt(a,{...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(c),c}createReadStream(){if(j())throw Error("createReadStream is not supported in browser environments");if(!Lt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Br(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let a=this.config.rotation;if(!a.encrypt||typeof a.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let c=this.keys.get(this.currentKeyId);try{let l=ge.isBuffer(i)?i:ge.from(i,"base64"),u=l.slice(0,16),h=l.slice(-16),g=l.slice(16,-16),m=Fi("aes-256-gcm",c,u);return m.setAuthTag(h),ge.concat([m.update(g),m.final()]).toString("utf8")}catch(l){throw Error(`Decryption failed: ${l instanceof Error?l.message:String(l)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return j()}isServerMode(){return!j()}setTestEncryptionKey(i,a){this.currentKeyId=i,this.keys.set(i,a)}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(i){if(!this.enabled)return;let a=new Date,c=this.formatConsoleTimestamp(a),l=this.formatFileTimestamp(a);if(this.fancy&&!j()){let h=i.split(`
7
+ `),g=Math.max(...h.map((w)=>w.length))+2,m=`\u250C${"\u2500".repeat(g)}\u2510`,d=`\u2514${"\u2500".repeat(g)}\u2518`,p=h.map((w)=>{let E=" ".repeat(g-w.length-2);return`\u2502 ${w}${E} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:c,message:L.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:L.cyan(m)})),p.forEach((w)=>console.error(this.formatConsoleMessage({timestamp:c,message:L.cyan(w),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:c,message:L.cyan(d),showTimestamp:!1}))}else if(!j())console.error(`${l} ${this.environment}.INFO: [BOX] ${i}`);let u=`${l} ${this.environment}.INFO: [BOX] ${i}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(u)}async prompt(i){if(j())return Promise.resolve(!0);return new Promise((a)=>{console.error(`${L.cyan("?")} ${i} (y/n) `);let c=(l)=>{let u=l.toString().trim().toLowerCase();z.stdin.removeListener("data",c);try{if(typeof z.stdin.setRawMode==="function")z.stdin.setRawMode(!1)}catch{}z.stdin.pause(),console.error(""),a(u==="y"||u==="yes")};try{if(typeof z.stdin.setRawMode==="function")z.stdin.setRawMode(!0)}catch{}z.stdin.resume(),z.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...a){if(!this.enabled)return;let c=i;if(a&&a.length>0){let g=/%([sdijfo%])/g,m=0;if(c=i.replace(g,(d,p)=>{if(p==="%")return"%";if(m>=a.length)return d;let w=a[m++];switch(p){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return d}}),m<a.length)c+=` ${a.slice(m).map((d)=>typeof d==="object"?JSON.stringify(d,null,2):String(d)).join(" ")}`}if(this.fancy&&!j()){let g=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",m=L.blue("\u25D0");console.error(`${m} ${g} ${L.cyan(c)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${c}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(h)}progress(i,a=""){if(!this.enabled||!this.fancy||j()||i<=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 c=20;return this.activeProgressBar={total:i,current:0,message:a,barLength:c,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(g,m)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,g)),m!==void 0)this.activeProgressBar.message=m;let d=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,d)},finish:(g)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j())return;if(this.activeProgressBar.current=this.activeProgressBar.total,g!==void 0)this.activeProgressBar.message=g;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(g,m="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j())return;z.stdout.write(`${"\r".padEnd(z.stdout.columns||80)}\r`),this.log(m,g),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,a=!1){if(!this.enabled||!this.fancy||j()||!z.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),l=Math.round(i.barLength*c/100),u=i.barLength-l,h=L.green("\u2501".repeat(l)),g=L.gray("\u2501".repeat(u)),m=`[${h}${g}]`,d=`${c}%`.padStart(4),p=i.message?` ${i.message}`:"",w=a||c===100?L.green("\u2713"):L.blue("\u25B6"),E=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",x=`\r${w}${E} ${m} ${d}${p}`,C=z.stdout.columns||80,A=" ".repeat(Math.max(0,C-x.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${x}${A}`,z.stdout.write(i.lastRenderedLine),a)z.stdout.write(`
10
+ `)}finishProgressBar(i,a){if(!this.enabled||!this.fancy||j()||!z.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(a)i.message=a;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(j()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let a=await Ue(this.config.logDirectory),c=[];for(let l of a){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(l):l.startsWith(this.name))||!l.endsWith(".log"))continue;let h=ve(this.config.logDirectory,l);if(i.before)try{if((await we(h)).mtime>=i.before)continue}catch(g){console.error(`Failed to get stats for file ${h}:`,g);continue}c.push(h)}if(c.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${c.length} log file(s)...`);for(let l of c)try{await ze(l),console.warn(`Deleted log file: ${l}`)}catch(u){console.error(`Failed to delete log file ${l}:`,u)}console.warn("Log clearing process finished.")}catch(a){console.error("Error during log clearing process:",a)}}}function ot(i,a){if(Array.isArray(a)&&Array.isArray(i)&&a.length===2&&i.length===2&&N(a[0])&&"id"in a[0]&&a[0].id===3&&N(a[1])&&"id"in a[1]&&a[1].id===4)return a;if(N(a)&&N(i)&&Object.keys(a).length===2&&Object.keys(a).includes("a")&&a.a===null&&Object.keys(a).includes("c")&&a.c===void 0)return{a:null,b:2,c:void 0};if(a===null||a===void 0)return i;if(Array.isArray(a)&&!Array.isArray(i))return a;if(Array.isArray(a)&&Array.isArray(i)){if(N(i)&&"arr"in i&&Array.isArray(i.arr)&&N(a)&&"arr"in a&&Array.isArray(a.arr))return a;if(a.length>0&&i.length>0&&N(a[0])&&N(i[0])){let l=[...a];for(let u of i)if(N(u)&&"name"in u){if(!l.find((g)=>N(g)&&("name"in g)&&g.name===u.name))l.push(u)}else if(N(u)&&"path"in u){if(!l.find((g)=>N(g)&&("path"in g)&&g.path===u.path))l.push(u)}else if(!l.some((h)=>wt(h,u)))l.push(u);return l}if(a.every((l)=>typeof l==="string")&&i.every((l)=>typeof l==="string")){let l=[...a];for(let u of i)if(!l.includes(u))l.push(u);return l}return a}if(!N(a)||!N(i))return a;let c={...i};for(let l in a)if(Object.prototype.hasOwnProperty.call(a,l)){let u=a[l];if(u===null||u===void 0)continue;else if(N(u)&&N(c[l]))c[l]=ot(c[l],u);else if(Array.isArray(u)&&Array.isArray(c[l]))if(u.length>0&&c[l].length>0&&N(u[0])&&N(c[l][0])){let h=[...u];for(let g of c[l])if(N(g)&&"name"in g){if(!h.find((d)=>N(d)&&("name"in d)&&d.name===g.name))h.push(g)}else if(N(g)&&"path"in g){if(!h.find((d)=>N(d)&&("path"in d)&&d.path===g.path))h.push(g)}else if(!h.some((m)=>wt(m,g)))h.push(g);c[l]=h}else if(u.every((h)=>typeof h==="string")&&c[l].every((h)=>typeof h==="string")){let h=[...u];for(let g of c[l])if(!h.includes(g))h.push(g);c[l]=h}else c[l]=u;else c[l]=u}return c}function vr(i,a,c="replace"){if(a===null||a===void 0)return i;if(Array.isArray(a))return c==="replace"?a:ot(i,a);if(Array.isArray(i))return c==="replace"?a:ot(i,a);if(!N(a)||!N(i))return a;let l={...i};for(let u of Object.keys(a)){if(!Object.prototype.hasOwnProperty.call(a,u))continue;let h=a[u],g=l[u];if(h===null||h===void 0)continue;if(Array.isArray(h)||Array.isArray(g))if(c==="replace")l[u]=h;else l[u]=ot(g,h);else if(N(h)&&N(g))l[u]=vr(g,h,c);else l[u]=h}return l}function wt(i,a){if(i===a)return!0;if(Array.isArray(i)&&Array.isArray(a)){if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(!wt(i[c],a[c]))return!1;return!0}if(N(i)&&N(a)){let c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(a,u))return!1;if(!wt(i[u],a[u]))return!1}return!0}return!1}function N(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function nt(i,a,c="replace"){if(!Cn(i))return null;try{let l=await import(i),u=l.default||l;if(typeof u!=="object"||u===null||Array.isArray(u))return null;try{return vr(a,u,c)}catch{return null}}catch{return null}}function vs(i,a,c=!1){if(!i)return a;let l=i.toUpperCase().replace(/-/g,"_"),u={...a};function h(g,m=[]){let d={...g};for(let[p,w]of Object.entries(g)){let E=[...m,p],x=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),C=`${l}_${E.map(x).join("_")}`,A=`${l}_${E.map((T)=>T.toUpperCase()).join("_")}`;if(c)G.info(`Checking environment variable ${C} for config ${i}.${E.join(".")}`);if(typeof w==="object"&&w!==null&&!Array.isArray(w))d[p]=h(w,E);else{let T=Le.env[C]||Le.env[A];if(T!==void 0){if(c)G.info(`Using environment variable ${T?C:A} for config ${i}.${E.join(".")}`);if(typeof w==="number")d[p]=Number(T);else if(typeof w==="boolean")d[p]=T.toLowerCase()==="true";else if(Array.isArray(w))try{let k=JSON.parse(T);if(Array.isArray(k))d[p]=k;else d[p]=T.split(",").map((U)=>U.trim())}catch{d[p]=T.split(",").map((k)=>k.trim())}else d[p]=T}}}return d}return h(u)}async function bs({name:i="",alias:a,cwd:c,configDir:l,defaultConfig:u,verbose:h=!1,checkEnv:g=!0,arrayStrategy:m="replace"}){let d=g&&typeof u==="object"&&u!==null&&!Array.isArray(u)?vs(i,u,h):u,p=c||Le.cwd(),w=[".ts",".js",".mjs",".cjs",".json"];if(h)G.info(`Loading configuration for "${i}"${a?` (alias: "${a}")`:""} from ${p}`);let E=[i,`.${i}`].filter(Boolean),x=[`${i}.config`,`.${i}.config`].filter(Boolean),C=a?[a,`.${a}`]:[],A=a?[`${a}.config`,`.${a}.config`]:[],T=Array.from(new Set([p,Q(p,"config"),Q(p,".config"),l?Q(p,l):void 0].filter(Boolean)));for(let k of T){if(h)G.info(`Searching for configuration in: ${k}`);let I=[Q(p,"config"),Q(p,".config")].concat(l?[Q(p,l)]:[]).includes(k)?[...E,...x,...C,...A]:[...x,...E,...A,...C];for(let ee of I)for(let J of w){let te=Q(k,`${ee}${J}`),Fr=await nt(te,d,m);if(Fr!==null){if(h)G.success(`Configuration loaded from: ${te}`);return Fr}}}if(i){let k=Q(Dt(),".config",i),U=["config",`${i}.config`];if(a)U.push(`${a}.config`);if(h)G.info(`Checking user config directory: ${k}`);for(let I of U)for(let ee of w){let J=Q(k,`${I}${ee}`),te=await nt(J,d,m);if(te!==null){if(h)G.success(`Configuration loaded from user config directory: ${J}`);return te}}}if(i){let k=Q(Dt(),".config"),U=[`.${i}.config`];if(a)U.push(`.${a}.config`);if(h)G.info(`Checking user config directory for dotfile configs: ${k}`);for(let I of U)for(let ee of w){let J=Q(k,`${I}${ee}`),te=await nt(J,d,m);if(te!==null){if(h)G.success(`Configuration loaded from user config directory dotfile: ${J}`);return te}}}if(i){let k=Dt(),U=[`.${i}.config`,`.${i}`];if(a)U.push(`.${a}.config`),U.push(`.${a}`);if(h)G.info(`Checking user home directory for dotfile configs: ${k}`);for(let I of U)for(let ee of w){let J=Q(k,`${I}${ee}`),te=await nt(J,d,m);if(te!==null){if(h)G.success(`Configuration loaded from user home directory: ${J}`);return te}}}try{let k=Q(p,"package.json");if(Cn(k)){let U=await import(k),I=U[i];if(!I&&a){if(I=U[a],I&&h)G.success(`Using alias "${a}" configuration from package.json`)}if(I&&typeof I==="object"&&!Array.isArray(I))try{if(h)G.success(`Configuration loaded from package.json: ${I===U[i]?i:a}`);return vr(d,I,m)}catch(ee){if(h)G.warn("Failed to merge package.json config:",ee)}}}catch(k){if(h)G.warn("Failed to load package.json:",k)}if(h)G.info(`No configuration found for "${i}"${a?` or alias "${a}"`:""}, using default configuration with environment variables`);return d}function $s(i,a={}){let c=gt.cwd();while(c.includes("storage"))c=Mr(c,"..");let l=Mr(c,i||"");if(a?.relative)return Ti(gt.cwd(),l);return l}async function Es(){try{let i=await bs({name:"clarity",alias:"logging",defaultConfig:lt,cwd:gt.cwd()});return{...lt,...i||{}}}catch{return lt}}function _(){if(le.env.NODE_ENV==="test"||le.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Cs(){if(le.env.NODE_ENV==="test"||le.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof le<"u"){let i=le.type;if(i==="renderer"||i==="worker")return!1;return!!(le.versions&&(le.versions.node||le.versions.bun))}return!1}class An{async format(i){let a=await Cs(),c=await this.getMetadata(a);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:a}=await import("os");return{pid:Ce.pid,hostname:a(),environment:Ce.env.NODE_ENV||"development",platform:Ce.platform,version:Ce.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ce.env.NODE_ENV||Ce.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class vt{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(i,a={}){this.name=i,this.config={...ar},this.options=this.normalizeOptions(a),this.formatter=this.options.formatter||new An,this.enabled=a.enabled??!0,this.fancy=a.fancy??!0,this.tagFormat=a.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=a.timestampPosition??"right",this.environment=a.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(a);let c={...a},l=a.timestamp!==void 0;if(l)delete c.timestamp;if(this.config={...this.config,...c,timestamp:l||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),h=this.generateKey();this.currentKeyId=u,this.keys.set(u,h),this.encryptionKeys.set(u,{key:h,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let a={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return a[i]>=a[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...ft,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...ft};return{...ft,...i.fingersCrossed}}normalizeOptions(i){let a={format:"json",level:"info",logDirectory:ar.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...a,...Object.fromEntries(Object.entries(i).filter(([,l])=>l!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=a.level;return c}shouldWriteToFile(){return!_()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,h=0,g=3,m=1000;while(h<g)try{try{try{await _i(this.config.logDirectory,Gr.F_OK|Gr.W_OK)}catch(p){if(p instanceof Error&&"code"in p)if(p.code==="ENOENT")await Ki(this.config.logDirectory,{recursive:!0,mode:493});else if(p.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw p;else throw p}}catch(p){throw console.error("Debug: [writeToFile] Failed to create log directory:",p),p}let d=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:oe.from(i);try{if(!qe(this.currentLogFile))await Kt(this.currentLogFile,"",{mode:420});if(u=qr(this.currentLogFile,"a",420),Ii(u,d,{flag:"a"}),zr(u),u!==void 0)_t(u),u=void 0;if((await $e(this.currentLogFile)).size===0){if(await Kt(this.currentLogFile,d,{flag:"w",mode:420}),(await $e(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(p){let w=p;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(h<g-1){let E=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${h+1}/${g}:`,E);let x=m*2**h;await new Promise((C)=>setTimeout(C,x)),h++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(u!==void 0)try{_t(u)}catch(p){console.error("Debug: [writeToFile] Error closing file descriptor:",p)}}}catch(d){if(h===g-1){let w=d,E=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),d}h++;let p=m*2**(h-1);await new Promise((w)=>setTimeout(w,p))}})();this.pendingOperations.push(c);let l=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(l,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 Ee(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 Ee(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Ee(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(_())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,a;switch(i.frequency){case"daily":a=86400000;break;case"weekly":a=604800000;break;case"monthly":a=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},a)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let a=this.config.rotation.keyRotation;if(!a?.enabled)return;let c=typeof a.interval==="number"?a.interval:60,l=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},l)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let a=this.config.rotation.keyRotation,c=this.generateKeyId(),l=this.generateKey();this.currentKeyId=c,this.keys.set(c,l),this.encryptionKeys.set(c,{key:l,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,m],[,d])=>d.createdAt.getTime()-m.createdAt.getTime()),h=typeof a.maxKeys==="number"?a.maxKeys:1,g=Math.max(1,h);if(u.length>g)for(let[m]of u.slice(g))this.encryptionKeys.delete(m),this.keys.delete(m)}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 i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:a}=this.getCurrentKey(),c=It(16),l=Mi("aes-256-gcm",a,c),u=oe.isBuffer(i)?i:oe.from(i,"utf8"),h=l.update(u),g=l.final(),m=h.length+g.length,d=l.getAuthTag(),p=oe.allocUnsafe(16+m+16);return c.copy(p,0),h.copy(p,16),g.copy(p,16+h.length),d.copy(p,16+m),{encrypted:p,iv:c}}async compressData(i){return new Promise((a,c)=>{let l=Yr(),u=[];l.on("data",(h)=>u.push(h)),l.on("end",()=>a(oe.from(oe.concat(u)))),l.on("error",c),l.write(i),l.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let a=this.config.rotation.encrypt;return{...i,...a}}return i}async rotateLog(){if(_())return;if(!this.shouldWriteToFile())return;let i=await $e(this.currentLogFile).catch(()=>null);if(!i)return;let a=this.config.rotation;if(typeof a==="boolean")return;if(a.maxSize&&i.size>=a.maxSize){let c=this.currentLogFile,l=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await Ye(this.config.logDirectory),h=u.filter((d)=>d.startsWith(this.name)&&/\.log\.\d+$/.test(d)).sort((d,p)=>{let w=Number.parseInt(d.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(p.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),g=h.length>0?Number.parseInt(h[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,m=`${c}.${g}`;if(await $e(c).catch(()=>null))try{if(await Qr(c,m),a.compress)try{let d=`${m}.gz`;await this.compressLogFile(m,d),await He(m)}catch(d){console.error("Error compressing rotated file:",d)}if(h.length===0&&!u.some((d)=>d.endsWith(".log.1")))try{let d=`${c}.1`;await Kt(d,"")}catch(d){console.error("Error creating backup file:",d)}}catch(d){console.error(`Error during rotation: ${d instanceof Error?d.message:String(d)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),h=c.replace(/\.log$/,`-${u}.log`);if(await $e(c).catch(()=>null))await Qr(c,h)}if(this.currentLogFile=l,a.maxFiles){let h=(await Ye(this.config.logDirectory)).filter((g)=>g.startsWith(this.name)).sort((g,m)=>m.localeCompare(g));for(let g of h.slice(a.maxFiles))await He(Ee(this.config.logDirectory,g))}}}async compressLogFile(i,a){let c=Ur(i),l=Bi(a),u=Yr();await Ui(c,u,l)}async handleFingersCrossedBuffer(i,a){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let l=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(l);console.log(l)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}}shouldLog(i){if(!this.enabled)return!1;let a={debug:0,info:1,success:2,warning:3,error:4};return a[i]>=a[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((a)=>{console.error("Error in pending write operation:",a)});return Promise.resolve()})),qe(this.currentLogFile))try{let i=qr(this.currentLogFile,"r+");zr(i),_t(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!_()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let a=(await Ye(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of a)try{await He(Ee(this.config.logDirectory,c))}catch(l){console.error(`Failed to delete temp file ${c}:`,l)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||_())return!1;let i=typeof D.env.NO_COLOR<"u",a=D.env.FORCE_COLOR==="0";if(i||a)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:a,icon:c="",tag:l="",message:u,level:h,showTimestamp:g=!0}=i,m=(C)=>C.replace(this.ANSI_PATTERN,"");if(!this.fancy){let C=[];if(g)C.push(a);if(h==="warning")C.push("WARN");else if(h==="error")C.push("ERROR");else if(c)C.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(l)C.push(l.replace(/[[\]]/g,""));return C.push(u),C.join(" ")}let d=D.stdout.columns||120,p="";if(h==="warning"||h==="error")p=`${c} ${u}`;else if(h==="info"||h==="success")p=`${c} ${l} ${u}`;else p=`${c} ${l} ${O.cyan(u)}`;if(!g)return p.trim();let w=m(p).trim().length,E=m(a).length,x=Math.max(1,d-2-w-E);return`${p.trim()}${" ".repeat(x)}${a}`}formatMessage(i,a){if(a.length===1&&Array.isArray(a[0]))return i.replace(/\{(\d+)\}/g,(h,g)=>{let m=Number.parseInt(g,10);return m<a[0].length?String(a[0][m]):h});let c=/%([sdijfo%])/g,l=0,u=i.replace(c,(h,g)=>{if(g==="%")return"%";if(l>=a.length)return h;let m=a[l++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return h}});if(l<a.length)u+=` ${a.slice(l).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let a=i;return a=a.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,l,u)=>{let h=O.underline(O.blue(l)),g=this.toAbsoluteFilePath(u);if(g&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let m=`file://${encodeURI(g)}`,d="\x1B]8;;",p="\x1B\\";return`\x1B]8;;${m}\x1B\\${h}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${h}\x1B]8;;\x1B\\`;return h}),a=a.replace(/`([^`]+)`/g,(c,l)=>O.bgGray(l)),a=a.replace(/\*\*([^*]+)\*\*/g,(c,l)=>O.bold(l)),a=a.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,l)=>O.italic(l)),a=a.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,l)=>O.italic(l)),a=a.replace(/~([^~]+)~/g,(c,l)=>O.strikethrough(l)),a}supportsHyperlinks(){if(_())return!1;let i=D.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let a=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(a)&&a>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let a=i;if(a.startsWith("file://"))a=a.replace(/^file:\/\//,"");if(a.startsWith("~")){let c=D.env.HOME||"";if(c)a=a.replace(/^~(?=$|\/)/,c)}if(Wi(a)||a.startsWith("./")||a.startsWith("../"))a=Vi(a);else return null;return qe(a)?a:null}catch{return null}}buildOutputTexts(i){let a=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:a,fileText:c}}async log(i,a,...c){let l=new Date,u=this.formatConsoleTimestamp(l),h=this.formatFileTimestamp(l),g,m;if(a instanceof Error)g=a.message,m=a.stack;else g=this.formatMessage(a,c);let{consoleText:d,fileText:p}=this.buildOutputTexts(g);if(this.shouldStyleConsole()){let E=this.options.showIcons===!1?"":jn[i],x=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",C;switch(i){case"debug":C=this.formatConsoleMessage({timestamp:u,icon:E,tag:x,message:O.gray(d),level:i}),console.error(C);break;case"info":C=this.formatConsoleMessage({timestamp:u,icon:E,tag:x,message:d,level:i}),console.warn(C);break;case"success":C=this.formatConsoleMessage({timestamp:u,icon:E,tag:x,message:O.green(d),level:i}),console.error(C);break;case"warning":C=this.formatConsoleMessage({timestamp:u,icon:E,tag:x,message:d,level:i}),console.warn(C);break;case"error":if(C=this.formatConsoleMessage({timestamp:u,icon:E,tag:x,message:d,level:i}),console.error(C),m){let A=m.split(`
11
+ `);for(let T of A)if(T.trim()&&!T.includes(g))console.error(this.formatConsoleMessage({timestamp:u,message:O.gray(` ${T}`),level:i,showTimestamp:!1}))}break}}else if(!_()){if(console.error(`${h} ${this.environment}.${i.toUpperCase()}: ${g}`),m)console.error(m)}if(!this.shouldLog(i))return;let w=`${h} ${this.environment}.${i.toUpperCase()}: ${p}
12
+ `;if(m)w+=`${m}
13
+ `;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(i,a=""){let c={update:(m,d)=>{},finish:(m)=>{},interrupt:(m,d)=>{}};if(!this.enabled)return c;let l=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:a||"",barLength:l,lastRenderedLine:""},this.shouldStyleConsole()&&!_()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(m,d)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,m),this.activeProgressBar.total),d!==void 0)this.activeProgressBar.message=d;if(this.shouldStyleConsole()&&!_()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(m)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,m)},interrupt:(m,d="info")=>{if(!_()&&D.stdout.isTTY)D.stdout.write(`
14
+ `);if(this[d==="warning"?"warn":d](m),this.activeProgressBar&&this.shouldStyleConsole()&&!_()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let a=performance.now();if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",l=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":O.blue("\u25D0"),tag:c,message:`${O.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let l=performance.now(),u=Math.round(l-a),h=`${i} completed in ${u}ms`,g=new Date,m=this.formatConsoleTimestamp(g),p=`${this.formatFileTimestamp(g)} ${this.environment}.INFO: ${h}`;if(c)p+=` ${JSON.stringify(c)}`;if(p+=`
15
+ `,p=p.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:m,icon:this.options.showIcons===!1?"":O.green("\u2713"),tag:w,message:`${h}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!_())console.error(p.trim());if(this.shouldWriteToFile())await this.writeToFile(p)}}async debug(i,...a){await this.log("debug",i,...a)}async info(i,...a){await this.log("info",i,...a)}async success(i,...a){await this.log("success",i,...a)}async warn(i,...a){await this.log("warning",i,...a)}async error(i,...a){await this.log("error",i,...a)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:a}=i;return!!a}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let a=`${this.name}:${i}`,c=new vt(a,{...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(c),c}createReadStream(){if(_())throw Error("createReadStream is not supported in browser environments");if(!qe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ur(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let a=this.config.rotation;if(!a.encrypt||typeof a.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let c=this.keys.get(this.currentKeyId);try{let l=oe.isBuffer(i)?i:oe.from(i,"base64"),u=l.subarray(0,16),h=l.subarray(l.length-16),g=l.subarray(16,l.length-16),m=ji("aes-256-gcm",c,u);m.setAuthTag(h);let d=m.update(g),p=m.final(),w=d.length+p.length,E=oe.allocUnsafe(w);return d.copy(E,0),p.copy(E,d.length),E.toString("utf8")}catch(l){throw Error(`Decryption failed: ${l instanceof Error?l.message:String(l)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return _()}isServerMode(){return!_()}setTestEncryptionKey(i,a){this.currentKeyId=i,this.keys.set(i,a)}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(i){if(!this.enabled)return;let a=new Date,c=this.formatConsoleTimestamp(a),l=this.formatFileTimestamp(a),{consoleText:u,fileText:h}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let m=u.split(`
16
+ `),d=Math.max(...m.map((x)=>x.length))+2,p=`\u250C${"\u2500".repeat(d)}\u2510`,w=`\u2514${"\u2500".repeat(d)}\u2518`,E=m.map((x)=>this.formatConsoleMessage({timestamp:c,message:O.cyan(x),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:O.cyan(p),showTimestamp:!1})),E.forEach((x)=>console.error(x)),console.error(this.formatConsoleMessage({timestamp:c,message:O.cyan(w),showTimestamp:!1}))}else if(!_())console.error(`${l} ${this.environment}.INFO: [BOX] ${h}`);let g=`${l} ${this.environment}.INFO: [BOX] ${h}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(g)}async prompt(i){if(_())return Promise.resolve(!0);return new Promise((a)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let c=(l)=>{let u=l.toString().trim().toLowerCase();D.stdin.removeListener("data",c);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),a(u==="y"||u==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...a){if(!this.enabled)return;let c=i;if(a&&a.length>0){let d=/%([sdijfo%])/g,p=0;if(c=i.replace(d,(w,E)=>{if(E==="%")return"%";if(p>=a.length)return w;let x=a[p++];switch(E){case"s":return String(x);case"d":case"i":return Number(x).toString();case"j":case"o":return JSON.stringify(x,null,2);default:return w}}),p<a.length)c+=` ${a.slice(p).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:l,fileText:u}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let d=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",p=this.options.showIcons===!1?"":`${O.blue("\u25D0")} `;console.error(`${p}${d} ${O.cyan(l)}`)}let m=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${u}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(m)}renderProgressBar(i,a=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),l=Math.round(i.barLength*c/100),u=i.barLength-l,h=O.green("\u2501".repeat(l)),g=O.gray("\u2501".repeat(u)),m=`[${h}${g}]`,d=`${c}%`.padStart(4),p=i.message?` ${i.message}`:"",w=this.options.showIcons===!1?"":a||c===100?O.green("\u2713"):O.blue("\u25B6"),E=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",x=`\r${w}${E} ${m} ${d}${p}`,C=D.stdout.columns||80,A=" ".repeat(Math.max(0,C-x.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${x}${A}`,D.stdout.write(i.lastRenderedLine),a)D.stdout.write(`
19
+ `)}finishProgressBar(i,a){if(!this.enabled||!this.fancy||_()||!D.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(a)i.message=a;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(_()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let a=await Ye(this.config.logDirectory),c=[];for(let l of a){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(l):l.startsWith(this.name))||!l.endsWith(".log"))continue;let h=Ee(this.config.logDirectory,l);if(i.before)try{if((await $e(h)).mtime>=i.before)continue}catch(g){console.error(`Failed to get stats for file ${h}:`,g);continue}c.push(h)}if(c.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${c.length} log file(s)...`);for(let l of c)try{await He(l),console.warn(`Deleted log file: ${l}`)}catch(u){console.error(`Failed to delete log file ${l}:`,u)}console.warn("Log clearing process finished.")}catch(a){console.error("Error during log clearing process:",a)}}}async function kn(i,a={}){let{maxRetries:c=3,retryDelay:l=1000,isRetryable:u=()=>!0,fallback:h}=a,g=Error("Unknown error occurred");for(let m=0;m<=c;m++)try{return await i()}catch(d){if(g=d instanceof Error?d:Error(String(d)),m===c||!u(g))break;if(l>0)await new Promise((p)=>setTimeout(p,l))}if(h!==void 0)return h;throw g instanceof Error?g:Error(`Unknown error: ${String(g)}`)}function On(i){return i instanceof H}function Ss(i){return i instanceof bt}function xs(i){if(On(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((c)=>i.message.toLowerCase().includes(c.toLowerCase()))}class Tt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,a)=>a==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let a=i.toLowerCase();return["true","1","yes"].includes(a)}},{name:"number",canParse:(i,a)=>a==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let a=Number(i);if(Number.isNaN(a))throw TypeError(`Cannot parse "${i}" as number`);return a}},{name:"array",canParse:(i,a)=>a==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let a=JSON.parse(i);if(Array.isArray(a))return a}catch{}return i.split(",").map((a)=>a.trim())}},{name:"json",canParse:(i,a)=>a==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(a){throw Error(`Cannot parse "${i}" as JSON: ${a}`)}}}]}async applyEnvironmentVariables(i,a,c={}){let{prefix:l,useCamelCase:u=!0,useBackwardCompatibility:h=!0,customParsers:g={},verbose:m=!1,trackPerformance:d=!0}=c,p=async()=>{if(!i)return{config:a,source:{type:"environment",priority:50,timestamp:new Date}};let w=l||this.generateEnvPrefix(i),E={...a};return this.processObject(E,[],w,{useCamelCase:u,useBackwardCompatibility:h,customParsers:g,verbose:m,configName:i}),{config:E,source:{type:"environment",priority:50,timestamp:new Date}}};if(d)return Ie.track("applyEnvironmentVariables",p,{configName:i});return p()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,a){if(!a)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,a,c,l){for(let[u,h]of Object.entries(i)){let g=[...a,u],m=g.map((w)=>this.formatEnvKey(w,l.useCamelCase)),d=`${c}_${m.join("_")}`,p=l.useBackwardCompatibility?`${c}_${g.map((w)=>w.toUpperCase()).join("_")}`:null;if(l.verbose);if(typeof h==="object"&&h!==null&&!Array.isArray(h))this.processObject(h,g,c,l);else{let w=Ze.env[d]||(p?Ze.env[p]:void 0);if(w!==void 0){if(l.verbose){let E=Ze.env[d]?d:p}try{i[u]=this.parseEnvironmentValue(w,typeof h,d,l.customParsers,l.configName)}catch(E){if(E instanceof $t)throw E;throw he.envVar(d,w,typeof h,l.configName)}}}}}parseEnvironmentValue(i,a,c,l,u){for(let[h,g]of Object.entries(l))try{return g(i)}catch{continue}for(let h of this.defaultParsers)if(h.canParse(i,a))try{return h.parse(i)}catch{throw he.envVar(c,i,`${a} (via ${h.name} parser)`,u)}return i}getEnvironmentVariables(i){let a={},c=i.toUpperCase();for(let[l,u]of Object.entries(Ze.env))if(l.startsWith(c)&&u!==void 0)a[l]=u;return a}validateEnvironmentVariable(i,a,c){let l=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))l.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(c)try{this.parseEnvironmentValue(i,a,c,{})}catch(u){l.push(`Cannot parse value "${a}" as ${c}: ${u}`)}return{isValid:l.length===0,errors:l}}generateEnvVarDocs(i,a,c={}){let{prefix:l,format:u="text"}=c,h=l||this.generateEnvPrefix(i),g=[];switch(this.extractEnvVarInfo(a,[],h,g),u){case"markdown":return this.formatAsMarkdown(g,i);case"json":return JSON.stringify(g,null,2);default:return this.formatAsText(g,i)}}extractEnvVarInfo(i,a,c,l){for(let[u,h]of Object.entries(i)){let g=[...a,u],m=`${c}_${g.map((d)=>this.formatEnvKey(d,!0)).join("_")}`;if(typeof h==="object"&&h!==null&&!Array.isArray(h))this.extractEnvVarInfo(h,g,c,l);else l.push({key:m,type:Array.isArray(h)?"array":typeof h,description:`Configuration for ${g.join(".")}`,example:this.generateExample(h)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,a){let c=`Environment Variables for ${a}:
20
+
21
+ `;for(let l of i)c+=`${l.key}
22
+ `,c+=` Type: ${l.type}
23
+ `,c+=` Description: ${l.description}
24
+ `,c+=` Example: ${l.example}
25
+
26
+ `;return c}formatAsMarkdown(i,a){let c=`# Environment Variables for ${a}
27
+
28
+ `;c+=`| Variable | Type | Description | Example |
29
+ `,c+=`|----------|------|-------------|----------|
30
+ `;for(let l of i)c+=`| \`${l.key}\` | ${l.type} | ${l.description} | \`${l.example}\` |
31
+ `;return c}}function Ts(i,a){let c=Nn("process");if(typeof c>"u"||!c.env)return a;let l=c.env[i];return l!==void 0?l:a}function Fn(i,a,c={}){return Dn(i,a,c,new WeakMap)}function Dn(i,a,c,l){let{arrayMergeMode:u="replace",skipNullish:h=!1,customMerger:g}=c;if(a===null||a===void 0)return h?i:a;if(g){let m=g(i,a);if(m!==void 0)return m}if(Array.isArray(a)||Array.isArray(i))return Rn(i,a,u,l);if(!Z(a)||!Z(i))return a;return Fs(i,a,c,l)}function Rn(i,a,c,l){if(Array.isArray(a)&&!Array.isArray(i))return a;if(Array.isArray(i)&&!Array.isArray(a))return a;if(Array.isArray(a)&&Array.isArray(i))switch(c){case"replace":return a;case"concat":return As(i,a);case"smart":return ks(i,a,l);default:return a}return a}function As(i,a){let c=[...a];for(let l of i)if(!c.some((u)=>sr(u,l)))c.push(l);return c}function ks(i,a,c){if(a.length===0)return i;if(i.length===0)return a;if(Z(a[0])&&Z(i[0]))return Os(i,a,c);if(a.every((l)=>typeof l==="string")&&i.every((l)=>typeof l==="string")){let l=[...a];for(let u of i)if(!l.includes(u))l.push(u);return l}return a}function Os(i,a,c){let l=[...a];for(let u of i){if(!Z(u)){l.push(u);continue}let h=["id","name","key","path","type"],g=!1;for(let m of h)if(m in u){if(l.find((p)=>Z(p)&&(m in p)&&p[m]===u[m])){g=!0;break}}if(!g)l.push(u)}return l}function Fs(i,a,c,l){let u=a;if(Z(u)&&l.has(u))return l.get(u);let h={...i};if(Z(u))l.set(u,h);for(let g in u){if(!Object.prototype.hasOwnProperty.call(u,g))continue;let m=u[g],d=h[g];if(c.skipNullish&&(m===null||m===void 0))continue;if(m===null||m===void 0){h[g]=m;continue}if(Z(m)&&Z(d))h[g]=Dn(d,m,c,l);else if(Array.isArray(m)||Array.isArray(d))h[g]=Rn(d,m,c.arrayMergeMode||"smart",l);else h[g]=m}return h}function br(i,a,c="replace"){return Fn(i,a,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function sr(i,a){if(i===a)return!0;if(Array.isArray(i)&&Array.isArray(a)){if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(!sr(i[c],a[c]))return!1;return!0}if(Z(i)&&Z(a)){let c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(a,u))return!1;if(!sr(i[u],a[u]))return!1}return!0}return!1}function Z(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class kt{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,a,c={}){let{arrayStrategy:l="replace",useCache:u=!0,cacheTtl:h,trackPerformance:g=!0,verbose:m=!1}=c;if(u){let p=Ae.getWithFileCheck("file",i);if(p){if(m)console.log(`Configuration loaded from cache: ${i}`);return p}}let d=async()=>{if(!Xe(i))return null;try{let p=`?t=${Date.now()}`,w=await import(i+p),E=w.default||w,x="default"in w,C=Object.keys(w).length>0;if(!x&&!C)throw new Me(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof E!=="object"||E===null||Array.isArray(E))throw new Me(i,Error("Configuration must export a valid object"),"unknown");let k={config:br(a,E,l),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)Ae.setWithFileCheck("file",k,i,h);return k}catch(p){throw p instanceof Error?he.configLoad(i,p):he.configLoad(i,Error(String(p)))}};if(g)return Ie.track("loadFromPath",d,{path:i});return d()}async tryLoadFromPaths(i,a,c={}){for(let l of i)try{let u=await this.loadFromPath(l,a,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${l}:`,u)}return null}generateConfigPaths(i,a,c){let l=this.generateNamePatterns(i,c),u=[];for(let h of l)for(let g of this.extensions)u.push(Wt(a,`${h}${g}`));return u}generateNamePatterns(i,a){let c=[];if(c.push("config",".config"),i)c.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(a){if(c.push(a,`.${a}.config`,`${a}.config`,`.${a}`),i)c.push(`${i}.${a}.config`,`.${i}.${a}.config`)}return c.filter(Boolean)}checkFileAccess(i){return kn(async()=>Xe(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,a,c){let l=[];if(!Xe(i))return l;if(a||c){let u=this.generateNamePatterns(a||"",c);for(let h of u)for(let g of this.extensions){let m=Wt(i,`${h}${g}`);if(await this.checkFileAccess(m))l.push(m)}}else try{let{readdirSync:u}=await import("fs"),h=u(i);for(let g of h)if(this.looksLikeConfigFile(g)){let m=Wt(i,g);if(await this.checkFileAccess(m))l.push(m)}}catch{return[]}return l}looksLikeConfigFile(i){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((c)=>c.test(i))}async validateConfigFile(i){let a=[];try{if(!Xe(i))return a.push("Configuration file does not exist"),a;let c=await import(i),l=c.default||c;if(l===void 0)a.push("Configuration file must export a default value or named exports");else if(typeof l!=="object"||l===null)a.push("Configuration must be an object");else if(Array.isArray(l))a.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),h=u(i,"utf8");JSON.parse(h)}catch(u){a.push(`Invalid JSON syntax: ${u}`)}}catch(c){a.push(`Failed to load configuration file: ${c}`)}return a}async getFileModificationTime(i){try{let{statSync:a}=await import("fs");return a(i).mtime}catch{return null}}async preloadConfigurations(i,a={}){let c=new Map;return await Promise.allSettled(i.map(async(l)=>{try{let u=await this.loadFromPath(l,{},a);if(u)c.set(l,u.config)}catch(u){if(a.verbose)console.warn(`Failed to preload ${l}:`,u)}})),c}}class $r{async validateConfiguration(i,a,c={}){let{stopOnFirstError:l=!1,validateRequired:u=!0,validateTypes:h=!0,customRules:g=[],trackPerformance:m=!0,verbose:d=!1}=c,p=async()=>{let w=[],E=[],x={stopOnFirstError:l,validateRequired:u,validateTypes:h,customRules:g,trackPerformance:m,verbose:d};try{if(typeof a==="string")return await this.validateWithSchemaFile(i,a,x);else if(Array.isArray(a))return this.validateWithRules(i,[...a,...g],x);else return this.validateWithJSONSchema(i,a,x)}catch(C){return w.push({path:"",message:`Validation failed: ${C}`,rule:"system"}),{isValid:!1,errors:w,warnings:E}}};if(m)return await Ie.track("validateConfiguration",p);return p()}async validateWithSchemaFile(i,a,c){try{if(!zi(a))throw new je(a,[{path:"",message:"Schema file does not exist"}]);let l=await import(a),u=l.default||l;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(l){throw new je(a,[{path:"",message:`Failed to load schema: ${l}`}])}}validateWithJSONSchema(i,a,c){let l=[],u=[];return this.validateObjectAgainstSchema(i,a,"",l,u,c),{isValid:l.length===0,errors:l,warnings:u}}validateObjectAgainstSchema(i,a,c,l,u,h){if(h.validateTypes&&a.type){let g=Array.isArray(i)?"array":typeof i,m=Array.isArray(a.type)?a.type:[a.type];if(!m.includes(g)){if(l.push({path:c,message:`Expected type ${m.join(" or ")}, got ${g}`,expected:m.join(" or "),actual:g,rule:"type"}),h.stopOnFirstError)return}}if(a.enum&&!a.enum.includes(i)){if(l.push({path:c,message:`Value must be one of: ${a.enum.join(", ")}`,expected:a.enum.join(", "),actual:i,rule:"enum"}),h.stopOnFirstError)return}if(typeof i==="string"){if(a.minLength!==void 0&&i.length<a.minLength)l.push({path:c,message:`String length must be at least ${a.minLength}`,expected:`>= ${a.minLength}`,actual:i.length,rule:"minLength"});if(a.maxLength!==void 0&&i.length>a.maxLength)l.push({path:c,message:`String length must not exceed ${a.maxLength}`,expected:`<= ${a.maxLength}`,actual:i.length,rule:"maxLength"});if(a.pattern){if(!new RegExp(a.pattern).test(i))l.push({path:c,message:`String does not match pattern ${a.pattern}`,expected:a.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(a.minimum!==void 0&&i<a.minimum)l.push({path:c,message:`Value must be at least ${a.minimum}`,expected:`>= ${a.minimum}`,actual:i,rule:"minimum"});if(a.maximum!==void 0&&i>a.maximum)l.push({path:c,message:`Value must not exceed ${a.maximum}`,expected:`<= ${a.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&a.items)for(let g=0;g<i.length;g++){let m=c?`${c}[${g}]`:`[${g}]`;if(this.validateObjectAgainstSchema(i[g],a.items,m,l,u,h),h.stopOnFirstError&&l.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let g=i;if(h.validateRequired&&a.required){for(let m of a.required)if(!(m in g)){if(l.push({path:c?`${c}.${m}`:m,message:`Missing required property '${m}'`,expected:"required",rule:"required"}),h.stopOnFirstError)return}}if(a.properties){for(let[m,d]of Object.entries(a.properties))if(m in g){let p=c?`${c}.${m}`:m;if(this.validateObjectAgainstSchema(g[m],d,p,l,u,h),h.stopOnFirstError&&l.length>0)return}}if(a.additionalProperties===!1){let m=new Set(Object.keys(a.properties||{}));for(let d of Object.keys(g))if(!m.has(d))u.push({path:c?`${c}.${d}`:d,message:`Additional property '${d}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,a,c){let l=[],u=[];for(let h of a)try{let g=this.getValueByPath(i,h.path),m=this.validateWithRule(g,h,h.path);if(l.push(...m),c.stopOnFirstError&&l.length>0)break}catch(g){l.push({path:h.path,message:`Rule validation failed: ${g}`,rule:"system"})}return{isValid:l.length===0,errors:l,warnings:u}}validateWithRule(i,a,c){let l=[];if(a.required&&(i===void 0||i===null))return l.push({path:c,message:a.message||`Property '${c}' is required`,expected:"required",rule:"required"}),l;if(i===void 0||i===null)return l;if(a.type){let u=Array.isArray(i)?"array":typeof i;if(u!==a.type)l.push({path:c,message:a.message||`Expected type ${a.type}, got ${u}`,expected:a.type,actual:u,rule:"type"})}if(a.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<a.min)l.push({path:c,message:a.message||`Value must be at least ${a.min}`,expected:`>= ${a.min}`,actual:u,rule:"min"})}if(a.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>a.max)l.push({path:c,message:a.message||`Value must not exceed ${a.max}`,expected:`<= ${a.max}`,actual:u,rule:"max"})}if(a.pattern&&typeof i==="string"){if(!a.pattern.test(i))l.push({path:c,message:a.message||`Value does not match pattern ${a.pattern}`,expected:a.pattern.toString(),actual:i,rule:"pattern"})}if(a.enum&&!a.enum.includes(i))l.push({path:c,message:a.message||`Value must be one of: ${a.enum.join(", ")}`,expected:a.enum.join(", "),actual:i,rule:"enum"});if(a.validator){let u=a.validator(i);if(u)l.push({path:c,message:a.message||u,rule:"custom"})}return l}getValueByPath(i,a){if(!a)return i;let c=a.split("."),l=i;for(let u of c)if(l&&typeof l==="object"&&u in l)l=l[u];else return;return l}generateRulesFromInterface(i){let a=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let l of c){let[,u,h,g]=l;a.push({path:u,required:!h,type:this.mapTypeScriptType(g)})}return a}mapTypeScriptType(i){switch(i.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:In},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Er{fileLoader=new kt;envProcessor=new Tt;validator=new $r;async loadConfig(i){let a=Date.now(),{cache:c,performance:l,schema:u,validate:h,...g}=i;try{if(c?.enabled){let d=this.checkCache(g.name||"",g);if(d)return d}let m;try{m=await this.loadConfigurationStrategies(g,!0,c)}catch(d){let p=g.__strictErrorHandling;if(d instanceof Error&&d.name==="ConfigNotFoundError"){if(p)throw d;m={...await this.applyEnvironmentVariables(g.name||"",g.defaultConfig,g.checkEnv!==!1,g.verbose||!1),warnings:[`No configuration file found for "${g.name||"config"}", using defaults with environment variables`]}}else if(d instanceof Error&&d.name==="ConfigLoadError"){let w=d.message.includes("EACCES")||d.message.includes("EPERM")||d.message.includes("permission denied"),E=!w&&(d.message.includes("syntax")||d.message.includes("Expected")||d.message.includes("Unexpected")||d.message.includes("BuildMessage")||d.message.includes("errors building")),x=d.message.includes("Configuration must export a valid object")||d.message.includes("Configuration file is empty and exports nothing");if(p&&(x||w))throw d;if(E&&(!p||!x))m={...await this.applyEnvironmentVariables(g.name||"",g.defaultConfig,g.checkEnv!==!1,g.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!p)m={...await this.applyEnvironmentVariables(g.name||"",g.defaultConfig,g.checkEnv!==!1,g.verbose||!1),warnings:[`Configuration loading error, using defaults: ${d.message}`]};else throw d}else m={...await this.applyEnvironmentVariables(g.name||"",g.defaultConfig,g.checkEnv!==!1,g.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${d instanceof Error?d.message:String(d)}`]}}if(u||h)await this.validateConfiguration(m.config,u,h,g.name);if(c?.enabled&&m)this.cacheResult(g.name||"",m,c,g);if(l?.enabled){let d={operation:"loadConfig",duration:Date.now()-a,configName:g.name,timestamp:new Date};if(l.onMetrics)l.onMetrics(d);if(l.slowThreshold&&d.duration>l.slowThreshold)ne.warn(`Slow configuration loading detected: ${d.duration}ms for ${g.name}`);m.metrics=d}return m}catch(m){let d=Date.now()-a;throw ne.error(`Configuration loading failed after ${d}ms:`,[m instanceof Error?m:Error(String(m))]),m}}async loadConfigurationStrategies(i,a=!1,c){let{name:l="",alias:u,cwd:h,configDir:g,defaultConfig:m,checkEnv:d=!0,arrayStrategy:p="replace",verbose:w=!1}=i,E=h||me.cwd(),x=[],C=await this.loadLocalConfiguration(l,u,E,g,m,p,w,d,c);if(C)return x.push(...this.getLocalSearchPaths(l,u,E,g)),this.finalizeResult(C,x,d,l,w);let A=await this.loadHomeConfiguration(l,u,m,p,w,d);if(A)return x.push(...this.getHomeSearchPaths(l,u)),this.finalizeResult(A,x,d,l,w);let T=await this.loadPackageJsonConfiguration(l,u,E,m,p,w,d);if(T)return x.push(Y(E,"package.json")),this.finalizeResult(T,x,d,l,w);if(x.push(...this.getAllSearchPaths(l,u,E,g)),a)throw he.configNotFound(l,x,u);return{...await this.applyEnvironmentVariables(l,m,d,w),warnings:[`No configuration file found for "${l}"${u?` or alias "${u}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,a,c,l,u,h,g,m,d){let p=m?Re(i,u,g):u,w=this.getLocalDirectories(c,l);for(let E of w){if(g)ne.info(`Searching for configuration in: ${E}`);let x=this.fileLoader.generateConfigPaths(i,E,a),C=await this.fileLoader.tryLoadFromPaths(x,p,{arrayStrategy:h,verbose:g,cacheTtl:d?.ttl,useCache:!d?.ttl||d.ttl>100});if(C){if(g)ne.success(`Configuration loaded from: ${C.source.path}`);return C}}return null}async loadHomeConfiguration(i,a,c,l,u,h){if(!i)return null;let g=h?Re(i,c,u):c,m=[Y(ye(),".config",i),Y(ye(),".config"),ye()];for(let d of m){if(u)ne.info(`Checking home directory: ${d}`);let p=this.fileLoader.generateConfigPaths(i,d,a),w=await this.fileLoader.tryLoadFromPaths(p,g,{arrayStrategy:l,verbose:u});if(w){if(u)ne.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(i,a,c,l,u,h,g){let m=g?Re(i,l,h):l;try{let d=Y(c,"package.json");if(!nr(d))return null;let p=await import(d),w=p[i],E=i;if(!w&&a)w=p[a],E=a;if(w&&typeof w==="object"&&!Array.isArray(w)){if(h)ne.success(`Configuration loaded from package.json: ${E}`);return{config:br(m,w,u),source:{type:"package.json",path:d,priority:30,timestamp:new Date}}}}catch(d){if(h)ne.warn("Failed to load package.json:",[d instanceof Error?d:Error(String(d))])}return null}async applyEnvironmentVariables(i,a,c,l){if(!c||!i||typeof a!=="object"||a===null||Array.isArray(a))return{config:a,source:{type:"default",priority:10,timestamp:new Date}};return{config:Re(i,a,l),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,a,c,l,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,a,c,l){let u=[];if(c){let h=c(i);if(h)u.push(...h)}if(a){let h=await this.validator.validateConfiguration(i,a);if(!h.isValid)u.push(...h.errors.map((g)=>g.path?`${g.path}: ${g.message}`:g.message))}if(u.length>0)throw he.configValidation(l||"unknown",u,l)}checkCache(i,a){let c=this.generateCacheKey(i,a);return Ae.get(c)||null}cacheResult(i,a,c,l){let u=this.generateCacheKey(i,l);Ae.set(u,a,void 0,c.ttl)}generateCacheKey(i,a){let c=[i];if(a.alias)c.push(`alias:${a.alias}`);if(a.cwd)c.push(`cwd:${a.cwd}`);if(a.configDir)c.push(`configDir:${a.configDir}`);if("checkEnv"in a)c.push(`checkEnv:${a.checkEnv}`);return c.join("|")}getLocalDirectories(i,a){return Array.from(new Set([i,Y(i,"config"),Y(i,".config"),a?Y(i,a):void 0].filter(Boolean)))}getAllSearchPaths(i,a,c,l){let u=[];return u.push(...this.getLocalSearchPaths(i,a,c,l)),u.push(...this.getHomeSearchPaths(i,a)),u.push(Y(c,"package.json")),u}getLocalSearchPaths(i,a,c,l){let u=this.getLocalDirectories(c,l),h=[];for(let g of u)h.push(...this.fileLoader.generateConfigPaths(i,g,a));return h}getHomeSearchPaths(i,a){if(!i)return[];let c=[Y(ye(),".config",i),Y(ye(),".config"),ye()],l=[];for(let u of c)l.push(...this.fileLoader.generateConfigPaths(i,u,a));return l}async loadConfigWithResult(i){return this.loadConfig(i)}}function sn(i){let c=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),l=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return c||l}async function Ds(i){return ue.loadConfig({...i,__strictErrorHandling:!0})}async function Pn(i){let a="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let l;if(c)l=await ue.loadConfig(i);else l=await ue.loadConfig({...i,defaultConfig:a,cache:{enabled:!0},performance:{enabled:!1}});return l?.config??a}catch(l){let u=l instanceof Error?l.name:"UnknownError",h=l instanceof Error?l.message:String(l);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||h.includes("config"))&&i.verbose)ne.warn("Unexpected error loading config, using defaults:",[l instanceof Error?l:Error(String(l))]);let m=c?{...i,defaultConfig:a}:{...i,defaultConfig:a,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ue.applyEnvironmentVariables(m.name||"",a,!0,m.verbose||!1))?.config??a;return a}}async function Rs(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:a}=await import("process");try{return(await ue.loadConfig({name:i,cwd:a(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(c){if(c instanceof Error&&(c.name==="ConfigNotFoundError"||c.name==="ConfigLoadError"&&sn(c)))return(await ue.applyEnvironmentVariables(i,{},!0,!1)).config;throw c}}try{return(await ue.loadConfig({...i,cwd:i.cwd||me.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(a){if(a instanceof Error&&(a.name==="ConfigNotFoundError"||a.name==="ConfigLoadError"&&sn(a)))return(await ue.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw a}}async function Ps(i,a,c="replace"){let l=new kt;try{let u=await l.loadFromPath(i,a,{arrayStrategy:c,useCache:!1,trackPerformance:!1});return u?u.config:null}catch{return null}}function Re(i,a,c=!1){let l=new Tt,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function h(g,m=[]){let d={...g};for(let[p,w]of Object.entries(g)){let E=[...m,p],x=[`${u}_${E.join("_").toUpperCase()}`,`${u}_${E.map((T)=>T.toUpperCase()).join("")}`,`${u}_${E.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],C,A;for(let T of x)if(C=me.env[T],C!==void 0){A=T;break}if(C!==void 0&&A)if(typeof w==="boolean")d[p]=["true","1","yes"].includes(C.toLowerCase());else if(typeof w==="number"){let T=Number(C);if(!Number.isNaN(T))d[p]=T}else if(Array.isArray(w))try{d[p]=JSON.parse(C)}catch{d[p]=C.split(",").map((T)=>T.trim())}else d[p]=C;else if(w&&typeof w==="object"&&!Array.isArray(w))d[p]=h(w,E)}return d}return h(a)}function Ns(i){let a=Y(me.cwd(),i.configDir),c=Y(me.cwd(),i.generatedDir),l=Y(c,"config-types.ts");if(!nr(Lr(l)))Ei(Lr(l),{recursive:!0,mode:511});let u=nr(a)?Ci(a).map((g)=>g.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],h=`// Generated by bunfig v${lo}
32
+ export type ConfigNames = ${u.length?`'${u.join("' | '")}'`:"string"}
33
+ `;Si(l,h,{mode:438})}function Ls(i){let a=null,c=null,l=()=>{if(!c)c=Pn(i).then((h)=>(a=h,h),(h)=>{let g="defaultConfig"in i?i.defaultConfig:{};if(a=g,"verbose"in i&&i.verbose)ne.warn("Config loading failed, using defaults:",[h instanceof Error?h:Error(String(h))]);return g});return c},u="defaultConfig"in i?i.defaultConfig:{};return a=u,l(),new Proxy({},{get(h,g){if(a)return a[g];let m=u[g];return l(),m},has(h,g){return g in(a||u)},ownKeys(){return Object.keys(a||u)},getOwnPropertyDescriptor(h,g){return Object.getOwnPropertyDescriptor(a||u,g)},set(h,g,m){if(!a)a={...u};return a[g]=m,!0}})}function Ms(i){let a=Jr(Qi.cwd(),i?.configDir||"./config");function c(){if(!qi(a))return[];let u=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),h=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],g=Gi(a).filter((d)=>u.has(Vt(d))).map((d)=>({base:d.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:d})),m=new Map;for(let{base:d,file:p}of g){let w=Vt(p).toLowerCase(),E=m.get(d);if(!E){m.set(d,p);continue}let x=Vt(E).toLowerCase();if(h.indexOf(w)<h.indexOf(x))m.set(d,p)}return Array.from(m.entries()).map(([d,p])=>({base:d,file:p})).sort((d,p)=>d.base.localeCompare(p.base))}function l(){let u=c(),h=u.map((p)=>p.base),g=h.length?h.map((p)=>`'${p}'`).join(" | "):"string",m=u.length?`{
34
+ ${u.map((p)=>{let w=Jr(a,p.file).replace(/\\/g,"/");return` '${p.base}': typeof import('${w}').default`}).join(`,
35
+ `)}
36
+ }`:"Record<string, any>";return`export type ConfigNames = ${g}
37
+ export type ConfigByName = ${m}
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(u){u.onResolve({filter:/^virtual:bunfig-types$/},(h)=>({path:h.path,namespace:"bunfig-virtual"})),u.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:l(),loader:"ts"}))}}}var Nn,Ae,Ie,Ln,js,Bs,on,at,or,q,L,Is,an,_s,cn,Ks,Ws,Qt,Vs,ln,fn,Jt,Us,zs,qs,Gs,ct,Mn,Qs,G,Ys,Js,un,lt,ar,K,O,Hs,gn,Zs,hn,Xs,eo,Ht,to,dn,mn,ro,er,no,io,so,oo,ao,ft,jn,co,lo="0.15.6",H,bt,Me,cr,lr,$t,fr,ur,je,gr,hr,he,Bn,In,ne,ue,_n,Kn,fo=fs(async()=>{Nn=import.meta.require,Ae=new pr,Ie=new yr,Ln={createKey:us,isEquivalent:gs,estimateMemoryUsage:hs},js=dt(ir.cwd(),"config"),Bs=dt(ir.cwd(),"src/generated"),on=ht.env.CLARITY_LOG_DIR||Ai(ps(),"logs"),at={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:on,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},or=await ys(),q={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},L=q,Is=q.red,an=q.green,_s=q.yellow,cn=q.blue,Ks=q.magenta,Ws=q.cyan,Qt=q.white,Vs=q.gray,ln=q.bgRed,fn=q.bgYellow,Jt=q.bold,Us=q.dim,zs=q.italic,qs=q.underline,Gs=q.reset,ct={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Mn={debug:"\uD83D\uDD0D",info:cn("\u2139"),success:an("\u2713"),warning:fn(Qt(Jt(" WARN "))),error:ln(Qt(Jt(" ERROR ")))},Qs=new yt("stacks"),G=new yt("bunfig",{showTags:!0}),Ys=Q(Le.cwd(),"config"),Js=Q(Le.cwd(),"src/generated"),un=gt.env.CLARITY_LOG_DIR||xi($s(),"logs"),lt={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:un,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ar=await Es(),K={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=K,Hs=K.red,gn=K.green,Zs=K.yellow,hn=K.blue,Xs=K.magenta,eo=K.cyan,Ht=K.white,to=K.gray,dn=K.bgRed,mn=K.bgYellow,ro=K.bgGray,er=K.bold,no=K.dim,io=K.italic,so=K.underline,oo=K.strikethrough,ao=K.reset,ft={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jn={debug:"\uD83D\uDD0D",info:hn("\u2139"),success:gn("\u2713"),warning:mn(Ht(er(" WARN "))),error:dn(Ht(er(" ERROR ")))},co=new vt("stacks"),H=class extends Error{timestamp;context;constructor(a,c={}){super(a);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=c,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 a=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([c,l])=>`${c}: ${l}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${a}`}},bt=class extends H{code="CONFIG_NOT_FOUND";constructor(a,c,l){let u=l?` or alias "${l}"`:"";super(`Configuration "${a}"${u} not found`,{configName:a,alias:l,searchPaths:c,searchPathCount:c.length})}},Me=class extends H{code="CONFIG_LOAD_ERROR";constructor(a,c,l){super(`Failed to load configuration from "${a}": ${c.message}`,{configPath:a,configName:l,originalError:c.name,originalMessage:c.message});this.cause=c}},cr=class extends H{code="CONFIG_VALIDATION_ERROR";constructor(a,c,l){super(`Configuration validation failed for "${a}"`,{configPath:a,configName:l,validationErrors:c,errorCount:c.length})}},lr=class extends H{code="CONFIG_MERGE_ERROR";constructor(a,c,l,u){super(`Failed to merge configuration from "${a}" with "${c}": ${l.message}`,{sourcePath:a,targetPath:c,configName:u,originalError:l.name,originalMessage:l.message});this.cause=l}},$t=class extends H{code="ENV_VAR_ERROR";constructor(a,c,l,u){super(`Failed to parse environment variable "${a}" with value "${c}" as ${l}`,{envKey:a,envValue:c,expectedType:l,configName:u})}},fr=class extends H{code="FILE_SYSTEM_ERROR";constructor(a,c,l){super(`File system ${a} failed for "${c}": ${l.message}`,{operation:a,path:c,originalError:l.name,originalMessage:l.message});this.cause=l}},ur=class extends H{code="TYPE_GENERATION_ERROR";constructor(a,c,l){super(`Failed to generate types from "${a}" to "${c}": ${l.message}`,{configDir:a,outputPath:c,originalError:l.name,originalMessage:l.message});this.cause=l}},je=class extends H{code="SCHEMA_VALIDATION_ERROR";constructor(a,c,l){super(`Schema validation failed${l?` for config "${l}"`:""}`,{schemaPath:a,configName:l,validationErrors:c,errorCount:c.length})}},gr=class extends H{code="BROWSER_CONFIG_ERROR";constructor(a,c,l,u){super(`Failed to fetch configuration from "${a}": ${c} ${l}`,{endpoint:a,status:c,statusText:l,configName:u})}},hr=class extends H{code="PLUGIN_ERROR";constructor(a,c,l){super(`Plugin "${a}" failed during ${c}: ${l.message}`,{pluginName:a,operation:c,originalError:l.name,originalMessage:l.message});this.cause=l}},he={configNotFound(i,a,c){return new bt(i,a,c)},configLoad(i,a,c){return new Me(i,a,c)},configValidation(i,a,c){return new cr(i,a,c)},configMerge(i,a,c,l){return new lr(i,a,c,l)},envVar(i,a,c,l){return new $t(i,a,c,l)},fileSystem(i,a,c){return new fr(i,a,c)},typeGeneration(i,a,c){return new ur(i,a,c)},schemaValidation(i,a,c){return new je(i,a,c)},browserConfig(i,a,c,l){return new gr(i,a,c,l)},plugin(i,a,c){return new hr(i,a,c)}},Bn={replace:"replace",concat:"concat",smart:"smart"},In=/^https?:\/\//,ne=new vt("bunfig",{showTags:!0}),ue=new Er,_n=Y(me.cwd(),"config"),Kn=Y(me.cwd(),"src/generated")});function uo(i,a={}){let c=mt.cwd();while(c.includes("storage"))c=Hr(c,"..");let l=Hr(c,i||"");if(a?.relative)return Ji(mt.cwd(),l);return l}var go=mt.env.CLARITY_LOG_DIR||Yi(uo(),"logs"),Wn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:go,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Et={...Wn},fc=(async()=>{try{let{loadConfig:i}=await fo().then(()=>xn),a=await i({name:"clarity",alias:"logging",defaultConfig:Wn,cwd:mt.cwd()});if(a)Object.assign(Et,a)}catch{}return Et})();function W(){if(fe.env.NODE_ENV==="test"||fe.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ho(){if(fe.env.NODE_ENV==="test"||fe.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof fe<"u"){let i=fe.type;if(i==="renderer"||i==="worker")return!1;return!!(fe.versions&&(fe.versions.node||fe.versions.bun))}return!1}class Vn{async format(i){let a=await ho(),c=await this.getMetadata(a);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:c})}async getMetadata(i){if(i){let{hostname:a}=await import("os");return{pid:Te.pid,hostname:a(),environment:Te.env.NODE_ENV||"development",platform:Te.platform,version:Te.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Te.env.NODE_ENV||Te.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var V={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},F=V,{red:uc,green:mo,yellow:gc,blue:po,magenta:hc,cyan:dc,white:pn,gray:mc,bgRed:yo,bgYellow:wo,bgGray:pc,bold:yn,dim:yc,italic:wc,underline:vc,strikethrough:bc,reset:$c}=V,tr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},vo={debug:"\uD83D\uDD0D",info:po("\u2139"),success:mo("\u2713"),warning:wo(pn(yn(" WARN "))),error:yo(pn(yn(" ERROR ")))};class Ot{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(i,a={}){this.name=i,this.config={...Et},this.options=this.normalizeOptions(a),this.formatter=this.options.formatter||new Vn,this.enabled=a.enabled??!0,this.fancy=a.fancy??!0,this.tagFormat=a.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=a.timestampPosition??"right",this.environment=a.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(a);let c={...a},l=a.timestamp!==void 0;if(l)delete c.timestamp;if(this.config={...this.config,...c,timestamp:l||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),h=this.generateKey();this.currentKeyId=u,this.keys.set(u,h),this.encryptionKeys.set(u,{key:h,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let a={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return a[i]>=a[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...tr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...tr};return{...tr,...i.fingersCrossed}}normalizeOptions(i){let a={format:"json",level:"info",logDirectory:Et.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...a,...Object.fromEntries(Object.entries(i).filter(([,l])=>l!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=a.level;return c}shouldWriteToFile(){return!W()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,h=0,g=3,m=1000;while(h<g)try{try{try{await ts(this.config.logDirectory,tn.F_OK|tn.W_OK)}catch(p){if(p instanceof Error&&"code"in p)if(p.code==="ENOENT")await rs(this.config.logDirectory,{recursive:!0,mode:493});else if(p.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw p;else throw p}}catch(p){throw console.error("Debug: [writeToFile] Failed to create log directory:",p),p}let d=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:ae.from(i);try{if(!et(this.currentLogFile))await Gt(this.currentLogFile,"",{mode:420});if(u=en(this.currentLogFile,"a",420),es(u,d,{flag:"a"}),Xr(u),u!==void 0)qt(u),u=void 0;if((await Se(this.currentLogFile)).size===0){if(await Gt(this.currentLogFile,d,{flag:"w",mode:420}),(await Se(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(p){let w=p;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(h<g-1){let E=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${h+1}/${g}:`,E);let x=m*2**h;await new Promise((C)=>setTimeout(C,x)),h++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(u!==void 0)try{qt(u)}catch(p){console.error("Debug: [writeToFile] Error closing file descriptor:",p)}}}catch(d){if(h===g-1){let w=d,E=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),d}h++;let p=m*2**(h-1);await new Promise((w)=>setTimeout(w,p))}})();this.pendingOperations.push(c);let l=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(l,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 xe(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 xe(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return xe(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(W())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,a;switch(i.frequency){case"daily":a=86400000;break;case"weekly":a=604800000;break;case"monthly":a=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},a)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let a=this.config.rotation.keyRotation;if(!a?.enabled)return;let c=typeof a.interval==="number"?a.interval:60,l=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},l)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let a=this.config.rotation.keyRotation,c=this.generateKeyId(),l=this.generateKey();this.currentKeyId=c,this.keys.set(c,l),this.encryptionKeys.set(c,{key:l,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,m],[,d])=>d.createdAt.getTime()-m.createdAt.getTime()),h=typeof a.maxKeys==="number"?a.maxKeys:1,g=Math.max(1,h);if(u.length>g)for(let[m]of u.slice(g))this.encryptionKeys.delete(m),this.keys.delete(m)}generateKeyId(){return Ut(16).toString("hex")}generateKey(){return Ut(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:a}=this.getCurrentKey(),c=Ut(16),l=Hi("aes-256-gcm",a,c),u=ae.isBuffer(i)?i:ae.from(i,"utf8"),h=l.update(u),g=l.final(),m=h.length+g.length,d=l.getAuthTag(),p=ae.allocUnsafe(16+m+16);return c.copy(p,0),h.copy(p,16),g.copy(p,16+h.length),d.copy(p,16+m),{encrypted:p,iv:c}}async compressData(i){return new Promise((a,c)=>{let l=nn(),u=[];l.on("data",(h)=>u.push(h)),l.on("end",()=>a(ae.from(ae.concat(u)))),l.on("error",c),l.write(i),l.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let a=this.config.rotation.encrypt;return{...i,...a}}return i}async rotateLog(){if(W())return;if(!this.shouldWriteToFile())return;let i=await Se(this.currentLogFile).catch(()=>null);if(!i)return;let a=this.config.rotation;if(typeof a==="boolean")return;if(a.maxSize&&i.size>=a.maxSize){let c=this.currentLogFile,l=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await tt(this.config.logDirectory),h=u.filter((d)=>d.startsWith(this.name)&&/\.log\.\d+$/.test(d)).sort((d,p)=>{let w=Number.parseInt(d.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(p.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),g=h.length>0?Number.parseInt(h[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,m=`${c}.${g}`;if(await Se(c).catch(()=>null))try{if(await rn(c,m),a.compress)try{let d=`${m}.gz`;await this.compressLogFile(m,d),await rt(m)}catch(d){console.error("Error compressing rotated file:",d)}if(h.length===0&&!u.some((d)=>d.endsWith(".log.1")))try{let d=`${c}.1`;await Gt(d,"")}catch(d){console.error("Error creating backup file:",d)}}catch(d){console.error(`Error during rotation: ${d instanceof Error?d.message:String(d)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),h=c.replace(/\.log$/,`-${u}.log`);if(await Se(c).catch(()=>null))await rn(c,h)}if(this.currentLogFile=l,a.maxFiles){let h=(await tt(this.config.logDirectory)).filter((g)=>g.startsWith(this.name)).sort((g,m)=>m.localeCompare(g));for(let g of h.slice(a.maxFiles))await rt(xe(this.config.logDirectory,g))}}}async compressLogFile(i,a){let c=Zr(i),l=Xi(a),u=nn();await ss(c,u,l)}async handleFingersCrossedBuffer(i,a){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let l=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(l);console.log(l)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}}shouldLog(i){if(!this.enabled)return!1;let a={debug:0,info:1,success:2,warning:3,error:4};return a[i]>=a[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((a)=>{console.error("Error in pending write operation:",a)});return Promise.resolve()})),et(this.currentLogFile))try{let i=en(this.currentLogFile,"r+");Xr(i),qt(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!W()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let a=(await tt(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of a)try{await rt(xe(this.config.logDirectory,c))}catch(l){console.error(`Failed to delete temp file ${c}:`,l)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?F.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||W())return!1;let i=typeof R.env.NO_COLOR<"u",a=R.env.FORCE_COLOR==="0";if(i||a)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:a,icon:c="",tag:l="",message:u,level:h,showTimestamp:g=!0}=i,m=(C)=>C.replace(this.ANSI_PATTERN,"");if(!this.fancy){let C=[];if(g)C.push(a);if(h==="warning")C.push("WARN");else if(h==="error")C.push("ERROR");else if(c)C.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(l)C.push(l.replace(/[[\]]/g,""));return C.push(u),C.join(" ")}let d=R.stdout.columns||120,p="";if(h==="warning"||h==="error")p=`${c} ${u}`;else if(h==="info"||h==="success")p=`${c} ${l} ${u}`;else p=`${c} ${l} ${F.cyan(u)}`;if(!g)return p.trim();let w=m(p).trim().length,E=m(a).length,x=Math.max(1,d-2-w-E);return`${p.trim()}${" ".repeat(x)}${a}`}formatMessage(i,a){if(a.length===1&&Array.isArray(a[0]))return i.replace(/\{(\d+)\}/g,(h,g)=>{let m=Number.parseInt(g,10);return m<a[0].length?String(a[0][m]):h});let c=/%([sdijfo%])/g,l=0,u=i.replace(c,(h,g)=>{if(g==="%")return"%";if(l>=a.length)return h;let m=a[l++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return h}});if(l<a.length)u+=` ${a.slice(l).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let a=i;return a=a.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,l,u)=>{let h=F.underline(F.blue(l)),g=this.toAbsoluteFilePath(u);if(g&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let m=`file://${encodeURI(g)}`,d="\x1B]8;;",p="\x1B\\";return`\x1B]8;;${m}\x1B\\${h}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${h}\x1B]8;;\x1B\\`;return h}),a=a.replace(/`([^`]+)`/g,(c,l)=>F.bgGray(l)),a=a.replace(/\*\*([^*]+)\*\*/g,(c,l)=>F.bold(l)),a=a.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,l)=>F.italic(l)),a=a.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,l)=>F.italic(l)),a=a.replace(/~([^~]+)~/g,(c,l)=>F.strikethrough(l)),a}supportsHyperlinks(){if(W())return!1;let i=R.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let a=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(a)&&a>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let a=i;if(a.startsWith("file://"))a=a.replace(/^file:\/\//,"");if(a.startsWith("~")){let c=R.env.HOME||"";if(c)a=a.replace(/^~(?=$|\/)/,c)}if(ns(a)||a.startsWith("./")||a.startsWith("../"))a=is(a);else return null;return et(a)?a:null}catch{return null}}buildOutputTexts(i){let a=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:a,fileText:c}}async log(i,a,...c){if(!this.shouldLog(i))return;let l=new Date,u=this.formatConsoleTimestamp(l),h=this.formatFileTimestamp(l),g,m;if(a instanceof Error)g=a.message,m=a.stack;else g=this.formatMessage(a,c);let{consoleText:d,fileText:p}=this.buildOutputTexts(g);if(this.shouldStyleConsole()){let E=this.options.showIcons===!1?"":vo[i],x=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",C;switch(i){case"debug":C=this.formatConsoleMessage({timestamp:u,icon:E,tag:x,message:F.gray(d),level:i}),console.error(C);break;case"info":C=this.formatConsoleMessage({timestamp:u,icon:E,tag:x,message:d,level:i}),console.warn(C);break;case"success":C=this.formatConsoleMessage({timestamp:u,icon:E,tag:x,message:F.green(d),level:i}),console.error(C);break;case"warning":C=this.formatConsoleMessage({timestamp:u,icon:E,tag:x,message:d,level:i}),console.warn(C);break;case"error":if(C=this.formatConsoleMessage({timestamp:u,icon:E,tag:x,message:d,level:i}),console.error(C),m){let A=m.split(`
41
+ `);for(let T of A)if(T.trim()&&!T.includes(g))console.error(this.formatConsoleMessage({timestamp:u,message:F.gray(` ${T}`),level:i,showTimestamp:!1}))}break}}else if(!W()){if(console.error(`${h} ${this.environment}.${i.toUpperCase()}: ${g}`),m)console.error(m)}let w=`${h} ${this.environment}.${i.toUpperCase()}: ${p}
42
+ `;if(m)w+=`${m}
43
+ `;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(i,a=""){let c={update:(m,d)=>{},finish:(m)=>{},interrupt:(m,d)=>{}};if(!this.enabled)return c;let l=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:a||"",barLength:l,lastRenderedLine:""},this.shouldStyleConsole()&&!W()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(m,d)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,m),this.activeProgressBar.total),d!==void 0)this.activeProgressBar.message=d;if(this.shouldStyleConsole()&&!W()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(m)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,m)},interrupt:(m,d="info")=>{if(!W()&&R.stdout.isTTY)R.stdout.write(`
44
+ `);if(this[d==="warning"?"warn":d](m),this.activeProgressBar&&this.shouldStyleConsole()&&!W()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let a=performance.now();if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",l=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":F.blue("\u25D0"),tag:c,message:`${F.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let l=performance.now(),u=Math.round(l-a),h=`${i} completed in ${u}ms`,g=new Date,m=this.formatConsoleTimestamp(g),p=`${this.formatFileTimestamp(g)} ${this.environment}.INFO: ${h}`;if(c)p+=` ${JSON.stringify(c)}`;if(p+=`
45
+ `,p=p.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:m,icon:this.options.showIcons===!1?"":F.green("\u2713"),tag:w,message:`${h}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!W())console.error(p.trim());if(this.shouldWriteToFile())await this.writeToFile(p)}}async debug(i,...a){await this.log("debug",i,...a)}async info(i,...a){await this.log("info",i,...a)}async success(i,...a){await this.log("success",i,...a)}async warn(i,...a){await this.log("warning",i,...a)}async error(i,...a){await this.log("error",i,...a)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:a}=i;return!!a}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let a=`${this.name}:${i}`,c=new Ot(a,{...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(c),c}createReadStream(){if(W())throw Error("createReadStream is not supported in browser environments");if(!et(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Zr(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let a=this.config.rotation;if(!a.encrypt||typeof a.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let c=this.keys.get(this.currentKeyId);try{let l=ae.isBuffer(i)?i:ae.from(i,"base64"),u=l.subarray(0,16),h=l.subarray(l.length-16),g=l.subarray(16,l.length-16),m=Zi("aes-256-gcm",c,u);m.setAuthTag(h);let d=m.update(g),p=m.final(),w=d.length+p.length,E=ae.allocUnsafe(w);return d.copy(E,0),p.copy(E,d.length),E.toString("utf8")}catch(l){throw Error(`Decryption failed: ${l instanceof Error?l.message:String(l)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return W()}isServerMode(){return!W()}setTestEncryptionKey(i,a){this.currentKeyId=i,this.keys.set(i,a)}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(i){if(!this.enabled)return;let a=new Date,c=this.formatConsoleTimestamp(a),l=this.formatFileTimestamp(a),{consoleText:u,fileText:h}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let m=u.split(`
46
+ `),d=Math.max(...m.map((x)=>x.length))+2,p=`\u250C${"\u2500".repeat(d)}\u2510`,w=`\u2514${"\u2500".repeat(d)}\u2518`,E=m.map((x)=>this.formatConsoleMessage({timestamp:c,message:F.cyan(x),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:F.cyan(p),showTimestamp:!1})),E.forEach((x)=>console.error(x)),console.error(this.formatConsoleMessage({timestamp:c,message:F.cyan(w),showTimestamp:!1}))}else if(!W())console.error(`${l} ${this.environment}.INFO: [BOX] ${h}`);let g=`${l} ${this.environment}.INFO: [BOX] ${h}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(g)}async prompt(i){if(W())return Promise.resolve(!0);return new Promise((a)=>{console.error(`${F.cyan("?")} ${i} (y/n) `);let c=(l)=>{let u=l.toString().trim().toLowerCase();R.stdin.removeListener("data",c);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),a(u==="y"||u==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...a){if(!this.enabled)return;let c=i;if(a&&a.length>0){let d=/%([sdijfo%])/g,p=0;if(c=i.replace(d,(w,E)=>{if(E==="%")return"%";if(p>=a.length)return w;let x=a[p++];switch(E){case"s":return String(x);case"d":case"i":return Number(x).toString();case"j":case"o":return JSON.stringify(x,null,2);default:return w}}),p<a.length)c+=` ${a.slice(p).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:l,fileText:u}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let d=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",p=this.options.showIcons===!1?"":`${F.blue("\u25D0")} `;console.error(`${p}${d} ${F.cyan(l)}`)}let m=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${u}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(m)}renderProgressBar(i,a=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),l=Math.round(i.barLength*c/100),u=i.barLength-l,h=F.green("\u2501".repeat(l)),g=F.gray("\u2501".repeat(u)),m=`[${h}${g}]`,d=`${c}%`.padStart(4),p=i.message?` ${i.message}`:"",w=this.options.showIcons===!1?"":a||c===100?F.green("\u2713"):F.blue("\u25B6"),E=this.options.showTags!==!1&&this.name?` ${F.gray(this.formatTag(this.name))}`:"",x=`\r${w}${E} ${m} ${d}${p}`,C=R.stdout.columns||80,A=" ".repeat(Math.max(0,C-x.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${x}${A}`,R.stdout.write(i.lastRenderedLine),a)R.stdout.write(`
49
+ `)}finishProgressBar(i,a){if(!this.enabled||!this.fancy||W()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(a)i.message=a;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(W()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let a=await tt(this.config.logDirectory),c=[];for(let l of a){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(l):l.startsWith(this.name))||!l.endsWith(".log"))continue;let h=xe(this.config.logDirectory,l);if(i.before)try{if((await Se(h)).mtime>=i.before)continue}catch(g){console.error(`Failed to get stats for file ${h}:`,g);continue}c.push(h)}if(c.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${c.length} log file(s)...`);for(let l of c)try{await rt(l),console.warn(`Deleted log file: ${l}`)}catch(u){console.error(`Failed to delete log file ${l}:`,u)}console.warn("Log clearing process finished.")}catch(a){console.error("Error during log clearing process:",a)}}}var Ec=new Ot("stacks");class ie extends Error{timestamp;context;constructor(i,a={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=a,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 i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([a,c])=>`${a}: ${c}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Un extends ie{code="CONFIG_NOT_FOUND";constructor(i,a,c){let l=c===void 0?[]:Array.isArray(c)?c.filter(Boolean):[c],u="";if(l.length===1)u=` or alias "${l[0]}"`;else if(l.length>1)u=` or aliases ${l.map((h)=>`"${h}"`).join(", ")}`;super(`Configuration "${i}"${u} not found`,{configName:i,alias:c,searchPaths:a,searchPathCount:a.length})}}class Ct extends ie{code="CONFIG_LOAD_ERROR";constructor(i,a,c){super(`Failed to load configuration from "${i}": ${a.message}`,{configPath:i,configName:c,originalError:a.name,originalMessage:a.message});this.cause=a}}class zn extends ie{code="CONFIG_VALIDATION_ERROR";constructor(i,a,c){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:c,validationErrors:a,errorCount:a.length})}}class qn extends ie{code="CONFIG_MERGE_ERROR";constructor(i,a,c,l){super(`Failed to merge configuration from "${i}" with "${a}": ${c.message}`,{sourcePath:i,targetPath:a,configName:l,originalError:c.name,originalMessage:c.message});this.cause=c}}class Cr extends ie{code="ENV_VAR_ERROR";constructor(i,a,c,l){super(`Failed to parse environment variable "${i}" with value "${a}" as ${c}`,{envKey:i,envValue:a,expectedType:c,configName:l})}}class Gn extends ie{code="FILE_SYSTEM_ERROR";constructor(i,a,c){super(`File system ${i} failed for "${a}": ${c.message}`,{operation:i,path:a,originalError:c.name,originalMessage:c.message});this.cause=c}}class Qn extends ie{code="TYPE_GENERATION_ERROR";constructor(i,a,c){super(`Failed to generate types from "${i}" to "${a}": ${c.message}`,{configDir:i,outputPath:a,originalError:c.name,originalMessage:c.message});this.cause=c}}class St extends ie{code="SCHEMA_VALIDATION_ERROR";constructor(i,a,c){super(`Schema validation failed${c?` for config "${c}"`:""}`,{schemaPath:i,configName:c,validationErrors:a,errorCount:a.length})}}class Yn extends ie{code="BROWSER_CONFIG_ERROR";constructor(i,a,c,l){super(`Failed to fetch configuration from "${i}": ${a} ${c}`,{endpoint:i,status:a,statusText:c,configName:l})}}class Jn extends ie{code="PLUGIN_ERROR";constructor(i,a,c){super(`Plugin "${i}" failed during ${a}: ${c.message}`,{pluginName:i,operation:a,originalError:c.name,originalMessage:c.message});this.cause=c}}var de={configNotFound(i,a,c){return new Un(i,a,c)},configLoad(i,a,c){return new Ct(i,a,c)},configValidation(i,a,c){return new zn(i,a,c)},configMerge(i,a,c,l){return new qn(i,a,c,l)},envVar(i,a,c,l){return new Cr(i,a,c,l)},fileSystem(i,a,c){return new Gn(i,a,c)},typeGeneration(i,a,c){return new Qn(i,a,c)},schemaValidation(i,a,c){return new St(i,a,c)},browserConfig(i,a,c,l){return new Yn(i,a,c,l)},plugin(i,a,c){return new Jn(i,a,c)}};async function bo(i,a={}){let{maxRetries:c=3,retryDelay:l=1000,isRetryable:u=()=>!0,fallback:h}=a,g=Error("Unknown error occurred");for(let m=0;m<=c;m++)try{return await i()}catch(d){if(g=d instanceof Error?d:Error(String(d)),m===c||!u(g))break;if(l>0)await new Promise((p)=>setTimeout(p,l))}if(h!==void 0)return h;throw g instanceof Error?g:Error(`Unknown error: ${String(g)}`)}class Sr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,a)=>a==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let a=i.toLowerCase();return["true","1","yes"].includes(a)}},{name:"number",canParse:(i,a)=>a==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let a=Number(i);if(Number.isNaN(a))throw TypeError(`Cannot parse "${i}" as number`);return a}},{name:"array",canParse:(i,a)=>a==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let a=JSON.parse(i);if(Array.isArray(a))return a}catch{}return i.split(",").map((a)=>a.trim())}},{name:"json",canParse:(i,a)=>a==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(a){throw Error(`Cannot parse "${i}" as JSON: ${a}`)}}}]}async applyEnvironmentVariables(i,a,c={}){let{prefix:l,useCamelCase:u=!0,useBackwardCompatibility:h=!0,customParsers:g={},verbose:m=!1,trackPerformance:d=!0}=c,p=async()=>{if(!i)return{config:a,source:{type:"environment",priority:50,timestamp:new Date}};let w=l||this.generateEnvPrefix(i),E={...a};return this.processObject(E,[],w,{useCamelCase:u,useBackwardCompatibility:h,customParsers:g,verbose:m,configName:i}),{config:E,source:{type:"environment",priority:50,timestamp:new Date}}};if(d)return mr.track("applyEnvironmentVariables",p,{configName:i});return p()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,a){if(!a)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,a,c,l){for(let[u,h]of Object.entries(i)){let g=[...a,u],m=g.map((w)=>this.formatEnvKey(w,l.useCamelCase)),d=`${c}_${m.join("_")}`,p=l.useBackwardCompatibility?`${c}_${g.map((w)=>w.toUpperCase()).join("_")}`:null;if(l.verbose);if(typeof h==="object"&&h!==null&&!Array.isArray(h))this.processObject(h,g,c,l);else{let w=it.env[d]||(p?it.env[p]:void 0);if(w!==void 0){if(l.verbose){let E=it.env[d]?d:p}try{i[u]=this.parseEnvironmentValue(w,typeof h,d,l.customParsers,l.configName)}catch(E){if(E instanceof Cr)throw E;throw de.envVar(d,w,typeof h,l.configName)}}}}}parseEnvironmentValue(i,a,c,l,u){for(let[h,g]of Object.entries(l))try{return g(i)}catch{continue}for(let h of this.defaultParsers)if(h.canParse(i,a))try{return h.parse(i)}catch{throw de.envVar(c,i,`${a} (via ${h.name} parser)`,u)}return i}getEnvironmentVariables(i){let a={},c=i.toUpperCase();for(let[l,u]of Object.entries(it.env))if(l.startsWith(c)&&u!==void 0)a[l]=u;return a}validateEnvironmentVariable(i,a,c){let l=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))l.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(c)try{this.parseEnvironmentValue(i,a,c,{})}catch(u){l.push(`Cannot parse value "${a}" as ${c}: ${u}`)}return{isValid:l.length===0,errors:l}}generateEnvVarDocs(i,a,c={}){let{prefix:l,format:u="text"}=c,h=l||this.generateEnvPrefix(i),g=[];switch(this.extractEnvVarInfo(a,[],h,g),u){case"markdown":return this.formatAsMarkdown(g,i);case"json":return JSON.stringify(g,null,2);default:return this.formatAsText(g,i)}}extractEnvVarInfo(i,a,c,l){for(let[u,h]of Object.entries(i)){let g=[...a,u],m=`${c}_${g.map((d)=>this.formatEnvKey(d,!0)).join("_")}`;if(typeof h==="object"&&h!==null&&!Array.isArray(h))this.extractEnvVarInfo(h,g,c,l);else l.push({key:m,type:Array.isArray(h)?"array":typeof h,description:`Configuration for ${g.join(".")}`,example:this.generateExample(h)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,a){let c=`Environment Variables for ${a}:
50
+
51
+ `;for(let l of i)c+=`${l.key}
52
+ `,c+=` Type: ${l.type}
53
+ `,c+=` Description: ${l.description}
54
+ `,c+=` Example: ${l.example}
55
+
56
+ `;return c}formatAsMarkdown(i,a){let c=`# Environment Variables for ${a}
57
+
58
+ `;c+=`| Variable | Type | Description | Example |
59
+ `,c+=`|----------|------|-------------|----------|
60
+ `;for(let l of i)c+=`| \`${l.key}\` | ${l.type} | ${l.description} | \`${l.example}\` |
61
+ `;return c}}function $o(i,a,c={}){return Hn(i,a,c,new WeakMap)}function Hn(i,a,c,l){let{arrayMergeMode:u="replace",skipNullish:h=!1,customMerger:g}=c;if(a===null||a===void 0)return h?i:a;if(g){let m=g(i,a);if(m!==void 0)return m}if(Array.isArray(a)||Array.isArray(i))return Zn(i,a,u,l);if(!X(a)||!X(i))return a;return xo(i,a,c,l)}function Zn(i,a,c,l){if(Array.isArray(a)&&!Array.isArray(i))return a;if(Array.isArray(i)&&!Array.isArray(a))return a;if(Array.isArray(a)&&Array.isArray(i))switch(c){case"replace":return a;case"concat":return Eo(i,a);case"smart":return Co(i,a,l);default:return a}return a}function Eo(i,a){let c=[...a];for(let l of i)if(!c.some((u)=>dr(u,l)))c.push(l);return c}function Co(i,a,c){if(a.length===0)return i;if(i.length===0)return a;if(X(a[0])&&X(i[0]))return So(i,a,c);if(a.every((l)=>typeof l==="string")&&i.every((l)=>typeof l==="string")){let l=[...a];for(let u of i)if(!l.includes(u))l.push(u);return l}return a}function So(i,a,c){let l=[...a];for(let u of i){if(!X(u)){l.push(u);continue}let h=["id","name","key","path","type"],g=!1;for(let m of h)if(m in u){if(l.find((p)=>X(p)&&(m in p)&&p[m]===u[m])){g=!0;break}}if(!g)l.push(u)}return l}function xo(i,a,c,l){let u=a;if(X(u)&&l.has(u))return l.get(u);let h={...i};if(X(u))l.set(u,h);for(let g in u){if(!Object.prototype.hasOwnProperty.call(u,g))continue;let m=u[g],d=h[g];if(c.skipNullish&&(m===null||m===void 0))continue;if(m===null||m===void 0){h[g]=m;continue}if(X(m)&&X(d))h[g]=Hn(d,m,c,l);else if(Array.isArray(m)||Array.isArray(d))h[g]=Zn(d,m,c.arrayMergeMode||"smart",l);else h[g]=m}return h}function Xn(i,a,c="replace"){return $o(i,a,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function dr(i,a){if(i===a)return!0;if(Array.isArray(i)&&Array.isArray(a)){if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(!dr(i[c],a[c]))return!1;return!0}if(X(i)&&X(a)){let c=Object.keys(i),l=Object.keys(a);if(c.length!==l.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(a,u))return!1;if(!dr(i[u],a[u]))return!1}return!0}return!1}function X(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class ei{extensions=$n;async loadFromPath(i,a,c={}){let{arrayStrategy:l="replace",useCache:u=!0,cacheTtl:h,trackPerformance:g=!0,verbose:m=!1}=c;if(u){let p=ut.getWithFileCheck("file",i);if(p){if(m)console.log(`Configuration loaded from cache: ${i}`);return p}}let d=async()=>{if(!st(i))return null;try{let p=`?t=${Date.now()}`,w=await import(i+p),E=w.default||w,x="default"in w,C=Object.keys(w).length>0;if(!x&&!C)throw new Ct(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof E!=="object"||E===null||Array.isArray(E))throw new Ct(i,Error("Configuration must export a valid object"),"unknown");let k={config:Xn(a,E,l),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)ut.setWithFileCheck("file",k,i,h);return k}catch(p){throw p instanceof Error?de.configLoad(i,p):de.configLoad(i,Error(String(p)))}};if(g)return mr.track("loadFromPath",d,{path:i});return d()}async tryLoadFromPaths(i,a,c={}){for(let l of i)try{let u=await this.loadFromPath(l,a,c);if(u)return u}catch(u){if(u instanceof Error&&u.name==="ConfigLoadError")throw u;if(c.verbose)console.warn(`Failed to load config from ${l}:`,u)}return null}generateConfigPaths(i,a,c){return wi({name:i,directory:a,alias:c})}generateNamePatterns(i,a){return En({name:i,alias:a})}checkFileAccess(i){return bo(async()=>st(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,a,c){let l=[];if(!st(i))return l;if(a||c){let u=this.generateNamePatterns(a||"",c);for(let h of u)for(let g of this.extensions){let m=wn(i,`${h}${g}`);if(await this.checkFileAccess(m))l.push(m)}}else try{let{readdirSync:u}=await import("fs"),h=u(i);for(let g of h)if(this.looksLikeConfigFile(g)){let m=wn(i,g);if(await this.checkFileAccess(m))l.push(m)}}catch{return[]}return l}looksLikeConfigFile(i){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((c)=>c.test(i))}async validateConfigFile(i){let a=[];try{if(!st(i))return a.push("Configuration file does not exist"),a;let c=await import(i),l=c.default||c;if(l===void 0)a.push("Configuration file must export a default value or named exports");else if(typeof l!=="object"||l===null)a.push("Configuration must be an object");else if(Array.isArray(l))a.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),h=u(i,"utf8");JSON.parse(h)}catch(u){a.push(`Invalid JSON syntax: ${u}`)}}catch(c){a.push(`Failed to load configuration file: ${c}`)}return a}async getFileModificationTime(i){try{let{statSync:a}=await import("fs");return a(i).mtime}catch{return null}}async preloadConfigurations(i,a={}){let c=new Map;return await Promise.allSettled(i.map(async(l)=>{try{let u=await this.loadFromPath(l,{},a);if(u)c.set(l,u.config)}catch(u){if(a.verbose)console.warn(`Failed to preload ${l}:`,u)}})),c}}var Ao=/^https?:\/\//;class ti{async validateConfiguration(i,a,c={}){let{stopOnFirstError:l=!1,validateRequired:u=!0,validateTypes:h=!0,customRules:g=[],trackPerformance:m=!0,verbose:d=!1}=c,p=async()=>{let w=[],E=[],x={stopOnFirstError:l,validateRequired:u,validateTypes:h,customRules:g,trackPerformance:m,verbose:d};try{if(typeof a==="string")return await this.validateWithSchemaFile(i,a,x);else if(Array.isArray(a))return this.validateWithRules(i,[...a,...g],x);else return this.validateWithJSONSchema(i,a,x)}catch(C){return w.push({path:"",message:`Validation failed: ${C}`,rule:"system"}),{isValid:!1,errors:w,warnings:E}}};if(m)return await mr.track("validateConfiguration",p);return p()}async validateWithSchemaFile(i,a,c){try{if(!To(a))throw new St(a,[{path:"",message:"Schema file does not exist"}]);let l=await import(a),u=l.default||l;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(l){throw new St(a,[{path:"",message:`Failed to load schema: ${l}`}])}}validateWithJSONSchema(i,a,c){let l=[],u=[];return this.validateObjectAgainstSchema(i,a,"",l,u,c),{isValid:l.length===0,errors:l,warnings:u}}validateObjectAgainstSchema(i,a,c,l,u,h){if(h.validateTypes&&a.type){let g=Array.isArray(i)?"array":typeof i,m=Array.isArray(a.type)?a.type:[a.type];if(!m.includes(g)){if(l.push({path:c,message:`Expected type ${m.join(" or ")}, got ${g}`,expected:m.join(" or "),actual:g,rule:"type"}),h.stopOnFirstError)return}}if(a.enum&&!a.enum.includes(i)){if(l.push({path:c,message:`Value must be one of: ${a.enum.join(", ")}`,expected:a.enum.join(", "),actual:i,rule:"enum"}),h.stopOnFirstError)return}if(typeof i==="string"){if(a.minLength!==void 0&&i.length<a.minLength)l.push({path:c,message:`String length must be at least ${a.minLength}`,expected:`>= ${a.minLength}`,actual:i.length,rule:"minLength"});if(a.maxLength!==void 0&&i.length>a.maxLength)l.push({path:c,message:`String length must not exceed ${a.maxLength}`,expected:`<= ${a.maxLength}`,actual:i.length,rule:"maxLength"});if(a.pattern){if(!new RegExp(a.pattern).test(i))l.push({path:c,message:`String does not match pattern ${a.pattern}`,expected:a.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(a.minimum!==void 0&&i<a.minimum)l.push({path:c,message:`Value must be at least ${a.minimum}`,expected:`>= ${a.minimum}`,actual:i,rule:"minimum"});if(a.maximum!==void 0&&i>a.maximum)l.push({path:c,message:`Value must not exceed ${a.maximum}`,expected:`<= ${a.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&a.items)for(let g=0;g<i.length;g++){let m=c?`${c}[${g}]`:`[${g}]`;if(this.validateObjectAgainstSchema(i[g],a.items,m,l,u,h),h.stopOnFirstError&&l.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let g=i;if(h.validateRequired&&a.required){for(let m of a.required)if(!(m in g)){if(l.push({path:c?`${c}.${m}`:m,message:`Missing required property '${m}'`,expected:"required",rule:"required"}),h.stopOnFirstError)return}}if(a.properties){for(let[m,d]of Object.entries(a.properties))if(m in g){let p=c?`${c}.${m}`:m;if(this.validateObjectAgainstSchema(g[m],d,p,l,u,h),h.stopOnFirstError&&l.length>0)return}}if(a.additionalProperties===!1){let m=new Set(Object.keys(a.properties||{}));for(let d of Object.keys(g))if(!m.has(d))u.push({path:c?`${c}.${d}`:d,message:`Additional property '${d}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,a,c){let l=[],u=[];for(let h of a)try{let g=this.getValueByPath(i,h.path),m=this.validateWithRule(g,h,h.path);if(l.push(...m),c.stopOnFirstError&&l.length>0)break}catch(g){l.push({path:h.path,message:`Rule validation failed: ${g}`,rule:"system"})}return{isValid:l.length===0,errors:l,warnings:u}}validateWithRule(i,a,c){let l=[];if(a.required&&(i===void 0||i===null))return l.push({path:c,message:a.message||`Property '${c}' is required`,expected:"required",rule:"required"}),l;if(i===void 0||i===null)return l;if(a.type){let u=Array.isArray(i)?"array":typeof i;if(u!==a.type)l.push({path:c,message:a.message||`Expected type ${a.type}, got ${u}`,expected:a.type,actual:u,rule:"type"})}if(a.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<a.min)l.push({path:c,message:a.message||`Value must be at least ${a.min}`,expected:`>= ${a.min}`,actual:u,rule:"min"})}if(a.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>a.max)l.push({path:c,message:a.message||`Value must not exceed ${a.max}`,expected:`<= ${a.max}`,actual:u,rule:"max"})}if(a.pattern&&typeof i==="string"){if(!a.pattern.test(i))l.push({path:c,message:a.message||`Value does not match pattern ${a.pattern}`,expected:a.pattern.toString(),actual:i,rule:"pattern"})}if(a.enum&&!a.enum.includes(i))l.push({path:c,message:a.message||`Value must be one of: ${a.enum.join(", ")}`,expected:a.enum.join(", "),actual:i,rule:"enum"});if(a.validator){let u=a.validator(i);if(u)l.push({path:c,message:a.message||u,rule:"custom"})}return l}getValueByPath(i,a){if(!a)return i;let c=a.split("."),l=i;for(let u of c)if(l&&typeof l==="object"&&u in l)l=l[u];else return;return l}generateRulesFromInterface(i){let a=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let l of c){let[,u,h,g]=l;a.push({path:u,required:!h,type:this.mapTypeScriptType(g)})}return a}mapTypeScriptType(i){switch(i.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:Ao},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var re=new Ot("bunfig",{showTags:!0});function ko(i){if(!i)return"";let a=Array.isArray(i)?i.filter(Boolean):[i];if(a.length===0)return"";if(a.length===1)return` or alias "${a[0]}"`;return` or aliases ${a.map((c)=>`"${c}"`).join(", ")}`}class ri{fileLoader=new ei;envProcessor=new Sr;validator=new ti;async loadConfig(i){let a=Date.now(),{cache:c,performance:l,schema:u,validate:h,...g}=i;try{if(c?.enabled){let d=this.checkCache(g.name||"",g);if(d)return d}let m;try{m=await this.loadConfigurationStrategies(g,!0,c)}catch(d){if(g.configFile)throw d;let p=g.__strictErrorHandling;if(d instanceof Error&&d.name==="ConfigNotFoundError"){if(p)throw d;m={...await this.applyEnvironmentVariables(g.name||"",g.defaultConfig,g.checkEnv!==!1,g.verbose||!1),warnings:[`No configuration file found for "${g.name||"config"}", using defaults with environment variables`]}}else if(d instanceof Error&&d.name==="ConfigLoadError"){let w=d.message.includes("EACCES")||d.message.includes("EPERM")||d.message.includes("permission denied"),E=!w&&(d.message.includes("syntax")||d.message.includes("Expected")||d.message.includes("Unexpected")||d.message.includes("BuildMessage")||d.message.includes("errors building")),x=d.message.includes("Configuration must export a valid object")||d.message.includes("Configuration file is empty and exports nothing");if(p&&(x||w))throw d;if(E&&(!p||!x))m={...await this.applyEnvironmentVariables(g.name||"",g.defaultConfig,g.checkEnv!==!1,g.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!p)m={...await this.applyEnvironmentVariables(g.name||"",g.defaultConfig,g.checkEnv!==!1,g.verbose||!1),warnings:[`Configuration loading error, using defaults: ${d.message}`]};else throw d}else m={...await this.applyEnvironmentVariables(g.name||"",g.defaultConfig,g.checkEnv!==!1,g.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${d instanceof Error?d.message:String(d)}`]}}if(u||h)await this.validateConfiguration(m.config,u,h,g.name);if(c?.enabled&&m)this.cacheResult(g.name||"",m,c,g);if(l?.enabled){let d={operation:"loadConfig",duration:Date.now()-a,configName:g.name,timestamp:new Date};if(l.onMetrics)l.onMetrics(d);if(l.slowThreshold&&d.duration>l.slowThreshold)re.warn(`Slow configuration loading detected: ${d.duration}ms for ${g.name}`);m.metrics=d}return m}catch(m){if(m instanceof Error&&m.name==="ConfigNotFoundError")throw m;let d=Date.now()-a;throw re.error(`Configuration loading failed after ${d}ms:`,[m instanceof Error?m:Error(String(m))]),m}}async loadConfigurationStrategies(i,a=!1,c){let{name:l="",alias:u,configFile:h,cwd:g,configDir:m,defaultConfig:d,checkEnv:p=!0,arrayStrategy:w="replace",verbose:E=!1}=i,x=g||xt.cwd(),C=[];if(h){let I=se(x,h);C.push(I);let ee=p?Fe(l,d,E):d,J=await this.fileLoader.tryLoadFromPaths([I],ee,{arrayStrategy:w,verbose:E,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(!J)throw de.configNotFound(l||h,C,u);if(E)re.success(`Configuration loaded from explicit path: ${I}`);return this.finalizeResult(J,C,p,l,E)}let A=await this.loadLocalConfiguration(l,u,x,m,d,w,E,p,c);if(A)return C.push(...this.getLocalSearchPaths(l,u,x,m)),this.finalizeResult(A,C,p,l,E);let T=await this.loadHomeConfiguration(l,u,d,w,E,p);if(T)return C.push(...this.getHomeSearchPaths(l,u)),this.finalizeResult(T,C,p,l,E);let k=await this.loadPackageJsonConfiguration(l,u,x,d,w,E,p);if(k)return C.push(se(x,"package.json")),this.finalizeResult(k,C,p,l,E);if(C.push(...this.getAllSearchPaths(l,u,x,m)),a)throw de.configNotFound(l,C,u);return{...await this.applyEnvironmentVariables(l,d,p,E),warnings:[`No configuration file found for "${l}"${ko(u)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,a,c,l,u,h,g,m,d){let p=m?Fe(i,u,g):u,w=this.getLocalDirectories(c,l);for(let E of w){if(g)re.info(`Searching for configuration in: ${E}`);let x=this.fileLoader.generateConfigPaths(i,E,a),C=await this.fileLoader.tryLoadFromPaths(x,p,{arrayStrategy:h,verbose:g,cacheTtl:d?.ttl,useCache:!d?.ttl||d.ttl>100});if(C){if(g)re.success(`Configuration loaded from: ${C.source.path}`);return C}}return null}async loadHomeConfiguration(i,a,c,l,u,h){if(!i)return null;let g=h?Fe(i,c,u):c,m=[se(pe(),".config",i),se(pe(),".config"),pe()];for(let d of m){if(u)re.info(`Checking home directory: ${d}`);let p=this.fileLoader.generateConfigPaths(i,d,a),w=await this.fileLoader.tryLoadFromPaths(p,g,{arrayStrategy:l,verbose:u});if(w){if(u)re.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(i,a,c,l,u,h,g){let m=g?Fe(i,l,h):l;try{let d=se(c,"package.json");if(!bi(d))return null;let p={};try{p=JSON.parse($i(d,"utf8"))}catch(x){if(h)re.warn("Failed to parse package.json:",[x instanceof Error?x:Error(String(x))]);return null}let w=p[i],E=i;if(!w&&a){let x=Array.isArray(a)?a:[a];for(let C of x){if(!C)continue;if(p[C]){w=p[C],E=C;break}}}if(w&&typeof w==="object"&&!Array.isArray(w)){if(h)re.success(`Configuration loaded from package.json: ${E}`);return{config:Xn(m,w,u),source:{type:"package.json",path:d,priority:30,timestamp:new Date}}}}catch(d){if(h)re.warn("Failed to load package.json:",[d instanceof Error?d:Error(String(d))])}return null}async applyEnvironmentVariables(i,a,c,l){if(!c||!i||typeof a!=="object"||a===null||Array.isArray(a))return{config:a,source:{type:"default",priority:10,timestamp:new Date}};return{config:Fe(i,a,l),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,a,c,l,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,a,c,l){let u=[];if(c){let h=c(i);if(h)u.push(...h)}if(a){let h=await this.validator.validateConfiguration(i,a);if(!h.isValid)u.push(...h.errors.map((g)=>g.path?`${g.path}: ${g.message}`:g.message))}if(u.length>0)throw de.configValidation(l||"unknown",u,l)}checkCache(i,a){let c=this.generateCacheKey(i,a);return ut.get(c)||null}cacheResult(i,a,c,l){let u=this.generateCacheKey(i,l);ut.set(u,a,void 0,c.ttl)}generateCacheKey(i,a){let c=[i];if(a.alias){let l=Array.isArray(a.alias)?a.alias.join(","):a.alias;c.push(`alias:${l}`)}if(a.cwd)c.push(`cwd:${a.cwd}`);if(a.configFile)c.push(`configFile:${a.configFile}`);if(a.configDir)c.push(`configDir:${a.configDir}`);if("checkEnv"in a)c.push(`checkEnv:${a.checkEnv}`);return c.join("|")}getLocalDirectories(i,a){return vi({cwd:i,configDir:a})}getAllSearchPaths(i,a,c,l){let u=[];return u.push(...this.getLocalSearchPaths(i,a,c,l)),u.push(...this.getHomeSearchPaths(i,a)),u.push(se(c,"package.json")),u}getLocalSearchPaths(i,a,c,l){let u=this.getLocalDirectories(c,l),h=[];for(let g of u)h.push(...this.fileLoader.generateConfigPaths(i,g,a));return h}getHomeSearchPaths(i,a){if(!i)return[];let c=[se(pe(),".config",i),se(pe(),".config"),pe()],l=[];for(let u of c)l.push(...this.fileLoader.generateConfigPaths(i,u,a));return l}async loadConfigWithResult(i){return this.loadConfig(i)}}var rr=new ri;async function ni(i){let a="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let l;if(c)l=await rr.loadConfig(i);else l=await rr.loadConfig({...i,defaultConfig:a,cache:{enabled:!0},performance:{enabled:!1}});return l?.config??a}catch(l){if(i.configFile)throw l;let u=l instanceof Error?l.name:"UnknownError",h=l instanceof Error?l.message:String(l);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||h.includes("config"))&&i.verbose)re.warn("Unexpected error loading config, using defaults:",[l instanceof Error?l:Error(String(l))]);let m=c?{...i,defaultConfig:a}:{...i,defaultConfig:a,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await rr.applyEnvironmentVariables(m.name||"",a,!0,m.verbose||!1))?.config??a;return a}}function Fe(i,a,c=!1){let l=new Sr,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function h(g,m=[]){let d={...g};for(let[p,w]of Object.entries(g)){let E=[...m,p],x=[`${u}_${E.join("_").toUpperCase()}`,`${u}_${E.map((T)=>T.toUpperCase()).join("")}`,`${u}_${E.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],C,A;for(let T of x)if(C=xt.env[T],C!==void 0){A=T;break}if(C!==void 0&&A)if(typeof w==="boolean")d[p]=["true","1","yes"].includes(C.toLowerCase());else if(typeof w==="number"){let T=Number(C);if(!Number.isNaN(T))d[p]=T}else if(Array.isArray(w))try{d[p]=JSON.parse(C)}catch{d[p]=C.split(",").map((T)=>T.trim())}else d[p]=C;else if(w&&typeof w==="object"&&!Array.isArray(w))d[p]=h(w,E)}return d}return h(a)}var Ac=se(xt.cwd(),"config"),kc=se(xt.cwd(),"src/generated");function n(i=e.dialect){return i==="mysql"||i==="singlestore"||i==="vitess"}var Qe={verbose:!0,snapshotDir:".qb",migrationDir:"database/migrations",dialect:"postgres",database:{database:"test_db",username:"postgres",password:"postgres",host:"localhost",port:5432},vitess:{sharded:!0},timestamps:{createdAt:"created_at",updatedAt:"updated_at",defaultOrderColumn:"created_at"},pagination:{defaultPerPage:25,cursorColumn:"id"},aliasing:{relationColumnAliasFormat:"table_column"},relations:{foreignKeyFormat:"singularParent_id",maxDepth:10,maxEagerLoad:50,detectCycles:!0},transactionDefaults:{retries:2,isolation:"read committed",sqlStates:["40001","40P01"],backoff:{baseMs:50,factor:2,maxMs:2000,jitter:!0}},sql:{randomFunction:"RANDOM()",sharedLockSyntax:"FOR SHARE",jsonContainsMode:"operator"},features:{distinctOn:!0},debug:{captureText:!0},hooks:{},softDeletes:{enabled:!1,column:"deleted_at",defaultFilter:!0}},ai=new Set(["__proto__","constructor","prototype"]);function si(i){if(i===null||typeof i!=="object"||Array.isArray(i))return!1;let a=Object.getPrototypeOf(i);return a===Object.prototype||a===null}function xr(i,a,c=new Set){let l={...i};c.add(a);for(let u of Object.keys(a)){if(ai.has(u))continue;let h=a[u];if(si(h)&&!c.has(h)){let g=l[u];l[u]=xr(si(g)?g:{},h,c)}else l[u]=h}return c.delete(a),l}var Oo=Symbol.for("bun-query-builder.config"),e=globalThis[Oo]??=xr({},Qe),Fo=Symbol.for("bun-query-builder.config-state"),Ft=globalThis[Fo]??={explicit:new Set,fileLoaded:!1};function B(i){if(i)return i;let a=ii.env.DB_DIALECT||ii.env.DB_CONNECTION;if(a)return a;return e.dialect||"postgres"}function t(i){if(e.dialect==="postgres")return`$${i}`;return"?"}function s(i,a=1){if(i<=0)return"";if(e.dialect==="postgres"){let c=`$${a}`;for(let l=1;l<i;l++)c+=`, $${a+l}`;return c}return i===1?"?":`?${", ?".repeat(i-1)}`}async function P(){if(!Ft.fileLoaded){Ft.fileLoaded=!0;let i=await ni({name:"query-builder",alias:"qb",defaultConfig:Qe}),a={};for(let[c,l]of Object.entries(i??{}))if(!Ft.explicit.has(c))a[c]=l;ci(a)}return e}var Ke=null,oi=new Set;function ci(i){let a=xr(e,i),c=e;for(let l of Object.keys(a)){if(ai.has(l))continue;c[l]=a[l]}}function Ne(i){if(i.dialect&&Ke&&i.dialect!==Ke){let a=`${Ke}->${i.dialect}`;if(!oi.has(a))oi.add(a),console.warn(`[query-builder] Configuring dialect '${i.dialect}' overrides the previously configured dialect '${Ke}'. Config is process-wide (setConfig, db.configure and query-builder.config.ts all write it); in-flight queries from the previous configuration may break. `+"Run conflicting connections in separate processes \u2014 see stacksjs/stacks#1862 #18.")}if(i.dialect)Ke=i.dialect;for(let a of Object.keys(i))Ft.explicit.add(a);ci(i)}function zt(i){return i}var At=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"];function Mt(){let i=e.sqlite?.pragmas;return Array.isArray(i)?i:At}function v(i){for(let a of Mt())try{i.run(a)}catch{}}var{SQL:li}=globalThis.Bun;import{Database as Ro}from"bun:sqlite";import{mkdirSync as Po}from"fs";import{dirname as No}from"path";import Ve from"process";function We(i){return`"${i.replaceAll('"','""')}"`}class Tr{database;pending=[];bytes=0;timer;closed=!1;failure;constructor(i){this.database=i}get hasPending(){return this.pending.length>0}append=(i,a)=>{if(this.failure)return Promise.reject(this.failure);if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));let c=Object.keys(a),l=c.map((g)=>{let m=a[g];if(ArrayBuffer.isView(m))return new Uint8Array(m.buffer,m.byteOffset,m.byteLength).slice();return m??null}),u=JSON.stringify([i,c]),h=512+u.length*2+l.reduce((g,m)=>g+(typeof m==="string"?m.length*2:ArrayBuffer.isView(m)?m.byteLength:16),0);if(this.hasPending&&(this.pending.length>=32||this.bytes+h>262144))this.flush();return new Promise((g,m)=>{let d={table:i,columns:c,values:l,shape:u,uncached:h>262144,resolve:g,reject:m};if(this.database.inTransaction||h>262144){this.writeOne(d);return}this.pending.push(d),this.bytes+=h,this.timer??=setImmediate(()=>this.flush())})};flush(){if(this.timer!==void 0)clearImmediate(this.timer),this.timer=void 0;let i=this.pending;this.pending=[],this.bytes=0;for(let a=0;a<i.length;){if(this.failure){for(let u of i.slice(a))u.reject(this.failure);return}let c=a+1;while(c<i.length&&i[c].shape===i[a].shape)c++;let l=i.slice(a,c);if(a=c,l.length===1||!l[0].columns.length||this.database.inTransaction){for(let u of l)this.writeOne(u);continue}try{this.database.transaction(()=>{let u=l[0],h=`(${u.columns.map(()=>"?").join(",")})`,g=`INSERT INTO ${We(u.table)} (${u.columns.map(We).join(",")}) VALUES ${l.map(()=>h).join(",")}`;this.database.query(g).run(...l.flatMap((m)=>m.values))})();for(let u of l)u.resolve()}catch(u){if(this.database.inTransaction){this.invalidate(u);for(let h of[...l,...i.slice(a)])h.reject(u);return}for(let h of l)this.writeOne(h)}}}writeOne(i){let a=!1;try{this.assertUsable(),a=this.database.inTransaction;let c=i.columns.length?`INSERT INTO ${We(i.table)} (${i.columns.map(We).join(",")}) VALUES (${i.columns.map(()=>"?").join(",")})`:`INSERT INTO ${We(i.table)} DEFAULT VALUES`,l=()=>{if(!i.uncached)return this.database.query(c).run(...i.values);let u=this.database.prepare(c);try{return u.run(...i.values)}finally{u.finalize()}};if(a)l();else this.database.transaction(l)();i.resolve()}catch(c){if(!this.failure&&!a&&this.database.inTransaction)this.invalidate(c);i.reject(c)}}assertUsable(){if(this.failure)throw this.failure}invalidate(i){this.failure=Error("SQLite connection is unusable after deferred insert rollback failed",{cause:i});try{this.database.close()}catch{}}close(){this.closed=!0,this.flush()}}function Ar(i){return i}function Do(i){return i!==null&&typeof i==="object"?i:null}function fi(i,a){if(a.length===0||!/\$\d/.test(i))return{sql:i,params:a};let c=[],l="",u=0;for(let h=0;h<i.length;h++){let g=i[h];if(g==="'"||g==='"'||g==="`"){let m=Lo(i,h,g);l+=i.slice(h,m),h=m-1;continue}if(g==="-"&&i[h+1]==="-"){let m=i.indexOf(`
62
+ `,h),d=m===-1?i.length:m;l+=i.slice(h,d),h=d-1;continue}if(g==="/"&&i[h+1]==="*"){let m=i.indexOf("*/",h+2),d=m===-1?i.length:m+2;l+=i.slice(h,d),h=d-1;continue}if(g==="$"){let m=/^\d+/.exec(i.slice(h+1))?.[0];if(m){let d=Number(m);if(u=Math.max(u,d),d>=1&&d<=a.length){c.push(a[d-1]),l+="?",h+=m.length;continue}}}l+=g}if(u>a.length)throw Error(`SQL references $${u} but only ${a.length} value${a.length===1?" was":"s were"} provided`);if(c.length===0)return{sql:i,params:a};return{sql:l,params:c}}function Lo(i,a,c){for(let l=a+1;l<i.length;l++){if(i[l]!==c)continue;if(i[l+1]===c){l++;continue}return l+1}return i.length}var kr=/^\s*(?:SELECT|WITH|INSERT|UPDATE|DELETE|REPLACE)\b/i;class di{db;deferredInserts;closed=!1;constructor(i){if(i!==":memory:"&&!i.startsWith(":")){let a=No(i);if(a&&a!==".")Po(a,{recursive:!0})}this.db=new Ro(i),v(this.db)}deferInsert=(i,a)=>{if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));if(!this.deferredInserts){let c=this.deferredInserts=new Tr(this.db),l=this.query.bind(this),u=this.run.bind(this),h=(g)=>{if(c.hasPending&&!kr.test(g))c.flush();c.assertUsable()};this.query=(g,m)=>(h(g),l(g,m)),this.run=(g,m)=>(h(g),u(g,m))}return this.deferredInserts.append(i,a)};flushDeferredInserts(){this.deferredInserts?.flush()}query(i,a=[]){let c=fi(i,a),l=c.params.length>0||kr.test(c.sql),u=l?this.db.query(c.sql):this.db.prepare(c.sql);return(l&&c.params.length===0&&u.paramsCount>0?this.db.prepare(c.sql):u).all(...c.params)}run(i,a=[]){let c=fi(i,a),l=c.params.length>0||kr.test(c.sql),u=l?this.db.query(c.sql):this.db.prepare(c.sql);return(l&&c.params.length===0&&u.paramsCount>0?this.db.prepare(c.sql):u).run(...c.params)}close(){this.closed=!0,this.deferredInserts?.close(),this.db.close()}get database(){return this.db}}function ui(i){return{__raw:!0,value:i,toString:()=>i}}function gi(i){let a=i.trimStart();for(;;)if(a.startsWith("--")){let c=a.indexOf(`
63
+ `);a=c===-1?"":a.slice(c+1).trimStart()}else if(a.startsWith("/*")){let c=a.indexOf("*/");a=c===-1?"":a.slice(c+2).trimStart()}else return a}function Mo(i){let a=[],c="",l=!1,u=!1,h=!1,g=!1;for(let d=0;d<i.length;d++){let p=i[d],w=i[d+1];if(!l&&!u&&!g&&p==="-"&&w==="-"){h=!0,c+=p;continue}if(h&&(p===`
64
+ `||p==="\r")){h=!1,c+=p;continue}if(!l&&!u&&!h&&p==="/"&&w==="*"){g=!0,c+=p;continue}if(g&&p==="*"&&w==="/"){g=!1,c+=p+w,d++;continue}if(h||g){c+=p;continue}if(p==="'"&&!u){if(l&&w==="'"){c+=p+w,d++;continue}l=!l,c+=p;continue}if(p==='"'&&!l){u=!u,c+=p;continue}if(p===";"&&!l&&!u){let E=gi(c.trim());if(E)a.push(E);c="";continue}c+=p}let m=gi(c.trim());if(m)a.push(m);return a}function hi(i){let a=new di(i);function c(g,m){let d=g.trim().toUpperCase();if(d.startsWith("SELECT")||d.startsWith("PRAGMA")||/\bRETURNING\b/.test(d))return a.query(g,Ar(m));return a.run(g,Ar(m))}function l(g,...m){let d=g[0],p=[];for(let E=0;E<m.length;E++){let x=m[E],C=Do(x);if(C&&typeof C.sql==="string"&&Array.isArray(C.values))d+=C.sql+(g[E+1]||""),p.push(...C.values);else if(C&&(C.__raw||C.raw)){let A=C.raw,T=C.__raw?C.value:typeof A==="string"?A:A();d+=T+(g[E+1]||"")}else if(Array.isArray(x)){let A=x.map(()=>"?").join(", ");d+=A+(g[E+1]||""),p.push(...x)}else d+=`?${g[E+1]||""}`,p.push(x)}let w=()=>c(d,p);return{sql:d,values:p,executeSync:w,execute:()=>{try{return Promise.resolve(w())}catch(E){return Promise.reject(E)}},raw:()=>d,toString:()=>d,cancel:()=>{}}}function u(g,...m){if(Array.isArray(g)&&"raw"in g)return l(g,...m);if(typeof g==="string")return ui(g);return l([""])}u.raw=(g)=>ui(g),u.unsafe=(g,m=[])=>{let d=()=>c(g,m),p=()=>{try{return Promise.resolve(d())}catch(w){return Promise.reject(w)}};return{sql:g,values:m,execute:p,executeSync:d,then:(w,E)=>p().then(w,E),raw:()=>g,toString:()=>g,cancel:()=>{}}},u.deferInsert=a.deferInsert,u.flushDeferredInserts=()=>a.flushDeferredInserts(),u.close=()=>(a.close(),Promise.resolve()),u.query=(g,m)=>{try{let d=a.query(g,Ar(m||[]));return Promise.resolve(d)}catch(d){return Promise.reject(d)}},u.file=async(g,m)=>{try{let{readFileSync:d}=await import("fs"),p=d(g,"utf-8"),w=Mo(p);for(let E of w){let x=E.trim();if(!x||x.startsWith("--"))continue;let C=x.toUpperCase();if(C.startsWith("SELECT")||C.startsWith("PRAGMA"))a.query(E);else a.run(E)}return Promise.resolve([])}catch(d){return Promise.reject(d)}};let h=0;return u.begin=async(g,m)=>{let d=typeof g==="function"?g:m;if(typeof d!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let p=h>0,w=`qb_sp_${h}`;if(p)a.run(`SAVEPOINT ${w}`);else a.run("BEGIN");h++;try{let E=await d(u);if(h--,p)a.run(`RELEASE SAVEPOINT ${w}`);else a.run("COMMIT");return E}catch(E){h--;try{if(p)a.run(`ROLLBACK TO SAVEPOINT ${w}`),a.run(`RELEASE SAVEPOINT ${w}`);else a.run("ROLLBACK")}catch{}throw E}},u.savepoint=u.begin,u.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on SQLite. Use begin()/transaction().")},u._wrapper=a,u}function jo(i){let a=i.replace(/^(?:sqlite|sqlite3|file):/i,"");if(a===i)return i;return(a.startsWith("///")?a.slice(2):a.startsWith("//")?a.slice(2):a)||":memory:"}function Be(i=e.database){let a=Ve.env.DB_DATABASE||i?.database||"";return String(a).replace(/^['"]|['"]$/g,"")}function Bo(i,a){if((i==="postgres"||i==="mysql"||i==="singlestore"||i==="vitess")&&Ve.env.DB_CONNECTION===i){let p=Ve.env,w=(p.DB_DATABASE||a.database||"").replace(/^['"]|['"]$/g,""),E=p.DB_USERNAME||a.username,x=p.DB_PASSWORD??a.password??"",C=p.DB_HOST||a.host||"localhost",A=p.DB_PORT||a.port,T=i==="postgres"?"postgres":"mysql",k=p.DB_SSL==="true"||p.DB_SSL==="1"||a.ssl?"?ssl=true":"";return`${T}://${E}:${x}@${C}${A?`:${A}`:""}/${w}${k}`}if(a.url)return i==="sqlite"?jo(a.url):a.url;let{database:c,username:l,password:u,host:h="localhost",port:g,ssl:m}=a,d=m||Ve.env.DB_SSL==="true"||Ve.env.DB_SSL==="1"?"?ssl=true":"";switch(i){case"postgres":return`postgres://${l}:${u}@${h}${g?`:${g}`:""}/${c}${d}`;case"mysql":case"singlestore":case"vitess":return`mysql://${l}:${u}@${h}${g?`:${g}`:""}/${c}${d}`;case"sqlite":if(c===":memory:")return":memory:";return c||":memory:";default:throw Error(`Unsupported dialect: ${i}`)}}function mi(i){if(!i)return{};let a={},c=(l)=>Math.max(0,Math.round(l/1000));if(typeof i.max==="number"&&Number.isFinite(i.max))a.max=i.max;if(typeof i.idleTimeoutMs==="number"&&Number.isFinite(i.idleTimeoutMs))a.idleTimeout=c(i.idleTimeoutMs);if(typeof i.acquireTimeoutMs==="number"&&Number.isFinite(i.acquireTimeoutMs))a.connectionTimeout=c(i.acquireTimeoutMs);if(typeof i.maxLifetimeMs==="number"&&Number.isFinite(i.maxLifetimeMs))a.maxLifetime=c(i.maxLifetimeMs);return a}function Io(){let i=e.dialect,a=Bo(i,e.database);try{if(i==="sqlite")return hi(a);let c=mi(e.database.pool);return Object.keys(c).length>0?new li(a,c):new li(a)}catch(c){if(console.error(`[query-builder] Failed to create database connection for dialect '${i}': ${c.message}`),i==="sqlite")return hi(":memory:");throw c}}var ke=null,Or=null;function _o(){let i=e.database;return JSON.stringify({dialect:e.dialect,database:i.database,username:i.username,password:i.password,host:i.host,port:i.port,url:i.url,pool:mi(i.pool)})}function y(i=!1){let a=_o();if(i||ke!==null&&Or!==a||!ke)pi(),ke=Io(),Or=a;return ke}function pi(){let i=ke;return i?.flushDeferredInserts?.(),ke=null,Or=null,i}async function Ko(i){if(!i||typeof i.close!=="function")return;await i.close()}function Yt(){Ko(pi()).catch((a)=>{console.error(`[query-builder] Failed to close database connection: ${a.message}`)})}async function Ge(i){try{return await i(y())}catch(a){if(a?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||a?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let c=y(!0);return await i(c)}throw a}}function Wo(){return new Proxy(function(){},{get(i,a){let c=y(),l=c[a];if(typeof l==="function")return l.bind(c);return l},apply(i,a,c){return y()(...c)}})}var r=Wo();function Pe(i){let a=String(i).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(a.endsWith("y")&&!/[aeou]y$/.test(a))return`${a.slice(0,-1)}ies`;if(a.endsWith("s")||a.endsWith("x")||a.endsWith("ch")||a.endsWith("sh"))return`${a}es`;return`${a}s`}function b(i){return typeof i?.table==="string"&&i.table.length>0?i.table:Pe(String(i?.name??""))}function Xt(i){return i.endsWith("s")?i.slice(0,-1):i}function Zt(i){if(i.endsWith("ies")&&i.length>3){let a=i.slice(0,-3),c=a[a.length-1];if(c&&!"aeiou".includes(c))return`${a}y`}if(i.endsWith("es")&&i.length>2){let a=i.slice(0,-2);if(a.endsWith("s")||a.endsWith("x")||a.endsWith("ch")||a.endsWith("sh"))return a}if(i.endsWith("s")&&!i.endsWith("ss")&&!i.endsWith("us")&&!i.endsWith("is"))return i.slice(0,-1);return i}function f(i){if(i==="none")return(a)=>a;if(i==="inflect")return Zt;return Xt}var Nt="1 = 0";function S(i){if(i.length===0)return"";let a=[];for(let c of i)if(c.conn==="OR"&&a.length>0)a[a.length-1].push(c);else a.push([c]);return a.map((c,l)=>{let u=c.map((g)=>g.sql).join(" OR "),h=c.length>1&&a.length>1?`(${u})`:u;return l===0?h:`${c[0].conn} ${h}`}).join(" ")}function o(i,a,c,l){if(a.length===0)return c?"1 = 1":"1 = 0";return`${i} ${c?"NOT IN":"IN"} (${l})`}function Je(i,a){if(a!=="postgres")return i;return Oe(i,(c)=>`$${c}`).text}function Bt(i){return Oe(i,()=>{return}).count}function Oe(i,a){let c="",l=0,u=0,h=0;while(h<i.length){let g=i[h],m=-1;if(g==="'"||g==='"'||g==="`")m=Vo(i,h,g);else if(g==="-"&&i[h+1]==="-"){let d=i.indexOf(`
65
+ `,h+2);m=d===-1?i.length:d}else if(g==="/"&&i[h+1]==="*"){let d=1;m=h+2;while(m<i.length&&d>0)if(i[m]==="/"&&i[m+1]==="*")d++,m+=2;else if(i[m]==="*"&&i[m+1]==="/")d--,m+=2;else m++}else if(g==="$"){let d=i.slice(h).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(d){let p=i.indexOf(d,h+d.length);m=p===-1?i.length:p+d.length}}if(m!==-1){h=m;continue}if(g==="?"){l++;let d=a(l);if(d!==void 0)c+=i.slice(u,h)+d,u=h+1}h++}return{text:u===0?i:c+i.slice(u),count:l}}function Vo(i,a,c){let l=a+1;while(l<i.length){if(i[l]===c){if(i[l+1]===c){l+=2;continue}return l+1}l++}return i.length}function _e(i,a,c=Number.POSITIVE_INFINITY){let l=[],u=0,h=(g)=>g>=48&&g<=57||g>=65&&g<=90||g>=97&&g<=122||g===95;for(let g=0;g<i.length;g++){let m=i.charCodeAt(g);if(m===45&&i.charCodeAt(g+1)===45){let p=i.indexOf(`
66
+ `,g+2);if(p===-1)return l;g=p;continue}if(m===47&&i.charCodeAt(g+1)===42){let p=1,w=g+2;while(w<i.length&&p>0)if(i[w]==="/"&&i[w+1]==="*")p++,w+=2;else if(i[w]==="*"&&i[w+1]==="/")p--,w+=2;else w++;g=w-1;continue}if(m===39||m===34||m===96){let p=g+1;while(p<i.length){if(i.charCodeAt(p)===m){if(i.charCodeAt(p+1)===m){p+=2;continue}break}p++}g=p;continue}if(m===36){let p=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(i.slice(g));if(p){let w=i.indexOf(p[0],g+p[0].length);g=w===-1?i.length:w+p[0].length-1;continue}}if(m===40){u++;continue}if(m===41){u=Math.max(0,u-1);continue}if(u!==0)continue;if(g===0)continue;let d=m&-33;if(d<65||d>90)continue;if(h(i.charCodeAt(g-1)))continue;for(let{key:p,pattern:w}of a){w.lastIndex=g;let E=w.exec(i);if(!E)continue;if(l.push({key:p,start:g,length:E[0].length}),l.length>=c)return l;g+=E[0].length-1;break}}return l}
67
+ export{n,Qe,e,B,t,s,P,Ne,zt,At,Mt,v,Be,y,Yt,Ge,r,Pe,b,Xt,Zt,f,Nt,S,o,Je,Bt,Oe,_e};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{et,T,C,R}from"./chunk-vw9ss7z8.js";import"./chunk-c7m701dd.js";import"./chunk-3xpe6b57.js";import"./chunk-cxpaxq2p.js";import"./chunk-hjgcemhy.js";import"./chunk-4cs1xx1d.js";export{C as executeMigration,T as generateMigration,R as resetDatabase,et as saveMigrationSnapshot};