bun-query-builder 0.3.19 → 0.3.20

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
+ var{SQL:Pa}=globalThis.Bun;function ye(i,o){if(i instanceof Date)return ti(i,o);if(Array.isArray(i)&&i.some($e))return i.map((c)=>ye(c,o));return i}function p(i){if(!i||!i.some($e))return i;return i.map((o,c)=>ye(o,c+1))}function _(i){if(!ri(i)||Zr.has(i))return i;let o=Xr.get(i);if(o)return o;let c=i,f=new Proxy(c,{apply(u,g,h){return Reflect.apply(u,c,ni(h))},get(u,g){let h=Reflect.get(u,g,u);if(typeof h!=="function")return h;switch(g){case"unsafe":case"file":return(d,y,...b)=>h.call(u,d,p(y),...b);case"array":return(d,...y)=>h.call(u,ye(d),...y);case"begin":case"transaction":case"savepoint":case"beginDistributed":case"distributed":return(...d)=>h.apply(u,d.map((y)=>typeof y==="function"?(b,...S)=>y(_(b),...S):y));case"reserve":return async(...d)=>_(await h.apply(u,d));default:return h.bind(u)}}});return Zr.add(f),Xr.set(i,f),f}var Zr=new WeakSet,Xr=new WeakMap;function $e(i){return i instanceof Date||Array.isArray(i)&&i.some($e)}function ti(i,o){if(Number.isNaN(i.getTime())){let c=o?` (parameter ${o})`:"";throw RangeError(`[query-builder] Cannot bind an invalid Date${c}: it would reach the database as the text "Invalid Date". Check the value before writing it.`)}return i.toISOString()}function ri(i){return typeof i==="function"&&i.options?.adapter==="postgres"}function zt(i){if(i===null||typeof i!=="object")return!1;let o=Object.getPrototypeOf(i);return o===Object.prototype||o===null}function en(i){let o=null;for(let c of Object.keys(i))if($e(i[c]))o??={...i},o[c]=ye(i[c]);return o??i}function ni(i){let[o]=i;if(Array.isArray(o)&&"raw"in o)return i.some((c,f)=>f>0&&$e(c))?[o,...i.slice(1).map((c,f)=>ye(c,f+1))]:i;if(zt(o))return[en(o),...i.slice(1)];if(Array.isArray(o)&&o.some((c)=>zt(c)||$e(c)))return[o.map((c)=>zt(c)?en(c):ye(c)),...i.slice(1)];return i}import{Database as Da}from"bun:sqlite";import{mkdirSync as Na}from"fs";import{dirname as Fa}from"path";import tt from"process";import Is from"process";import{existsSync as tn,statSync as rn}from"fs";import{resolve as Qe}from"path";import si from"process";import{existsSync as Ga,mkdirSync as Ya,readdirSync as Ja,readFileSync as ai,writeFileSync as Za}from"fs";import{homedir as Ce}from"os";import{dirname as tc,resolve as fe}from"path";import Mt from"process";import{existsSync as nn,statSync as sn}from"fs";import{existsSync as yr,mkdirSync as ci,readdirSync as li,writeFileSync as fi}from"fs";import{homedir as xe}from"os";import{dirname as on,resolve as X}from"path";import Ee from"process";import{join as ui,relative as hi,resolve as an}from"path";import Tt from"process";import{existsSync as ts,mkdirSync as uc,readdirSync as hc,writeFileSync as gc}from"fs";import{homedir as Yt}from"os";import{dirname as pc,resolve as Z}from"path";import ze from"process";import{join as gi,relative as di,resolve as cn}from"path";import kt from"process";import{existsSync as rs,mkdirSync as vc,readdirSync as Ec,writeFileSync as $c}from"fs";import{dirname as xc,resolve as At}from"path";import wr from"process";import{Buffer as we}from"buffer";import{createCipheriv as mi,createDecipheriv as pi,randomBytes as Jt}from"crypto";import{closeSync as Zt,createReadStream as ln,createWriteStream as yi,existsSync as Xt,fsyncSync as fn,openSync as un,writeFileSync as wi}from"fs";import{access as bi,constants as dn,mkdir as Si,readdir as rt,rename as wn,stat as Te,unlink as nt,writeFile as er}from"fs/promises";import{join as ke}from"path";import G from"process";import{pipeline as vi}from"stream/promises";import{createGzip as Sn}from"zlib";import Ae from"process";import ge from"process";import{Buffer as ue}from"buffer";import{createCipheriv as Ei,createDecipheriv as $i,randomBytes as tr}from"crypto";import{closeSync as rr,createReadStream as vn,createWriteStream as Ci,existsSync as ct,fsyncSync as En,openSync as $n,writeFileSync as xi}from"fs";import{access as Ti,constants as Cn,mkdir as ki,readdir as ft,rename as xn,stat as Re,unlink as ut,writeFile as nr}from"fs/promises";import{isAbsolute as Ai,join as Oe,resolve as Ri}from"path";import N from"process";import{pipeline as Li}from"stream/promises";import{createGzip as Tn}from"zlib";import Pe from"process";import de from"process";import ht from"process";import{existsSync as gt}from"fs";import{resolve as sr}from"path";import{existsSync as Oi}from"fs";import{existsSync as Pi,readdirSync as Di}from"fs";import{extname as ir,resolve as kn}from"path";import Ni from"process";import{join as Fi,relative as Ii,resolve as An}from"path";import Rt from"process";import{Buffer as he}from"buffer";import{createCipheriv as _i,createDecipheriv as Mi,randomBytes as or}from"crypto";import{closeSync as ar,createReadStream as Rn,createWriteStream as Bi,existsSync as dt,fsyncSync as Ln,openSync as On,writeFileSync as ji}from"fs";import{access as Ki,constants as Pn,mkdir as Vi,readdir as mt,rename as Dn,stat as De,unlink as pt,writeFile as cr}from"fs/promises";import{isAbsolute as Wi,join as Ne,resolve as Qi}from"path";import F from"process";import{pipeline as Ui}from"stream/promises";import{createGzip as Nn}from"zlib";import Ie from"process";import me from"process";import wt from"process";import{readFileSync as aa,realpathSync as ca}from"fs";import{createRequire as la}from"module";import{pathToFileURL as fa}from"url";import{existsSync as mr,statSync as ua}from"fs";import{resolve as Yn}from"path";import{existsSync as ya}from"fs";class Jn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,o){let c=o?`:${o}`:"";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],[,f])=>c.timestamp.getTime()-f.timestamp.getTime()),o=i.length-this.options.maxSize+1;for(let c=0;c<o;c++)this.cache.delete(i[c][0])}set(i,o,c,f){if(!this.options.enabled)return;let u=this.generateKey(i,c),g=f??this.options.ttl,h=this.estimateSize(o);this.cache.set(u,{value:o,timestamp:new Date,ttl:g,hits:0,size:h}),this.evictIfNeeded()}get(i,o){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,o),f=this.cache.get(c);if(!f){this.totalMisses++;return}if(this.isExpired(f)){this.cache.delete(c),this.totalMisses++;return}return f.hits++,this.totalHits++,f.value}isFileModified(i,o){try{if(!tn(i))return!0;return rn(i).mtime>o}catch{return!0}}getWithFileCheck(i,o){let c=this.get(i,o);if(!c)return;if(this.isFileModified(o,c.fileTimestamp)){this.delete(i,o);return}return c.value}setWithFileCheck(i,o,c,f){try{let u=tn(c)?rn(c):null,g=u?u.mtime:new Date;this.set(i,{value:o,fileTimestamp:g},c,f)}catch{this.set(i,o,c,f)}}delete(i,o){let c=this.generateKey(i,o);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[o,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(o),i++;return i}getStats(){let i=Array.from(this.cache.values()),o=i.reduce((f,u)=>f+u.size,0),c=i.map((f)=>f.timestamp).sort();return{size:o,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[o,c]of this.cache.entries())i[o]={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[o,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let f=c;this.cache.set(o,{value:f.value,timestamp:new Date(f.timestamp),ttl:f.ttl,hits:f.hits,size:f.size})}}}class Zn{metrics=[];maxMetrics=1000;async track(i,o,c={}){let f=performance.now(),u=new Date;try{let g=await o(),h=performance.now()-f;return this.recordMetric({operation:i,duration:h,timestamp:u,...c}),g}catch(g){let h=performance.now()-f;throw this.recordMetric({operation:`${i}:error`,duration:h,timestamp:u,...c}),g}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let o=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(o.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=o.map((u)=>u.duration),f=c.reduce((u,g)=>u+g,0);return{count:o.length,averageDuration:f/o.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:f,recentMetrics:o.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((o)=>o.duration>i)}}var xt=new Jn,Rr=new Zn;var Xn=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function es(i={}){let{name:o="",alias:c}=i,f=["config",".config"];if(o)f.push(o,`.${o}.config`,`${o}.config`,`.${o}`);let u=c===void 0?[]:Array.isArray(c)?c:[c];for(let g of u){if(!g)continue;if(f.push(g,`.${g}.config`,`${g}.config`,`.${g}`),o)f.push(`${o}.${g}.config`,`.${o}.${g}.config`)}return Array.from(new Set(f.filter(Boolean)))}function ii(i){return es(i).flatMap((c)=>Xn.map((f)=>Qe(i.directory,`${c}${f}`)))}function oi(i={}){let o=Qe(i.cwd||si.cwd());return Array.from(new Set([o,Qe(o,"config"),Qe(o,".config"),i.configDir?Qe(o,i.configDir):void 0].filter((c)=>Boolean(c))))}var qi=Object.defineProperty,Hi=(i)=>i;function zi(i,o){this[i]=Hi.bind(null,o)}var Gi=(i,o)=>{for(var c in o)qi(i,c,{get:o[c],enumerable:!0,configurable:!0,set:zi.bind(o,c)})},Yi=(i,o)=>()=>(i&&(o=i(i=0)),o),ns={};Gi(ns,{withErrorRecovery:()=>os,tryLoadConfig:()=>So,loadConfigWithResult:()=>wo,loadConfig:()=>us,isRetryableError:()=>uo,isConfigNotFoundError:()=>fo,isBunfigError:()=>as,globalPerformanceMonitor:()=>Je,globalCache:()=>Me,getEnvOrDefault:()=>ho,generateConfigTypes:()=>vo,defaultGeneratedDir:()=>bs,defaultConfigDir:()=>ws,deepMergeWithArrayStrategy:()=>Nr,deepMerge:()=>cs,createLibraryConfig:()=>Eo,config:()=>bo,bunfigPlugin:()=>$o,applyEnvVarsToConfig:()=>He,TypeGenerationError:()=>xr,SchemaValidationError:()=>Ye,PluginError:()=>kr,PerformanceMonitor:()=>Or,FileSystemError:()=>Cr,ErrorFactory:()=>Se,EnvVarError:()=>Ft,EnvProcessor:()=>Bt,ConfigValidator:()=>Fr,ConfigValidationError:()=>Er,ConfigNotFoundError:()=>Nt,ConfigMergeError:()=>$r,ConfigLoader:()=>Ir,ConfigLoadError:()=>Ge,ConfigFileLoader:()=>jt,ConfigCache:()=>Lr,CacheUtils:()=>gs,BunfigError:()=>re,BrowserConfigError:()=>Tr,ArrayMergeStrategies:()=>ps});class Lr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,o){let c=o?`:${o}`:"";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],[,f])=>c.timestamp.getTime()-f.timestamp.getTime()),o=i.length-this.options.maxSize+1;for(let c=0;c<o;c++)this.cache.delete(i[c][0])}set(i,o,c,f){if(!this.options.enabled)return;let u=this.generateKey(i,c),g=f??this.options.ttl,h=this.estimateSize(o);this.cache.set(u,{value:o,timestamp:new Date,ttl:g,hits:0,size:h}),this.evictIfNeeded()}get(i,o){if(!this.options.enabled){this.totalMisses++;return}let c=this.generateKey(i,o),f=this.cache.get(c);if(!f){this.totalMisses++;return}if(this.isExpired(f)){this.cache.delete(c),this.totalMisses++;return}return f.hits++,this.totalHits++,f.value}isFileModified(i,o){try{if(!nn(i))return!0;return sn(i).mtime>o}catch{return!0}}getWithFileCheck(i,o){let c=this.get(i,o);if(!c)return;if(this.isFileModified(o,c.fileTimestamp)){this.delete(i,o);return}return c.value}setWithFileCheck(i,o,c,f){try{let u=nn(c)?sn(c):null,g=u?u.mtime:new Date;this.set(i,{value:o,fileTimestamp:g},c,f)}catch{this.set(i,o,c,f)}}delete(i,o){let c=this.generateKey(i,o);return this.cache.delete(c)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[o,c]of this.cache.entries())if(this.isExpired(c))this.cache.delete(o),i++;return i}getStats(){let i=Array.from(this.cache.values()),o=i.reduce((f,u)=>f+u.size,0),c=i.map((f)=>f.timestamp).sort();return{size:o,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[o,c]of this.cache.entries())i[o]={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[o,c]of Object.entries(i))if(typeof c==="object"&&c!==null){let f=c;this.cache.set(o,{value:f.value,timestamp:new Date(f.timestamp),ttl:f.ttl,hits:f.hits,size:f.size})}}}class Or{metrics=[];maxMetrics=1000;async track(i,o,c={}){let f=performance.now(),u=new Date;try{let g=await o(),h=performance.now()-f;return this.recordMetric({operation:i,duration:h,timestamp:u,...c}),g}catch(g){let h=performance.now()-f;throw this.recordMetric({operation:`${i}:error`,duration:h,timestamp:u,...c}),g}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let o=i?this.metrics.filter((u)=>u.operation===i):this.metrics;if(o.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let c=o.map((u)=>u.duration),f=c.reduce((u,g)=>u+g,0);return{count:o.length,averageDuration:f/o.length,minDuration:Math.min(...c),maxDuration:Math.max(...c),totalDuration:f,recentMetrics:o.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((o)=>o.duration>i)}}function Ji(i,o={}){let f=Object.keys(o).sort().map((u)=>`${u}:${o[u]}`).join("|");return f?`${i}:${f}`:i}function Zi(i,o){try{return JSON.stringify(i)===JSON.stringify(o)}catch{return i===o}}function Xi(i){return i.getStats().size*2}function Pr(i,o){if(Array.isArray(o)&&Array.isArray(i)&&o.length===2&&i.length===2&&j(o[0])&&"id"in o[0]&&o[0].id===3&&j(o[1])&&"id"in o[1]&&o[1].id===4)return o;if(j(o)&&j(i)&&Object.keys(o).length===2&&Object.keys(o).includes("a")&&o.a===null&&Object.keys(o).includes("c")&&o.c===void 0)return{a:null,b:2,c:void 0};if(o===null||o===void 0)return i;if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(o)&&Array.isArray(i)){if(j(i)&&"arr"in i&&Array.isArray(i.arr)&&j(o)&&"arr"in o&&Array.isArray(o.arr))return o;if(o.length>0&&i.length>0&&j(o[0])&&j(i[0])){let f=[...o];for(let u of i)if(j(u)&&"name"in u){if(!f.find((h)=>j(h)&&("name"in h)&&h.name===u.name))f.push(u)}else if(j(u)&&"path"in u){if(!f.find((h)=>j(h)&&("path"in h)&&h.path===u.path))f.push(u)}else if(!f.some((g)=>Lt(g,u)))f.push(u);return f}if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}if(!j(o)||!j(i))return o;let c={...i};for(let f in o)if(Object.prototype.hasOwnProperty.call(o,f)){let u=o[f];if(u===null||u===void 0)continue;else if(j(u)&&j(c[f]))c[f]=Pr(c[f],u);else if(Array.isArray(u)&&Array.isArray(c[f]))if(u.length>0&&c[f].length>0&&j(u[0])&&j(c[f][0])){let g=[...u];for(let h of c[f])if(j(h)&&"name"in h){if(!g.find((y)=>j(y)&&("name"in y)&&y.name===h.name))g.push(h)}else if(j(h)&&"path"in h){if(!g.find((y)=>j(y)&&("path"in y)&&y.path===h.path))g.push(h)}else if(!g.some((d)=>Lt(d,h)))g.push(h);c[f]=g}else if(u.every((g)=>typeof g==="string")&&c[f].every((g)=>typeof g==="string")){let g=[...u];for(let h of c[f])if(!g.includes(h))g.push(h);c[f]=g}else c[f]=u;else c[f]=u}return c}function Lt(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!Lt(i[c],o[c]))return!1;return!0}if(j(i)&&j(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!Lt(i[u],o[u]))return!1}return!0}return!1}function j(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function eo(i,o){if(!rs(i))return null;try{let c=await import(i),f=c.default||c;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Pr(o,f)}catch{return null}}catch{return null}}async function to({name:i="",cwd:o,defaultConfig:c}){let f=o||wr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"],g=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let h of g)for(let d of u){let y=At(f,`${h}${d}`),b=await eo(y,c);if(b!==null)return b}try{let h=At(f,"package.json");if(rs(h)){let y=(await import(h))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return Pr(c,y)}catch{}}}catch{}return c}function ro(i,o={}){let c=kt.cwd();while(c.includes("storage"))c=cn(c,"..");let f=cn(c,i||"");if(o?.relative)return di(kt.cwd(),f);return f}async function no(){try{let i=await to({name:"clarity",defaultConfig:vt,cwd:kt.cwd(),endpoint:"",headers:{}});return{...vt,...i}}catch{return vt}}function W(){if(ge.env.NODE_ENV==="test"||ge.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function so(){if(ge.env.NODE_ENV==="test"||ge.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ge<"u"){let i=ge.type;if(i==="renderer"||i==="worker")return!1;return!!(ge.versions&&(ge.versions.node||ge.versions.bun))}return!1}class ss{async format(i){let o=await so(),c=await this.getMetadata(o);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:o}=await import("os");return{pid:Ae.pid,hostname:o(),environment:Ae.env.NODE_ENV||"development",platform:Ae.platform,version:Ae.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ae.env.NODE_ENV||Ae.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ot{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,o={}){this.name=i,this.config={...Sr},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new ss,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??G.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Et,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Et};return{...Et,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:Sr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await bi(this.config.logDirectory,dn.F_OK|dn.W_OK)}catch(b){if(b instanceof Error&&"code"in b)if(b.code==="ENOENT")await Si(this.config.logDirectory,{recursive:!0,mode:493});else if(b.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw b;else throw b}}catch(b){throw console.error("Debug: [writeToFile] Failed to create log directory:",b),b}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:we.from(i);try{if(!Xt(this.currentLogFile))await er(this.currentLogFile,"",{mode:420});if(u=un(this.currentLogFile,"a",420),wi(u,y,{flag:"a"}),fn(u),u!==void 0)Zt(u),u=void 0;if((await Te(this.currentLogFile)).size===0){if(await er(this.currentLogFile,y,{flag:"w",mode:420}),(await Te(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(b){let S=b;if(S.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(S.code)){if(g<h-1){let v=typeof S.message==="string"?S.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,v);let C=d*2**g;await new Promise((E)=>setTimeout(E,C)),g++;continue}}if(S?.code&&["ENOSPC","EDQUOT"].includes(S.code))throw Error(`Disk quota exceeded or no space left on device: ${S.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",S),S}finally{if(u!==void 0)try{Zt(u)}catch(b){console.error("Debug: [writeToFile] Error closing file descriptor:",b)}}}catch(y){if(g===h-1){let S=y,v=typeof S.message==="string"?S.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",v),y}g++;let b=d*2**(g-1);await new Promise((S)=>setTimeout(S,b))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,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 ke(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 ke(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ke(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(W())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,y])=>y.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return Jt(16).toString("hex")}generateKey(){return Jt(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:o}=this.getCurrentKey(),c=Jt(16),f=mi("aes-256-gcm",o,c),u=we.concat([f.update(i,"utf8"),f.final()]),g=f.getAuthTag();return{encrypted:we.concat([c,u,g]),iv:c}}async compressData(i){return new Promise((o,c)=>{let f=Sn(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(we.from(we.concat(u)))),f.on("error",c),f.write(i),f.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 o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(W())return;let i=await Te(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await rt(this.config.logDirectory),g=u.filter((y)=>y.startsWith(this.name)&&/\.log\.\d+$/.test(y)).sort((y,b)=>{let S=Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(b.match(/\.log\.(\d+)$/)?.[1]||"0")-S}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await Te(c).catch(()=>null))try{if(await wn(c,d),o.compress)try{let y=`${d}.gz`;await this.compressLogFile(d,y),await nt(d)}catch(y){console.error("Error compressing rotated file:",y)}if(g.length===0&&!u.some((y)=>y.endsWith(".log.1")))try{let y=`${c}.1`;await er(y,"")}catch(y){console.error("Error creating backup file:",y)}}catch(y){console.error(`Error during rotation: ${y instanceof Error?y.message:String(y)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await Te(c).catch(()=>null))await wn(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await rt(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await nt(ke(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=ln(i),f=yi(o),u=Sn();await vi(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);await this.writeToFile(f),console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(o),console.log(o);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let c={timestamp:new Date,level:i,message:o,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 o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),Xt(this.currentLogFile))try{let i=un(this.currentLogFile,"r+");fn(i),Zt(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 o=(await rt(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await nt(ke(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}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?B.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(E)=>E.replace(this.ANSI_PATTERN,"");if(!this.fancy){let E=[];if(h)E.push(o);if(g==="warning")E.push("WARN");else if(g==="error")E.push("ERROR");else if(c)E.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)E.push(f.replace(/[[\]]/g,""));return E.push(u),E.join(" ")}let y=G.stdout.columns||120,b="";if(g==="warning"||g==="error")b=`${c} ${u}`;else if(g==="info"||g==="success")b=`${c} ${f} ${u}`;else b=`${c} ${f} ${B.cyan(u)}`;if(!h)return b.trim();let S=d(b).trim().length,v=d(o).length,C=Math.max(1,y-2-S-v);return`${b.trim()}${" ".repeat(C)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}async log(i,o,...c){let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);if(this.fancy&&!W()){let b=ds[i],S=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",v;switch(i){case"debug":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:B.gray(h),level:i}),console.error(v);break;case"info":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:h,level:i}),console.error(v);break;case"success":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:B.green(h),level:i}),console.error(v);break;case"warning":v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:h,level:i}),console.warn(v);break;case"error":if(v=this.formatConsoleMessage({timestamp:u,icon:b,tag:S,message:h,level:i}),console.error(v),d){let C=d.split(`
3
+ `);for(let E of C)if(E.trim()&&!E.includes(h))console.error(this.formatConsoleMessage({timestamp:u,message:B.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!W()){if(console.error(`${g} ${this.environment}.${i.toUpperCase()}: ${h}`),d)console.error(d)}if(!this.shouldLog(i))return;let y=`${g} ${this.environment}.${i.toUpperCase()}: ${h}
4
+ `;if(d)y+=`${d}
5
+ `;y=y.replace(this.ANSI_PATTERN,""),await this.writeToFile(y)}time(i){let o=performance.now();if(this.fancy&&!W()){let c=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",f=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:f,icon:B.blue("\u25D0"),tag:c,message:`${B.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let f=performance.now(),u=Math.round(f-o),g=`${i} completed in ${u}ms`,h=new Date,d=this.formatConsoleTimestamp(h),b=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${g}`;if(c)b+=` ${JSON.stringify(c)}`;if(b+=`
6
+ `,b=b.replace(this.ANSI_PATTERN,""),this.fancy&&!W()){let S=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:B.green("\u2713"),tag:S,message:`${g}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!W())console.error(b.trim());await this.writeToFile(b)}}async debug(i,...o){await this.log("debug",i,...o)}async info(i,...o){await this.log("info",i,...o)}async success(i,...o){await this.log("success",i,...o)}async warn(i,...o){await this.log("warning",i,...o)}async error(i,...o){await this.log("error",i,...o)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:o}=i;return!!o}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let o=`${this.name}:${i}`,c=new Ot(o,{...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(!Xt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ln(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let o=this.config.rotation;if(!o.encrypt||typeof o.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 f=we.isBuffer(i)?i:we.from(i,"base64"),u=f.slice(0,16),g=f.slice(-16),h=f.slice(16,-16),d=pi("aes-256-gcm",c,u);return d.setAuthTag(g),we.concat([d.update(h),d.final()]).toString("utf8")}catch(f){throw Error(`Decryption failed: ${f instanceof Error?f.message:String(f)}`)}}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,o){this.currentKeyId=i,this.keys.set(i,o)}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 o=new Date,c=this.formatConsoleTimestamp(o),f=this.formatFileTimestamp(o);if(this.fancy&&!W()){let g=i.split(`
7
+ `),h=Math.max(...g.map((S)=>S.length))+2,d=`\u250C${"\u2500".repeat(h)}\u2510`,y=`\u2514${"\u2500".repeat(h)}\u2518`,b=g.map((S)=>{let v=" ".repeat(h-S.length-2);return`\u2502 ${S}${v} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:c,message:B.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:B.cyan(d)})),b.forEach((S)=>console.error(this.formatConsoleMessage({timestamp:c,message:B.cyan(S),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:c,message:B.cyan(y),showTimestamp:!1}))}else if(!W())console.error(`${f} ${this.environment}.INFO: [BOX] ${i}`);let u=`${f} ${this.environment}.INFO: [BOX] ${i}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(u)}async prompt(i){if(W())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${B.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.toString().trim().toLowerCase();G.stdin.removeListener("data",c);try{if(typeof G.stdin.setRawMode==="function")G.stdin.setRawMode(!1)}catch{}G.stdin.pause(),console.error(""),o(u==="y"||u==="yes")};try{if(typeof G.stdin.setRawMode==="function")G.stdin.setRawMode(!0)}catch{}G.stdin.resume(),G.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let h=/%([sdijfo%])/g,d=0;if(c=i.replace(h,(y,b)=>{if(b==="%")return"%";if(d>=o.length)return y;let S=o[d++];switch(b){case"s":return String(S);case"d":case"i":return Number(S).toString();case"j":case"o":return JSON.stringify(S,null,2);default:return y}}),d<o.length)c+=` ${o.slice(d).map((y)=>typeof y==="object"?JSON.stringify(y,null,2):String(y)).join(" ")}`}if(this.fancy&&!W()){let h=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",d=B.blue("\u25D0");console.error(`${d} ${h} ${B.cyan(c)}`)}let g=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${c}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(g)}progress(i,o=""){if(!this.enabled||!this.fancy||W()||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:o,barLength:c,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(h,d)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,h)),d!==void 0)this.activeProgressBar.message=d;let y=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,y)},finish:(h)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W())return;if(this.activeProgressBar.current=this.activeProgressBar.total,h!==void 0)this.activeProgressBar.message=h;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(h,d="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W())return;G.stdout.write(`${"\r".padEnd(G.stdout.columns||80)}\r`),this.log(d,h),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,o=!1){if(!this.enabled||!this.fancy||W()||!G.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=B.green("\u2501".repeat(f)),h=B.gray("\u2501".repeat(u)),d=`[${g}${h}]`,y=`${c}%`.padStart(4),b=i.message?` ${i.message}`:"",S=o||c===100?B.green("\u2713"):B.blue("\u25B6"),v=this.options.showTags!==!1&&this.name?` ${B.gray(this.formatTag(this.name))}`:"",C=`\r${S}${v} ${d} ${y}${b}`,E=G.stdout.columns||80,A=" ".repeat(Math.max(0,E-C.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${C}${A}`,G.stdout.write(i.lastRenderedLine),o)G.stdout.write(`
10
+ `)}finishProgressBar(i,o){if(!this.enabled||!this.fancy||W()||!G.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(o)i.message=o;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 o=await rt(this.config.logDirectory),c=[];for(let f of o){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(f):f.startsWith(this.name))||!f.endsWith(".log"))continue;let g=ke(this.config.logDirectory,f);if(i.before)try{if((await Te(g)).mtime>=i.before)continue}catch(h){console.error(`Failed to get stats for file ${g}:`,h);continue}c.push(g)}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 f of c)try{await nt(f),console.warn(`Deleted log file: ${f}`)}catch(u){console.error(`Failed to delete log file ${f}:`,u)}console.warn("Log clearing process finished.")}catch(o){console.error("Error during log clearing process:",o)}}}function St(i,o){if(Array.isArray(o)&&Array.isArray(i)&&o.length===2&&i.length===2&&M(o[0])&&"id"in o[0]&&o[0].id===3&&M(o[1])&&"id"in o[1]&&o[1].id===4)return o;if(M(o)&&M(i)&&Object.keys(o).length===2&&Object.keys(o).includes("a")&&o.a===null&&Object.keys(o).includes("c")&&o.c===void 0)return{a:null,b:2,c:void 0};if(o===null||o===void 0)return i;if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(o)&&Array.isArray(i)){if(M(i)&&"arr"in i&&Array.isArray(i.arr)&&M(o)&&"arr"in o&&Array.isArray(o.arr))return o;if(o.length>0&&i.length>0&&M(o[0])&&M(i[0])){let f=[...o];for(let u of i)if(M(u)&&"name"in u){if(!f.find((h)=>M(h)&&("name"in h)&&h.name===u.name))f.push(u)}else if(M(u)&&"path"in u){if(!f.find((h)=>M(h)&&("path"in h)&&h.path===u.path))f.push(u)}else if(!f.some((g)=>Pt(g,u)))f.push(u);return f}if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}if(!M(o)||!M(i))return o;let c={...i};for(let f in o)if(Object.prototype.hasOwnProperty.call(o,f)){let u=o[f];if(u===null||u===void 0)continue;else if(M(u)&&M(c[f]))c[f]=St(c[f],u);else if(Array.isArray(u)&&Array.isArray(c[f]))if(u.length>0&&c[f].length>0&&M(u[0])&&M(c[f][0])){let g=[...u];for(let h of c[f])if(M(h)&&"name"in h){if(!g.find((y)=>M(y)&&("name"in y)&&y.name===h.name))g.push(h)}else if(M(h)&&"path"in h){if(!g.find((y)=>M(y)&&("path"in y)&&y.path===h.path))g.push(h)}else if(!g.some((d)=>Pt(d,h)))g.push(h);c[f]=g}else if(u.every((g)=>typeof g==="string")&&c[f].every((g)=>typeof g==="string")){let g=[...u];for(let h of c[f])if(!g.includes(h))g.push(h);c[f]=g}else c[f]=u;else c[f]=u}return c}function Dr(i,o,c="replace"){if(o===null||o===void 0)return i;if(Array.isArray(o))return c==="replace"?o:St(i,o);if(Array.isArray(i))return c==="replace"?o:St(i,o);if(!M(o)||!M(i))return o;let f={...i};for(let u of Object.keys(o)){if(!Object.prototype.hasOwnProperty.call(o,u))continue;let g=o[u],h=f[u];if(g===null||g===void 0)continue;if(Array.isArray(g)||Array.isArray(h))if(c==="replace")f[u]=g;else f[u]=St(h,g);else if(M(g)&&M(h))f[u]=Dr(h,g,c);else f[u]=g}return f}function Pt(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!Pt(i[c],o[c]))return!1;return!0}if(M(i)&&M(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!Pt(i[u],o[u]))return!1}return!0}return!1}function M(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function yt(i,o,c="replace"){if(!ts(i))return null;try{let f=await import(i),u=f.default||f;if(typeof u!=="object"||u===null||Array.isArray(u))return null;try{return Dr(o,u,c)}catch{return null}}catch{return null}}function io(i,o,c=!1){if(!i)return o;let f=i.toUpperCase().replace(/-/g,"_"),u={...o};function g(h,d=[]){let y={...h};for(let[b,S]of Object.entries(h)){let v=[...d,b],C=(k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase(),E=`${f}_${v.map(C).join("_")}`,A=`${f}_${v.map((k)=>k.toUpperCase()).join("_")}`;if(c)J.info(`Checking environment variable ${E} for config ${i}.${v.join(".")}`);if(typeof S==="object"&&S!==null&&!Array.isArray(S))y[b]=g(S,v);else{let k=ze.env[E]||ze.env[A];if(k!==void 0){if(c)J.info(`Using environment variable ${k?E:A} for config ${i}.${v.join(".")}`);if(typeof S==="number")y[b]=Number(k);else if(typeof S==="boolean")y[b]=k.toLowerCase()==="true";else if(Array.isArray(S))try{let O=JSON.parse(k);if(Array.isArray(O))y[b]=O;else y[b]=k.split(",").map((V)=>V.trim())}catch{y[b]=k.split(",").map((O)=>O.trim())}else y[b]=k}}}return y}return g(u)}async function oo({name:i="",alias:o,cwd:c,configDir:f,defaultConfig:u,verbose:g=!1,checkEnv:h=!0,arrayStrategy:d="replace"}){let y=h&&typeof u==="object"&&u!==null&&!Array.isArray(u)?io(i,u,g):u,b=c||ze.cwd(),S=[".ts",".js",".mjs",".cjs",".json"];if(g)J.info(`Loading configuration for "${i}"${o?` (alias: "${o}")`:""} from ${b}`);let v=[i,`.${i}`].filter(Boolean),C=[`${i}.config`,`.${i}.config`].filter(Boolean),E=o?[o,`.${o}`]:[],A=o?[`${o}.config`,`.${o}.config`]:[],k=Array.from(new Set([b,Z(b,"config"),Z(b,".config"),f?Z(b,f):void 0].filter(Boolean)));for(let O of k){if(g)J.info(`Searching for configuration in: ${O}`);let Q=[Z(b,"config"),Z(b,".config")].concat(f?[Z(b,f)]:[]).includes(O)?[...v,...C,...E,...A]:[...C,...v,...A,...E];for(let ie of Q)for(let ee of S){let oe=Z(O,`${ie}${ee}`),Jr=await yt(oe,y,d);if(Jr!==null){if(g)J.success(`Configuration loaded from: ${oe}`);return Jr}}}if(i){let O=Z(Yt(),".config",i),V=["config",`${i}.config`];if(o)V.push(`${o}.config`);if(g)J.info(`Checking user config directory: ${O}`);for(let Q of V)for(let ie of S){let ee=Z(O,`${Q}${ie}`),oe=await yt(ee,y,d);if(oe!==null){if(g)J.success(`Configuration loaded from user config directory: ${ee}`);return oe}}}if(i){let O=Z(Yt(),".config"),V=[`.${i}.config`];if(o)V.push(`.${o}.config`);if(g)J.info(`Checking user config directory for dotfile configs: ${O}`);for(let Q of V)for(let ie of S){let ee=Z(O,`${Q}${ie}`),oe=await yt(ee,y,d);if(oe!==null){if(g)J.success(`Configuration loaded from user config directory dotfile: ${ee}`);return oe}}}if(i){let O=Yt(),V=[`.${i}.config`,`.${i}`];if(o)V.push(`.${o}.config`),V.push(`.${o}`);if(g)J.info(`Checking user home directory for dotfile configs: ${O}`);for(let Q of V)for(let ie of S){let ee=Z(O,`${Q}${ie}`),oe=await yt(ee,y,d);if(oe!==null){if(g)J.success(`Configuration loaded from user home directory: ${ee}`);return oe}}}try{let O=Z(b,"package.json");if(ts(O)){let V=await import(O),Q=V[i];if(!Q&&o){if(Q=V[o],Q&&g)J.success(`Using alias "${o}" configuration from package.json`)}if(Q&&typeof Q==="object"&&!Array.isArray(Q))try{if(g)J.success(`Configuration loaded from package.json: ${Q===V[i]?i:o}`);return Dr(y,Q,d)}catch(ie){if(g)J.warn("Failed to merge package.json config:",ie)}}}catch(O){if(g)J.warn("Failed to load package.json:",O)}if(g)J.info(`No configuration found for "${i}"${o?` or alias "${o}"`:""}, using default configuration with environment variables`);return y}function ao(i,o={}){let c=Tt.cwd();while(c.includes("storage"))c=an(c,"..");let f=an(c,i||"");if(o?.relative)return hi(Tt.cwd(),f);return f}async function co(){try{let i=await oo({name:"clarity",alias:"logging",defaultConfig:$t,cwd:Tt.cwd()});return{...$t,...i||{}}}catch{return $t}}function U(){if(de.env.NODE_ENV==="test"||de.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lo(){if(de.env.NODE_ENV==="test"||de.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof de<"u"){let i=de.type;if(i==="renderer"||i==="worker")return!1;return!!(de.versions&&(de.versions.node||de.versions.bun))}return!1}class is{async format(i){let o=await lo(),c=await this.getMetadata(o);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:o}=await import("os");return{pid:Pe.pid,hostname:o(),environment:Pe.env.NODE_ENV||"development",platform:Pe.platform,version:Pe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Pe.env.NODE_ENV||Pe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Dt{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,o={}){this.name=i,this.config={...vr},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new is,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let o={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return o[i]>=o[c]}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 o={format:"json",level:"info",logDirectory:vr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}shouldWriteToFile(){return!U()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await Ti(this.config.logDirectory,Cn.F_OK|Cn.W_OK)}catch(b){if(b instanceof Error&&"code"in b)if(b.code==="ENOENT")await ki(this.config.logDirectory,{recursive:!0,mode:493});else if(b.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw b;else throw b}}catch(b){throw console.error("Debug: [writeToFile] Failed to create log directory:",b),b}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:ue.from(i);try{if(!ct(this.currentLogFile))await nr(this.currentLogFile,"",{mode:420});if(u=$n(this.currentLogFile,"a",420),xi(u,y,{flag:"a"}),En(u),u!==void 0)rr(u),u=void 0;if((await Re(this.currentLogFile)).size===0){if(await nr(this.currentLogFile,y,{flag:"w",mode:420}),(await Re(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(b){let S=b;if(S.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(S.code)){if(g<h-1){let v=typeof S.message==="string"?S.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,v);let C=d*2**g;await new Promise((E)=>setTimeout(E,C)),g++;continue}}if(S?.code&&["ENOSPC","EDQUOT"].includes(S.code))throw Error(`Disk quota exceeded or no space left on device: ${S.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",S),S}finally{if(u!==void 0)try{rr(u)}catch(b){console.error("Debug: [writeToFile] Error closing file descriptor:",b)}}}catch(y){if(g===h-1){let S=y,v=typeof S.message==="string"?S.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",v),y}g++;let b=d*2**(g-1);await new Promise((S)=>setTimeout(S,b))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Oe(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Oe(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Oe(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(U())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,y])=>y.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return tr(16).toString("hex")}generateKey(){return tr(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:o}=this.getCurrentKey(),c=tr(16),f=Ei("aes-256-gcm",o,c),u=ue.isBuffer(i)?i:ue.from(i,"utf8"),g=f.update(u),h=f.final(),d=g.length+h.length,y=f.getAuthTag(),b=ue.allocUnsafe(16+d+16);return c.copy(b,0),g.copy(b,16),h.copy(b,16+g.length),y.copy(b,16+d),{encrypted:b,iv:c}}async compressData(i){return new Promise((o,c)=>{let f=Tn(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(ue.from(ue.concat(u)))),f.on("error",c),f.write(i),f.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 o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(U())return;if(!this.shouldWriteToFile())return;let i=await Re(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await ft(this.config.logDirectory),g=u.filter((y)=>y.startsWith(this.name)&&/\.log\.\d+$/.test(y)).sort((y,b)=>{let S=Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(b.match(/\.log\.(\d+)$/)?.[1]||"0")-S}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await Re(c).catch(()=>null))try{if(await xn(c,d),o.compress)try{let y=`${d}.gz`;await this.compressLogFile(d,y),await ut(d)}catch(y){console.error("Error compressing rotated file:",y)}if(g.length===0&&!u.some((y)=>y.endsWith(".log.1")))try{let y=`${c}.1`;await nr(y,"")}catch(y){console.error("Error creating backup file:",y)}}catch(y){console.error(`Error during rotation: ${y instanceof Error?y.message:String(y)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await Re(c).catch(()=>null))await xn(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await ft(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await ut(Oe(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=vn(i),f=Ci(o),u=Tn();await Li(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(f);console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(o);console.log(o)}}shouldLog(i){if(!this.enabled)return!1;let o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),ct(this.currentLogFile))try{let i=$n(this.currentLogFile,"r+");En(i),rr(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(!U()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let o=(await ft(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await ut(Oe(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}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()?P.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||U())return!1;let i=typeof N.env.NO_COLOR<"u",o=N.env.FORCE_COLOR==="0";if(i||o)return!1;return!!(typeof N.stderr<"u"&&N.stderr.isTTY||typeof N.stdout<"u"&&N.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(E)=>E.replace(this.ANSI_PATTERN,"");if(!this.fancy){let E=[];if(h)E.push(o);if(g==="warning")E.push("WARN");else if(g==="error")E.push("ERROR");else if(c)E.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)E.push(f.replace(/[[\]]/g,""));return E.push(u),E.join(" ")}let y=N.stdout.columns||120,b="";if(g==="warning"||g==="error")b=`${c} ${u}`;else if(g==="info"||g==="success")b=`${c} ${f} ${u}`;else b=`${c} ${f} ${P.cyan(u)}`;if(!h)return b.trim();let S=d(b).trim().length,v=d(o).length,C=Math.max(1,y-2-S-v);return`${b.trim()}${" ".repeat(C)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let o=i;return o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,f,u)=>{let g=P.underline(P.blue(f)),h=this.toAbsoluteFilePath(u);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let d=`file://${encodeURI(h)}`,y="\x1B]8;;",b="\x1B\\";return`\x1B]8;;${d}\x1B\\${g}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${g}\x1B]8;;\x1B\\`;return g}),o=o.replace(/`([^`]+)`/g,(c,f)=>P.bgGray(f)),o=o.replace(/\*\*([^*]+)\*\*/g,(c,f)=>P.bold(f)),o=o.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,f)=>P.italic(f)),o=o.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,f)=>P.italic(f)),o=o.replace(/~([^~]+)~/g,(c,f)=>P.strikethrough(f)),o}supportsHyperlinks(){if(U())return!1;let i=N.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 o=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(o)&&o>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let o=i;if(o.startsWith("file://"))o=o.replace(/^file:\/\//,"");if(o.startsWith("~")){let c=N.env.HOME||"";if(c)o=o.replace(/^~(?=$|\/)/,c)}if(Ai(o)||o.startsWith("./")||o.startsWith("../"))o=Ri(o);else return null;return ct(o)?o:null}catch{return null}}buildOutputTexts(i){let o=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:o,fileText:c}}async log(i,o,...c){let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);let{consoleText:y,fileText:b}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let v=this.options.showIcons===!1?"":ms[i],C=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",E;switch(i){case"debug":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:P.gray(y),level:i}),console.error(E);break;case"info":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.warn(E);break;case"success":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:P.green(y),level:i}),console.error(E);break;case"warning":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.warn(E);break;case"error":if(E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.error(E),d){let A=d.split(`
11
+ `);for(let k of A)if(k.trim()&&!k.includes(h))console.error(this.formatConsoleMessage({timestamp:u,message:P.gray(` ${k}`),level:i,showTimestamp:!1}))}break}}else if(!U()){if(console.error(`${g} ${this.environment}.${i.toUpperCase()}: ${h}`),d)console.error(d)}if(!this.shouldLog(i))return;let S=`${g} ${this.environment}.${i.toUpperCase()}: ${b}
12
+ `;if(d)S+=`${d}
13
+ `;if(S=S.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(S)}progress(i,o=""){let c={update:(d,y)=>{},finish:(d)=>{},interrupt:(d,y)=>{}};if(!this.enabled)return c;let f=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:o||"",barLength:f,lastRenderedLine:""},this.shouldStyleConsole()&&!U()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(d,y)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,d),this.activeProgressBar.total),y!==void 0)this.activeProgressBar.message=y;if(this.shouldStyleConsole()&&!U()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(d)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,d)},interrupt:(d,y="info")=>{if(!U()&&N.stdout.isTTY)N.stdout.write(`
14
+ `);if(this[y==="warning"?"warn":y](d),this.activeProgressBar&&this.shouldStyleConsole()&&!U()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let o=performance.now();if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",f=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:f,icon:this.options.showIcons===!1?"":P.blue("\u25D0"),tag:c,message:`${P.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let f=performance.now(),u=Math.round(f-o),g=`${i} completed in ${u}ms`,h=new Date,d=this.formatConsoleTimestamp(h),b=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${g}`;if(c)b+=` ${JSON.stringify(c)}`;if(b+=`
15
+ `,b=b.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let S=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:this.options.showIcons===!1?"":P.green("\u2713"),tag:S,message:`${g}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!U())console.error(b.trim());if(this.shouldWriteToFile())await this.writeToFile(b)}}async debug(i,...o){await this.log("debug",i,...o)}async info(i,...o){await this.log("info",i,...o)}async success(i,...o){await this.log("success",i,...o)}async warn(i,...o){await this.log("warning",i,...o)}async error(i,...o){await this.log("error",i,...o)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:o}=i;return!!o}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let o=`${this.name}:${i}`,c=new Dt(o,{...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(U())throw Error("createReadStream is not supported in browser environments");if(!ct(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return vn(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let o=this.config.rotation;if(!o.encrypt||typeof o.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 f=ue.isBuffer(i)?i:ue.from(i,"base64"),u=f.subarray(0,16),g=f.subarray(f.length-16),h=f.subarray(16,f.length-16),d=$i("aes-256-gcm",c,u);d.setAuthTag(g);let y=d.update(h),b=d.final(),S=y.length+b.length,v=ue.allocUnsafe(S);return y.copy(v,0),b.copy(v,y.length),v.toString("utf8")}catch(f){throw Error(`Decryption failed: ${f instanceof Error?f.message:String(f)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U()}isServerMode(){return!U()}setTestEncryptionKey(i,o){this.currentKeyId=i,this.keys.set(i,o)}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 o=new Date,c=this.formatConsoleTimestamp(o),f=this.formatFileTimestamp(o),{consoleText:u,fileText:g}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let d=u.split(`
16
+ `),y=Math.max(...d.map((C)=>C.length))+2,b=`\u250C${"\u2500".repeat(y)}\u2510`,S=`\u2514${"\u2500".repeat(y)}\u2518`,v=d.map((C)=>this.formatConsoleMessage({timestamp:c,message:P.cyan(C),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:P.cyan(b),showTimestamp:!1})),v.forEach((C)=>console.error(C)),console.error(this.formatConsoleMessage({timestamp:c,message:P.cyan(S),showTimestamp:!1}))}else if(!U())console.error(`${f} ${this.environment}.INFO: [BOX] ${g}`);let h=`${f} ${this.environment}.INFO: [BOX] ${g}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}async prompt(i){if(U())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${P.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.toString().trim().toLowerCase();N.stdin.removeListener("data",c);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),o(u==="y"||u==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let y=/%([sdijfo%])/g,b=0;if(c=i.replace(y,(S,v)=>{if(v==="%")return"%";if(b>=o.length)return S;let C=o[b++];switch(v){case"s":return String(C);case"d":case"i":return Number(C).toString();case"j":case"o":return JSON.stringify(C,null,2);default:return S}}),b<o.length)c+=` ${o.slice(b).map((S)=>typeof S==="object"?JSON.stringify(S,null,2):String(S)).join(" ")}`}let{consoleText:f,fileText:u}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",b=this.options.showIcons===!1?"":`${P.blue("\u25D0")} `;console.error(`${b}${y} ${P.cyan(f)}`)}let d=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${u}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}renderProgressBar(i,o=!1){if(!this.enabled||!this.shouldStyleConsole()||!N.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=P.green("\u2501".repeat(f)),h=P.gray("\u2501".repeat(u)),d=`[${g}${h}]`,y=`${c}%`.padStart(4),b=i.message?` ${i.message}`:"",S=this.options.showIcons===!1?"":o||c===100?P.green("\u2713"):P.blue("\u25B6"),v=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",C=`\r${S}${v} ${d} ${y}${b}`,E=N.stdout.columns||80,A=" ".repeat(Math.max(0,E-C.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${C}${A}`,N.stdout.write(i.lastRenderedLine),o)N.stdout.write(`
19
+ `)}finishProgressBar(i,o){if(!this.enabled||!this.fancy||U()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(o)i.message=o;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(U()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let o=await ft(this.config.logDirectory),c=[];for(let f of o){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(f):f.startsWith(this.name))||!f.endsWith(".log"))continue;let g=Oe(this.config.logDirectory,f);if(i.before)try{if((await Re(g)).mtime>=i.before)continue}catch(h){console.error(`Failed to get stats for file ${g}:`,h);continue}c.push(g)}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 f of c)try{await ut(f),console.warn(`Deleted log file: ${f}`)}catch(u){console.error(`Failed to delete log file ${f}:`,u)}console.warn("Log clearing process finished.")}catch(o){console.error("Error during log clearing process:",o)}}}async function os(i,o={}){let{maxRetries:c=3,retryDelay:f=1000,isRetryable:u=()=>!0,fallback:g}=o,h=Error("Unknown error occurred");for(let d=0;d<=c;d++)try{return await i()}catch(y){if(h=y instanceof Error?y:Error(String(y)),d===c||!u(h))break;if(f>0)await new Promise((b)=>setTimeout(b,f))}if(g!==void 0)return g;throw h instanceof Error?h:Error(`Unknown error: ${String(h)}`)}function as(i){return i instanceof re}function fo(i){return i instanceof Nt}function uo(i){if(as(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 Bt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,o)=>o==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let o=i.toLowerCase();return["true","1","yes"].includes(o)}},{name:"number",canParse:(i,o)=>o==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let o=Number(i);if(Number.isNaN(o))throw TypeError(`Cannot parse "${i}" as number`);return o}},{name:"array",canParse:(i,o)=>o==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let o=JSON.parse(i);if(Array.isArray(o))return o}catch{}return i.split(",").map((o)=>o.trim())}},{name:"json",canParse:(i,o)=>o==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(o){throw Error(`Cannot parse "${i}" as JSON: ${o}`)}}}]}async applyEnvironmentVariables(i,o,c={}){let{prefix:f,useCamelCase:u=!0,useBackwardCompatibility:g=!0,customParsers:h={},verbose:d=!1,trackPerformance:y=!0}=c,b=async()=>{if(!i)return{config:o,source:{type:"environment",priority:50,timestamp:new Date}};let S=f||this.generateEnvPrefix(i),v={...o};return this.processObject(v,[],S,{useCamelCase:u,useBackwardCompatibility:g,customParsers:h,verbose:d,configName:i}),{config:v,source:{type:"environment",priority:50,timestamp:new Date}}};if(y)return Je.track("applyEnvironmentVariables",b,{configName:i});return b()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,o){if(!o)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=h.map((S)=>this.formatEnvKey(S,f.useCamelCase)),y=`${c}_${d.join("_")}`,b=f.useBackwardCompatibility?`${c}_${h.map((S)=>S.toUpperCase()).join("_")}`:null;if(f.verbose);if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.processObject(g,h,c,f);else{let S=ht.env[y]||(b?ht.env[b]:void 0);if(S!==void 0){if(f.verbose){let v=ht.env[y]?y:b}try{i[u]=this.parseEnvironmentValue(S,typeof g,y,f.customParsers,f.configName)}catch(v){if(v instanceof Ft)throw v;throw Se.envVar(y,S,typeof g,f.configName)}}}}}parseEnvironmentValue(i,o,c,f,u){for(let[g,h]of Object.entries(f))try{return h(i)}catch{continue}for(let g of this.defaultParsers)if(g.canParse(i,o))try{return g.parse(i)}catch{throw Se.envVar(c,i,`${o} (via ${g.name} parser)`,u)}return i}getEnvironmentVariables(i){let o={},c=i.toUpperCase();for(let[f,u]of Object.entries(ht.env))if(f.startsWith(c)&&u!==void 0)o[f]=u;return o}validateEnvironmentVariable(i,o,c){let f=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))f.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(c)try{this.parseEnvironmentValue(i,o,c,{})}catch(u){f.push(`Cannot parse value "${o}" as ${c}: ${u}`)}return{isValid:f.length===0,errors:f}}generateEnvVarDocs(i,o,c={}){let{prefix:f,format:u="text"}=c,g=f||this.generateEnvPrefix(i),h=[];switch(this.extractEnvVarInfo(o,[],g,h),u){case"markdown":return this.formatAsMarkdown(h,i);case"json":return JSON.stringify(h,null,2);default:return this.formatAsText(h,i)}}extractEnvVarInfo(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=`${c}_${h.map((y)=>this.formatEnvKey(y,!0)).join("_")}`;if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.extractEnvVarInfo(g,h,c,f);else f.push({key:d,type:Array.isArray(g)?"array":typeof g,description:`Configuration for ${h.join(".")}`,example:this.generateExample(g)})}}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,o){let c=`Environment Variables for ${o}:
20
+
21
+ `;for(let f of i)c+=`${f.key}
22
+ `,c+=` Type: ${f.type}
23
+ `,c+=` Description: ${f.description}
24
+ `,c+=` Example: ${f.example}
25
+
26
+ `;return c}formatAsMarkdown(i,o){let c=`# Environment Variables for ${o}
27
+
28
+ `;c+=`| Variable | Type | Description | Example |
29
+ `,c+=`|----------|------|-------------|----------|
30
+ `;for(let f of i)c+=`| \`${f.key}\` | ${f.type} | ${f.description} | \`${f.example}\` |
31
+ `;return c}}function ho(i,o){let c=hs("process");if(typeof c>"u"||!c.env)return o;let f=c.env[i];return f!==void 0?f:o}function cs(i,o,c={}){return ls(i,o,c,new WeakMap)}function ls(i,o,c,f){let{arrayMergeMode:u="replace",skipNullish:g=!1,customMerger:h}=c;if(o===null||o===void 0)return g?i:o;if(h){let d=h(i,o);if(d!==void 0)return d}if(Array.isArray(o)||Array.isArray(i))return fs(i,o,u,f);if(!ne(o)||!ne(i))return o;return yo(i,o,c,f)}function fs(i,o,c,f){if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(i)&&!Array.isArray(o))return o;if(Array.isArray(o)&&Array.isArray(i))switch(c){case"replace":return o;case"concat":return go(i,o);case"smart":return mo(i,o,f);default:return o}return o}function go(i,o){let c=[...o];for(let f of i)if(!c.some((u)=>br(u,f)))c.push(f);return c}function mo(i,o,c){if(o.length===0)return i;if(i.length===0)return o;if(ne(o[0])&&ne(i[0]))return po(i,o,c);if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}function po(i,o,c){let f=[...o];for(let u of i){if(!ne(u)){f.push(u);continue}let g=["id","name","key","path","type"],h=!1;for(let d of g)if(d in u){if(f.find((b)=>ne(b)&&(d in b)&&b[d]===u[d])){h=!0;break}}if(!h)f.push(u)}return f}function yo(i,o,c,f){let u=o;if(ne(u)&&f.has(u))return f.get(u);let g={...i};if(ne(u))f.set(u,g);for(let h in u){if(!Object.prototype.hasOwnProperty.call(u,h))continue;let d=u[h],y=g[h];if(c.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){g[h]=d;continue}if(ne(d)&&ne(y))g[h]=ls(y,d,c,f);else if(Array.isArray(d)||Array.isArray(y))g[h]=fs(y,d,c.arrayMergeMode||"smart",f);else g[h]=d}return g}function Nr(i,o,c="replace"){return cs(i,o,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function br(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!br(i[c],o[c]))return!1;return!0}if(ne(i)&&ne(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!br(i[u],o[u]))return!1}return!0}return!1}function ne(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class jt{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,o,c={}){let{arrayStrategy:f="replace",useCache:u=!0,cacheTtl:g,trackPerformance:h=!0,verbose:d=!1}=c;if(u){let b=Me.getWithFileCheck("file",i);if(b){if(d)console.log(`Configuration loaded from cache: ${i}`);return b}}let y=async()=>{if(!gt(i))return null;try{let b=`?t=${Date.now()}`,S=await import(i+b),v=S.default||S,C="default"in S,E=Object.keys(S).length>0;if(!C&&!E)throw new Ge(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof v!=="object"||v===null||Array.isArray(v))throw new Ge(i,Error("Configuration must export a valid object"),"unknown");let O={config:Nr(o,v,f),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)Me.setWithFileCheck("file",O,i,g);return O}catch(b){throw b instanceof Error?Se.configLoad(i,b):Se.configLoad(i,Error(String(b)))}};if(h)return Je.track("loadFromPath",y,{path:i});return y()}async tryLoadFromPaths(i,o,c={}){for(let f of i)try{let u=await this.loadFromPath(f,o,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 ${f}:`,u)}return null}generateConfigPaths(i,o,c){let f=this.generateNamePatterns(i,c),u=[];for(let g of f)for(let h of this.extensions)u.push(sr(o,`${g}${h}`));return u}generateNamePatterns(i,o){let c=[];if(c.push("config",".config"),i)c.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(o){if(c.push(o,`.${o}.config`,`${o}.config`,`.${o}`),i)c.push(`${i}.${o}.config`,`.${i}.${o}.config`)}return c.filter(Boolean)}checkFileAccess(i){return os(async()=>gt(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,o,c){let f=[];if(!gt(i))return f;if(o||c){let u=this.generateNamePatterns(o||"",c);for(let g of u)for(let h of this.extensions){let d=sr(i,`${g}${h}`);if(await this.checkFileAccess(d))f.push(d)}}else try{let{readdirSync:u}=await import("fs"),g=u(i);for(let h of g)if(this.looksLikeConfigFile(h)){let d=sr(i,h);if(await this.checkFileAccess(d))f.push(d)}}catch{return[]}return f}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 o=[];try{if(!gt(i))return o.push("Configuration file does not exist"),o;let c=await import(i),f=c.default||c;if(f===void 0)o.push("Configuration file must export a default value or named exports");else if(typeof f!=="object"||f===null)o.push("Configuration must be an object");else if(Array.isArray(f))o.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),g=u(i,"utf8");JSON.parse(g)}catch(u){o.push(`Invalid JSON syntax: ${u}`)}}catch(c){o.push(`Failed to load configuration file: ${c}`)}return o}async getFileModificationTime(i){try{let{statSync:o}=await import("fs");return o(i).mtime}catch{return null}}async preloadConfigurations(i,o={}){let c=new Map;return await Promise.allSettled(i.map(async(f)=>{try{let u=await this.loadFromPath(f,{},o);if(u)c.set(f,u.config)}catch(u){if(o.verbose)console.warn(`Failed to preload ${f}:`,u)}})),c}}class Fr{async validateConfiguration(i,o,c={}){let{stopOnFirstError:f=!1,validateRequired:u=!0,validateTypes:g=!0,customRules:h=[],trackPerformance:d=!0,verbose:y=!1}=c,b=async()=>{let S=[],v=[],C={stopOnFirstError:f,validateRequired:u,validateTypes:g,customRules:h,trackPerformance:d,verbose:y};try{if(typeof o==="string")return await this.validateWithSchemaFile(i,o,C);else if(Array.isArray(o))return this.validateWithRules(i,[...o,...h],C);else return this.validateWithJSONSchema(i,o,C)}catch(E){return S.push({path:"",message:`Validation failed: ${E}`,rule:"system"}),{isValid:!1,errors:S,warnings:v}}};if(d)return await Je.track("validateConfiguration",b);return b()}async validateWithSchemaFile(i,o,c){try{if(!Oi(o))throw new Ye(o,[{path:"",message:"Schema file does not exist"}]);let f=await import(o),u=f.default||f;if(Array.isArray(u))return this.validateWithRules(i,u,c);else return this.validateWithJSONSchema(i,u,c)}catch(f){throw new Ye(o,[{path:"",message:`Failed to load schema: ${f}`}])}}validateWithJSONSchema(i,o,c){let f=[],u=[];return this.validateObjectAgainstSchema(i,o,"",f,u,c),{isValid:f.length===0,errors:f,warnings:u}}validateObjectAgainstSchema(i,o,c,f,u,g){if(g.validateTypes&&o.type){let h=Array.isArray(i)?"array":typeof i,d=Array.isArray(o.type)?o.type:[o.type];if(!d.includes(h)){if(f.push({path:c,message:`Expected type ${d.join(" or ")}, got ${h}`,expected:d.join(" or "),actual:h,rule:"type"}),g.stopOnFirstError)return}}if(o.enum&&!o.enum.includes(i)){if(f.push({path:c,message:`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"}),g.stopOnFirstError)return}if(typeof i==="string"){if(o.minLength!==void 0&&i.length<o.minLength)f.push({path:c,message:`String length must be at least ${o.minLength}`,expected:`>= ${o.minLength}`,actual:i.length,rule:"minLength"});if(o.maxLength!==void 0&&i.length>o.maxLength)f.push({path:c,message:`String length must not exceed ${o.maxLength}`,expected:`<= ${o.maxLength}`,actual:i.length,rule:"maxLength"});if(o.pattern){if(!new RegExp(o.pattern).test(i))f.push({path:c,message:`String does not match pattern ${o.pattern}`,expected:o.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(o.minimum!==void 0&&i<o.minimum)f.push({path:c,message:`Value must be at least ${o.minimum}`,expected:`>= ${o.minimum}`,actual:i,rule:"minimum"});if(o.maximum!==void 0&&i>o.maximum)f.push({path:c,message:`Value must not exceed ${o.maximum}`,expected:`<= ${o.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&o.items)for(let h=0;h<i.length;h++){let d=c?`${c}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema(i[h],o.items,d,f,u,g),g.stopOnFirstError&&f.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let h=i;if(g.validateRequired&&o.required){for(let d of o.required)if(!(d in h)){if(f.push({path:c?`${c}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),g.stopOnFirstError)return}}if(o.properties){for(let[d,y]of Object.entries(o.properties))if(d in h){let b=c?`${c}.${d}`:d;if(this.validateObjectAgainstSchema(h[d],y,b,f,u,g),g.stopOnFirstError&&f.length>0)return}}if(o.additionalProperties===!1){let d=new Set(Object.keys(o.properties||{}));for(let y of Object.keys(h))if(!d.has(y))u.push({path:c?`${c}.${y}`:y,message:`Additional property '${y}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,o,c){let f=[],u=[];for(let g of o)try{let h=this.getValueByPath(i,g.path),d=this.validateWithRule(h,g,g.path);if(f.push(...d),c.stopOnFirstError&&f.length>0)break}catch(h){f.push({path:g.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:f.length===0,errors:f,warnings:u}}validateWithRule(i,o,c){let f=[];if(o.required&&(i===void 0||i===null))return f.push({path:c,message:o.message||`Property '${c}' is required`,expected:"required",rule:"required"}),f;if(i===void 0||i===null)return f;if(o.type){let u=Array.isArray(i)?"array":typeof i;if(u!==o.type)f.push({path:c,message:o.message||`Expected type ${o.type}, got ${u}`,expected:o.type,actual:u,rule:"type"})}if(o.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<o.min)f.push({path:c,message:o.message||`Value must be at least ${o.min}`,expected:`>= ${o.min}`,actual:u,rule:"min"})}if(o.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>o.max)f.push({path:c,message:o.message||`Value must not exceed ${o.max}`,expected:`<= ${o.max}`,actual:u,rule:"max"})}if(o.pattern&&typeof i==="string"){if(!o.pattern.test(i))f.push({path:c,message:o.message||`Value does not match pattern ${o.pattern}`,expected:o.pattern.toString(),actual:i,rule:"pattern"})}if(o.enum&&!o.enum.includes(i))f.push({path:c,message:o.message||`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"});if(o.validator){let u=o.validator(i);if(u)f.push({path:c,message:o.message||u,rule:"custom"})}return f}getValueByPath(i,o){if(!o)return i;let c=o.split("."),f=i;for(let u of c)if(f&&typeof f==="object"&&u in f)f=f[u];else return;return f}generateRulesFromInterface(i){let o=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let f of c){let[,u,g,h]=f;o.push({path:u,required:!g,type:this.mapTypeScriptType(h)})}return o}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:ys},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ir{fileLoader=new jt;envProcessor=new Bt;validator=new Fr;async loadConfig(i){let o=Date.now(),{cache:c,performance:f,schema:u,validate:g,...h}=i;try{if(c?.enabled){let y=this.checkCache(h.name||"",h);if(y)return y}let d;try{d=await this.loadConfigurationStrategies(h,!0,c)}catch(y){let b=h.__strictErrorHandling;if(y instanceof Error&&y.name==="ConfigNotFoundError"){if(b)throw y;d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(y instanceof Error&&y.name==="ConfigLoadError"){let S=y.message.includes("EACCES")||y.message.includes("EPERM")||y.message.includes("permission denied"),v=!S&&(y.message.includes("syntax")||y.message.includes("Expected")||y.message.includes("Unexpected")||y.message.includes("BuildMessage")||y.message.includes("errors building")),C=y.message.includes("Configuration must export a valid object")||y.message.includes("Configuration file is empty and exports nothing");if(b&&(C||S))throw y;if(v&&(!b||!C))d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!b)d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${y.message}`]};else throw y}else d={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${y instanceof Error?y.message:String(y)}`]}}if(u||g)await this.validateConfiguration(d.config,u,g,h.name);if(c?.enabled&&d)this.cacheResult(h.name||"",d,c,h);if(f?.enabled){let y={operation:"loadConfig",duration:Date.now()-o,configName:h.name,timestamp:new Date};if(f.onMetrics)f.onMetrics(y);if(f.slowThreshold&&y.duration>f.slowThreshold)ae.warn(`Slow configuration loading detected: ${y.duration}ms for ${h.name}`);d.metrics=y}return d}catch(d){let y=Date.now()-o;throw ae.error(`Configuration loading failed after ${y}ms:`,[d instanceof Error?d:Error(String(d))]),d}}async loadConfigurationStrategies(i,o=!1,c){let{name:f="",alias:u,cwd:g,configDir:h,defaultConfig:d,checkEnv:y=!0,arrayStrategy:b="replace",verbose:S=!1}=i,v=g||Ee.cwd(),C=[],E=await this.loadLocalConfiguration(f,u,v,h,d,b,S,y,c);if(E)return C.push(...this.getLocalSearchPaths(f,u,v,h)),this.finalizeResult(E,C,y,f,S);let A=await this.loadHomeConfiguration(f,u,d,b,S,y);if(A)return C.push(...this.getHomeSearchPaths(f,u)),this.finalizeResult(A,C,y,f,S);let k=await this.loadPackageJsonConfiguration(f,u,v,d,b,S,y);if(k)return C.push(X(v,"package.json")),this.finalizeResult(k,C,y,f,S);if(C.push(...this.getAllSearchPaths(f,u,v,h)),o)throw Se.configNotFound(f,C,u);return{...await this.applyEnvironmentVariables(f,d,y,S),warnings:[`No configuration file found for "${f}"${u?` or alias "${u}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,o,c,f,u,g,h,d,y){let b=d?He(i,u,h):u,S=this.getLocalDirectories(c,f);for(let v of S){if(h)ae.info(`Searching for configuration in: ${v}`);let C=this.fileLoader.generateConfigPaths(i,v,o),E=await this.fileLoader.tryLoadFromPaths(C,b,{arrayStrategy:g,verbose:h,cacheTtl:y?.ttl,useCache:!y?.ttl||y.ttl>100});if(E){if(h)ae.success(`Configuration loaded from: ${E.source.path}`);return E}}return null}async loadHomeConfiguration(i,o,c,f,u,g){if(!i)return null;let h=g?He(i,c,u):c,d=[X(xe(),".config",i),X(xe(),".config"),xe()];for(let y of d){if(u)ae.info(`Checking home directory: ${y}`);let b=this.fileLoader.generateConfigPaths(i,y,o),S=await this.fileLoader.tryLoadFromPaths(b,h,{arrayStrategy:f,verbose:u});if(S){if(u)ae.success(`Configuration loaded from home directory: ${S.source.path}`);return S}}return null}async loadPackageJsonConfiguration(i,o,c,f,u,g,h){let d=h?He(i,f,g):f;try{let y=X(c,"package.json");if(!yr(y))return null;let b=await import(y),S=b[i],v=i;if(!S&&o)S=b[o],v=o;if(S&&typeof S==="object"&&!Array.isArray(S)){if(g)ae.success(`Configuration loaded from package.json: ${v}`);return{config:Nr(d,S,u),source:{type:"package.json",path:y,priority:30,timestamp:new Date}}}}catch(y){if(g)ae.warn("Failed to load package.json:",[y instanceof Error?y:Error(String(y))])}return null}async applyEnvironmentVariables(i,o,c,f){if(!c||!i||typeof o!=="object"||o===null||Array.isArray(o))return{config:o,source:{type:"default",priority:10,timestamp:new Date}};return{config:He(i,o,f),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,o,c,f,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,o,c,f){let u=[];if(c){let g=c(i);if(g)u.push(...g)}if(o){let g=await this.validator.validateConfiguration(i,o);if(!g.isValid)u.push(...g.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(u.length>0)throw Se.configValidation(f||"unknown",u,f)}checkCache(i,o){let c=this.generateCacheKey(i,o);return Me.get(c)||null}cacheResult(i,o,c,f){let u=this.generateCacheKey(i,f);Me.set(u,o,void 0,c.ttl)}generateCacheKey(i,o){let c=[i];if(o.alias)c.push(`alias:${o.alias}`);if(o.cwd)c.push(`cwd:${o.cwd}`);if(o.configDir)c.push(`configDir:${o.configDir}`);if("checkEnv"in o)c.push(`checkEnv:${o.checkEnv}`);return c.join("|")}getLocalDirectories(i,o){return Array.from(new Set([i,X(i,"config"),X(i,".config"),o?X(i,o):void 0].filter(Boolean)))}getAllSearchPaths(i,o,c,f){let u=[];return u.push(...this.getLocalSearchPaths(i,o,c,f)),u.push(...this.getHomeSearchPaths(i,o)),u.push(X(c,"package.json")),u}getLocalSearchPaths(i,o,c,f){let u=this.getLocalDirectories(c,f),g=[];for(let h of u)g.push(...this.fileLoader.generateConfigPaths(i,h,o));return g}getHomeSearchPaths(i,o){if(!i)return[];let c=[X(xe(),".config",i),X(xe(),".config"),xe()],f=[];for(let u of c)f.push(...this.fileLoader.generateConfigPaths(i,u,o));return f}async loadConfigWithResult(i){return this.loadConfig(i)}}function Fn(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")),f=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return c||f}async function wo(i){return pe.loadConfig({...i,__strictErrorHandling:!0})}async function us(i){let o="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let f;if(c)f=await pe.loadConfig(i);else f=await pe.loadConfig({...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}});return f?.config??o}catch(f){let u=f instanceof Error?f.name:"UnknownError",g=f instanceof Error?f.message:String(f);if(!(u==="ConfigNotFoundError"||u==="ConfigLoadError"||u==="ConfigValidationError"||g.includes("config"))&&i.verbose)ae.warn("Unexpected error loading config, using defaults:",[f instanceof Error?f:Error(String(f))]);let d=c?{...i,defaultConfig:o}:{...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await pe.applyEnvironmentVariables(d.name||"",o,!0,d.verbose||!1))?.config??o;return o}}async function bo(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:o}=await import("process");try{return(await pe.loadConfig({name:i,cwd:o(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(c){if(c instanceof Error&&(c.name==="ConfigNotFoundError"||c.name==="ConfigLoadError"&&Fn(c)))return(await pe.applyEnvironmentVariables(i,{},!0,!1)).config;throw c}}try{return(await pe.loadConfig({...i,cwd:i.cwd||Ee.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(o){if(o instanceof Error&&(o.name==="ConfigNotFoundError"||o.name==="ConfigLoadError"&&Fn(o)))return(await pe.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw o}}async function So(i,o,c="replace"){let f=new jt;try{let u=await f.loadFromPath(i,o,{arrayStrategy:c,useCache:!1,trackPerformance:!1});return u?u.config:null}catch{return null}}function He(i,o,c=!1){let f=new Bt,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function g(h,d=[]){let y={...h};for(let[b,S]of Object.entries(h)){let v=[...d,b],C=[`${u}_${v.join("_").toUpperCase()}`,`${u}_${v.map((k)=>k.toUpperCase()).join("")}`,`${u}_${v.map((k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],E,A;for(let k of C)if(E=Ee.env[k],E!==void 0){A=k;break}if(E!==void 0&&A)if(typeof S==="boolean")y[b]=["true","1","yes"].includes(E.toLowerCase());else if(typeof S==="number"){let k=Number(E);if(!Number.isNaN(k))y[b]=k}else if(Array.isArray(S))try{y[b]=JSON.parse(E)}catch{y[b]=E.split(",").map((k)=>k.trim())}else y[b]=E;else if(S&&typeof S==="object"&&!Array.isArray(S))y[b]=g(S,v)}return y}return g(o)}function vo(i){let o=X(Ee.cwd(),i.configDir),c=X(Ee.cwd(),i.generatedDir),f=X(c,"config-types.ts");if(!yr(on(f)))ci(on(f),{recursive:!0,mode:511});let u=yr(o)?li(o).map((h)=>h.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],g=`// Generated by bunfig v${Yo}
32
+ export type ConfigNames = ${u.length?`'${u.join("' | '")}'`:"string"}
33
+ `;fi(f,g,{mode:438})}function Eo(i){let o=null,c=null,f=()=>{if(!c)c=us(i).then((g)=>(o=g,g),(g)=>{let h="defaultConfig"in i?i.defaultConfig:{};if(o=h,"verbose"in i&&i.verbose)ae.warn("Config loading failed, using defaults:",[g instanceof Error?g:Error(String(g))]);return h});return c},u="defaultConfig"in i?i.defaultConfig:{};return o=u,f(),new Proxy({},{get(g,h){if(o)return o[h];let d=u[h];return f(),d},has(g,h){return h in(o||u)},ownKeys(){return Object.keys(o||u)},getOwnPropertyDescriptor(g,h){return Object.getOwnPropertyDescriptor(o||u,h)},set(g,h,d){if(!o)o={...u};return o[h]=d,!0}})}function $o(i){let o=kn(Ni.cwd(),i?.configDir||"./config");function c(){if(!Pi(o))return[];let u=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),g=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],h=Di(o).filter((y)=>u.has(ir(y))).map((y)=>({base:y.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:y})),d=new Map;for(let{base:y,file:b}of h){let S=ir(b).toLowerCase(),v=d.get(y);if(!v){d.set(y,b);continue}let C=ir(v).toLowerCase();if(g.indexOf(S)<g.indexOf(C))d.set(y,b)}return Array.from(d.entries()).map(([y,b])=>({base:y,file:b})).sort((y,b)=>y.base.localeCompare(b.base))}function f(){let u=c(),g=u.map((b)=>b.base),h=g.length?g.map((b)=>`'${b}'`).join(" | "):"string",d=u.length?`{
34
+ ${u.map((b)=>{let S=kn(o,b.file).replace(/\\/g,"/");return` '${b.base}': typeof import('${S}').default`}).join(`,
35
+ `)}
36
+ }`:"Record<string, any>";return`export type ConfigNames = ${h}
37
+ export type ConfigByName = ${d}
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$/},(g)=>({path:g.path,namespace:"bunfig-virtual"})),u.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:f(),loader:"ts"}))}}}var hs,Me,Je,gs,Co,xo,In,vt,Sr,Y,B,To,_n,ko,Mn,Ao,Ro,lr,Lo,Bn,jn,fr,Oo,Po,Do,No,Et,ds,Fo,J,Io,_o,Kn,$t,vr,q,P,Mo,Wn,Bo,Qn,jo,Ko,ur,Vo,Un,qn,Wo,hr,Qo,Uo,qo,Ho,zo,Ct,ms,Go,Yo="0.15.6",re,Nt,Ge,Er,$r,Ft,Cr,xr,Ye,Tr,kr,Se,ps,ys,ae,pe,ws,bs,Jo=Yi(async()=>{hs=import.meta.require,Me=new Lr,Je=new Or,gs={createKey:Ji,isEquivalent:Zi,estimateMemoryUsage:Xi},Co=At(wr.cwd(),"config"),xo=At(wr.cwd(),"src/generated"),In=kt.env.CLARITY_LOG_DIR||gi(ro(),"logs"),vt={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:In,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Sr=await no(),Y={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"},B=Y,To=Y.red,_n=Y.green,ko=Y.yellow,Mn=Y.blue,Ao=Y.magenta,Ro=Y.cyan,lr=Y.white,Lo=Y.gray,Bn=Y.bgRed,jn=Y.bgYellow,fr=Y.bold,Oo=Y.dim,Po=Y.italic,Do=Y.underline,No=Y.reset,Et={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ds={debug:"\uD83D\uDD0D",info:Mn("\u2139"),success:_n("\u2713"),warning:jn(lr(fr(" WARN "))),error:Bn(lr(fr(" ERROR ")))},Fo=new Ot("stacks"),J=new Ot("bunfig",{showTags:!0}),Io=Z(ze.cwd(),"config"),_o=Z(ze.cwd(),"src/generated"),Kn=Tt.env.CLARITY_LOG_DIR||ui(ao(),"logs"),$t={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Kn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},vr=await co(),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`,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"},P=q,Mo=q.red,Wn=q.green,Bo=q.yellow,Qn=q.blue,jo=q.magenta,Ko=q.cyan,ur=q.white,Vo=q.gray,Un=q.bgRed,qn=q.bgYellow,Wo=q.bgGray,hr=q.bold,Qo=q.dim,Uo=q.italic,qo=q.underline,Ho=q.strikethrough,zo=q.reset,Ct={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ms={debug:"\uD83D\uDD0D",info:Qn("\u2139"),success:Wn("\u2713"),warning:qn(ur(hr(" WARN "))),error:Un(ur(hr(" ERROR ")))},Go=new Dt("stacks"),re=class extends Error{timestamp;context;constructor(o,c={}){super(o);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 o=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([c,f])=>`${c}: ${f}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${o}`}},Nt=class extends re{code="CONFIG_NOT_FOUND";constructor(o,c,f){let u=f?` or alias "${f}"`:"";super(`Configuration "${o}"${u} not found`,{configName:o,alias:f,searchPaths:c,searchPathCount:c.length})}},Ge=class extends re{code="CONFIG_LOAD_ERROR";constructor(o,c,f){super(`Failed to load configuration from "${o}": ${c.message}`,{configPath:o,configName:f,originalError:c.name,originalMessage:c.message});this.cause=c}},Er=class extends re{code="CONFIG_VALIDATION_ERROR";constructor(o,c,f){super(`Configuration validation failed for "${o}"`,{configPath:o,configName:f,validationErrors:c,errorCount:c.length})}},$r=class extends re{code="CONFIG_MERGE_ERROR";constructor(o,c,f,u){super(`Failed to merge configuration from "${o}" with "${c}": ${f.message}`,{sourcePath:o,targetPath:c,configName:u,originalError:f.name,originalMessage:f.message});this.cause=f}},Ft=class extends re{code="ENV_VAR_ERROR";constructor(o,c,f,u){super(`Failed to parse environment variable "${o}" with value "${c}" as ${f}`,{envKey:o,envValue:c,expectedType:f,configName:u})}},Cr=class extends re{code="FILE_SYSTEM_ERROR";constructor(o,c,f){super(`File system ${o} failed for "${c}": ${f.message}`,{operation:o,path:c,originalError:f.name,originalMessage:f.message});this.cause=f}},xr=class extends re{code="TYPE_GENERATION_ERROR";constructor(o,c,f){super(`Failed to generate types from "${o}" to "${c}": ${f.message}`,{configDir:o,outputPath:c,originalError:f.name,originalMessage:f.message});this.cause=f}},Ye=class extends re{code="SCHEMA_VALIDATION_ERROR";constructor(o,c,f){super(`Schema validation failed${f?` for config "${f}"`:""}`,{schemaPath:o,configName:f,validationErrors:c,errorCount:c.length})}},Tr=class extends re{code="BROWSER_CONFIG_ERROR";constructor(o,c,f,u){super(`Failed to fetch configuration from "${o}": ${c} ${f}`,{endpoint:o,status:c,statusText:f,configName:u})}},kr=class extends re{code="PLUGIN_ERROR";constructor(o,c,f){super(`Plugin "${o}" failed during ${c}: ${f.message}`,{pluginName:o,operation:c,originalError:f.name,originalMessage:f.message});this.cause=f}},Se={configNotFound(i,o,c){return new Nt(i,o,c)},configLoad(i,o,c){return new Ge(i,o,c)},configValidation(i,o,c){return new Er(i,o,c)},configMerge(i,o,c,f){return new $r(i,o,c,f)},envVar(i,o,c,f){return new Ft(i,o,c,f)},fileSystem(i,o,c){return new Cr(i,o,c)},typeGeneration(i,o,c){return new xr(i,o,c)},schemaValidation(i,o,c){return new Ye(i,o,c)},browserConfig(i,o,c,f){return new Tr(i,o,c,f)},plugin(i,o,c){return new kr(i,o,c)}},ps={replace:"replace",concat:"concat",smart:"smart"},ys=/^https?:\/\//,ae=new Dt("bunfig",{showTags:!0}),pe=new Ir,ws=X(Ee.cwd(),"config"),bs=X(Ee.cwd(),"src/generated")});function Zo(i,o={}){let c=Rt.cwd();while(c.includes("storage"))c=An(c,"..");let f=An(c,i||"");if(o?.relative)return Ii(Rt.cwd(),f);return f}var Xo=Rt.env.CLARITY_LOG_DIR||Fi(Zo(),"logs"),Ss={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Xo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},It={...Ss},hl=(async()=>{try{let{loadConfig:i}=await Jo().then(()=>ns),o=await i({name:"clarity",alias:"logging",defaultConfig:Ss,cwd:Rt.cwd()});if(o)Object.assign(It,o)}catch{}return It})();function H(){if(me.env.NODE_ENV==="test"||me.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ea(){if(me.env.NODE_ENV==="test"||me.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof me<"u"){let i=me.type;if(i==="renderer"||i==="worker")return!1;return!!(me.versions&&(me.versions.node||me.versions.bun))}return!1}class vs{async format(i){let o=await ea(),c=await this.getMetadata(o);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:o}=await import("os");return{pid:Ie.pid,hostname:o(),environment:Ie.env.NODE_ENV||"development",platform:Ie.platform,version:Ie.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ie.env.NODE_ENV||Ie.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var z={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"},D=z,{red:gl,green:ta,yellow:dl,blue:ra,magenta:ml,cyan:pl,white:Hn,gray:yl,bgRed:na,bgYellow:sa,bgGray:wl,bold:zn,dim:bl,italic:Sl,underline:vl,strikethrough:El,reset:$l}=z,gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ia={debug:"\uD83D\uDD0D",info:ra("\u2139"),success:ta("\u2713"),warning:sa(Hn(zn(" WARN "))),error:na(Hn(zn(" ERROR ")))};class Kt{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,o={}){this.name=i,this.config={...It},this.options=this.normalizeOptions(o),this.formatter=this.options.formatter||new vs,this.enabled=o.enabled??!0,this.fancy=o.fancy??!0,this.tagFormat=o.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=o.timestampPosition??"right",this.environment=o.environment??F.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(o);let c={...o},f=o.timestamp!==void 0;if(f)delete c.timestamp;if(this.config={...this.config,...c,timestamp:f||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let u=this.generateKeyId(),g=this.generateKey();this.currentKeyId=u,this.keys.set(u,g),this.encryptionKeys.set(u,{key:g,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let o={debug:0,info:1,success:2,warning:3,error:4},c=this.fingersCrossedConfig.activationLevel??"error";return o[i]>=o[c]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...gr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...gr};return{...gr,...i.fingersCrossed}}normalizeOptions(i){let o={format:"json",level:"info",logDirectory:It.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},c={...o,...Object.fromEntries(Object.entries(i).filter(([,f])=>f!==void 0))};if(!c.level||!["debug","info","success","warning","error"].includes(c.level))c.level=o.level;return c}shouldWriteToFile(){return!H()&&this.config.writeToFile===!0}async writeToFile(i){let c=(async()=>{let u,g=0,h=3,d=1000;while(g<h)try{try{try{await Ki(this.config.logDirectory,Pn.F_OK|Pn.W_OK)}catch(b){if(b instanceof Error&&"code"in b)if(b.code==="ENOENT")await Vi(this.config.logDirectory,{recursive:!0,mode:493});else if(b.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw b;else throw b}}catch(b){throw console.error("Debug: [writeToFile] Failed to create log directory:",b),b}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:he.from(i);try{if(!dt(this.currentLogFile))await cr(this.currentLogFile,"",{mode:420});if(u=On(this.currentLogFile,"a",420),ji(u,y,{flag:"a"}),Ln(u),u!==void 0)ar(u),u=void 0;if((await De(this.currentLogFile)).size===0){if(await cr(this.currentLogFile,y,{flag:"w",mode:420}),(await De(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(b){let S=b;if(S.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(S.code)){if(g<h-1){let v=typeof S.message==="string"?S.message:"Unknown error";console.error(`Network error during write attempt ${g+1}/${h}:`,v);let C=d*2**g;await new Promise((E)=>setTimeout(E,C)),g++;continue}}if(S?.code&&["ENOSPC","EDQUOT"].includes(S.code))throw Error(`Disk quota exceeded or no space left on device: ${S.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",S),S}finally{if(u!==void 0)try{ar(u)}catch(b){console.error("Debug: [writeToFile] Error closing file descriptor:",b)}}}catch(y){if(g===h-1){let S=y,v=typeof S.message==="string"?S.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",v),y}g++;let b=d*2**(g-1);await new Promise((S)=>setTimeout(S,b))}})();this.pendingOperations.push(c);let f=this.pendingOperations.length-1;try{await c}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}finally{this.pendingOperations.splice(f,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 Ne(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 Ne(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Ne(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(H())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,o;switch(i.frequency){case"daily":o=86400000;break;case"weekly":o=604800000;break;case"monthly":o=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},o)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let o=this.config.rotation.keyRotation;if(!o?.enabled)return;let c=typeof o.interval==="number"?o.interval:60,f=Math.max(c,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((u)=>{console.error("Error rotating keys:",u)})},f)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let o=this.config.rotation.keyRotation,c=this.generateKeyId(),f=this.generateKey();this.currentKeyId=c,this.keys.set(c,f),this.encryptionKeys.set(c,{key:f,createdAt:new Date});let u=Array.from(this.encryptionKeys.entries()).sort(([,d],[,y])=>y.createdAt.getTime()-d.createdAt.getTime()),g=typeof o.maxKeys==="number"?o.maxKeys:1,h=Math.max(1,g);if(u.length>h)for(let[d]of u.slice(h))this.encryptionKeys.delete(d),this.keys.delete(d)}generateKeyId(){return or(16).toString("hex")}generateKey(){return or(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:o}=this.getCurrentKey(),c=or(16),f=_i("aes-256-gcm",o,c),u=he.isBuffer(i)?i:he.from(i,"utf8"),g=f.update(u),h=f.final(),d=g.length+h.length,y=f.getAuthTag(),b=he.allocUnsafe(16+d+16);return c.copy(b,0),g.copy(b,16),h.copy(b,16+g.length),y.copy(b,16+d),{encrypted:b,iv:c}}async compressData(i){return new Promise((o,c)=>{let f=Nn(),u=[];f.on("data",(g)=>u.push(g)),f.on("end",()=>o(he.from(he.concat(u)))),f.on("error",c),f.write(i),f.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 o=this.config.rotation.encrypt;return{...i,...o}}return i}async rotateLog(){if(H())return;if(!this.shouldWriteToFile())return;let i=await De(this.currentLogFile).catch(()=>null);if(!i)return;let o=this.config.rotation;if(typeof o==="boolean")return;if(o.maxSize&&i.size>=o.maxSize){let c=this.currentLogFile,f=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let u=await mt(this.config.logDirectory),g=u.filter((y)=>y.startsWith(this.name)&&/\.log\.\d+$/.test(y)).sort((y,b)=>{let S=Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(b.match(/\.log\.(\d+)$/)?.[1]||"0")-S}),h=g.length>0?Number.parseInt(g[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,d=`${c}.${h}`;if(await De(c).catch(()=>null))try{if(await Dn(c,d),o.compress)try{let y=`${d}.gz`;await this.compressLogFile(d,y),await pt(d)}catch(y){console.error("Error compressing rotated file:",y)}if(g.length===0&&!u.some((y)=>y.endsWith(".log.1")))try{let y=`${c}.1`;await cr(y,"")}catch(y){console.error("Error creating backup file:",y)}}catch(y){console.error(`Error during rotation: ${y instanceof Error?y.message:String(y)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=c.replace(/\.log$/,`-${u}.log`);if(await De(c).catch(()=>null))await Dn(c,g)}if(this.currentLogFile=f,o.maxFiles){let g=(await mt(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,d)=>d.localeCompare(h));for(let h of g.slice(o.maxFiles))await pt(Ne(this.config.logDirectory,h))}}}async compressLogFile(i,o){let c=Rn(i),f=Bi(o),u=Nn();await Ui(c,u,f)}async handleFingersCrossedBuffer(i,o){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let c of this.logBuffer){let f=await this.formatter.format(c);if(this.shouldWriteToFile())await this.writeToFile(f);console.log(f)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(o);console.log(o)}}shouldLog(i){if(!this.enabled)return!1;let o={debug:0,info:1,success:2,warning:3,error:4};return o[i]>=o[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((o)=>{console.error("Error in pending write operation:",o)});return Promise.resolve()})),dt(this.currentLogFile))try{let i=On(this.currentLogFile,"r+");Ln(i),ar(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(!H()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let o=(await mt(this.config.logDirectory)).filter((c)=>(c.includes("temp")||c.includes(".tmp"))&&c.includes(this.name));for(let c of o)try{await pt(Ne(this.config.logDirectory,c))}catch(f){console.error(`Failed to delete temp file ${c}:`,f)}}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()?D.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H())return!1;let i=typeof F.env.NO_COLOR<"u",o=F.env.FORCE_COLOR==="0";if(i||o)return!1;return!!(typeof F.stderr<"u"&&F.stderr.isTTY||typeof F.stdout<"u"&&F.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:o,icon:c="",tag:f="",message:u,level:g,showTimestamp:h=!0}=i,d=(E)=>E.replace(this.ANSI_PATTERN,"");if(!this.fancy){let E=[];if(h)E.push(o);if(g==="warning")E.push("WARN");else if(g==="error")E.push("ERROR");else if(c)E.push(c.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(f)E.push(f.replace(/[[\]]/g,""));return E.push(u),E.join(" ")}let y=F.stdout.columns||120,b="";if(g==="warning"||g==="error")b=`${c} ${u}`;else if(g==="info"||g==="success")b=`${c} ${f} ${u}`;else b=`${c} ${f} ${D.cyan(u)}`;if(!h)return b.trim();let S=d(b).trim().length,v=d(o).length,C=Math.max(1,y-2-S-v);return`${b.trim()}${" ".repeat(C)}${o}`}formatMessage(i,o){if(o.length===1&&Array.isArray(o[0]))return i.replace(/\{(\d+)\}/g,(g,h)=>{let d=Number.parseInt(h,10);return d<o[0].length?String(o[0][d]):g});let c=/%([sdijfo%])/g,f=0,u=i.replace(c,(g,h)=>{if(h==="%")return"%";if(f>=o.length)return g;let d=o[f++];switch(h){case"s":return String(d);case"d":case"i":return Number(d).toString();case"j":case"o":return JSON.stringify(d,null,2);default:return g}});if(f<o.length)u+=` ${o.slice(f).map((g)=>typeof g==="object"?JSON.stringify(g,null,2):String(g)).join(" ")}`;return u}formatMarkdown(i){if(!i)return i;let o=i;return o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(c,f,u)=>{let g=D.underline(D.blue(f)),h=this.toAbsoluteFilePath(u);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let d=`file://${encodeURI(h)}`,y="\x1B]8;;",b="\x1B\\";return`\x1B]8;;${d}\x1B\\${g}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${u}\x1B\\${g}\x1B]8;;\x1B\\`;return g}),o=o.replace(/`([^`]+)`/g,(c,f)=>D.bgGray(f)),o=o.replace(/\*\*([^*]+)\*\*/g,(c,f)=>D.bold(f)),o=o.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(c,f)=>D.italic(f)),o=o.replace(/(?<!_)_([^_]+)_(?!_)/g,(c,f)=>D.italic(f)),o=o.replace(/~([^~]+)~/g,(c,f)=>D.strikethrough(f)),o}supportsHyperlinks(){if(H())return!1;let i=F.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 o=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(o)&&o>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let o=i;if(o.startsWith("file://"))o=o.replace(/^file:\/\//,"");if(o.startsWith("~")){let c=F.env.HOME||"";if(c)o=o.replace(/^~(?=$|\/)/,c)}if(Wi(o)||o.startsWith("./")||o.startsWith("../"))o=Qi(o);else return null;return dt(o)?o:null}catch{return null}}buildOutputTexts(i){let o=this.shouldStyleConsole()?this.formatMarkdown(i):i,c=i.replace(this.ANSI_PATTERN,"");return{consoleText:o,fileText:c}}async log(i,o,...c){if(!this.shouldLog(i))return;let f=new Date,u=this.formatConsoleTimestamp(f),g=this.formatFileTimestamp(f),h,d;if(o instanceof Error)h=o.message,d=o.stack;else h=this.formatMessage(o,c);let{consoleText:y,fileText:b}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let v=this.options.showIcons===!1?"":ia[i],C=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",E;switch(i){case"debug":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:D.gray(y),level:i}),console.error(E);break;case"info":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.warn(E);break;case"success":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:D.green(y),level:i}),console.error(E);break;case"warning":E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.warn(E);break;case"error":if(E=this.formatConsoleMessage({timestamp:u,icon:v,tag:C,message:y,level:i}),console.error(E),d){let A=d.split(`
41
+ `);for(let k of A)if(k.trim()&&!k.includes(h))console.error(this.formatConsoleMessage({timestamp:u,message:D.gray(` ${k}`),level:i,showTimestamp:!1}))}break}}else if(!H()){if(console.error(`${g} ${this.environment}.${i.toUpperCase()}: ${h}`),d)console.error(d)}let S=`${g} ${this.environment}.${i.toUpperCase()}: ${b}
42
+ `;if(d)S+=`${d}
43
+ `;if(S=S.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(S)}progress(i,o=""){let c={update:(d,y)=>{},finish:(d)=>{},interrupt:(d,y)=>{}};if(!this.enabled)return c;let f=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:o||"",barLength:f,lastRenderedLine:""},this.shouldStyleConsole()&&!H()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(d,y)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,d),this.activeProgressBar.total),y!==void 0)this.activeProgressBar.message=y;if(this.shouldStyleConsole()&&!H()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(d)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,d)},interrupt:(d,y="info")=>{if(!H()&&F.stdout.isTTY)F.stdout.write(`
44
+ `);if(this[y==="warning"?"warn":y](d),this.activeProgressBar&&this.shouldStyleConsole()&&!H()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let o=performance.now();if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",f=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:f,icon:this.options.showIcons===!1?"":D.blue("\u25D0"),tag:c,message:`${D.cyan(i)}...`}))}return async(c)=>{if(!this.enabled)return;let f=performance.now(),u=Math.round(f-o),g=`${i} completed in ${u}ms`,h=new Date,d=this.formatConsoleTimestamp(h),b=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${g}`;if(c)b+=` ${JSON.stringify(c)}`;if(b+=`
45
+ `,b=b.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let S=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:d,icon:this.options.showIcons===!1?"":D.green("\u2713"),tag:S,message:`${g}${c?` ${JSON.stringify(c)}`:""}`}))}else if(!H())console.error(b.trim());if(this.shouldWriteToFile())await this.writeToFile(b)}}async debug(i,...o){await this.log("debug",i,...o)}async info(i,...o){await this.log("info",i,...o)}async success(i,...o){await this.log("success",i,...o)}async warn(i,...o){await this.log("warning",i,...o)}async error(i,...o){await this.log("error",i,...o)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:o}=i;return!!o}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let o=`${this.name}:${i}`,c=new Kt(o,{...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(H())throw Error("createReadStream is not supported in browser environments");if(!dt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Rn(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let o=this.config.rotation;if(!o.encrypt||typeof o.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 f=he.isBuffer(i)?i:he.from(i,"base64"),u=f.subarray(0,16),g=f.subarray(f.length-16),h=f.subarray(16,f.length-16),d=Mi("aes-256-gcm",c,u);d.setAuthTag(g);let y=d.update(h),b=d.final(),S=y.length+b.length,v=he.allocUnsafe(S);return y.copy(v,0),b.copy(v,y.length),v.toString("utf8")}catch(f){throw Error(`Decryption failed: ${f instanceof Error?f.message:String(f)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return H()}isServerMode(){return!H()}setTestEncryptionKey(i,o){this.currentKeyId=i,this.keys.set(i,o)}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 o=new Date,c=this.formatConsoleTimestamp(o),f=this.formatFileTimestamp(o),{consoleText:u,fileText:g}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let d=u.split(`
46
+ `),y=Math.max(...d.map((C)=>C.length))+2,b=`\u250C${"\u2500".repeat(y)}\u2510`,S=`\u2514${"\u2500".repeat(y)}\u2518`,v=d.map((C)=>this.formatConsoleMessage({timestamp:c,message:D.cyan(C),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:c,message:D.cyan(b),showTimestamp:!1})),v.forEach((C)=>console.error(C)),console.error(this.formatConsoleMessage({timestamp:c,message:D.cyan(S),showTimestamp:!1}))}else if(!H())console.error(`${f} ${this.environment}.INFO: [BOX] ${g}`);let h=`${f} ${this.environment}.INFO: [BOX] ${g}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}async prompt(i){if(H())return Promise.resolve(!0);return new Promise((o)=>{console.error(`${D.cyan("?")} ${i} (y/n) `);let c=(f)=>{let u=f.toString().trim().toLowerCase();F.stdin.removeListener("data",c);try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!1)}catch{}F.stdin.pause(),console.error(""),o(u==="y"||u==="yes")};try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!0)}catch{}F.stdin.resume(),F.stdin.once("data",c)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...o){if(!this.enabled)return;let c=i;if(o&&o.length>0){let y=/%([sdijfo%])/g,b=0;if(c=i.replace(y,(S,v)=>{if(v==="%")return"%";if(b>=o.length)return S;let C=o[b++];switch(v){case"s":return String(C);case"d":case"i":return Number(C).toString();case"j":case"o":return JSON.stringify(C,null,2);default:return S}}),b<o.length)c+=` ${o.slice(b).map((S)=>typeof S==="object"?JSON.stringify(S,null,2):String(S)).join(" ")}`}let{consoleText:f,fileText:u}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",b=this.options.showIcons===!1?"":`${D.blue("\u25D0")} `;console.error(`${b}${y} ${D.cyan(f)}`)}let d=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${u}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(d)}renderProgressBar(i,o=!1){if(!this.enabled||!this.shouldStyleConsole()||!F.stdout.isTTY)return;let c=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),f=Math.round(i.barLength*c/100),u=i.barLength-f,g=D.green("\u2501".repeat(f)),h=D.gray("\u2501".repeat(u)),d=`[${g}${h}]`,y=`${c}%`.padStart(4),b=i.message?` ${i.message}`:"",S=this.options.showIcons===!1?"":o||c===100?D.green("\u2713"):D.blue("\u25B6"),v=this.options.showTags!==!1&&this.name?` ${D.gray(this.formatTag(this.name))}`:"",C=`\r${S}${v} ${d} ${y}${b}`,E=F.stdout.columns||80,A=" ".repeat(Math.max(0,E-C.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${C}${A}`,F.stdout.write(i.lastRenderedLine),o)F.stdout.write(`
49
+ `)}finishProgressBar(i,o){if(!this.enabled||!this.fancy||H()||!F.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(o)i.message=o;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(H()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let o=await mt(this.config.logDirectory),c=[];for(let f of o){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(f):f.startsWith(this.name))||!f.endsWith(".log"))continue;let g=Ne(this.config.logDirectory,f);if(i.before)try{if((await De(g)).mtime>=i.before)continue}catch(h){console.error(`Failed to get stats for file ${g}:`,h);continue}c.push(g)}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 f of c)try{await pt(f),console.warn(`Deleted log file: ${f}`)}catch(u){console.error(`Failed to delete log file ${f}:`,u)}console.warn("Log clearing process finished.")}catch(o){console.error("Error during log clearing process:",o)}}}var Cl=new Kt("stacks");class ce extends Error{timestamp;context;constructor(i,o={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=o,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(([o,c])=>`${o}: ${c}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class _e extends ce{name="ConfigNotFoundError";code="CONFIG_NOT_FOUND";constructor(i,o,c){let f=c===void 0?[]:Array.isArray(c)?c.filter(Boolean):[c],u="";if(f.length===1)u=` or alias "${f[0]}"`;else if(f.length>1)u=` or aliases ${f.map((g)=>`"${g}"`).join(", ")}`;super(`Configuration "${i}"${u} not found`,{configName:i,alias:c,searchPaths:o,searchPathCount:o.length})}}class ve extends ce{name="ConfigLoadError";code="CONFIG_LOAD_ERROR";constructor(i,o,c){super(`Failed to load configuration from "${i}": ${o.message}`,{configPath:i,configName:c,originalError:o.name,originalMessage:o.message});this.cause=o}}class _r extends ce{name="ConfigValidationError";code="CONFIG_VALIDATION_ERROR";constructor(i,o,c){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:c,validationErrors:o,errorCount:o.length})}}class Es extends ce{name="ConfigMergeError";code="CONFIG_MERGE_ERROR";constructor(i,o,c,f){super(`Failed to merge configuration from "${i}" with "${o}": ${c.message}`,{sourcePath:i,targetPath:o,configName:f,originalError:c.name,originalMessage:c.message});this.cause=c}}class Mr extends ce{name="EnvVarError";code="ENV_VAR_ERROR";constructor(i,o,c,f){super(`Failed to parse environment variable "${i}" with value "${o}" as ${c}`,{envKey:i,envValue:o,expectedType:c,configName:f})}}class $s extends ce{name="FileSystemError";code="FILE_SYSTEM_ERROR";constructor(i,o,c){super(`File system ${i} failed for "${o}": ${c.message}`,{operation:i,path:o,originalError:c.name,originalMessage:c.message});this.cause=c}}class Cs extends ce{name="TypeGenerationError";code="TYPE_GENERATION_ERROR";constructor(i,o,c){super(`Failed to generate types from "${i}" to "${o}": ${c.message}`,{configDir:i,outputPath:o,originalError:c.name,originalMessage:c.message});this.cause=c}}class _t extends ce{name="SchemaValidationError";code="SCHEMA_VALIDATION_ERROR";constructor(i,o,c){super(`Schema validation failed${c?` for config "${c}"`:""}`,{schemaPath:i,configName:c,validationErrors:o,errorCount:o.length})}}class xs extends ce{name="BrowserConfigError";code="BROWSER_CONFIG_ERROR";constructor(i,o,c,f){super(`Failed to fetch configuration from "${i}": ${o} ${c}`,{endpoint:i,status:o,statusText:c,configName:f})}}class Ts extends ce{name="PluginError";code="PLUGIN_ERROR";constructor(i,o,c){super(`Plugin "${i}" failed during ${o}: ${c.message}`,{pluginName:i,operation:o,originalError:c.name,originalMessage:c.message});this.cause=c}}var be={configNotFound(i,o,c){return new _e(i,o,c)},configLoad(i,o,c){return new ve(i,o,c)},configValidation(i,o,c){return new _r(i,o,c)},configMerge(i,o,c,f){return new Es(i,o,c,f)},envVar(i,o,c,f){return new Mr(i,o,c,f)},fileSystem(i,o,c){return new $s(i,o,c)},typeGeneration(i,o,c){return new Cs(i,o,c)},schemaValidation(i,o,c){return new _t(i,o,c)},browserConfig(i,o,c,f){return new xs(i,o,c,f)},plugin(i,o,c){return new Ts(i,o,c)}};async function oa(i,o={}){let{maxRetries:c=3,retryDelay:f=1000,isRetryable:u=()=>!0,fallback:g}=o,h=Error("Unknown error occurred");for(let d=0;d<=c;d++)try{return await i()}catch(y){if(h=y instanceof Error?y:Error(String(y)),d===c||!u(h))break;if(f>0)await new Promise((b)=>setTimeout(b,f))}if(g!==void 0)return g;throw h instanceof Error?h:Error(`Unknown error: ${String(h)}`)}class Br{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,o)=>o==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let o=i.toLowerCase();return["true","1","yes"].includes(o)}},{name:"number",canParse:(i,o)=>o==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let o=Number(i);if(Number.isNaN(o))throw TypeError(`Cannot parse "${i}" as number`);return o}},{name:"array",canParse:(i,o)=>o==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let o=JSON.parse(i);if(Array.isArray(o))return o}catch{}return i.split(",").map((o)=>o.trim())}},{name:"json",canParse:(i,o)=>o==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(o){throw Error(`Cannot parse "${i}" as JSON: ${o}`)}}}]}async applyEnvironmentVariables(i,o,c={}){let{prefix:f,useCamelCase:u=!0,useBackwardCompatibility:g=!0,customParsers:h={},verbose:d=!1,trackPerformance:y=!0}=c,b=async()=>{if(!i)return{config:o,source:{type:"environment",priority:50,timestamp:new Date}};let S=f||this.generateEnvPrefix(i),v={...o};return this.processObject(v,[],S,{useCamelCase:u,useBackwardCompatibility:g,customParsers:h,verbose:d,configName:i}),{config:v,source:{type:"environment",priority:50,timestamp:new Date}}};if(y)return Rr.track("applyEnvironmentVariables",b,{configName:i});return b()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,o){if(!o)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=h.map((S)=>this.formatEnvKey(S,f.useCamelCase)),y=`${c}_${d.join("_")}`,b=f.useBackwardCompatibility?`${c}_${h.map((S)=>S.toUpperCase()).join("_")}`:null;if(f.verbose);if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.processObject(g,h,c,f);else{let S=wt.env[y]||(b?wt.env[b]:void 0);if(S!==void 0){if(f.verbose){let v=wt.env[y]?y:b}try{i[u]=this.parseEnvironmentValue(S,typeof g,y,f.customParsers,f.configName)}catch(v){if(v instanceof Mr)throw v;throw be.envVar(y,S,typeof g,f.configName)}}}}}parseEnvironmentValue(i,o,c,f,u){for(let[g,h]of Object.entries(f))try{return h(i)}catch{continue}for(let g of this.defaultParsers)if(g.canParse(i,o))try{return g.parse(i)}catch{throw be.envVar(c,i,`${o} (via ${g.name} parser)`,u)}return i}getEnvironmentVariables(i){let o={},c=i.toUpperCase();for(let[f,u]of Object.entries(wt.env))if(f.startsWith(c)&&u!==void 0)o[f]=u;return o}validateEnvironmentVariable(i,o,c){let f=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))f.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(c)try{this.parseEnvironmentValue(i,o,c,{})}catch(u){f.push(`Cannot parse value "${o}" as ${c}: ${u}`)}return{isValid:f.length===0,errors:f}}generateEnvVarDocs(i,o,c={}){let{prefix:f,format:u="text"}=c,g=f||this.generateEnvPrefix(i),h=[];switch(this.extractEnvVarInfo(o,[],g,h),u){case"markdown":return this.formatAsMarkdown(h,i);case"json":return JSON.stringify(h,null,2);default:return this.formatAsText(h,i)}}extractEnvVarInfo(i,o,c,f){for(let[u,g]of Object.entries(i)){let h=[...o,u],d=`${c}_${h.map((y)=>this.formatEnvKey(y,!0)).join("_")}`;if(typeof g==="object"&&g!==null&&!Array.isArray(g))this.extractEnvVarInfo(g,h,c,f);else f.push({key:d,type:Array.isArray(g)?"array":typeof g,description:`Configuration for ${h.join(".")}`,example:this.generateExample(g)})}}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,o){let c=`Environment Variables for ${o}:
50
+
51
+ `;for(let f of i)c+=`${f.key}
52
+ `,c+=` Type: ${f.type}
53
+ `,c+=` Description: ${f.description}
54
+ `,c+=` Example: ${f.example}
55
+
56
+ `;return c}formatAsMarkdown(i,o){let c=`# Environment Variables for ${o}
57
+
58
+ `;c+=`| Variable | Type | Description | Example |
59
+ `,c+=`|----------|------|-------------|----------|
60
+ `;for(let f of i)c+=`| \`${f.key}\` | ${f.type} | ${f.description} | \`${f.example}\` |
61
+ `;return c}}var Gn=la(import.meta.url),bt=new Map,dr=new Set;function ks(i){return i instanceof Error&&"code"in i&&(i.code==="ENOENT"||i.code==="ENOTDIR")}async function As(i){let o=ca(i),c=bt.get(o),f,u=new Promise((g)=>{f=g});bt.set(o,u),await c;try{if(aa(o),Gn.cache[o]?.loaded===!0||dr.has(o))delete Gn.cache[o];try{let g=await import(fa(o).href);return dr.delete(o),g}catch(g){throw dr.add(o),g}}finally{if(f(),bt.get(o)===u)bt.delete(o)}}function ha(i,o,c={}){return Rs(i,o,c,new WeakMap)}function Rs(i,o,c,f){let{arrayMergeMode:u="replace",skipNullish:g=!1,customMerger:h}=c;if(o===null||o===void 0)return g?i:o;if(h){let d=h(i,o);if(d!==void 0)return d}if(Array.isArray(o)||Array.isArray(i))return Ls(i,o,u,f);if(!se(o)||!se(i))return o;return pa(i,o,c,f)}function Ls(i,o,c,f){if(Array.isArray(o)&&!Array.isArray(i))return o;if(Array.isArray(i)&&!Array.isArray(o))return o;if(Array.isArray(o)&&Array.isArray(i))switch(c){case"replace":return o;case"concat":return ga(i,o);case"smart":return da(i,o,f);default:return o}return o}function ga(i,o){let c=[...o];for(let f of i)if(!c.some((u)=>Ar(u,f)))c.push(f);return c}function da(i,o,c){if(o.length===0)return i;if(i.length===0)return o;if(se(o[0])&&se(i[0]))return ma(i,o,c);if(o.every((f)=>typeof f==="string")&&i.every((f)=>typeof f==="string")){let f=[...o];for(let u of i)if(!f.includes(u))f.push(u);return f}return o}function ma(i,o,c){let f=[...o];for(let u of i){if(!se(u)){f.push(u);continue}let g=["id","name","key","path","type"],h=!1;for(let d of g)if(d in u){if(f.find((b)=>se(b)&&(d in b)&&b[d]===u[d])){h=!0;break}}if(!h)f.push(u)}return f}function pa(i,o,c,f){let u=o;if(se(u)&&f.has(u))return f.get(u);let g={...i};if(se(u))f.set(u,g);for(let h in u){if(!Object.prototype.hasOwnProperty.call(u,h))continue;let d=u[h],y=g[h];if(c.skipNullish&&(d===null||d===void 0))continue;if(d===null||d===void 0){g[h]=d;continue}if(se(d)&&se(y))g[h]=Rs(y,d,c,f);else if(Array.isArray(d)||Array.isArray(y))g[h]=Ls(y,d,c.arrayMergeMode||"smart",f);else g[h]=d}return g}function Os(i,o,c="replace"){return ha(i,o,{arrayMergeMode:c==="replace"?"replace":"smart",skipNullish:!0})}function Ar(i,o){if(i===o)return!0;if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length)return!1;for(let c=0;c<i.length;c++)if(!Ar(i[c],o[c]))return!1;return!0}if(se(i)&&se(o)){let c=Object.keys(i),f=Object.keys(o);if(c.length!==f.length)return!1;for(let u of c){if(!Object.prototype.hasOwnProperty.call(o,u))return!1;if(!Ar(i[u],o[u]))return!1}return!0}return!1}function se(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Ps{extensions=Xn;async loadFromPath(i,o,c={}){let{arrayStrategy:f="replace",useCache:u=!0,cacheTtl:g,trackPerformance:h=!0,verbose:d=!1,strictDiscovery:y=!1}=c;if(u){let S=xt.getWithFileCheck("file",i);if(S){if(d)console.log(`Configuration loaded from cache: ${i}`);return S}}let b=async()=>{try{try{ua(i)}catch(V){if(ks(V)||!y)return null;throw V}let S=await As(i),v=Object.hasOwn(S,"default"),C=Object.keys(S).length>0,E=v?S.default:S;if(!v&&!C)throw new ve(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof E!=="object"||E===null||Array.isArray(E))throw new ve(i,Error("Configuration must export a valid object"),"unknown");let O={config:Os(o,E,f),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(u)xt.setWithFileCheck("file",O,i,g);return O}catch(S){throw S instanceof Error?be.configLoad(i,S):be.configLoad(i,Error(String(S)))}};if(h)return Rr.track("loadFromPath",b,{path:i});return b()}async tryLoadFromPaths(i,o,c={}){for(let f of i)try{let u=await this.loadFromPath(f,o,c);if(u)return u}catch(u){if(u instanceof ve)throw u;if(c.verbose)console.warn(`Failed to load config from ${f}:`,u)}return null}generateConfigPaths(i,o,c){return ii({name:i,directory:o,alias:c})}generateNamePatterns(i,o){return es({name:i,alias:o})}checkFileAccess(i){return oa(async()=>mr(i),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,o,c){let f=[];if(!mr(i))return f;if(o||c){let u=this.generateNamePatterns(o||"",c);for(let g of u)for(let h of this.extensions){let d=Yn(i,`${g}${h}`);if(await this.checkFileAccess(d))f.push(d)}}else try{let{readdirSync:u}=await import("fs"),g=u(i);for(let h of g)if(this.looksLikeConfigFile(h)){let d=Yn(i,h);if(await this.checkFileAccess(d))f.push(d)}}catch{return[]}return f}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 o=[];try{if(!mr(i))return o.push("Configuration file does not exist"),o;let c=await import(i),f=c.default||c;if(f===void 0)o.push("Configuration file must export a default value or named exports");else if(typeof f!=="object"||f===null)o.push("Configuration must be an object");else if(Array.isArray(f))o.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:u}=await import("fs"),g=u(i,"utf8");JSON.parse(g)}catch(u){o.push(`Invalid JSON syntax: ${u}`)}}catch(c){o.push(`Failed to load configuration file: ${c}`)}return o}async getFileModificationTime(i){try{let{statSync:o}=await import("fs");return o(i).mtime}catch{return null}}async preloadConfigurations(i,o={}){let c=new Map;return await Promise.allSettled(i.map(async(f)=>{try{let u=await this.loadFromPath(f,{},o);if(u)c.set(f,u.config)}catch(u){if(o.verbose)console.warn(`Failed to preload ${f}:`,u)}})),c}}var wa=/^https?:\/\//;class Ds{async validateConfiguration(i,o,c={}){let{stopOnFirstError:f=!1,validateRequired:u=!0,validateTypes:g=!0,customRules:h=[],trackPerformance:d=!0,verbose:y=!1}=c,b=async()=>{let S=[],v=[],C={stopOnFirstError:f,validateRequired:u,validateTypes:g,customRules:h,trackPerformance:d,verbose:y};try{if(typeof o==="string")return await this.validateWithSchemaFile(i,o,C);else if(Array.isArray(o))return this.validateWithRules(i,[...o,...h],C);else return this.validateWithJSONSchema(i,o,C)}catch(E){return S.push({path:"",message:`Validation failed: ${E}`,rule:"system"}),{isValid:!1,errors:S,warnings:v}}};if(d)return await Rr.track("validateConfiguration",b);return b()}async validateWithSchemaFile(i,o,c){try{if(!ya(o))throw new _t(o,[{path:"",message:"Schema file does not exist"}]);let f=await As(o),u=Object.hasOwn(f,"default")?f.default:f;if(Array.isArray(u))return this.validateWithRules(i,u,c);else{if(typeof u!=="object"||u===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(i,u,c)}}catch(f){throw new _t(o,[{path:"",message:`Failed to load schema: ${f}`}])}}validateWithJSONSchema(i,o,c){let f=[],u=[];return this.validateObjectAgainstSchema(i,o,"",f,u,c),{isValid:f.length===0,errors:f,warnings:u}}validateObjectAgainstSchema(i,o,c,f,u,g){if(g.validateTypes&&o.type){let h=Array.isArray(i)?"array":typeof i,d=Array.isArray(o.type)?o.type:[o.type];if(!d.includes(h)){if(f.push({path:c,message:`Expected type ${d.join(" or ")}, got ${h}`,expected:d.join(" or "),actual:h,rule:"type"}),g.stopOnFirstError)return}}if(o.enum&&!o.enum.includes(i)){if(f.push({path:c,message:`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"}),g.stopOnFirstError)return}if(typeof i==="string"){if(o.minLength!==void 0&&i.length<o.minLength)f.push({path:c,message:`String length must be at least ${o.minLength}`,expected:`>= ${o.minLength}`,actual:i.length,rule:"minLength"});if(o.maxLength!==void 0&&i.length>o.maxLength)f.push({path:c,message:`String length must not exceed ${o.maxLength}`,expected:`<= ${o.maxLength}`,actual:i.length,rule:"maxLength"});if(o.pattern){if(!new RegExp(o.pattern).test(i))f.push({path:c,message:`String does not match pattern ${o.pattern}`,expected:o.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(o.minimum!==void 0&&i<o.minimum)f.push({path:c,message:`Value must be at least ${o.minimum}`,expected:`>= ${o.minimum}`,actual:i,rule:"minimum"});if(o.maximum!==void 0&&i>o.maximum)f.push({path:c,message:`Value must not exceed ${o.maximum}`,expected:`<= ${o.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&o.items)for(let h=0;h<i.length;h++){let d=c?`${c}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema(i[h],o.items,d,f,u,g),g.stopOnFirstError&&f.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let h=i;if(g.validateRequired&&o.required){for(let d of o.required)if(!(d in h)){if(f.push({path:c?`${c}.${d}`:d,message:`Missing required property '${d}'`,expected:"required",rule:"required"}),g.stopOnFirstError)return}}if(o.properties){for(let[d,y]of Object.entries(o.properties))if(d in h){let b=c?`${c}.${d}`:d;if(this.validateObjectAgainstSchema(h[d],y,b,f,u,g),g.stopOnFirstError&&f.length>0)return}}if(o.additionalProperties===!1){let d=new Set(Object.keys(o.properties||{}));for(let y of Object.keys(h))if(!d.has(y))u.push({path:c?`${c}.${y}`:y,message:`Additional property '${y}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,o,c){let f=[],u=[];for(let g of o)try{let h=this.getValueByPath(i,g.path),d=this.validateWithRule(h,g,g.path);if(f.push(...d),c.stopOnFirstError&&f.length>0)break}catch(h){f.push({path:g.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:f.length===0,errors:f,warnings:u}}validateWithRule(i,o,c){let f=[];if(o.required&&(i===void 0||i===null))return f.push({path:c,message:o.message||`Property '${c}' is required`,expected:"required",rule:"required"}),f;if(i===void 0||i===null)return f;if(o.type){let u=Array.isArray(i)?"array":typeof i;if(u!==o.type)f.push({path:c,message:o.message||`Expected type ${o.type}, got ${u}`,expected:o.type,actual:u,rule:"type"})}if(o.min!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u<o.min)f.push({path:c,message:o.message||`Value must be at least ${o.min}`,expected:`>= ${o.min}`,actual:u,rule:"min"})}if(o.max!==void 0){let u=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(u>o.max)f.push({path:c,message:o.message||`Value must not exceed ${o.max}`,expected:`<= ${o.max}`,actual:u,rule:"max"})}if(o.pattern&&typeof i==="string"){if(!o.pattern.test(i))f.push({path:c,message:o.message||`Value does not match pattern ${o.pattern}`,expected:o.pattern.toString(),actual:i,rule:"pattern"})}if(o.enum&&!o.enum.includes(i))f.push({path:c,message:o.message||`Value must be one of: ${o.enum.join(", ")}`,expected:o.enum.join(", "),actual:i,rule:"enum"});if(o.validator){let u=o.validator(i);if(u)f.push({path:c,message:o.message||u,rule:"custom"})}return f}getValueByPath(i,o){if(!o)return i;let c=o.split("."),f=i;for(let u of c)if(f&&typeof f==="object"&&u in f)f=f[u];else return;return f}generateRulesFromInterface(i){let o=[],c=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let f of c){let[,u,g,h]=f;o.push({path:u,required:!g,type:this.mapTypeScriptType(h)})}return o}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:wa},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var le=new Kt("bunfig",{showTags:!0});function ba(i){if(!i)return"";let o=Array.isArray(i)?i.filter(Boolean):[i];if(o.length===0)return"";if(o.length===1)return` or alias "${o[0]}"`;return` or aliases ${o.map((c)=>`"${c}"`).join(", ")}`}class Ns{fileLoader=new Ps;envProcessor=new Br;validator=new Ds;async loadConfig(i){let o=Date.now(),{cache:c,performance:f,schema:u,validate:g,...h}=i,d=h.errorPolicy==="throw"?{...c,enabled:!1}:c;try{if(d?.enabled){let b=this.checkCache(h.name||"",h);if(b)return b}let y;try{y=await this.loadConfigurationStrategies(h,!0,d)}catch(b){if(h.configFile||h.errorPolicy==="throw"&&!(b instanceof _e))throw b;let S=h.__strictErrorHandling;if(b instanceof _e){if(S&&h.errorPolicy!=="throw")throw b;y={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(b instanceof ve){let v=b.message.includes("EACCES")||b.message.includes("EPERM")||b.message.includes("permission denied"),C=!v&&(b.message.includes("syntax")||b.message.includes("Expected")||b.message.includes("Unexpected")||b.message.includes("BuildMessage")||b.message.includes("errors building")),E=b.message.includes("Configuration must export a valid object")||b.message.includes("Configuration file is empty and exports nothing");if(S&&(E||v))throw b;if(C&&(!S||!E))y={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!S)y={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${b.message}`]};else throw b}else y={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${b instanceof Error?b.message:String(b)}`]}}if(u||g)await this.validateConfiguration(y.config,u,g,h.name);if(d?.enabled&&y)this.cacheResult(h.name||"",y,d,h);if(f?.enabled){let b={operation:"loadConfig",duration:Date.now()-o,configName:h.name,timestamp:new Date};if(f.onMetrics)f.onMetrics(b);if(f.slowThreshold&&b.duration>f.slowThreshold)le.warn(`Slow configuration loading detected: ${b.duration}ms for ${h.name}`);y.metrics=b}return y}catch(y){if(y instanceof _e)throw y;let b=Date.now()-o;throw le.error(`Configuration loading failed after ${b}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,o=!1,c){let{name:f="",alias:u,configFile:g,cwd:h,configDir:d,defaultConfig:y,checkEnv:b=!0,arrayStrategy:S="replace",verbose:v=!1}=i,C=h||Mt.cwd(),E=[];if(g){let Q=fe(C,g);E.push(Q);let ie=b?Ve(f,y,v):y,ee=await this.fileLoader.tryLoadFromPaths([Q],ie,{arrayStrategy:S,verbose:v,cacheTtl:c?.ttl,useCache:c?.enabled!==!1&&(!c?.ttl||c.ttl>100),strictDiscovery:!0});if(!ee)throw be.configNotFound(f||g,E,u);if(v)le.success(`Configuration loaded from explicit path: ${Q}`);return this.finalizeResult(ee,E,b,f,v)}let A=await this.loadLocalConfiguration(f,u,C,d,y,S,v,b,c,i.errorPolicy==="throw");if(A)return E.push(...this.getLocalSearchPaths(f,u,C,d)),this.finalizeResult(A,E,b,f,v);let k=await this.loadHomeConfiguration(f,u,y,S,v,b,c,i.errorPolicy==="throw");if(k)return E.push(...this.getHomeSearchPaths(f,u)),this.finalizeResult(k,E,b,f,v);let O=await this.loadPackageJsonConfiguration(f,u,C,y,S,v,b,i.errorPolicy);if(O)return E.push(fe(C,"package.json")),this.finalizeResult(O,E,b,f,v);if(E.push(...this.getAllSearchPaths(f,u,C,d)),o)throw be.configNotFound(f,E,u);return{...await this.applyEnvironmentVariables(f,y,b,v),warnings:[`No configuration file found for "${f}"${ba(u)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,o,c,f,u,g,h,d,y,b=!1){let S=d?Ve(i,u,h):u,v=this.getLocalDirectories(c,f);for(let C of v){if(h)le.info(`Searching for configuration in: ${C}`);let E=this.fileLoader.generateConfigPaths(i,C,o),A=await this.fileLoader.tryLoadFromPaths(E,S,{arrayStrategy:g,verbose:h,cacheTtl:y?.ttl,useCache:y?.enabled!==!1&&(!y?.ttl||y.ttl>100),strictDiscovery:b});if(A){if(h)le.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,o,c,f,u,g,h,d=!1){if(!i)return null;let y=g?Ve(i,c,u):c,b=[fe(Ce(),".config",i),fe(Ce(),".config"),Ce()];for(let S of b){if(u)le.info(`Checking home directory: ${S}`);let v=this.fileLoader.generateConfigPaths(i,S,o),C=await this.fileLoader.tryLoadFromPaths(v,y,{arrayStrategy:f,verbose:u,cacheTtl:h?.ttl,useCache:h?.enabled!==!1&&(!h?.ttl||h.ttl>100),strictDiscovery:d});if(C){if(u)le.success(`Configuration loaded from home directory: ${C.source.path}`);return C}}return null}async loadPackageJsonConfiguration(i,o,c,f,u,g,h,d){let y=h?Ve(i,f,g):f,b=fe(c,"package.json"),S=d==="throw";try{let v=JSON.parse(ai(b,"utf8"));if(typeof v!=="object"||v===null||Array.isArray(v))throw Error("package.json must contain an object");let C=v,E=o===void 0?[]:Array.isArray(o)?o:[o],k=[i,...E.filter(Boolean)].find((V)=>Object.hasOwn(C,V)&&(S||Boolean(C[V])));if(k===void 0)return null;let O=C[k];if(typeof O!=="object"||O===null||Array.isArray(O))throw Error(`Configuration field "${k}" must contain an object`);if(g)le.success(`Configuration loaded from package.json: ${k}`);return{config:Os(y,O,u),source:{type:"package.json",path:b,priority:30,timestamp:new Date}}}catch(v){if(ks(v))return null;if(S)throw be.configLoad(b,v instanceof Error?v:Error(String(v)));if(g)le.warn("Failed to load package.json:",[v instanceof Error?v:Error(String(v))]);return null}}async applyEnvironmentVariables(i,o,c,f){if(!c||!i||typeof o!=="object"||o===null||Array.isArray(o))return{config:o,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ve(i,o,f),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,o,c,f,u){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,o,c,f){let u=[];if(c){let g=c(i);if(g)u.push(...g)}if(o){let g=await this.validator.validateConfiguration(i,o);if(!g.isValid)u.push(...g.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(u.length>0)throw be.configValidation(f||"unknown",u,f)}checkCache(i,o){let c=this.generateCacheKey(i,o);return xt.get(c)||null}cacheResult(i,o,c,f){let u=this.generateCacheKey(i,f);xt.set(u,o,void 0,c.ttl)}generateCacheKey(i,o){let c=[i];if(o.alias){let f=Array.isArray(o.alias)?o.alias.join(","):o.alias;c.push(`alias:${f}`)}if(o.cwd)c.push(`cwd:${o.cwd}`);if(o.configFile)c.push(`configFile:${o.configFile}`);if(o.configDir)c.push(`configDir:${o.configDir}`);if("checkEnv"in o)c.push(`checkEnv:${o.checkEnv}`);return c.join("|")}getLocalDirectories(i,o){return oi({cwd:i,configDir:o})}getAllSearchPaths(i,o,c,f){let u=[];return u.push(...this.getLocalSearchPaths(i,o,c,f)),u.push(...this.getHomeSearchPaths(i,o)),u.push(fe(c,"package.json")),u}getLocalSearchPaths(i,o,c,f){let u=this.getLocalDirectories(c,f),g=[];for(let h of u)g.push(...this.fileLoader.generateConfigPaths(i,h,o));return g}getHomeSearchPaths(i,o){if(!i)return[];let c=[fe(Ce(),".config",i),fe(Ce(),".config"),Ce()],f=[];for(let u of c)f.push(...this.fileLoader.generateConfigPaths(i,u,o));return f}async loadConfigWithResult(i){return this.loadConfig(i)}}var pr=new Ns;async function Fs(i){let o="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},c="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let f;if(c)f=await pr.loadConfig(i);else f=await pr.loadConfig({...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}});return f?.config??o}catch(f){if(i.configFile||i.errorPolicy==="throw")throw f;let u=f instanceof Error?f.message:String(f);if(!(f instanceof _e||f instanceof ve||f instanceof _r||u.includes("config"))&&i.verbose)le.warn("Unexpected error loading config, using defaults:",[f instanceof Error?f:Error(String(f))]);let h=c?{...i,defaultConfig:o}:{...i,defaultConfig:o,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await pr.applyEnvironmentVariables(h.name||"",o,!0,h.verbose||!1))?.config??o;return o}}function Ve(i,o,c=!1){let f=new Br,u=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function g(h,d=[]){let y={...h};for(let[b,S]of Object.entries(h)){let v=[...d,b],C=[`${u}_${v.join("_").toUpperCase()}`,`${u}_${v.map((k)=>k.toUpperCase()).join("")}`,`${u}_${v.map((k)=>k.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],E,A;for(let k of C)if(E=Mt.env[k],E!==void 0){A=k;break}if(E!==void 0&&A)if(typeof S==="boolean")y[b]=["true","1","yes"].includes(E.toLowerCase());else if(typeof S==="number"){let k=Number(E);if(!Number.isNaN(k))y[b]=k}else if(Array.isArray(S))try{y[b]=JSON.parse(E)}catch{y[b]=E.split(",").map((k)=>k.trim())}else y[b]=E;else if(S&&typeof S==="object"&&!Array.isArray(S))y[b]=g(S,v)}return y}return g(o)}var Pl=fe(Mt.cwd(),"config"),Dl=fe(Mt.cwd(),"src/generated");function n(i=e.dialect){return i==="mysql"||i==="singlestore"||i==="vitess"}var it={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}},Bs=new Set(["__proto__","constructor","prototype"]);function _s(i){if(i===null||typeof i!=="object"||Array.isArray(i))return!1;let o=Object.getPrototypeOf(i);return o===Object.prototype||o===null}function jr(i,o,c=new Set){let f={...i};c.add(o);for(let u of Object.keys(o)){if(Bs.has(u))continue;let g=o[u];if(_s(g)&&!c.has(g)){let h=f[u];f[u]=jr(_s(h)?h:{},g,c)}else f[u]=g}return c.delete(o),f}var Sa=Symbol.for("bun-query-builder.config"),e=globalThis[Sa]??=jr({},it),va=Symbol.for("bun-query-builder.config-state"),qt=globalThis[va]??={explicit:new Set,fileLoaded:!1};function I(i){if(i)return st(i);let o=Is.env.DB_DIALECT||Is.env.DB_CONNECTION;if(o)return st(o);return e.dialect||"postgres"}function st(i){let o=i.trim().toLowerCase();if(o==="turso"||o==="libsql")return"sqlite";return o}function t(i){if(e.dialect==="postgres")return`$${i}`;return"?"}function s(i,o=1){if(i<=0)return"";if(e.dialect==="postgres"){let c=`$${o}`;for(let f=1;f<i;f++)c+=`, $${o+f}`;return c}return i===1?"?":`?${", ?".repeat(i-1)}`}async function L(){if(!qt.fileLoaded){qt.fileLoaded=!0;let i=await Fs({name:"query-builder",alias:"qb",defaultConfig:it}),o={};for(let[c,f]of Object.entries(i??{}))if(!qt.explicit.has(c))o[c]=f;js(o)}return e}var Ze=null,Ms=new Set;function js(i){let o=jr(e,i),c=e;for(let f of Object.keys(o)){if(Bs.has(f))continue;c[f]=o[f]}}function Le(i){if(i.dialect&&Ze&&i.dialect!==Ze){let o=`${Ze}->${i.dialect}`;if(!Ms.has(o))Ms.add(o),console.warn(`[query-builder] Configuring dialect '${i.dialect}' overrides the previously configured dialect '${Ze}'. 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)Ze=i.dialect;for(let o of Object.keys(i))qt.explicit.add(o);js(i)}function mn(i){return i}function at(i){return typeof i==="string"&&/^(?:libsql|https?|wss?):\/\//i.test(i.trim())}function hn(i){let o;try{o=new URL(i.trim())}catch{throw new a("Invalid libSQL URL: expected libsql://, https://, http://, ws:// or wss://",{code:"LIBSQL_INVALID_URL"})}let c=o.protocol.replace(/:$/,"").toLowerCase(),f=o.searchParams.get("tls"),u=f==="0"||f==="false",g=o.searchParams.get("authToken")??void 0,h;switch(c){case"libsql":h=u?"http":"https";break;case"https":case"wss":h="https";break;case"http":case"ws":h="http";break;default:throw new a(`Unsupported libSQL URL scheme '${c}:'`,{code:"LIBSQL_INVALID_URL"})}if(o.username||o.password)throw new a("libSQL URLs must not embed credentials; pass the token as authToken",{code:"LIBSQL_INVALID_URL"});let d=o.pathname.replace(/\/+$/,"");return{baseUrl:`${h}://${o.host}${d}`,authToken:g||void 0}}var Ea=[[/^UNIQUE constraint failed/i,"SQLITE_CONSTRAINT_UNIQUE",2067],[/^NOT NULL constraint failed/i,"SQLITE_CONSTRAINT_NOTNULL",1299],[/^FOREIGN KEY constraint failed/i,"SQLITE_CONSTRAINT_FOREIGNKEY",787],[/^CHECK constraint failed/i,"SQLITE_CONSTRAINT_CHECK",275]],Ks={SQLITE_ERROR:1,SQLITE_INTERNAL:2,SQLITE_PERM:3,SQLITE_ABORT:4,SQLITE_BUSY:5,SQLITE_LOCKED:6,SQLITE_NOMEM:7,SQLITE_READONLY:8,SQLITE_INTERRUPT:9,SQLITE_IOERR:10,SQLITE_CORRUPT:11,SQLITE_FULL:13,SQLITE_CANTOPEN:14,SQLITE_SCHEMA:17,SQLITE_TOOBIG:18,SQLITE_CONSTRAINT:19,SQLITE_MISMATCH:20,SQLITE_MISUSE:21,SQLITE_RANGE:25};class a extends Error{code;errno;libsqlCode;status;constructor(i,o){super(i,o.cause===void 0?void 0:{cause:o.cause});this.name="LibSQLError",this.code=o.code,this.errno=o.errno,this.libsqlCode=o.libsqlCode,this.status=o.status}}function Ke(i){let c=String(i.message??"libSQL statement failed").replace(/^SQLite error:\s*/i,""),f=i.code??void 0;for(let[u,g,h]of Ea)if(u.test(c))return new a(c,{code:g,errno:h,libsqlCode:f});if(f&&f in Ks)return new a(c,{code:f,errno:Ks[f],libsqlCode:f});if(f==="SQL_PARSE_ERROR"||f==="SQL_INPUT_ERROR")return new a(c,{code:"SQLITE_ERROR",errno:1,libsqlCode:f});return new a(c,{code:f??"LIBSQL_ERROR",libsqlCode:f})}var $a=-(2n**63n),Ca=2n**63n-1n;function Kr(i){return Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Wt(i){if(i===null||i===void 0)return{type:"null"};switch(typeof i){case"string":return{type:"text",value:i};case"boolean":return{type:"integer",value:i?"1":"0"};case"number":if(!Number.isFinite(i))throw RangeError(`Cannot bind ${i} to a libSQL statement: only finite numbers are allowed`);return Number.isSafeInteger(i)?{type:"integer",value:String(i===0?0:i)}:{type:"float",value:i};case"bigint":if(i<$a||i>Ca)throw RangeError(`Cannot bind ${i} to a libSQL statement: it does not fit in a 64-bit integer`);return{type:"integer",value:i.toString()}}if(i instanceof Date){if(Number.isNaN(i.getTime()))throw RangeError("Cannot bind an invalid Date to a libSQL statement");return{type:"text",value:i.toISOString()}}if(i instanceof Uint8Array)return{type:"blob",base64:Kr(i)};if(i instanceof ArrayBuffer)return{type:"blob",base64:Kr(new Uint8Array(i))};if(ArrayBuffer.isView(i))return{type:"blob",base64:Kr(new Uint8Array(i.buffer,i.byteOffset,i.byteLength))};throw TypeError(`Cannot bind a value of type ${Object.prototype.toString.call(i).slice(8,-1)} to a libSQL statement; serialize it first (e.g. JSON.stringify)`)}function Ut(i,o="bigint"){switch(i.type){case"null":return null;case"integer":{let c=Number(i.value);if(Number.isSafeInteger(c))return c;return o==="string"?i.value:BigInt(i.value)}case"float":return typeof i.value==="number"?i.value:Number(i.value);case"text":return i.value;case"blob":{let c=Buffer.from(i.base64??"","base64");return new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}default:throw new a(`Unknown libSQL value type '${i.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"})}}function gn(i,o="bigint"){let c=i.cols.map((d,y)=>d.name??String(y)),f=i.rows.map((d)=>{let y={};for(let b=0;b<c.length;b++)y[c[b]]=Ut(d[b]??{type:"null"},o);return y}),u=Number(i.affected_row_count??0),g=i.last_insert_rowid==null?null:Ut({type:"integer",value:i.last_insert_rowid},o),h=(d)=>({value:d,enumerable:!1,writable:!0,configurable:!0});return Object.defineProperties(f,{changes:h(u),count:h(u>0?u:f.length),lastInsertRowid:h(g),columns:h(c)}),f}function Fe(i,o=[]){if(!Array.isArray(o)){let f=Object.entries(o).map(([u,g])=>({name:/^[:@$]/.test(u)?u:`:${u}`,value:Wt(g)}));return{sql:i,named_args:f,want_rows:!0}}let c=Ur(i,[...o]);return{sql:c.sql,args:c.params.map(Wt),want_rows:!0}}var xa=/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i,Ta=/^\s*PRAGMA\s+(?:main\.)?foreign_keys\s*(?:=\s*|\(\s*)['"]?(\w+)['"]?\s*\)?\s*;?\s*$/i;function ka(i){let o=Ta.exec(i);return o?o[1].toUpperCase():null}class Qs{baseUrl;authToken;timeoutMs;fetchImpl;constructor(i){let o=hn(i.url);this.baseUrl=o.baseUrl,this.authToken=i.authToken||o.authToken,this.timeoutMs=i.timeoutMs,this.fetchImpl=i.fetch??fetch}async pipeline(i,o,c){let f={"content-type":"application/json"};if(this.authToken)f.authorization=`Bearer ${this.authToken}`;let u;try{u=await this.fetchImpl(`${i}/v3/pipeline`,{method:"POST",headers:f,body:JSON.stringify({baton:o,requests:c}),signal:this.timeoutMs?AbortSignal.timeout(this.timeoutMs):void 0})}catch(h){let d=h instanceof Error?h.message:String(h);throw new a(`Could not reach the libSQL server at ${this.baseUrl}: ${d}`,{code:"LIBSQL_CONNECTION_FAILED",cause:h})}if(!u.ok){let h=await Aa(u),d=h?` (${h})`:"";if(u.status===401||u.status===403)throw new a(`The libSQL server at ${this.baseUrl} rejected the request: HTTP ${u.status}${d}. `+(this.authToken?"The auth token was refused - check that it belongs to this database and has not expired.":"No auth token was sent - set one (TURSO_AUTH_TOKEN in Stacks)."),{code:"LIBSQL_UNAUTHORIZED",status:u.status});if(u.status===404)throw new a(`The libSQL server at ${this.baseUrl} has no Hrana v3 pipeline endpoint (HTTP 404). Check the URL, and that the server is sqld 0.21+ or Turso.`,{code:"LIBSQL_NOT_FOUND",status:404});throw new a(`The libSQL server at ${this.baseUrl} answered HTTP ${u.status}${d}`,{code:"LIBSQL_HTTP_ERROR",status:u.status})}let g=await u.json();if(!g||!Array.isArray(g.results))throw new a(`The libSQL server at ${this.baseUrl} sent a reply that is not a Hrana pipeline response`,{code:"LIBSQL_PROTOCOL_ERROR"});return g}}async function Aa(i){try{let o=(await i.text()).trim();if(!o)return"";try{let c=JSON.parse(o),f=c.error??c.message;if(typeof f==="string")return f}catch{}return o.slice(0,300)}catch{return""}}class Us{http;prelude;baton=null;baseUrl;tail=Promise.resolve();opened=!1;closed=!1;constructor(i,o){this.http=i;this.prelude=o;this.baseUrl=i.baseUrl}send(i,o={}){let c=async()=>{if(this.closed)throw new a("This libSQL stream is closed",{code:"LIBSQL_STREAM_CLOSED"});let u=this.opened?[]:this.prelude();this.opened=!0;let g=[...u,...i];if(o.close)g.push({type:"close"});let h;try{h=await this.http.pipeline(this.baseUrl,this.baton,g)}catch(d){throw this.closed=!0,d}if(this.baton=h.baton,h.base_url)this.baseUrl=h.base_url.replace(/\/+$/,"");if(o.close||h.baton===null)this.closed=!0;for(let d=0;d<u.length;d++){let y=h.results[d];if(y?.type==="error")throw Ke(y.error)}return h.results.slice(u.length,u.length+i.length)},f=this.tail.then(c,c);return this.tail=f.catch(()=>{}),f}async close(){if(this.closed)return;if(!this.opened){this.closed=!0;return}await this.send([],{close:!0})}}function Xe(i){if(!i)throw new a("The libSQL server sent fewer results than requests",{code:"LIBSQL_PROTOCOL_ERROR"});if(i.type==="error")throw Ke(i.error);if(i.response.type!=="execute")throw new a(`Expected an execute result, got '${i.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});return i.response.result}function Vs(i){if(i?.type==="ok"&&i.response.type==="get_autocommit")return i.response.is_autocommit;return!1}class qs{http;largeIntegers;foreignKeys=null;pinned=null;closed=!1;constructor(i){this.http=new Qs(i),this.largeIntegers=i.largeIntegers??"bigint"}prelude=()=>this.foreignKeys?[{type:"execute",stmt:{sql:`PRAGMA foreign_keys = ${this.foreignKeys}`,want_rows:!1}}]:[];openStream(){return this.assertOpen(),new Us(this.http,this.prelude)}assertOpen(){if(this.closed)throw new a("Cannot use a closed libSQL connection",{code:"LIBSQL_CLOSED"})}rows(i){return gn(i,this.largeIntegers)}notePragma(i){let o=ka(i);if(o)this.foreignKeys=o==="OFF"||o==="0"||o==="FALSE"||o==="NO"?"OFF":"ON"}async execute(i){this.assertOpen();let o=xa.test(i.sql);if(this.pinned){let g=this.pinned,h=[{type:"execute",stmt:i}];if(o)h.push({type:"get_autocommit"});let d;try{d=await g.send(h)}catch(b){if(this.pinned===g)this.pinned=null;throw b}if(o&&Vs(d[1])){if(this.pinned===g)this.pinned=null;await g.close().catch(()=>{})}let y=this.rows(Xe(d[0]));return this.notePragma(i.sql),y}if(o){let g=this.openStream(),h;try{h=await g.send([{type:"execute",stmt:i},{type:"get_autocommit"}])}catch(y){throw await g.close().catch(()=>{}),y}if(h[0]?.type!=="error"&&!Vs(h[1]))this.pinned=g;else await g.close().catch(()=>{});return this.rows(Xe(h[0]))}let c=this.openStream(),[f]=await c.send([{type:"execute",stmt:i}],{close:!0}),u=this.rows(Xe(f));return this.notePragma(i.sql),u}async close(){this.closed=!0;let i=this.pinned;this.pinned=null,await i?.close().catch(()=>{})}}function Hs(i,o){return{async execute(c){let[f]=await o.send([{type:"execute",stmt:c}]),u=i.rows(Xe(f));return i.notePragma(c.sql),u},async sequence(c){let f=[];for(let u of c)f.push(await this.execute(u));return f}}}function Ra(i){return{execute:(o)=>i.execute(o),async sequence(o){if(i.pinned){let f=[];for(let u of o)f.push(await i.execute(u));return f}let c=i.openStream();try{let f=[];for(let u of o)f.push(await Hs(i,c).execute(u));return f}finally{await c.close().catch(()=>{})}}}}function Ws(i){return{__raw:!0,value:i,toString:()=>i}}function La(i,o){let c=i[0],f=[];for(let u=0;u<o.length;u++){let g=o[u],h=Qr(g);if(h&&typeof h.sql==="string"&&Array.isArray(h.values))c+=h.sql+(i[u+1]||""),f.push(...h.values);else if(h&&(h.__raw||h.raw)){let d=h.raw,y=h.__raw?h.value:typeof d==="string"?d:d();c+=y+(i[u+1]||"")}else if(Array.isArray(g))c+=g.map(()=>"?").join(", ")+(i[u+1]||""),f.push(...g);else c+=`?${i[u+1]||""}`,f.push(g)}return{sql:c,params:f}}function Vr(i,o,c,f){let u=()=>{try{return i.target.execute(Fe(o,c))}catch(h){return Promise.reject(h)}},g={sql:o,values:c,execute:u,raw:()=>o,toString:()=>o,cancel:()=>{}};if(f)g.then=(h,d)=>u().then(h,d);return g}function Wr(i){function o(c,...f){if(Array.isArray(c)&&"raw"in c){let{sql:u,params:g}=La(c,f);return Vr(i,u,g,!1)}if(typeof c==="string")return Ws(c);return Vr(i,"",[],!1)}return o.raw=(c)=>Ws(c),o.unsafe=(c,f=[])=>Vr(i,c,f??[],!0),o.query=(c,f)=>{try{return i.target.execute(Fe(c,f??[]))}catch(u){return Promise.reject(u)}},o.file=async(c)=>{let{readFileSync:f}=await import("fs"),u=qr(f(c,"utf-8")).map((g)=>g.trim()).filter((g)=>g&&!g.startsWith("--"));return await i.target.sequence(u.map((g)=>Fe(g))),[]},o.batch=async(c)=>{if(i.session.assertOpen(),c.length===0)return[];let f=i.stream!==null,u=c.map((C)=>Fe(C.sql,C.args??[])),g=[];if(!f)g.push({stmt:{sql:"BEGIN"}});for(let C of u)g.push({stmt:C,condition:g.length?{type:"ok",step:g.length-1}:null});if(!f){let C=g.length-1;g.push({stmt:{sql:"COMMIT"},condition:{type:"ok",step:C}}),g.push({stmt:{sql:"ROLLBACK"},condition:{type:"not",cond:{type:"ok",step:C+1}}})}let h=i.stream??i.session.openStream(),d;try{d=await h.send([{type:"batch",batch:{steps:g}}],{close:!f})}finally{if(!f)await h.close().catch(()=>{})}let y=d[0];if(!y)throw new a("The libSQL server sent no batch result",{code:"LIBSQL_PROTOCOL_ERROR"});if(y.type==="error")throw Ke(y.error);if(y.response.type!=="batch")throw new a(`Expected a batch result, got '${y.response.type}'`,{code:"LIBSQL_PROTOCOL_ERROR"});let{step_results:b,step_errors:S}=y.response.result,v=f?0:1;for(let C=0;C<S.length;C++){let E=S[C];if(E)throw Ke(E)}return u.map((C,E)=>{let A=b[E+v];if(!A)throw new a(`Batch statement ${E+1} did not run`,{code:"LIBSQL_BATCH_SKIPPED"});return i.session.rows(A)})},o.begin=async(c,f)=>{let u=typeof c==="function"?c:f;if(typeof u!=="function")throw TypeError("[query-builder] libsql begin(): a transaction callback is required");if(i.session.assertOpen(),i.stream){let S=`qb_sp_${i.depth}`,v=i.target;await v.execute({sql:`SAVEPOINT ${S}`});let C=Wr({...i,depth:i.depth+1});try{let E=await u(C);return await v.execute({sql:`RELEASE SAVEPOINT ${S}`}),E}catch(E){try{await v.execute({sql:`ROLLBACK TO SAVEPOINT ${S}`}),await v.execute({sql:`RELEASE SAVEPOINT ${S}`})}catch{}throw E}}let g=i.session.openStream(),h=Hs(i.session,g);try{await h.execute({sql:"BEGIN"})}catch(S){throw await g.close().catch(()=>{}),S}let d=Wr({session:i.session,target:h,stream:g,depth:1}),y;try{y=await u(d)}catch(S){try{await g.send([{type:"execute",stmt:{sql:"ROLLBACK"}}],{close:!0})}catch{await g.close().catch(()=>{})}throw S}let[b]=await g.send([{type:"execute",stmt:{sql:"COMMIT"}}],{close:!0});return Xe(b),y},o.savepoint=o.begin,o.beginDistributed=async()=>{throw Error("[query-builder] beginDistributed() (two-phase commit) is not supported on libSQL. Use begin()/transaction().")},o.close=async()=>{if(i.stream)return;await i.session.close()},o.libsql={url:i.session.http.baseUrl,transaction:i.stream!==null},o}function Vt(i){let o=new qs(i);return Wr({session:o,target:Ra(o),stream:null,depth:0})}function Vn(i){return(typeof i==="function"||typeof i==="object"&&i!==null)&&typeof i.libsql==="object"&&i.libsql!==null}var Ht=["PRAGMA journal_mode = WAL","PRAGMA foreign_keys = ON","PRAGMA busy_timeout = 5000"];function Qt(){let i=e.sqlite?.pragmas;return Array.isArray(i)?i:Ht}function R(i){for(let o of Qt())try{i.run(o)}catch{}}var Oa=32,Hr=262144;function et(i){return`"${i.replaceAll('"','""')}"`}class zr{database;pending=[];bytes=0;timer;closed=!1;failure;constructor(i){this.database=i}get hasPending(){return this.pending.length>0}append=(i,o)=>{if(this.failure)return Promise.reject(this.failure);if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));let c=Object.keys(o),f=c.map((h)=>{let d=o[h];if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength).slice();if(d instanceof Date)return ye(d);return d??null}),u=JSON.stringify([i,c]),g=512+u.length*2+f.reduce((h,d)=>h+(typeof d==="string"?d.length*2:ArrayBuffer.isView(d)?d.byteLength:16),0);if(this.hasPending&&(this.pending.length>=Oa||this.bytes+g>Hr))this.flush();return new Promise((h,d)=>{let y={table:i,columns:c,values:f,shape:u,uncached:g>Hr,resolve:h,reject:d};if(this.database.inTransaction||g>Hr){this.writeOne(y);return}this.pending.push(y),this.bytes+=g,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 o=0;o<i.length;){if(this.failure){for(let u of i.slice(o))u.reject(this.failure);return}let c=o+1;while(c<i.length&&i[c].shape===i[o].shape)c++;let f=i.slice(o,c);if(o=c,f.length===1||!f[0].columns.length||this.database.inTransaction){for(let u of f)this.writeOne(u);continue}try{this.database.transaction(()=>{let u=f[0],g=`(${u.columns.map(()=>"?").join(",")})`,h=`INSERT INTO ${et(u.table)} (${u.columns.map(et).join(",")}) VALUES ${f.map(()=>g).join(",")}`;this.database.query(h).run(...f.flatMap((d)=>d.values))})();for(let u of f)u.resolve()}catch(u){if(this.database.inTransaction){this.invalidate(u);for(let g of[...f,...i.slice(o)])g.reject(u);return}for(let g of f)this.writeOne(g)}}}writeOne(i){let o=!1;try{this.assertUsable(),o=this.database.inTransaction;let c=i.columns.length?`INSERT INTO ${et(i.table)} (${i.columns.map(et).join(",")}) VALUES (${i.columns.map(()=>"?").join(",")})`:`INSERT INTO ${et(i.table)} DEFAULT VALUES`,f=()=>{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(o)f();else this.database.transaction(f)();i.resolve()}catch(c){if(!this.failure&&!o&&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 Gr(i){return p(i)}function Qr(i){return i!==null&&typeof i==="object"?i:null}function Ur(i,o){if(o.length===0||!/\$\d/.test(i))return{sql:i,params:o};let c=[],f="",u=0;for(let g=0;g<i.length;g++){let h=i[g];if(h==="'"||h==='"'||h==="`"){let d=Ia(i,g,h);f+=i.slice(g,d),g=d-1;continue}if(h==="-"&&i[g+1]==="-"){let d=i.indexOf(`
62
+ `,g),y=d===-1?i.length:d;f+=i.slice(g,y),g=y-1;continue}if(h==="/"&&i[g+1]==="*"){let d=i.indexOf("*/",g+2),y=d===-1?i.length:d+2;f+=i.slice(g,y),g=y-1;continue}if(h==="$"){let d=/^\d+/.exec(i.slice(g+1))?.[0];if(d){let y=Number(d);if(u=Math.max(u,y),y>=1&&y<=o.length){c.push(o[y-1]),f+="?",g+=d.length;continue}}}f+=h}if(u>o.length)throw Error(`SQL references $${u} but only ${o.length} value${o.length===1?" was":"s were"} provided`);if(c.length===0)return{sql:i,params:o};return{sql:f,params:c}}function Ia(i,o,c){for(let f=o+1;f<i.length;f++){if(i[f]!==c)continue;if(i[f+1]===c){f++;continue}return f+1}return i.length}var zs=/^\s*(?:SELECT|WITH|INSERT|UPDATE|DELETE|REPLACE)\b/i;class Zs{db;deferredInserts;closed=!1;constructor(i){if(i!==":memory:"&&!i.startsWith(":")){let o=Fa(i);if(o&&o!==".")Na(o,{recursive:!0})}this.db=new Da(i),R(this.db)}deferInsert=(i,o)=>{if(this.closed)return Promise.reject(Error("Deferred insert connection is closed"));if(!this.deferredInserts){let c=this.deferredInserts=new zr(this.db),f=this.query.bind(this),u=this.run.bind(this),g=(h)=>{if(c.hasPending&&!zs.test(h))c.flush();c.assertUsable()};this.query=(h,d)=>(g(h),f(h,d)),this.run=(h,d)=>(g(h),u(h,d))}return this.deferredInserts.append(i,o)};flushDeferredInserts(){this.deferredInserts?.flush()}query(i,o=[]){return this.withStatement(i,o,(c,f)=>c.all(...f))}run(i,o=[]){return this.withStatement(i,o,(c,f)=>c.run(...f))}withStatement(i,o,c){let f=Ur(i,o),u=f.params.length>0||zs.test(f.sql),g=u?this.db.query(f.sql):this.db.prepare(f.sql),h=u&&f.params.length===0&&g.paramsCount>0,d=h?this.db.prepare(f.sql):g;try{return c(d,f.params)}finally{if(h||!u)d.finalize()}}close(){this.closed=!0,this.deferredInserts?.close(),this.db.close()}get database(){return this.db}}function Gs(i){return{__raw:!0,value:i,toString:()=>i}}function Ys(i){let o=i.trimStart();for(;;)if(o.startsWith("--")){let c=o.indexOf(`
63
+ `);o=c===-1?"":o.slice(c+1).trimStart()}else if(o.startsWith("/*")){let c=o.indexOf("*/");o=c===-1?"":o.slice(c+2).trimStart()}else return o}function qr(i){let o=[],c="",f=!1,u=!1,g=!1,h=!1;for(let y=0;y<i.length;y++){let b=i[y],S=i[y+1];if(!f&&!u&&!h&&b==="-"&&S==="-"){g=!0,c+=b;continue}if(g&&(b===`
64
+ `||b==="\r")){g=!1,c+=b;continue}if(!f&&!u&&!g&&b==="/"&&S==="*"){h=!0,c+=b;continue}if(h&&b==="*"&&S==="/"){h=!1,c+=b+S,y++;continue}if(g||h){c+=b;continue}if(b==="'"&&!u){if(f&&S==="'"){c+=b+S,y++;continue}f=!f,c+=b;continue}if(b==='"'&&!f){u=!u,c+=b;continue}if(b===";"&&!f&&!u){let v=Ys(c.trim());if(v)o.push(v);c="";continue}c+=b}let d=Ys(c.trim());if(d)o.push(d);return o}function Js(i){let o=new Zs(i);function c(h,d){let y=h.trim().toUpperCase();if(y.startsWith("SELECT")||y.startsWith("PRAGMA")||/\bRETURNING\b/.test(y))return o.query(h,Gr(d));return o.run(h,Gr(d))}function f(h,...d){let y=h[0],b=[];for(let v=0;v<d.length;v++){let C=d[v],E=Qr(C);if(E&&typeof E.sql==="string"&&Array.isArray(E.values))y+=E.sql+(h[v+1]||""),b.push(...E.values);else if(E&&(E.__raw||E.raw)){let A=E.raw,k=E.__raw?E.value:typeof A==="string"?A:A();y+=k+(h[v+1]||"")}else if(Array.isArray(C)){let A=C.map(()=>"?").join(", ");y+=A+(h[v+1]||""),b.push(...C)}else y+=`?${h[v+1]||""}`,b.push(C)}let S=()=>c(y,b);return{sql:y,values:b,executeSync:S,execute:()=>{try{return Promise.resolve(S())}catch(v){return Promise.reject(v)}},raw:()=>y,toString:()=>y,cancel:()=>{}}}function u(h,...d){if(Array.isArray(h)&&"raw"in h)return f(h,...d);if(typeof h==="string")return Gs(h);return f([""])}u.raw=(h)=>Gs(h),u.unsafe=(h,d=[])=>{let y=()=>c(h,d),b=()=>{try{return Promise.resolve(y())}catch(S){return Promise.reject(S)}};return{sql:h,values:d,execute:b,executeSync:y,then:(S,v)=>b().then(S,v),raw:()=>h,toString:()=>h,cancel:()=>{}}},u.deferInsert=o.deferInsert,u.flushDeferredInserts=()=>o.flushDeferredInserts(),u.close=()=>(o.close(),Promise.resolve()),u.query=(h,d)=>{try{let y=o.query(h,Gr(d||[]));return Promise.resolve(y)}catch(y){return Promise.reject(y)}},u.file=async(h,d)=>{try{let{readFileSync:y}=await import("fs"),b=y(h,"utf-8"),S=qr(b);for(let v of S){let C=v.trim();if(!C||C.startsWith("--"))continue;let E=C.toUpperCase();if(E.startsWith("SELECT")||E.startsWith("PRAGMA"))o.query(v);else o.run(v)}return Promise.resolve([])}catch(y){return Promise.reject(y)}};let g=0;return u.begin=async(h,d)=>{let y=typeof h==="function"?h:d;if(typeof y!=="function")throw TypeError("[query-builder] sqlite begin(): a transaction callback is required");let b=typeof h==="string"?h.trim().toUpperCase():"DEFERRED";if(!["DEFERRED","IMMEDIATE","EXCLUSIVE"].includes(b))throw TypeError("[query-builder] sqlite begin(): expected DEFERRED, IMMEDIATE or EXCLUSIVE");let S=g>0,v=`qb_sp_${g}`;if(S)o.run(`SAVEPOINT ${v}`);else o.run(b==="DEFERRED"?"BEGIN":`BEGIN ${b}`);g++;try{let C=await y(u);if(g--,S)o.run(`RELEASE SAVEPOINT ${v}`);else o.run("COMMIT");return C}catch(C){g--;try{if(S)o.run(`ROLLBACK TO SAVEPOINT ${v}`),o.run(`RELEASE SAVEPOINT ${v}`);else o.run("ROLLBACK")}catch{}throw C}},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=o,u}function _a(i){let o=i.replace(/^(?:sqlite|sqlite3|file):/i,"");if(o===i)return i;return(o.startsWith("///")?o.slice(2):o.startsWith("//")?o.slice(2):o)||":memory:"}function je(i=e.database){let o=tt.env.DB_DATABASE||i?.database||"";return String(o).replace(/^['"]|['"]$/g,"")}function Ma(i,o){if((i==="postgres"||i==="mysql"||i==="singlestore"||i==="vitess")&&tt.env.DB_CONNECTION===i){let b=tt.env,S=(b.DB_DATABASE||o.database||"").replace(/^['"]|['"]$/g,""),v=b.DB_USERNAME||o.username,C=b.DB_PASSWORD??o.password??"",E=b.DB_HOST||o.host||"localhost",A=b.DB_PORT||o.port,k=i==="postgres"?"postgres":"mysql",O=b.DB_SSL==="true"||b.DB_SSL==="1"||o.ssl?"?ssl=true":"";return`${k}://${v}:${C}@${E}${A?`:${A}`:""}/${S}${O}`}if(o.url)return i==="sqlite"?_a(o.url):o.url;let{database:c,username:f,password:u,host:g="localhost",port:h,ssl:d}=o,y=d||tt.env.DB_SSL==="true"||tt.env.DB_SSL==="1"?"?ssl=true":"";switch(i){case"postgres":return`postgres://${f}:${u}@${g}${h?`:${h}`:""}/${c}${y}`;case"mysql":case"singlestore":case"vitess":return`mysql://${f}:${u}@${g}${h?`:${h}`:""}/${c}${y}`;case"sqlite":if(c===":memory:")return":memory:";return c||":memory:";default:throw Error(`Unsupported dialect: ${i}`)}}function Xs(i){if(!i)return{};let o={},c=(f)=>Math.max(0,Math.round(f/1000));if(typeof i.max==="number"&&Number.isFinite(i.max))o.max=i.max;if(typeof i.idleTimeoutMs==="number"&&Number.isFinite(i.idleTimeoutMs))o.idleTimeout=c(i.idleTimeoutMs);if(typeof i.acquireTimeoutMs==="number"&&Number.isFinite(i.acquireTimeoutMs))o.connectionTimeout=c(i.acquireTimeoutMs);if(typeof i.maxLifetimeMs==="number"&&Number.isFinite(i.maxLifetimeMs))o.maxLifetime=c(i.maxLifetimeMs);if(typeof i.preparedStatements==="boolean")o.prepare=i.preparedStatements;return o}function K(i=e.database,o=e.dialect){if(o!=="sqlite"||!i)return null;let c=at(i.url)?i.url:at(i.database)?i.database:null;if(!c)return null;return{url:c,authToken:i.authToken||void 0}}function Ba(){let i=e.dialect,o=K(e.database,i);if(o)return Vt(o);let c=Ma(i,e.database);try{if(i==="sqlite")return Js(c);let f=Xs(e.database.pool),u=decodeURIComponent(new URL(c).pathname.slice(1)),g=new Pa(c,{...f,...u?{database:u}:{}});return _(g)}catch(f){if(console.error(`[query-builder] Failed to create database connection for dialect '${i}': ${f.message}`),i==="sqlite")return Js(":memory:");throw f}}var Be=null,Yr=null;function ja(){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,authToken:i.authToken,pool:Xs(i.pool)})}function T(i=!1){let o=ja();if(i||Be!==null&&Yr!==o||!Be)ei(),Be=Ba(),Yr=o;return Be}function ei(){let i=Be;return i?.flushDeferredInserts?.(),Be=null,Yr=null,i}async function Ka(i){if(!i||typeof i.close!=="function")return;await i.close()}function pn(){Ka(ei()).catch((o)=>{console.error(`[query-builder] Failed to close database connection: ${o.message}`)})}async function ot(i){try{return await i(T())}catch(o){if(o?.code==="ERR_POSTGRES_CONNECTION_CLOSED"||o?.message?.includes("Connection closed")){console.log("-- Connection closed, creating fresh connection...");let c=T(!0);return await i(c)}throw o}}function Va(){return new Proxy(function(){},{get(i,o){let c=T(),f=c[o];if(typeof f==="function")return f.bind(c);return f},apply(i,o,c){return T()(...c)}})}var r=Va();function qe(i){let o=String(i).replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"");if(o.endsWith("y")&&!/[aeou]y$/.test(o))return`${o.slice(0,-1)}ies`;if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return`${o}es`;return`${o}s`}function w(i){return typeof i?.table==="string"&&i.table.length>0?i.table:qe(String(i?.name??""))}function yn(i){return i.endsWith("s")?i.slice(0,-1):i}function bn(i){if(i.endsWith("ies")&&i.length>3){let o=i.slice(0,-3),c=o[o.length-1];if(c&&!"aeiou".includes(c))return`${o}y`}if(i.endsWith("es")&&i.length>2){let o=i.slice(0,-2);if(o.endsWith("s")||o.endsWith("x")||o.endsWith("ch")||o.endsWith("sh"))return o}if(i.endsWith("s")&&!i.endsWith("ss")&&!i.endsWith("us")&&!i.endsWith("is"))return i.slice(0,-1);return i}function m(i){if(i==="none")return(o)=>o;if(i==="inflect")return bn;return yn}var Gt="1 = 0";function x(i){if(i.length===0)return"";let o=[];for(let c of i)if(c.conn==="OR"&&o.length>0)o[o.length-1].push(c);else o.push([c]);return o.map((c,f)=>{let u=c.map((h)=>h.sql).join(" OR "),g=c.length>1&&o.length>1?`(${u})`:u;return f===0?g:`${c[0].conn} ${g}`}).join(" ")}function l(i,o,c,f){if(o.length===0)return c?"1 = 1":"1 = 0";return`${i} ${c?"NOT IN":"IN"} (${f})`}function lt(i,o){if(o!=="postgres")return i;return We(i,(c)=>`$${c}`).text}function te(i){return We(i,()=>{return}).count}function We(i,o){let c="",f=0,u=0,g=0;while(g<i.length){let h=i[g],d=-1;if(h==="'"||h==='"'||h==="`")d=Wa(i,g,h);else if(h==="-"&&i[g+1]==="-"){let y=i.indexOf(`
65
+ `,g+2);d=y===-1?i.length:y}else if(h==="/"&&i[g+1]==="*"){let y=1;d=g+2;while(d<i.length&&y>0)if(i[d]==="/"&&i[d+1]==="*")y++,d+=2;else if(i[d]==="*"&&i[d+1]==="/")y--,d+=2;else d++}else if(h==="$"){let y=i.slice(g).match(/^\$[A-Z_a-z]\w*\$|^\$\$/)?.[0];if(y){let b=i.indexOf(y,g+y.length);d=b===-1?i.length:b+y.length}}if(d!==-1){g=d;continue}if(h==="?"){f++;let y=o(f);if(y!==void 0)c+=i.slice(u,g)+y,u=g+1}g++}return{text:u===0?i:c+i.slice(u),count:f}}function Wa(i,o,c){let f=o+1;while(f<i.length){if(i[f]===c){if(i[f+1]===c){f+=2;continue}return f+1}f++}return i.length}function Ue(i,o,c=Number.POSITIVE_INFINITY){let f=[],u=0,g=(h)=>h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||h===95;for(let h=0;h<i.length;h++){let d=i.charCodeAt(h);if(d===45&&i.charCodeAt(h+1)===45){let b=i.indexOf(`
66
+ `,h+2);if(b===-1)return f;h=b;continue}if(d===47&&i.charCodeAt(h+1)===42){let b=1,S=h+2;while(S<i.length&&b>0)if(i[S]==="/"&&i[S+1]==="*")b++,S+=2;else if(i[S]==="*"&&i[S+1]==="/")b--,S+=2;else S++;h=S-1;continue}if(d===39||d===34||d===96){let b=h+1;while(b<i.length){if(i.charCodeAt(b)===d){if(i.charCodeAt(b+1)===d){b+=2;continue}break}b++}h=b;continue}if(d===36){let b=/^\$(?:[A-Z_][A-Z0-9_]*)?\$/i.exec(i.slice(h));if(b){let S=i.indexOf(b[0],h+b[0].length);h=S===-1?i.length:S+b[0].length-1;continue}}if(d===40){u++;continue}if(d===41){u=Math.max(0,u-1);continue}if(u!==0)continue;if(h===0)continue;let y=d&-33;if(y<65||y>90)continue;if(g(i.charCodeAt(h-1)))continue;for(let{key:b,pattern:S}of o){S.lastIndex=h;let v=S.exec(i);if(!v)continue;if(f.push({key:b,start:h,length:v[0].length}),f.length>=c)return f;h+=v[0].length-1;break}}return f}
67
+ export{p,_,n,it,e,I,st,t,s,L,Le,mn,at,hn,a,Ke,Wt,Ut,gn,Fe,Vt,Vn,Ht,Qt,R,je,K,T,pn,ot,r,qe,w,yn,bn,m,Gt,x,l,lt,te,We,Ue};