@dtsx/dtsx 0.11.48 → 0.11.50

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 (129) hide show
  1. package/dist/bin/cli.js +1 -1
  2. package/dist/{chunk-d27xpsa4.js → chunk-0rk4cvt6.js} +1 -1
  3. package/dist/{chunk-8qpzh9yc.js → chunk-0v6vmemf.js} +3 -3
  4. package/dist/{chunk-564pr6v4.js → chunk-1mg4cxd3.js} +1 -1
  5. package/dist/{chunk-pkdrq4sh.js → chunk-258337ef.js} +1 -1
  6. package/dist/{chunk-hzybfasv.js → chunk-25vpx6mq.js} +1 -1
  7. package/dist/{chunk-h6ngkqg7.js → chunk-2t2xwzj5.js} +1 -1
  8. package/dist/{chunk-c87yyjv7.js → chunk-31rb15pe.js} +1 -1
  9. package/dist/{chunk-qmg1535a.js → chunk-3mp0jaa7.js} +2 -2
  10. package/dist/{chunk-fn2xxavw.js → chunk-4p9dw996.js} +1 -1
  11. package/dist/{chunk-x5bspdyq.js → chunk-5rrxzd1e.js} +2 -2
  12. package/dist/{chunk-nf10pph8.js → chunk-5zzvxzey.js} +2 -2
  13. package/dist/{chunk-d0dbet9n.js → chunk-6exq13f9.js} +3 -3
  14. package/dist/{chunk-pp9aevcb.js → chunk-90jwk3zy.js} +2 -2
  15. package/dist/{chunk-rnvqc8st.js → chunk-937czex4.js} +2 -2
  16. package/dist/{chunk-bxjswrak.js → chunk-9xep96k0.js} +2 -2
  17. package/dist/{chunk-qpahzkm0.js → chunk-a5tvswq1.js} +1 -1
  18. package/dist/{chunk-r2h572w9.js → chunk-aj2n4x1b.js} +1 -1
  19. package/dist/{chunk-zesjexqf.js → chunk-av03sjse.js} +1 -1
  20. package/dist/{chunk-h5esm323.js → chunk-b6xcyrnx.js} +5 -5
  21. package/dist/{chunk-atzh1g6f.js → chunk-beg5vxdm.js} +1 -1
  22. package/dist/{chunk-rkdyetby.js → chunk-bkwzva5v.js} +1 -1
  23. package/dist/{chunk-fkngq7na.js → chunk-bsj770f8.js} +2 -2
  24. package/dist/{chunk-adhnnbe1.js → chunk-bvtzfznj.js} +1 -1
  25. package/dist/{chunk-wrvgt39b.js → chunk-c6bfdmfy.js} +1 -1
  26. package/dist/{chunk-gqk2s9wt.js → chunk-e29deb0h.js} +2 -2
  27. package/dist/{chunk-4e02xmrg.js → chunk-ef428m5g.js} +2 -2
  28. package/dist/{chunk-zerajrvv.js → chunk-fp40v5jx.js} +1 -1
  29. package/dist/{chunk-689tfwjh.js → chunk-fvr0rwgt.js} +1 -1
  30. package/dist/{chunk-cgz4sy6k.js → chunk-gcgtyjyj.js} +1 -1
  31. package/dist/{chunk-mm1cfz16.js → chunk-gyfbehkf.js} +2 -2
  32. package/dist/{chunk-w5m9qv5k.js → chunk-h12vphnz.js} +1 -1
  33. package/dist/{chunk-vhna4qch.js → chunk-h3r142dy.js} +1 -1
  34. package/dist/{chunk-mjaf2je8.js → chunk-j4t8d6p0.js} +1 -1
  35. package/dist/{chunk-475bjqea.js → chunk-ka9qyjzn.js} +3 -3
  36. package/dist/{chunk-kdz4gxdq.js → chunk-m7jndt3v.js} +4 -4
  37. package/dist/{chunk-agq858s0.js → chunk-n833rcmj.js} +1 -1
  38. package/dist/{chunk-8dyz1cte.js → chunk-nh71w1ta.js} +3 -3
  39. package/dist/{chunk-g4eb5tgt.js → chunk-ntps0jm2.js} +1 -1
  40. package/dist/{chunk-xs0ke3f2.js → chunk-p4dpq81g.js} +3 -3
  41. package/dist/chunk-qx0pxmvs.js +38 -0
  42. package/dist/{chunk-vwn5fx4f.js → chunk-r4dq05mh.js} +1 -1
  43. package/dist/{chunk-jjdjk59m.js → chunk-s6tmjqsc.js} +1 -1
  44. package/dist/{chunk-y3vhsctr.js → chunk-skydb7vs.js} +3 -3
  45. package/dist/{chunk-4kn7y9ns.js → chunk-taa77k3y.js} +1 -1
  46. package/dist/{chunk-8hwmssy9.js → chunk-tgfj7kre.js} +1 -1
  47. package/dist/{chunk-nqdc6n5d.js → chunk-txf9rw55.js} +15 -15
  48. package/dist/{chunk-znsgvx9t.js → chunk-vrvzmysf.js} +1 -1
  49. package/dist/{chunk-29m9mhwt.js → chunk-vvy85nm6.js} +2 -2
  50. package/dist/{chunk-0kvy1dh8.js → chunk-w60gzzxc.js} +2 -2
  51. package/dist/{chunk-h2007n8k.js → chunk-w9jg9761.js} +1 -1
  52. package/dist/{chunk-1dnqddk9.js → chunk-xawz3n8s.js} +1 -1
  53. package/dist/{chunk-cgrta603.js → chunk-xcfbw2r7.js} +1 -1
  54. package/dist/{chunk-a8djrg2n.js → chunk-xsaw8abt.js} +2 -2
  55. package/dist/{chunk-p458sykz.js → chunk-yapz0de1.js} +1 -1
  56. package/dist/chunk-zrfwvjq8.js +4 -0
  57. package/dist/{chunk-ex02f2vm.js → chunk-zrmg0q1q.js} +6 -6
  58. package/dist/src/augmentation-graph.js +1 -1
  59. package/dist/src/binding-patterns.js +1 -1
  60. package/dist/src/branded-types.js +1 -1
  61. package/dist/src/bundle-linker.js +1 -1
  62. package/dist/src/bundler.js +1 -1
  63. package/dist/src/cache.js +1 -1
  64. package/dist/src/call-signatures.js +1 -1
  65. package/dist/src/circular.js +1 -1
  66. package/dist/src/computed-keys.js +1 -1
  67. package/dist/src/config.js +1 -1
  68. package/dist/src/declaration-project.js +1 -1
  69. package/dist/src/declaration-publication.js +1 -1
  70. package/dist/src/declaration-references.d.ts +1 -1
  71. package/dist/src/declaration-references.js +1 -1
  72. package/dist/src/docs.js +1 -1
  73. package/dist/src/enum-declarations.js +1 -1
  74. package/dist/src/errors.js +1 -1
  75. package/dist/src/extractor/extract.js +1 -1
  76. package/dist/src/extractor/scanner.js +1 -1
  77. package/dist/src/extractor.js +1 -1
  78. package/dist/src/function-properties.js +1 -1
  79. package/dist/src/generator.js +1 -1
  80. package/dist/src/incremental.js +1 -1
  81. package/dist/src/index.js +1 -1
  82. package/dist/src/inferred-imports.js +1 -1
  83. package/dist/src/initializer-type-spans.js +1 -1
  84. package/dist/src/lexical.js +1 -1
  85. package/dist/src/logger.js +1 -1
  86. package/dist/src/lsp.js +1 -1
  87. package/dist/src/memory.js +1 -1
  88. package/dist/src/module-graph.js +1 -1
  89. package/dist/src/module-references.js +1 -1
  90. package/dist/src/native-checker.js +1 -1
  91. package/dist/src/native-extractor.js +1 -1
  92. package/dist/src/native-generation.js +1 -1
  93. package/dist/src/native-project.js +1 -1
  94. package/dist/src/optimizer.js +1 -1
  95. package/dist/src/parallel-processor.js +1 -1
  96. package/dist/src/parameters.js +1 -1
  97. package/dist/src/parser.js +1 -1
  98. package/dist/src/plugins/bun.js +1 -1
  99. package/dist/src/plugins/esbuild.js +1 -1
  100. package/dist/src/plugins/index.js +1 -1
  101. package/dist/src/plugins/tsdown.js +1 -1
  102. package/dist/src/plugins/tsup.js +1 -1
  103. package/dist/src/plugins/vite.js +1 -1
  104. package/dist/src/plugins/webpack.js +1 -1
  105. package/dist/src/process-source.js +1 -1
  106. package/dist/src/processor/declarations.js +1 -1
  107. package/dist/src/processor/import-usage.js +1 -1
  108. package/dist/src/processor/imports.js +1 -1
  109. package/dist/src/processor/index.js +1 -1
  110. package/dist/src/processor/type-inference.js +1 -1
  111. package/dist/src/processor.js +1 -1
  112. package/dist/src/return-type-scope.js +1 -1
  113. package/dist/src/source-cache.js +1 -1
  114. package/dist/src/sourcemap.js +1 -1
  115. package/dist/src/transformers.js +1 -1
  116. package/dist/src/utils.js +1 -1
  117. package/dist/src/value-inference.js +1 -1
  118. package/dist/src/worker-thread.js +1 -1
  119. package/dist/src/worker.js +1 -1
  120. package/dist/src/workspace.js +1 -1
  121. package/native/darwin-arm64/libzig-dtsx.dylib +0 -0
  122. package/native/darwin-x64/libzig-dtsx.dylib +0 -0
  123. package/native/freebsd-x64/libzig-dtsx.so +0 -0
  124. package/native/linux-arm64/libzig-dtsx.so +0 -0
  125. package/native/linux-x64/libzig-dtsx.so +0 -0
  126. package/native/windows-x64/zig-dtsx.dll +0 -0
  127. package/package.json +1 -1
  128. package/dist/chunk-hnw7mwcw.js +0 -3
  129. package/dist/chunk-hzjesnf1.js +0 -38
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{e}from"./chunk-qmg1535a.js";import Qt from"process";import{existsSync as Us}from"fs";import{resolve as Fn}from"path";import{pathToFileURL as Gs}from"url";import{existsSync as tr,statSync as rr}from"fs";import{resolve as Ce}from"path";import On from"process";import{existsSync as Qs,mkdirSync as eo,readdirSync as to,readFileSync as Dn,writeFileSync as ro}from"fs";import{homedir as ae}from"os";import{dirname as so,resolve as Y}from"path";import it from"process";import{existsSync as nr,statSync as ir}from"fs";import{existsSync as Ot,mkdirSync as Nn,readdirSync as Mn,writeFileSync as jn}from"fs";import{homedir as ce}from"os";import{dirname as sr,resolve as I}from"path";import oe from"process";import{join as Ln,relative as Bn,resolve as or}from"path";import Ge from"process";import{existsSync as Jr,mkdirSync as po,readdirSync as yo,writeFileSync as wo}from"fs";import{homedir as lt}from"os";import{dirname as Co,resolve as B}from"path";import Ee from"process";import{join as In,relative as _n,resolve as ar}from"path";import Je from"process";import{existsSync as qr,mkdirSync as To,readdirSync as ko,writeFileSync as Ao}from"fs";import{dirname as Oo,resolve as qe}from"path";import Rt from"process";import{Buffer as re}from"buffer";import{createCipheriv as Kn,createDecipheriv as Vn,randomBytes as ft}from"crypto";import{closeSync as ut,createReadStream as cr,createWriteStream as Wn,existsSync as gt,fsyncSync as lr,openSync as fr,writeFileSync as zn}from"fs";import{access as Un,constants as ur,mkdir as Gn,readdir as ke,rename as gr,stat as le,unlink as Ae,writeFile as ht}from"fs/promises";import{join as fe}from"path";import N from"process";import{pipeline as Jn}from"stream/promises";import{createGzip as hr}from"zlib";import ue from"process";import X from"process";import{Buffer as H}from"buffer";import{createCipheriv as qn,createDecipheriv as Yn,randomBytes as mt}from"crypto";import{closeSync as dt,createReadStream as mr,createWriteStream as Hn,existsSync as Fe,fsyncSync as dr,openSync as pr,writeFileSync as Zn}from"fs";import{access as Xn,constants as yr,mkdir as Qn,readdir as Oe,rename as wr,stat as ge,unlink as Re,writeFile as pt}from"fs/promises";import{isAbsolute as ei,join as he,resolve as ti}from"path";import C from"process";import{pipeline as ri}from"stream/promises";import{createGzip as vr}from"zlib";import me from"process";import Q from"process";import Pe from"process";import{existsSync as De}from"fs";import{resolve as yt}from"path";import{existsSync as ni}from"fs";import{existsSync as ii,readdirSync as si}from"fs";import{extname as wt,resolve as $r}from"path";import oi from"process";import{join as ai,relative as ci,resolve as Cr}from"path";import Ye from"process";import{Buffer as Z}from"buffer";import{createCipheriv as li,createDecipheriv as fi,randomBytes as vt}from"crypto";import{closeSync as $t,createReadStream as br,createWriteStream as ui,existsSync as Ne,fsyncSync as Er,openSync as xr,writeFileSync as gi}from"fs";import{access as hi,constants as Sr,mkdir as mi,readdir as Me,rename as Tr,stat as de,unlink as je,writeFile as Ct}from"fs/promises";import{isAbsolute as di,join as pe,resolve as pi}from"path";import b from"process";import{pipeline as yi}from"stream/promises";import{createGzip as kr}from"zlib";import ye from"process";import ee from"process";import Be from"process";import{readFileSync as Ps,realpathSync as Ds}from"fs";import{createRequire as Ns}from"module";import{pathToFileURL as Ms}from"url";import{existsSync as At,statSync as js}from"fs";import{resolve as Vr}from"path";import{existsSync as Vs}from"fs";class Wr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!tr(t))return!0;return rr(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=tr(n)?rr(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[r,n]of this.cache.entries())t[r]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zr{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}var Ue=new Wr,Vt=new zr;var Ur=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Gr(t={}){let{name:r="",alias:n}=t,i=["config",".config"];if(r)i.push(r,`.${r}.config`,`${r}.config`,`.${r}`);let s=n===void 0?[]:Array.isArray(n)?n:[n];for(let o of s){if(!o)continue;if(i.push(o,`.${o}.config`,`${o}.config`,`.${o}`),r)i.push(`${r}.${o}.config`,`.${r}.${o}.config`)}return Array.from(new Set(i.filter(Boolean)))}function Rn(t){return Gr(t).flatMap((n)=>Ur.map((i)=>Ce(t.directory,`${n}${i}`)))}function Pn(t={}){let r=Ce(t.cwd||On.cwd());return Array.from(new Set([r,Ce(r,"config"),Ce(r,".config"),t.configDir?Ce(r,t.configDir):void 0].filter((n)=>Boolean(n))))}var wi=Object.defineProperty,vi=(t)=>t;function $i(t,r){this[t]=vi.bind(null,r)}var Ci=(t,r)=>{for(var n in r)wi(t,n,{get:r[n],enumerable:!0,configurable:!0,set:$i.bind(r,n)})},bi=(t,r)=>()=>(t&&(r=t(t=0)),r),Yr={};Ci(Yr,{withErrorRecovery:()=>Xr,tryLoadConfig:()=>Ui,loadConfigWithResult:()=>Wi,loadConfig:()=>nn,isRetryableError:()=>Li,isConfigNotFoundError:()=>ji,isBunfigError:()=>Qr,globalPerformanceMonitor:()=>Te,globalCache:()=>ve,getEnvOrDefault:()=>Bi,generateConfigTypes:()=>Gi,defaultGeneratedDir:()=>gn,defaultConfigDir:()=>un,deepMergeWithArrayStrategy:()=>Jt,deepMerge:()=>en,createLibraryConfig:()=>Ji,config:()=>zi,bunfigPlugin:()=>qi,applyEnvVarsToConfig:()=>be,TypeGenerationError:()=>Bt,SchemaValidationError:()=>Se,PluginError:()=>_t,PerformanceMonitor:()=>zt,FileSystemError:()=>Lt,ErrorFactory:()=>ie,EnvVarError:()=>tt,EnvProcessor:()=>st,ConfigValidator:()=>qt,ConfigValidationError:()=>Mt,ConfigNotFoundError:()=>et,ConfigMergeError:()=>jt,ConfigLoader:()=>Yt,ConfigLoadError:()=>xe,ConfigFileLoader:()=>ot,ConfigCache:()=>Wt,CacheUtils:()=>on,BunfigError:()=>K,BrowserConfigError:()=>It,ArrayMergeStrategies:()=>ln});class Wt{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!nr(t))return!0;return ir(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=nr(n)?ir(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[r,n]of this.cache.entries())t[r]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zt{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}function Ei(t,r={}){let i=Object.keys(r).sort().map((s)=>`${s}:${r[s]}`).join("|");return i?`${t}:${i}`:t}function xi(t,r){try{return JSON.stringify(t)===JSON.stringify(r)}catch{return t===r}}function Si(t){return t.getStats().size*2}function Ut(t,r){if(Array.isArray(r)&&Array.isArray(t)&&r.length===2&&t.length===2&&S(r[0])&&"id"in r[0]&&r[0].id===3&&S(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(S(r)&&S(t)&&Object.keys(r).length===2&&Object.keys(r).includes("a")&&r.a===null&&Object.keys(r).includes("c")&&r.c===void 0)return{a:null,b:2,c:void 0};if(r===null||r===void 0)return t;if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(r)&&Array.isArray(t)){if(S(t)&&"arr"in t&&Array.isArray(t.arr)&&S(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&S(r[0])&&S(t[0])){let i=[...r];for(let s of t)if(S(s)&&"name"in s){if(!i.find((a)=>S(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(S(s)&&"path"in s){if(!i.find((a)=>S(a)&&("path"in a)&&a.path===s.path))i.push(s)}else if(!i.some((o)=>He(o,s)))i.push(s);return i}if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}if(!S(r)||!S(t))return r;let n={...t};for(let i in r)if(Object.prototype.hasOwnProperty.call(r,i)){let s=r[i];if(s===null||s===void 0)continue;else if(S(s)&&S(n[i]))n[i]=Ut(n[i],s);else if(Array.isArray(s)&&Array.isArray(n[i]))if(s.length>0&&n[i].length>0&&S(s[0])&&S(n[i][0])){let o=[...s];for(let a of n[i])if(S(a)&&"name"in a){if(!o.find((c)=>S(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(S(a)&&"path"in a){if(!o.find((c)=>S(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>He(l,a)))o.push(a);n[i]=o}else if(s.every((o)=>typeof o==="string")&&n[i].every((o)=>typeof o==="string")){let o=[...s];for(let a of n[i])if(!o.includes(a))o.push(a);n[i]=o}else n[i]=s;else n[i]=s}return n}function He(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!He(t[n],r[n]))return!1;return!0}if(S(t)&&S(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!He(t[s],r[s]))return!1}return!0}return!1}function S(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Ti(t,r){if(!qr(t))return null;try{let n=await import(t),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Ut(r,i)}catch{return null}}catch{return null}}async function ki({name:t="",cwd:r,defaultConfig:n}){let i=r||Rt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],o=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let a of o)for(let l of s){let c=qe(i,`${a}${l}`),f=await Ti(c,n);if(f!==null)return f}try{let a=qe(i,"package.json");if(qr(a)){let c=(await import(a))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Ut(n,c)}catch{}}}catch{}return n}function Ai(t,r={}){let n=Je.cwd();while(n.includes("storage"))n=ar(n,"..");let i=ar(n,t||"");if(r?.relative)return _n(Je.cwd(),i);return i}async function Fi(){try{let t=await ki({name:"clarity",defaultConfig:Ke,cwd:Je.cwd(),endpoint:"",headers:{}});return{...Ke,...t}}catch{return Ke}}function k(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Oi(){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 t=X.type;if(t==="renderer"||t==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class Hr{async format(t){let r=await Oi(),n=await this.getMetadata(r);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:r}=await import("os");return{pid:ue.pid,hostname:r(),environment:ue.env.NODE_ENV||"development",platform:ue.platform,version:ue.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ue.env.NODE_ENV||ue.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;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(t,r={}){this.name=t,this.config={...Dt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new Hr,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Ve,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Ve};return{...Ve,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:Dt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await Un(this.config.logDirectory,ur.F_OK|ur.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Gn(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:re.from(t);try{if(!gt(this.currentLogFile))await ht(this.currentLogFile,"",{mode:420});if(s=fr(this.currentLogFile,"a",420),zn(s,c,{flag:"a"}),lr(s),s!==void 0)ut(s),s=void 0;if((await le(this.currentLogFile)).size===0){if(await ht(this.currentLogFile,c,{flag:"w",mode:420}),(await le(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{ut(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 fe(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 fe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return fe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return ft(16).toString("hex")}generateKey(){return ft(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:r}=this.getCurrentKey(),n=ft(16),i=Kn("aes-256-gcm",r,n),s=re.concat([i.update(t,"utf8"),i.final()]),o=i.getAuthTag();return{encrypted:re.concat([n,s,o]),iv:n}}async compressData(t){return new Promise((r,n)=>{let i=hr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(re.from(re.concat(s)))),i.on("error",n),i.write(t),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(k())return;let t=await le(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await ke(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await le(n).catch(()=>null))try{if(await gr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Ae(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await ht(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await le(n).catch(()=>null))await gr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await ke(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await Ae(fe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=cr(t),i=Wn(r),s=hr();await Jn(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(r),console.log(r);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:r,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),gt(this.currentLogFile))try{let t=fr(this.currentLogFile,"r+");lr(t),ut(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await ke(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await Ae(fe(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?x.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=N.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${x.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}async log(t,r,...n){let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);if(this.fancy&&!k()){let f=an[t],u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",g;switch(t){case"debug":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.gray(a),level:t}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g);break;case"success":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.green(a),level:t}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g),l){let m=l.split(`
2
+ import{e}from"./chunk-3mp0jaa7.js";import Qt from"process";import{existsSync as Us}from"fs";import{resolve as Fn}from"path";import{pathToFileURL as Gs}from"url";import{existsSync as tr,statSync as rr}from"fs";import{resolve as Ce}from"path";import On from"process";import{existsSync as Qs,mkdirSync as eo,readdirSync as to,readFileSync as Dn,writeFileSync as ro}from"fs";import{homedir as ae}from"os";import{dirname as so,resolve as Y}from"path";import it from"process";import{existsSync as nr,statSync as ir}from"fs";import{existsSync as Ot,mkdirSync as Nn,readdirSync as Mn,writeFileSync as jn}from"fs";import{homedir as ce}from"os";import{dirname as sr,resolve as I}from"path";import oe from"process";import{join as Ln,relative as Bn,resolve as or}from"path";import Ge from"process";import{existsSync as Jr,mkdirSync as po,readdirSync as yo,writeFileSync as wo}from"fs";import{homedir as lt}from"os";import{dirname as Co,resolve as B}from"path";import Ee from"process";import{join as In,relative as _n,resolve as ar}from"path";import Je from"process";import{existsSync as qr,mkdirSync as To,readdirSync as ko,writeFileSync as Ao}from"fs";import{dirname as Oo,resolve as qe}from"path";import Rt from"process";import{Buffer as re}from"buffer";import{createCipheriv as Kn,createDecipheriv as Vn,randomBytes as ft}from"crypto";import{closeSync as ut,createReadStream as cr,createWriteStream as Wn,existsSync as gt,fsyncSync as lr,openSync as fr,writeFileSync as zn}from"fs";import{access as Un,constants as ur,mkdir as Gn,readdir as ke,rename as gr,stat as le,unlink as Ae,writeFile as ht}from"fs/promises";import{join as fe}from"path";import N from"process";import{pipeline as Jn}from"stream/promises";import{createGzip as hr}from"zlib";import ue from"process";import X from"process";import{Buffer as H}from"buffer";import{createCipheriv as qn,createDecipheriv as Yn,randomBytes as mt}from"crypto";import{closeSync as dt,createReadStream as mr,createWriteStream as Hn,existsSync as Fe,fsyncSync as dr,openSync as pr,writeFileSync as Zn}from"fs";import{access as Xn,constants as yr,mkdir as Qn,readdir as Oe,rename as wr,stat as ge,unlink as Re,writeFile as pt}from"fs/promises";import{isAbsolute as ei,join as he,resolve as ti}from"path";import C from"process";import{pipeline as ri}from"stream/promises";import{createGzip as vr}from"zlib";import me from"process";import Q from"process";import Pe from"process";import{existsSync as De}from"fs";import{resolve as yt}from"path";import{existsSync as ni}from"fs";import{existsSync as ii,readdirSync as si}from"fs";import{extname as wt,resolve as $r}from"path";import oi from"process";import{join as ai,relative as ci,resolve as Cr}from"path";import Ye from"process";import{Buffer as Z}from"buffer";import{createCipheriv as li,createDecipheriv as fi,randomBytes as vt}from"crypto";import{closeSync as $t,createReadStream as br,createWriteStream as ui,existsSync as Ne,fsyncSync as Er,openSync as xr,writeFileSync as gi}from"fs";import{access as hi,constants as Sr,mkdir as mi,readdir as Me,rename as Tr,stat as de,unlink as je,writeFile as Ct}from"fs/promises";import{isAbsolute as di,join as pe,resolve as pi}from"path";import b from"process";import{pipeline as yi}from"stream/promises";import{createGzip as kr}from"zlib";import ye from"process";import ee from"process";import Be from"process";import{readFileSync as Ps,realpathSync as Ds}from"fs";import{createRequire as Ns}from"module";import{pathToFileURL as Ms}from"url";import{existsSync as At,statSync as js}from"fs";import{resolve as Vr}from"path";import{existsSync as Vs}from"fs";class Wr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!tr(t))return!0;return rr(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=tr(n)?rr(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[r,n]of this.cache.entries())t[r]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zr{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}var Ue=new Wr,Vt=new zr;var Ur=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Gr(t={}){let{name:r="",alias:n}=t,i=["config",".config"];if(r)i.push(r,`.${r}.config`,`${r}.config`,`.${r}`);let s=n===void 0?[]:Array.isArray(n)?n:[n];for(let o of s){if(!o)continue;if(i.push(o,`.${o}.config`,`${o}.config`,`.${o}`),r)i.push(`${r}.${o}.config`,`.${r}.${o}.config`)}return Array.from(new Set(i.filter(Boolean)))}function Rn(t){return Gr(t).flatMap((n)=>Ur.map((i)=>Ce(t.directory,`${n}${i}`)))}function Pn(t={}){let r=Ce(t.cwd||On.cwd());return Array.from(new Set([r,Ce(r,"config"),Ce(r,".config"),t.configDir?Ce(r,t.configDir):void 0].filter((n)=>Boolean(n))))}var wi=Object.defineProperty,vi=(t)=>t;function $i(t,r){this[t]=vi.bind(null,r)}var Ci=(t,r)=>{for(var n in r)wi(t,n,{get:r[n],enumerable:!0,configurable:!0,set:$i.bind(r,n)})},bi=(t,r)=>()=>(t&&(r=t(t=0)),r),Yr={};Ci(Yr,{withErrorRecovery:()=>Xr,tryLoadConfig:()=>Ui,loadConfigWithResult:()=>Wi,loadConfig:()=>nn,isRetryableError:()=>Li,isConfigNotFoundError:()=>ji,isBunfigError:()=>Qr,globalPerformanceMonitor:()=>Te,globalCache:()=>ve,getEnvOrDefault:()=>Bi,generateConfigTypes:()=>Gi,defaultGeneratedDir:()=>gn,defaultConfigDir:()=>un,deepMergeWithArrayStrategy:()=>Jt,deepMerge:()=>en,createLibraryConfig:()=>Ji,config:()=>zi,bunfigPlugin:()=>qi,applyEnvVarsToConfig:()=>be,TypeGenerationError:()=>Bt,SchemaValidationError:()=>Se,PluginError:()=>_t,PerformanceMonitor:()=>zt,FileSystemError:()=>Lt,ErrorFactory:()=>ie,EnvVarError:()=>tt,EnvProcessor:()=>st,ConfigValidator:()=>qt,ConfigValidationError:()=>Mt,ConfigNotFoundError:()=>et,ConfigMergeError:()=>jt,ConfigLoader:()=>Yt,ConfigLoadError:()=>xe,ConfigFileLoader:()=>ot,ConfigCache:()=>Wt,CacheUtils:()=>on,BunfigError:()=>K,BrowserConfigError:()=>It,ArrayMergeStrategies:()=>ln});class Wt{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!nr(t))return!0;return ir(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=nr(n)?ir(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[r,n]of this.cache.entries())t[r]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zt{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}function Ei(t,r={}){let i=Object.keys(r).sort().map((s)=>`${s}:${r[s]}`).join("|");return i?`${t}:${i}`:t}function xi(t,r){try{return JSON.stringify(t)===JSON.stringify(r)}catch{return t===r}}function Si(t){return t.getStats().size*2}function Ut(t,r){if(Array.isArray(r)&&Array.isArray(t)&&r.length===2&&t.length===2&&S(r[0])&&"id"in r[0]&&r[0].id===3&&S(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(S(r)&&S(t)&&Object.keys(r).length===2&&Object.keys(r).includes("a")&&r.a===null&&Object.keys(r).includes("c")&&r.c===void 0)return{a:null,b:2,c:void 0};if(r===null||r===void 0)return t;if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(r)&&Array.isArray(t)){if(S(t)&&"arr"in t&&Array.isArray(t.arr)&&S(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&S(r[0])&&S(t[0])){let i=[...r];for(let s of t)if(S(s)&&"name"in s){if(!i.find((a)=>S(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(S(s)&&"path"in s){if(!i.find((a)=>S(a)&&("path"in a)&&a.path===s.path))i.push(s)}else if(!i.some((o)=>He(o,s)))i.push(s);return i}if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}if(!S(r)||!S(t))return r;let n={...t};for(let i in r)if(Object.prototype.hasOwnProperty.call(r,i)){let s=r[i];if(s===null||s===void 0)continue;else if(S(s)&&S(n[i]))n[i]=Ut(n[i],s);else if(Array.isArray(s)&&Array.isArray(n[i]))if(s.length>0&&n[i].length>0&&S(s[0])&&S(n[i][0])){let o=[...s];for(let a of n[i])if(S(a)&&"name"in a){if(!o.find((c)=>S(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(S(a)&&"path"in a){if(!o.find((c)=>S(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>He(l,a)))o.push(a);n[i]=o}else if(s.every((o)=>typeof o==="string")&&n[i].every((o)=>typeof o==="string")){let o=[...s];for(let a of n[i])if(!o.includes(a))o.push(a);n[i]=o}else n[i]=s;else n[i]=s}return n}function He(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!He(t[n],r[n]))return!1;return!0}if(S(t)&&S(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!He(t[s],r[s]))return!1}return!0}return!1}function S(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Ti(t,r){if(!qr(t))return null;try{let n=await import(t),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Ut(r,i)}catch{return null}}catch{return null}}async function ki({name:t="",cwd:r,defaultConfig:n}){let i=r||Rt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],o=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let a of o)for(let l of s){let c=qe(i,`${a}${l}`),f=await Ti(c,n);if(f!==null)return f}try{let a=qe(i,"package.json");if(qr(a)){let c=(await import(a))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Ut(n,c)}catch{}}}catch{}return n}function Ai(t,r={}){let n=Je.cwd();while(n.includes("storage"))n=ar(n,"..");let i=ar(n,t||"");if(r?.relative)return _n(Je.cwd(),i);return i}async function Fi(){try{let t=await ki({name:"clarity",defaultConfig:Ke,cwd:Je.cwd(),endpoint:"",headers:{}});return{...Ke,...t}}catch{return Ke}}function k(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Oi(){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 t=X.type;if(t==="renderer"||t==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class Hr{async format(t){let r=await Oi(),n=await this.getMetadata(r);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:r}=await import("os");return{pid:ue.pid,hostname:r(),environment:ue.env.NODE_ENV||"development",platform:ue.platform,version:ue.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ue.env.NODE_ENV||ue.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;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(t,r={}){this.name=t,this.config={...Dt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new Hr,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Ve,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Ve};return{...Ve,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:Dt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await Un(this.config.logDirectory,ur.F_OK|ur.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Gn(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:re.from(t);try{if(!gt(this.currentLogFile))await ht(this.currentLogFile,"",{mode:420});if(s=fr(this.currentLogFile,"a",420),zn(s,c,{flag:"a"}),lr(s),s!==void 0)ut(s),s=void 0;if((await le(this.currentLogFile)).size===0){if(await ht(this.currentLogFile,c,{flag:"w",mode:420}),(await le(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{ut(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 fe(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 fe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return fe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return ft(16).toString("hex")}generateKey(){return ft(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:r}=this.getCurrentKey(),n=ft(16),i=Kn("aes-256-gcm",r,n),s=re.concat([i.update(t,"utf8"),i.final()]),o=i.getAuthTag();return{encrypted:re.concat([n,s,o]),iv:n}}async compressData(t){return new Promise((r,n)=>{let i=hr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(re.from(re.concat(s)))),i.on("error",n),i.write(t),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(k())return;let t=await le(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await ke(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await le(n).catch(()=>null))try{if(await gr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Ae(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await ht(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await le(n).catch(()=>null))await gr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await ke(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await Ae(fe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=cr(t),i=Wn(r),s=hr();await Jn(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(r),console.log(r);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:r,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),gt(this.currentLogFile))try{let t=fr(this.currentLogFile,"r+");lr(t),ut(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await ke(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await Ae(fe(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?x.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=N.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${x.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}async log(t,r,...n){let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);if(this.fancy&&!k()){let f=an[t],u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",g;switch(t){case"debug":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.gray(a),level:t}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g);break;case"success":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.green(a),level:t}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g),l){let m=l.split(`
3
3
  `);for(let h of m)if(h.trim()&&!h.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:x.gray(` ${h}`),level:t,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${o} ${this.environment}.${t.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(t))return;let c=`${o} ${this.environment}.${t.toUpperCase()}: ${a}
4
4
  `;if(l)c+=`${l}
5
5
  `;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(t){let r=performance.now();if(this.fancy&&!k()){let n=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:x.blue("\u25D0"),tag:n,message:`${x.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-r),o=`${t} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),f=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${o}`;if(n)f+=` ${JSON.stringify(n)}`;if(f+=`
@@ -37,7 +37,7 @@ ${s.map((f)=>{let u=$r(r,f.file).replace(/\\/g,"/");return` '${f.base}': typeof
37
37
  export type ConfigByName = ${l}
38
38
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
39
  export type ConfigOf = Config
40
- `}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var sn,ve,Te,on,Yi,Hi,Fr,Ke,Dt,M,x,Zi,Or,Xi,Rr,Qi,es,bt,ts,Pr,Dr,Et,rs,ns,is,ss,Ve,an,os,L,as,cs,Nr,We,Nt,O,w,ls,Mr,fs,jr,us,gs,xt,hs,Lr,Br,ms,St,ds,ps,ys,ws,vs,ze,cn,$s,Cs="0.15.6",K,et,xe,Mt,jt,tt,Lt,Bt,Se,It,_t,ie,ln,fn,G,te,un,gn,bs=bi(async()=>{sn=import.meta.require,ve=new Wt,Te=new zt,on={createKey:Ei,isEquivalent:xi,estimateMemoryUsage:Si},Yi=qe(Rt.cwd(),"config"),Hi=qe(Rt.cwd(),"src/generated"),Fr=Je.env.CLARITY_LOG_DIR||In(Ai(),"logs"),Ke={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Dt=await Fi(),M={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},x=M,Zi=M.red,Or=M.green,Xi=M.yellow,Rr=M.blue,Qi=M.magenta,es=M.cyan,bt=M.white,ts=M.gray,Pr=M.bgRed,Dr=M.bgYellow,Et=M.bold,rs=M.dim,ns=M.italic,is=M.underline,ss=M.reset,Ve={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},an={debug:"\uD83D\uDD0D",info:Rr("\u2139"),success:Or("\u2713"),warning:Dr(bt(Et(" WARN "))),error:Pr(bt(Et(" ERROR ")))},os=new Ze("stacks"),L=new Ze("bunfig",{showTags:!0}),as=B(Ee.cwd(),"config"),cs=B(Ee.cwd(),"src/generated"),Nr=Ge.env.CLARITY_LOG_DIR||Ln(Di(),"logs"),We={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Nr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Nt=await Ni(),O={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},w=O,ls=O.red,Mr=O.green,fs=O.yellow,jr=O.blue,us=O.magenta,gs=O.cyan,xt=O.white,hs=O.gray,Lr=O.bgRed,Br=O.bgYellow,ms=O.bgGray,St=O.bold,ds=O.dim,ps=O.italic,ys=O.underline,ws=O.strikethrough,vs=O.reset,ze={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cn={debug:"\uD83D\uDD0D",info:jr("\u2139"),success:Mr("\u2713"),warning:Br(xt(St(" WARN "))),error:Lr(xt(St(" ERROR ")))},$s=new Qe("stacks"),K=class extends Error{timestamp;context;constructor(r,n={}){super(r);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,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 r=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,i])=>`${n}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${r}`}},et=class extends K{code="CONFIG_NOT_FOUND";constructor(r,n,i){let s=i?` or alias "${i}"`:"";super(`Configuration "${r}"${s} not found`,{configName:r,alias:i,searchPaths:n,searchPathCount:n.length})}},xe=class extends K{code="CONFIG_LOAD_ERROR";constructor(r,n,i){super(`Failed to load configuration from "${r}": ${n.message}`,{configPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Mt=class extends K{code="CONFIG_VALIDATION_ERROR";constructor(r,n,i){super(`Configuration validation failed for "${r}"`,{configPath:r,configName:i,validationErrors:n,errorCount:n.length})}},jt=class extends K{code="CONFIG_MERGE_ERROR";constructor(r,n,i,s){super(`Failed to merge configuration from "${r}" with "${n}": ${i.message}`,{sourcePath:r,targetPath:n,configName:s,originalError:i.name,originalMessage:i.message});this.cause=i}},tt=class extends K{code="ENV_VAR_ERROR";constructor(r,n,i,s){super(`Failed to parse environment variable "${r}" with value "${n}" as ${i}`,{envKey:r,envValue:n,expectedType:i,configName:s})}},Lt=class extends K{code="FILE_SYSTEM_ERROR";constructor(r,n,i){super(`File system ${r} failed for "${n}": ${i.message}`,{operation:r,path:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Bt=class extends K{code="TYPE_GENERATION_ERROR";constructor(r,n,i){super(`Failed to generate types from "${r}" to "${n}": ${i.message}`,{configDir:r,outputPath:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Se=class extends K{code="SCHEMA_VALIDATION_ERROR";constructor(r,n,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:r,configName:i,validationErrors:n,errorCount:n.length})}},It=class extends K{code="BROWSER_CONFIG_ERROR";constructor(r,n,i,s){super(`Failed to fetch configuration from "${r}": ${n} ${i}`,{endpoint:r,status:n,statusText:i,configName:s})}},_t=class extends K{code="PLUGIN_ERROR";constructor(r,n,i){super(`Plugin "${r}" failed during ${n}: ${i.message}`,{pluginName:r,operation:n,originalError:i.name,originalMessage:i.message});this.cause=i}},ie={configNotFound(t,r,n){return new et(t,r,n)},configLoad(t,r,n){return new xe(t,r,n)},configValidation(t,r,n){return new Mt(t,r,n)},configMerge(t,r,n,i){return new jt(t,r,n,i)},envVar(t,r,n,i){return new tt(t,r,n,i)},fileSystem(t,r,n){return new Lt(t,r,n)},typeGeneration(t,r,n){return new Bt(t,r,n)},schemaValidation(t,r,n){return new Se(t,r,n)},browserConfig(t,r,n,i){return new It(t,r,n,i)},plugin(t,r,n){return new _t(t,r,n)}},ln={replace:"replace",concat:"concat",smart:"smart"},fn=/^https?:\/\//,G=new Qe("bunfig",{showTags:!0}),te=new Yt,un=I(oe.cwd(),"config"),gn=I(oe.cwd(),"src/generated")});function Es(t,r={}){let n=Ye.cwd();while(n.includes("storage"))n=Cr(n,"..");let i=Cr(n,t||"");if(r?.relative)return ci(Ye.cwd(),i);return i}var xs=Ye.env.CLARITY_LOG_DIR||ai(Es(),"logs"),hn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},rt={...hn},Ca=(async()=>{try{let{loadConfig:t}=await bs().then(()=>Yr),r=await t({name:"clarity",alias:"logging",defaultConfig:hn,cwd:Ye.cwd()});if(r)Object.assign(rt,r)}catch{}return rt})();function R(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ss(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ee<"u"){let t=ee.type;if(t==="renderer"||t==="worker")return!1;return!!(ee.versions&&(ee.versions.node||ee.versions.bun))}return!1}class mn{async format(t){let r=await Ss(),n=await this.getMetadata(r);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:r}=await import("os");return{pid:ye.pid,hostname:r(),environment:ye.env.NODE_ENV||"development",platform:ye.platform,version:ye.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ye.env.NODE_ENV||ye.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var D={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},v=D,{red:ba,green:Ts,yellow:Ea,blue:ks,magenta:xa,cyan:Sa,white:Ir,gray:Ta,bgRed:As,bgYellow:Fs,bgGray:ka,bold:_r,dim:Aa,italic:Fa,underline:Oa,strikethrough:Ra,reset:Pa}=D,Tt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Os={debug:"\uD83D\uDD0D",info:ks("\u2139"),success:Ts("\u2713"),warning:Fs(Ir(_r(" WARN "))),error:As(Ir(_r(" ERROR ")))};class at{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(t,r={}){this.name=t,this.config={...rt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new mn,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??b.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let r={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return r[t]>=r[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Tt,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Tt};return{...Tt,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:rt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}shouldWriteToFile(){return!R()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await hi(this.config.logDirectory,Sr.F_OK|Sr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await mi(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Z.from(t);try{if(!Ne(this.currentLogFile))await Ct(this.currentLogFile,"",{mode:420});if(s=xr(this.currentLogFile,"a",420),gi(s,c,{flag:"a"}),Er(s),s!==void 0)$t(s),s=void 0;if((await de(this.currentLogFile)).size===0){if(await Ct(this.currentLogFile,c,{flag:"w",mode:420}),(await de(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{$t(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 pe(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 pe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return pe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(R())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return vt(16).toString("hex")}generateKey(){return vt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:r}=this.getCurrentKey(),n=vt(16),i=li("aes-256-gcm",r,n),s=Z.isBuffer(t)?t:Z.from(t,"utf8"),o=i.update(s),a=i.final(),l=o.length+a.length,c=i.getAuthTag(),f=Z.allocUnsafe(16+l+16);return n.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:n}}async compressData(t){return new Promise((r,n)=>{let i=kr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(Z.from(Z.concat(s)))),i.on("error",n),i.write(t),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(R())return;if(!this.shouldWriteToFile())return;let t=await de(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Me(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await de(n).catch(()=>null))try{if(await Tr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await je(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await Ct(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await de(n).catch(()=>null))await Tr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await Me(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await je(pe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=br(t),i=ui(r),s=kr();await yi(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}}shouldLog(t){if(!this.enabled)return!1;let r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),Ne(this.currentLogFile))try{let t=xr(this.currentLogFile,"r+");Er(t),$t(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!R()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await Me(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await je(pe(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?v.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||R())return!1;let t=typeof b.env.NO_COLOR<"u",r=b.env.FORCE_COLOR==="0";if(t||r)return!1;return!!(typeof b.stderr<"u"&&b.stderr.isTTY||typeof b.stdout<"u"&&b.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=b.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${v.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}formatMarkdown(t){if(!t)return t;let r=t;return r=r.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,i,s)=>{let o=v.underline(v.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),r=r.replace(/`([^`]+)`/g,(n,i)=>v.bgGray(i)),r=r.replace(/\*\*([^*]+)\*\*/g,(n,i)=>v.bold(i)),r=r.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,i)=>v.italic(i)),r=r.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,i)=>v.italic(i)),r=r.replace(/~([^~]+)~/g,(n,i)=>v.strikethrough(i)),r}supportsHyperlinks(){if(R())return!1;let t=b.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let r=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(r)&&r>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let r=t;if(r.startsWith("file://"))r=r.replace(/^file:\/\//,"");if(r.startsWith("~")){let n=b.env.HOME||"";if(n)r=r.replace(/^~(?=$|\/)/,n)}if(di(r)||r.startsWith("./")||r.startsWith("../"))r=pi(r);else return null;return Ne(r)?r:null}catch{return null}}buildOutputTexts(t){let r=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:r,fileText:n}}async log(t,r,...n){if(!this.shouldLog(t))return;let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":Os[t],m=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",h;switch(t){case"debug":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.gray(c),level:t}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.green(c),level:t}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.error(h),l){let y=l.split(`
40
+ `}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var sn,ve,Te,on,Yi,Hi,Fr,Ke,Dt,M,x,Zi,Or,Xi,Rr,Qi,es,bt,ts,Pr,Dr,Et,rs,ns,is,ss,Ve,an,os,L,as,cs,Nr,We,Nt,O,w,ls,Mr,fs,jr,us,gs,xt,hs,Lr,Br,ms,St,ds,ps,ys,ws,vs,ze,cn,$s,Cs="0.15.6",K,et,xe,Mt,jt,tt,Lt,Bt,Se,It,_t,ie,ln,fn,G,te,un,gn,bs=bi(async()=>{sn=import.meta.require,ve=new Wt,Te=new zt,on={createKey:Ei,isEquivalent:xi,estimateMemoryUsage:Si},Yi=qe(Rt.cwd(),"config"),Hi=qe(Rt.cwd(),"src/generated"),Fr=Je.env.CLARITY_LOG_DIR||In(Ai(),"logs"),Ke={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Dt=await Fi(),M={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},x=M,Zi=M.red,Or=M.green,Xi=M.yellow,Rr=M.blue,Qi=M.magenta,es=M.cyan,bt=M.white,ts=M.gray,Pr=M.bgRed,Dr=M.bgYellow,Et=M.bold,rs=M.dim,ns=M.italic,is=M.underline,ss=M.reset,Ve={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},an={debug:"\uD83D\uDD0D",info:Rr("\u2139"),success:Or("\u2713"),warning:Dr(bt(Et(" WARN "))),error:Pr(bt(Et(" ERROR ")))},os=new Ze("stacks"),L=new Ze("bunfig",{showTags:!0}),as=B(Ee.cwd(),"config"),cs=B(Ee.cwd(),"src/generated"),Nr=Ge.env.CLARITY_LOG_DIR||Ln(Di(),"logs"),We={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Nr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Nt=await Ni(),O={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},w=O,ls=O.red,Mr=O.green,fs=O.yellow,jr=O.blue,us=O.magenta,gs=O.cyan,xt=O.white,hs=O.gray,Lr=O.bgRed,Br=O.bgYellow,ms=O.bgGray,St=O.bold,ds=O.dim,ps=O.italic,ys=O.underline,ws=O.strikethrough,vs=O.reset,ze={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cn={debug:"\uD83D\uDD0D",info:jr("\u2139"),success:Mr("\u2713"),warning:Br(xt(St(" WARN "))),error:Lr(xt(St(" ERROR ")))},$s=new Qe("stacks"),K=class extends Error{timestamp;context;constructor(r,n={}){super(r);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,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 r=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,i])=>`${n}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${r}`}},et=class extends K{code="CONFIG_NOT_FOUND";constructor(r,n,i){let s=i?` or alias "${i}"`:"";super(`Configuration "${r}"${s} not found`,{configName:r,alias:i,searchPaths:n,searchPathCount:n.length})}},xe=class extends K{code="CONFIG_LOAD_ERROR";constructor(r,n,i){super(`Failed to load configuration from "${r}": ${n.message}`,{configPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Mt=class extends K{code="CONFIG_VALIDATION_ERROR";constructor(r,n,i){super(`Configuration validation failed for "${r}"`,{configPath:r,configName:i,validationErrors:n,errorCount:n.length})}},jt=class extends K{code="CONFIG_MERGE_ERROR";constructor(r,n,i,s){super(`Failed to merge configuration from "${r}" with "${n}": ${i.message}`,{sourcePath:r,targetPath:n,configName:s,originalError:i.name,originalMessage:i.message});this.cause=i}},tt=class extends K{code="ENV_VAR_ERROR";constructor(r,n,i,s){super(`Failed to parse environment variable "${r}" with value "${n}" as ${i}`,{envKey:r,envValue:n,expectedType:i,configName:s})}},Lt=class extends K{code="FILE_SYSTEM_ERROR";constructor(r,n,i){super(`File system ${r} failed for "${n}": ${i.message}`,{operation:r,path:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Bt=class extends K{code="TYPE_GENERATION_ERROR";constructor(r,n,i){super(`Failed to generate types from "${r}" to "${n}": ${i.message}`,{configDir:r,outputPath:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Se=class extends K{code="SCHEMA_VALIDATION_ERROR";constructor(r,n,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:r,configName:i,validationErrors:n,errorCount:n.length})}},It=class extends K{code="BROWSER_CONFIG_ERROR";constructor(r,n,i,s){super(`Failed to fetch configuration from "${r}": ${n} ${i}`,{endpoint:r,status:n,statusText:i,configName:s})}},_t=class extends K{code="PLUGIN_ERROR";constructor(r,n,i){super(`Plugin "${r}" failed during ${n}: ${i.message}`,{pluginName:r,operation:n,originalError:i.name,originalMessage:i.message});this.cause=i}},ie={configNotFound(t,r,n){return new et(t,r,n)},configLoad(t,r,n){return new xe(t,r,n)},configValidation(t,r,n){return new Mt(t,r,n)},configMerge(t,r,n,i){return new jt(t,r,n,i)},envVar(t,r,n,i){return new tt(t,r,n,i)},fileSystem(t,r,n){return new Lt(t,r,n)},typeGeneration(t,r,n){return new Bt(t,r,n)},schemaValidation(t,r,n){return new Se(t,r,n)},browserConfig(t,r,n,i){return new It(t,r,n,i)},plugin(t,r,n){return new _t(t,r,n)}},ln={replace:"replace",concat:"concat",smart:"smart"},fn=/^https?:\/\//,G=new Qe("bunfig",{showTags:!0}),te=new Yt,un=I(oe.cwd(),"config"),gn=I(oe.cwd(),"src/generated")});function Es(t,r={}){let n=Ye.cwd();while(n.includes("storage"))n=Cr(n,"..");let i=Cr(n,t||"");if(r?.relative)return ci(Ye.cwd(),i);return i}var xs=Ye.env.CLARITY_LOG_DIR||ai(Es(),"logs"),hn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},rt={...hn},Ca=(async()=>{try{let{loadConfig:t}=await bs().then(()=>Yr),r=await t({name:"clarity",alias:"logging",defaultConfig:hn,cwd:Ye.cwd()});if(r)Object.assign(rt,r)}catch{}return rt})();function R(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ss(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ee<"u"){let t=ee.type;if(t==="renderer"||t==="worker")return!1;return!!(ee.versions&&(ee.versions.node||ee.versions.bun))}return!1}class mn{async format(t){let r=await Ss(),n=await this.getMetadata(r);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:r}=await import("os");return{pid:ye.pid,hostname:r(),environment:ye.env.NODE_ENV||"development",platform:ye.platform,version:ye.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ye.env.NODE_ENV||ye.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var P={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},v=P,{red:ba,green:Ts,yellow:Ea,blue:ks,magenta:xa,cyan:Sa,white:Ir,gray:Ta,bgRed:As,bgYellow:Fs,bgGray:ka,bold:_r,dim:Aa,italic:Fa,underline:Oa,strikethrough:Ra,reset:Pa}=P,Tt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Os={debug:"\uD83D\uDD0D",info:ks("\u2139"),success:Ts("\u2713"),warning:Fs(Ir(_r(" WARN "))),error:As(Ir(_r(" ERROR ")))};class at{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(t,r={}){this.name=t,this.config={...rt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new mn,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??b.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let r={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return r[t]>=r[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Tt,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Tt};return{...Tt,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:rt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}shouldWriteToFile(){return!R()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await hi(this.config.logDirectory,Sr.F_OK|Sr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await mi(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Z.from(t);try{if(!Ne(this.currentLogFile))await Ct(this.currentLogFile,"",{mode:420});if(s=xr(this.currentLogFile,"a",420),gi(s,c,{flag:"a"}),Er(s),s!==void 0)$t(s),s=void 0;if((await de(this.currentLogFile)).size===0){if(await Ct(this.currentLogFile,c,{flag:"w",mode:420}),(await de(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{$t(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 pe(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 pe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return pe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(R())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return vt(16).toString("hex")}generateKey(){return vt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:r}=this.getCurrentKey(),n=vt(16),i=li("aes-256-gcm",r,n),s=Z.isBuffer(t)?t:Z.from(t,"utf8"),o=i.update(s),a=i.final(),l=o.length+a.length,c=i.getAuthTag(),f=Z.allocUnsafe(16+l+16);return n.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:n}}async compressData(t){return new Promise((r,n)=>{let i=kr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(Z.from(Z.concat(s)))),i.on("error",n),i.write(t),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(R())return;if(!this.shouldWriteToFile())return;let t=await de(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Me(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await de(n).catch(()=>null))try{if(await Tr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await je(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await Ct(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await de(n).catch(()=>null))await Tr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await Me(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await je(pe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=br(t),i=ui(r),s=kr();await yi(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}}shouldLog(t){if(!this.enabled)return!1;let r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),Ne(this.currentLogFile))try{let t=xr(this.currentLogFile,"r+");Er(t),$t(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!R()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await Me(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await je(pe(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?v.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||R())return!1;let t=typeof b.env.NO_COLOR<"u",r=b.env.FORCE_COLOR==="0";if(t||r)return!1;return!!(typeof b.stderr<"u"&&b.stderr.isTTY||typeof b.stdout<"u"&&b.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=b.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${v.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}formatMarkdown(t){if(!t)return t;let r=t;return r=r.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,i,s)=>{let o=v.underline(v.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),r=r.replace(/`([^`]+)`/g,(n,i)=>v.bgGray(i)),r=r.replace(/\*\*([^*]+)\*\*/g,(n,i)=>v.bold(i)),r=r.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,i)=>v.italic(i)),r=r.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,i)=>v.italic(i)),r=r.replace(/~([^~]+)~/g,(n,i)=>v.strikethrough(i)),r}supportsHyperlinks(){if(R())return!1;let t=b.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let r=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(r)&&r>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let r=t;if(r.startsWith("file://"))r=r.replace(/^file:\/\//,"");if(r.startsWith("~")){let n=b.env.HOME||"";if(n)r=r.replace(/^~(?=$|\/)/,n)}if(di(r)||r.startsWith("./")||r.startsWith("../"))r=pi(r);else return null;return Ne(r)?r:null}catch{return null}}buildOutputTexts(t){let r=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:r,fileText:n}}async log(t,r,...n){if(!this.shouldLog(t))return;let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":Os[t],m=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",h;switch(t){case"debug":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.gray(c),level:t}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.green(c),level:t}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.error(h),l){let y=l.split(`
41
41
  `);for(let d of y)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:v.gray(` ${d}`),level:t,showTimestamp:!1}))}break}}else if(!R()){if(console.error(`${o} ${this.environment}.${t.toUpperCase()}: ${a}`),l)console.error(l)}let u=`${o} ${this.environment}.${t.toUpperCase()}: ${f}
42
42
  `;if(l)u+=`${l}
43
43
  `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,r=""){let n={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return n;let i=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:r||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!R()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!R()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,c="info")=>{if(!R()&&b.stdout.isTTY)b.stdout.write(`
@@ -58,5 +58,5 @@ export type ConfigOf = Config
58
58
  `;n+=`| Variable | Type | Description | Example |
59
59
  `,n+=`|----------|------|-------------|----------|
60
60
  `;for(let i of t)n+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
61
- `;return n}}var Kr=Ns(import.meta.url),Ie=new Map,kt=new Set;function $n(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="ENOTDIR")}async function Cn(t){let r=Ds(t),n=Ie.get(r),i,s=new Promise((o)=>{i=o});Ie.set(r,s),await n;try{if(Ps(r),Kr.cache[r]?.loaded===!0||kt.has(r))delete Kr.cache[r];try{let o=await import(Ms(r).href);return kt.delete(r),o}catch(o){throw kt.add(r),o}}finally{if(i(),Ie.get(r)===s)Ie.delete(r)}}function Ls(t,r,n={}){return bn(t,r,n,new WeakMap)}function bn(t,r,n,i){let{arrayMergeMode:s="replace",skipNullish:o=!1,customMerger:a}=n;if(r===null||r===void 0)return o?t:r;if(a){let l=a(t,r);if(l!==void 0)return l}if(Array.isArray(r)||Array.isArray(t))return En(t,r,s,i);if(!W(r)||!W(t))return r;return Ks(t,r,n,i)}function En(t,r,n,i){if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(t)&&!Array.isArray(r))return r;if(Array.isArray(r)&&Array.isArray(t))switch(n){case"replace":return r;case"concat":return Bs(t,r);case"smart":return Is(t,r,i);default:return r}return r}function Bs(t,r){let n=[...r];for(let i of t)if(!n.some((s)=>Kt(s,i)))n.push(i);return n}function Is(t,r,n){if(r.length===0)return t;if(t.length===0)return r;if(W(r[0])&&W(t[0]))return _s(t,r,n);if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}function _s(t,r,n){let i=[...r];for(let s of t){if(!W(s)){i.push(s);continue}let o=["id","name","key","path","type"],a=!1;for(let l of o)if(l in s){if(i.find((f)=>W(f)&&(l in f)&&f[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function Ks(t,r,n,i){let s=r;if(W(s)&&i.has(s))return i.get(s);let o={...t};if(W(s))i.set(s,o);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],c=o[a];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[a]=l;continue}if(W(l)&&W(c))o[a]=bn(c,l,n,i);else if(Array.isArray(l)||Array.isArray(c))o[a]=En(c,l,n.arrayMergeMode||"smart",i);else o[a]=l}return o}function xn(t,r,n="replace"){return Ls(t,r,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Kt(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!Kt(t[n],r[n]))return!1;return!0}if(W(t)&&W(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!Kt(t[s],r[s]))return!1}return!0}return!1}function W(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Sn{extensions=Ur;async loadFromPath(t,r,n={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:o,trackPerformance:a=!0,verbose:l=!1,strictDiscovery:c=!1}=n;if(s){let u=Ue.getWithFileCheck("file",t);if(u){if(l)console.log(`Configuration loaded from cache: ${t}`);return u}}let f=async()=>{try{try{js(t)}catch(T){if($n(T)||!c)return null;throw T}let u=await Cn(t),g=Object.hasOwn(u,"default"),m=Object.keys(u).length>0,h=g?u.default:u;if(!g&&!m)throw new se(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new se(t,Error("Configuration must export a valid object"),"unknown");let p={config:xn(r,h,i),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(s)Ue.setWithFileCheck("file",p,t,o);return p}catch(u){throw u instanceof Error?ne.configLoad(t,u):ne.configLoad(t,Error(String(u)))}};if(a)return Vt.track("loadFromPath",f,{path:t});return f()}async tryLoadFromPaths(t,r,n={}){for(let i of t)try{let s=await this.loadFromPath(i,r,n);if(s)return s}catch(s){if(s instanceof se)throw s;if(n.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(t,r,n){return Rn({name:t,directory:r,alias:n})}generateNamePatterns(t,r){return Gr({name:t,alias:r})}checkFileAccess(t){return Rs(async()=>At(t),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,r,n){let i=[];if(!At(t))return i;if(r||n){let s=this.generateNamePatterns(r||"",n);for(let o of s)for(let a of this.extensions){let l=Vr(t,`${o}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),o=s(t);for(let a of o)if(this.looksLikeConfigFile(a)){let l=Vr(t,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}looksLikeConfigFile(t){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((n)=>n.test(t))}async validateConfigFile(t){let r=[];try{if(!At(t))return r.push("Configuration file does not exist"),r;let n=await import(t),i=n.default||n;if(i===void 0)r.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)r.push("Configuration must be an object");else if(Array.isArray(i))r.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),o=s(t,"utf8");JSON.parse(o)}catch(s){r.push(`Invalid JSON syntax: ${s}`)}}catch(n){r.push(`Failed to load configuration file: ${n}`)}return r}async getFileModificationTime(t){try{let{statSync:r}=await import("fs");return r(t).mtime}catch{return null}}async preloadConfigurations(t,r={}){let n=new Map;return await Promise.allSettled(t.map(async(i)=>{try{let s=await this.loadFromPath(i,{},r);if(s)n.set(i,s.config)}catch(s){if(r.verbose)console.warn(`Failed to preload ${i}:`,s)}})),n}}var Ws=/^https?:\/\//;class Tn{async validateConfiguration(t,r,n={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:o=!0,customRules:a=[],trackPerformance:l=!0,verbose:c=!1}=n,f=async()=>{let u=[],g=[],m={stopOnFirstError:i,validateRequired:s,validateTypes:o,customRules:a,trackPerformance:l,verbose:c};try{if(typeof r==="string")return await this.validateWithSchemaFile(t,r,m);else if(Array.isArray(r))return this.validateWithRules(t,[...r,...a],m);else return this.validateWithJSONSchema(t,r,m)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:g}}};if(l)return await Vt.track("validateConfiguration",f);return f()}async validateWithSchemaFile(t,r,n){try{if(!Vs(r))throw new nt(r,[{path:"",message:"Schema file does not exist"}]);let i=await Cn(r),s=Object.hasOwn(i,"default")?i.default:i;if(Array.isArray(s))return this.validateWithRules(t,s,n);else{if(typeof s!=="object"||s===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(t,s,n)}}catch(i){throw new nt(r,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(t,r,n){let i=[],s=[];return this.validateObjectAgainstSchema(t,r,"",i,s,n),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(t,r,n,i,s,o){if(o.validateTypes&&r.type){let a=Array.isArray(t)?"array":typeof t,l=Array.isArray(r.type)?r.type:[r.type];if(!l.includes(a)){if(i.push({path:n,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),o.stopOnFirstError)return}}if(r.enum&&!r.enum.includes(t)){if(i.push({path:n,message:`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"}),o.stopOnFirstError)return}if(typeof t==="string"){if(r.minLength!==void 0&&t.length<r.minLength)i.push({path:n,message:`String length must be at least ${r.minLength}`,expected:`>= ${r.minLength}`,actual:t.length,rule:"minLength"});if(r.maxLength!==void 0&&t.length>r.maxLength)i.push({path:n,message:`String length must not exceed ${r.maxLength}`,expected:`<= ${r.maxLength}`,actual:t.length,rule:"maxLength"});if(r.pattern){if(!new RegExp(r.pattern).test(t))i.push({path:n,message:`String does not match pattern ${r.pattern}`,expected:r.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(r.minimum!==void 0&&t<r.minimum)i.push({path:n,message:`Value must be at least ${r.minimum}`,expected:`>= ${r.minimum}`,actual:t,rule:"minimum"});if(r.maximum!==void 0&&t>r.maximum)i.push({path:n,message:`Value must not exceed ${r.maximum}`,expected:`<= ${r.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&r.items)for(let a=0;a<t.length;a++){let l=n?`${n}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(t[a],r.items,l,i,s,o),o.stopOnFirstError&&i.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let a=t;if(o.validateRequired&&r.required){for(let l of r.required)if(!(l in a)){if(i.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(r.properties){for(let[l,c]of Object.entries(r.properties))if(l in a){let f=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],c,f,i,s,o),o.stopOnFirstError&&i.length>0)return}}if(r.additionalProperties===!1){let l=new Set(Object.keys(r.properties||{}));for(let c of Object.keys(a))if(!l.has(c))s.push({path:n?`${n}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,r,n){let i=[],s=[];for(let o of r)try{let a=this.getValueByPath(t,o.path),l=this.validateWithRule(a,o,o.path);if(i.push(...l),n.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:o.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(t,r,n){let i=[];if(r.required&&(t===void 0||t===null))return i.push({path:n,message:r.message||`Property '${n}' is required`,expected:"required",rule:"required"}),i;if(t===void 0||t===null)return i;if(r.type){let s=Array.isArray(t)?"array":typeof t;if(s!==r.type)i.push({path:n,message:r.message||`Expected type ${r.type}, got ${s}`,expected:r.type,actual:s,rule:"type"})}if(r.min!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s<r.min)i.push({path:n,message:r.message||`Value must be at least ${r.min}`,expected:`>= ${r.min}`,actual:s,rule:"min"})}if(r.max!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s>r.max)i.push({path:n,message:r.message||`Value must not exceed ${r.max}`,expected:`<= ${r.max}`,actual:s,rule:"max"})}if(r.pattern&&typeof t==="string"){if(!r.pattern.test(t))i.push({path:n,message:r.message||`Value does not match pattern ${r.pattern}`,expected:r.pattern.toString(),actual:t,rule:"pattern"})}if(r.enum&&!r.enum.includes(t))i.push({path:n,message:r.message||`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"});if(r.validator){let s=r.validator(t);if(s)i.push({path:n,message:r.message||s,rule:"custom"})}return i}getValueByPath(t,r){if(!r)return t;let n=r.split("."),i=t;for(let s of n)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(t){let r=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of n){let[,s,o,a]=i;r.push({path:s,required:!o,type:this.mapTypeScriptType(a)})}return r}mapTypeScriptType(t){switch(t.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 q=new at("bunfig",{showTags:!0});function zs(t){if(!t)return"";let r=Array.isArray(t)?t.filter(Boolean):[t];if(r.length===0)return"";if(r.length===1)return` or alias "${r[0]}"`;return` or aliases ${r.map((n)=>`"${n}"`).join(", ")}`}class kn{fileLoader=new Sn;envProcessor=new Xt;validator=new Tn;async loadConfig(t){let r=Date.now(),{cache:n,performance:i,schema:s,validate:o,...a}=t,l=a.errorPolicy==="throw"?{...n,enabled:!1}:n;try{if(l?.enabled){let f=this.checkCache(a.name||"",a);if(f)return f}let c;try{c=await this.loadConfigurationStrategies(a,!0,l)}catch(f){if(a.configFile||a.errorPolicy==="throw"&&!(f instanceof we))throw f;let u=a.__strictErrorHandling;if(f instanceof we){if(u&&a.errorPolicy!=="throw")throw f;c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(f instanceof se){let g=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),m=!g&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),h=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(u&&(h||g))throw f;if(m&&(!u||!h))c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(s||o)await this.validateConfiguration(c.config,s,o,a.name);if(l?.enabled&&c)this.cacheResult(a.name||"",c,l,a);if(i?.enabled){let f={operation:"loadConfig",duration:Date.now()-r,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(f);if(i.slowThreshold&&f.duration>i.slowThreshold)q.warn(`Slow configuration loading detected: ${f.duration}ms for ${a.name}`);c.metrics=f}return c}catch(c){if(c instanceof we)throw c;let f=Date.now()-r;throw q.error(`Configuration loading failed after ${f}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,r=!1,n){let{name:i="",alias:s,configFile:o,cwd:a,configDir:l,defaultConfig:c,checkEnv:f=!0,arrayStrategy:u="replace",verbose:g=!1}=t,m=a||it.cwd(),h=[];if(o){let A=Y(m,o);h.push(A);let z=f?$e(i,c,g):c,_=await this.fileLoader.tryLoadFromPaths([A],z,{arrayStrategy:u,verbose:g,cacheTtl:n?.ttl,useCache:n?.enabled!==!1&&(!n?.ttl||n.ttl>100),strictDiscovery:!0});if(!_)throw ne.configNotFound(i||o,h,s);if(g)q.success(`Configuration loaded from explicit path: ${A}`);return this.finalizeResult(_,h,f,i,g)}let y=await this.loadLocalConfiguration(i,s,m,l,c,u,g,f,n,t.errorPolicy==="throw");if(y)return h.push(...this.getLocalSearchPaths(i,s,m,l)),this.finalizeResult(y,h,f,i,g);let d=await this.loadHomeConfiguration(i,s,c,u,g,f,n,t.errorPolicy==="throw");if(d)return h.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,h,f,i,g);let p=await this.loadPackageJsonConfiguration(i,s,m,c,u,g,f,t.errorPolicy);if(p)return h.push(Y(m,"package.json")),this.finalizeResult(p,h,f,i,g);if(h.push(...this.getAllSearchPaths(i,s,m,l)),r)throw ne.configNotFound(i,h,s);return{...await this.applyEnvironmentVariables(i,c,f,g),warnings:[`No configuration file found for "${i}"${zs(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,r,n,i,s,o,a,l,c,f=!1){let u=l?$e(t,s,a):s,g=this.getLocalDirectories(n,i);for(let m of g){if(a)q.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(t,m,r),y=await this.fileLoader.tryLoadFromPaths(h,u,{arrayStrategy:o,verbose:a,cacheTtl:c?.ttl,useCache:c?.enabled!==!1&&(!c?.ttl||c.ttl>100),strictDiscovery:f});if(y){if(a)q.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,r,n,i,s,o,a,l=!1){if(!t)return null;let c=o?$e(t,n,s):n,f=[Y(ae(),".config",t),Y(ae(),".config"),ae()];for(let u of f){if(s)q.info(`Checking home directory: ${u}`);let g=this.fileLoader.generateConfigPaths(t,u,r),m=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:i,verbose:s,cacheTtl:a?.ttl,useCache:a?.enabled!==!1&&(!a?.ttl||a.ttl>100),strictDiscovery:l});if(m){if(s)q.success(`Configuration loaded from home directory: ${m.source.path}`);return m}}return null}async loadPackageJsonConfiguration(t,r,n,i,s,o,a,l){let c=a?$e(t,i,o):i,f=Y(n,"package.json"),u=l==="throw";try{let g=JSON.parse(Dn(f,"utf8"));if(typeof g!=="object"||g===null||Array.isArray(g))throw Error("package.json must contain an object");let m=g,h=r===void 0?[]:Array.isArray(r)?r:[r],d=[t,...h.filter(Boolean)].find((T)=>Object.hasOwn(m,T)&&(u||Boolean(m[T])));if(d===void 0)return null;let p=m[d];if(typeof p!=="object"||p===null||Array.isArray(p))throw Error(`Configuration field "${d}" must contain an object`);if(o)q.success(`Configuration loaded from package.json: ${d}`);return{config:xn(c,p,s),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(g){if($n(g))return null;if(u)throw ne.configLoad(f,g instanceof Error?g:Error(String(g)));if(o)q.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))]);return null}}async applyEnvironmentVariables(t,r,n,i){if(!n||!t||typeof r!=="object"||r===null||Array.isArray(r))return{config:r,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(t,r,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,r,n,i,s){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,r,n,i){let s=[];if(n){let o=n(t);if(o)s.push(...o)}if(r){let o=await this.validator.validateConfiguration(t,r);if(!o.isValid)s.push(...o.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw ne.configValidation(i||"unknown",s,i)}checkCache(t,r){let n=this.generateCacheKey(t,r);return Ue.get(n)||null}cacheResult(t,r,n,i){let s=this.generateCacheKey(t,i);Ue.set(s,r,void 0,n.ttl)}generateCacheKey(t,r){let n=[t];if(r.alias){let i=Array.isArray(r.alias)?r.alias.join(","):r.alias;n.push(`alias:${i}`)}if(r.cwd)n.push(`cwd:${r.cwd}`);if(r.configFile)n.push(`configFile:${r.configFile}`);if(r.configDir)n.push(`configDir:${r.configDir}`);if("checkEnv"in r)n.push(`checkEnv:${r.checkEnv}`);return n.join("|")}getLocalDirectories(t,r){return Pn({cwd:t,configDir:r})}getAllSearchPaths(t,r,n,i){let s=[];return s.push(...this.getLocalSearchPaths(t,r,n,i)),s.push(...this.getHomeSearchPaths(t,r)),s.push(Y(n,"package.json")),s}getLocalSearchPaths(t,r,n,i){let s=this.getLocalDirectories(n,i),o=[];for(let a of s)o.push(...this.fileLoader.generateConfigPaths(t,a,r));return o}getHomeSearchPaths(t,r){if(!t)return[];let n=[Y(ae(),".config",t),Y(ae(),".config"),ae()],i=[];for(let s of n)i.push(...this.fileLoader.generateConfigPaths(t,s,r));return i}async loadConfigWithResult(t){return this.loadConfig(t)}}var Ft=new kn;async function An(t){let r="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let i;if(n)i=await Ft.loadConfig(t);else i=await Ft.loadConfig({...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??r}catch(i){if(t.configFile||t.errorPolicy==="throw")throw i;let s=i instanceof Error?i.message:String(i);if(!(i instanceof we||i instanceof se||i instanceof Ht||s.includes("config"))&&t.verbose)q.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=n?{...t,defaultConfig:r}:{...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Ft.applyEnvironmentVariables(a.name||"",r,!0,a.verbose||!1))?.config??r;return r}}function $e(t,r,n=!1){let i=new Xt,s=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=[`${s}_${g.join("_").toUpperCase()}`,`${s}_${g.map((d)=>d.toUpperCase()).join("")}`,`${s}_${g.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,y;for(let d of m)if(h=it.env[d],h!==void 0){y=d;break}if(h!==void 0&&y)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let d=Number(h);if(!Number.isNaN(d))c[f]=d}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((d)=>d.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,g)}return c}return o(r)}var Ka=Y(it.cwd(),"config"),Va=Y(it.cwd(),"src/generated");var j={cwd:Qt.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},Js=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function qs(t=Qt.cwd()){for(let r of Js){let n=Fn(t,r);if(Us(n))try{let s=await import(Gs(n).href),o=s.default||s.config||s,a=typeof o==="function"?await o():o;return{...j,...a,cwd:t}}catch(i){let s=i instanceof Error?i.message:String(i);e.warn(`Failed to load config from ${r}: ${s}`)}}return null}var ct=new Map;async function oa(t){let r=Fn(t??Qt.cwd()),n=ct.get(r);if(!n)n=(async()=>{let i=await qs(r);if(i)return i;return{...await An({name:"dts",cwd:r,defaultConfig:{...j,cwd:r}}),cwd:r}})(),ct.set(r,n);try{return await n}catch(i){throw ct.delete(r),i}}function aa(){ct.clear()}function ca(t){return{...j,...t}}function la(t){return async()=>{let r=await t();return{...j,...r}}}var P=j;
62
- export{j,oa,aa,ca,la,P};
61
+ `;return n}}var Kr=Ns(import.meta.url),Ie=new Map,kt=new Set;function $n(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="ENOTDIR")}async function Cn(t){let r=Ds(t),n=Ie.get(r),i,s=new Promise((o)=>{i=o});Ie.set(r,s),await n;try{if(Ps(r),Kr.cache[r]?.loaded===!0||kt.has(r))delete Kr.cache[r];try{let o=await import(Ms(r).href);return kt.delete(r),o}catch(o){throw kt.add(r),o}}finally{if(i(),Ie.get(r)===s)Ie.delete(r)}}function Ls(t,r,n={}){return bn(t,r,n,new WeakMap)}function bn(t,r,n,i){let{arrayMergeMode:s="replace",skipNullish:o=!1,customMerger:a}=n;if(r===null||r===void 0)return o?t:r;if(a){let l=a(t,r);if(l!==void 0)return l}if(Array.isArray(r)||Array.isArray(t))return En(t,r,s,i);if(!W(r)||!W(t))return r;return Ks(t,r,n,i)}function En(t,r,n,i){if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(t)&&!Array.isArray(r))return r;if(Array.isArray(r)&&Array.isArray(t))switch(n){case"replace":return r;case"concat":return Bs(t,r);case"smart":return Is(t,r,i);default:return r}return r}function Bs(t,r){let n=[...r];for(let i of t)if(!n.some((s)=>Kt(s,i)))n.push(i);return n}function Is(t,r,n){if(r.length===0)return t;if(t.length===0)return r;if(W(r[0])&&W(t[0]))return _s(t,r,n);if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}function _s(t,r,n){let i=[...r];for(let s of t){if(!W(s)){i.push(s);continue}let o=["id","name","key","path","type"],a=!1;for(let l of o)if(l in s){if(i.find((f)=>W(f)&&(l in f)&&f[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function Ks(t,r,n,i){let s=r;if(W(s)&&i.has(s))return i.get(s);let o={...t};if(W(s))i.set(s,o);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],c=o[a];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[a]=l;continue}if(W(l)&&W(c))o[a]=bn(c,l,n,i);else if(Array.isArray(l)||Array.isArray(c))o[a]=En(c,l,n.arrayMergeMode||"smart",i);else o[a]=l}return o}function xn(t,r,n="replace"){return Ls(t,r,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Kt(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!Kt(t[n],r[n]))return!1;return!0}if(W(t)&&W(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!Kt(t[s],r[s]))return!1}return!0}return!1}function W(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Sn{extensions=Ur;async loadFromPath(t,r,n={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:o,trackPerformance:a=!0,verbose:l=!1,strictDiscovery:c=!1}=n;if(s){let u=Ue.getWithFileCheck("file",t);if(u){if(l)console.log(`Configuration loaded from cache: ${t}`);return u}}let f=async()=>{try{try{js(t)}catch(T){if($n(T)||!c)return null;throw T}let u=await Cn(t),g=Object.hasOwn(u,"default"),m=Object.keys(u).length>0,h=g?u.default:u;if(!g&&!m)throw new se(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new se(t,Error("Configuration must export a valid object"),"unknown");let p={config:xn(r,h,i),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(s)Ue.setWithFileCheck("file",p,t,o);return p}catch(u){throw u instanceof Error?ne.configLoad(t,u):ne.configLoad(t,Error(String(u)))}};if(a)return Vt.track("loadFromPath",f,{path:t});return f()}async tryLoadFromPaths(t,r,n={}){for(let i of t)try{let s=await this.loadFromPath(i,r,n);if(s)return s}catch(s){if(s instanceof se)throw s;if(n.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(t,r,n){return Rn({name:t,directory:r,alias:n})}generateNamePatterns(t,r){return Gr({name:t,alias:r})}checkFileAccess(t){return Rs(async()=>At(t),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,r,n){let i=[];if(!At(t))return i;if(r||n){let s=this.generateNamePatterns(r||"",n);for(let o of s)for(let a of this.extensions){let l=Vr(t,`${o}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),o=s(t);for(let a of o)if(this.looksLikeConfigFile(a)){let l=Vr(t,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}looksLikeConfigFile(t){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((n)=>n.test(t))}async validateConfigFile(t){let r=[];try{if(!At(t))return r.push("Configuration file does not exist"),r;let n=await import(t),i=n.default||n;if(i===void 0)r.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)r.push("Configuration must be an object");else if(Array.isArray(i))r.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),o=s(t,"utf8");JSON.parse(o)}catch(s){r.push(`Invalid JSON syntax: ${s}`)}}catch(n){r.push(`Failed to load configuration file: ${n}`)}return r}async getFileModificationTime(t){try{let{statSync:r}=await import("fs");return r(t).mtime}catch{return null}}async preloadConfigurations(t,r={}){let n=new Map;return await Promise.allSettled(t.map(async(i)=>{try{let s=await this.loadFromPath(i,{},r);if(s)n.set(i,s.config)}catch(s){if(r.verbose)console.warn(`Failed to preload ${i}:`,s)}})),n}}var Ws=/^https?:\/\//;class Tn{async validateConfiguration(t,r,n={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:o=!0,customRules:a=[],trackPerformance:l=!0,verbose:c=!1}=n,f=async()=>{let u=[],g=[],m={stopOnFirstError:i,validateRequired:s,validateTypes:o,customRules:a,trackPerformance:l,verbose:c};try{if(typeof r==="string")return await this.validateWithSchemaFile(t,r,m);else if(Array.isArray(r))return this.validateWithRules(t,[...r,...a],m);else return this.validateWithJSONSchema(t,r,m)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:g}}};if(l)return await Vt.track("validateConfiguration",f);return f()}async validateWithSchemaFile(t,r,n){try{if(!Vs(r))throw new nt(r,[{path:"",message:"Schema file does not exist"}]);let i=await Cn(r),s=Object.hasOwn(i,"default")?i.default:i;if(Array.isArray(s))return this.validateWithRules(t,s,n);else{if(typeof s!=="object"||s===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(t,s,n)}}catch(i){throw new nt(r,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(t,r,n){let i=[],s=[];return this.validateObjectAgainstSchema(t,r,"",i,s,n),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(t,r,n,i,s,o){if(o.validateTypes&&r.type){let a=Array.isArray(t)?"array":typeof t,l=Array.isArray(r.type)?r.type:[r.type];if(!l.includes(a)){if(i.push({path:n,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),o.stopOnFirstError)return}}if(r.enum&&!r.enum.includes(t)){if(i.push({path:n,message:`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"}),o.stopOnFirstError)return}if(typeof t==="string"){if(r.minLength!==void 0&&t.length<r.minLength)i.push({path:n,message:`String length must be at least ${r.minLength}`,expected:`>= ${r.minLength}`,actual:t.length,rule:"minLength"});if(r.maxLength!==void 0&&t.length>r.maxLength)i.push({path:n,message:`String length must not exceed ${r.maxLength}`,expected:`<= ${r.maxLength}`,actual:t.length,rule:"maxLength"});if(r.pattern){if(!new RegExp(r.pattern).test(t))i.push({path:n,message:`String does not match pattern ${r.pattern}`,expected:r.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(r.minimum!==void 0&&t<r.minimum)i.push({path:n,message:`Value must be at least ${r.minimum}`,expected:`>= ${r.minimum}`,actual:t,rule:"minimum"});if(r.maximum!==void 0&&t>r.maximum)i.push({path:n,message:`Value must not exceed ${r.maximum}`,expected:`<= ${r.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&r.items)for(let a=0;a<t.length;a++){let l=n?`${n}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(t[a],r.items,l,i,s,o),o.stopOnFirstError&&i.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let a=t;if(o.validateRequired&&r.required){for(let l of r.required)if(!(l in a)){if(i.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(r.properties){for(let[l,c]of Object.entries(r.properties))if(l in a){let f=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],c,f,i,s,o),o.stopOnFirstError&&i.length>0)return}}if(r.additionalProperties===!1){let l=new Set(Object.keys(r.properties||{}));for(let c of Object.keys(a))if(!l.has(c))s.push({path:n?`${n}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,r,n){let i=[],s=[];for(let o of r)try{let a=this.getValueByPath(t,o.path),l=this.validateWithRule(a,o,o.path);if(i.push(...l),n.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:o.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(t,r,n){let i=[];if(r.required&&(t===void 0||t===null))return i.push({path:n,message:r.message||`Property '${n}' is required`,expected:"required",rule:"required"}),i;if(t===void 0||t===null)return i;if(r.type){let s=Array.isArray(t)?"array":typeof t;if(s!==r.type)i.push({path:n,message:r.message||`Expected type ${r.type}, got ${s}`,expected:r.type,actual:s,rule:"type"})}if(r.min!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s<r.min)i.push({path:n,message:r.message||`Value must be at least ${r.min}`,expected:`>= ${r.min}`,actual:s,rule:"min"})}if(r.max!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s>r.max)i.push({path:n,message:r.message||`Value must not exceed ${r.max}`,expected:`<= ${r.max}`,actual:s,rule:"max"})}if(r.pattern&&typeof t==="string"){if(!r.pattern.test(t))i.push({path:n,message:r.message||`Value does not match pattern ${r.pattern}`,expected:r.pattern.toString(),actual:t,rule:"pattern"})}if(r.enum&&!r.enum.includes(t))i.push({path:n,message:r.message||`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"});if(r.validator){let s=r.validator(t);if(s)i.push({path:n,message:r.message||s,rule:"custom"})}return i}getValueByPath(t,r){if(!r)return t;let n=r.split("."),i=t;for(let s of n)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(t){let r=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of n){let[,s,o,a]=i;r.push({path:s,required:!o,type:this.mapTypeScriptType(a)})}return r}mapTypeScriptType(t){switch(t.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 q=new at("bunfig",{showTags:!0});function zs(t){if(!t)return"";let r=Array.isArray(t)?t.filter(Boolean):[t];if(r.length===0)return"";if(r.length===1)return` or alias "${r[0]}"`;return` or aliases ${r.map((n)=>`"${n}"`).join(", ")}`}class kn{fileLoader=new Sn;envProcessor=new Xt;validator=new Tn;async loadConfig(t){let r=Date.now(),{cache:n,performance:i,schema:s,validate:o,...a}=t,l=a.errorPolicy==="throw"?{...n,enabled:!1}:n;try{if(l?.enabled){let f=this.checkCache(a.name||"",a);if(f)return f}let c;try{c=await this.loadConfigurationStrategies(a,!0,l)}catch(f){if(a.configFile||a.errorPolicy==="throw"&&!(f instanceof we))throw f;let u=a.__strictErrorHandling;if(f instanceof we){if(u&&a.errorPolicy!=="throw")throw f;c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(f instanceof se){let g=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),m=!g&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),h=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(u&&(h||g))throw f;if(m&&(!u||!h))c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(s||o)await this.validateConfiguration(c.config,s,o,a.name);if(l?.enabled&&c)this.cacheResult(a.name||"",c,l,a);if(i?.enabled){let f={operation:"loadConfig",duration:Date.now()-r,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(f);if(i.slowThreshold&&f.duration>i.slowThreshold)q.warn(`Slow configuration loading detected: ${f.duration}ms for ${a.name}`);c.metrics=f}return c}catch(c){if(c instanceof we)throw c;let f=Date.now()-r;throw q.error(`Configuration loading failed after ${f}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,r=!1,n){let{name:i="",alias:s,configFile:o,cwd:a,configDir:l,defaultConfig:c,checkEnv:f=!0,arrayStrategy:u="replace",verbose:g=!1}=t,m=a||it.cwd(),h=[];if(o){let A=Y(m,o);h.push(A);let z=f?$e(i,c,g):c,_=await this.fileLoader.tryLoadFromPaths([A],z,{arrayStrategy:u,verbose:g,cacheTtl:n?.ttl,useCache:n?.enabled!==!1&&(!n?.ttl||n.ttl>100),strictDiscovery:!0});if(!_)throw ne.configNotFound(i||o,h,s);if(g)q.success(`Configuration loaded from explicit path: ${A}`);return this.finalizeResult(_,h,f,i,g)}let y=await this.loadLocalConfiguration(i,s,m,l,c,u,g,f,n,t.errorPolicy==="throw");if(y)return h.push(...this.getLocalSearchPaths(i,s,m,l)),this.finalizeResult(y,h,f,i,g);let d=await this.loadHomeConfiguration(i,s,c,u,g,f,n,t.errorPolicy==="throw");if(d)return h.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,h,f,i,g);let p=await this.loadPackageJsonConfiguration(i,s,m,c,u,g,f,t.errorPolicy);if(p)return h.push(Y(m,"package.json")),this.finalizeResult(p,h,f,i,g);if(h.push(...this.getAllSearchPaths(i,s,m,l)),r)throw ne.configNotFound(i,h,s);return{...await this.applyEnvironmentVariables(i,c,f,g),warnings:[`No configuration file found for "${i}"${zs(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,r,n,i,s,o,a,l,c,f=!1){let u=l?$e(t,s,a):s,g=this.getLocalDirectories(n,i);for(let m of g){if(a)q.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(t,m,r),y=await this.fileLoader.tryLoadFromPaths(h,u,{arrayStrategy:o,verbose:a,cacheTtl:c?.ttl,useCache:c?.enabled!==!1&&(!c?.ttl||c.ttl>100),strictDiscovery:f});if(y){if(a)q.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,r,n,i,s,o,a,l=!1){if(!t)return null;let c=o?$e(t,n,s):n,f=[Y(ae(),".config",t),Y(ae(),".config"),ae()];for(let u of f){if(s)q.info(`Checking home directory: ${u}`);let g=this.fileLoader.generateConfigPaths(t,u,r),m=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:i,verbose:s,cacheTtl:a?.ttl,useCache:a?.enabled!==!1&&(!a?.ttl||a.ttl>100),strictDiscovery:l});if(m){if(s)q.success(`Configuration loaded from home directory: ${m.source.path}`);return m}}return null}async loadPackageJsonConfiguration(t,r,n,i,s,o,a,l){let c=a?$e(t,i,o):i,f=Y(n,"package.json"),u=l==="throw";try{let g=JSON.parse(Dn(f,"utf8"));if(typeof g!=="object"||g===null||Array.isArray(g))throw Error("package.json must contain an object");let m=g,h=r===void 0?[]:Array.isArray(r)?r:[r],d=[t,...h.filter(Boolean)].find((T)=>Object.hasOwn(m,T)&&(u||Boolean(m[T])));if(d===void 0)return null;let p=m[d];if(typeof p!=="object"||p===null||Array.isArray(p))throw Error(`Configuration field "${d}" must contain an object`);if(o)q.success(`Configuration loaded from package.json: ${d}`);return{config:xn(c,p,s),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(g){if($n(g))return null;if(u)throw ne.configLoad(f,g instanceof Error?g:Error(String(g)));if(o)q.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))]);return null}}async applyEnvironmentVariables(t,r,n,i){if(!n||!t||typeof r!=="object"||r===null||Array.isArray(r))return{config:r,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(t,r,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,r,n,i,s){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,r,n,i){let s=[];if(n){let o=n(t);if(o)s.push(...o)}if(r){let o=await this.validator.validateConfiguration(t,r);if(!o.isValid)s.push(...o.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw ne.configValidation(i||"unknown",s,i)}checkCache(t,r){let n=this.generateCacheKey(t,r);return Ue.get(n)||null}cacheResult(t,r,n,i){let s=this.generateCacheKey(t,i);Ue.set(s,r,void 0,n.ttl)}generateCacheKey(t,r){let n=[t];if(r.alias){let i=Array.isArray(r.alias)?r.alias.join(","):r.alias;n.push(`alias:${i}`)}if(r.cwd)n.push(`cwd:${r.cwd}`);if(r.configFile)n.push(`configFile:${r.configFile}`);if(r.configDir)n.push(`configDir:${r.configDir}`);if("checkEnv"in r)n.push(`checkEnv:${r.checkEnv}`);return n.join("|")}getLocalDirectories(t,r){return Pn({cwd:t,configDir:r})}getAllSearchPaths(t,r,n,i){let s=[];return s.push(...this.getLocalSearchPaths(t,r,n,i)),s.push(...this.getHomeSearchPaths(t,r)),s.push(Y(n,"package.json")),s}getLocalSearchPaths(t,r,n,i){let s=this.getLocalDirectories(n,i),o=[];for(let a of s)o.push(...this.fileLoader.generateConfigPaths(t,a,r));return o}getHomeSearchPaths(t,r){if(!t)return[];let n=[Y(ae(),".config",t),Y(ae(),".config"),ae()],i=[];for(let s of n)i.push(...this.fileLoader.generateConfigPaths(t,s,r));return i}async loadConfigWithResult(t){return this.loadConfig(t)}}var Ft=new kn;async function An(t){let r="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let i;if(n)i=await Ft.loadConfig(t);else i=await Ft.loadConfig({...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??r}catch(i){if(t.configFile||t.errorPolicy==="throw")throw i;let s=i instanceof Error?i.message:String(i);if(!(i instanceof we||i instanceof se||i instanceof Ht||s.includes("config"))&&t.verbose)q.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=n?{...t,defaultConfig:r}:{...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Ft.applyEnvironmentVariables(a.name||"",r,!0,a.verbose||!1))?.config??r;return r}}function $e(t,r,n=!1){let i=new Xt,s=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=[`${s}_${g.join("_").toUpperCase()}`,`${s}_${g.map((d)=>d.toUpperCase()).join("")}`,`${s}_${g.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,y;for(let d of m)if(h=it.env[d],h!==void 0){y=d;break}if(h!==void 0&&y)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let d=Number(h);if(!Number.isNaN(d))c[f]=d}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((d)=>d.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,g)}return c}return o(r)}var Ka=Y(it.cwd(),"config"),Va=Y(it.cwd(),"src/generated");var j={cwd:Qt.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},Js=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function qs(t=Qt.cwd()){for(let r of Js){let n=Fn(t,r);if(Us(n))try{let s=await import(Gs(n).href),o=s.default||s.config||s,a=typeof o==="function"?await o():o;return{...j,...a,cwd:t}}catch(i){let s=i instanceof Error?i.message:String(i);e.warn(`Failed to load config from ${r}: ${s}`)}}return null}var ct=new Map;async function oa(t){let r=Fn(t??Qt.cwd()),n=ct.get(r);if(!n)n=(async()=>{let i=await qs(r);if(i)return i;return{...await An({name:"dts",cwd:r,defaultConfig:{...j,cwd:r}}),cwd:r}})(),ct.set(r,n);try{return await n}catch(i){throw ct.delete(r),i}}function aa(){ct.clear()}function ca(t){return{...j,...t}}function la(t){return async()=>{let r=await t();return{...j,...r}}}var D=j;
62
+ export{j,oa,aa,ca,la,D};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{e,M}from"./chunk-qmg1535a.js";import{Ie}from"./chunk-g9emajpc.js";import{s}from"./chunk-ex02f2vm.js";import{existsSync as u,readFileSync as w}from"fs";import{dirname as W,join as d,resolve as v}from"path";async function ei(i){let c=[],n=new Set;async function t(a,f){let o=v(a);if(n.has(o))return;if(n.add(o),!u(o)){e.warn(`tsconfig not found: ${o}`);return}try{let p=w(o,"utf-8"),r=JSON.parse(Ie(p)),l=W(o),g=P(l,f),m=[];if(r.references)for(let y of r.references){let h=v(l,y.path),C=u(d(h,"tsconfig.json"))?d(h,"tsconfig.json"):h;await t(C,g);let G=P(W(C),g);m.push(G)}let j="./src";if(r.compilerOptions?.rootDir)j=r.compilerOptions.rootDir;else if(r.include&&r.include.length>0){if(r.include[0].startsWith("src/"))j="./src"}let k="./dist";if(r.compilerOptions?.outDir)k=r.compilerOptions.outDir;else if(r.compilerOptions?.declarationDir)k=r.compilerOptions.declarationDir;c.push({name:g,root:l,tsconfigPath:o,references:m,config:{root:j,outdir:k}})}catch(p){let r=p instanceof Error?p.message:String(p);e.warn(`Failed to parse ${o}: ${r}`)}}return await t(i),c}function P(i,c){let n=d(i,"package.json");if(u(n))try{let a=w(n,"utf-8"),f=JSON.parse(a);if(f.name)return f.name}catch{}let t=i.split("/").pop()||"unknown";return c?`${c}/${t}`:t}function ti(i){let c=new Map(i.map((o)=>[o.name,o])),n=[],t=new Set,a=new Set;function f(o){if(t.has(o))return;if(a.has(o)){e.warn(`Circular dependency detected involving: ${o}`);return}a.add(o);let p=c.get(o);if(p){for(let r of p.references)f(r);n.push(p)}a.delete(o),t.add(o)}for(let o of i)f(o.name);return n}async function yn(i){let c=Date.now(),n=ti(i.projects);e.info(`Generating declarations for ${n.length} projects...`);let t=[],a=!0;for(let r of n){e.info(`
2
+ import{e,M}from"./chunk-3mp0jaa7.js";import{Ie}from"./chunk-g9emajpc.js";import{s}from"./chunk-zrmg0q1q.js";import{existsSync as u,readFileSync as w}from"fs";import{dirname as W,join as d,resolve as v}from"path";async function ei(i){let c=[],n=new Set;async function t(a,f){let o=v(a);if(n.has(o))return;if(n.add(o),!u(o)){e.warn(`tsconfig not found: ${o}`);return}try{let p=w(o,"utf-8"),r=JSON.parse(Ie(p)),l=W(o),g=P(l,f),m=[];if(r.references)for(let y of r.references){let h=v(l,y.path),C=u(d(h,"tsconfig.json"))?d(h,"tsconfig.json"):h;await t(C,g);let G=P(W(C),g);m.push(G)}let j="./src";if(r.compilerOptions?.rootDir)j=r.compilerOptions.rootDir;else if(r.include&&r.include.length>0){if(r.include[0].startsWith("src/"))j="./src"}let k="./dist";if(r.compilerOptions?.outDir)k=r.compilerOptions.outDir;else if(r.compilerOptions?.declarationDir)k=r.compilerOptions.declarationDir;c.push({name:g,root:l,tsconfigPath:o,references:m,config:{root:j,outdir:k}})}catch(p){let r=p instanceof Error?p.message:String(p);e.warn(`Failed to parse ${o}: ${r}`)}}return await t(i),c}function P(i,c){let n=d(i,"package.json");if(u(n))try{let a=w(n,"utf-8"),f=JSON.parse(a);if(f.name)return f.name}catch{}let t=i.split("/").pop()||"unknown";return c?`${c}/${t}`:t}function ti(i){let c=new Map(i.map((o)=>[o.name,o])),n=[],t=new Set,a=new Set;function f(o){if(t.has(o))return;if(a.has(o)){e.warn(`Circular dependency detected involving: ${o}`);return}a.add(o);let p=c.get(o);if(p){for(let r of p.references)f(r);n.push(p)}a.delete(o),t.add(o)}for(let o of i)f(o.name);return n}async function yn(i){let c=Date.now(),n=ti(i.projects);e.info(`Generating declarations for ${n.length} projects...`);let t=[],a=!0;for(let r of n){e.info(`
3
3
  [${r.name}] Generating...`);try{let l={...i.sharedConfig,...r.config,cwd:r.root,tsconfigPath:r.tsconfigPath},g=await s(l),m=g.filesFailed===0;if(!m)a=!1;t.push({name:r.name,stats:g,success:m}),e.info(`[${r.name}] Generated ${g.filesGenerated} files`)}catch(l){a=!1;let g=l instanceof Error?l.message:String(l);t.push({name:r.name,stats:{generationMode:r.config?.isolatedDeclarations||i.sharedConfig?.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},success:!1,error:g}),e.error(`[${r.name}] Failed: ${g}`)}}let f=Date.now()-c,o=t.filter((r)=>r.success).length,p=t.length-o;if(e.info(`
4
4
  --- Workspace Generation Summary ---`),e.info(`Projects processed: ${t.length}`),e.info(`Successful: ${o}`),p>0)e.info(`Failed: ${p}`);return e.info(`Total duration: ${f}ms`),e.info(`------------------------------------
5
5
  `),{success:a,projects:t,durationMs:f}}async function lo(i,c){if(c?.logLevel)M(c.logLevel);let n=d(i,"tsconfig.json");if(!u(n))throw Error(`Root tsconfig.json not found at: ${n}`);e.info("Discovering workspace projects...");let t=await ei(n);if(t.length===0)return e.warn("No projects found in workspace"),{success:!0,projects:[],durationMs:0};return e.info(`Found ${t.length} projects`),yn({root:i,projects:t,sharedConfig:c})}async function ni(i){let c=d(i,"package.json");if(!u(c))return[];try{let n=w(c,"utf-8"),t=JSON.parse(n),a=[];if(Array.isArray(t.workspaces))a=t.workspaces;else if(t.workspaces?.packages)a=t.workspaces.packages;return a}catch{return[]}}async function ri(i,c){let{Glob:n}=await Promise.resolve(globalThis.Bun),t=[];for(let a of c){let f=new n(a);for await(let o of f.scan({cwd:i,absolute:!0,onlyFiles:!1})){let p=d(o,"package.json");if(u(p))t.push(o)}}return t}async function uo(i,c){if(c?.logLevel)M(c.logLevel);let n=await ni(i);if(n.length===0)return e.warn("No workspace patterns found in package.json"),{success:!0,projects:[],durationMs:0};e.info(`Found workspace patterns: ${n.join(", ")}`);let t=await ri(i,n);if(t.length===0)return e.warn("No projects found matching workspace patterns"),{success:!0,projects:[],durationMs:0};e.info(`Found ${t.length} workspace packages`);let a=t.map((f)=>{let o=d(f,"tsconfig.json");return{name:P(f),root:f,tsconfigPath:u(o)?o:"",references:[]}});return yn({root:i,projects:a,sharedConfig:c})}
@@ -1,16 +1,16 @@
1
1
  // @bun
2
- import{f,be}from"./chunk-587w6ktw.js";import{Vt,Ut,n,We,z}from"./chunk-nqdc6n5d.js";function h(t){if(t.includes(`
2
+ import{f,be}from"./chunk-587w6ktw.js";import{Vt,zt,n,We,U}from"./chunk-txf9rw55.js";function h(t){if(t.includes(`
3
3
  `))return`/**
4
4
  * ${t}
5
5
  */
6
6
  `;return`/** ${t} */
7
- `}function D(t){let o=t.indexOf("{");if(o===-1)return-1;let s=t.indexOf("<");if(s===-1||s>o)return o;let e=0,r=!1,a="";for(let i=0;i<t.length;i++){let l=t[i],u=i>0?t[i-1]:"";if(!r&&(l==='"'||l==="'"||l==="`"))r=!0,a=l;else if(r&&l===a&&u!=="\\")r=!1;if(!r){if(l==="<")e++;else if(l===">")e--;else if(l==="{"&&e===0)return i}}return-1}function fe(t,o=!0){return f(t.leadingComments,o)+t.text}function x(t,o=!0){if(t.inferenceError)throw Object.assign(Error(`Cannot infer alias '${t.name}': unsupported source value flow`),{code:t.inferenceError});let s=f(t.leadingComments,o);if(!t.typeAnnotation&&t.inferredType)return s+t.text;if(t.typeAnnotation&&!t.value)return s+t.text;let e="";if(t.isExported)e+="export ";e+="declare ";let r=t.modifiers?.[0]||"const";e+=`${r} `,e+=t.name;let{typeAnnotation:a,value:i}=t,l=!a&&i?z(i):null;if(l)a=l;else if(!a&&i&&i.trim().endsWith("as const"))a=n(i,!0,!1,0,t.computedKeyConstants);else if(!a&&i&&r==="const"){let c=i.trim(),m=c.startsWith("{")||c.startsWith("[");if(m)Vt();a=n(i,!m,!1,0,t.computedKeyConstants)}else if(!a&&i)a=n(i,r==="const",!1,0,t.computedKeyConstants);if(!a)a="unknown";let u="";if(o&&i&&!t.typeAnnotation&&!i.trim().endsWith("as const")){let c=i.trim();if(r!=="const"){if((a==="string"||a==="number"||a==="boolean")&&c.length>0)u=`@defaultValue ${c}`}else if(c.startsWith("{")||c.startsWith("[")){let m=Ut();if(m)if(m.includes(`
7
+ `}function D(t){let o=t.indexOf("{");if(o===-1)return-1;let s=t.indexOf("<");if(s===-1||s>o)return o;let e=0,r=!1,a="";for(let i=0;i<t.length;i++){let l=t[i],u=i>0?t[i-1]:"";if(!r&&(l==='"'||l==="'"||l==="`"))r=!0,a=l;else if(r&&l===a&&u!=="\\")r=!1;if(!r){if(l==="<")e++;else if(l===">")e--;else if(l==="{"&&e===0)return i}}return-1}function fe(t,o=!0){return f(t.leadingComments,o)+t.text}function x(t,o=!0){if(t.inferenceError)throw Object.assign(Error(`Cannot infer alias '${t.name}': unsupported source value flow`),{code:t.inferenceError});let s=f(t.leadingComments,o);if(!t.typeAnnotation&&t.inferredType)return s+t.text;if(t.typeAnnotation&&!t.value)return s+t.text;let e="";if(t.isExported)e+="export ";e+="declare ";let r=t.modifiers?.[0]||"const";e+=`${r} `,e+=t.name;let{typeAnnotation:a,value:i}=t,l=!a&&i?U(i):null;if(l)a=l;else if(!a&&i&&i.trim().endsWith("as const"))a=n(i,!0,!1,0,t.computedKeyConstants);else if(!a&&i&&r==="const"){let c=i.trim(),m=c.startsWith("{")||c.startsWith("[");if(m)Vt();a=n(i,!m,!1,0,t.computedKeyConstants)}else if(!a&&i)a=n(i,r==="const",!1,0,t.computedKeyConstants);if(!a)a="unknown";let u="";if(o&&i&&!t.typeAnnotation&&!i.trim().endsWith("as const")){let c=i.trim();if(r!=="const"){if((a==="string"||a==="number"||a==="boolean")&&c.length>0)u=`@defaultValue ${c}`}else if(c.startsWith("{")||c.startsWith("[")){let m=zt();if(m)if(m.includes(`
8
8
  `))u=`@defaultValue
9
9
  * \`\`\`ts
10
10
  ${m.split(`
11
11
  `).map((p)=>` * ${p}`).join(`
12
12
  `)}
13
- * \`\`\``;else u=`@defaultValue \`${m}\``}}else if(o&&i&&t.typeAnnotation&&We(t.typeAnnotation)){Vt();let c=i.trim(),m=c.endsWith("as const")?c.slice(0,-8).trim():c;n(m,!1,!1,0,t.computedKeyConstants);let d=Ut();if(d)if(d.includes(`
13
+ * \`\`\``;else u=`@defaultValue \`${m}\``}}else if(o&&i&&t.typeAnnotation&&We(t.typeAnnotation)){Vt();let c=i.trim(),m=c.endsWith("as const")?c.slice(0,-8).trim():c;n(m,!1,!1,0,t.computedKeyConstants);let d=zt();if(d)if(d.includes(`
14
14
  `))u=`@defaultValue
15
15
  * \`\`\`ts
16
16
  ${d.split(`
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- var e="@dtsx/dtsx",i="module",n="0.11.48",r=!0,c="A modern, fast .d.ts generation tool, powered by Bun.",u="Chris Breuer <chris@stacksjs.org>",a="MIT",b="https://github.com/stacksjs/dtsx#readme",o={type:"git",url:"git+https://github.com/stacksjs/dtsx.git"},p={url:"https://github.com/stacksjs/dtsx/issues"},d=["dts","generation","isolated declarations","development","bun","stacks","typescript","javascript"],m={".":{import:"./dist/index.js"},"./*":{import:"./dist/*"}},k="./dist/index.js",l="./dist/index.d.ts",x={dtsx:"./dist/cli.js"},g=["dist"],h={benchmark:"bun benchmark/index.ts","benchmark:prepare":"cd packages/zig-dtsx && zig build -Doptimize=ReleaseFast && cd ../.. && bun build benchmark/oxc-emit.ts --compile --splitting --bytecode --minify --format=esm --outfile benchmark/oxc-emit","benchmark:publish":"bun benchmark/index.ts --json benchmark/results.json --runs 3 && bun benchmark/render.ts","benchmark:tsdown":"bun benchmark/tsdown.ts",build:"bun --filter './packages/dtsx' build",test:"find packages -name '*.test.ts' -print | xargs bun test","test:public-sdk":"bun scripts/verify-public-sdk.ts","test:standalone":"bun scripts/verify-standalone.ts","typecheck:public-sdk":"bun x tsc --project tsconfig.public-sdk.json",lint:"bun x --bun pickier .","lint:fix":"bun x --bun pickier . --fix",format:"bun x --bun pickier . --format","format:fix":"bun x --bun pickier . --format --write",changelog:"bun x @stacksjs/logsmith --verbose","changelog:generate":"bun x @stacksjs/logsmith --output CHANGELOG.md",release:"bun x --bun @stacksjs/bumpx prompt --recursive","release:patch":"bun x --bun @stacksjs/bumpx patch --recursive --commit --tag --push --yes","release:minor":"bun x --bun @stacksjs/bumpx minor --recursive --commit --tag --push --yes",typecheck:"bun x tsc --noEmit","dev:docs":"bun --bun bunpress dev docs","build:docs":"bun --bun bunpress build docs","preview:docs":"bun --bun bunpress preview docs"},j={"@stacksjs/bumpx":"^0.2.32","@stacksjs/bunpress":"^0.2.31","@stacksjs/clapp":"^0.2.16",pickier:"^0.1.88","@stacksjs/gitlint":"^0.1.8","@stacksjs/logsmith":"^0.2.14","@types/bun":"^1.4.4","buddy-bot":"^0.10.5","bun-git-hooks":"^0.3.3","@dtsx/bun":"workspace:*",mitata:"^1.0.34","oxc-transform":"^0.157.0","oxc-parser":"^0.157.0",tsdown:"^0.23.7",typescript:"^7.0.2"},y=["packages/*"],f={typescript:"^7.0.2"},v={name:e,type:i,version:n,private:r,description:c,author:u,license:a,homepage:b,repository:o,bugs:p,keywords:d,exports:m,module:k,types:l,bin:x,files:g,scripts:h,devDependencies:j,workspaces:y,overrides:f,"git-hooks":{"pre-commit":{"staged-lint":{"*.{js,ts,json,yaml,yml,md}":"bun x --bun pickier lint --fix"}},"commit-msg":"bun x gitlint --edit .git/COMMIT_EDITMSG"}};export{u as author,x as bin,p as bugs,v as default,c as description,j as devDependencies,m as exports,g as files,b as homepage,d as keywords,a as license,k as module,e as name,f as overrides,r as private,o as repository,h as scripts,i as type,l as types,n as version,y as workspaces};
2
+ var e="@dtsx/dtsx",i="module",n="0.11.50",r=!0,c="A modern, fast .d.ts generation tool, powered by Bun.",u="Chris Breuer <chris@stacksjs.org>",a="MIT",b="https://github.com/stacksjs/dtsx#readme",o={type:"git",url:"git+https://github.com/stacksjs/dtsx.git"},p={url:"https://github.com/stacksjs/dtsx/issues"},d=["dts","generation","isolated declarations","development","bun","stacks","typescript","javascript"],m={".":{import:"./dist/index.js"},"./*":{import:"./dist/*"}},k="./dist/index.js",l="./dist/index.d.ts",x={dtsx:"./dist/cli.js"},g=["dist"],h={benchmark:"bun benchmark/index.ts","benchmark:prepare":"cd packages/zig-dtsx && zig build -Doptimize=ReleaseFast && cd ../.. && bun build benchmark/oxc-emit.ts --compile --splitting --bytecode --minify --format=esm --outfile benchmark/oxc-emit","benchmark:publish":"bun benchmark/index.ts --json benchmark/results.json --runs 3 && bun benchmark/render.ts","benchmark:tsdown":"bun benchmark/tsdown.ts",build:"bun --filter './packages/dtsx' build",test:"find packages -name '*.test.ts' -print | xargs bun test","test:public-sdk":"bun scripts/verify-public-sdk.ts","test:standalone":"bun scripts/verify-standalone.ts","typecheck:public-sdk":"bun x tsc --project tsconfig.public-sdk.json",lint:"bun x --bun pickier .","lint:fix":"bun x --bun pickier . --fix",format:"bun x --bun pickier . --format","format:fix":"bun x --bun pickier . --format --write",changelog:"bun x @stacksjs/logsmith --verbose","changelog:generate":"bun x @stacksjs/logsmith --output CHANGELOG.md",release:"bun x --bun @stacksjs/bumpx prompt --recursive","release:patch":"bun x --bun @stacksjs/bumpx patch --recursive --commit --tag --push --yes","release:minor":"bun x --bun @stacksjs/bumpx minor --recursive --commit --tag --push --yes",typecheck:"bun x tsc --noEmit","dev:docs":"bun --bun bunpress dev docs","build:docs":"bun --bun bunpress build docs","preview:docs":"bun --bun bunpress preview docs"},j={"@stacksjs/bumpx":"^0.2.32","@stacksjs/bunpress":"^0.2.31","@stacksjs/clapp":"^0.2.16",pickier:"^0.1.88","@stacksjs/gitlint":"^0.1.8","@stacksjs/logsmith":"^0.2.14","@types/bun":"^1.4.4","buddy-bot":"^0.10.5","bun-git-hooks":"^0.3.3","@dtsx/bun":"workspace:*",mitata:"^1.0.34","oxc-transform":"^0.157.0","oxc-parser":"^0.157.0",tsdown:"^0.23.7",typescript:"^7.0.2"},y=["packages/*"],f={typescript:"^7.0.2"},v={name:e,type:i,version:n,private:r,description:c,author:u,license:a,homepage:b,repository:o,bugs:p,keywords:d,exports:m,module:k,types:l,bin:x,files:g,scripts:h,devDependencies:j,workspaces:y,overrides:f,"git-hooks":{"pre-commit":{"staged-lint":{"*.{js,ts,json,yaml,yml,md}":"bun x --bun pickier lint --fix"}},"commit-msg":"bun x gitlint --edit .git/COMMIT_EDITMSG"}};export{u as author,x as bin,p as bugs,v as default,c as description,j as devDependencies,m as exports,g as files,b as homepage,d as keywords,a as license,k as module,e as name,f as overrides,r as private,o as repository,h as scripts,i as type,l as types,n as version,y as workspaces};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{t,d}from"./chunk-d0dbet9n.js";import{V}from"./chunk-hnw7mwcw.js";import{jt}from"./chunk-hzjesnf1.js";import{v}from"./chunk-vhna4qch.js";import{ae}from"./chunk-29m9mhwt.js";import{relative as O}from"path";function P(n){let k=t(n),c=(l)=>k[l]?n.slice(k[l].start,k[l].end):"",i=c(0)==="export"?1:0;if(c(i++)!=="declare")return;let f;if(c(i)==="module"&&k[i+1]?.kind==="quoted"){if(f=d(c(i+1)),f===void 0)return;i+=2}else if(c(i++)!=="global")return;if(c(i)!=="{")return;let h=k[i].end,M=1;for(i++;i<k.length;i++)if(c(i)==="{")M++;else if(c(i)==="}"&&--M===0)return{specifier:f,body:n.slice(h,k[i].start),start:h,end:k[i].start};return}var te=/^[A-Z_$][\w$]*$/i;function Oo(n){let k=[],c=[],i=0,f=0,h=[],M=!1,l=0,y=n.length,R=(a)=>{let b=n.slice(i,a).trim();if(i=a,!b)return;if(ne(b)){c.push(b);return}k.push({text:b,comments:c}),c=[]};while(l<y){let a=n[l];if(M){if(a==="\\"){l+=2;continue}if(a==="`"){M=!1,l++;continue}if(a==="$"&&n[l+1]==="{"){h.push(f),f++,M=!1,l+=2;continue}l++;continue}if(a==="/"&&n[l+1]==="*"){let b=n.indexOf("*/",l+2);l=b===-1?y:b+2;continue}if(a==="/"&&n[l+1]==="/"){let b=n.indexOf(`
2
+ import{t,d}from"./chunk-6exq13f9.js";import{V}from"./chunk-zrfwvjq8.js";import{jt}from"./chunk-qx0pxmvs.js";import{v}from"./chunk-h3r142dy.js";import{ae}from"./chunk-vvy85nm6.js";import{relative as O}from"path";function P(n){let k=t(n),c=(l)=>k[l]?n.slice(k[l].start,k[l].end):"",i=c(0)==="export"?1:0;if(c(i++)!=="declare")return;let f;if(c(i)==="module"&&k[i+1]?.kind==="quoted"){if(f=d(c(i+1)),f===void 0)return;i+=2}else if(c(i++)!=="global")return;if(c(i)!=="{")return;let h=k[i].end,M=1;for(i++;i<k.length;i++)if(c(i)==="{")M++;else if(c(i)==="}"&&--M===0)return{specifier:f,body:n.slice(h,k[i].start),start:h,end:k[i].start};return}var te=/^[A-Z_$][\w$]*$/i;function Oo(n){let k=[],c=[],i=0,f=0,h=[],M=!1,l=0,y=n.length,R=(a)=>{let b=n.slice(i,a).trim();if(i=a,!b)return;if(ne(b)){c.push(b);return}k.push({text:b,comments:c}),c=[]};while(l<y){let a=n[l];if(M){if(a==="\\"){l+=2;continue}if(a==="`"){M=!1,l++;continue}if(a==="$"&&n[l+1]==="{"){h.push(f),f++,M=!1,l+=2;continue}l++;continue}if(a==="/"&&n[l+1]==="*"){let b=n.indexOf("*/",l+2);l=b===-1?y:b+2;continue}if(a==="/"&&n[l+1]==="/"){let b=n.indexOf(`
3
3
  `,l);l=b===-1?y:b;continue}if(a==="'"||a==='"'){l++;while(l<y&&n[l]!==a&&n[l]!==`
4
4
  `){if(n[l]==="\\")l++;l++}l++;continue}if(a==="`"){M=!0,l++;continue}if(a==="("||a==="["||a==="{"){f++,l++;continue}if(a===")"||a==="]"||a==="}"){if(f--,h.length>0&&a==="}"&&f===h[h.length-1])h.pop(),M=!0;l++;continue}if(f===0&&a===";"){R(l+1),l++;continue}if(f===0&&a===`
5
5
  `){let b=n[l+1];if(b!==void 0&&/[\w$@/]/.test(b))R(l+1);l++;continue}l++}return R(y),k}function ne(n){let k=0;while(k<n.length){while(k<n.length&&/\s/.test(n[k]))k++;if(k>=n.length)return!0;if(n.startsWith("//",k)){let c=n.indexOf(`
@@ -8,7 +8,7 @@ import{t,d}from"./chunk-d0dbet9n.js";import{V}from"./chunk-hnw7mwcw.js";import{j
8
8
  `;while(a<b){let m=i.get(a);if(m!==void 0){R+=n.slice(a,m),a=m,S="`";continue}let x=n[a];if(x==="/"&&n[a+1]==="*"){let w=n.indexOf("*/",a+2),N=w===-1?b:w+2;R+=n.slice(a,N),a=N;continue}if(x==="/"&&n[a+1]==="/"){let w=n.indexOf(`
9
9
  `,a),N=w===-1?b:w;R+=n.slice(a,N),a=N;continue}if(x==="'"||x==='"'){let w=a+1;while(w<b&&n[w]!==x&&n[w]!==`
10
10
  `){if(n[w]==="\\")w++;w++}R+=n.slice(a,w+1),a=w+1,S=x;continue}if(/[A-Z_$]/i.test(x)){let w=a+1;while(w<b&&/[\w$]/.test(n[w]))w++;let N=n.slice(a,w),I=k.get(N);if(I!==void 0&&S!=="."&&!y.has(a)){let u=w;while(u<b&&(n[u]===" "||n[u]==="\t"))u++;let D=(n[u]===":"||n[u]==="?"&&n[u+1]===":")&&/[{;,(\n]/.test(S);R+=D?N:I}else R+=N;S="a",a=w;continue}if(R+=x,x===`
11
- `||!/\s/.test(x))S=x;a++}return R}function Dn(n,k,c,i){let f=[],h=new Map,M=[n,...k.filter((e)=>e!==n)];for(let e of M){let s=c.get(e);if(s===void 0){f.push(`No declarations were generated for ${O(i.cwd,e)}; it is left out of the bundle`);continue}h.set(e,q(e,s))}let l=(e,s)=>{if(!e.startsWith(".")&&!e.startsWith("/"))return null;let o=ae(e,s).resolved;return o&&h.has(o)?o:null},y=(e)=>e.startsWith(".")||e.startsWith("/"),R=new Set,a=(e)=>{let s=e;for(let o=1;R.has(s);o++)s=`${e}_${o}`;return R.add(s),s},b=new Map;for(let[e,s]of h){let o=new Map;for(let g of s.declared)o.set(g,a(g));b.set(e,o)}let S=new Map,m=(e,s,o)=>{let g=`${e}\x00${s}`,r=S.get(g);if(!r)r=a(o),S.set(g,r);return r},x=new Map,w=new Map,N=new Set,I=new Map,u=!0,D=(e,s,o)=>{let g=l(s,e.file);if(g){if(o==="*")return{kind:"namespace",file:g};let r=L(g).get(o);if(!r&&!u)f.push(`${O(i.cwd,e.file)}: '${o}' is not exported by '${s}'`);return r??null}if(y(s))return f.push(`${O(i.cwd,e.file)}: '${s}' is not part of the bundle`),null;return o==="*"?{kind:"external-namespace",source:s}:{kind:"external",source:s,imported:o}},Y=(e,s)=>{if(e.declared.has(s))return{kind:"local",name:b.get(e.file).get(s)};let o=e.imports.get(s);if(o)return D(e,o.specifier,o.imported);return f.push(`${O(i.cwd,e.file)}: cannot resolve exported name '${s}'`),null};function L(e){let s=x.get(e);if(s)return s;let o=new Map,g=h.get(e);if(!g||N.has(e))return o;N.add(e);let r=new Set;for(let[p,E]of g.localExports){let B=Y(g,E);if(B)o.set(p,B)}for(let p of g.namedReExports){let E=D(g,p.specifier,p.imported);if(E)o.set(p.exported,E)}for(let p of g.namespaceReExports){let E=D(g,p.specifier,"*");if(E)o.set(p.exported,E)}for(let p of g.starReExports){let E=l(p,e);if(E){for(let[B,C]of L(E))if(B!=="default"&&!o.has(B))o.set(B,C);for(let B of w.get(E)??[])r.add(B)}else if(y(p))f.push(`${O(i.cwd,e)}: '${p}' is not part of the bundle`);else r.add(p)}for(let[p,E]of I.get(e)??[])o.set(p,E);return N.delete(e),x.set(e,o),w.set(e,r),o}for(let[e,s]of h)for(let o of s.augmentations){let g=l(o.specifier,e);if(!g)continue;for(let r of q(e,o.body,!0).declared){if(L(g).has(r))continue;let p=I.get(g);if(!p)p=new Map,I.set(g,p);p.set(r,{kind:"local",name:a(r)}),x.clear()}}u=!1,x.clear(),w.clear();let J=new Map,F=[],z=(e,s)=>{switch(e.kind){case"local":return e.name;case"external":return m(e.source,e.imported,e.imported==="default"?s:e.imported);case"external-namespace":return m(e.source,"*",s);case"namespace":return ee(e.file,s)}};function ee(e,s){let o=J.get(e);if(o)return o;let g=a(s);J.set(e,g);let r=[];for(let[p,E]of L(e)){if(p==="default")continue;let B=z(E,p);r.push(B===p?p:`${B} as ${p}`)}if(w.get(e)?.size)f.push(`${O(i.cwd,e)}: 'export * from' an external module cannot be expressed inside namespace '${g}'`);return F.push(`declare namespace ${g} {
11
+ `||!/\s/.test(x))S=x;a++}return R}function Pn(n,k,c,i){let f=[],h=new Map,M=[n,...k.filter((e)=>e!==n)];for(let e of M){let s=c.get(e);if(s===void 0){f.push(`No declarations were generated for ${O(i.cwd,e)}; it is left out of the bundle`);continue}h.set(e,q(e,s))}let l=(e,s)=>{if(!e.startsWith(".")&&!e.startsWith("/"))return null;let o=ae(e,s).resolved;return o&&h.has(o)?o:null},y=(e)=>e.startsWith(".")||e.startsWith("/"),R=new Set,a=(e)=>{let s=e;for(let o=1;R.has(s);o++)s=`${e}_${o}`;return R.add(s),s},b=new Map;for(let[e,s]of h){let o=new Map;for(let g of s.declared)o.set(g,a(g));b.set(e,o)}let S=new Map,m=(e,s,o)=>{let g=`${e}\x00${s}`,r=S.get(g);if(!r)r=a(o),S.set(g,r);return r},x=new Map,w=new Map,N=new Set,I=new Map,u=!0,D=(e,s,o)=>{let g=l(s,e.file);if(g){if(o==="*")return{kind:"namespace",file:g};let r=L(g).get(o);if(!r&&!u)f.push(`${O(i.cwd,e.file)}: '${o}' is not exported by '${s}'`);return r??null}if(y(s))return f.push(`${O(i.cwd,e.file)}: '${s}' is not part of the bundle`),null;return o==="*"?{kind:"external-namespace",source:s}:{kind:"external",source:s,imported:o}},Y=(e,s)=>{if(e.declared.has(s))return{kind:"local",name:b.get(e.file).get(s)};let o=e.imports.get(s);if(o)return D(e,o.specifier,o.imported);return f.push(`${O(i.cwd,e.file)}: cannot resolve exported name '${s}'`),null};function L(e){let s=x.get(e);if(s)return s;let o=new Map,g=h.get(e);if(!g||N.has(e))return o;N.add(e);let r=new Set;for(let[p,E]of g.localExports){let B=Y(g,E);if(B)o.set(p,B)}for(let p of g.namedReExports){let E=D(g,p.specifier,p.imported);if(E)o.set(p.exported,E)}for(let p of g.namespaceReExports){let E=D(g,p.specifier,"*");if(E)o.set(p.exported,E)}for(let p of g.starReExports){let E=l(p,e);if(E){for(let[B,C]of L(E))if(B!=="default"&&!o.has(B))o.set(B,C);for(let B of w.get(E)??[])r.add(B)}else if(y(p))f.push(`${O(i.cwd,e)}: '${p}' is not part of the bundle`);else r.add(p)}for(let[p,E]of I.get(e)??[])o.set(p,E);return N.delete(e),x.set(e,o),w.set(e,r),o}for(let[e,s]of h)for(let o of s.augmentations){let g=l(o.specifier,e);if(!g)continue;for(let r of q(e,o.body,!0).declared){if(L(g).has(r))continue;let p=I.get(g);if(!p)p=new Map,I.set(g,p);p.set(r,{kind:"local",name:a(r)}),x.clear()}}u=!1,x.clear(),w.clear();let J=new Map,F=[],z=(e,s)=>{switch(e.kind){case"local":return e.name;case"external":return m(e.source,e.imported,e.imported==="default"?s:e.imported);case"external-namespace":return m(e.source,"*",s);case"namespace":return ee(e.file,s)}};function ee(e,s){let o=J.get(e);if(o)return o;let g=a(s);J.set(e,g);let r=[];for(let[p,E]of L(e)){if(p==="default")continue;let B=z(E,p);r.push(B===p?p:`${B} as ${p}`)}if(w.get(e)?.size)f.push(`${O(i.cwd,e)}: 'export * from' an external module cannot be expressed inside namespace '${g}'`);return F.push(`declare namespace ${g} {
12
12
  export { ${r.join(", ")} };
13
13
  }`),g}let Q=[],A=[],H=new Set;for(let[e,s]of h){for(let r of s.directives)H.add(r);let o=new Map;for(let[r,p]of b.get(e))if(r!==p)o.set(r,p);for(let[r,p]of s.imports){if(s.declared.has(r))continue;let E=D(s,p.specifier,p.imported);if(!E)continue;let B=z(E,r);if(B!==r)o.set(r,B)}let g=[];for(let r of s.declarations){if(i.keepComments)g.push(...r.statement.comments);let p=nt(r.emit,o);if(!/[;}]$/.test(p))p+=";";g.push(p)}for(let r of s.verbatim){if(i.keepComments)A.push(...r.comments);let p=P(r.text);if(p){let E=new Map(o);for(let B of q(e,p.body,!0).declared)E.delete(B);A.push(r.text.slice(0,p.start)+nt(p.body,E)+r.text.slice(p.end))}else{let E=t(r.text),B=E[1]?.kind==="quoted"?d(r.text.slice(E[1].start,E[1].end)):void 0;if(B===void 0||!l(B,e))A.push(nt(r.text,o))}}for(let r of s.augmentations){let p=l(r.specifier,e),E=q(e,r.body,!0),B=new Map(o);if(!p){for(let K of E.declared)B.delete(K);let C=P(r.statement.text);if(i.keepComments)A.push(...r.statement.comments);A.push(r.statement.text.slice(0,C.start)+nt(C.body,B)+r.statement.text.slice(C.end));continue}for(let[C,K]of L(p))B.set(C,z(K,C));if(i.keepComments)g.push(...r.statement.comments);for(let C of E.declarations){if(!C.name||!L(p).has(C.name))throw Error(`Cannot link augmentation '${r.specifier}' member '${C.name??C.emit}'`);if(i.keepComments)g.push(...C.statement.comments);g.push(nt(C.emit,B))}}if(g.length>0)Q.push(`// From: ${O(i.cwd,e)}
14
14
  ${g.join(`
@@ -24,4 +24,4 @@ ${g.join(`
24
24
 
25
25
  `)}
26
26
  `,files:[...h.keys()],exportCount:U.size,warnings:f}}
27
- export{Oo,nt,Dn};
27
+ export{Oo,nt,Pn};