@stacksjs/bun-router 0.1.0 → 0.1.2

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.
Files changed (150) hide show
  1. package/dist/chunk-03m2j6h7.js +2 -0
  2. package/dist/chunk-08cw7ejr.js +3 -0
  3. package/dist/chunk-0e4g0fyv.js +62 -0
  4. package/dist/chunk-0mmn02yw.js +2 -0
  5. package/dist/chunk-126c9qm3.js +2 -0
  6. package/dist/chunk-12p13817.js +2 -0
  7. package/dist/chunk-14v65c37.js +4 -0
  8. package/dist/{chunk-s3dn1kwx.js → chunk-1b6a7t3v.js} +2 -2
  9. package/dist/chunk-1wenkmk0.js +2 -0
  10. package/dist/chunk-2152npfd.js +2 -0
  11. package/dist/chunk-26w23krx.js +2 -0
  12. package/dist/chunk-2g8m379z.js +10 -0
  13. package/dist/{chunk-5mxby3fd.js → chunk-2rr178et.js} +2 -2
  14. package/dist/chunk-2w8f3swz.js +29 -0
  15. package/dist/chunk-3y4gaz7v.js +82 -0
  16. package/dist/chunk-4r1x4afz.js +12 -0
  17. package/dist/chunk-4wyw66zk.js +2 -0
  18. package/dist/chunk-4z5sf8ag.js +2 -0
  19. package/dist/{chunk-krkchy8v.js → chunk-58tfvayh.js} +3 -3
  20. package/dist/{chunk-ex5fkjah.js → chunk-5dp83qcx.js} +43 -43
  21. package/dist/chunk-5f0d9j9a.js +2 -0
  22. package/dist/{chunk-zhx0hxdd.js → chunk-5z52b0fc.js} +7 -7
  23. package/dist/{chunk-kc659vhx.js → chunk-5zrnk2kq.js} +3 -3
  24. package/dist/chunk-6dmqtdnq.js +2 -0
  25. package/dist/{chunk-5s1pr62n.js → chunk-6e91956t.js} +2 -2
  26. package/dist/{chunk-jrf5a2ap.js → chunk-6rv8w5jk.js} +1 -1
  27. package/dist/{chunk-5n0ckcmc.js → chunk-6x1feysm.js} +2 -2
  28. package/dist/chunk-7y72hm1x.js +2 -0
  29. package/dist/{chunk-zetqzgf3.js → chunk-8hbhfh6b.js} +6 -6
  30. package/dist/{chunk-5ncn73tp.js → chunk-8kfzygg5.js} +2 -2
  31. package/dist/chunk-8wydx2we.js +2 -0
  32. package/dist/chunk-8zjnjvv7.js +2 -0
  33. package/dist/chunk-988h4bzr.js +2 -0
  34. package/dist/chunk-9b6a58ac.js +2 -0
  35. package/dist/chunk-a8fcaywb.js +2 -0
  36. package/dist/chunk-bfjwn7yg.js +2 -0
  37. package/dist/chunk-bp2522mm.js +2 -0
  38. package/dist/chunk-bswe62q4.js +48 -0
  39. package/dist/chunk-c3v796c8.js +943 -0
  40. package/dist/chunk-ccqmwdry.js +2 -0
  41. package/dist/chunk-ck0crwnx.js +2 -0
  42. package/dist/chunk-cqgkxcb4.js +2 -0
  43. package/dist/chunk-dntnakjy.js +2 -0
  44. package/dist/{chunk-67wgad4f.js → chunk-ettdpnrw.js} +2 -2
  45. package/dist/{chunk-csfrpsp7.js → chunk-ezqwq17j.js} +10 -10
  46. package/dist/chunk-ezx3qsez.js +2 -0
  47. package/dist/{chunk-73k79n7q.js → chunk-f72nnjy4.js} +360 -360
  48. package/dist/chunk-fna5n0ey.js +246 -0
  49. package/dist/chunk-fqhckdt8.js +2 -0
  50. package/dist/chunk-fr6hbx25.js +2 -0
  51. package/dist/{chunk-vr10sbbh.js → chunk-g9cwng6w.js} +1 -1
  52. package/dist/chunk-gd3za5x0.js +2 -0
  53. package/dist/chunk-gf28608k.js +2 -0
  54. package/dist/chunk-h1dj6v8q.js +3 -0
  55. package/dist/chunk-hjxe7k2g.js +2 -0
  56. package/dist/chunk-hrkgznbn.js +2 -0
  57. package/dist/chunk-j6h5v0br.js +2 -0
  58. package/dist/{chunk-0gjq8ttx.js → chunk-mgb01qdv.js} +2 -2
  59. package/dist/chunk-n24c9whp.js +2 -0
  60. package/dist/{chunk-kxp888dn.js → chunk-n2j24b0h.js} +244 -244
  61. package/dist/{chunk-vv3gb1m5.js → chunk-nhmtg01n.js} +2 -2
  62. package/dist/chunk-p0qhpnqh.js +70 -0
  63. package/dist/chunk-p0w1x8y2.js +3 -0
  64. package/dist/{chunk-9ght4n4r.js → chunk-p3dk1w2w.js} +11 -11
  65. package/dist/{chunk-6sjvhy5f.js → chunk-q4e9pxs7.js} +2 -2
  66. package/dist/chunk-q5dv1kyy.js +2 -0
  67. package/dist/chunk-qnqgf9tq.js +2 -0
  68. package/dist/chunk-qvwy1808.js +898 -0
  69. package/dist/{chunk-5s0pnsd6.js → chunk-r18f77vc.js} +4 -4
  70. package/dist/chunk-r63za1mr.js +2 -0
  71. package/dist/{chunk-6s1kbajm.js → chunk-rft8gw92.js} +1 -1
  72. package/dist/chunk-ryvmyskt.js +4211 -0
  73. package/dist/chunk-sa6mx308.js +2 -0
  74. package/dist/chunk-va0pc7hx.js +2 -0
  75. package/dist/chunk-vcp8dnjq.js +412 -0
  76. package/dist/chunk-vg1erq1q.js +2 -0
  77. package/dist/{chunk-hmgedrmr.js → chunk-w0jv49ch.js} +3 -3
  78. package/dist/{chunk-0t5vz87j.js → chunk-wm805tte.js} +19 -19
  79. package/dist/chunk-xj9h6mc9.js +2 -0
  80. package/dist/chunk-ytvzwrq3.js +51 -0
  81. package/dist/{chunk-w4r464v5.js → chunk-zde7ebc4.js} +2 -2
  82. package/dist/chunk-zmqsv2xy.js +2 -0
  83. package/dist/cli.js +57 -66
  84. package/dist/container/index.js +1 -1
  85. package/dist/index.d.ts +1 -0
  86. package/dist/index.js +29 -29
  87. package/dist/typed/client.d.ts +89 -0
  88. package/dist/typed/contract.d.ts +34 -0
  89. package/dist/typed/endpoint.d.ts +90 -0
  90. package/dist/typed/index.d.ts +14 -0
  91. package/dist/typed/router.d.ts +141 -0
  92. package/package.json +1 -1
  93. package/dist/chunk-30rkn2ym.js +0 -2
  94. package/dist/chunk-38cmrard.js +0 -2
  95. package/dist/chunk-3qna6dwd.js +0 -2
  96. package/dist/chunk-4d5fmta0.js +0 -2
  97. package/dist/chunk-4x3b4b4q.js +0 -2
  98. package/dist/chunk-6xed4va1.js +0 -2
  99. package/dist/chunk-748n6ydj.js +0 -2
  100. package/dist/chunk-7rsf8tes.js +0 -898
  101. package/dist/chunk-8aspmtf1.js +0 -2
  102. package/dist/chunk-8yfdg595.js +0 -2
  103. package/dist/chunk-90eze7av.js +0 -3
  104. package/dist/chunk-9dvwyej7.js +0 -2
  105. package/dist/chunk-a2w45krb.js +0 -2
  106. package/dist/chunk-a547f2ab.js +0 -48
  107. package/dist/chunk-bqdycvtc.js +0 -2
  108. package/dist/chunk-cd03rk3x.js +0 -2
  109. package/dist/chunk-ct0m17q5.js +0 -2
  110. package/dist/chunk-dhbvvr5h.js +0 -2
  111. package/dist/chunk-dhptcsya.js +0 -943
  112. package/dist/chunk-dq93zag9.js +0 -2
  113. package/dist/chunk-edrtesh7.js +0 -2
  114. package/dist/chunk-ejcws37w.js +0 -2
  115. package/dist/chunk-ex890p45.js +0 -51
  116. package/dist/chunk-f69cpnhw.js +0 -2
  117. package/dist/chunk-fjf53b44.js +0 -2
  118. package/dist/chunk-fjzye4qj.js +0 -2
  119. package/dist/chunk-gfd23b6t.js +0 -2
  120. package/dist/chunk-habv0vef.js +0 -12
  121. package/dist/chunk-hz6fc788.js +0 -2
  122. package/dist/chunk-jff6j9y3.js +0 -10
  123. package/dist/chunk-jmeb7n8k.js +0 -70
  124. package/dist/chunk-jy2jhcpy.js +0 -246
  125. package/dist/chunk-m249t3je.js +0 -3
  126. package/dist/chunk-m9yabnjx.js +0 -2
  127. package/dist/chunk-mekrq9wd.js +0 -2
  128. package/dist/chunk-mmxv535f.js +0 -82
  129. package/dist/chunk-mypn7jss.js +0 -2
  130. package/dist/chunk-n18x1k3c.js +0 -2
  131. package/dist/chunk-nkddjzsa.js +0 -2
  132. package/dist/chunk-pjmhqmr9.js +0 -2
  133. package/dist/chunk-qyrnsaq1.js +0 -2
  134. package/dist/chunk-r19ff2qm.js +0 -62
  135. package/dist/chunk-r338fssq.js +0 -2
  136. package/dist/chunk-s36z58x2.js +0 -29
  137. package/dist/chunk-s79dd325.js +0 -471
  138. package/dist/chunk-ta38j9em.js +0 -2
  139. package/dist/chunk-tpfgntwj.js +0 -4211
  140. package/dist/chunk-vw8rwv6e.js +0 -2
  141. package/dist/chunk-wcrqs5z9.js +0 -2
  142. package/dist/chunk-x6d1rmwa.js +0 -2
  143. package/dist/chunk-x7ft15zz.js +0 -2
  144. package/dist/chunk-x8trwn7j.js +0 -3
  145. package/dist/chunk-xhepdj1f.js +0 -2
  146. package/dist/chunk-xv2em0q4.js +0 -4
  147. package/dist/chunk-ypw6g0te.js +0 -2
  148. package/dist/chunk-z8szsm21.js +0 -2
  149. package/dist/chunk-zfbh14qe.js +0 -2
  150. /package/dist/{chunk-a3wahyg7.js → chunk-nf3kv7kv.js} +0 -0
@@ -72,7 +72,7 @@ else {
72
72
  ${r}
73
73
  })();
74
74
  </script>
75
- `}function $(a,n,o){h=0;let l=/@defer\s*\(([^)]*)\)\s*([\s\S]*?)@enddefer/g;return a.replace(l,(r,t,d)=>{let i=m(),e=p(r,t,d),c=e.placeholder?`<div data-defer-placeholder>${e.placeholder}</div>`:"",s=e.loading?`<div data-defer-loading style="display: none;">${e.loading}</div>`:'<div data-defer-loading style="display: none;"></div>',f=e.error?`<div data-defer-error style="display: none;">${e.error}</div>`:"",u=`<div data-defer-content style="display: none;">${e.content}</div>`,g=E(i,e);return`
75
+ `}function y(a,n,o){h=0;let l=/@defer\s*\(([^)]*)\)\s*([\s\S]*?)@enddefer/g;return a.replace(l,(r,t,d)=>{let i=m(),e=p(r,t,d),c=e.placeholder?`<div data-defer-placeholder>${e.placeholder}</div>`:"",s=e.loading?`<div data-defer-loading style="display: none;">${e.loading}</div>`:'<div data-defer-loading style="display: none;"></div>',f=e.error?`<div data-defer-error style="display: none;">${e.error}</div>`:"",u=`<div data-defer-content style="display: none;">${e.content}</div>`,g=E(i,e);return`
76
76
  <div id="${i}" class="stx-defer" data-defer-trigger="${e.trigger}">
77
77
  ${c}
78
78
  ${s}
@@ -81,4 +81,4 @@ else {
81
81
  </div>
82
82
  ${g}
83
83
  `})}
84
- export{$ as we};
84
+ export{y as we};
@@ -0,0 +1,70 @@
1
+ // @bun
2
+ import{Zu as G}from"./chunk-nf3kv7kv.js";import{existsSync as Zt,statSync as Xt}from"fs";import{existsSync as On}from"fs";import{resolve as ve}from"path";import Rn from"process";import{existsSync as St,mkdirSync as Dn,readdirSync as Mn,readFileSync as Ln,writeFileSync as jn}from"fs";import{homedir as oe}from"os";import{dirname as Qt,resolve as I}from"path";import ie from"process";import{existsSync as er,statSync as tr}from"fs";import{existsSync as Tt,mkdirSync as Bn,readdirSync as In,writeFileSync as _n}from"fs";import{homedir as ae}from"os";import{dirname as rr,resolve as L}from"path";import se from"process";import{join as Kn,relative as Vn,resolve as nr}from"path";import ze from"process";import{existsSync as Gr,mkdirSync as mo,readdirSync as po,writeFileSync as yo}from"fs";import{homedir as ot}from"os";import{dirname as $o,resolve as M}from"path";import Ce from"process";import{join as Wn,relative as zn,resolve as ir}from"path";import Ue from"process";import{existsSync as qr,mkdirSync as So,readdirSync as To,writeFileSync as ko}from"fs";import{dirname as Fo,resolve as Je}from"path";import kt from"process";import{Buffer as ee}from"buffer";import{createCipheriv as Un,createDecipheriv as Jn,randomBytes as at}from"crypto";import{closeSync as ct,createReadStream as sr,createWriteStream as Gn,existsSync as lt,fsyncSync as or,openSync as ar,writeFileSync as qn}from"fs";import{access as Yn,constants as cr,mkdir as Hn,readdir as Se,rename as lr,stat as ce,unlink as Te,writeFile as ft}from"fs/promises";import{join as le}from"path";import N from"process";import{pipeline as Zn}from"stream/promises";import{createGzip as fr}from"zlib";import fe from"process";import H from"process";import{Buffer as q}from"buffer";import{createCipheriv as Xn,createDecipheriv as Qn,randomBytes as ut}from"crypto";import{closeSync as gt,createReadStream as ur,createWriteStream as ei,existsSync as ke,fsyncSync as gr,openSync as hr,writeFileSync as ti}from"fs";import{access as ri,constants as mr,mkdir as ni,readdir as Ae,rename as dr,stat as ue,unlink as Fe,writeFile as ht}from"fs/promises";import{isAbsolute as ii,join as ge,resolve as si}from"path";import p from"process";import{pipeline as oi}from"stream/promises";import{createGzip as pr}from"zlib";import he from"process";import Z from"process";import Oe from"process";import{existsSync as Re}from"fs";import{resolve as mt}from"path";import{existsSync as ai}from"fs";import{existsSync as ci,readdirSync as li}from"fs";import{extname as dt,resolve as yr}from"path";import fi from"process";import{join as ui,relative as gi,resolve as wr}from"path";import Ge from"process";import{Buffer as Y}from"buffer";import{createCipheriv as hi,createDecipheriv as mi,randomBytes as pt}from"crypto";import{closeSync as yt,createReadStream as vr,createWriteStream as di,existsSync as Ne,fsyncSync as $r,openSync as Cr,writeFileSync as pi}from"fs";import{access as yi,constants as Er,mkdir as wi,readdir as Pe,rename as br,stat as me,unlink as De,writeFile as wt}from"fs/promises";import{isAbsolute as vi,join as de,resolve as $i}from"path";import y from"process";import{pipeline as Ci}from"stream/promises";import{createGzip as xr}from"zlib";import pe from"process";import X from"process";import Le from"process";import{existsSync as je}from"fs";import{resolve as Br}from"path";import{existsSync as Vs}from"fs";import{existsSync as Gs,readdirSync as qs}from"fs";import{extname as xt,resolve as _r}from"path";import Ys from"process";var Tn=import.meta.require;class Kr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Zt(e))return!0;return Xt(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Zt(r)?Xt(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Vr{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var We=new Kr,Bt=new Vr;function kn(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function An(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Fn(e){return e.getStats().size*2}var Zs={createKey:kn,isEquivalent:An,estimateMemoryUsage:Fn},Wr=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function zr(e={}){let{name:t="",alias:r}=e,n=["config",".config"];if(t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let i=r===void 0?[]:Array.isArray(r)?r:[r];for(let s of i){if(!s)continue;if(n.push(s,`.${s}.config`,`${s}.config`,`.${s}`),t)n.push(`${t}.${s}.config`,`.${t}.${s}.config`)}return Array.from(new Set(n.filter(Boolean)))}function Ur(e){return zr(e).flatMap((r)=>Wr.map((n)=>ve(e.directory,`${r}${n}`)))}function Jr(e={}){let t=ve(e.cwd||Rn.cwd());return Array.from(new Set([t,ve(t,"config"),ve(t,".config"),e.configDir?ve(t,e.configDir):void 0].filter((r)=>Boolean(r))))}function Nn(e={}){return Jr(e).flatMap((t)=>Ur({directory:t,name:e.name,alias:e.alias}))}function Pn(e={}){return Nn(e).find((t)=>On(t))??null}function to(e={}){return Pn(e)!==null}var Ei=Object.defineProperty,bi=(e)=>e;function xi(e,t){this[e]=bi.bind(null,t)}var Si=(e,t)=>{for(var r in t)Ei(e,r,{get:t[r],enumerable:!0,configurable:!0,set:xi.bind(t,r)})},Ti=(e,t)=>()=>(e&&(t=e(e=0)),t),Yr={};Si(Yr,{withErrorRecovery:()=>Xr,tryLoadConfig:()=>Yi,loadConfigWithResult:()=>Gi,loadConfig:()=>nn,isRetryableError:()=>Ki,isConfigNotFoundError:()=>_i,isBunfigError:()=>Qr,globalPerformanceMonitor:()=>xe,globalCache:()=>ye,getEnvOrDefault:()=>Vi,generateConfigTypes:()=>Hi,defaultGeneratedDir:()=>gn,defaultConfigDir:()=>un,deepMergeWithArrayStrategy:()=>Wt,deepMerge:()=>en,createLibraryConfig:()=>Zi,config:()=>qi,bunfigPlugin:()=>Xi,applyEnvVarsToConfig:()=>$e,TypeGenerationError:()=>Dt,SchemaValidationError:()=>be,PluginError:()=>Lt,PerformanceMonitor:()=>_t,FileSystemError:()=>Pt,ErrorFactory:()=>re,EnvVarError:()=>Qe,EnvProcessor:()=>nt,ConfigValidator:()=>zt,ConfigValidationError:()=>Rt,ConfigNotFoundError:()=>Xe,ConfigMergeError:()=>Nt,ConfigLoader:()=>Ut,ConfigLoadError:()=>Ee,ConfigFileLoader:()=>it,ConfigCache:()=>It,CacheUtils:()=>on,BunfigError:()=>B,BrowserConfigError:()=>Mt,ArrayMergeStrategies:()=>ln});class It{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!er(e))return!0;return tr(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=er(r)?tr(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class _t{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function ki(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function Ai(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Fi(e){return e.getStats().size*2}function Kt(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&x(t[0])&&"id"in t[0]&&t[0].id===3&&x(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(x(t)&&x(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(x(e)&&"arr"in e&&Array.isArray(e.arr)&&x(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&x(t[0])&&x(e[0])){let n=[...t];for(let i of e)if(x(i)&&"name"in i){if(!n.find((o)=>x(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(x(i)&&"path"in i){if(!n.find((o)=>x(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>qe(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!x(t)||!x(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(x(i)&&x(r[n]))r[n]=Kt(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&x(i[0])&&x(r[n][0])){let s=[...i];for(let o of r[n])if(x(o)&&"name"in o){if(!s.find((a)=>x(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(x(o)&&"path"in o){if(!s.find((a)=>x(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>qe(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function qe(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!qe(e[r],t[r]))return!1;return!0}if(x(e)&&x(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!qe(e[i],t[i]))return!1}return!0}return!1}function x(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Oi(e,t){if(!qr(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Kt(t,n)}catch{return null}}catch{return null}}async function Ri({name:e="",cwd:t,defaultConfig:r}){let n=t||kt.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=Je(n,`${o}${c}`),l=await Oi(a,r);if(l!==null)return l}try{let o=Je(n,"package.json");if(qr(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Kt(r,a)}catch{}}}catch{}return r}function Ni(e,t={}){let r=Ue.cwd();while(r.includes("storage"))r=ir(r,"..");let n=ir(r,e||"");if(t?.relative)return zn(Ue.cwd(),n);return n}async function Pi(){try{let e=await Ri({name:"clarity",defaultConfig:Ie,cwd:Ue.cwd(),endpoint:"",headers:{}});return{...Ie,...e}}catch{return Ie}}function S(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Di(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof H<"u"){let e=H.type;if(e==="renderer"||e==="worker")return!1;return!!(H.versions&&(H.versions.node||H.versions.bun))}return!1}class Hr{async format(e){let t=await Di(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:fe.pid,hostname:t(),environment:fe.env.NODE_ENV||"development",platform:fe.platform,version:fe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:fe.env.NODE_ENV||fe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ye{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Ft},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Hr,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{..._e,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{..._e};return{..._e,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ft.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await Yn(this.config.logDirectory,cr.F_OK|cr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Hn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ee.from(e);try{if(!lt(this.currentLogFile))await ft(this.currentLogFile,"",{mode:420});if(i=ar(this.currentLogFile,"a",420),qn(i,a,{flag:"a"}),or(i),i!==void 0)ct(i),i=void 0;if((await ce(this.currentLogFile)).size===0){if(await ft(this.currentLogFile,a,{flag:"w",mode:420}),(await ce(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{ct(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return le(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return le(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return le(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return at(16).toString("hex")}generateKey(){return at(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=at(16),n=Un("aes-256-gcm",t,r),i=ee.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:ee.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=fr(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(ee.from(ee.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(S())return;let e=await ce(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Se(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ce(r).catch(()=>null))try{if(await lr(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Te(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ft(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ce(r).catch(()=>null))await lr(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Se(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Te(le(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=sr(e),n=Gn(t),i=fr();await Zn(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),lt(this.currentLogFile))try{let e=ar(this.currentLogFile,"r+");or(e),ct(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Se(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Te(le(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?b.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=N.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${b.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!S()){let l=an[e],f=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:b.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:b.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.error(u),c){let h=c.split(`
3
+ `);for(let g of h)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:b.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
4
+ `;if(c)a+=`${c}
5
+ `;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!S()){let r=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:b.blue("\u25D0"),tag:r,message:`${b.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
6
+ `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!S()){let f=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:b.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!S())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ye(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(S())throw Error("createReadStream is not supported in browser environments");if(!lt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return sr(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ee.isBuffer(e)?e:ee.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=Jn("aes-256-gcm",r,i);return c.setAuthTag(s),ee.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S()}isServerMode(){return!S()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!S()){let s=e.split(`
7
+ `),o=Math.max(...s.map((f)=>f.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,a=`\u2514${"\u2500".repeat(o)}\u2518`,l=s.map((f)=>{let u=" ".repeat(o-f.length-2);return`\u2502 ${f}${u} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:b.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:b.cyan(c)})),l.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:r,message:b.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:b.cyan(a),showTimestamp:!1}))}else if(!S())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(S())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${b.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();N.stdin.removeListener("data",r);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let f=t[c++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!S()){let o=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",c=b.blue("\u25D0");console.error(`${c} ${o} ${b.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||S()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=b.green("\u2501".repeat(n)),o=b.gray("\u2501".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=t||r===100?b.green("\u2713"):b.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=N.stdout.columns||80,C=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${C}`,N.stdout.write(e.lastRenderedLine),t)N.stdout.write(`
10
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Se(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=le(this.config.logDirectory,n);if(e.before)try{if((await ce(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Te(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Be(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&E(t[0])&&"id"in t[0]&&t[0].id===3&&E(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(E(t)&&E(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(E(e)&&"arr"in e&&Array.isArray(e.arr)&&E(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&E(t[0])&&E(e[0])){let n=[...t];for(let i of e)if(E(i)&&"name"in i){if(!n.find((o)=>E(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(E(i)&&"path"in i){if(!n.find((o)=>E(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>He(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!E(t)||!E(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(E(i)&&E(r[n]))r[n]=Be(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&E(i[0])&&E(r[n][0])){let s=[...i];for(let o of r[n])if(E(o)&&"name"in o){if(!s.find((a)=>E(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(E(o)&&"path"in o){if(!s.find((a)=>E(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>He(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function Vt(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Be(e,t);if(Array.isArray(e))return r==="replace"?t:Be(e,t);if(!E(t)||!E(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=Be(o,s);else if(E(s)&&E(o))n[i]=Vt(o,s,r);else n[i]=s}return n}function He(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!He(e[r],t[r]))return!1;return!0}if(E(e)&&E(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!He(e[i],t[i]))return!1}return!0}return!1}function E(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Me(e,t,r="replace"){if(!Gr(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Vt(t,i,r)}catch{return null}}catch{return null}}function Mi(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=(m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase(),g=`${n}_${u.map(h).join("_")}`,C=`${n}_${u.map((m)=>m.toUpperCase()).join("_")}`;if(r)D.info(`Checking environment variable ${g} for config ${e}.${u.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))a[l]=s(f,u);else{let m=Ce.env[g]||Ce.env[C];if(m!==void 0){if(r)D.info(`Using environment variable ${m?g:C} for config ${e}.${u.join(".")}`);if(typeof f==="number")a[l]=Number(m);else if(typeof f==="boolean")a[l]=m.toLowerCase()==="true";else if(Array.isArray(f))try{let d=JSON.parse(m);if(Array.isArray(d))a[l]=d;else a[l]=m.split(",").map((R)=>R.trim())}catch{a[l]=m.split(",").map((d)=>d.trim())}else a[l]=m}}}return a}return s(i)}async function Li({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?Mi(e,i,s):i,l=r||Ce.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(s)D.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let u=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),g=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],m=Array.from(new Set([l,M(l,"config"),M(l,".config"),n?M(l,n):void 0].filter(Boolean)));for(let d of m){if(s)D.info(`Searching for configuration in: ${d}`);let T=[M(l,"config"),M(l,".config")].concat(n?[M(l,n)]:[]).includes(d)?[...u,...h,...g,...C]:[...h,...u,...C,...g];for(let z of T)for(let j of f){let U=M(d,`${z}${j}`),Ht=await Me(U,a,c);if(Ht!==null){if(s)D.success(`Configuration loaded from: ${U}`);return Ht}}}if(e){let d=M(ot(),".config",e),R=["config",`${e}.config`];if(t)R.push(`${t}.config`);if(s)D.info(`Checking user config directory: ${d}`);for(let T of R)for(let z of f){let j=M(d,`${T}${z}`),U=await Me(j,a,c);if(U!==null){if(s)D.success(`Configuration loaded from user config directory: ${j}`);return U}}}if(e){let d=M(ot(),".config"),R=[`.${e}.config`];if(t)R.push(`.${t}.config`);if(s)D.info(`Checking user config directory for dotfile configs: ${d}`);for(let T of R)for(let z of f){let j=M(d,`${T}${z}`),U=await Me(j,a,c);if(U!==null){if(s)D.success(`Configuration loaded from user config directory dotfile: ${j}`);return U}}}if(e){let d=ot(),R=[`.${e}.config`,`.${e}`];if(t)R.push(`.${t}.config`),R.push(`.${t}`);if(s)D.info(`Checking user home directory for dotfile configs: ${d}`);for(let T of R)for(let z of f){let j=M(d,`${T}${z}`),U=await Me(j,a,c);if(U!==null){if(s)D.success(`Configuration loaded from user home directory: ${j}`);return U}}}try{let d=M(l,"package.json");if(Gr(d)){let R=await import(d),T=R[e];if(!T&&t){if(T=R[t],T&&s)D.success(`Using alias "${t}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(s)D.success(`Configuration loaded from package.json: ${T===R[e]?e:t}`);return Vt(a,T,c)}catch(z){if(s)D.warn("Failed to merge package.json config:",z)}}}catch(d){if(s)D.warn("Failed to load package.json:",d)}if(s)D.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function ji(e,t={}){let r=ze.cwd();while(r.includes("storage"))r=nr(r,"..");let n=nr(r,e||"");if(t?.relative)return Vn(ze.cwd(),n);return n}async function Bi(){try{let e=await Li({name:"clarity",alias:"logging",defaultConfig:Ke,cwd:ze.cwd()});return{...Ke,...e||{}}}catch{return Ke}}function k(){if(Z.env.NODE_ENV==="test"||Z.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ii(){if(Z.env.NODE_ENV==="test"||Z.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z<"u"){let e=Z.type;if(e==="renderer"||e==="worker")return!1;return!!(Z.versions&&(Z.versions.node||Z.versions.bun))}return!1}class Zr{async format(e){let t=await Ii(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:he.pid,hostname:t(),environment:he.env.NODE_ENV||"development",platform:he.platform,version:he.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:he.env.NODE_ENV||he.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ze{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Ot},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Zr,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??p.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ve,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ve};return{...Ve,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ot.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!k()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await ri(this.config.logDirectory,mr.F_OK|mr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await ni(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:q.from(e);try{if(!ke(this.currentLogFile))await ht(this.currentLogFile,"",{mode:420});if(i=hr(this.currentLogFile,"a",420),ti(i,a,{flag:"a"}),gr(i),i!==void 0)gt(i),i=void 0;if((await ue(this.currentLogFile)).size===0){if(await ht(this.currentLogFile,a,{flag:"w",mode:420}),(await ue(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{gt(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ge(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ge(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ge(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(k())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ut(16).toString("hex")}generateKey(){return ut(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=ut(16),n=Xn("aes-256-gcm",t,r),i=q.isBuffer(e)?e:q.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=q.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=pr(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(q.from(q.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(k())return;if(!this.shouldWriteToFile())return;let e=await ue(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Ae(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ue(r).catch(()=>null))try{if(await dr(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Fe(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ht(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ue(r).catch(()=>null))await dr(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Ae(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Fe(ge(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=ur(e),n=ei(t),i=pr();await oi(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ke(this.currentLogFile))try{let e=hr(this.currentLogFile,"r+");gr(e),gt(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ae(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Fe(ge(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?w.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||k())return!1;let e=typeof p.env.NO_COLOR<"u",t=p.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof p.stderr<"u"&&p.stderr.isTTY||typeof p.stdout<"u"&&p.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=p.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${w.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=w.underline(w.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>w.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>w.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>w.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>w.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>w.strikethrough(n)),t}supportsHyperlinks(){if(k())return!1;let e=p.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=p.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ii(t)||t.startsWith("./")||t.startsWith("../"))t=si(t);else return null;return ke(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":cn[e],h=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:w.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:w.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.error(g),c){let C=c.split(`
11
+ `);for(let m of C)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:w.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
12
+ `;if(c)f+=`${c}
13
+ `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!k()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!k()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!k()&&p.stdout.isTTY)p.stdout.write(`
14
+ `);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!k()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":w.blue("\u25D0"),tag:r,message:`${w.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
15
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":w.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!k())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ze(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(k())throw Error("createReadStream is not supported in browser environments");if(!ke(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ur(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=q.isBuffer(e)?e:q.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=Qn("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),f=a.length+l.length,u=q.allocUnsafe(f);return a.copy(u,0),l.copy(u,a.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return k()}isServerMode(){return!k()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
16
+ `),a=Math.max(...c.map((h)=>h.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,f=`\u2514${"\u2500".repeat(a)}\u2518`,u=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:w.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:w.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:w.cyan(f),showTimestamp:!1}))}else if(!k())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(k())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${w.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();p.stdin.removeListener("data",r);try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!1)}catch{}p.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!0)}catch{}p.stdin.resume(),p.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${w.blue("\u25D0")} `;console.error(`${l}${a} ${w.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!p.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=w.green("\u2501".repeat(n)),o=w.gray("\u2501".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?w.green("\u2713"):w.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=p.stdout.columns||80,C=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${C}`,p.stdout.write(e.lastRenderedLine),t)p.stdout.write(`
19
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||k()||!p.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ae(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=ge(this.config.logDirectory,n);if(e.before)try{if((await ue(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Fe(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Xr(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Qr(e){return e instanceof B}function _i(e){return e instanceof Xe}function Ki(e){if(Qr(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class nt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=n||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return xe.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((f)=>this.formatEnvKey(f,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let f=Oe.env[a]||(l?Oe.env[l]:void 0);if(f!==void 0){if(n.verbose){let u=Oe.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(f,typeof s,a,n.customParsers,n.configName)}catch(u){if(u instanceof Qe)throw u;throw re.envVar(a,f,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw re.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Oe.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
20
+
21
+ `;for(let n of e)r+=`${n.key}
22
+ `,r+=` Type: ${n.type}
23
+ `,r+=` Description: ${n.description}
24
+ `,r+=` Example: ${n.example}
25
+
26
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
27
+
28
+ `;r+=`| Variable | Type | Description | Example |
29
+ `,r+=`|----------|------|-------------|----------|
30
+ `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
31
+ `;return r}}function Vi(e,t){let r=sn("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function en(e,t,r={}){return tn(e,t,r,new WeakMap)}function tn(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return rn(e,t,i,n);if(!K(t)||!K(e))return t;return Ji(e,t,r,n)}function rn(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Wi(e,t);case"smart":return zi(e,t,n);default:return t}return t}function Wi(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>At(i,n)))r.push(n);return r}function zi(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(K(t[0])&&K(e[0]))return Ui(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Ui(e,t,r){let n=[...t];for(let i of e){if(!K(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>K(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function Ji(e,t,r,n){let i=t;if(K(i)&&n.has(i))return n.get(i);let s={...e};if(K(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(K(c)&&K(a))s[o]=tn(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=rn(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function Wt(e,t,r="replace"){return en(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function At(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!At(e[r],t[r]))return!1;return!0}if(K(e)&&K(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!At(e[i],t[i]))return!1}return!0}return!1}function K(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class it{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=ye.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Re(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,g=Object.keys(f).length>0;if(!h&&!g)throw new Ee(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Ee(e,Error("Configuration must export a valid object"),"unknown");let d={config:Wt(t,u,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)ye.setWithFileCheck("file",d,e,s);return d}catch(l){throw l instanceof Error?re.configLoad(e,l):re.configLoad(e,Error(String(l)))}};if(o)return xe.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(mt(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Xr(async()=>Re(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Re(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=mt(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=mt(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Re(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class zt{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(g){return f.push({path:"",message:`Validation failed: ${g}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(c)return await xe.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!ai(t))throw new be(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new be(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:fn},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ut{fileLoader=new it;envProcessor=new nt;validator=new zt;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let f=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),u=!f&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw a;if(u&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)J.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw J.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||se.cwd(),h=[],g=await this.loadLocalConfiguration(n,i,u,o,c,l,f,a,r);if(g)return h.push(...this.getLocalSearchPaths(n,i,u,o)),this.finalizeResult(g,h,a,n,f);let C=await this.loadHomeConfiguration(n,i,c,l,f,a);if(C)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(C,h,a,n,f);let m=await this.loadPackageJsonConfiguration(n,i,u,c,l,f,a);if(m)return h.push(L(u,"package.json")),this.finalizeResult(m,h,a,n,f);if(h.push(...this.getAllSearchPaths(n,i,u,o)),t)throw re.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,f),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?$e(e,i,o):i,f=this.getLocalDirectories(r,n);for(let u of f){if(o)J.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(g){if(o)J.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?$e(e,r,i):r,c=[L(ae(),".config",e),L(ae(),".config"),ae()];for(let a of c){if(i)J.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(f){if(i)J.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?$e(e,n,s):n;try{let a=L(r,"package.json");if(!Tt(a))return null;let l=await import(a),f=l[e],u=e;if(!f&&t)f=l[t],u=t;if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)J.success(`Configuration loaded from package.json: ${u}`);return{config:Wt(c,f,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)J.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw re.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ye.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);ye.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,L(e,"config"),L(e,".config"),t?L(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(L(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[L(ae(),".config",e),L(ae(),".config"),ae()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Sr(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function Gi(e){return Q.loadConfig({...e,__strictErrorHandling:!0})}async function nn(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Q.loadConfig(e);else n=await Q.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)J.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Q.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function qi(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Q.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Sr(r)))return(await Q.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Q.loadConfig({...e,cwd:e.cwd||se.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Sr(t)))return(await Q.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Yi(e,t,r="replace"){let n=new it;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function $e(e,t,r=!1){let n=new nt,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=[`${i}_${u.join("_").toUpperCase()}`,`${i}_${u.map((m)=>m.toUpperCase()).join("")}`,`${i}_${u.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,C;for(let m of h)if(g=se.env[m],g!==void 0){C=m;break}if(g!==void 0&&C)if(typeof f==="boolean")a[l]=["true","1","yes"].includes(g.toLowerCase());else if(typeof f==="number"){let m=Number(g);if(!Number.isNaN(m))a[l]=m}else if(Array.isArray(f))try{a[l]=JSON.parse(g)}catch{a[l]=g.split(",").map((m)=>m.trim())}else a[l]=g;else if(f&&typeof f==="object"&&!Array.isArray(f))a[l]=s(f,u)}return a}return s(t)}function Hi(e){let t=L(se.cwd(),e.configDir),r=L(se.cwd(),e.generatedDir),n=L(r,"config-types.ts");if(!Tt(rr(n)))Bn(rr(n),{recursive:!0,mode:511});let i=Tt(t)?In(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${Ss}
32
+ export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
33
+ `;_n(n,s,{mode:438})}function Zi(e){let t=null,r=null,n=()=>{if(!r)r=nn(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)J.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function Xi(e){let t=yr(fi.cwd(),e?.configDir||"./config");function r(){if(!ci(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=li(t).filter((a)=>i.has(dt(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let f=dt(l).toLowerCase(),u=c.get(a);if(!u){c.set(a,l);continue}let h=dt(u).toLowerCase();if(s.indexOf(f)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=i.length?`{
34
+ ${i.map((l)=>{let f=yr(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
35
+ `)}
36
+ }`:"Record<string, any>";return`export type ConfigNames = ${o}
37
+ export type ConfigByName = ${c}
38
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
+ export type ConfigOf = Config
40
+ `}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}var sn,ye,xe,on,Qi,es,Tr,Ie,Ft,P,b,ts,kr,rs,Ar,ns,is,vt,ss,Fr,Or,$t,os,as,cs,ls,_e,an,fs,D,us,gs,Rr,Ke,Ot,A,w,hs,Nr,ms,Pr,ds,ps,Ct,ys,Dr,Mr,ws,Et,vs,$s,Cs,Es,bs,Ve,cn,xs,Ss="0.15.6",B,Xe,Ee,Rt,Nt,Qe,Pt,Dt,be,Mt,Lt,re,ln,fn,J,Q,un,gn,Ts=Ti(async()=>{sn=import.meta.require,ye=new It,xe=new _t,on={createKey:ki,isEquivalent:Ai,estimateMemoryUsage:Fi},Qi=Je(kt.cwd(),"config"),es=Je(kt.cwd(),"src/generated"),Tr=Ue.env.CLARITY_LOG_DIR||Wn(Ni(),"logs"),Ie={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Tr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ft=await Pi(),P={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},b=P,ts=P.red,kr=P.green,rs=P.yellow,Ar=P.blue,ns=P.magenta,is=P.cyan,vt=P.white,ss=P.gray,Fr=P.bgRed,Or=P.bgYellow,$t=P.bold,os=P.dim,as=P.italic,cs=P.underline,ls=P.reset,_e={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},an={debug:"\uD83D\uDD0D",info:Ar("\u2139"),success:kr("\u2713"),warning:Or(vt($t(" WARN "))),error:Fr(vt($t(" ERROR ")))},fs=new Ye("stacks"),D=new Ye("bunfig",{showTags:!0}),us=M(Ce.cwd(),"config"),gs=M(Ce.cwd(),"src/generated"),Rr=ze.env.CLARITY_LOG_DIR||Kn(ji(),"logs"),Ke={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ot=await Bi(),A={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},w=A,hs=A.red,Nr=A.green,ms=A.yellow,Pr=A.blue,ds=A.magenta,ps=A.cyan,Ct=A.white,ys=A.gray,Dr=A.bgRed,Mr=A.bgYellow,ws=A.bgGray,Et=A.bold,vs=A.dim,$s=A.italic,Cs=A.underline,Es=A.strikethrough,bs=A.reset,Ve={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cn={debug:"\uD83D\uDD0D",info:Pr("\u2139"),success:Nr("\u2713"),warning:Mr(Ct(Et(" WARN "))),error:Dr(Ct(Et(" ERROR ")))},xs=new Ze("stacks"),B=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Xe=class extends B{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},Ee=class extends B{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Rt=class extends B{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Nt=class extends B{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Qe=class extends B{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},Pt=class extends B{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Dt=class extends B{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},be=class extends B{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Mt=class extends B{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},Lt=class extends B{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},re={configNotFound(e,t,r){return new Xe(e,t,r)},configLoad(e,t,r){return new Ee(e,t,r)},configValidation(e,t,r){return new Rt(e,t,r)},configMerge(e,t,r,n){return new Nt(e,t,r,n)},envVar(e,t,r,n){return new Qe(e,t,r,n)},fileSystem(e,t,r){return new Pt(e,t,r)},typeGeneration(e,t,r){return new Dt(e,t,r)},schemaValidation(e,t,r){return new be(e,t,r)},browserConfig(e,t,r,n){return new Mt(e,t,r,n)},plugin(e,t,r){return new Lt(e,t,r)}},ln={replace:"replace",concat:"concat",smart:"smart"},fn=/^https?:\/\//,J=new Ze("bunfig",{showTags:!0}),Q=new Ut,un=L(se.cwd(),"config"),gn=L(se.cwd(),"src/generated")});function ks(e,t={}){let r=Ge.cwd();while(r.includes("storage"))r=wr(r,"..");let n=wr(r,e||"");if(t?.relative)return gi(Ge.cwd(),n);return n}var As=Ge.env.CLARITY_LOG_DIR||ui(ks(),"logs"),hn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:As,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},et={...hn},pa=(async()=>{try{let{loadConfig:e}=await Ts().then(()=>Yr),t=await e({name:"clarity",alias:"logging",defaultConfig:hn,cwd:Ge.cwd()});if(t)Object.assign(et,t)}catch{}return et})();function F(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Fs(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X<"u"){let e=X.type;if(e==="renderer"||e==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class mn{async format(e){let t=await Fs(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:pe.pid,hostname:t(),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}}}var O={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},v=O,ya=O.red,Os=O.green,wa=O.yellow,Rs=O.blue,va=O.magenta,$a=O.cyan,Lr=O.white,Ca=O.gray,Ns=O.bgRed,Ps=O.bgYellow,Ea=O.bgGray,jr=O.bold,ba=O.dim,xa=O.italic,Sa=O.underline,Ta=O.strikethrough,ka=O.reset,bt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ds={debug:"\uD83D\uDD0D",info:Rs("\u2139"),success:Os("\u2713"),warning:Ps(Lr(jr(" WARN "))),error:Ns(Lr(jr(" ERROR ")))};class st{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...et},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new mn,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??y.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...bt,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...bt};return{...bt,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:et.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!F()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await yi(this.config.logDirectory,Er.F_OK|Er.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await wi(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Y.from(e);try{if(!Ne(this.currentLogFile))await wt(this.currentLogFile,"",{mode:420});if(i=Cr(this.currentLogFile,"a",420),pi(i,a,{flag:"a"}),$r(i),i!==void 0)yt(i),i=void 0;if((await me(this.currentLogFile)).size===0){if(await wt(this.currentLogFile,a,{flag:"w",mode:420}),(await me(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{yt(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return de(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 de(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return de(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(F())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return pt(16).toString("hex")}generateKey(){return pt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=pt(16),n=hi("aes-256-gcm",t,r),i=Y.isBuffer(e)?e:Y.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=Y.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=xr(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Y.from(Y.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(F())return;if(!this.shouldWriteToFile())return;let e=await me(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Pe(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await me(r).catch(()=>null))try{if(await br(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await De(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await wt(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await me(r).catch(()=>null))await br(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Pe(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await De(de(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=vr(e),n=di(t),i=xr();await Ci(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Ne(this.currentLogFile))try{let e=Cr(this.currentLogFile,"r+");$r(e),yt(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!F()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Pe(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await De(de(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?v.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F())return!1;let e=typeof y.env.NO_COLOR<"u",t=y.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof y.stderr<"u"&&y.stderr.isTTY||typeof y.stdout<"u"&&y.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=y.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${v.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=v.underline(v.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>v.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>v.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>v.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>v.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>v.strikethrough(n)),t}supportsHyperlinks(){if(F())return!1;let e=y.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=y.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(vi(t)||t.startsWith("./")||t.startsWith("../"))t=$i(t);else return null;return Ne(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Ds[e],h=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:v.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:v.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.error(g),c){let C=c.split(`
41
+ `);for(let m of C)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:v.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!F()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
42
+ `;if(c)f+=`${c}
43
+ `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!F()&&y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!F()&&y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!F()&&y.stdout.isTTY)y.stdout.write(`
44
+ `);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!F()&&y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":v.blue("\u25D0"),tag:r,message:`${v.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
45
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":v.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!F())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new st(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(F())throw Error("createReadStream is not supported in browser environments");if(!Ne(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return vr(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Y.isBuffer(e)?e:Y.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=mi("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),f=a.length+l.length,u=Y.allocUnsafe(f);return a.copy(u,0),l.copy(u,a.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F()}isServerMode(){return!F()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
46
+ `),a=Math.max(...c.map((h)=>h.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,f=`\u2514${"\u2500".repeat(a)}\u2518`,u=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:v.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:v.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:v.cyan(f),showTimestamp:!1}))}else if(!F())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(F())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${v.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();y.stdin.removeListener("data",r);try{if(typeof y.stdin.setRawMode==="function")y.stdin.setRawMode(!1)}catch{}y.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof y.stdin.setRawMode==="function")y.stdin.setRawMode(!0)}catch{}y.stdin.resume(),y.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${v.blue("\u25D0")} `;console.error(`${l}${a} ${v.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!y.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=v.green("\u2501".repeat(n)),o=v.gray("\u2501".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?v.green("\u2713"):v.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=y.stdout.columns||80,C=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${C}`,y.stdout.write(e.lastRenderedLine),t)y.stdout.write(`
49
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||F()||!y.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(F()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Pe(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=de(this.config.logDirectory,n);if(e.before)try{if((await me(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await De(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var Aa=new st("stacks");class W extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class Jt extends W{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class tt extends W{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class dn extends W{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class pn extends W{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Gt extends W{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}}class yn extends W{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class wn extends W{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class rt extends W{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class vn extends W{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}}class $n extends W{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var ne={configNotFound(e,t,r){return new Jt(e,t,r)},configLoad(e,t,r){return new tt(e,t,r)},configValidation(e,t,r){return new dn(e,t,r)},configMerge(e,t,r,n){return new pn(e,t,r,n)},envVar(e,t,r,n){return new Gt(e,t,r,n)},fileSystem(e,t,r){return new yn(e,t,r)},typeGeneration(e,t,r){return new wn(e,t,r)},schemaValidation(e,t,r){return new rt(e,t,r)},browserConfig(e,t,r,n){return new vn(e,t,r,n)},plugin(e,t,r){return new $n(e,t,r)}};async function Ms(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Ls(e){return e instanceof W}function Fa(e){return e instanceof Jt}function Oa(e){if(Ls(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class qt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=n||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Bt.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((f)=>this.formatEnvKey(f,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let f=Le.env[a]||(l?Le.env[l]:void 0);if(f!==void 0){if(n.verbose){let u=Le.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(f,typeof s,a,n.customParsers,n.configName)}catch(u){if(u instanceof Gt)throw u;throw ne.envVar(a,f,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw ne.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Le.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
50
+
51
+ `;for(let n of e)r+=`${n.key}
52
+ `,r+=` Type: ${n.type}
53
+ `,r+=` Description: ${n.description}
54
+ `,r+=` Example: ${n.example}
55
+
56
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
57
+
58
+ `;r+=`| Variable | Type | Description | Example |
59
+ `,r+=`|----------|------|-------------|----------|
60
+ `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
61
+ `;return r}}function Da(e,t){let r=Tn("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}var Ma={replace:"replace",concat:"concat",smart:"smart"};function js(e,t,r={}){return Cn(e,t,r,new WeakMap)}function Cn(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return En(e,t,i,n);if(!V(t)||!V(e))return t;return Ks(e,t,r,n)}function En(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Bs(e,t);case"smart":return Is(e,t,n);default:return t}return t}function Bs(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>jt(i,n)))r.push(n);return r}function Is(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(V(t[0])&&V(e[0]))return _s(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function _s(e,t,r){let n=[...t];for(let i of e){if(!V(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>V(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function Ks(e,t,r,n){let i=t;if(V(i)&&n.has(i))return n.get(i);let s={...e};if(V(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(V(c)&&V(a))s[o]=Cn(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=En(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function bn(e,t,r="replace"){return js(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function jt(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!jt(e[r],t[r]))return!1;return!0}if(V(e)&&V(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!jt(e[i],t[i]))return!1}return!0}return!1}function V(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Yt{extensions=Wr;async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=We.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!je(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,g=Object.keys(f).length>0;if(!h&&!g)throw new tt(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new tt(e,Error("Configuration must export a valid object"),"unknown");let d={config:bn(t,u,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)We.setWithFileCheck("file",d,e,s);return d}catch(l){throw l instanceof Error?ne.configLoad(e,l):ne.configLoad(e,Error(String(l)))}};if(o)return Bt.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){return Ur({name:e,directory:t,alias:r})}generateNamePatterns(e,t){return zr({name:e,alias:t})}checkFileAccess(e){return Ms(async()=>je(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!je(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=Br(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=Br(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!je(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}var Ws=/^https?:\/\//;class xn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(g){return f.push({path:"",message:`Validation failed: ${g}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(c)return await Bt.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Vs(t))throw new rt(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new rt(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Ws},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var zs="0.15.17",_=new st("bunfig",{showTags:!0});function Us(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Sn{fileLoader=new Yt;envProcessor=new qt;validator=new xn;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){if(o.configFile)throw a;let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let f=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),u=!f&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw a;if(u&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)_.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw _.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,configFile:s,cwd:o,configDir:c,defaultConfig:a,checkEnv:l=!0,arrayStrategy:f="replace",verbose:u=!1}=e,h=o||ie.cwd(),g=[];if(s){let T=I(h,s);g.push(T);let z=l?we(n,a,u):a,j=await this.fileLoader.tryLoadFromPaths([T],z,{arrayStrategy:f,verbose:u,cacheTtl:r?.ttl,useCache:!r?.ttl||r.ttl>100});if(!j)throw ne.configNotFound(n||s,g,i);if(u)_.success(`Configuration loaded from explicit path: ${T}`);return this.finalizeResult(j,g,l,n,u)}let C=await this.loadLocalConfiguration(n,i,h,c,a,f,u,l,r);if(C)return g.push(...this.getLocalSearchPaths(n,i,h,c)),this.finalizeResult(C,g,l,n,u);let m=await this.loadHomeConfiguration(n,i,a,f,u,l);if(m)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(m,g,l,n,u);let d=await this.loadPackageJsonConfiguration(n,i,h,a,f,u,l);if(d)return g.push(I(h,"package.json")),this.finalizeResult(d,g,l,n,u);if(g.push(...this.getAllSearchPaths(n,i,h,c)),t)throw ne.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,a,l,u),warnings:[`No configuration file found for "${n}"${Us(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?we(e,i,o):i,f=this.getLocalDirectories(r,n);for(let u of f){if(o)_.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(g){if(o)_.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?we(e,r,i):r,c=[I(oe(),".config",e),I(oe(),".config"),oe()];for(let a of c){if(i)_.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(f){if(i)_.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?we(e,n,s):n;try{let a=I(r,"package.json");if(!St(a))return null;let l={};try{l=JSON.parse(Ln(a,"utf8"))}catch(h){if(s)_.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let f=l[e],u=e;if(!f&&t){let h=Array.isArray(t)?t:[t];for(let g of h){if(!g)continue;if(l[g]){f=l[g],u=g;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)_.success(`Configuration loaded from package.json: ${u}`);return{config:bn(c,f,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)_.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:we(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw ne.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return We.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);We.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configFile)r.push(`configFile:${t.configFile}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Jr({cwd:e,configDir:t})}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(I(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[I(oe(),".config",e),I(oe(),".config"),oe()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}var te=new Sn;function Ir(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function ja(e){return te.loadConfig({...e,__strictErrorHandling:!0})}async function Js(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await te.loadConfig(e);else n=await te.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){if(e.configFile)throw n;let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)_.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await te.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Ba(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await te.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Ir(r)))return(await te.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await te.loadConfig({...e,cwd:e.cwd||ie.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Ir(t)))return(await te.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Ia(e,t,r="replace"){let n=new Yt;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function we(e,t,r=!1){let n=new qt,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=[`${i}_${u.join("_").toUpperCase()}`,`${i}_${u.map((m)=>m.toUpperCase()).join("")}`,`${i}_${u.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,C;for(let m of h)if(g=ie.env[m],g!==void 0){C=m;break}if(g!==void 0&&C)if(typeof f==="boolean")a[l]=["true","1","yes"].includes(g.toLowerCase());else if(typeof f==="number"){let m=Number(g);if(!Number.isNaN(m))a[l]=m}else if(Array.isArray(f))try{a[l]=JSON.parse(g)}catch{a[l]=g.split(",").map((m)=>m.trim())}else a[l]=g;else if(f&&typeof f==="object"&&!Array.isArray(f))a[l]=s(f,u)}return a}return s(t)}var _a=I(ie.cwd(),"config"),Ka=I(ie.cwd(),"src/generated");function Va(e){let t=I(ie.cwd(),e.configDir),r=I(ie.cwd(),e.generatedDir),n=I(r,"config-types.ts");if(!St(Qt(n)))Dn(Qt(n),{recursive:!0,mode:511});let i=St(t)?Mn(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${zs}
62
+ export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
63
+ `;jn(n,s,{mode:438})}function Wa(e){let t="defaultConfig"in e?e.defaultConfig:{},r={...t},n=new Map,i=new Set,s=null,o=(a)=>{let l={...a};for(let[f,u]of n)l[f]=u;for(let f of i)delete l[f];return l};return(()=>{if(!s)s=Js(e).then((a)=>(r=o(a),r),(a)=>{if(r=o({...t}),"verbose"in e&&e.verbose)_.warn("Config loading failed, using defaults:",[a instanceof Error?a:Error(String(a))]);return r});return s})(),new Proxy({},{get(a,l){return r[l]},has(a,l){return l in r},ownKeys(){return Reflect.ownKeys(r)},getOwnPropertyDescriptor(a,l){let f=Object.getOwnPropertyDescriptor(r,l);if(f)f.configurable=!0;return f},set(a,l,f){return n.set(l,f),i.delete(l),r[l]=f,!0},deleteProperty(a,l){return i.add(l),n.delete(l),delete r[l],!0}})}function Ga(e){let t=_r(Ys.cwd(),e?.configDir||"./config");function r(){if(!Gs(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=qs(t).filter((a)=>i.has(xt(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let f=xt(l).toLowerCase(),u=c.get(a);if(!u){c.set(a,l);continue}let h=xt(u).toLowerCase();if(s.indexOf(f)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=i.length?`{
64
+ ${i.map((l)=>{let f=_r(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
65
+ `)}
66
+ }`:"Record<string, any>";return`export type ConfigNames = ${o}
67
+ export type ConfigByName = ${c}
68
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
69
+ export type ConfigOf = Config
70
+ `}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}export{Kr as _p,Vr as $p,We as aq,Bt as bq,Zs as cq,Wr as dq,zr as eq,Ur as fq,Jr as gq,Nn as hq,Pn as iq,to as jq,W as kq,Jt as lq,tt as mq,dn as nq,pn as oq,Gt as pq,yn as qq,wn as rq,rt as sq,vn as tq,$n as uq,ne as vq,Ms as wq,Ls as xq,Fa as yq,Oa as zq,qt as Aq,Da as Bq,Ma as Cq,js as Dq,bn as Eq,Yt as Fq,xn as Gq,Sn as Hq,ja as Iq,Js as Jq,Ba as Kq,Ia as Lq,we as Mq,_a as Nq,Ka as Oq,Va as Pq,Wa as Qq,Ga as Rq};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ var f=null,m=[],s=0,a=new Set;function b(){return f}function d(t){let r=f;return m.push(t),f=t,r}function h(t){m.pop(),f=t}function y(){return s>0}function g(t){a.add(t)}function D(t){s++;try{t()}finally{if(s--,s===0){let r=[...a];a.clear();for(let n of r)n()}}}function E(t){let r=f;f=null;try{return t()}finally{f=r}}var x=[],p=[];function A(t){let r=t,n=new Set,i=new Set,o=()=>{let e=b();if(e)i.add(e);return r};return o.set=(e)=>{if(!Object.is(e,r)){let c=r;if(r=e,n.forEach((u)=>u(r,c)),y())i.forEach((u)=>g(u));else i.forEach((u)=>u())}},o.update=(e)=>{o.set(e(r))},o.subscribe=(e)=>(n.add(e),()=>n.delete(e)),Object.defineProperty(o,"_isSignal",{value:!0,writable:!1}),Object.defineProperty(o,"value",{get:()=>o(),set:(e)=>o.set(e),configurable:!0}),o}function O(t){let r,n=!0,i=new Set,o=()=>{if(!n)if(n=!0,y())i.forEach((c)=>g(c));else i.forEach((c)=>c())},e=()=>{let c=b();if(c)i.add(c);if(n){let u=d(o);try{r=t()}finally{h(u)}n=!1}return r};return Object.defineProperty(e,"_isDerived",{value:!0,writable:!1}),Object.defineProperty(e,"value",{get:()=>e(),configurable:!0}),e}function j(t,r={}){let n,i=!1,o=()=>{if(i)return;if(n)n(),n=void 0;let e=d(o);try{let c=t();n=typeof c==="function"?c:void 0}finally{h(e)}};if(r.immediate!==!1)o();return()=>{if(i=!0,n)n()}}function q(t){D(t)}function T(t){x.push(t)}function L(t){p.push(t)}function z(){k(x,"onMount",p)}function F(){k(p,"onDestroy")}function k(t,r,n){let i=t.splice(0,t.length);for(let o of i)try{let e=o();if(n&&typeof e==="function")n.push(e)}catch(e){console.error(`[stx] ${r} callback threw:`,e)}}function G(){return{mount:x.length,destroy:p.length}}function B(t){return typeof t==="function"&&t._isSignal===!0}function C(t){return typeof t==="function"&&t._isDerived===!0}function H(t){if(B(t)||C(t))return t();return t}function P(t){return E(t)}function I(t,r){let n=typeof t==="function"?t:()=>t,i=A([]),o=O(()=>i().reduce((c,u)=>r(c,u.action),n())),e=!1;return j(()=>{if(n(),!e){e=!0;return}if(P(()=>i().length))i.set([])}),[o,(c,u)=>{let v={action:c};i.set([...i(),v]);let l=()=>{let S=i().filter((w)=>w!==v);if(S.length!==i().length)i.set(S)};if(u&&typeof u.then==="function")Promise.resolve(u).then(l,l);return l}]}
3
+ export{b as Ze,d as _e,h as $e,y as af,g as bf,A as cf,O as df,j as ef,q as ff,T as gf,L as hf,z as if,F as jf,G as kf,B as lf,C as mf,H as nf,P as of,I as pf};
@@ -1,10 +1,10 @@
1
1
  // @bun
2
- function L(v,c){let{itemHeight:a,containerHeight:g,overscan:l=3,keyProperty:x="id",dynamicHeight:d=!1,estimatedItemHeight:u=a,direction:w="vertical"}=c,e=[...v],t=0,n=new Map;function f(){if(d)return m();let i=Math.max(0,Math.floor(t/a)-l),r=Math.ceil(g/a),h=Math.min(e.length-1,i+r+l*2);return{startIndex:i,endIndex:h}}function m(){let i=0,r=0,h=e.length-1;for(let p=0;p<e.length;p++){let M=n.get(p)||u;if(i+M>t){r=Math.max(0,p-l);break}i+=M}i=0;for(let p=0;p<e.length;p++){let M=n.get(p)||u;if(i+=M,i>t+g){h=Math.min(e.length-1,p+l);break}}return{startIndex:r,endIndex:h}}function H(){if(d){let i=0;for(let r=0;r<e.length;r++)i+=n.get(r)||u;return i}return e.length*a}function y(i){if(d){let r=0;for(let h=0;h<i;h++)r+=n.get(h)||u;return r}return i*a}function I(){let{startIndex:i,endIndex:r}=f();return{startIndex:i,endIndex:r,scrollTop:t,totalHeight:H(),visibleItems:e.slice(i,r+1),itemHeights:new Map(n)}}function S(i,r="auto"){let h=y(i);s(h,r)}function s(i,r="auto"){t=Math.max(0,Math.min(i,H()-g))}function o(){f()}function b(i){e=[...i],n.clear(),o()}function $(){e=[],n.clear()}return{scrollToIndex:S,scrollToOffset:s,getState:I,refresh:o,setItems:b,destroy:$}}function T(v,c={},a){let g=/@virtualList\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@endvirtualList/gi;return v.replace(g,(l,x,d,u)=>{let w=x.trim(),e=c[w];if(!e||!Array.isArray(e))return`<!-- virtualList: items "${w}" not found or not an array -->`;let t={itemHeight:50,containerHeight:400,overscan:3};if(d)try{let s=d.trim(),o=Function(`return ${s}`)();t={...t,...o}}catch{}let n=`vlist-${Math.random().toString(36).substring(2,9)}`,f=Math.ceil(t.containerHeight/t.itemHeight),m=t.overscan||3,H=0,y=Math.min(e.length-1,f+m),I="";for(let s=H;s<=y&&s<e.length;s++){let o=e[s],b=u.replace(/\{\{\s*item\s*\}\}/g,typeof o==="object"?JSON.stringify(o):String(o)).replace(/\{\{\s*item\.(\w+)\s*\}\}/g,($,i)=>{if(typeof o==="object"&&o!==null)return String(o[i]??"");return""}).replace(/\{\{\s*index\s*\}\}/g,String(s));I+=`
2
+ function T(v,c){let{itemHeight:a,containerHeight:g,overscan:l=3,keyProperty:x="id",dynamicHeight:d=!1,estimatedItemHeight:u=a,direction:w="vertical"}=c,e=[...v],t=0,n=new Map;function f(){if(d)return m();let i=Math.max(0,Math.floor(t/a)-l),r=Math.ceil(g/a),h=Math.min(e.length-1,i+r+l*2);return{startIndex:i,endIndex:h}}function m(){let i=0,r=0,h=e.length-1;for(let p=0;p<e.length;p++){let L=n.get(p)||u;if(i+L>t){r=Math.max(0,p-l);break}i+=L}i=0;for(let p=0;p<e.length;p++){let L=n.get(p)||u;if(i+=L,i>t+g){h=Math.min(e.length-1,p+l);break}}return{startIndex:r,endIndex:h}}function H(){if(d){let i=0;for(let r=0;r<e.length;r++)i+=n.get(r)||u;return i}return e.length*a}function I(i){if(d){let r=0;for(let h=0;h<i;h++)r+=n.get(h)||u;return r}return i*a}function S(){let{startIndex:i,endIndex:r}=f();return{startIndex:i,endIndex:r,scrollTop:t,totalHeight:H(),visibleItems:e.slice(i,r+1),itemHeights:new Map(n)}}function M(i,r="auto"){let h=I(i);s(h,r)}function s(i,r="auto"){t=Math.max(0,Math.min(i,H()-g))}function o(){f()}function b(i){e=[...i],n.clear(),o()}function y(){e=[],n.clear()}return{scrollToIndex:M,scrollToOffset:s,getState:S,refresh:o,setItems:b,destroy:y}}function C(v,c={},a){let g=/@virtualList\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@endvirtualList/gi;return v.replace(g,(l,x,d,u)=>{let w=x.trim(),e=c[w];if(!e||!Array.isArray(e))return`<!-- virtualList: items "${w}" not found or not an array -->`;let t={itemHeight:50,containerHeight:400,overscan:3};if(d)try{let s=d.trim(),o=Function(`return ${s}`)();t={...t,...o}}catch{}let n=`vlist-${Math.random().toString(36).substring(2,9)}`,f=Math.ceil(t.containerHeight/t.itemHeight),m=t.overscan||3,H=0,I=Math.min(e.length-1,f+m),S="";for(let s=H;s<=I&&s<e.length;s++){let o=e[s],b=u.replace(/\{\{\s*item\s*\}\}/g,typeof o==="object"?JSON.stringify(o):String(o)).replace(/\{\{\s*item\.(\w+)\s*\}\}/g,(y,i)=>{if(typeof o==="object"&&o!==null)return String(o[i]??"");return""}).replace(/\{\{\s*index\s*\}\}/g,String(s));S+=`
3
3
  <div class="virtual-item ${t.itemClass||""}"
4
4
  style="position: absolute; top: ${s*t.itemHeight}px; height: ${t.itemHeight}px; width: 100%;"
5
5
  data-index="${s}">
6
6
  ${b}
7
- </div>`}let S=e.length*t.itemHeight;return`
7
+ </div>`}let M=e.length*t.itemHeight;return`
8
8
  <div id="${n}"
9
9
  class="virtual-list-container ${t.containerClass||""}"
10
10
  style="position: relative; height: ${t.containerHeight}px; overflow-y: auto;"
@@ -12,8 +12,8 @@ function L(v,c){let{itemHeight:a,containerHeight:g,overscan:l=3,keyProperty:x="i
12
12
  data-total-items="${e.length}"
13
13
  data-overscan="${m}">
14
14
  <div class="virtual-list-viewport ${t.viewportClass||""}"
15
- style="position: relative; height: ${S}px; width: 100%;">
16
- ${I}
15
+ style="position: relative; height: ${M}px; width: 100%;">
16
+ ${S}
17
17
  </div>
18
18
  </div>
19
19
  <script data-virtual-list="${n}">
@@ -76,7 +76,7 @@ function L(v,c){let{itemHeight:a,containerHeight:g,overscan:l=3,keyProperty:x="i
76
76
  };
77
77
  })();
78
78
  </script>
79
- `})}function R(){return`
79
+ `})}function k(){return`
80
80
  .virtual-list-container {
81
81
  position: relative;
82
82
  overflow-y: auto;
@@ -124,7 +124,7 @@ function L(v,c){let{itemHeight:a,containerHeight:g,overscan:l=3,keyProperty:x="i
124
124
  0% { background-position: 200% 0; }
125
125
  100% { background-position: -200% 0; }
126
126
  }
127
- `}function k(v,c){let a=null,g=()=>{if(!a)a=L(v(),c);return a};return{visibleItems:()=>{return g().getState().visibleItems},totalHeight:()=>{return g().getState().totalHeight},containerProps:()=>({style:{height:`${c.containerHeight}px`,overflow:"auto",position:"relative"},onScroll:(l)=>{let x=l.target;if(a)a.scrollToOffset(x.scrollTop)}}),itemProps:(l)=>({style:{position:"absolute",top:`${l*c.itemHeight}px`,height:`${c.itemHeight}px`,width:"100%"},"data-index":l}),scrollToIndex:(l)=>{g().scrollToIndex(l)}}}function N(v,c={},a){let g=/@infiniteList\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@loading\s*([\s\S]*?)@endinfiniteList/gi;return v.replace(g,(l,x,d,u,w)=>{let e=x.trim(),t=c[e];if(!t||!Array.isArray(t))return`<!-- infiniteList: items "${e}" not found or not an array -->`;let n={itemHeight:50,containerHeight:400,overscan:3,threshold:100,hasMore:!0};if(d)try{let H=Function(`return ${d.trim()}`)();n={...n,...H}}catch{}let f=`ilist-${Math.random().toString(36).substring(2,9)}`,m=T(`@virtualList(${e}, ${JSON.stringify({itemHeight:n.itemHeight,containerHeight:n.containerHeight,overscan:n.overscan,containerClass:n.containerClass})})${u}@endvirtualList`,c);return m=m.replace("</script>",`
127
+ `}function N(v,c){let a=null,g=()=>{if(!a)a=T(v(),c);return a};return{visibleItems:()=>g().getState().visibleItems,totalHeight:()=>g().getState().totalHeight,containerProps:()=>({style:{height:`${c.containerHeight}px`,overflow:"auto",position:"relative"},onScroll:(l)=>{let x=l.target;if(a)a.scrollToOffset(x.scrollTop)}}),itemProps:(l)=>({style:{position:"absolute",top:`${l*c.itemHeight}px`,height:`${c.itemHeight}px`,width:"100%"},"data-index":l}),scrollToIndex:(l)=>{g().scrollToIndex(l)}}}function O(v,c={},a){let g=/@infiniteList\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@loading\s*([\s\S]*?)@endinfiniteList/gi;return v.replace(g,(l,x,d,u,w)=>{let e=x.trim(),t=c[e];if(!t||!Array.isArray(t))return`<!-- infiniteList: items "${e}" not found or not an array -->`;let n={itemHeight:50,containerHeight:400,overscan:3,threshold:100,hasMore:!0};if(d)try{let H=Function(`return ${d.trim()}`)();n={...n,...H}}catch{}let f=`ilist-${Math.random().toString(36).substring(2,9)}`,m=C(`@virtualList(${e}, ${JSON.stringify({itemHeight:n.itemHeight,containerHeight:n.containerHeight,overscan:n.overscan,containerClass:n.containerClass})})${u}@endvirtualList`,c);return m=m.replace("</script>",`
128
128
  // Infinite scroll detection
129
129
  container.addEventListener('scroll', function() {
130
130
  const scrollBottom = container.scrollTop + container.clientHeight;
@@ -142,10 +142,10 @@ function L(v,c){let{itemHeight:a,containerHeight:g,overscan:l=3,keyProperty:x="i
142
142
  ${w}
143
143
  </div>
144
144
  </div>
145
- `})}function O(v,c={},a){let g=/@virtualGrid\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@endvirtualGrid/gi;return v.replace(g,(l,x,d,u)=>{let w=x.trim(),e=c[w];if(!e||!Array.isArray(e))return`<!-- virtualGrid: items "${w}" not found or not an array -->`;let t={columns:3,rowHeight:100,containerHeight:400,gap:10,overscan:2};if(d)try{let o=Function(`return ${d.trim()}`)();t={...t,...o}}catch{}let n=`vgrid-${Math.random().toString(36).substring(2,9)}`,f=Math.ceil(e.length/t.columns),m=f*(t.rowHeight+(t.gap||0)),H=Math.ceil(t.containerHeight/(t.rowHeight+(t.gap||0))),y=t.overscan||2,I=0,S=Math.min(f-1,H+y),s="";for(let o=I;o<=S;o++)for(let b=0;b<t.columns;b++){let $=o*t.columns+b;if($>=e.length)break;let i=e[$],r=b*(100/t.columns),h=o*(t.rowHeight+(t.gap||0)),p=u.replace(/\{\{\s*item\s*\}\}/g,typeof i==="object"?JSON.stringify(i):String(i)).replace(/\{\{\s*item\.(\w+)\s*\}\}/g,(M,C)=>{if(typeof i==="object"&&i!==null)return String(i[C]??"");return""}).replace(/\{\{\s*index\s*\}\}/g,String($));s+=`
145
+ `})}function _(v,c={},a){let g=/@virtualGrid\s*\(\s*([^,]+)\s*(?:,\s*(\{[^}]*\}))?\s*\)\s*([\s\S]*?)@endvirtualGrid/gi;return v.replace(g,(l,x,d,u)=>{let w=x.trim(),e=c[w];if(!e||!Array.isArray(e))return`<!-- virtualGrid: items "${w}" not found or not an array -->`;let t={columns:3,rowHeight:100,containerHeight:400,gap:10,overscan:2};if(d)try{let o=Function(`return ${d.trim()}`)();t={...t,...o}}catch{}let n=`vgrid-${Math.random().toString(36).substring(2,9)}`,f=Math.ceil(e.length/t.columns),m=f*(t.rowHeight+(t.gap||0)),H=Math.ceil(t.containerHeight/(t.rowHeight+(t.gap||0))),I=t.overscan||2,S=0,M=Math.min(f-1,H+I),s="";for(let o=S;o<=M;o++)for(let b=0;b<t.columns;b++){let y=o*t.columns+b;if(y>=e.length)break;let i=e[y],r=b*(100/t.columns),h=o*(t.rowHeight+(t.gap||0)),p=u.replace(/\{\{\s*item\s*\}\}/g,typeof i==="object"?JSON.stringify(i):String(i)).replace(/\{\{\s*item\.(\w+)\s*\}\}/g,(L,R)=>{if(typeof i==="object"&&i!==null)return String(i[R]??"");return""}).replace(/\{\{\s*index\s*\}\}/g,String(y));s+=`
146
146
  <div class="virtual-grid-item"
147
147
  style="position: absolute; top: ${h}px; left: ${r}%; width: calc(${100/t.columns}% - ${t.gap||0}px); height: ${t.rowHeight}px;"
148
- data-index="${$}">
148
+ data-index="${y}">
149
149
  ${p}
150
150
  </div>`}return`
151
151
  <div id="${n}"
@@ -166,7 +166,7 @@ function L(v,c){let{itemHeight:a,containerHeight:g,overscan:l=3,keyProperty:x="i
166
166
  const rowHeight = ${t.rowHeight};
167
167
  const gap = ${t.gap||0};
168
168
  const totalItems = ${e.length};
169
- const overscan = ${y};
169
+ const overscan = ${I};
170
170
  const containerHeight = ${t.containerHeight};
171
171
  const items = ${JSON.stringify(e)};
172
172
  const template = ${JSON.stringify(u.trim())};
@@ -212,5 +212,5 @@ function L(v,c){let{itemHeight:a,containerHeight:g,overscan:l=3,keyProperty:x="i
212
212
  });
213
213
  })();
214
214
  </script>
215
- `})}var _={createVirtualList:L,processVirtualListDirectives:T,processInfiniteListDirectives:N,processVirtualGridDirectives:O,generateVirtualListCSS:R,useVirtualList:k};
216
- export{L as Td,T as Ud,R as Vd,k as Wd,N as Xd,O as Yd,_ as Zd};
215
+ `})}var A={createVirtualList:T,processVirtualListDirectives:C,processInfiniteListDirectives:O,processVirtualGridDirectives:_,generateVirtualListCSS:k,useVirtualList:N};
216
+ export{T as Td,C as Ud,k as Vd,N as Wd,O as Xd,_ as Yd,A as Zd};