pickier 0.1.68 → 0.1.69

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 (135) hide show
  1. package/dist/bin/cli.js +2 -2
  2. package/dist/chunk-0wjnsb7e.js +3 -0
  3. package/dist/chunk-1c4363f9.js +3 -0
  4. package/dist/chunk-1gsmqw00.js +2 -0
  5. package/dist/chunk-1r811fef.js +9 -0
  6. package/dist/chunk-861zc8zq.js +2 -0
  7. package/dist/chunk-9nk05dhr.js +3 -0
  8. package/dist/chunk-9w2q7ghj.js +2 -0
  9. package/dist/chunk-acdw0br0.js +3 -0
  10. package/dist/chunk-dqv1qww5.js +128 -0
  11. package/dist/chunk-dxrcbgyc.js +49 -0
  12. package/dist/chunk-he3fbz3w.js +8 -0
  13. package/dist/chunk-hyabhvem.js +2 -0
  14. package/dist/chunk-jqsghmew.js +3 -0
  15. package/dist/chunk-t4eg5fx5.js +41 -0
  16. package/dist/chunk-vjsh2bkt.js +25 -0
  17. package/dist/chunk-w7q10fyj.js +2 -0
  18. package/dist/chunk-yvrap76h.js +3 -0
  19. package/dist/chunk-zp6n036m.js +61 -0
  20. package/dist/native/darwin-arm64/pickier-native +0 -0
  21. package/dist/native/darwin-x64/pickier-native +0 -0
  22. package/dist/native/linux-arm64/pickier-native +0 -0
  23. package/dist/native/linux-x64/pickier-native +0 -0
  24. package/dist/native/win32-arm64/pickier-native.exe +0 -0
  25. package/dist/native/win32-x64/pickier-native.exe +0 -0
  26. package/dist/src/cache.d.ts +21 -0
  27. package/dist/src/index.js +1 -1
  28. package/dist/src/lexer.d.ts +2 -0
  29. package/dist/src/lint-worker.d.ts +1 -0
  30. package/dist/src/lint-worker.js +2 -0
  31. package/dist/src/linter.d.ts +17 -1
  32. package/dist/src/logger.d.ts +20 -0
  33. package/dist/src/native.d.ts +64 -0
  34. package/dist/src/parallel.d.ts +17 -0
  35. package/dist/src/plugins/lazy.d.ts +10 -0
  36. package/dist/src/plugins/manifest.d.ts +123 -0
  37. package/dist/src/plugins/utils.d.ts +6 -0
  38. package/dist/src/rules/style/consistent-list-newline.d.ts +2 -0
  39. package/dist/src/types.d.ts +1 -0
  40. package/dist/src/utils.d.ts +1 -0
  41. package/package.json +3 -2
  42. package/dist/chunk-5dpt7qv4.js +0 -2
  43. package/dist/chunk-ek25vxkw.js +0 -2
  44. package/dist/chunk-jcy3sgzh.js +0 -2
  45. package/dist/chunk-q47v401h.js +0 -92
  46. package/dist/chunk-s0n5r5hb.js +0 -227
  47. package/dist/chunk-zeaz9zt8.js +0 -2
  48. package/dist/src/plugins/index.d.ts +0 -2
  49. package/dist/src/plugins/lockfile.d.ts +0 -22
  50. package/dist/src/plugins/markdown.d.ts +0 -2
  51. package/dist/src/plugins/publint.d.ts +0 -10
  52. package/dist/src/plugins/shell.d.ts +0 -2
  53. package/dist/src/plugins/spell.d.ts +0 -3
  54. package/dist/src/rules/lockfile/parser.d.ts +0 -85
  55. package/dist/src/rules/lockfile/validate-host.d.ts +0 -18
  56. package/dist/src/rules/lockfile/validate-https.d.ts +0 -14
  57. package/dist/src/rules/lockfile/validate-integrity.d.ts +0 -19
  58. package/dist/src/rules/lockfile/validate-package-names.d.ts +0 -23
  59. package/dist/src/rules/lockfile/validate-scheme.d.ts +0 -17
  60. package/dist/src/rules/markdown/_fence-tracking.d.ts +0 -70
  61. package/dist/src/rules/markdown/_shared.d.ts +0 -9
  62. package/dist/src/rules/markdown/blanks-around-fences.d.ts +0 -5
  63. package/dist/src/rules/markdown/blanks-around-headings.d.ts +0 -5
  64. package/dist/src/rules/markdown/blanks-around-lists.d.ts +0 -5
  65. package/dist/src/rules/markdown/blanks-around-tables.d.ts +0 -5
  66. package/dist/src/rules/markdown/code-block-style.d.ts +0 -5
  67. package/dist/src/rules/markdown/code-fence-style.d.ts +0 -5
  68. package/dist/src/rules/markdown/commands-show-output.d.ts +0 -5
  69. package/dist/src/rules/markdown/descriptive-link-text.d.ts +0 -5
  70. package/dist/src/rules/markdown/emphasis-style.d.ts +0 -5
  71. package/dist/src/rules/markdown/fenced-code-language.d.ts +0 -5
  72. package/dist/src/rules/markdown/first-line-heading.d.ts +0 -5
  73. package/dist/src/rules/markdown/heading-increment.d.ts +0 -5
  74. package/dist/src/rules/markdown/heading-start-left.d.ts +0 -5
  75. package/dist/src/rules/markdown/heading-style.d.ts +0 -5
  76. package/dist/src/rules/markdown/hr-style.d.ts +0 -5
  77. package/dist/src/rules/markdown/line-length.d.ts +0 -5
  78. package/dist/src/rules/markdown/link-fragments.d.ts +0 -5
  79. package/dist/src/rules/markdown/link-image-reference-definitions.d.ts +0 -5
  80. package/dist/src/rules/markdown/link-image-style.d.ts +0 -5
  81. package/dist/src/rules/markdown/list-indent.d.ts +0 -5
  82. package/dist/src/rules/markdown/list-marker-space.d.ts +0 -5
  83. package/dist/src/rules/markdown/no-alt-text.d.ts +0 -5
  84. package/dist/src/rules/markdown/no-bare-urls.d.ts +0 -5
  85. package/dist/src/rules/markdown/no-blanks-blockquote.d.ts +0 -5
  86. package/dist/src/rules/markdown/no-duplicate-heading.d.ts +0 -10
  87. package/dist/src/rules/markdown/no-emphasis-as-heading.d.ts +0 -9
  88. package/dist/src/rules/markdown/no-empty-links.d.ts +0 -5
  89. package/dist/src/rules/markdown/no-hard-tabs.d.ts +0 -5
  90. package/dist/src/rules/markdown/no-inline-html.d.ts +0 -5
  91. package/dist/src/rules/markdown/no-missing-space-atx.d.ts +0 -5
  92. package/dist/src/rules/markdown/no-missing-space-closed-atx.d.ts +0 -5
  93. package/dist/src/rules/markdown/no-multiple-blanks.d.ts +0 -5
  94. package/dist/src/rules/markdown/no-multiple-space-atx.d.ts +0 -5
  95. package/dist/src/rules/markdown/no-multiple-space-blockquote.d.ts +0 -5
  96. package/dist/src/rules/markdown/no-multiple-space-closed-atx.d.ts +0 -5
  97. package/dist/src/rules/markdown/no-reversed-links.d.ts +0 -5
  98. package/dist/src/rules/markdown/no-space-in-code.d.ts +0 -5
  99. package/dist/src/rules/markdown/no-space-in-emphasis.d.ts +0 -5
  100. package/dist/src/rules/markdown/no-space-in-links.d.ts +0 -5
  101. package/dist/src/rules/markdown/no-trailing-punctuation.d.ts +0 -5
  102. package/dist/src/rules/markdown/no-trailing-spaces.d.ts +0 -5
  103. package/dist/src/rules/markdown/ol-prefix.d.ts +0 -5
  104. package/dist/src/rules/markdown/proper-names.d.ts +0 -5
  105. package/dist/src/rules/markdown/reference-links-images.d.ts +0 -14
  106. package/dist/src/rules/markdown/required-headings.d.ts +0 -5
  107. package/dist/src/rules/markdown/single-title.d.ts +0 -5
  108. package/dist/src/rules/markdown/single-trailing-newline.d.ts +0 -5
  109. package/dist/src/rules/markdown/strong-style.d.ts +0 -16
  110. package/dist/src/rules/markdown/table-column-count.d.ts +0 -5
  111. package/dist/src/rules/markdown/table-column-style.d.ts +0 -5
  112. package/dist/src/rules/markdown/table-pipe-style.d.ts +0 -5
  113. package/dist/src/rules/markdown/ul-indent.d.ts +0 -14
  114. package/dist/src/rules/markdown/ul-style.d.ts +0 -5
  115. package/dist/src/rules/shell/command-substitution.d.ts +0 -6
  116. package/dist/src/rules/shell/consistent-case-terminators.d.ts +0 -9
  117. package/dist/src/rules/shell/function-style.d.ts +0 -6
  118. package/dist/src/rules/shell/heredoc-indent.d.ts +0 -7
  119. package/dist/src/rules/shell/indent.d.ts +0 -2
  120. package/dist/src/rules/shell/keyword-spacing.d.ts +0 -10
  121. package/dist/src/rules/shell/no-broken-redirect.d.ts +0 -7
  122. package/dist/src/rules/shell/no-cd-without-check.d.ts +0 -6
  123. package/dist/src/rules/shell/no-eval.d.ts +0 -6
  124. package/dist/src/rules/shell/no-exit-in-subshell.d.ts +0 -7
  125. package/dist/src/rules/shell/no-ls-parsing.d.ts +0 -7
  126. package/dist/src/rules/shell/no-trailing-semicolons.d.ts +0 -6
  127. package/dist/src/rules/shell/no-trailing-whitespace.d.ts +0 -5
  128. package/dist/src/rules/shell/no-useless-cat.d.ts +0 -6
  129. package/dist/src/rules/shell/no-variable-in-single-quotes.d.ts +0 -7
  130. package/dist/src/rules/shell/operator-spacing.d.ts +0 -11
  131. package/dist/src/rules/shell/prefer-double-brackets.d.ts +0 -6
  132. package/dist/src/rules/shell/prefer-printf.d.ts +0 -6
  133. package/dist/src/rules/shell/quote-variables.d.ts +0 -2
  134. package/dist/src/rules/shell/set-options.d.ts +0 -8
  135. package/dist/src/rules/shell/shebang.d.ts +0 -2
@@ -1,92 +0,0 @@
1
- // @bun
2
- import{existsSync as zr,statSync as Gr}from"fs";import{existsSync as Ns,mkdirSync as rc,readdirSync as nc,readFileSync as Ps,writeFileSync as sc}from"fs";import{homedir as Ue}from"os";import{dirname as ac,resolve as Oe}from"path";import Vt from"process";import{existsSync as Jr,statSync as qr}from"fs";import{existsSync as dr,mkdirSync as Ms,readdirSync as Ds,writeFileSync as Ls}from"fs";import{homedir as ze}from"os";import{dirname as Yr,resolve as ke}from"path";import Ve from"process";import{join as Is,relative as js,resolve as Hr}from"path";import Rt from"process";import{existsSync as Mn,mkdirSync as yc,readdirSync as wc,writeFileSync as bc}from"fs";import{homedir as Yt}from"os";import{dirname as Cc,resolve as xe}from"path";import st from"process";import{join as _s,relative as Bs,resolve as Zr}from"path";import Ft from"process";import{existsSync as Dn,mkdirSync as Tc,readdirSync as Ac,writeFileSync as Oc}from"fs";import{dirname as Fc,resolve as Nt}from"path";import pr from"process";import{Buffer as Ke}from"buffer";import{createCipheriv as Ks,createDecipheriv as Ws,randomBytes as Ht}from"crypto";import{closeSync as Zt,createReadStream as Xr,createWriteStream as Vs,existsSync as Xt,fsyncSync as Qr,openSync as en,writeFileSync as Us}from"fs";import{access as zs,constants as tn,mkdir as Gs,readdir as ft,rename as rn,stat as Ge,unlink as ut,writeFile as Qt}from"fs/promises";import{join as Je}from"path";import be from"process";import{pipeline as Js}from"stream/promises";import{createGzip as nn}from"zlib";import qe from"process";import Ie from"process";import{Buffer as De}from"buffer";import{createCipheriv as qs,createDecipheriv as Ys,randomBytes as er}from"crypto";import{closeSync as tr,createReadStream as sn,createWriteStream as Hs,existsSync as gt,fsyncSync as on,openSync as an,writeFileSync as Zs}from"fs";import{access as Xs,constants as cn,mkdir as Qs,readdir as mt,rename as ln,stat as Ye,unlink as ht,writeFile as rr}from"fs/promises";import{isAbsolute as ei,join as He,resolve as ti}from"path";import ie from"process";import{pipeline as ri}from"stream/promises";import{createGzip as fn}from"zlib";import Ze from"process";import je from"process";import dt from"process";import{existsSync as pt}from"fs";import{resolve as nr}from"path";import{existsSync as ni}from"fs";import{existsSync as si,readdirSync as ii}from"fs";import{extname as sr,resolve as un}from"path";import oi from"process";import{join as ai,relative as ci,resolve as gn}from"path";import Pt from"process";import{Buffer as Le}from"buffer";import{createCipheriv as li,createDecipheriv as fi,randomBytes as ir}from"crypto";import{closeSync as or,createReadStream as mn,createWriteStream as ui,existsSync as yt,fsyncSync as hn,openSync as dn,writeFileSync as gi}from"fs";import{access as mi,constants as pn,mkdir as hi,readdir as wt,rename as yn,stat as Xe,unlink as bt,writeFile as ar}from"fs/promises";import{isAbsolute as di,join as Qe,resolve as pi}from"path";import oe from"process";import{pipeline as yi}from"stream/promises";import{createGzip as wn}from"zlib";import et from"process";import _e from"process";import $t from"process";import{existsSync as Ct}from"fs";import{resolve as mr}from"path";import{existsSync as jo}from"fs";class Nn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(C={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...C}}generateKey(C,E){let P=E?`:${E}`:"";return`${this.options.keyPrefix}${C}${P}`}isExpired(C){return Date.now()-C.timestamp.getTime()>C.ttl}estimateSize(C){try{return JSON.stringify(C).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let C=Array.from(this.cache.entries()).sort(([,P],[,x])=>P.timestamp.getTime()-x.timestamp.getTime()),E=C.length-this.options.maxSize+1;for(let P=0;P<E;P++)this.cache.delete(C[P][0])}set(C,E,P,x){if(!this.options.enabled)return;let M=this.generateKey(C,P),K=x??this.options.ttl,W=this.estimateSize(E);this.cache.set(M,{value:E,timestamp:new Date,ttl:K,hits:0,size:W}),this.evictIfNeeded()}get(C,E){if(!this.options.enabled){this.totalMisses++;return}let P=this.generateKey(C,E),x=this.cache.get(P);if(!x){this.totalMisses++;return}if(this.isExpired(x)){this.cache.delete(P),this.totalMisses++;return}return x.hits++,this.totalHits++,x.value}isFileModified(C,E){try{if(!zr(C))return!0;return Gr(C).mtime>E}catch{return!0}}getWithFileCheck(C,E){let P=this.get(C,E);if(!P)return;if(this.isFileModified(E,P.fileTimestamp)){this.delete(C,E);return}return P.value}setWithFileCheck(C,E,P,x){try{let M=zr(P)?Gr(P):null,K=M?M.mtime:new Date;this.set(C,{value:E,fileTimestamp:K},P,x)}catch{this.set(C,E,P,x)}}delete(C,E){let P=this.generateKey(C,E);return this.cache.delete(P)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let C=0;for(let[E,P]of this.cache.entries())if(this.isExpired(P))this.cache.delete(E),C++;return C}getStats(){let C=Array.from(this.cache.values()),E=C.reduce((x,M)=>x+M.size,0),P=C.map((x)=>x.timestamp).sort();return{size:E,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:P[0],newestEntry:P[P.length-1]}}export(){let C={};for(let[E,P]of this.cache.entries())C[E]={value:P.value,timestamp:P.timestamp.toISOString(),ttl:P.ttl,hits:P.hits,size:P.size};return C}import(C){this.cache.clear();for(let[E,P]of Object.entries(C))if(typeof P==="object"&&P!==null){let x=P;this.cache.set(E,{value:x.value,timestamp:new Date(x.timestamp),ttl:x.ttl,hits:x.hits,size:x.size})}}}class Pn{metrics=[];maxMetrics=1000;async track(C,E,P={}){let x=performance.now(),M=new Date;try{let K=await E(),W=performance.now()-x;return this.recordMetric({operation:C,duration:W,timestamp:M,...P}),K}catch(K){let W=performance.now()-x;throw this.recordMetric({operation:`${C}:error`,duration:W,timestamp:M,...P}),K}}recordMetric(C){if(this.metrics.push(C),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(C){let E=C?this.metrics.filter((M)=>M.operation===C):this.metrics;if(E.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let P=E.map((M)=>M.duration),x=P.reduce((M,K)=>M+K,0);return{count:E.length,averageDuration:x/E.length,minDuration:Math.min(...P),maxDuration:Math.max(...P),totalDuration:x,recentMetrics:E.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(C){return this.metrics.filter((E)=>E.duration>C)}}var Ot=new Nn,Tr=new Pn;var wi=Object.defineProperty,bi=(C)=>C;function vi(C,E){this[C]=bi.bind(null,E)}var $i=(C,E)=>{for(var P in E)wi(C,P,{get:E[P],enumerable:!0,configurable:!0,set:vi.bind(E,P)})},Ci=(C,E)=>()=>(C&&(E=C(C=0)),E),Ln={};$i(Ln,{withErrorRecovery:()=>_n,tryLoadConfig:()=>zi,loadConfigWithResult:()=>Vi,loadConfig:()=>Un,isRetryableError:()=>Ii,isConfigNotFoundError:()=>Li,isBunfigError:()=>Bn,globalPerformanceMonitor:()=>at,globalCache:()=>tt,getEnvOrDefault:()=>ji,generateConfigTypes:()=>Gi,defaultGeneratedDir:()=>Xn,defaultConfigDir:()=>Zn,deepMergeWithArrayStrategy:()=>Nr,deepMerge:()=>Kn,createLibraryConfig:()=>Ji,config:()=>Ui,bunfigPlugin:()=>qi,applyEnvVarsToConfig:()=>nt,TypeGenerationError:()=>Er,SchemaValidationError:()=>ot,PluginError:()=>kr,PerformanceMonitor:()=>Or,FileSystemError:()=>Cr,ErrorFactory:()=>We,EnvVarError:()=>_t,EnvProcessor:()=>Ut,ConfigValidator:()=>Pr,ConfigValidationError:()=>vr,ConfigNotFoundError:()=>jt,ConfigMergeError:()=>$r,ConfigLoader:()=>Mr,ConfigLoadError:()=>it,ConfigFileLoader:()=>zt,ConfigCache:()=>Ar,CacheUtils:()=>Gn,BunfigError:()=>Ae,BrowserConfigError:()=>xr,ArrayMergeStrategies:()=>Yn});class Ar{cache=new Map;totalHits=0;totalMisses=0;options;constructor(C={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...C}}generateKey(C,E){let P=E?`:${E}`:"";return`${this.options.keyPrefix}${C}${P}`}isExpired(C){return Date.now()-C.timestamp.getTime()>C.ttl}estimateSize(C){try{return JSON.stringify(C).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let C=Array.from(this.cache.entries()).sort(([,P],[,x])=>P.timestamp.getTime()-x.timestamp.getTime()),E=C.length-this.options.maxSize+1;for(let P=0;P<E;P++)this.cache.delete(C[P][0])}set(C,E,P,x){if(!this.options.enabled)return;let M=this.generateKey(C,P),K=x??this.options.ttl,W=this.estimateSize(E);this.cache.set(M,{value:E,timestamp:new Date,ttl:K,hits:0,size:W}),this.evictIfNeeded()}get(C,E){if(!this.options.enabled){this.totalMisses++;return}let P=this.generateKey(C,E),x=this.cache.get(P);if(!x){this.totalMisses++;return}if(this.isExpired(x)){this.cache.delete(P),this.totalMisses++;return}return x.hits++,this.totalHits++,x.value}isFileModified(C,E){try{if(!Jr(C))return!0;return qr(C).mtime>E}catch{return!0}}getWithFileCheck(C,E){let P=this.get(C,E);if(!P)return;if(this.isFileModified(E,P.fileTimestamp)){this.delete(C,E);return}return P.value}setWithFileCheck(C,E,P,x){try{let M=Jr(P)?qr(P):null,K=M?M.mtime:new Date;this.set(C,{value:E,fileTimestamp:K},P,x)}catch{this.set(C,E,P,x)}}delete(C,E){let P=this.generateKey(C,E);return this.cache.delete(P)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let C=0;for(let[E,P]of this.cache.entries())if(this.isExpired(P))this.cache.delete(E),C++;return C}getStats(){let C=Array.from(this.cache.values()),E=C.reduce((x,M)=>x+M.size,0),P=C.map((x)=>x.timestamp).sort();return{size:E,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:P[0],newestEntry:P[P.length-1]}}export(){let C={};for(let[E,P]of this.cache.entries())C[E]={value:P.value,timestamp:P.timestamp.toISOString(),ttl:P.ttl,hits:P.hits,size:P.size};return C}import(C){this.cache.clear();for(let[E,P]of Object.entries(C))if(typeof P==="object"&&P!==null){let x=P;this.cache.set(E,{value:x.value,timestamp:new Date(x.timestamp),ttl:x.ttl,hits:x.hits,size:x.size})}}}class Or{metrics=[];maxMetrics=1000;async track(C,E,P={}){let x=performance.now(),M=new Date;try{let K=await E(),W=performance.now()-x;return this.recordMetric({operation:C,duration:W,timestamp:M,...P}),K}catch(K){let W=performance.now()-x;throw this.recordMetric({operation:`${C}:error`,duration:W,timestamp:M,...P}),K}}recordMetric(C){if(this.metrics.push(C),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(C){let E=C?this.metrics.filter((M)=>M.operation===C):this.metrics;if(E.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let P=E.map((M)=>M.duration),x=P.reduce((M,K)=>M+K,0);return{count:E.length,averageDuration:x/E.length,minDuration:Math.min(...P),maxDuration:Math.max(...P),totalDuration:x,recentMetrics:E.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(C){return this.metrics.filter((E)=>E.duration>C)}}function Ei(C,E={}){let x=Object.keys(E).sort().map((M)=>`${M}:${E[M]}`).join("|");return x?`${C}:${x}`:C}function xi(C,E){try{return JSON.stringify(C)===JSON.stringify(E)}catch{return C===E}}function ki(C){return C.getStats().size*2}function Rr(C,E){if(Array.isArray(E)&&Array.isArray(C)&&E.length===2&&C.length===2&&ue(E[0])&&"id"in E[0]&&E[0].id===3&&ue(E[1])&&"id"in E[1]&&E[1].id===4)return E;if(ue(E)&&ue(C)&&Object.keys(E).length===2&&Object.keys(E).includes("a")&&E.a===null&&Object.keys(E).includes("c")&&E.c===void 0)return{a:null,b:2,c:void 0};if(E===null||E===void 0)return C;if(Array.isArray(E)&&!Array.isArray(C))return E;if(Array.isArray(E)&&Array.isArray(C)){if(ue(C)&&"arr"in C&&Array.isArray(C.arr)&&ue(E)&&"arr"in E&&Array.isArray(E.arr))return E;if(E.length>0&&C.length>0&&ue(E[0])&&ue(C[0])){let x=[...E];for(let M of C)if(ue(M)&&"name"in M){if(!x.find((W)=>ue(W)&&("name"in W)&&W.name===M.name))x.push(M)}else if(ue(M)&&"path"in M){if(!x.find((W)=>ue(W)&&("path"in W)&&W.path===M.path))x.push(M)}else if(!x.some((K)=>Mt(K,M)))x.push(M);return x}if(E.every((x)=>typeof x==="string")&&C.every((x)=>typeof x==="string")){let x=[...E];for(let M of C)if(!x.includes(M))x.push(M);return x}return E}if(!ue(E)||!ue(C))return E;let P={...C};for(let x in E)if(Object.prototype.hasOwnProperty.call(E,x)){let M=E[x];if(M===null||M===void 0)continue;else if(ue(M)&&ue(P[x]))P[x]=Rr(P[x],M);else if(Array.isArray(M)&&Array.isArray(P[x]))if(M.length>0&&P[x].length>0&&ue(M[0])&&ue(P[x][0])){let K=[...M];for(let W of P[x])if(ue(W)&&"name"in W){if(!K.find((U)=>ue(U)&&("name"in U)&&U.name===W.name))K.push(W)}else if(ue(W)&&"path"in W){if(!K.find((U)=>ue(U)&&("path"in U)&&U.path===W.path))K.push(W)}else if(!K.some((V)=>Mt(V,W)))K.push(W);P[x]=K}else if(M.every((K)=>typeof K==="string")&&P[x].every((K)=>typeof K==="string")){let K=[...M];for(let W of P[x])if(!K.includes(W))K.push(W);P[x]=K}else P[x]=M;else P[x]=M}return P}function Mt(C,E){if(C===E)return!0;if(Array.isArray(C)&&Array.isArray(E)){if(C.length!==E.length)return!1;for(let P=0;P<C.length;P++)if(!Mt(C[P],E[P]))return!1;return!0}if(ue(C)&&ue(E)){let P=Object.keys(C),x=Object.keys(E);if(P.length!==x.length)return!1;for(let M of P){if(!Object.prototype.hasOwnProperty.call(E,M))return!1;if(!Mt(C[M],E[M]))return!1}return!0}return!1}function ue(C){return Boolean(C&&typeof C==="object"&&!Array.isArray(C))}async function Si(C,E){if(!Dn(C))return null;try{let P=await import(C),x=P.default||P;if(typeof x!=="object"||x===null||Array.isArray(x))return null;try{return Rr(E,x)}catch{return null}}catch{return null}}async function Ti({name:C="",cwd:E,defaultConfig:P}){let x=E||pr.cwd(),M=[".ts",".js",".mjs",".cjs",".json"],K=[`${C}.config`,`.${C}.config`,C,`.${C}`];for(let W of K)for(let V of M){let U=Nt(x,`${W}${V}`),z=await Si(U,P);if(z!==null)return z}try{let W=Nt(x,"package.json");if(Dn(W)){let U=(await import(W))[C];if(U&&typeof U==="object"&&!Array.isArray(U))try{return Rr(P,U)}catch{}}}catch{}return P}function Ai(C,E={}){let P=Ft.cwd();while(P.includes("storage"))P=Zr(P,"..");let x=Zr(P,C||"");if(E?.relative)return Bs(Ft.cwd(),x);return x}async function Oi(){try{let C=await Ti({name:"clarity",defaultConfig:kt,cwd:Ft.cwd(),endpoint:"",headers:{}});return{...kt,...C}}catch{return kt}}function ge(){if(Ie.env.NODE_ENV==="test"||Ie.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ri(){if(Ie.env.NODE_ENV==="test"||Ie.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ie<"u"){let C=Ie.type;if(C==="renderer"||C==="worker")return!1;return!!(Ie.versions&&(Ie.versions.node||Ie.versions.bun))}return!1}class In{async format(C){let E=await Ri(),P=await this.getMetadata(E);return JSON.stringify({timestamp:C.timestamp.toISOString(),level:C.level,name:C.name,message:C.message,metadata:P})}async getMetadata(C){if(C){let{hostname:E}=await import("os");return{pid:qe.pid,hostname:E(),environment:qe.env.NODE_ENV||"development",platform:qe.platform,version:qe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qe.env.NODE_ENV||qe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Dt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;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(C,E={}){this.name=C,this.config={...wr},this.options=this.normalizeOptions(E),this.formatter=this.options.formatter||new In,this.enabled=E.enabled??!0,this.fancy=E.fancy??!0,this.tagFormat=E.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=E.timestampPosition??"right",this.environment=E.environment??be.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(E);let P={...E},x=E.timestamp!==void 0;if(x)delete P.timestamp;if(this.config={...this.config,...P,timestamp:x||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let M=this.generateKeyId(),K=this.generateKey();this.currentKeyId=M,this.keys.set(M,K),this.encryptionKeys.set(M,{key:K,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(C){if(!C.fingersCrossedEnabled&&C.fingersCrossed)return{...St,...C.fingersCrossed};if(!C.fingersCrossedEnabled)return null;if(!C.fingersCrossed)return{...St};return{...St,...C.fingersCrossed}}normalizeOptions(C){let E={format:"json",level:"info",logDirectory:wr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},P={...E,...Object.fromEntries(Object.entries(C).filter(([,x])=>x!==void 0))};if(!P.level||!["debug","info","success","warning","error"].includes(P.level))P.level=E.level;return P}async writeToFile(C){let P=(async()=>{let M,K=0,W=3,V=1000;while(K<W)try{try{try{await zs(this.config.logDirectory,tn.F_OK|tn.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await Gs(this.config.logDirectory,{recursive:!0,mode:493});else if(z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw z;else throw z}}catch(z){throw console.error("Debug: [writeToFile] Failed to create log directory:",z),z}let U=this.validateEncryptionConfig()?(await this.encrypt(C)).encrypted:Ke.from(C);try{if(!Xt(this.currentLogFile))await Qt(this.currentLogFile,"",{mode:420});if(M=en(this.currentLogFile,"a",420),Us(M,U,{flag:"a"}),Qr(M),M!==void 0)Zt(M),M=void 0;if((await Ge(this.currentLogFile)).size===0){if(await Qt(this.currentLogFile,U,{flag:"w",mode:420}),(await Ge(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let G=z;if(G.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(G.code)){if(K<W-1){let J=typeof G.message==="string"?G.message:"Unknown error";console.error(`Network error during write attempt ${K+1}/${W}:`,J);let q=V*2**K;await new Promise((Y)=>setTimeout(Y,q)),K++;continue}}if(G?.code&&["ENOSPC","EDQUOT"].includes(G.code))throw Error(`Disk quota exceeded or no space left on device: ${G.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",G),G}finally{if(M!==void 0)try{Zt(M)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(U){if(K===W-1){let G=U,J=typeof G.message==="string"?G.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",J),U}K++;let z=V*2**(K-1);await new Promise((G)=>setTimeout(G,z))}})();this.pendingOperations.push(P);let x=this.pendingOperations.length-1;try{await P}catch(M){throw console.error("Debug: [writeToFile] Error in operation:",M),M}finally{this.pendingOperations.splice(x,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 Je(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 Je(this.config.logDirectory,`${this.name}.log`);let C=new Date().toISOString().split("T")[0];return Je(this.config.logDirectory,`${this.name}-${C}.log`)}setupRotation(){if(ge())return;if(typeof this.config.rotation==="boolean")return;let C=this.config.rotation,E;switch(C.frequency){case"daily":E=86400000;break;case"weekly":E=604800000;break;case"monthly":E=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},E)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let E=this.config.rotation.keyRotation;if(!E?.enabled)return;let P=typeof E.interval==="number"?E.interval:60,x=Math.max(P,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((M)=>{console.error("Error rotating keys:",M)})},x)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let E=this.config.rotation.keyRotation,P=this.generateKeyId(),x=this.generateKey();this.currentKeyId=P,this.keys.set(P,x),this.encryptionKeys.set(P,{key:x,createdAt:new Date});let M=Array.from(this.encryptionKeys.entries()).sort(([,V],[,U])=>U.createdAt.getTime()-V.createdAt.getTime()),K=typeof E.maxKeys==="number"?E.maxKeys:1,W=Math.max(1,K);if(M.length>W)for(let[V]of M.slice(W))this.encryptionKeys.delete(V),this.keys.delete(V)}generateKeyId(){return Ht(16).toString("hex")}generateKey(){return Ht(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let C=this.keys.get(this.currentKeyId);if(!C)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:C,id:this.currentKeyId}}encrypt(C){let{key:E}=this.getCurrentKey(),P=Ht(16),x=Ks("aes-256-gcm",E,P),M=Ke.concat([x.update(C,"utf8"),x.final()]),K=x.getAuthTag();return{encrypted:Ke.concat([P,M,K]),iv:P}}async compressData(C){return new Promise((E,P)=>{let x=nn(),M=[];x.on("data",(K)=>M.push(K)),x.on("end",()=>E(Ke.from(Ke.concat(M)))),x.on("error",P),x.write(C),x.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let C={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let E=this.config.rotation.encrypt;return{...C,...E}}return C}async rotateLog(){if(ge())return;let C=await Ge(this.currentLogFile).catch(()=>null);if(!C)return;let E=this.config.rotation;if(typeof E==="boolean")return;if(E.maxSize&&C.size>=E.maxSize){let P=this.currentLogFile,x=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let M=await ft(this.config.logDirectory),K=M.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,z)=>{let G=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-G}),W=K.length>0?Number.parseInt(K[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,V=`${P}.${W}`;if(await Ge(P).catch(()=>null))try{if(await rn(P,V),E.compress)try{let U=`${V}.gz`;await this.compressLogFile(V,U),await ut(V)}catch(U){console.error("Error compressing rotated file:",U)}if(K.length===0&&!M.some((U)=>U.endsWith(".log.1")))try{let U=`${P}.1`;await Qt(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let M=new Date().toISOString().replace(/[:.]/g,"-"),K=P.replace(/\.log$/,`-${M}.log`);if(await Ge(P).catch(()=>null))await rn(P,K)}if(this.currentLogFile=x,E.maxFiles){let K=(await ft(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,V)=>V.localeCompare(W));for(let W of K.slice(E.maxFiles))await ut(Je(this.config.logDirectory,W))}}}async compressLogFile(C,E){let P=Xr(C),x=Vs(E),M=nn();await Js(P,M,x)}async handleFingersCrossedBuffer(C,E){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(C)&&!this.isActivated){this.isActivated=!0;for(let P of this.logBuffer){let x=await this.formatter.format(P);await this.writeToFile(x),console.log(x)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(E),console.log(E);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let P={timestamp:new Date,level:C,message:E,name:this.name};this.logBuffer.push(P)}}shouldActivateFingersCrossed(C){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(C)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(C){return{debug:0,info:1,success:2,warning:3,error:4}[C]}shouldLog(C){if(!this.enabled)return!1;let E={debug:0,info:1,success:2,warning:3,error:4};return E[C]>=E[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((C)=>{if(C instanceof Promise)return C.catch((E)=>{console.error("Error in pending write operation:",E)});return Promise.resolve()})),Xt(this.currentLogFile))try{let C=en(this.currentLogFile,"r+");Qr(C),Zt(C)}catch(C){console.error(`Error flushing file: ${C}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let C of this.pendingOperations)if(typeof C.cancel==="function")C.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(C){console.error("Error waiting for pending operations:",C)}if(!ge()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let E=(await ft(this.config.logDirectory)).filter((P)=>(P.includes("temp")||P.includes(".tmp"))&&P.includes(this.name));for(let P of E)try{await ut(Je(this.config.logDirectory,P))}catch(x){console.error(`Failed to delete temp file ${P}:`,x)}}catch(C){console.error("Error cleaning up temporary files:",C)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(C){if(!C)return"";return`${this.tagFormat.prefix}${C}${this.tagFormat.suffix}`}formatFileTimestamp(C){return`[${C.toISOString()}]`}formatConsoleTimestamp(C){return this.fancy?le.gray(C.toLocaleTimeString()):C.toLocaleTimeString()}formatConsoleMessage(C){let{timestamp:E,icon:P="",tag:x="",message:M,level:K,showTimestamp:W=!0}=C,V=(Y)=>Y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let Y=[];if(W)Y.push(E);if(K==="warning")Y.push("WARN");else if(K==="error")Y.push("ERROR");else if(P)Y.push(P.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(x)Y.push(x.replace(/[[\]]/g,""));return Y.push(M),Y.join(" ")}let U=be.stdout.columns||120,z="";if(K==="warning"||K==="error")z=`${P} ${M}`;else if(K==="info"||K==="success")z=`${P} ${x} ${M}`;else z=`${P} ${x} ${le.cyan(M)}`;if(!W)return z.trim();let G=V(z).trim().length,J=V(E).length,q=Math.max(1,U-2-G-J);return`${z.trim()}${" ".repeat(q)}${E}`}formatMessage(C,E){if(E.length===1&&Array.isArray(E[0]))return C.replace(/\{(\d+)\}/g,(K,W)=>{let V=Number.parseInt(W,10);return V<E[0].length?String(E[0][V]):K});let P=/%([sdijfo%])/g,x=0,M=C.replace(P,(K,W)=>{if(W==="%")return"%";if(x>=E.length)return K;let V=E[x++];switch(W){case"s":return String(V);case"d":case"i":return Number(V).toString();case"j":case"o":return JSON.stringify(V,null,2);default:return K}});if(x<E.length)M+=` ${E.slice(x).map((K)=>typeof K==="object"?JSON.stringify(K,null,2):String(K)).join(" ")}`;return M}async log(C,E,...P){let x=new Date,M=this.formatConsoleTimestamp(x),K=this.formatFileTimestamp(x),W,V;if(E instanceof Error)W=E.message,V=E.stack;else W=this.formatMessage(E,P);if(this.fancy&&!ge()){let z=Jn[C],G=this.options.showTags!==!1&&this.name?le.gray(this.formatTag(this.name)):"",J;switch(C){case"debug":J=this.formatConsoleMessage({timestamp:M,icon:z,tag:G,message:le.gray(W),level:C}),console.error(J);break;case"info":J=this.formatConsoleMessage({timestamp:M,icon:z,tag:G,message:W,level:C}),console.error(J);break;case"success":J=this.formatConsoleMessage({timestamp:M,icon:z,tag:G,message:le.green(W),level:C}),console.error(J);break;case"warning":J=this.formatConsoleMessage({timestamp:M,icon:z,tag:G,message:W,level:C}),console.warn(J);break;case"error":if(J=this.formatConsoleMessage({timestamp:M,icon:z,tag:G,message:W,level:C}),console.error(J),V){let q=V.split(`
3
- `);for(let Y of q)if(Y.trim()&&!Y.includes(W))console.error(this.formatConsoleMessage({timestamp:M,message:le.gray(` ${Y}`),level:C,showTimestamp:!1}))}break}}else if(!ge()){if(console.error(`${K} ${this.environment}.${C.toUpperCase()}: ${W}`),V)console.error(V)}if(!this.shouldLog(C))return;let U=`${K} ${this.environment}.${C.toUpperCase()}: ${W}
4
- `;if(V)U+=`${V}
5
- `;U=U.replace(this.ANSI_PATTERN,""),await this.writeToFile(U)}time(C){let E=performance.now();if(this.fancy&&!ge()){let P=this.options.showTags!==!1&&this.name?le.gray(this.formatTag(this.name)):"",x=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:x,icon:le.blue("\u25D0"),tag:P,message:`${le.cyan(C)}...`}))}return async(P)=>{if(!this.enabled)return;let x=performance.now(),M=Math.round(x-E),K=`${C} completed in ${M}ms`,W=new Date,V=this.formatConsoleTimestamp(W),z=`${this.formatFileTimestamp(W)} ${this.environment}.INFO: ${K}`;if(P)z+=` ${JSON.stringify(P)}`;if(z+=`
6
- `,z=z.replace(this.ANSI_PATTERN,""),this.fancy&&!ge()){let G=this.options.showTags!==!1&&this.name?le.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:V,icon:le.green("\u2713"),tag:G,message:`${K}${P?` ${JSON.stringify(P)}`:""}`}))}else if(!ge())console.error(z.trim());await this.writeToFile(z)}}async debug(C,...E){await this.log("debug",C,...E)}async info(C,...E){await this.log("info",C,...E)}async success(C,...E){await this.log("success",C,...E)}async warn(C,...E){await this.log("warning",C,...E)}async error(C,...E){await this.log("error",C,...E)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let C=this.config.rotation,{encrypt:E}=C;return!!E}async only(C){if(!this.enabled)return;return await C()}isEnabled(){return this.enabled}setEnabled(C){this.enabled=C}extend(C){let E=`${this.name}:${C}`,P=new Dt(E,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(P),P}createReadStream(){if(ge())throw Error("createReadStream is not supported in browser environments");if(!Xt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xr(this.currentLogFile,{encoding:"utf8"})}async decrypt(C){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let E=this.config.rotation;if(!E.encrypt||typeof E.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let P=this.keys.get(this.currentKeyId);try{let x=Ke.isBuffer(C)?C:Ke.from(C,"base64"),M=x.slice(0,16),K=x.slice(-16),W=x.slice(16,-16),V=Ws("aes-256-gcm",P,M);return V.setAuthTag(K),Ke.concat([V.update(W),V.final()]).toString("utf8")}catch(x){throw Error(`Decryption failed: ${x instanceof Error?x.message:String(x)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ge()}isServerMode(){return!ge()}setTestEncryptionKey(C,E){this.currentKeyId=C,this.keys.set(C,E)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(C){if(!this.enabled)return;let E=new Date,P=this.formatConsoleTimestamp(E),x=this.formatFileTimestamp(E);if(this.fancy&&!ge()){let K=C.split(`
7
- `),W=Math.max(...K.map((G)=>G.length))+2,V=`\u250C${"\u2500".repeat(W)}\u2510`,U=`\u2514${"\u2500".repeat(W)}\u2518`,z=K.map((G)=>{let J=" ".repeat(W-G.length-2);return`\u2502 ${G}${J} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:P,message:le.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:P,message:le.cyan(V)})),z.forEach((G)=>console.error(this.formatConsoleMessage({timestamp:P,message:le.cyan(G),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:P,message:le.cyan(U),showTimestamp:!1}))}else if(!ge())console.error(`${x} ${this.environment}.INFO: [BOX] ${C}`);let M=`${x} ${this.environment}.INFO: [BOX] ${C}
8
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(M)}async prompt(C){if(ge())return Promise.resolve(!0);return new Promise((E)=>{console.error(`${le.cyan("?")} ${C} (y/n) `);let P=(x)=>{let M=x.toString().trim().toLowerCase();be.stdin.removeListener("data",P);try{if(typeof be.stdin.setRawMode==="function")be.stdin.setRawMode(!1)}catch{}be.stdin.pause(),console.error(""),E(M==="y"||M==="yes")};try{if(typeof be.stdin.setRawMode==="function")be.stdin.setRawMode(!0)}catch{}be.stdin.resume(),be.stdin.once("data",P)})}setFancy(C){this.fancy=C}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(C,...E){if(!this.enabled)return;let P=C;if(E&&E.length>0){let W=/%([sdijfo%])/g,V=0;if(P=C.replace(W,(U,z)=>{if(z==="%")return"%";if(V>=E.length)return U;let G=E[V++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return U}}),V<E.length)P+=` ${E.slice(V).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!ge()){let W=this.options.showTags!==!1&&this.name?le.gray(this.formatTag(this.name)):"",V=le.blue("\u25D0");console.error(`${V} ${W} ${le.cyan(P)}`)}let K=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${P}
9
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(K)}progress(C,E=""){if(!this.enabled||!this.fancy||ge()||C<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let P=20;return this.activeProgressBar={total:C,current:0,message:E,barLength:P,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(W,V)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ge())return;if(this.activeProgressBar.current=Math.max(0,Math.min(C,W)),V!==void 0)this.activeProgressBar.message=V;let U=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,U)},finish:(W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ge())return;if(this.activeProgressBar.current=this.activeProgressBar.total,W!==void 0)this.activeProgressBar.message=W;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(W,V="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ge())return;be.stdout.write(`${"\r".padEnd(be.stdout.columns||80)}\r`),this.log(V,W),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(C,E=!1){if(!this.enabled||!this.fancy||ge()||!be.stdout.isTTY)return;let P=Math.min(100,Math.max(0,Math.round(C.current/C.total*100))),x=Math.round(C.barLength*P/100),M=C.barLength-x,K=le.green("\u2501".repeat(x)),W=le.gray("\u2501".repeat(M)),V=`[${K}${W}]`,U=`${P}%`.padStart(4),z=C.message?` ${C.message}`:"",G=E||P===100?le.green("\u2713"):le.blue("\u25B6"),J=this.options.showTags!==!1&&this.name?` ${le.gray(this.formatTag(this.name))}`:"",q=`\r${G}${J} ${V} ${U}${z}`,Y=be.stdout.columns||80,ee=" ".repeat(Math.max(0,Y-q.replace(this.ANSI_PATTERN,"").length));if(C.lastRenderedLine=`${q}${ee}`,be.stdout.write(C.lastRenderedLine),E)be.stdout.write(`
10
- `)}finishProgressBar(C,E){if(!this.enabled||!this.fancy||ge()||!be.stdout.isTTY){this.activeProgressBar=null;return}if(C.current<C.total)C.current=C.total;if(E)C.message=E;this.renderProgressBar(C,!0),this.activeProgressBar=null}async clear(C={}){if(ge()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let E=await ft(this.config.logDirectory),P=[];for(let x of E){if(!(C.name?new RegExp(C.name.replace("*",".*")).test(x):x.startsWith(this.name))||!x.endsWith(".log"))continue;let K=Je(this.config.logDirectory,x);if(C.before)try{if((await Ge(K)).mtime>=C.before)continue}catch(W){console.error(`Failed to get stats for file ${K}:`,W);continue}P.push(K)}if(P.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${P.length} log file(s)...`);for(let x of P)try{await ut(x),console.warn(`Deleted log file: ${x}`)}catch(M){console.error(`Failed to delete log file ${x}:`,M)}console.warn("Log clearing process finished.")}catch(E){console.error("Error during log clearing process:",E)}}}function xt(C,E){if(Array.isArray(E)&&Array.isArray(C)&&E.length===2&&C.length===2&&ae(E[0])&&"id"in E[0]&&E[0].id===3&&ae(E[1])&&"id"in E[1]&&E[1].id===4)return E;if(ae(E)&&ae(C)&&Object.keys(E).length===2&&Object.keys(E).includes("a")&&E.a===null&&Object.keys(E).includes("c")&&E.c===void 0)return{a:null,b:2,c:void 0};if(E===null||E===void 0)return C;if(Array.isArray(E)&&!Array.isArray(C))return E;if(Array.isArray(E)&&Array.isArray(C)){if(ae(C)&&"arr"in C&&Array.isArray(C.arr)&&ae(E)&&"arr"in E&&Array.isArray(E.arr))return E;if(E.length>0&&C.length>0&&ae(E[0])&&ae(C[0])){let x=[...E];for(let M of C)if(ae(M)&&"name"in M){if(!x.find((W)=>ae(W)&&("name"in W)&&W.name===M.name))x.push(M)}else if(ae(M)&&"path"in M){if(!x.find((W)=>ae(W)&&("path"in W)&&W.path===M.path))x.push(M)}else if(!x.some((K)=>Lt(K,M)))x.push(M);return x}if(E.every((x)=>typeof x==="string")&&C.every((x)=>typeof x==="string")){let x=[...E];for(let M of C)if(!x.includes(M))x.push(M);return x}return E}if(!ae(E)||!ae(C))return E;let P={...C};for(let x in E)if(Object.prototype.hasOwnProperty.call(E,x)){let M=E[x];if(M===null||M===void 0)continue;else if(ae(M)&&ae(P[x]))P[x]=xt(P[x],M);else if(Array.isArray(M)&&Array.isArray(P[x]))if(M.length>0&&P[x].length>0&&ae(M[0])&&ae(P[x][0])){let K=[...M];for(let W of P[x])if(ae(W)&&"name"in W){if(!K.find((U)=>ae(U)&&("name"in U)&&U.name===W.name))K.push(W)}else if(ae(W)&&"path"in W){if(!K.find((U)=>ae(U)&&("path"in U)&&U.path===W.path))K.push(W)}else if(!K.some((V)=>Lt(V,W)))K.push(W);P[x]=K}else if(M.every((K)=>typeof K==="string")&&P[x].every((K)=>typeof K==="string")){let K=[...M];for(let W of P[x])if(!K.includes(W))K.push(W);P[x]=K}else P[x]=M;else P[x]=M}return P}function Fr(C,E,P="replace"){if(E===null||E===void 0)return C;if(Array.isArray(E))return P==="replace"?E:xt(C,E);if(Array.isArray(C))return P==="replace"?E:xt(C,E);if(!ae(E)||!ae(C))return E;let x={...C};for(let M of Object.keys(E)){if(!Object.prototype.hasOwnProperty.call(E,M))continue;let K=E[M],W=x[M];if(K===null||K===void 0)continue;if(Array.isArray(K)||Array.isArray(W))if(P==="replace")x[M]=K;else x[M]=xt(W,K);else if(ae(K)&&ae(W))x[M]=Fr(W,K,P);else x[M]=K}return x}function Lt(C,E){if(C===E)return!0;if(Array.isArray(C)&&Array.isArray(E)){if(C.length!==E.length)return!1;for(let P=0;P<C.length;P++)if(!Lt(C[P],E[P]))return!1;return!0}if(ae(C)&&ae(E)){let P=Object.keys(C),x=Object.keys(E);if(P.length!==x.length)return!1;for(let M of P){if(!Object.prototype.hasOwnProperty.call(E,M))return!1;if(!Lt(C[M],E[M]))return!1}return!0}return!1}function ae(C){return Boolean(C&&typeof C==="object"&&!Array.isArray(C))}async function vt(C,E,P="replace"){if(!Mn(C))return null;try{let x=await import(C),M=x.default||x;if(typeof M!=="object"||M===null||Array.isArray(M))return null;try{return Fr(E,M,P)}catch{return null}}catch{return null}}function Fi(C,E,P=!1){if(!C)return E;let x=C.toUpperCase().replace(/-/g,"_"),M={...E};function K(W,V=[]){let U={...W};for(let[z,G]of Object.entries(W)){let J=[...V,z],q=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),Y=`${x}_${J.map(q).join("_")}`,ee=`${x}_${J.map((H)=>H.toUpperCase()).join("_")}`;if(P)$e.info(`Checking environment variable ${Y} for config ${C}.${J.join(".")}`);if(typeof G==="object"&&G!==null&&!Array.isArray(G))U[z]=K(G,J);else{let H=st.env[Y]||st.env[ee];if(H!==void 0){if(P)$e.info(`Using environment variable ${H?Y:ee} for config ${C}.${J.join(".")}`);if(typeof G==="number")U[z]=Number(H);else if(typeof G==="boolean")U[z]=H.toLowerCase()==="true";else if(Array.isArray(G))try{let Z=JSON.parse(H);if(Array.isArray(Z))U[z]=Z;else U[z]=H.split(",").map((te)=>te.trim())}catch{U[z]=H.split(",").map((Z)=>Z.trim())}else U[z]=H}}}return U}return K(M)}async function Ni({name:C="",alias:E,cwd:P,configDir:x,defaultConfig:M,verbose:K=!1,checkEnv:W=!0,arrayStrategy:V="replace"}){let U=W&&typeof M==="object"&&M!==null&&!Array.isArray(M)?Fi(C,M,K):M,z=P||st.cwd(),G=[".ts",".js",".mjs",".cjs",".json"];if(K)$e.info(`Loading configuration for "${C}"${E?` (alias: "${E}")`:""} from ${z}`);let J=[C,`.${C}`].filter(Boolean),q=[`${C}.config`,`.${C}.config`].filter(Boolean),Y=E?[E,`.${E}`]:[],ee=E?[`${E}.config`,`.${E}.config`]:[],H=Array.from(new Set([z,xe(z,"config"),xe(z,".config"),x?xe(z,x):void 0].filter(Boolean)));for(let Z of H){if(K)$e.info(`Searching for configuration in: ${Z}`);let re=[xe(z,"config"),xe(z,".config")].concat(x?[xe(z,x)]:[]).includes(Z)?[...J,...q,...Y,...ee]:[...q,...J,...ee,...Y];for(let fe of re)for(let Ce of G){let we=xe(Z,`${fe}${Ce}`),Se=await vt(we,U,V);if(Se!==null){if(K)$e.success(`Configuration loaded from: ${we}`);return Se}}}if(C){let Z=xe(Yt(),".config",C),te=["config",`${C}.config`];if(E)te.push(`${E}.config`);if(K)$e.info(`Checking user config directory: ${Z}`);for(let re of te)for(let fe of G){let Ce=xe(Z,`${re}${fe}`),we=await vt(Ce,U,V);if(we!==null){if(K)$e.success(`Configuration loaded from user config directory: ${Ce}`);return we}}}if(C){let Z=xe(Yt(),".config"),te=[`.${C}.config`];if(E)te.push(`.${E}.config`);if(K)$e.info(`Checking user config directory for dotfile configs: ${Z}`);for(let re of te)for(let fe of G){let Ce=xe(Z,`${re}${fe}`),we=await vt(Ce,U,V);if(we!==null){if(K)$e.success(`Configuration loaded from user config directory dotfile: ${Ce}`);return we}}}if(C){let Z=Yt(),te=[`.${C}.config`,`.${C}`];if(E)te.push(`.${E}.config`),te.push(`.${E}`);if(K)$e.info(`Checking user home directory for dotfile configs: ${Z}`);for(let re of te)for(let fe of G){let Ce=xe(Z,`${re}${fe}`),we=await vt(Ce,U,V);if(we!==null){if(K)$e.success(`Configuration loaded from user home directory: ${Ce}`);return we}}}try{let Z=xe(z,"package.json");if(Mn(Z)){let te=await import(Z),re=te[C];if(!re&&E){if(re=te[E],re&&K)$e.success(`Using alias "${E}" configuration from package.json`)}if(re&&typeof re==="object"&&!Array.isArray(re))try{if(K)$e.success(`Configuration loaded from package.json: ${re===te[C]?C:E}`);return Fr(U,re,V)}catch(fe){if(K)$e.warn("Failed to merge package.json config:",fe)}}}catch(Z){if(K)$e.warn("Failed to load package.json:",Z)}if(K)$e.info(`No configuration found for "${C}"${E?` or alias "${E}"`:""}, using default configuration with environment variables`);return U}function Pi(C,E={}){let P=Rt.cwd();while(P.includes("storage"))P=Hr(P,"..");let x=Hr(P,C||"");if(E?.relative)return js(Rt.cwd(),x);return x}async function Mi(){try{let C=await Ni({name:"clarity",alias:"logging",defaultConfig:Tt,cwd:Rt.cwd()});return{...Tt,...C||{}}}catch{return Tt}}function he(){if(je.env.NODE_ENV==="test"||je.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Di(){if(je.env.NODE_ENV==="test"||je.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof je<"u"){let C=je.type;if(C==="renderer"||C==="worker")return!1;return!!(je.versions&&(je.versions.node||je.versions.bun))}return!1}class jn{async format(C){let E=await Di(),P=await this.getMetadata(E);return JSON.stringify({timestamp:C.timestamp.toISOString(),level:C.level,name:C.name,message:C.message,metadata:P})}async getMetadata(C){if(C){let{hostname:E}=await import("os");return{pid:Ze.pid,hostname:E(),environment:Ze.env.NODE_ENV||"development",platform:Ze.platform,version:Ze.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ze.env.NODE_ENV||Ze.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class It{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(C,E={}){this.name=C,this.config={...br},this.options=this.normalizeOptions(E),this.formatter=this.options.formatter||new jn,this.enabled=E.enabled??!0,this.fancy=E.fancy??!0,this.tagFormat=E.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=E.timestampPosition??"right",this.environment=E.environment??ie.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(E);let P={...E},x=E.timestamp!==void 0;if(x)delete P.timestamp;if(this.config={...this.config,...P,timestamp:x||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let M=this.generateKeyId(),K=this.generateKey();this.currentKeyId=M,this.keys.set(M,K),this.encryptionKeys.set(M,{key:K,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(C){if(!this.fingersCrossedConfig)return!1;let E={debug:0,info:1,success:2,warning:3,error:4},P=this.fingersCrossedConfig.activationLevel??"error";return E[C]>=E[P]}initializeFingersCrossedConfig(C){if(!C.fingersCrossedEnabled&&C.fingersCrossed)return{...At,...C.fingersCrossed};if(!C.fingersCrossedEnabled)return null;if(!C.fingersCrossed)return{...At};return{...At,...C.fingersCrossed}}normalizeOptions(C){let E={format:"json",level:"info",logDirectory:br.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},P={...E,...Object.fromEntries(Object.entries(C).filter(([,x])=>x!==void 0))};if(!P.level||!["debug","info","success","warning","error"].includes(P.level))P.level=E.level;return P}shouldWriteToFile(){return!he()&&this.config.writeToFile===!0}async writeToFile(C){let P=(async()=>{let M,K=0,W=3,V=1000;while(K<W)try{try{try{await Xs(this.config.logDirectory,cn.F_OK|cn.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await Qs(this.config.logDirectory,{recursive:!0,mode:493});else if(z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw z;else throw z}}catch(z){throw console.error("Debug: [writeToFile] Failed to create log directory:",z),z}let U=this.validateEncryptionConfig()?(await this.encrypt(C)).encrypted:De.from(C);try{if(!gt(this.currentLogFile))await rr(this.currentLogFile,"",{mode:420});if(M=an(this.currentLogFile,"a",420),Zs(M,U,{flag:"a"}),on(M),M!==void 0)tr(M),M=void 0;if((await Ye(this.currentLogFile)).size===0){if(await rr(this.currentLogFile,U,{flag:"w",mode:420}),(await Ye(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let G=z;if(G.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(G.code)){if(K<W-1){let J=typeof G.message==="string"?G.message:"Unknown error";console.error(`Network error during write attempt ${K+1}/${W}:`,J);let q=V*2**K;await new Promise((Y)=>setTimeout(Y,q)),K++;continue}}if(G?.code&&["ENOSPC","EDQUOT"].includes(G.code))throw Error(`Disk quota exceeded or no space left on device: ${G.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",G),G}finally{if(M!==void 0)try{tr(M)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(U){if(K===W-1){let G=U,J=typeof G.message==="string"?G.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",J),U}K++;let z=V*2**(K-1);await new Promise((G)=>setTimeout(G,z))}})();this.pendingOperations.push(P);let x=this.pendingOperations.length-1;try{await P}catch(M){throw console.error("Debug: [writeToFile] Error in operation:",M),M}finally{this.pendingOperations.splice(x,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 He(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 He(this.config.logDirectory,`${this.name}.log`);let C=new Date().toISOString().split("T")[0];return He(this.config.logDirectory,`${this.name}-${C}.log`)}setupRotation(){if(he())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let C=this.config.rotation,E;switch(C.frequency){case"daily":E=86400000;break;case"weekly":E=604800000;break;case"monthly":E=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},E)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let E=this.config.rotation.keyRotation;if(!E?.enabled)return;let P=typeof E.interval==="number"?E.interval:60,x=Math.max(P,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((M)=>{console.error("Error rotating keys:",M)})},x)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let E=this.config.rotation.keyRotation,P=this.generateKeyId(),x=this.generateKey();this.currentKeyId=P,this.keys.set(P,x),this.encryptionKeys.set(P,{key:x,createdAt:new Date});let M=Array.from(this.encryptionKeys.entries()).sort(([,V],[,U])=>U.createdAt.getTime()-V.createdAt.getTime()),K=typeof E.maxKeys==="number"?E.maxKeys:1,W=Math.max(1,K);if(M.length>W)for(let[V]of M.slice(W))this.encryptionKeys.delete(V),this.keys.delete(V)}generateKeyId(){return er(16).toString("hex")}generateKey(){return er(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let C=this.keys.get(this.currentKeyId);if(!C)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:C,id:this.currentKeyId}}encrypt(C){let{key:E}=this.getCurrentKey(),P=er(16),x=qs("aes-256-gcm",E,P),M=De.isBuffer(C)?C:De.from(C,"utf8"),K=x.update(M),W=x.final(),V=K.length+W.length,U=x.getAuthTag(),z=De.allocUnsafe(16+V+16);return P.copy(z,0),K.copy(z,16),W.copy(z,16+K.length),U.copy(z,16+V),{encrypted:z,iv:P}}async compressData(C){return new Promise((E,P)=>{let x=fn(),M=[];x.on("data",(K)=>M.push(K)),x.on("end",()=>E(De.from(De.concat(M)))),x.on("error",P),x.write(C),x.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let C={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let E=this.config.rotation.encrypt;return{...C,...E}}return C}async rotateLog(){if(he())return;if(!this.shouldWriteToFile())return;let C=await Ye(this.currentLogFile).catch(()=>null);if(!C)return;let E=this.config.rotation;if(typeof E==="boolean")return;if(E.maxSize&&C.size>=E.maxSize){let P=this.currentLogFile,x=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let M=await mt(this.config.logDirectory),K=M.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,z)=>{let G=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-G}),W=K.length>0?Number.parseInt(K[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,V=`${P}.${W}`;if(await Ye(P).catch(()=>null))try{if(await ln(P,V),E.compress)try{let U=`${V}.gz`;await this.compressLogFile(V,U),await ht(V)}catch(U){console.error("Error compressing rotated file:",U)}if(K.length===0&&!M.some((U)=>U.endsWith(".log.1")))try{let U=`${P}.1`;await rr(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let M=new Date().toISOString().replace(/[:.]/g,"-"),K=P.replace(/\.log$/,`-${M}.log`);if(await Ye(P).catch(()=>null))await ln(P,K)}if(this.currentLogFile=x,E.maxFiles){let K=(await mt(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,V)=>V.localeCompare(W));for(let W of K.slice(E.maxFiles))await ht(He(this.config.logDirectory,W))}}}async compressLogFile(C,E){let P=sn(C),x=Hs(E),M=fn();await ri(P,M,x)}async handleFingersCrossedBuffer(C,E){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(C)&&!this.isActivated){this.isActivated=!0;for(let P of this.logBuffer){let x=await this.formatter.format(P);if(this.shouldWriteToFile())await this.writeToFile(x);console.log(x)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(E);console.log(E)}}shouldLog(C){if(!this.enabled)return!1;let E={debug:0,info:1,success:2,warning:3,error:4};return E[C]>=E[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((C)=>{if(C instanceof Promise)return C.catch((E)=>{console.error("Error in pending write operation:",E)});return Promise.resolve()})),gt(this.currentLogFile))try{let C=an(this.currentLogFile,"r+");on(C),tr(C)}catch(C){console.error(`Error flushing file: ${C}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let C of this.pendingOperations)if(typeof C.cancel==="function")C.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(C){console.error("Error waiting for pending operations:",C)}if(!he()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let E=(await mt(this.config.logDirectory)).filter((P)=>(P.includes("temp")||P.includes(".tmp"))&&P.includes(this.name));for(let P of E)try{await ht(He(this.config.logDirectory,P))}catch(x){console.error(`Failed to delete temp file ${P}:`,x)}}catch(C){console.error("Error cleaning up temporary files:",C)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(C){if(!C)return"";return`${this.tagFormat.prefix}${C}${this.tagFormat.suffix}`}formatFileTimestamp(C){return`[${C.toISOString()}]`}formatConsoleTimestamp(C){return this.shouldStyleConsole()?ne.gray(C.toLocaleTimeString()):C.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||he())return!1;let C=typeof ie.env.NO_COLOR<"u",E=ie.env.FORCE_COLOR==="0";if(C||E)return!1;return!!(typeof ie.stderr<"u"&&ie.stderr.isTTY||typeof ie.stdout<"u"&&ie.stdout.isTTY)}formatConsoleMessage(C){let{timestamp:E,icon:P="",tag:x="",message:M,level:K,showTimestamp:W=!0}=C,V=(Y)=>Y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let Y=[];if(W)Y.push(E);if(K==="warning")Y.push("WARN");else if(K==="error")Y.push("ERROR");else if(P)Y.push(P.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(x)Y.push(x.replace(/[[\]]/g,""));return Y.push(M),Y.join(" ")}let U=ie.stdout.columns||120,z="";if(K==="warning"||K==="error")z=`${P} ${M}`;else if(K==="info"||K==="success")z=`${P} ${x} ${M}`;else z=`${P} ${x} ${ne.cyan(M)}`;if(!W)return z.trim();let G=V(z).trim().length,J=V(E).length,q=Math.max(1,U-2-G-J);return`${z.trim()}${" ".repeat(q)}${E}`}formatMessage(C,E){if(E.length===1&&Array.isArray(E[0]))return C.replace(/\{(\d+)\}/g,(K,W)=>{let V=Number.parseInt(W,10);return V<E[0].length?String(E[0][V]):K});let P=/%([sdijfo%])/g,x=0,M=C.replace(P,(K,W)=>{if(W==="%")return"%";if(x>=E.length)return K;let V=E[x++];switch(W){case"s":return String(V);case"d":case"i":return Number(V).toString();case"j":case"o":return JSON.stringify(V,null,2);default:return K}});if(x<E.length)M+=` ${E.slice(x).map((K)=>typeof K==="object"?JSON.stringify(K,null,2):String(K)).join(" ")}`;return M}formatMarkdown(C){if(!C)return C;let E=C;return E=E.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(P,x,M)=>{let K=ne.underline(ne.blue(x)),W=this.toAbsoluteFilePath(M);if(W&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let V=`file://${encodeURI(W)}`,U="\x1B]8;;",z="\x1B\\";return`\x1B]8;;${V}\x1B\\${K}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${M}\x1B\\${K}\x1B]8;;\x1B\\`;return K}),E=E.replace(/`([^`]+)`/g,(P,x)=>ne.bgGray(x)),E=E.replace(/\*\*([^*]+)\*\*/g,(P,x)=>ne.bold(x)),E=E.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(P,x)=>ne.italic(x)),E=E.replace(/(?<!_)_([^_]+)_(?!_)/g,(P,x)=>ne.italic(x)),E=E.replace(/~([^~]+)~/g,(P,x)=>ne.strikethrough(x)),E}supportsHyperlinks(){if(he())return!1;let C=ie.env;if(!C)return!1;if(C.TERM_PROGRAM==="iTerm.app"||C.TERM_PROGRAM==="vscode"||C.TERM_PROGRAM==="WezTerm")return!0;if(C.WT_SESSION)return!0;if(C.TERM==="xterm-kitty")return!0;let E=C.VTE_VERSION?Number.parseInt(C.VTE_VERSION,10):0;if(!Number.isNaN(E)&&E>=5000)return!0;return!1}toAbsoluteFilePath(C){try{let E=C;if(E.startsWith("file://"))E=E.replace(/^file:\/\//,"");if(E.startsWith("~")){let P=ie.env.HOME||"";if(P)E=E.replace(/^~(?=$|\/)/,P)}if(ei(E)||E.startsWith("./")||E.startsWith("../"))E=ti(E);else return null;return gt(E)?E:null}catch{return null}}buildOutputTexts(C){let E=this.shouldStyleConsole()?this.formatMarkdown(C):C,P=C.replace(this.ANSI_PATTERN,"");return{consoleText:E,fileText:P}}async log(C,E,...P){let x=new Date,M=this.formatConsoleTimestamp(x),K=this.formatFileTimestamp(x),W,V;if(E instanceof Error)W=E.message,V=E.stack;else W=this.formatMessage(E,P);let{consoleText:U,fileText:z}=this.buildOutputTexts(W);if(this.shouldStyleConsole()){let J=this.options.showIcons===!1?"":qn[C],q=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"",Y;switch(C){case"debug":Y=this.formatConsoleMessage({timestamp:M,icon:J,tag:q,message:ne.gray(U),level:C}),console.error(Y);break;case"info":Y=this.formatConsoleMessage({timestamp:M,icon:J,tag:q,message:U,level:C}),console.warn(Y);break;case"success":Y=this.formatConsoleMessage({timestamp:M,icon:J,tag:q,message:ne.green(U),level:C}),console.error(Y);break;case"warning":Y=this.formatConsoleMessage({timestamp:M,icon:J,tag:q,message:U,level:C}),console.warn(Y);break;case"error":if(Y=this.formatConsoleMessage({timestamp:M,icon:J,tag:q,message:U,level:C}),console.error(Y),V){let ee=V.split(`
11
- `);for(let H of ee)if(H.trim()&&!H.includes(W))console.error(this.formatConsoleMessage({timestamp:M,message:ne.gray(` ${H}`),level:C,showTimestamp:!1}))}break}}else if(!he()){if(console.error(`${K} ${this.environment}.${C.toUpperCase()}: ${W}`),V)console.error(V)}if(!this.shouldLog(C))return;let G=`${K} ${this.environment}.${C.toUpperCase()}: ${z}
12
- `;if(V)G+=`${V}
13
- `;if(G=G.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(G)}progress(C,E=""){let P={update:(V,U)=>{},finish:(V)=>{},interrupt:(V,U)=>{}};if(!this.enabled)return P;let x=30;if(this.activeProgressBar={total:Math.max(1,C||1),current:0,message:E||"",barLength:x,lastRenderedLine:""},this.shouldStyleConsole()&&!he()&&ie.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(V,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,V),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!he()&&ie.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(V)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,V)},interrupt:(V,U="info")=>{if(!he()&&ie.stdout.isTTY)ie.stdout.write(`
14
- `);if(this[U==="warning"?"warn":U](V),this.activeProgressBar&&this.shouldStyleConsole()&&!he()&&ie.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(C){let E=performance.now();if(this.shouldStyleConsole()){let P=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"",x=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:x,icon:this.options.showIcons===!1?"":ne.blue("\u25D0"),tag:P,message:`${ne.cyan(C)}...`}))}return async(P)=>{if(!this.enabled)return;let x=performance.now(),M=Math.round(x-E),K=`${C} completed in ${M}ms`,W=new Date,V=this.formatConsoleTimestamp(W),z=`${this.formatFileTimestamp(W)} ${this.environment}.INFO: ${K}`;if(P)z+=` ${JSON.stringify(P)}`;if(z+=`
15
- `,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let G=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:V,icon:this.options.showIcons===!1?"":ne.green("\u2713"),tag:G,message:`${K}${P?` ${JSON.stringify(P)}`:""}`}))}else if(!he())console.error(z.trim());if(this.shouldWriteToFile())await this.writeToFile(z)}}async debug(C,...E){await this.log("debug",C,...E)}async info(C,...E){await this.log("info",C,...E)}async success(C,...E){await this.log("success",C,...E)}async warn(C,...E){await this.log("warning",C,...E)}async error(C,...E){await this.log("error",C,...E)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let C=this.config.rotation,{encrypt:E}=C;return!!E}async only(C){if(!this.enabled)return;return await C()}isEnabled(){return this.enabled}setEnabled(C){this.enabled=C}extend(C){let E=`${this.name}:${C}`,P=new It(E,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(P),P}createReadStream(){if(he())throw Error("createReadStream is not supported in browser environments");if(!gt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return sn(this.currentLogFile,{encoding:"utf8"})}async decrypt(C){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let E=this.config.rotation;if(!E.encrypt||typeof E.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let P=this.keys.get(this.currentKeyId);try{let x=De.isBuffer(C)?C:De.from(C,"base64"),M=x.subarray(0,16),K=x.subarray(x.length-16),W=x.subarray(16,x.length-16),V=Ys("aes-256-gcm",P,M);V.setAuthTag(K);let U=V.update(W),z=V.final(),G=U.length+z.length,J=De.allocUnsafe(G);return U.copy(J,0),z.copy(J,U.length),J.toString("utf8")}catch(x){throw Error(`Decryption failed: ${x instanceof Error?x.message:String(x)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return he()}isServerMode(){return!he()}setTestEncryptionKey(C,E){this.currentKeyId=C,this.keys.set(C,E)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(C){if(!this.enabled)return;let E=new Date,P=this.formatConsoleTimestamp(E),x=this.formatFileTimestamp(E),{consoleText:M,fileText:K}=this.buildOutputTexts(C);if(this.shouldStyleConsole()){let V=M.split(`
16
- `),U=Math.max(...V.map((q)=>q.length))+2,z=`\u250C${"\u2500".repeat(U)}\u2510`,G=`\u2514${"\u2500".repeat(U)}\u2518`,J=V.map((q)=>this.formatConsoleMessage({timestamp:P,message:ne.cyan(q),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:P,message:ne.cyan(z),showTimestamp:!1})),J.forEach((q)=>console.error(q)),console.error(this.formatConsoleMessage({timestamp:P,message:ne.cyan(G),showTimestamp:!1}))}else if(!he())console.error(`${x} ${this.environment}.INFO: [BOX] ${K}`);let W=`${x} ${this.environment}.INFO: [BOX] ${K}
17
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}async prompt(C){if(he())return Promise.resolve(!0);return new Promise((E)=>{console.error(`${ne.cyan("?")} ${C} (y/n) `);let P=(x)=>{let M=x.toString().trim().toLowerCase();ie.stdin.removeListener("data",P);try{if(typeof ie.stdin.setRawMode==="function")ie.stdin.setRawMode(!1)}catch{}ie.stdin.pause(),console.error(""),E(M==="y"||M==="yes")};try{if(typeof ie.stdin.setRawMode==="function")ie.stdin.setRawMode(!0)}catch{}ie.stdin.resume(),ie.stdin.once("data",P)})}setFancy(C){this.fancy=C}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(C,...E){if(!this.enabled)return;let P=C;if(E&&E.length>0){let U=/%([sdijfo%])/g,z=0;if(P=C.replace(U,(G,J)=>{if(J==="%")return"%";if(z>=E.length)return G;let q=E[z++];switch(J){case"s":return String(q);case"d":case"i":return Number(q).toString();case"j":case"o":return JSON.stringify(q,null,2);default:return G}}),z<E.length)P+=` ${E.slice(z).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`}let{consoleText:x,fileText:M}=this.buildOutputTexts(P);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"",z=this.options.showIcons===!1?"":`${ne.blue("\u25D0")} `;console.error(`${z}${U} ${ne.cyan(x)}`)}let V=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${M}
18
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(V)}renderProgressBar(C,E=!1){if(!this.enabled||!this.shouldStyleConsole()||!ie.stdout.isTTY)return;let P=Math.min(100,Math.max(0,Math.round(C.current/C.total*100))),x=Math.round(C.barLength*P/100),M=C.barLength-x,K=ne.green("\u2501".repeat(x)),W=ne.gray("\u2501".repeat(M)),V=`[${K}${W}]`,U=`${P}%`.padStart(4),z=C.message?` ${C.message}`:"",G=this.options.showIcons===!1?"":E||P===100?ne.green("\u2713"):ne.blue("\u25B6"),J=this.options.showTags!==!1&&this.name?` ${ne.gray(this.formatTag(this.name))}`:"",q=`\r${G}${J} ${V} ${U}${z}`,Y=ie.stdout.columns||80,ee=" ".repeat(Math.max(0,Y-q.replace(this.ANSI_PATTERN,"").length));if(C.lastRenderedLine=`${q}${ee}`,ie.stdout.write(C.lastRenderedLine),E)ie.stdout.write(`
19
- `)}finishProgressBar(C,E){if(!this.enabled||!this.fancy||he()||!ie.stdout.isTTY){this.activeProgressBar=null;return}if(C.current<C.total)C.current=C.total;if(E)C.message=E;this.renderProgressBar(C,!0),this.activeProgressBar=null}async clear(C={}){if(he()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let E=await mt(this.config.logDirectory),P=[];for(let x of E){if(!(C.name?new RegExp(C.name.replace("*",".*")).test(x):x.startsWith(this.name))||!x.endsWith(".log"))continue;let K=He(this.config.logDirectory,x);if(C.before)try{if((await Ye(K)).mtime>=C.before)continue}catch(W){console.error(`Failed to get stats for file ${K}:`,W);continue}P.push(K)}if(P.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${P.length} log file(s)...`);for(let x of P)try{await ht(x),console.warn(`Deleted log file: ${x}`)}catch(M){console.error(`Failed to delete log file ${x}:`,M)}console.warn("Log clearing process finished.")}catch(E){console.error("Error during log clearing process:",E)}}}async function _n(C,E={}){let{maxRetries:P=3,retryDelay:x=1000,isRetryable:M=()=>!0,fallback:K}=E,W=Error("Unknown error occurred");for(let V=0;V<=P;V++)try{return await C()}catch(U){if(W=U instanceof Error?U:Error(String(U)),V===P||!M(W))break;if(x>0)await new Promise((z)=>setTimeout(z,x))}if(K!==void 0)return K;throw W instanceof Error?W:Error(`Unknown error: ${String(W)}`)}function Bn(C){return C instanceof Ae}function Li(C){return C instanceof jt}function Ii(C){if(Bn(C))return C.code==="FILE_SYSTEM_ERROR"||C.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((P)=>C.message.toLowerCase().includes(P.toLowerCase()))}class Ut{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(C,E)=>E==="boolean"||["true","false","1","0","yes","no"].includes(C.toLowerCase()),parse:(C)=>{let E=C.toLowerCase();return["true","1","yes"].includes(E)}},{name:"number",canParse:(C,E)=>E==="number"||!Number.isNaN(Number(C))&&!Number.isNaN(Number.parseFloat(C)),parse:(C)=>{let E=Number(C);if(Number.isNaN(E))throw TypeError(`Cannot parse "${C}" as number`);return E}},{name:"array",canParse:(C,E)=>E==="array"||C.startsWith("[")||C.includes(","),parse:(C)=>{try{let E=JSON.parse(C);if(Array.isArray(E))return E}catch{}return C.split(",").map((E)=>E.trim())}},{name:"json",canParse:(C,E)=>E==="object"||(C.startsWith("{")&&C.endsWith("}")||C.startsWith("[")&&C.endsWith("]")),parse:(C)=>{try{return JSON.parse(C)}catch(E){throw Error(`Cannot parse "${C}" as JSON: ${E}`)}}}]}async applyEnvironmentVariables(C,E,P={}){let{prefix:x,useCamelCase:M=!0,useBackwardCompatibility:K=!0,customParsers:W={},verbose:V=!1,trackPerformance:U=!0}=P,z=async()=>{if(!C)return{config:E,source:{type:"environment",priority:50,timestamp:new Date}};let G=x||this.generateEnvPrefix(C),J={...E};return this.processObject(J,[],G,{useCamelCase:M,useBackwardCompatibility:K,customParsers:W,verbose:V,configName:C}),{config:J,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return at.track("applyEnvironmentVariables",z,{configName:C});return z()}generateEnvPrefix(C){return C.toUpperCase().replace(/-/g,"_")}formatEnvKey(C,E){if(!E)return C.toUpperCase();return C.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(C,E,P,x){for(let[M,K]of Object.entries(C)){let W=[...E,M],V=W.map((G)=>this.formatEnvKey(G,x.useCamelCase)),U=`${P}_${V.join("_")}`,z=x.useBackwardCompatibility?`${P}_${W.map((G)=>G.toUpperCase()).join("_")}`:null;if(x.verbose);if(typeof K==="object"&&K!==null&&!Array.isArray(K))this.processObject(K,W,P,x);else{let G=dt.env[U]||(z?dt.env[z]:void 0);if(G!==void 0){if(x.verbose){let J=dt.env[U]?U:z}try{C[M]=this.parseEnvironmentValue(G,typeof K,U,x.customParsers,x.configName)}catch(J){if(J instanceof _t)throw J;throw We.envVar(U,G,typeof K,x.configName)}}}}}parseEnvironmentValue(C,E,P,x,M){for(let[K,W]of Object.entries(x))try{return W(C)}catch{continue}for(let K of this.defaultParsers)if(K.canParse(C,E))try{return K.parse(C)}catch{throw We.envVar(P,C,`${E} (via ${K.name} parser)`,M)}return C}getEnvironmentVariables(C){let E={},P=C.toUpperCase();for(let[x,M]of Object.entries(dt.env))if(x.startsWith(P)&&M!==void 0)E[x]=M;return E}validateEnvironmentVariable(C,E,P){let x=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(C))x.push(`Environment variable key "${C}" should only contain uppercase letters, numbers, and underscores`);if(P)try{this.parseEnvironmentValue(C,E,P,{})}catch(M){x.push(`Cannot parse value "${E}" as ${P}: ${M}`)}return{isValid:x.length===0,errors:x}}generateEnvVarDocs(C,E,P={}){let{prefix:x,format:M="text"}=P,K=x||this.generateEnvPrefix(C),W=[];switch(this.extractEnvVarInfo(E,[],K,W),M){case"markdown":return this.formatAsMarkdown(W,C);case"json":return JSON.stringify(W,null,2);default:return this.formatAsText(W,C)}}extractEnvVarInfo(C,E,P,x){for(let[M,K]of Object.entries(C)){let W=[...E,M],V=`${P}_${W.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof K==="object"&&K!==null&&!Array.isArray(K))this.extractEnvVarInfo(K,W,P,x);else x.push({key:V,type:Array.isArray(K)?"array":typeof K,description:`Configuration for ${W.join(".")}`,example:this.generateExample(K)})}}generateExample(C){if(Array.isArray(C))return JSON.stringify(C);if(typeof C==="object"&&C!==null)return JSON.stringify(C);return String(C)}formatAsText(C,E){let P=`Environment Variables for ${E}:
20
-
21
- `;for(let x of C)P+=`${x.key}
22
- `,P+=` Type: ${x.type}
23
- `,P+=` Description: ${x.description}
24
- `,P+=` Example: ${x.example}
25
-
26
- `;return P}formatAsMarkdown(C,E){let P=`# Environment Variables for ${E}
27
-
28
- `;P+=`| Variable | Type | Description | Example |
29
- `,P+=`|----------|------|-------------|----------|
30
- `;for(let x of C)P+=`| \`${x.key}\` | ${x.type} | ${x.description} | \`${x.example}\` |
31
- `;return P}}function ji(C,E){let P=zn("process");if(typeof P>"u"||!P.env)return E;let x=P.env[C];return x!==void 0?x:E}function Kn(C,E,P={}){return Wn(C,E,P,new WeakMap)}function Wn(C,E,P,x){let{arrayMergeMode:M="replace",skipNullish:K=!1,customMerger:W}=P;if(E===null||E===void 0)return K?C:E;if(W){let V=W(C,E);if(V!==void 0)return V}if(Array.isArray(E)||Array.isArray(C))return Vn(C,E,M,x);if(!Re(E)||!Re(C))return E;return Wi(C,E,P,x)}function Vn(C,E,P,x){if(Array.isArray(E)&&!Array.isArray(C))return E;if(Array.isArray(C)&&!Array.isArray(E))return E;if(Array.isArray(E)&&Array.isArray(C))switch(P){case"replace":return E;case"concat":return _i(C,E);case"smart":return Bi(C,E,x);default:return E}return E}function _i(C,E){let P=[...E];for(let x of C)if(!P.some((M)=>yr(M,x)))P.push(x);return P}function Bi(C,E,P){if(E.length===0)return C;if(C.length===0)return E;if(Re(E[0])&&Re(C[0]))return Ki(C,E,P);if(E.every((x)=>typeof x==="string")&&C.every((x)=>typeof x==="string")){let x=[...E];for(let M of C)if(!x.includes(M))x.push(M);return x}return E}function Ki(C,E,P){let x=[...E];for(let M of C){if(!Re(M)){x.push(M);continue}let K=["id","name","key","path","type"],W=!1;for(let V of K)if(V in M){if(x.find((z)=>Re(z)&&(V in z)&&z[V]===M[V])){W=!0;break}}if(!W)x.push(M)}return x}function Wi(C,E,P,x){let M=E;if(Re(M)&&x.has(M))return x.get(M);let K={...C};if(Re(M))x.set(M,K);for(let W in M){if(!Object.prototype.hasOwnProperty.call(M,W))continue;let V=M[W],U=K[W];if(P.skipNullish&&(V===null||V===void 0))continue;if(V===null||V===void 0){K[W]=V;continue}if(Re(V)&&Re(U))K[W]=Wn(U,V,P,x);else if(Array.isArray(V)||Array.isArray(U))K[W]=Vn(U,V,P.arrayMergeMode||"smart",x);else K[W]=V}return K}function Nr(C,E,P="replace"){return Kn(C,E,{arrayMergeMode:P==="replace"?"replace":"smart",skipNullish:!0})}function yr(C,E){if(C===E)return!0;if(Array.isArray(C)&&Array.isArray(E)){if(C.length!==E.length)return!1;for(let P=0;P<C.length;P++)if(!yr(C[P],E[P]))return!1;return!0}if(Re(C)&&Re(E)){let P=Object.keys(C),x=Object.keys(E);if(P.length!==x.length)return!1;for(let M of P){if(!Object.prototype.hasOwnProperty.call(E,M))return!1;if(!yr(C[M],E[M]))return!1}return!0}return!1}function Re(C){return Boolean(C&&typeof C==="object"&&!Array.isArray(C))}class zt{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(C,E,P={}){let{arrayStrategy:x="replace",useCache:M=!0,cacheTtl:K,trackPerformance:W=!0,verbose:V=!1}=P;if(M){let z=tt.getWithFileCheck("file",C);if(z){if(V)console.log(`Configuration loaded from cache: ${C}`);return z}}let U=async()=>{if(!pt(C))return null;try{let z=`?t=${Date.now()}`,G=await import(C+z),J=G.default||G,q="default"in G,Y=Object.keys(G).length>0;if(!q&&!Y)throw new it(C,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof J!=="object"||J===null||Array.isArray(J))throw new it(C,Error("Configuration must export a valid object"),"unknown");let Z={config:Nr(E,J,x),source:{type:"file",path:C,priority:100,timestamp:new Date}};if(M)tt.setWithFileCheck("file",Z,C,K);return Z}catch(z){throw z instanceof Error?We.configLoad(C,z):We.configLoad(C,Error(String(z)))}};if(W)return at.track("loadFromPath",U,{path:C});return U()}async tryLoadFromPaths(C,E,P={}){for(let x of C)try{let M=await this.loadFromPath(x,E,P);if(M)return M}catch(M){if(M instanceof Error&&M.name==="ConfigLoadError")throw M;if(P.verbose)console.warn(`Failed to load config from ${x}:`,M)}return null}generateConfigPaths(C,E,P){let x=this.generateNamePatterns(C,P),M=[];for(let K of x)for(let W of this.extensions)M.push(nr(E,`${K}${W}`));return M}generateNamePatterns(C,E){let P=[];if(P.push("config",".config"),C)P.push(C,`.${C}.config`,`${C}.config`,`.${C}`);if(E){if(P.push(E,`.${E}.config`,`${E}.config`,`.${E}`),C)P.push(`${C}.${E}.config`,`.${C}.${E}.config`)}return P.filter(Boolean)}checkFileAccess(C){return _n(async()=>pt(C),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(C,E,P){let x=[];if(!pt(C))return x;if(E||P){let M=this.generateNamePatterns(E||"",P);for(let K of M)for(let W of this.extensions){let V=nr(C,`${K}${W}`);if(await this.checkFileAccess(V))x.push(V)}}else try{let{readdirSync:M}=await import("fs"),K=M(C);for(let W of K)if(this.looksLikeConfigFile(W)){let V=nr(C,W);if(await this.checkFileAccess(V))x.push(V)}}catch{return[]}return x}looksLikeConfigFile(C){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((P)=>P.test(C))}async validateConfigFile(C){let E=[];try{if(!pt(C))return E.push("Configuration file does not exist"),E;let P=await import(C),x=P.default||P;if(x===void 0)E.push("Configuration file must export a default value or named exports");else if(typeof x!=="object"||x===null)E.push("Configuration must be an object");else if(Array.isArray(x))E.push("Configuration cannot be an array at the root level");if(C.endsWith(".json"))try{let{readFileSync:M}=await import("fs"),K=M(C,"utf8");JSON.parse(K)}catch(M){E.push(`Invalid JSON syntax: ${M}`)}}catch(P){E.push(`Failed to load configuration file: ${P}`)}return E}async getFileModificationTime(C){try{let{statSync:E}=await import("fs");return E(C).mtime}catch{return null}}async preloadConfigurations(C,E={}){let P=new Map;return await Promise.allSettled(C.map(async(x)=>{try{let M=await this.loadFromPath(x,{},E);if(M)P.set(x,M.config)}catch(M){if(E.verbose)console.warn(`Failed to preload ${x}:`,M)}})),P}}class Pr{async validateConfiguration(C,E,P={}){let{stopOnFirstError:x=!1,validateRequired:M=!0,validateTypes:K=!0,customRules:W=[],trackPerformance:V=!0,verbose:U=!1}=P,z=async()=>{let G=[],J=[],q={stopOnFirstError:x,validateRequired:M,validateTypes:K,customRules:W,trackPerformance:V,verbose:U};try{if(typeof E==="string")return await this.validateWithSchemaFile(C,E,q);else if(Array.isArray(E))return this.validateWithRules(C,[...E,...W],q);else return this.validateWithJSONSchema(C,E,q)}catch(Y){return G.push({path:"",message:`Validation failed: ${Y}`,rule:"system"}),{isValid:!1,errors:G,warnings:J}}};if(V)return await at.track("validateConfiguration",z);return z()}async validateWithSchemaFile(C,E,P){try{if(!ni(E))throw new ot(E,[{path:"",message:"Schema file does not exist"}]);let x=await import(E),M=x.default||x;if(Array.isArray(M))return this.validateWithRules(C,M,P);else return this.validateWithJSONSchema(C,M,P)}catch(x){throw new ot(E,[{path:"",message:`Failed to load schema: ${x}`}])}}validateWithJSONSchema(C,E,P){let x=[],M=[];return this.validateObjectAgainstSchema(C,E,"",x,M,P),{isValid:x.length===0,errors:x,warnings:M}}validateObjectAgainstSchema(C,E,P,x,M,K){if(K.validateTypes&&E.type){let W=Array.isArray(C)?"array":typeof C,V=Array.isArray(E.type)?E.type:[E.type];if(!V.includes(W)){if(x.push({path:P,message:`Expected type ${V.join(" or ")}, got ${W}`,expected:V.join(" or "),actual:W,rule:"type"}),K.stopOnFirstError)return}}if(E.enum&&!E.enum.includes(C)){if(x.push({path:P,message:`Value must be one of: ${E.enum.join(", ")}`,expected:E.enum.join(", "),actual:C,rule:"enum"}),K.stopOnFirstError)return}if(typeof C==="string"){if(E.minLength!==void 0&&C.length<E.minLength)x.push({path:P,message:`String length must be at least ${E.minLength}`,expected:`>= ${E.minLength}`,actual:C.length,rule:"minLength"});if(E.maxLength!==void 0&&C.length>E.maxLength)x.push({path:P,message:`String length must not exceed ${E.maxLength}`,expected:`<= ${E.maxLength}`,actual:C.length,rule:"maxLength"});if(E.pattern){if(!new RegExp(E.pattern).test(C))x.push({path:P,message:`String does not match pattern ${E.pattern}`,expected:E.pattern,actual:C,rule:"pattern"})}}if(typeof C==="number"){if(E.minimum!==void 0&&C<E.minimum)x.push({path:P,message:`Value must be at least ${E.minimum}`,expected:`>= ${E.minimum}`,actual:C,rule:"minimum"});if(E.maximum!==void 0&&C>E.maximum)x.push({path:P,message:`Value must not exceed ${E.maximum}`,expected:`<= ${E.maximum}`,actual:C,rule:"maximum"})}if(Array.isArray(C)&&E.items)for(let W=0;W<C.length;W++){let V=P?`${P}[${W}]`:`[${W}]`;if(this.validateObjectAgainstSchema(C[W],E.items,V,x,M,K),K.stopOnFirstError&&x.length>0)return}if(C&&typeof C==="object"&&!Array.isArray(C)){let W=C;if(K.validateRequired&&E.required){for(let V of E.required)if(!(V in W)){if(x.push({path:P?`${P}.${V}`:V,message:`Missing required property '${V}'`,expected:"required",rule:"required"}),K.stopOnFirstError)return}}if(E.properties){for(let[V,U]of Object.entries(E.properties))if(V in W){let z=P?`${P}.${V}`:V;if(this.validateObjectAgainstSchema(W[V],U,z,x,M,K),K.stopOnFirstError&&x.length>0)return}}if(E.additionalProperties===!1){let V=new Set(Object.keys(E.properties||{}));for(let U of Object.keys(W))if(!V.has(U))M.push({path:P?`${P}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(C,E,P){let x=[],M=[];for(let K of E)try{let W=this.getValueByPath(C,K.path),V=this.validateWithRule(W,K,K.path);if(x.push(...V),P.stopOnFirstError&&x.length>0)break}catch(W){x.push({path:K.path,message:`Rule validation failed: ${W}`,rule:"system"})}return{isValid:x.length===0,errors:x,warnings:M}}validateWithRule(C,E,P){let x=[];if(E.required&&(C===void 0||C===null))return x.push({path:P,message:E.message||`Property '${P}' is required`,expected:"required",rule:"required"}),x;if(C===void 0||C===null)return x;if(E.type){let M=Array.isArray(C)?"array":typeof C;if(M!==E.type)x.push({path:P,message:E.message||`Expected type ${E.type}, got ${M}`,expected:E.type,actual:M,rule:"type"})}if(E.min!==void 0){let M=Array.isArray(C)?C.length:typeof C==="string"?C.length:typeof C==="number"?C:0;if(M<E.min)x.push({path:P,message:E.message||`Value must be at least ${E.min}`,expected:`>= ${E.min}`,actual:M,rule:"min"})}if(E.max!==void 0){let M=Array.isArray(C)?C.length:typeof C==="string"?C.length:typeof C==="number"?C:0;if(M>E.max)x.push({path:P,message:E.message||`Value must not exceed ${E.max}`,expected:`<= ${E.max}`,actual:M,rule:"max"})}if(E.pattern&&typeof C==="string"){if(!E.pattern.test(C))x.push({path:P,message:E.message||`Value does not match pattern ${E.pattern}`,expected:E.pattern.toString(),actual:C,rule:"pattern"})}if(E.enum&&!E.enum.includes(C))x.push({path:P,message:E.message||`Value must be one of: ${E.enum.join(", ")}`,expected:E.enum.join(", "),actual:C,rule:"enum"});if(E.validator){let M=E.validator(C);if(M)x.push({path:P,message:E.message||M,rule:"custom"})}return x}getValueByPath(C,E){if(!E)return C;let P=E.split("."),x=C;for(let M of P)if(x&&typeof x==="object"&&M in x)x=x[M];else return;return x}generateRulesFromInterface(C){let E=[],P=C.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let x of P){let[,M,K,W]=x;E.push({path:M,required:!K,type:this.mapTypeScriptType(W)})}return E}mapTypeScriptType(C){switch(C.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:Hn},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Mr{fileLoader=new zt;envProcessor=new Ut;validator=new Pr;async loadConfig(C){let E=Date.now(),{cache:P,performance:x,schema:M,validate:K,...W}=C;try{if(P?.enabled){let U=this.checkCache(W.name||"",W);if(U)return U}let V;try{V=await this.loadConfigurationStrategies(W,!0,P)}catch(U){let z=W.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(z)throw U;V={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`No configuration file found for "${W.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let G=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),J=!G&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),q=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(z&&(q||G))throw U;if(J&&(!z||!q))V={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!z)V={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else V={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(M||K)await this.validateConfiguration(V.config,M,K,W.name);if(P?.enabled&&V)this.cacheResult(W.name||"",V,P,W);if(x?.enabled){let U={operation:"loadConfig",duration:Date.now()-E,configName:W.name,timestamp:new Date};if(x.onMetrics)x.onMetrics(U);if(x.slowThreshold&&U.duration>x.slowThreshold)Ne.warn(`Slow configuration loading detected: ${U.duration}ms for ${W.name}`);V.metrics=U}return V}catch(V){let U=Date.now()-E;throw Ne.error(`Configuration loading failed after ${U}ms:`,[V instanceof Error?V:Error(String(V))]),V}}async loadConfigurationStrategies(C,E=!1,P){let{name:x="",alias:M,cwd:K,configDir:W,defaultConfig:V,checkEnv:U=!0,arrayStrategy:z="replace",verbose:G=!1}=C,J=K||Ve.cwd(),q=[],Y=await this.loadLocalConfiguration(x,M,J,W,V,z,G,U,P);if(Y)return q.push(...this.getLocalSearchPaths(x,M,J,W)),this.finalizeResult(Y,q,U,x,G);let ee=await this.loadHomeConfiguration(x,M,V,z,G,U);if(ee)return q.push(...this.getHomeSearchPaths(x,M)),this.finalizeResult(ee,q,U,x,G);let H=await this.loadPackageJsonConfiguration(x,M,J,V,z,G,U);if(H)return q.push(ke(J,"package.json")),this.finalizeResult(H,q,U,x,G);if(q.push(...this.getAllSearchPaths(x,M,J,W)),E)throw We.configNotFound(x,q,M);return{...await this.applyEnvironmentVariables(x,V,U,G),warnings:[`No configuration file found for "${x}"${M?` or alias "${M}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(C,E,P,x,M,K,W,V,U){let z=V?nt(C,M,W):M,G=this.getLocalDirectories(P,x);for(let J of G){if(W)Ne.info(`Searching for configuration in: ${J}`);let q=this.fileLoader.generateConfigPaths(C,J,E),Y=await this.fileLoader.tryLoadFromPaths(q,z,{arrayStrategy:K,verbose:W,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(Y){if(W)Ne.success(`Configuration loaded from: ${Y.source.path}`);return Y}}return null}async loadHomeConfiguration(C,E,P,x,M,K){if(!C)return null;let W=K?nt(C,P,M):P,V=[ke(ze(),".config",C),ke(ze(),".config"),ze()];for(let U of V){if(M)Ne.info(`Checking home directory: ${U}`);let z=this.fileLoader.generateConfigPaths(C,U,E),G=await this.fileLoader.tryLoadFromPaths(z,W,{arrayStrategy:x,verbose:M});if(G){if(M)Ne.success(`Configuration loaded from home directory: ${G.source.path}`);return G}}return null}async loadPackageJsonConfiguration(C,E,P,x,M,K,W){let V=W?nt(C,x,K):x;try{let U=ke(P,"package.json");if(!dr(U))return null;let z=await import(U),G=z[C],J=C;if(!G&&E)G=z[E],J=E;if(G&&typeof G==="object"&&!Array.isArray(G)){if(K)Ne.success(`Configuration loaded from package.json: ${J}`);return{config:Nr(V,G,M),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(K)Ne.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables(C,E,P,x){if(!P||!C||typeof E!=="object"||E===null||Array.isArray(E))return{config:E,source:{type:"default",priority:10,timestamp:new Date}};return{config:nt(C,E,x),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(C,E,P,x,M){return{config:C.config,source:C.source,path:C.source.path}}async validateConfiguration(C,E,P,x){let M=[];if(P){let K=P(C);if(K)M.push(...K)}if(E){let K=await this.validator.validateConfiguration(C,E);if(!K.isValid)M.push(...K.errors.map((W)=>W.path?`${W.path}: ${W.message}`:W.message))}if(M.length>0)throw We.configValidation(x||"unknown",M,x)}checkCache(C,E){let P=this.generateCacheKey(C,E);return tt.get(P)||null}cacheResult(C,E,P,x){let M=this.generateCacheKey(C,x);tt.set(M,E,void 0,P.ttl)}generateCacheKey(C,E){let P=[C];if(E.alias)P.push(`alias:${E.alias}`);if(E.cwd)P.push(`cwd:${E.cwd}`);if(E.configDir)P.push(`configDir:${E.configDir}`);if("checkEnv"in E)P.push(`checkEnv:${E.checkEnv}`);return P.join("|")}getLocalDirectories(C,E){return Array.from(new Set([C,ke(C,"config"),ke(C,".config"),E?ke(C,E):void 0].filter(Boolean)))}getAllSearchPaths(C,E,P,x){let M=[];return M.push(...this.getLocalSearchPaths(C,E,P,x)),M.push(...this.getHomeSearchPaths(C,E)),M.push(ke(P,"package.json")),M}getLocalSearchPaths(C,E,P,x){let M=this.getLocalDirectories(P,x),K=[];for(let W of M)K.push(...this.fileLoader.generateConfigPaths(C,W,E));return K}getHomeSearchPaths(C,E){if(!C)return[];let P=[ke(ze(),".config",C),ke(ze(),".config"),ze()],x=[];for(let M of P)x.push(...this.fileLoader.generateConfigPaths(C,M,E));return x}async loadConfigWithResult(C){return this.loadConfig(C)}}function bn(C){let P=!(C.message.includes("EACCES")||C.message.includes("EPERM")||C.message.includes("permission denied"))&&(C.message.includes("syntax")||C.message.includes("Expected")||C.message.includes("Unexpected")||C.message.includes("BuildMessage")),x=C.message.includes("Configuration must export a valid object")||C.message.includes("Configuration file is empty and exports nothing");return P||x}async function Vi(C){return Be.loadConfig({...C,__strictErrorHandling:!0})}async function Un(C){let E="defaultConfig"in C&&C.defaultConfig!==void 0?C.defaultConfig:{},P="cache"in C||"performance"in C||"schema"in C||"validate"in C;try{let x;if(P)x=await Be.loadConfig(C);else x=await Be.loadConfig({...C,defaultConfig:E,cache:{enabled:!0},performance:{enabled:!1}});return x?.config??E}catch(x){let M=x instanceof Error?x.name:"UnknownError",K=x instanceof Error?x.message:String(x);if(!(M==="ConfigNotFoundError"||M==="ConfigLoadError"||M==="ConfigValidationError"||K.includes("config"))&&C.verbose)Ne.warn("Unexpected error loading config, using defaults:",[x instanceof Error?x:Error(String(x))]);let V=P?{...C,defaultConfig:E}:{...C,defaultConfig:E,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in C?C.checkEnv!==!1:!0)return(await Be.applyEnvironmentVariables(V.name||"",E,!0,V.verbose||!1))?.config??E;return E}}async function Ui(C={defaultConfig:{}}){if(typeof C==="string"){let{cwd:E}=await import("process");try{return(await Be.loadConfig({name:C,cwd:E(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(P){if(P instanceof Error&&(P.name==="ConfigNotFoundError"||P.name==="ConfigLoadError"&&bn(P)))return(await Be.applyEnvironmentVariables(C,{},!0,!1)).config;throw P}}try{return(await Be.loadConfig({...C,cwd:C.cwd||Ve.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(E){if(E instanceof Error&&(E.name==="ConfigNotFoundError"||E.name==="ConfigLoadError"&&bn(E)))return(await Be.applyEnvironmentVariables(C.name||"",C.defaultConfig||{},C.checkEnv!==!1,C.verbose||!1)).config;throw E}}async function zi(C,E,P="replace"){let x=new zt;try{let M=await x.loadFromPath(C,E,{arrayStrategy:P,useCache:!1,trackPerformance:!1});return M?M.config:null}catch{return null}}function nt(C,E,P=!1){let x=new Ut,M=C.toUpperCase().replace(/[^A-Z0-9]/g,"_");function K(W,V=[]){let U={...W};for(let[z,G]of Object.entries(W)){let J=[...V,z],q=[`${M}_${J.join("_").toUpperCase()}`,`${M}_${J.map((H)=>H.toUpperCase()).join("")}`,`${M}_${J.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],Y,ee;for(let H of q)if(Y=Ve.env[H],Y!==void 0){ee=H;break}if(Y!==void 0&&ee)if(typeof G==="boolean")U[z]=["true","1","yes"].includes(Y.toLowerCase());else if(typeof G==="number"){let H=Number(Y);if(!Number.isNaN(H))U[z]=H}else if(Array.isArray(G))try{U[z]=JSON.parse(Y)}catch{U[z]=Y.split(",").map((H)=>H.trim())}else U[z]=Y;else if(G&&typeof G==="object"&&!Array.isArray(G))U[z]=K(G,J)}return U}return K(E)}function Gi(C){let E=ke(Ve.cwd(),C.configDir),P=ke(Ve.cwd(),C.generatedDir),x=ke(P,"config-types.ts");if(!dr(Yr(x)))Ms(Yr(x),{recursive:!0,mode:511});let M=dr(E)?Ds(E).map((W)=>W.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],K=`// Generated by bunfig v${Co}
32
- export type ConfigNames = ${M.length?`'${M.join("' | '")}'`:"string"}
33
- `;Ls(x,K,{mode:438})}function Ji(C){let E=null,P=null,x=()=>{if(!P)P=Un(C).then((K)=>(E=K,K),(K)=>{let W="defaultConfig"in C?C.defaultConfig:{};if(E=W,"verbose"in C&&C.verbose)Ne.warn("Config loading failed, using defaults:",[K instanceof Error?K:Error(String(K))]);return W});return P},M="defaultConfig"in C?C.defaultConfig:{};return E=M,x(),new Proxy({},{get(K,W){if(E)return E[W];let V=M[W];return x(),V},has(K,W){return W in(E||M)},ownKeys(){return Object.keys(E||M)},getOwnPropertyDescriptor(K,W){return Object.getOwnPropertyDescriptor(E||M,W)},set(K,W,V){if(!E)E={...M};return E[W]=V,!0}})}function qi(C){let E=un(oi.cwd(),C?.configDir||"./config");function P(){if(!si(E))return[];let M=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),K=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],W=ii(E).filter((U)=>M.has(sr(U))).map((U)=>({base:U.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:U})),V=new Map;for(let{base:U,file:z}of W){let G=sr(z).toLowerCase(),J=V.get(U);if(!J){V.set(U,z);continue}let q=sr(J).toLowerCase();if(K.indexOf(G)<K.indexOf(q))V.set(U,z)}return Array.from(V.entries()).map(([U,z])=>({base:U,file:z})).sort((U,z)=>U.base.localeCompare(z.base))}function x(){let M=P(),K=M.map((z)=>z.base),W=K.length?K.map((z)=>`'${z}'`).join(" | "):"string",V=M.length?`{
34
- ${M.map((z)=>{let G=un(E,z.file).replace(/\\/g,"/");return` '${z.base}': typeof import('${G}').default`}).join(`,
35
- `)}
36
- }`:"Record<string, any>";return`export type ConfigNames = ${W}
37
- export type ConfigByName = ${V}
38
- export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
- export type ConfigOf = Config
40
- `}return{name:"bunfig-plugin",setup(M){M.onResolve({filter:/^virtual:bunfig-types$/},(K)=>({path:K.path,namespace:"bunfig-virtual"})),M.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:x(),loader:"ts"}))}}}var zn,tt,at,Gn,Yi,Hi,vn,kt,wr,ve,le,Zi,$n,Xi,Cn,Qi,eo,cr,to,En,xn,lr,ro,no,so,io,St,Jn,oo,$e,ao,co,kn,Tt,br,de,ne,lo,Sn,fo,Tn,uo,go,fr,mo,An,On,ho,ur,po,yo,wo,bo,vo,At,qn,$o,Co="0.15.6",Ae,jt,it,vr,$r,_t,Cr,Er,ot,xr,kr,We,Yn,Hn,Ne,Be,Zn,Xn,Eo=Ci(async()=>{zn=import.meta.require,tt=new Ar,at=new Or,Gn={createKey:Ei,isEquivalent:xi,estimateMemoryUsage:ki},Yi=Nt(pr.cwd(),"config"),Hi=Nt(pr.cwd(),"src/generated"),vn=Ft.env.CLARITY_LOG_DIR||_s(Ai(),"logs"),kt={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:vn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},wr=await Oi(),ve={red:(C)=>`\x1B[31m${C}\x1B[0m`,green:(C)=>`\x1B[32m${C}\x1B[0m`,yellow:(C)=>`\x1B[33m${C}\x1B[0m`,blue:(C)=>`\x1B[34m${C}\x1B[0m`,magenta:(C)=>`\x1B[35m${C}\x1B[0m`,cyan:(C)=>`\x1B[36m${C}\x1B[0m`,white:(C)=>`\x1B[37m${C}\x1B[0m`,gray:(C)=>`\x1B[90m${C}\x1B[0m`,bgRed:(C)=>`\x1B[41m${C}\x1B[0m`,bgYellow:(C)=>`\x1B[43m${C}\x1B[0m`,bold:(C)=>`\x1B[1m${C}\x1B[0m`,dim:(C)=>`\x1B[2m${C}\x1B[0m`,italic:(C)=>`\x1B[3m${C}\x1B[0m`,underline:(C)=>`\x1B[4m${C}\x1B[0m`,reset:"\x1B[0m"},le=ve,Zi=ve.red,$n=ve.green,Xi=ve.yellow,Cn=ve.blue,Qi=ve.magenta,eo=ve.cyan,cr=ve.white,to=ve.gray,En=ve.bgRed,xn=ve.bgYellow,lr=ve.bold,ro=ve.dim,no=ve.italic,so=ve.underline,io=ve.reset,St={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Jn={debug:"\uD83D\uDD0D",info:Cn("\u2139"),success:$n("\u2713"),warning:xn(cr(lr(" WARN "))),error:En(cr(lr(" ERROR ")))},oo=new Dt("stacks"),$e=new Dt("bunfig",{showTags:!0}),ao=xe(st.cwd(),"config"),co=xe(st.cwd(),"src/generated"),kn=Rt.env.CLARITY_LOG_DIR||Is(Pi(),"logs"),Tt={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:kn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},br=await Mi(),de={red:(C)=>`\x1B[31m${C}\x1B[0m`,green:(C)=>`\x1B[32m${C}\x1B[0m`,yellow:(C)=>`\x1B[33m${C}\x1B[0m`,blue:(C)=>`\x1B[34m${C}\x1B[0m`,magenta:(C)=>`\x1B[35m${C}\x1B[0m`,cyan:(C)=>`\x1B[36m${C}\x1B[0m`,white:(C)=>`\x1B[37m${C}\x1B[0m`,gray:(C)=>`\x1B[90m${C}\x1B[0m`,bgRed:(C)=>`\x1B[41m${C}\x1B[0m`,bgYellow:(C)=>`\x1B[43m${C}\x1B[0m`,bgGray:(C)=>`\x1B[100m${C}\x1B[0m`,bold:(C)=>`\x1B[1m${C}\x1B[0m`,dim:(C)=>`\x1B[2m${C}\x1B[0m`,italic:(C)=>`\x1B[3m${C}\x1B[0m`,underline:(C)=>`\x1B[4m${C}\x1B[0m`,strikethrough:(C)=>`\x1B[9m${C}\x1B[0m`,reset:"\x1B[0m"},ne=de,lo=de.red,Sn=de.green,fo=de.yellow,Tn=de.blue,uo=de.magenta,go=de.cyan,fr=de.white,mo=de.gray,An=de.bgRed,On=de.bgYellow,ho=de.bgGray,ur=de.bold,po=de.dim,yo=de.italic,wo=de.underline,bo=de.strikethrough,vo=de.reset,At={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},qn={debug:"\uD83D\uDD0D",info:Tn("\u2139"),success:Sn("\u2713"),warning:On(fr(ur(" WARN "))),error:An(fr(ur(" ERROR ")))},$o=new It("stacks"),Ae=class extends Error{timestamp;context;constructor(E,P={}){super(E);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=P,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let E=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([P,x])=>`${P}: ${x}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${E}`}},jt=class extends Ae{code="CONFIG_NOT_FOUND";constructor(E,P,x){let M=x?` or alias "${x}"`:"";super(`Configuration "${E}"${M} not found`,{configName:E,alias:x,searchPaths:P,searchPathCount:P.length})}},it=class extends Ae{code="CONFIG_LOAD_ERROR";constructor(E,P,x){super(`Failed to load configuration from "${E}": ${P.message}`,{configPath:E,configName:x,originalError:P.name,originalMessage:P.message});this.cause=P}},vr=class extends Ae{code="CONFIG_VALIDATION_ERROR";constructor(E,P,x){super(`Configuration validation failed for "${E}"`,{configPath:E,configName:x,validationErrors:P,errorCount:P.length})}},$r=class extends Ae{code="CONFIG_MERGE_ERROR";constructor(E,P,x,M){super(`Failed to merge configuration from "${E}" with "${P}": ${x.message}`,{sourcePath:E,targetPath:P,configName:M,originalError:x.name,originalMessage:x.message});this.cause=x}},_t=class extends Ae{code="ENV_VAR_ERROR";constructor(E,P,x,M){super(`Failed to parse environment variable "${E}" with value "${P}" as ${x}`,{envKey:E,envValue:P,expectedType:x,configName:M})}},Cr=class extends Ae{code="FILE_SYSTEM_ERROR";constructor(E,P,x){super(`File system ${E} failed for "${P}": ${x.message}`,{operation:E,path:P,originalError:x.name,originalMessage:x.message});this.cause=x}},Er=class extends Ae{code="TYPE_GENERATION_ERROR";constructor(E,P,x){super(`Failed to generate types from "${E}" to "${P}": ${x.message}`,{configDir:E,outputPath:P,originalError:x.name,originalMessage:x.message});this.cause=x}},ot=class extends Ae{code="SCHEMA_VALIDATION_ERROR";constructor(E,P,x){super(`Schema validation failed${x?` for config "${x}"`:""}`,{schemaPath:E,configName:x,validationErrors:P,errorCount:P.length})}},xr=class extends Ae{code="BROWSER_CONFIG_ERROR";constructor(E,P,x,M){super(`Failed to fetch configuration from "${E}": ${P} ${x}`,{endpoint:E,status:P,statusText:x,configName:M})}},kr=class extends Ae{code="PLUGIN_ERROR";constructor(E,P,x){super(`Plugin "${E}" failed during ${P}: ${x.message}`,{pluginName:E,operation:P,originalError:x.name,originalMessage:x.message});this.cause=x}},We={configNotFound(C,E,P){return new jt(C,E,P)},configLoad(C,E,P){return new it(C,E,P)},configValidation(C,E,P){return new vr(C,E,P)},configMerge(C,E,P,x){return new $r(C,E,P,x)},envVar(C,E,P,x){return new _t(C,E,P,x)},fileSystem(C,E,P){return new Cr(C,E,P)},typeGeneration(C,E,P){return new Er(C,E,P)},schemaValidation(C,E,P){return new ot(C,E,P)},browserConfig(C,E,P,x){return new xr(C,E,P,x)},plugin(C,E,P){return new kr(C,E,P)}},Yn={replace:"replace",concat:"concat",smart:"smart"},Hn=/^https?:\/\//,Ne=new It("bunfig",{showTags:!0}),Be=new Mr,Zn=ke(Ve.cwd(),"config"),Xn=ke(Ve.cwd(),"src/generated")});function xo(C,E={}){let P=Pt.cwd();while(P.includes("storage"))P=gn(P,"..");let x=gn(P,C||"");if(E?.relative)return ci(Pt.cwd(),x);return x}var ko=Pt.env.CLARITY_LOG_DIR||ai(xo(),"logs"),Qn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ko,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Bt={...Qn},wl=(async()=>{try{let{loadConfig:C}=await Eo().then(()=>Ln),E=await C({name:"clarity",alias:"logging",defaultConfig:Qn,cwd:Pt.cwd()});if(E)Object.assign(Bt,E)}catch{}return Bt})();function pe(){if(_e.env.NODE_ENV==="test"||_e.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function So(){if(_e.env.NODE_ENV==="test"||_e.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof _e<"u"){let C=_e.type;if(C==="renderer"||C==="worker")return!1;return!!(_e.versions&&(_e.versions.node||_e.versions.bun))}return!1}class es{async format(C){let E=await So(),P=await this.getMetadata(E);return JSON.stringify({timestamp:C.timestamp.toISOString(),level:C.level,name:C.name,message:C.message,metadata:P})}async getMetadata(C){if(C){let{hostname:E}=await import("os");return{pid:et.pid,hostname:E(),environment:et.env.NODE_ENV||"development",platform:et.platform,version:et.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:et.env.NODE_ENV||et.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ye={red:(C)=>`\x1B[31m${C}\x1B[0m`,green:(C)=>`\x1B[32m${C}\x1B[0m`,yellow:(C)=>`\x1B[33m${C}\x1B[0m`,blue:(C)=>`\x1B[34m${C}\x1B[0m`,magenta:(C)=>`\x1B[35m${C}\x1B[0m`,cyan:(C)=>`\x1B[36m${C}\x1B[0m`,white:(C)=>`\x1B[37m${C}\x1B[0m`,gray:(C)=>`\x1B[90m${C}\x1B[0m`,bgRed:(C)=>`\x1B[41m${C}\x1B[0m`,bgYellow:(C)=>`\x1B[43m${C}\x1B[0m`,bgGray:(C)=>`\x1B[100m${C}\x1B[0m`,bold:(C)=>`\x1B[1m${C}\x1B[0m`,dim:(C)=>`\x1B[2m${C}\x1B[0m`,italic:(C)=>`\x1B[3m${C}\x1B[0m`,underline:(C)=>`\x1B[4m${C}\x1B[0m`,strikethrough:(C)=>`\x1B[9m${C}\x1B[0m`,reset:"\x1B[0m"},se=ye,{red:bl,green:To,yellow:vl,blue:Ao,magenta:$l,cyan:Cl,white:Rn,gray:El,bgRed:Oo,bgYellow:Ro,bgGray:xl,bold:Fn,dim:kl,italic:Sl,underline:Tl,strikethrough:Al,reset:Ol}=ye,gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Fo={debug:"\uD83D\uDD0D",info:Ao("\u2139"),success:To("\u2713"),warning:Ro(Rn(Fn(" WARN "))),error:Oo(Rn(Fn(" ERROR ")))};class Gt{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(C,E={}){this.name=C,this.config={...Bt},this.options=this.normalizeOptions(E),this.formatter=this.options.formatter||new es,this.enabled=E.enabled??!0,this.fancy=E.fancy??!0,this.tagFormat=E.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=E.timestampPosition??"right",this.environment=E.environment??oe.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(E);let P={...E},x=E.timestamp!==void 0;if(x)delete P.timestamp;if(this.config={...this.config,...P,timestamp:x||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let M=this.generateKeyId(),K=this.generateKey();this.currentKeyId=M,this.keys.set(M,K),this.encryptionKeys.set(M,{key:K,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(C){if(!this.fingersCrossedConfig)return!1;let E={debug:0,info:1,success:2,warning:3,error:4},P=this.fingersCrossedConfig.activationLevel??"error";return E[C]>=E[P]}initializeFingersCrossedConfig(C){if(!C.fingersCrossedEnabled&&C.fingersCrossed)return{...gr,...C.fingersCrossed};if(!C.fingersCrossedEnabled)return null;if(!C.fingersCrossed)return{...gr};return{...gr,...C.fingersCrossed}}normalizeOptions(C){let E={format:"json",level:"info",logDirectory:Bt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},P={...E,...Object.fromEntries(Object.entries(C).filter(([,x])=>x!==void 0))};if(!P.level||!["debug","info","success","warning","error"].includes(P.level))P.level=E.level;return P}shouldWriteToFile(){return!pe()&&this.config.writeToFile===!0}async writeToFile(C){let P=(async()=>{let M,K=0,W=3,V=1000;while(K<W)try{try{try{await mi(this.config.logDirectory,pn.F_OK|pn.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await hi(this.config.logDirectory,{recursive:!0,mode:493});else if(z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw z;else throw z}}catch(z){throw console.error("Debug: [writeToFile] Failed to create log directory:",z),z}let U=this.validateEncryptionConfig()?(await this.encrypt(C)).encrypted:Le.from(C);try{if(!yt(this.currentLogFile))await ar(this.currentLogFile,"",{mode:420});if(M=dn(this.currentLogFile,"a",420),gi(M,U,{flag:"a"}),hn(M),M!==void 0)or(M),M=void 0;if((await Xe(this.currentLogFile)).size===0){if(await ar(this.currentLogFile,U,{flag:"w",mode:420}),(await Xe(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let G=z;if(G.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(G.code)){if(K<W-1){let J=typeof G.message==="string"?G.message:"Unknown error";console.error(`Network error during write attempt ${K+1}/${W}:`,J);let q=V*2**K;await new Promise((Y)=>setTimeout(Y,q)),K++;continue}}if(G?.code&&["ENOSPC","EDQUOT"].includes(G.code))throw Error(`Disk quota exceeded or no space left on device: ${G.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",G),G}finally{if(M!==void 0)try{or(M)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(U){if(K===W-1){let G=U,J=typeof G.message==="string"?G.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",J),U}K++;let z=V*2**(K-1);await new Promise((G)=>setTimeout(G,z))}})();this.pendingOperations.push(P);let x=this.pendingOperations.length-1;try{await P}catch(M){throw console.error("Debug: [writeToFile] Error in operation:",M),M}finally{this.pendingOperations.splice(x,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 Qe(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 Qe(this.config.logDirectory,`${this.name}.log`);let C=new Date().toISOString().split("T")[0];return Qe(this.config.logDirectory,`${this.name}-${C}.log`)}setupRotation(){if(pe())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let C=this.config.rotation,E;switch(C.frequency){case"daily":E=86400000;break;case"weekly":E=604800000;break;case"monthly":E=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},E)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let E=this.config.rotation.keyRotation;if(!E?.enabled)return;let P=typeof E.interval==="number"?E.interval:60,x=Math.max(P,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((M)=>{console.error("Error rotating keys:",M)})},x)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let E=this.config.rotation.keyRotation,P=this.generateKeyId(),x=this.generateKey();this.currentKeyId=P,this.keys.set(P,x),this.encryptionKeys.set(P,{key:x,createdAt:new Date});let M=Array.from(this.encryptionKeys.entries()).sort(([,V],[,U])=>U.createdAt.getTime()-V.createdAt.getTime()),K=typeof E.maxKeys==="number"?E.maxKeys:1,W=Math.max(1,K);if(M.length>W)for(let[V]of M.slice(W))this.encryptionKeys.delete(V),this.keys.delete(V)}generateKeyId(){return ir(16).toString("hex")}generateKey(){return ir(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let C=this.keys.get(this.currentKeyId);if(!C)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:C,id:this.currentKeyId}}encrypt(C){let{key:E}=this.getCurrentKey(),P=ir(16),x=li("aes-256-gcm",E,P),M=Le.isBuffer(C)?C:Le.from(C,"utf8"),K=x.update(M),W=x.final(),V=K.length+W.length,U=x.getAuthTag(),z=Le.allocUnsafe(16+V+16);return P.copy(z,0),K.copy(z,16),W.copy(z,16+K.length),U.copy(z,16+V),{encrypted:z,iv:P}}async compressData(C){return new Promise((E,P)=>{let x=wn(),M=[];x.on("data",(K)=>M.push(K)),x.on("end",()=>E(Le.from(Le.concat(M)))),x.on("error",P),x.write(C),x.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let C={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let E=this.config.rotation.encrypt;return{...C,...E}}return C}async rotateLog(){if(pe())return;if(!this.shouldWriteToFile())return;let C=await Xe(this.currentLogFile).catch(()=>null);if(!C)return;let E=this.config.rotation;if(typeof E==="boolean")return;if(E.maxSize&&C.size>=E.maxSize){let P=this.currentLogFile,x=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let M=await wt(this.config.logDirectory),K=M.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,z)=>{let G=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-G}),W=K.length>0?Number.parseInt(K[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,V=`${P}.${W}`;if(await Xe(P).catch(()=>null))try{if(await yn(P,V),E.compress)try{let U=`${V}.gz`;await this.compressLogFile(V,U),await bt(V)}catch(U){console.error("Error compressing rotated file:",U)}if(K.length===0&&!M.some((U)=>U.endsWith(".log.1")))try{let U=`${P}.1`;await ar(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let M=new Date().toISOString().replace(/[:.]/g,"-"),K=P.replace(/\.log$/,`-${M}.log`);if(await Xe(P).catch(()=>null))await yn(P,K)}if(this.currentLogFile=x,E.maxFiles){let K=(await wt(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,V)=>V.localeCompare(W));for(let W of K.slice(E.maxFiles))await bt(Qe(this.config.logDirectory,W))}}}async compressLogFile(C,E){let P=mn(C),x=ui(E),M=wn();await yi(P,M,x)}async handleFingersCrossedBuffer(C,E){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(C)&&!this.isActivated){this.isActivated=!0;for(let P of this.logBuffer){let x=await this.formatter.format(P);if(this.shouldWriteToFile())await this.writeToFile(x);console.log(x)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(E);console.log(E)}}shouldLog(C){if(!this.enabled)return!1;let E={debug:0,info:1,success:2,warning:3,error:4};return E[C]>=E[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((C)=>{if(C instanceof Promise)return C.catch((E)=>{console.error("Error in pending write operation:",E)});return Promise.resolve()})),yt(this.currentLogFile))try{let C=dn(this.currentLogFile,"r+");hn(C),or(C)}catch(C){console.error(`Error flushing file: ${C}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let C of this.pendingOperations)if(typeof C.cancel==="function")C.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(C){console.error("Error waiting for pending operations:",C)}if(!pe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let E=(await wt(this.config.logDirectory)).filter((P)=>(P.includes("temp")||P.includes(".tmp"))&&P.includes(this.name));for(let P of E)try{await bt(Qe(this.config.logDirectory,P))}catch(x){console.error(`Failed to delete temp file ${P}:`,x)}}catch(C){console.error("Error cleaning up temporary files:",C)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(C){if(!C)return"";return`${this.tagFormat.prefix}${C}${this.tagFormat.suffix}`}formatFileTimestamp(C){return`[${C.toISOString()}]`}formatConsoleTimestamp(C){return this.shouldStyleConsole()?se.gray(C.toLocaleTimeString()):C.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||pe())return!1;let C=typeof oe.env.NO_COLOR<"u",E=oe.env.FORCE_COLOR==="0";if(C||E)return!1;return!!(typeof oe.stderr<"u"&&oe.stderr.isTTY||typeof oe.stdout<"u"&&oe.stdout.isTTY)}formatConsoleMessage(C){let{timestamp:E,icon:P="",tag:x="",message:M,level:K,showTimestamp:W=!0}=C,V=(Y)=>Y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let Y=[];if(W)Y.push(E);if(K==="warning")Y.push("WARN");else if(K==="error")Y.push("ERROR");else if(P)Y.push(P.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(x)Y.push(x.replace(/[[\]]/g,""));return Y.push(M),Y.join(" ")}let U=oe.stdout.columns||120,z="";if(K==="warning"||K==="error")z=`${P} ${M}`;else if(K==="info"||K==="success")z=`${P} ${x} ${M}`;else z=`${P} ${x} ${se.cyan(M)}`;if(!W)return z.trim();let G=V(z).trim().length,J=V(E).length,q=Math.max(1,U-2-G-J);return`${z.trim()}${" ".repeat(q)}${E}`}formatMessage(C,E){if(E.length===1&&Array.isArray(E[0]))return C.replace(/\{(\d+)\}/g,(K,W)=>{let V=Number.parseInt(W,10);return V<E[0].length?String(E[0][V]):K});let P=/%([sdijfo%])/g,x=0,M=C.replace(P,(K,W)=>{if(W==="%")return"%";if(x>=E.length)return K;let V=E[x++];switch(W){case"s":return String(V);case"d":case"i":return Number(V).toString();case"j":case"o":return JSON.stringify(V,null,2);default:return K}});if(x<E.length)M+=` ${E.slice(x).map((K)=>typeof K==="object"?JSON.stringify(K,null,2):String(K)).join(" ")}`;return M}formatMarkdown(C){if(!C)return C;let E=C;return E=E.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(P,x,M)=>{let K=se.underline(se.blue(x)),W=this.toAbsoluteFilePath(M);if(W&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let V=`file://${encodeURI(W)}`,U="\x1B]8;;",z="\x1B\\";return`\x1B]8;;${V}\x1B\\${K}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${M}\x1B\\${K}\x1B]8;;\x1B\\`;return K}),E=E.replace(/`([^`]+)`/g,(P,x)=>se.bgGray(x)),E=E.replace(/\*\*([^*]+)\*\*/g,(P,x)=>se.bold(x)),E=E.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(P,x)=>se.italic(x)),E=E.replace(/(?<!_)_([^_]+)_(?!_)/g,(P,x)=>se.italic(x)),E=E.replace(/~([^~]+)~/g,(P,x)=>se.strikethrough(x)),E}supportsHyperlinks(){if(pe())return!1;let C=oe.env;if(!C)return!1;if(C.TERM_PROGRAM==="iTerm.app"||C.TERM_PROGRAM==="vscode"||C.TERM_PROGRAM==="WezTerm")return!0;if(C.WT_SESSION)return!0;if(C.TERM==="xterm-kitty")return!0;let E=C.VTE_VERSION?Number.parseInt(C.VTE_VERSION,10):0;if(!Number.isNaN(E)&&E>=5000)return!0;return!1}toAbsoluteFilePath(C){try{let E=C;if(E.startsWith("file://"))E=E.replace(/^file:\/\//,"");if(E.startsWith("~")){let P=oe.env.HOME||"";if(P)E=E.replace(/^~(?=$|\/)/,P)}if(di(E)||E.startsWith("./")||E.startsWith("../"))E=pi(E);else return null;return yt(E)?E:null}catch{return null}}buildOutputTexts(C){let E=this.shouldStyleConsole()?this.formatMarkdown(C):C,P=C.replace(this.ANSI_PATTERN,"");return{consoleText:E,fileText:P}}async log(C,E,...P){if(!this.shouldLog(C))return;let x=new Date,M=this.formatConsoleTimestamp(x),K=this.formatFileTimestamp(x),W,V;if(E instanceof Error)W=E.message,V=E.stack;else W=this.formatMessage(E,P);let{consoleText:U,fileText:z}=this.buildOutputTexts(W);if(this.shouldStyleConsole()){let J=this.options.showIcons===!1?"":Fo[C],q=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",Y;switch(C){case"debug":Y=this.formatConsoleMessage({timestamp:M,icon:J,tag:q,message:se.gray(U),level:C}),console.error(Y);break;case"info":Y=this.formatConsoleMessage({timestamp:M,icon:J,tag:q,message:U,level:C}),console.warn(Y);break;case"success":Y=this.formatConsoleMessage({timestamp:M,icon:J,tag:q,message:se.green(U),level:C}),console.error(Y);break;case"warning":Y=this.formatConsoleMessage({timestamp:M,icon:J,tag:q,message:U,level:C}),console.warn(Y);break;case"error":if(Y=this.formatConsoleMessage({timestamp:M,icon:J,tag:q,message:U,level:C}),console.error(Y),V){let ee=V.split(`
41
- `);for(let H of ee)if(H.trim()&&!H.includes(W))console.error(this.formatConsoleMessage({timestamp:M,message:se.gray(` ${H}`),level:C,showTimestamp:!1}))}break}}else if(!pe()){if(console.error(`${K} ${this.environment}.${C.toUpperCase()}: ${W}`),V)console.error(V)}let G=`${K} ${this.environment}.${C.toUpperCase()}: ${z}
42
- `;if(V)G+=`${V}
43
- `;if(G=G.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(G)}progress(C,E=""){let P={update:(V,U)=>{},finish:(V)=>{},interrupt:(V,U)=>{}};if(!this.enabled)return P;let x=30;if(this.activeProgressBar={total:Math.max(1,C||1),current:0,message:E||"",barLength:x,lastRenderedLine:""},this.shouldStyleConsole()&&!pe()&&oe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(V,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,V),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!pe()&&oe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(V)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,V)},interrupt:(V,U="info")=>{if(!pe()&&oe.stdout.isTTY)oe.stdout.write(`
44
- `);if(this[U==="warning"?"warn":U](V),this.activeProgressBar&&this.shouldStyleConsole()&&!pe()&&oe.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(C){let E=performance.now();if(this.shouldStyleConsole()){let P=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",x=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:x,icon:this.options.showIcons===!1?"":se.blue("\u25D0"),tag:P,message:`${se.cyan(C)}...`}))}return async(P)=>{if(!this.enabled)return;let x=performance.now(),M=Math.round(x-E),K=`${C} completed in ${M}ms`,W=new Date,V=this.formatConsoleTimestamp(W),z=`${this.formatFileTimestamp(W)} ${this.environment}.INFO: ${K}`;if(P)z+=` ${JSON.stringify(P)}`;if(z+=`
45
- `,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let G=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:V,icon:this.options.showIcons===!1?"":se.green("\u2713"),tag:G,message:`${K}${P?` ${JSON.stringify(P)}`:""}`}))}else if(!pe())console.error(z.trim());if(this.shouldWriteToFile())await this.writeToFile(z)}}async debug(C,...E){await this.log("debug",C,...E)}async info(C,...E){await this.log("info",C,...E)}async success(C,...E){await this.log("success",C,...E)}async warn(C,...E){await this.log("warning",C,...E)}async error(C,...E){await this.log("error",C,...E)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let C=this.config.rotation,{encrypt:E}=C;return!!E}async only(C){if(!this.enabled)return;return await C()}isEnabled(){return this.enabled}setEnabled(C){this.enabled=C}extend(C){let E=`${this.name}:${C}`,P=new Gt(E,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(P),P}createReadStream(){if(pe())throw Error("createReadStream is not supported in browser environments");if(!yt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return mn(this.currentLogFile,{encoding:"utf8"})}async decrypt(C){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let E=this.config.rotation;if(!E.encrypt||typeof E.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let P=this.keys.get(this.currentKeyId);try{let x=Le.isBuffer(C)?C:Le.from(C,"base64"),M=x.subarray(0,16),K=x.subarray(x.length-16),W=x.subarray(16,x.length-16),V=fi("aes-256-gcm",P,M);V.setAuthTag(K);let U=V.update(W),z=V.final(),G=U.length+z.length,J=Le.allocUnsafe(G);return U.copy(J,0),z.copy(J,U.length),J.toString("utf8")}catch(x){throw Error(`Decryption failed: ${x instanceof Error?x.message:String(x)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return pe()}isServerMode(){return!pe()}setTestEncryptionKey(C,E){this.currentKeyId=C,this.keys.set(C,E)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(C){if(!this.enabled)return;let E=new Date,P=this.formatConsoleTimestamp(E),x=this.formatFileTimestamp(E),{consoleText:M,fileText:K}=this.buildOutputTexts(C);if(this.shouldStyleConsole()){let V=M.split(`
46
- `),U=Math.max(...V.map((q)=>q.length))+2,z=`\u250C${"\u2500".repeat(U)}\u2510`,G=`\u2514${"\u2500".repeat(U)}\u2518`,J=V.map((q)=>this.formatConsoleMessage({timestamp:P,message:se.cyan(q),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:P,message:se.cyan(z),showTimestamp:!1})),J.forEach((q)=>console.error(q)),console.error(this.formatConsoleMessage({timestamp:P,message:se.cyan(G),showTimestamp:!1}))}else if(!pe())console.error(`${x} ${this.environment}.INFO: [BOX] ${K}`);let W=`${x} ${this.environment}.INFO: [BOX] ${K}
47
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}async prompt(C){if(pe())return Promise.resolve(!0);return new Promise((E)=>{console.error(`${se.cyan("?")} ${C} (y/n) `);let P=(x)=>{let M=x.toString().trim().toLowerCase();oe.stdin.removeListener("data",P);try{if(typeof oe.stdin.setRawMode==="function")oe.stdin.setRawMode(!1)}catch{}oe.stdin.pause(),console.error(""),E(M==="y"||M==="yes")};try{if(typeof oe.stdin.setRawMode==="function")oe.stdin.setRawMode(!0)}catch{}oe.stdin.resume(),oe.stdin.once("data",P)})}setFancy(C){this.fancy=C}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(C,...E){if(!this.enabled)return;let P=C;if(E&&E.length>0){let U=/%([sdijfo%])/g,z=0;if(P=C.replace(U,(G,J)=>{if(J==="%")return"%";if(z>=E.length)return G;let q=E[z++];switch(J){case"s":return String(q);case"d":case"i":return Number(q).toString();case"j":case"o":return JSON.stringify(q,null,2);default:return G}}),z<E.length)P+=` ${E.slice(z).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`}let{consoleText:x,fileText:M}=this.buildOutputTexts(P);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",z=this.options.showIcons===!1?"":`${se.blue("\u25D0")} `;console.error(`${z}${U} ${se.cyan(x)}`)}let V=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${M}
48
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(V)}renderProgressBar(C,E=!1){if(!this.enabled||!this.shouldStyleConsole()||!oe.stdout.isTTY)return;let P=Math.min(100,Math.max(0,Math.round(C.current/C.total*100))),x=Math.round(C.barLength*P/100),M=C.barLength-x,K=se.green("\u2501".repeat(x)),W=se.gray("\u2501".repeat(M)),V=`[${K}${W}]`,U=`${P}%`.padStart(4),z=C.message?` ${C.message}`:"",G=this.options.showIcons===!1?"":E||P===100?se.green("\u2713"):se.blue("\u25B6"),J=this.options.showTags!==!1&&this.name?` ${se.gray(this.formatTag(this.name))}`:"",q=`\r${G}${J} ${V} ${U}${z}`,Y=oe.stdout.columns||80,ee=" ".repeat(Math.max(0,Y-q.replace(this.ANSI_PATTERN,"").length));if(C.lastRenderedLine=`${q}${ee}`,oe.stdout.write(C.lastRenderedLine),E)oe.stdout.write(`
49
- `)}finishProgressBar(C,E){if(!this.enabled||!this.fancy||pe()||!oe.stdout.isTTY){this.activeProgressBar=null;return}if(C.current<C.total)C.current=C.total;if(E)C.message=E;this.renderProgressBar(C,!0),this.activeProgressBar=null}async clear(C={}){if(pe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let E=await wt(this.config.logDirectory),P=[];for(let x of E){if(!(C.name?new RegExp(C.name.replace("*",".*")).test(x):x.startsWith(this.name))||!x.endsWith(".log"))continue;let K=Qe(this.config.logDirectory,x);if(C.before)try{if((await Xe(K)).mtime>=C.before)continue}catch(W){console.error(`Failed to get stats for file ${K}:`,W);continue}P.push(K)}if(P.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${P.length} log file(s)...`);for(let x of P)try{await bt(x),console.warn(`Deleted log file: ${x}`)}catch(M){console.error(`Failed to delete log file ${x}:`,M)}console.warn("Log clearing process finished.")}catch(E){console.error("Error during log clearing process:",E)}}}var Rl=new Gt("stacks");class Pe extends Error{timestamp;context;constructor(C,E={}){super(C);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=E,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 C=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([E,P])=>`${E}: ${P}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${C}`}}class ts extends Pe{code="CONFIG_NOT_FOUND";constructor(C,E,P){let x=P===void 0?[]:Array.isArray(P)?P.filter(Boolean):[P],M="";if(x.length===1)M=` or alias "${x[0]}"`;else if(x.length>1)M=` or aliases ${x.map((K)=>`"${K}"`).join(", ")}`;super(`Configuration "${C}"${M} not found`,{configName:C,alias:P,searchPaths:E,searchPathCount:E.length})}}class Kt extends Pe{code="CONFIG_LOAD_ERROR";constructor(C,E,P){super(`Failed to load configuration from "${C}": ${E.message}`,{configPath:C,configName:P,originalError:E.name,originalMessage:E.message});this.cause=E}}class rs extends Pe{code="CONFIG_VALIDATION_ERROR";constructor(C,E,P){super(`Configuration validation failed for "${C}"`,{configPath:C,configName:P,validationErrors:E,errorCount:E.length})}}class ns extends Pe{code="CONFIG_MERGE_ERROR";constructor(C,E,P,x){super(`Failed to merge configuration from "${C}" with "${E}": ${P.message}`,{sourcePath:C,targetPath:E,configName:x,originalError:P.name,originalMessage:P.message});this.cause=P}}class Dr extends Pe{code="ENV_VAR_ERROR";constructor(C,E,P,x){super(`Failed to parse environment variable "${C}" with value "${E}" as ${P}`,{envKey:C,envValue:E,expectedType:P,configName:x})}}class ss extends Pe{code="FILE_SYSTEM_ERROR";constructor(C,E,P){super(`File system ${C} failed for "${E}": ${P.message}`,{operation:C,path:E,originalError:P.name,originalMessage:P.message});this.cause=P}}class is extends Pe{code="TYPE_GENERATION_ERROR";constructor(C,E,P){super(`Failed to generate types from "${C}" to "${E}": ${P.message}`,{configDir:C,outputPath:E,originalError:P.name,originalMessage:P.message});this.cause=P}}class Wt extends Pe{code="SCHEMA_VALIDATION_ERROR";constructor(C,E,P){super(`Schema validation failed${P?` for config "${P}"`:""}`,{schemaPath:C,configName:P,validationErrors:E,errorCount:E.length})}}class os extends Pe{code="BROWSER_CONFIG_ERROR";constructor(C,E,P,x){super(`Failed to fetch configuration from "${C}": ${E} ${P}`,{endpoint:C,status:E,statusText:P,configName:x})}}class as extends Pe{code="PLUGIN_ERROR";constructor(C,E,P){super(`Plugin "${C}" failed during ${E}: ${P.message}`,{pluginName:C,operation:E,originalError:P.name,originalMessage:P.message});this.cause=P}}var rt={configNotFound(C,E,P){return new ts(C,E,P)},configLoad(C,E,P){return new Kt(C,E,P)},configValidation(C,E,P){return new rs(C,E,P)},configMerge(C,E,P,x){return new ns(C,E,P,x)},envVar(C,E,P,x){return new Dr(C,E,P,x)},fileSystem(C,E,P){return new ss(C,E,P)},typeGeneration(C,E,P){return new is(C,E,P)},schemaValidation(C,E,P){return new Wt(C,E,P)},browserConfig(C,E,P,x){return new os(C,E,P,x)},plugin(C,E,P){return new as(C,E,P)}};async function No(C,E={}){let{maxRetries:P=3,retryDelay:x=1000,isRetryable:M=()=>!0,fallback:K}=E,W=Error("Unknown error occurred");for(let V=0;V<=P;V++)try{return await C()}catch(U){if(W=U instanceof Error?U:Error(String(U)),V===P||!M(W))break;if(x>0)await new Promise((z)=>setTimeout(z,x))}if(K!==void 0)return K;throw W instanceof Error?W:Error(`Unknown error: ${String(W)}`)}class Lr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(C,E)=>E==="boolean"||["true","false","1","0","yes","no"].includes(C.toLowerCase()),parse:(C)=>{let E=C.toLowerCase();return["true","1","yes"].includes(E)}},{name:"number",canParse:(C,E)=>E==="number"||!Number.isNaN(Number(C))&&!Number.isNaN(Number.parseFloat(C)),parse:(C)=>{let E=Number(C);if(Number.isNaN(E))throw TypeError(`Cannot parse "${C}" as number`);return E}},{name:"array",canParse:(C,E)=>E==="array"||C.startsWith("[")||C.includes(","),parse:(C)=>{try{let E=JSON.parse(C);if(Array.isArray(E))return E}catch{}return C.split(",").map((E)=>E.trim())}},{name:"json",canParse:(C,E)=>E==="object"||(C.startsWith("{")&&C.endsWith("}")||C.startsWith("[")&&C.endsWith("]")),parse:(C)=>{try{return JSON.parse(C)}catch(E){throw Error(`Cannot parse "${C}" as JSON: ${E}`)}}}]}async applyEnvironmentVariables(C,E,P={}){let{prefix:x,useCamelCase:M=!0,useBackwardCompatibility:K=!0,customParsers:W={},verbose:V=!1,trackPerformance:U=!0}=P,z=async()=>{if(!C)return{config:E,source:{type:"environment",priority:50,timestamp:new Date}};let G=x||this.generateEnvPrefix(C),J={...E};return this.processObject(J,[],G,{useCamelCase:M,useBackwardCompatibility:K,customParsers:W,verbose:V,configName:C}),{config:J,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return Tr.track("applyEnvironmentVariables",z,{configName:C});return z()}generateEnvPrefix(C){return C.toUpperCase().replace(/-/g,"_")}formatEnvKey(C,E){if(!E)return C.toUpperCase();return C.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(C,E,P,x){for(let[M,K]of Object.entries(C)){let W=[...E,M],V=W.map((G)=>this.formatEnvKey(G,x.useCamelCase)),U=`${P}_${V.join("_")}`,z=x.useBackwardCompatibility?`${P}_${W.map((G)=>G.toUpperCase()).join("_")}`:null;if(x.verbose);if(typeof K==="object"&&K!==null&&!Array.isArray(K))this.processObject(K,W,P,x);else{let G=$t.env[U]||(z?$t.env[z]:void 0);if(G!==void 0){if(x.verbose){let J=$t.env[U]?U:z}try{C[M]=this.parseEnvironmentValue(G,typeof K,U,x.customParsers,x.configName)}catch(J){if(J instanceof Dr)throw J;throw rt.envVar(U,G,typeof K,x.configName)}}}}}parseEnvironmentValue(C,E,P,x,M){for(let[K,W]of Object.entries(x))try{return W(C)}catch{continue}for(let K of this.defaultParsers)if(K.canParse(C,E))try{return K.parse(C)}catch{throw rt.envVar(P,C,`${E} (via ${K.name} parser)`,M)}return C}getEnvironmentVariables(C){let E={},P=C.toUpperCase();for(let[x,M]of Object.entries($t.env))if(x.startsWith(P)&&M!==void 0)E[x]=M;return E}validateEnvironmentVariable(C,E,P){let x=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(C))x.push(`Environment variable key "${C}" should only contain uppercase letters, numbers, and underscores`);if(P)try{this.parseEnvironmentValue(C,E,P,{})}catch(M){x.push(`Cannot parse value "${E}" as ${P}: ${M}`)}return{isValid:x.length===0,errors:x}}generateEnvVarDocs(C,E,P={}){let{prefix:x,format:M="text"}=P,K=x||this.generateEnvPrefix(C),W=[];switch(this.extractEnvVarInfo(E,[],K,W),M){case"markdown":return this.formatAsMarkdown(W,C);case"json":return JSON.stringify(W,null,2);default:return this.formatAsText(W,C)}}extractEnvVarInfo(C,E,P,x){for(let[M,K]of Object.entries(C)){let W=[...E,M],V=`${P}_${W.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof K==="object"&&K!==null&&!Array.isArray(K))this.extractEnvVarInfo(K,W,P,x);else x.push({key:V,type:Array.isArray(K)?"array":typeof K,description:`Configuration for ${W.join(".")}`,example:this.generateExample(K)})}}generateExample(C){if(Array.isArray(C))return JSON.stringify(C);if(typeof C==="object"&&C!==null)return JSON.stringify(C);return String(C)}formatAsText(C,E){let P=`Environment Variables for ${E}:
50
-
51
- `;for(let x of C)P+=`${x.key}
52
- `,P+=` Type: ${x.type}
53
- `,P+=` Description: ${x.description}
54
- `,P+=` Example: ${x.example}
55
-
56
- `;return P}formatAsMarkdown(C,E){let P=`# Environment Variables for ${E}
57
-
58
- `;P+=`| Variable | Type | Description | Example |
59
- `,P+=`|----------|------|-------------|----------|
60
- `;for(let x of C)P+=`| \`${x.key}\` | ${x.type} | ${x.description} | \`${x.example}\` |
61
- `;return P}}function Po(C,E,P={}){return cs(C,E,P,new WeakMap)}function cs(C,E,P,x){let{arrayMergeMode:M="replace",skipNullish:K=!1,customMerger:W}=P;if(E===null||E===void 0)return K?C:E;if(W){let V=W(C,E);if(V!==void 0)return V}if(Array.isArray(E)||Array.isArray(C))return ls(C,E,M,x);if(!Fe(E)||!Fe(C))return E;return Io(C,E,P,x)}function ls(C,E,P,x){if(Array.isArray(E)&&!Array.isArray(C))return E;if(Array.isArray(C)&&!Array.isArray(E))return E;if(Array.isArray(E)&&Array.isArray(C))switch(P){case"replace":return E;case"concat":return Mo(C,E);case"smart":return Do(C,E,x);default:return E}return E}function Mo(C,E){let P=[...E];for(let x of C)if(!P.some((M)=>Sr(M,x)))P.push(x);return P}function Do(C,E,P){if(E.length===0)return C;if(C.length===0)return E;if(Fe(E[0])&&Fe(C[0]))return Lo(C,E,P);if(E.every((x)=>typeof x==="string")&&C.every((x)=>typeof x==="string")){let x=[...E];for(let M of C)if(!x.includes(M))x.push(M);return x}return E}function Lo(C,E,P){let x=[...E];for(let M of C){if(!Fe(M)){x.push(M);continue}let K=["id","name","key","path","type"],W=!1;for(let V of K)if(V in M){if(x.find((z)=>Fe(z)&&(V in z)&&z[V]===M[V])){W=!0;break}}if(!W)x.push(M)}return x}function Io(C,E,P,x){let M=E;if(Fe(M)&&x.has(M))return x.get(M);let K={...C};if(Fe(M))x.set(M,K);for(let W in M){if(!Object.prototype.hasOwnProperty.call(M,W))continue;let V=M[W],U=K[W];if(P.skipNullish&&(V===null||V===void 0))continue;if(V===null||V===void 0){K[W]=V;continue}if(Fe(V)&&Fe(U))K[W]=cs(U,V,P,x);else if(Array.isArray(V)||Array.isArray(U))K[W]=ls(U,V,P.arrayMergeMode||"smart",x);else K[W]=V}return K}function fs(C,E,P="replace"){return Po(C,E,{arrayMergeMode:P==="replace"?"replace":"smart",skipNullish:!0})}function Sr(C,E){if(C===E)return!0;if(Array.isArray(C)&&Array.isArray(E)){if(C.length!==E.length)return!1;for(let P=0;P<C.length;P++)if(!Sr(C[P],E[P]))return!1;return!0}if(Fe(C)&&Fe(E)){let P=Object.keys(C),x=Object.keys(E);if(P.length!==x.length)return!1;for(let M of P){if(!Object.prototype.hasOwnProperty.call(E,M))return!1;if(!Sr(C[M],E[M]))return!1}return!0}return!1}function Fe(C){return Boolean(C&&typeof C==="object"&&!Array.isArray(C))}class us{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(C,E,P={}){let{arrayStrategy:x="replace",useCache:M=!0,cacheTtl:K,trackPerformance:W=!0,verbose:V=!1}=P;if(M){let z=Ot.getWithFileCheck("file",C);if(z){if(V)console.log(`Configuration loaded from cache: ${C}`);return z}}let U=async()=>{if(!Ct(C))return null;try{let z=`?t=${Date.now()}`,G=await import(C+z),J=G.default||G,q="default"in G,Y=Object.keys(G).length>0;if(!q&&!Y)throw new Kt(C,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof J!=="object"||J===null||Array.isArray(J))throw new Kt(C,Error("Configuration must export a valid object"),"unknown");let Z={config:fs(E,J,x),source:{type:"file",path:C,priority:100,timestamp:new Date}};if(M)Ot.setWithFileCheck("file",Z,C,K);return Z}catch(z){throw z instanceof Error?rt.configLoad(C,z):rt.configLoad(C,Error(String(z)))}};if(W)return Tr.track("loadFromPath",U,{path:C});return U()}async tryLoadFromPaths(C,E,P={}){for(let x of C)try{let M=await this.loadFromPath(x,E,P);if(M)return M}catch(M){if(M instanceof Error&&M.name==="ConfigLoadError")throw M;if(P.verbose)console.warn(`Failed to load config from ${x}:`,M)}return null}generateConfigPaths(C,E,P){let x=this.generateNamePatterns(C,P),M=[];for(let K of x)for(let W of this.extensions)M.push(mr(E,`${K}${W}`));return M}generateNamePatterns(C,E){let P=[];if(P.push("config",".config"),C)P.push(C,`.${C}.config`,`${C}.config`,`.${C}`);let x=E===void 0?[]:Array.isArray(E)?E:[E];for(let K of x){if(!K)continue;if(P.push(K,`.${K}.config`,`${K}.config`,`.${K}`),C)P.push(`${C}.${K}.config`,`.${C}.${K}.config`)}let M=new Set;return P.filter((K)=>{if(!K||M.has(K))return!1;return M.add(K),!0})}checkFileAccess(C){return No(async()=>Ct(C),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(C,E,P){let x=[];if(!Ct(C))return x;if(E||P){let M=this.generateNamePatterns(E||"",P);for(let K of M)for(let W of this.extensions){let V=mr(C,`${K}${W}`);if(await this.checkFileAccess(V))x.push(V)}}else try{let{readdirSync:M}=await import("fs"),K=M(C);for(let W of K)if(this.looksLikeConfigFile(W)){let V=mr(C,W);if(await this.checkFileAccess(V))x.push(V)}}catch{return[]}return x}looksLikeConfigFile(C){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((P)=>P.test(C))}async validateConfigFile(C){let E=[];try{if(!Ct(C))return E.push("Configuration file does not exist"),E;let P=await import(C),x=P.default||P;if(x===void 0)E.push("Configuration file must export a default value or named exports");else if(typeof x!=="object"||x===null)E.push("Configuration must be an object");else if(Array.isArray(x))E.push("Configuration cannot be an array at the root level");if(C.endsWith(".json"))try{let{readFileSync:M}=await import("fs"),K=M(C,"utf8");JSON.parse(K)}catch(M){E.push(`Invalid JSON syntax: ${M}`)}}catch(P){E.push(`Failed to load configuration file: ${P}`)}return E}async getFileModificationTime(C){try{let{statSync:E}=await import("fs");return E(C).mtime}catch{return null}}async preloadConfigurations(C,E={}){let P=new Map;return await Promise.allSettled(C.map(async(x)=>{try{let M=await this.loadFromPath(x,{},E);if(M)P.set(x,M.config)}catch(M){if(E.verbose)console.warn(`Failed to preload ${x}:`,M)}})),P}}var _o=/^https?:\/\//;class gs{async validateConfiguration(C,E,P={}){let{stopOnFirstError:x=!1,validateRequired:M=!0,validateTypes:K=!0,customRules:W=[],trackPerformance:V=!0,verbose:U=!1}=P,z=async()=>{let G=[],J=[],q={stopOnFirstError:x,validateRequired:M,validateTypes:K,customRules:W,trackPerformance:V,verbose:U};try{if(typeof E==="string")return await this.validateWithSchemaFile(C,E,q);else if(Array.isArray(E))return this.validateWithRules(C,[...E,...W],q);else return this.validateWithJSONSchema(C,E,q)}catch(Y){return G.push({path:"",message:`Validation failed: ${Y}`,rule:"system"}),{isValid:!1,errors:G,warnings:J}}};if(V)return await Tr.track("validateConfiguration",z);return z()}async validateWithSchemaFile(C,E,P){try{if(!jo(E))throw new Wt(E,[{path:"",message:"Schema file does not exist"}]);let x=await import(E),M=x.default||x;if(Array.isArray(M))return this.validateWithRules(C,M,P);else return this.validateWithJSONSchema(C,M,P)}catch(x){throw new Wt(E,[{path:"",message:`Failed to load schema: ${x}`}])}}validateWithJSONSchema(C,E,P){let x=[],M=[];return this.validateObjectAgainstSchema(C,E,"",x,M,P),{isValid:x.length===0,errors:x,warnings:M}}validateObjectAgainstSchema(C,E,P,x,M,K){if(K.validateTypes&&E.type){let W=Array.isArray(C)?"array":typeof C,V=Array.isArray(E.type)?E.type:[E.type];if(!V.includes(W)){if(x.push({path:P,message:`Expected type ${V.join(" or ")}, got ${W}`,expected:V.join(" or "),actual:W,rule:"type"}),K.stopOnFirstError)return}}if(E.enum&&!E.enum.includes(C)){if(x.push({path:P,message:`Value must be one of: ${E.enum.join(", ")}`,expected:E.enum.join(", "),actual:C,rule:"enum"}),K.stopOnFirstError)return}if(typeof C==="string"){if(E.minLength!==void 0&&C.length<E.minLength)x.push({path:P,message:`String length must be at least ${E.minLength}`,expected:`>= ${E.minLength}`,actual:C.length,rule:"minLength"});if(E.maxLength!==void 0&&C.length>E.maxLength)x.push({path:P,message:`String length must not exceed ${E.maxLength}`,expected:`<= ${E.maxLength}`,actual:C.length,rule:"maxLength"});if(E.pattern){if(!new RegExp(E.pattern).test(C))x.push({path:P,message:`String does not match pattern ${E.pattern}`,expected:E.pattern,actual:C,rule:"pattern"})}}if(typeof C==="number"){if(E.minimum!==void 0&&C<E.minimum)x.push({path:P,message:`Value must be at least ${E.minimum}`,expected:`>= ${E.minimum}`,actual:C,rule:"minimum"});if(E.maximum!==void 0&&C>E.maximum)x.push({path:P,message:`Value must not exceed ${E.maximum}`,expected:`<= ${E.maximum}`,actual:C,rule:"maximum"})}if(Array.isArray(C)&&E.items)for(let W=0;W<C.length;W++){let V=P?`${P}[${W}]`:`[${W}]`;if(this.validateObjectAgainstSchema(C[W],E.items,V,x,M,K),K.stopOnFirstError&&x.length>0)return}if(C&&typeof C==="object"&&!Array.isArray(C)){let W=C;if(K.validateRequired&&E.required){for(let V of E.required)if(!(V in W)){if(x.push({path:P?`${P}.${V}`:V,message:`Missing required property '${V}'`,expected:"required",rule:"required"}),K.stopOnFirstError)return}}if(E.properties){for(let[V,U]of Object.entries(E.properties))if(V in W){let z=P?`${P}.${V}`:V;if(this.validateObjectAgainstSchema(W[V],U,z,x,M,K),K.stopOnFirstError&&x.length>0)return}}if(E.additionalProperties===!1){let V=new Set(Object.keys(E.properties||{}));for(let U of Object.keys(W))if(!V.has(U))M.push({path:P?`${P}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(C,E,P){let x=[],M=[];for(let K of E)try{let W=this.getValueByPath(C,K.path),V=this.validateWithRule(W,K,K.path);if(x.push(...V),P.stopOnFirstError&&x.length>0)break}catch(W){x.push({path:K.path,message:`Rule validation failed: ${W}`,rule:"system"})}return{isValid:x.length===0,errors:x,warnings:M}}validateWithRule(C,E,P){let x=[];if(E.required&&(C===void 0||C===null))return x.push({path:P,message:E.message||`Property '${P}' is required`,expected:"required",rule:"required"}),x;if(C===void 0||C===null)return x;if(E.type){let M=Array.isArray(C)?"array":typeof C;if(M!==E.type)x.push({path:P,message:E.message||`Expected type ${E.type}, got ${M}`,expected:E.type,actual:M,rule:"type"})}if(E.min!==void 0){let M=Array.isArray(C)?C.length:typeof C==="string"?C.length:typeof C==="number"?C:0;if(M<E.min)x.push({path:P,message:E.message||`Value must be at least ${E.min}`,expected:`>= ${E.min}`,actual:M,rule:"min"})}if(E.max!==void 0){let M=Array.isArray(C)?C.length:typeof C==="string"?C.length:typeof C==="number"?C:0;if(M>E.max)x.push({path:P,message:E.message||`Value must not exceed ${E.max}`,expected:`<= ${E.max}`,actual:M,rule:"max"})}if(E.pattern&&typeof C==="string"){if(!E.pattern.test(C))x.push({path:P,message:E.message||`Value does not match pattern ${E.pattern}`,expected:E.pattern.toString(),actual:C,rule:"pattern"})}if(E.enum&&!E.enum.includes(C))x.push({path:P,message:E.message||`Value must be one of: ${E.enum.join(", ")}`,expected:E.enum.join(", "),actual:C,rule:"enum"});if(E.validator){let M=E.validator(C);if(M)x.push({path:P,message:E.message||M,rule:"custom"})}return x}getValueByPath(C,E){if(!E)return C;let P=E.split("."),x=C;for(let M of P)if(x&&typeof x==="object"&&M in x)x=x[M];else return;return x}generateRulesFromInterface(C){let E=[],P=C.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let x of P){let[,M,K,W]=x;E.push({path:M,required:!K,type:this.mapTypeScriptType(W)})}return E}mapTypeScriptType(C){switch(C.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:_o},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Me=new Gt("bunfig",{showTags:!0});function Bo(C){if(!C)return"";let E=Array.isArray(C)?C.filter(Boolean):[C];if(E.length===0)return"";if(E.length===1)return` or alias "${E[0]}"`;return` or aliases ${E.map((P)=>`"${P}"`).join(", ")}`}class ms{fileLoader=new us;envProcessor=new Lr;validator=new gs;async loadConfig(C){let E=Date.now(),{cache:P,performance:x,schema:M,validate:K,...W}=C;try{if(P?.enabled){let U=this.checkCache(W.name||"",W);if(U)return U}let V;try{V=await this.loadConfigurationStrategies(W,!0,P)}catch(U){let z=W.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(z)throw U;V={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`No configuration file found for "${W.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let G=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),J=!G&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),q=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(z&&(q||G))throw U;if(J&&(!z||!q))V={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!z)V={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else V={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(M||K)await this.validateConfiguration(V.config,M,K,W.name);if(P?.enabled&&V)this.cacheResult(W.name||"",V,P,W);if(x?.enabled){let U={operation:"loadConfig",duration:Date.now()-E,configName:W.name,timestamp:new Date};if(x.onMetrics)x.onMetrics(U);if(x.slowThreshold&&U.duration>x.slowThreshold)Me.warn(`Slow configuration loading detected: ${U.duration}ms for ${W.name}`);V.metrics=U}return V}catch(V){if(V instanceof Error&&V.name==="ConfigNotFoundError")throw V;let U=Date.now()-E;throw Me.error(`Configuration loading failed after ${U}ms:`,[V instanceof Error?V:Error(String(V))]),V}}async loadConfigurationStrategies(C,E=!1,P){let{name:x="",alias:M,cwd:K,configDir:W,defaultConfig:V,checkEnv:U=!0,arrayStrategy:z="replace",verbose:G=!1}=C,J=K||Vt.cwd(),q=[],Y=await this.loadLocalConfiguration(x,M,J,W,V,z,G,U,P);if(Y)return q.push(...this.getLocalSearchPaths(x,M,J,W)),this.finalizeResult(Y,q,U,x,G);let ee=await this.loadHomeConfiguration(x,M,V,z,G,U);if(ee)return q.push(...this.getHomeSearchPaths(x,M)),this.finalizeResult(ee,q,U,x,G);let H=await this.loadPackageJsonConfiguration(x,M,J,V,z,G,U);if(H)return q.push(Oe(J,"package.json")),this.finalizeResult(H,q,U,x,G);if(q.push(...this.getAllSearchPaths(x,M,J,W)),E)throw rt.configNotFound(x,q,M);return{...await this.applyEnvironmentVariables(x,V,U,G),warnings:[`No configuration file found for "${x}"${Bo(M)}, using defaults with environment variables`]}}async loadLocalConfiguration(C,E,P,x,M,K,W,V,U){let z=V?Et(C,M,W):M,G=this.getLocalDirectories(P,x);for(let J of G){if(W)Me.info(`Searching for configuration in: ${J}`);let q=this.fileLoader.generateConfigPaths(C,J,E),Y=await this.fileLoader.tryLoadFromPaths(q,z,{arrayStrategy:K,verbose:W,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(Y){if(W)Me.success(`Configuration loaded from: ${Y.source.path}`);return Y}}return null}async loadHomeConfiguration(C,E,P,x,M,K){if(!C)return null;let W=K?Et(C,P,M):P,V=[Oe(Ue(),".config",C),Oe(Ue(),".config"),Ue()];for(let U of V){if(M)Me.info(`Checking home directory: ${U}`);let z=this.fileLoader.generateConfigPaths(C,U,E),G=await this.fileLoader.tryLoadFromPaths(z,W,{arrayStrategy:x,verbose:M});if(G){if(M)Me.success(`Configuration loaded from home directory: ${G.source.path}`);return G}}return null}async loadPackageJsonConfiguration(C,E,P,x,M,K,W){let V=W?Et(C,x,K):x;try{let U=Oe(P,"package.json");if(!Ns(U))return null;let z={};try{z=JSON.parse(Ps(U,"utf8"))}catch(q){if(K)Me.warn("Failed to parse package.json:",[q instanceof Error?q:Error(String(q))]);return null}let G=z[C],J=C;if(!G&&E){let q=Array.isArray(E)?E:[E];for(let Y of q){if(!Y)continue;if(z[Y]){G=z[Y],J=Y;break}}}if(G&&typeof G==="object"&&!Array.isArray(G)){if(K)Me.success(`Configuration loaded from package.json: ${J}`);return{config:fs(V,G,M),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(K)Me.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables(C,E,P,x){if(!P||!C||typeof E!=="object"||E===null||Array.isArray(E))return{config:E,source:{type:"default",priority:10,timestamp:new Date}};return{config:Et(C,E,x),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(C,E,P,x,M){return{config:C.config,source:C.source,path:C.source.path}}async validateConfiguration(C,E,P,x){let M=[];if(P){let K=P(C);if(K)M.push(...K)}if(E){let K=await this.validator.validateConfiguration(C,E);if(!K.isValid)M.push(...K.errors.map((W)=>W.path?`${W.path}: ${W.message}`:W.message))}if(M.length>0)throw rt.configValidation(x||"unknown",M,x)}checkCache(C,E){let P=this.generateCacheKey(C,E);return Ot.get(P)||null}cacheResult(C,E,P,x){let M=this.generateCacheKey(C,x);Ot.set(M,E,void 0,P.ttl)}generateCacheKey(C,E){let P=[C];if(E.alias){let x=Array.isArray(E.alias)?E.alias.join(","):E.alias;P.push(`alias:${x}`)}if(E.cwd)P.push(`cwd:${E.cwd}`);if(E.configDir)P.push(`configDir:${E.configDir}`);if("checkEnv"in E)P.push(`checkEnv:${E.checkEnv}`);return P.join("|")}getLocalDirectories(C,E){return Array.from(new Set([C,Oe(C,"config"),Oe(C,".config"),E?Oe(C,E):void 0].filter(Boolean)))}getAllSearchPaths(C,E,P,x){let M=[];return M.push(...this.getLocalSearchPaths(C,E,P,x)),M.push(...this.getHomeSearchPaths(C,E)),M.push(Oe(P,"package.json")),M}getLocalSearchPaths(C,E,P,x){let M=this.getLocalDirectories(P,x),K=[];for(let W of M)K.push(...this.fileLoader.generateConfigPaths(C,W,E));return K}getHomeSearchPaths(C,E){if(!C)return[];let P=[Oe(Ue(),".config",C),Oe(Ue(),".config"),Ue()],x=[];for(let M of P)x.push(...this.fileLoader.generateConfigPaths(C,M,E));return x}async loadConfigWithResult(C){return this.loadConfig(C)}}var hr=new ms;async function hs(C){let E="defaultConfig"in C&&C.defaultConfig!==void 0?C.defaultConfig:{},P="cache"in C||"performance"in C||"schema"in C||"validate"in C;try{let x;if(P)x=await hr.loadConfig(C);else x=await hr.loadConfig({...C,defaultConfig:E,cache:{enabled:!0},performance:{enabled:!1}});return x?.config??E}catch(x){let M=x instanceof Error?x.name:"UnknownError",K=x instanceof Error?x.message:String(x);if(!(M==="ConfigNotFoundError"||M==="ConfigLoadError"||M==="ConfigValidationError"||K.includes("config"))&&C.verbose)Me.warn("Unexpected error loading config, using defaults:",[x instanceof Error?x:Error(String(x))]);let V=P?{...C,defaultConfig:E}:{...C,defaultConfig:E,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in C?C.checkEnv!==!1:!0)return(await hr.applyEnvironmentVariables(V.name||"",E,!0,V.verbose||!1))?.config??E;return E}}function Et(C,E,P=!1){let x=new Lr,M=C.toUpperCase().replace(/[^A-Z0-9]/g,"_");function K(W,V=[]){let U={...W};for(let[z,G]of Object.entries(W)){let J=[...V,z],q=[`${M}_${J.join("_").toUpperCase()}`,`${M}_${J.map((H)=>H.toUpperCase()).join("")}`,`${M}_${J.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],Y,ee;for(let H of q)if(Y=Vt.env[H],Y!==void 0){ee=H;break}if(Y!==void 0&&ee)if(typeof G==="boolean")U[z]=["true","1","yes"].includes(Y.toLowerCase());else if(typeof G==="number"){let H=Number(Y);if(!Number.isNaN(H))U[z]=H}else if(Array.isArray(G))try{U[z]=JSON.parse(Y)}catch{U[z]=Y.split(",").map((H)=>H.trim())}else U[z]=Y;else if(G&&typeof G==="object"&&!Array.isArray(G))U[z]=K(G,J)}return U}return K(E)}var Dl=Oe(Vt.cwd(),"config"),Ll=Oe(Vt.cwd(),"src/generated");var Ko=["code-style","lint"],s={ignores:["**/node_modules/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/.output/**","**/.next/**","**/.nuxt/**","**/.vite/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/vendor/**","**/pantry/**","**/tmp/**","**/.git/**","**/.idea/**","**/.vscode/**","**/.zed/**","**/.cursor/**","**/.claude/**","**/.github/**","**/*.test.ts","**/*.spec.ts","**/.bunpress/**","**/.vitepress/cache/**","**/storage/framework/stx/**","**/storage/framework/runtime/**","**/storage/cloud/**","**/*.lock","**/package-lock.json","**/pnpm-lock.yaml"],lint:{extensions:["ts","js","html","css","json","jsonc","md","yaml","yml","stx","sh","bash","zsh"],reporter:"stylish",cache:!1,maxWarnings:-1},format:{extensions:["ts","js","html","css","json","jsonc","md","yaml","yml","stx","sh","bash","zsh"],trimTrailingWhitespace:!0,maxConsecutiveBlankLines:1,finalNewline:"one",indent:2,indentStyle:"spaces",preserveCodeIndentation:!1,quotes:"single",semi:!1},rules:{noDebugger:"error",noConsole:"warn"},pluginRules:{"style/brace-style":"warn","style/curly":"off","style/if-newline":"off","style/max-statements-per-line":"warn","pickier/import-dedupe":"warn","pickier/no-import-node-modules-by-path":"error","pickier/no-import-dist":"error","pickier/prefer-const":"error","pickier/prefer-template":"warn","pickier/no-unused-vars":"error","pickier/no-unused-imports":"error","pickier/sort-tailwind-classes":"warn","regexp/no-unused-capturing-group":"error","regexp/no-super-linear-backtracking":"error","regexp/no-useless-lazy":"error","ts/no-top-level-await":"error","ts/member-delimiter-style":"off","ts/type-annotation-spacing":"off","style/comma-dangle":"off","style/keyword-spacing":"off","style/arrow-spacing":"off","style/space-infix-ops":"off","style/object-curly-spacing":"off","style/spaced-comment":"off","style/block-spacing":"off","style/space-before-blocks":"off","style/comma-spacing":"off","style/semi-spacing":"off","style/rest-spread-spacing":"off","style/key-spacing":"off","style/computed-property-spacing":"off","style/array-bracket-spacing":"off","style/space-in-parens":"off","style/template-curly-spacing":"off","style/space-unary-ops":"off","style/switch-colon-spacing":"off","style/arrow-parens":"off","style/space-before-function-paren":"off","style/quote-props":"off","style/no-floating-decimal":"off","style/new-parens":"off","style/no-extra-parens":"off","style/wrap-iife":"off","style/comma-style":"off","style/dot-location":"off","style/operator-linebreak":"off","style/multiline-ternary":"off","style/padded-blocks":"off","style/lines-between-class-members":"off","style/no-tabs":"off","style/no-mixed-spaces-and-tabs":"off","style/generator-star-spacing":"off","style/yield-star-spacing":"off","style/function-call-spacing":"off","style/template-tag-spacing":"off","style/no-whitespace-before-property":"off","style/no-mixed-operators":"off","style/indent-binary-ops":"off","ts/type-generic-spacing":"off","ts/type-named-tuple-spacing":"off","markdown/heading-increment":"warn","markdown/heading-style":"warn","markdown/no-missing-space-atx":"error","markdown/no-multiple-space-atx":"error","markdown/no-missing-space-closed-atx":"error","markdown/no-multiple-space-closed-atx":"error","markdown/blanks-around-headings":"warn","markdown/heading-start-left":"warn","markdown/no-duplicate-heading":"warn","markdown/single-title":"warn","markdown/no-trailing-punctuation":"warn","markdown/ul-style":"warn","markdown/list-indent":"error","markdown/ul-indent":"warn","markdown/ol-prefix":"warn","markdown/list-marker-space":"error","markdown/blanks-around-lists":"warn","markdown/no-trailing-spaces":"error","markdown/no-hard-tabs":"error","markdown/no-multiple-blanks":"warn","markdown/no-multiple-space-blockquote":"error","markdown/no-blanks-blockquote":"warn","markdown/blanks-around-fences":"warn","markdown/single-trailing-newline":"error","markdown/blanks-around-tables":"warn","markdown/no-reversed-links":"error","markdown/no-bare-urls":"warn","markdown/no-space-in-links":"error","markdown/no-empty-links":"error","markdown/link-fragments":"warn","markdown/reference-links-images":"warn","markdown/link-image-reference-definitions":"warn","markdown/link-image-style":"warn","markdown/descriptive-link-text":"warn","markdown/line-length":"off","markdown/commands-show-output":"warn","markdown/fenced-code-language":"warn","markdown/code-block-style":"off","markdown/code-fence-style":"warn","markdown/no-emphasis-as-heading":"warn","markdown/no-space-in-emphasis":"warn","markdown/no-space-in-code":"warn","markdown/emphasis-style":"warn","markdown/strong-style":"warn","markdown/no-inline-html":"off","markdown/hr-style":"warn","markdown/first-line-heading":"off","markdown/required-headings":"off","markdown/proper-names":"off","markdown/no-alt-text":"warn","markdown/table-pipe-style":"warn","markdown/table-column-count":"warn","markdown/table-column-style":"warn","lockfile/validate-host":["warn",{allowedHosts:["npm","yarn"]}],"lockfile/validate-https":"error","lockfile/validate-integrity":["warn",{requiredAlgorithm:"sha512"}],"lockfile/validate-package-names":"error","lockfile/validate-scheme":["error",{allowedSchemes:["https:","git+https:","git+ssh:"]}],"publint/exports-types-should-be-first":"error","publint/exports-default-should-be-last":"error","publint/exports-module-should-precede-require":"error","publint/exports-value-invalid":"error","publint/imports-key-invalid":"error","publint/imports-value-invalid":"error","publint/imports-default-should-be-last":"error","publint/imports-module-should-precede-require":"error","publint/use-type":"warn","publint/deprecated-field-jsnext":"warn","publint/field-invalid-value-type":"error","publint/local-dependency":"error","publint/has-module-but-no-exports":"warn","publint/exports-missing-root-entrypoint":"warn","publint/exports-fallback-array-use":"warn","publint/file-does-not-exist":"warn","publint/file-invalid-format":"warn","publint/module-should-be-esm":"error","publint/bin-file-not-executable":"error","publint/exports-module-should-be-esm":"error","shell/command-substitution":"error","shell/quote-variables":"warn","shell/no-cd-without-check":"warn","shell/no-eval":"error","shell/no-useless-cat":"warn","shell/shebang":"warn","shell/indent":"warn","shell/function-style":"warn","shell/operator-spacing":"warn","shell/keyword-spacing":"warn","shell/no-trailing-semicolons":"warn","shell/no-trailing-whitespace":"error","shell/prefer-double-brackets":"warn","shell/set-options":"off","shell/prefer-printf":"warn","shell/consistent-case-terminators":"warn","shell/no-broken-redirect":"error","shell/heredoc-indent":"warn","shell/no-ls-parsing":"warn","shell/no-variable-in-single-quotes":"warn","shell/no-exit-in-subshell":"warn","spell/check":"off","spell/check-comments":"off","spell/check-markdown":"off"},verbose:!0},Ir=null;async function F(){if(!Ir)Ir=await hs({name:"pickier",alias:[...Ko],defaultConfig:s});return Ir}var S=s;import{readFileSync as Ya,statSync as Ha,writeFileSync as Za}from"fs";import{isAbsolute as Xa,resolve as Qa}from"path";function r(C){let E=C.length,P=Array.from({length:E},(M,K)=>C[K]),x=0;while(x<E){let M=C[x];if(M==="#"&&(x===0||/\s/.test(C[x-1]))){while(x<E)P[x]=" ",x++;break}if(M==="$"&&C[x+1]==="'"){x+=2;while(x<E){if(C[x]==="\\"&&x+1<E){P[x]=" ",P[x+1]=" ",x+=2;continue}if(C[x]==="'"){x++;break}P[x]=" ",x++}continue}if(M==="$"&&C[x+1]==='"'){x++,x=ct(C,x,P);continue}if(M==="$"&&C[x+1]==="{"){x+=2;let K=1;while(x<E&&K>0){let W=C[x];if(W==="\\"&&x+1<E){P[x]=" ",P[x+1]=" ",x+=2;continue}if(W==="'"){x++;while(x<E&&C[x]!=="'")P[x]=" ",x++;if(x<E)x++;continue}if(W==='"'){x=ct(C,x,P);continue}if(W==="{"){K++,x++;continue}if(W==="}"){K--,x++;continue}P[x]=" ",x++}continue}if(M==="$"&&C[x+1]==="("&&C[x+2]==="("){x+=3;let K=2;while(x<E&&K>0){let W=C[x];if(W==="("){K++,x++;continue}if(W===")"){K--,x++;continue}P[x]=" ",x++}continue}if(M==="$"&&C[x+1]==="("){x+=2;let K=1;while(x<E&&K>0){let W=C[x];if(W==="\\"&&x+1<E){P[x]=" ",P[x+1]=" ",x+=2;continue}if(W==="'"){x++;while(x<E&&C[x]!=="'")P[x]=" ",x++;if(x<E)x++;continue}if(W==='"'){x=ct(C,x,P);continue}if(W==="("){K++,x++;continue}if(W===")"){K--,x++;continue}P[x]=" ",x++}continue}if(M==="'"){x++;while(x<E&&C[x]!=="'")P[x]=" ",x++;if(x<E)x++;continue}if(M==='"'){x=ct(C,x,P);continue}if(M==="`"){x++;while(x<E&&C[x]!=="`"){if(C[x]==="\\"&&x+1<E){P[x]=" ",P[x+1]=" ",x+=2;continue}P[x]=" ",x++}if(x<E)x++;continue}x++}return P.join("")}function ct(C,E,P){let x=C.length,M=E+1;while(M<x){let K=C[M];if(K==="\\"&&M+1<x){P[M]=" ",P[M+1]=" ",M+=2;continue}if(K==='"')return M+1;if(K==="$"&&C[M+1]==="("&&C[M+2]==="("){M+=3;let W=2;while(M<x&&W>0){let V=C[M];if(V==="("){W++,M++;continue}if(V===")"){W--,M++;continue}P[M]=" ",M++}continue}if(K==="$"&&C[M+1]==="("){M+=2;let W=1;while(M<x&&W>0){let V=C[M];if(V==="\\"&&M+1<x){P[M]=" ",P[M+1]=" ",M+=2;continue}if(V==="'"){M++;while(M<x&&C[M]!=="'")P[M]=" ",M++;if(M<x)M++;continue}if(V==='"'){M=ct(C,M,P);continue}if(V==="("){W++,M++;continue}if(V===")"){W--,M++;continue}P[M]=" ",M++}continue}if(K==="$"&&C[M+1]==="{"){M+=2;let W=1;while(M<x&&W>0){let V=C[M];if(V==="{"){W++,M++;continue}if(V==="}"){W--,M++;continue}P[M]=" ",M++}continue}P[M]=" ",M++}return M}function t(C){let P=r(C).match(/<<-?/);if(!P||P.index===void 0)return null;let M=C.slice(P.index+P[0].length).match(/^\s*(['"]?)(\w+)\1/);if(!M)return null;return M[2]}var Wo=new Set([".ts",".js"]),Vo=new Set([".json",".jsonc"]),Uo=new Set([".yaml",".yml"]),zo=new Set([".sh",".bash",".zsh",".ksh",".dash"]),Go=/^#!\s*(?:\/usr\/bin\/env\s+)?(?:ba|z|k|da)?sh\b/;var Jo=/^[}\])]/,qo=/[{[(]\s*$/,Yo=/\s*\/\/.*$/,Ho=/^(?:if|else\s+if|for|while)\s*\(/,Zo=/^(?:\.[\w$[]|\?[\s.:]|:\s|&&|\|\|)/;function Xo(C){let E=Ho.exec(C);if(!E)return/^(?:else|do)\s*$/.test(C);let P=0,x=null;for(let M=E[0].length-1;M<C.length;M++){let K=C[M];if(x){if(K==="\\"){M++;continue}if(K===x)x=null;continue}if(K==="'"||K==='"'||K==="`"){x=K;continue}if(K==="(")P++;else if(K===")"){if(P--,P===0)return C.slice(M+1).trim().length===0}}return!1}var Qo=/^\s*for\s*\(/,ea=new RegExp("^\\s*;\\s*$"),ta=new RegExp(";{2,}\\s*$"),ra=/([\w)])\{/g,na=/\{(return|if|for|while|switch|const|let|var|function)\b/g,sa=/,(\S)/g,ia=/(?<![=!<>+\-*/%&|^?])=(?![=><])/g,oa=/(\w)\+(\w)/g,aa=/(\w)-(\w)/g,ca=/(\w)\*(\w)/g,la=/(\w)\/(\w)/g,fa=new RegExp("(?<=\\S);([^\\s;])","g"),ua=/([\w)\]])<(\d)/g,ga=/([\w)\]])>(\d)/g,ds=/\s{2,}/g,ps=/^\s*$/,ma=/^\s*\/\//,ys=/^\s*\/\*/,ha=/^\s*import\b/,ws=/\bfrom\s*['"][^'"]+['"]|^\s*import\s+['"][^'"]+['"]/,da=/package\.json$/i,pa=/[jt]sconfig(?:\..+)?\.json$/i,jr=/[ \t]+$/,ya=/^\n+/;function Jt(C){let E=C.lastIndexOf(".");return E>=0?C.slice(E):""}function _r(C){return Wo.has(Jt(C))}function wa(C){return Vo.has(Jt(C))}function ba(C){return Uo.has(Jt(C))}function va(C){return zo.has(Jt(C))}function $a(C,E){return va(C)||Go.test(E)}function Ca(C,E){let P=C.split(`
62
- `),x=P.length,M=Array(x),K=E.format.indent,W=E.format.indentStyle==="tabs",V=0,U=!1,z="",G=!1,J=0;for(let q=0;q<x;q++){let Y=P[q];if(Y.length===0||/^\s*$/.test(Y)){M[q]="";continue}if(U){if(M[q]=Y,Y.trim()===z)U=!1,z="";continue}let ee=t(Y);if(ee)U=!0,z=ee;let H=0;while(H<Y.length&&(Y.charCodeAt(H)===32||Y.charCodeAt(H)===9))H++;let Z=Y.slice(H).trimEnd();if(Z.startsWith("#")&&q>0){let we=W?"\t".repeat(V):" ".repeat(V*K);M[q]=we+Z;continue}if(/^case\b/.test(Z)&&/\bin\s*$/.test(Z))J++,G=!0;if(/^esac\b/.test(Z)){if(J=Math.max(0,J-1),J===0)G=!1}let te=G&&/\)\s*$/.test(Z)&&!/\$\(/.test(Z)&&!/^\s*\(/.test(Z)&&!Z.startsWith("#"),re=/^;[;&]\s*$/.test(Z);if(/^(?:fi|done|esac|elif|else)\b/.test(Z)||/^\}/.test(Z))V=Math.max(0,V-1);if(re)V=Math.max(0,V-1);let Ce=W?"\t".repeat(V):" ".repeat(V*K);if(M[q]=Ce+Z,/^then\b/.test(Z)||/^do\b/.test(Z)||/^else\b/.test(Z))V++;else if(/^if\b/.test(Z)&&/\bthen\s*$/.test(Z))V++;else if(/^elif\b/.test(Z)&&/\bthen\s*$/.test(Z))V++;else if(/^(?:while|for|until)\b/.test(Z)&&/\bdo\s*$/.test(Z))V++;else if(/^case\b/.test(Z)&&/\bin\s*$/.test(Z))V++;else if(te)V++;else if(/\{\s*$/.test(Z)&&!Z.startsWith("#"))V++}return M.join(`
63
- `)}function Ea(C,E){try{let P=Bun.YAML.parse(C),x=E.format.indentStyle==="tabs"?"\t":E.format.indent;return Bun.YAML.stringify(P,null,x).split(`
64
- `).map((K)=>K.replace(/[ \t]+$/,"")).join(`
65
- `)}catch{return C}}function xa(C){return" ".repeat(Math.max(0,C))}function ka(C,E){if((E.format.indentStyle||"spaces")==="tabs")return"\t".repeat(Math.max(0,C));return xa(Math.max(0,C*E.format.indent))}function Sa(C){return`'${C.slice(1,-1).replace(/\\"/g,'"')}'`}function Ta(C){return`"${C.slice(1,-1).replace(/\\'/g,"'")}"`}function Aa(C,E){for(let P=0;P<C.length;P++){if(C[P]==="\\"){P++;continue}if(C[P]===E)return!0}return!1}function Oa(C,E,P){if(!_r(P))return C;let x=C.split(`
66
- `);for(let M=0;M<x.length;M++)x[M]=Cs(x[M],E);return x.join(`
67
- `)}function Cs(C,E){let P=E==="single";if(P?!C.includes('"'):!C.includes("'"))return C;let x=[],M=0,K=0,W=0,V=0;while(M<C.length){let U=C[M];if(W===0){if(U==="/"){let z=C[M+1];if(z==="/")break;if(z==="*"){let G=C.indexOf("*/",M+2);M=G===-1?C.length:G+2;continue}if(ks(C,M)){let G=Ss(C,M);if(G!==-1){M=G;continue}}M++;continue}if(U==='"'){W=2,V=M,M++;continue}if(U==="'"){W=1,V=M,M++;continue}if(U==="`"){W=3,M++;continue}M++}else if(W===3){if(U==="\\"){M+=2;continue}if(U==="`")W=0;M++}else{if(U==="\\"){M+=2;continue}if(U===(W===1?"'":'"')){let G=C.slice(V+1,M);if((W===2&&P||W===1&&!P)&&!Aa(G,P?"'":'"')){if(V>K)x.push(C.slice(K,V));if(W===2)x.push(Sa(`"${G}"`));else x.push(Ta(`'${G}'`));K=M+1}W=0,M++;continue}M++}}if(x.length===0)return C;if(K<C.length)x.push(C.slice(K));return x.join("")}var Ra=new Set(["{",",","=","+","-","*","/",";","<",">"]);function Fa(C){if(C.length<4)return C;let E=0;while(E<C.length&&(C[E]===" "||C[E]==="\t"))E++;if(E<C.length){let W=C[E];if(W==="/"&&(C[E+1]==="/"||C[E+1]==="*"))return C;if(W==="*")return C}let P=!1;for(let W=E;W<C.length;W++)if(Ra.has(C[W])){P=!0;break}if(!P)return C;let{text:x,strings:M}=Da(C),K=x;if(K=K.replace(ra,"$1 {"),K=K.replace(na,"{ $1"),K=K.replace(sa,", $1"),K=K.replace(ia," = "),K=K.replace(oa,"$1 + $2"),K=K.replace(aa,"$1 - $2"),K=K.replace(ca,"$1 * $2"),K=K.replace(la,"$1 / $2"),K=K.replace(fa,"; $1"),K=K.replace(ua,"$1 < $2"),K=K.replace(ga,"$1 > $2"),E>0){let W=K.slice(E);K=K.slice(0,E)+W.replace(ds," ")}else K=K.replace(ds," ");return M.length>0?La(K,M):K}function qt(C){let E=C[C.length-1];return E!==void 0&&E.t==="tmpl"}function Es(C,E,P){E++;while(E<C.length){let x=C[E];if(x==="\\"){E+=2;continue}if(x===P)return E+1;E++}return E}function Br(C,E){for(let x of E)if(x.t==="tmpl")x.start=-1;let P=0;while(P<C.length){let x=E[E.length-1],M=C[P];if(x===void 0||x.t==="interp"){if(M==="`"){E.push({t:"tmpl",start:P}),P++;continue}if(M==="'"||M==='"'){P=Es(C,P,M);continue}if(M==="/"&&C[P+1]==="/")break;if(x!==void 0){if(M==="{"){x.braces++,P++;continue}if(M==="}"){if(x.braces===0)E.pop();else x.braces--;P++;continue}}P++}else{if(M==="\\"){P+=2;continue}if(M==="`"){E.pop(),P++;continue}if(M==="$"&&C[P+1]==="{"){E.push({t:"interp",braces:0}),P+=2;continue}P++}}if(qt(E)){for(let x of E)if(x.t==="tmpl"&&x.start>=0)return x.start}return-1}function bs(C,E){let P=E,x=null,M=0;while(M<C.length){let K=C[M];if(P){if(K==="*"&&C[M+1]==="/"){P=!1,M+=2;continue}M++;continue}if(x){if(K==="\\"){M+=2;continue}if(K===x)x=null;M++;continue}if(K==="'"||K==='"'||K==="`"){x=K,M++;continue}if(K==="/"){if(C[M+1]==="/")break;if(C[M+1]==="*"){P=!0,M+=2;continue}}M++}return P}function Na(C,E){let P=C.split(`
68
- `),x=P.length,M=Array(x),K=E.format.quotes,W=E.format.semi===!0,V=0,U=0,z=!1,G=[];for(let J=0;J<x;J++){let q=P[J];if(z){z=bs(q,!0),M[J]=q;continue}let Y=qt(G),ee=-1;if(G.length>0||q.indexOf("`")!==-1)ee=Br(q,G);if(Y){M[J]=q;continue}if(ee<0&&G.length===0)z=bs(q,!1);let H="",Z=!1,te="";if(ee>=0){H=q.slice(ee);let Se=q.slice(0,ee);if(Se.length===0){M[J]=H;continue}if(Z=jr.test(Se),Se.trim().length===0)te=Se;q=Se}if(q.length===0){M[J]="";continue}q=Cs(q,K);let re=0;while(re<q.length&&(q.charCodeAt(re)===32||q.charCodeAt(re)===9))re++;let fe=q.slice(re).trimEnd();if(Jo.test(fe))V=Math.max(0,V-1);let Ce=Zo.test(fe)?1:0,we=q.slice(0,re);if(q=E.format.preserveCodeIndentation?we+fe:ka(V+U+Ce,E)+fe,qo.test(fe))V+=1,U=0;else if(!fe.startsWith("//")&&!fe.startsWith("*")&&!fe.startsWith("/*")){let Se=fe.replace(Yo,"");U=Xo(Se)?U+1:0}if(q=Fa(q),W){if(!Qo.test(q))if(ea.test(q))q="";else q=q.replace(ta,";")}if(E.format.trimTrailingWhitespace)q=q.trimEnd();if(ee>=0){if(te)q=te;else if(Z&&!jr.test(q))q+=" ";q+=H}M[J]=q}return M.join(`
69
- `)}function Pa(C,E){let P=[],x=0,M=[];for(let K of C){let W=qt(M);if(M.length>0||K.indexOf("`")!==-1)Br(K,M);if(W){P.push(K),x=0;continue}if(K===""){if(x++,x<=E)P.push("")}else x=0,P.push(K)}return P}function f(C,E,P){if(C.length===0)return"";let M=(C.includes("\r")?C.replace(/\r\n/g,`
70
- `):C).split(`
71
- `),K;if(E.format.trimTrailingWhitespace){K=[];let z=0,G=Math.max(0,E.format.maxConsecutiveBlankLines),J=[];for(let q of M){let Y=qt(J),ee=!1;if(J.length>0||q.indexOf("`")!==-1)ee=Br(q,J)>=0;if(Y||ee){K.push(q),z=0;continue}let H=q[q.length-1],Z=H===" "||H==="\t"?q.replace(jr,""):q;if(Z===""){if(z++,z<=G)K.push("")}else z=0,K.push(Z)}}else K=Pa(M,Math.max(0,E.format.maxConsecutiveBlankLines));let W=K.join(`
72
- `);if(W=W.replace(ya,""),_r(P))W=p(W);if(ba(P)){let z=Ea(W,E);if(z!==W)W=z}if(wa(P)){let z=Ba(W,P);if(z!=null)W=z}if($a(P,W))W=Ca(W,E);else if(_r(P))W=Na(W,E);else W=Oa(W,E.format.quotes,P);if(E.format.finalNewline==="none")return W.replace(/\n+$/g,"");let V=/[^\n]\n$/.test(W)||W===`
73
- `,U=/\n\n$/.test(W);if(E.format.finalNewline==="two"){if(U)return W;if(V)return`${W}
74
- `;return`${W}
75
-
76
- `}if(U)return W.replace(/\n\n$/,`
77
- `);if(V)return W;return`${W}
78
- `}function vs(C,E,P,x){for(let M=E+1;M<C.length;M++){let K=C[M];if(K==="\\"){M++;continue}if(K===P)return!0;if(K===x)return!1}return!0}function k(C,E){if(/^\s*\/\/\/\s*<reference/.test(C))return[];let P=[],x=null,M=!1;for(let K=0;K<C.length;K++){let W=C[K];if(M){M=!1;continue}if(W==="\\"){M=!0;continue}if(!x){if(W==="/"&&C[K+1]==="/")break;if(W==="'"){if(E==="double"&&vs(C,K,"'",'"'))P.push(K);x="single";continue}else if(W==='"'){if(E==="single"&&vs(C,K,'"',"'"))P.push(K);x="double";continue}else if(W==="`"){x="template";continue}}else if(x==="single"&&W==="'"||x==="double"&&W==='"'||x==="template"&&W==="`"){x=null;continue}}return P}function y(C,E,P="spaces",x){if(P==="tabs")return/[^\t]/.test(C);if(/\t/.test(C))return!0;let M=C.length;if(x&&M%E===1){let K=x.trimStart();if(K.startsWith("* ")||K.startsWith("*/")||K==="*")return!1}return M%E!==0}function xs(C,E){let P=E+1;while(P<C.length){let x=C[P];if(x==="\\"){P+=2;continue}if(x==="`")return P+1;if(x==="$"&&C[P+1]==="{"){P+=2;let M=1;while(P<C.length&&M>0){let K=C[P];if(K==="\\"){P+=2;continue}if(K==="`"){P=xs(C,P);continue}if(K==="'"||K==='"'){P=Es(C,P,K);continue}if(K==="{")M++;else if(K==="}")M--;P++}continue}P++}return P}var Ma=new Set(["return","typeof","instanceof","in","of","new","delete","void","do","else","case","yield","await"]);function ks(C,E){let P=E-1;while(P>=0&&(C[P]===" "||C[P]==="\t"))P--;if(P<0)return!0;let x=C[P];if("(,=:[!&|?;{}<>+-*%^~".includes(x))return!0;if(/[\w$]/.test(x)){let M=P;while(M>=0&&/[\w$]/.test(C[M]))M--;return Ma.has(C.slice(M+1,P+1))}return!1}function Ss(C,E){let P=E+1,x=!1,M=-1;while(P<C.length){let K=C[P];if(K==="\\"){P+=2;continue}if(K==="["&&!x)x=!0,M=P;else if(K==="]"&&x){let W=C[M+1]==="^"?M+2:M+1;if(P!==W)x=!1}else if(K==="/"&&!x){P++;while(P<C.length&&/[a-z]/i.test(C[P]))P++;return P}P++}return-1}function Da(C){if(!C.includes("'")&&!C.includes('"')&&!C.includes("`")&&!C.includes("/"))return{text:C,strings:[]};let E=[],P=[],x=0,M=0;while(x<C.length){let K=C[x];if(K==="/"){let W=C[x+1];if(W==="/"){if(x>M)P.push(C.slice(M,x));E.push(C.slice(x)),P.push(`@@S${E.length-1}@@`),M=C.length;break}if(W==="*"){let V=C.indexOf("*/",x+2),U=V===-1?C.length:V+2;if(x>M)P.push(C.slice(M,x));E.push(C.slice(x,U)),P.push(`@@S${E.length-1}@@`),x=U,M=x;continue}if(ks(C,x)){let V=Ss(C,x);if(V!==-1){if(x>M)P.push(C.slice(M,x));E.push(C.slice(x,V)),P.push(`@@S${E.length-1}@@`),x=V,M=x;continue}}x++;continue}if(K==="'"||K==='"'||K==="`"){if(x>M)P.push(C.slice(M,x));let W=x;if(K==="`")x=xs(C,x);else{let V=K;x++;while(x<C.length){if(C[x]==="\\"){x+=2;continue}if(C[x]===V){x++;break}x++}}E.push(C.slice(W,x)),P.push(`@@S${E.length-1}@@`),M=x;continue}x++}if(M<C.length)P.push(C.slice(M));return{text:P.join(""),strings:E}}function La(C,E){if(E.length===0)return C;return C.replace(/@@S(\d+)@@/g,(P,x)=>E[Number(x)]??"")}function Ia(C){let E=new Set,P=/[$A-Z_][\w$]*/gi,x=P.exec(C);while(x!==null)E.add(x[0]),x=P.exec(C);return E}function p(C){let E=C[0];if(E!=="i"&&E!==" "&&E!=="\t"&&E!=="/"&&E!==`
79
- `)return C;let P=C.split(`
80
- `),x=[],M=[],K=[],W=0,V=0,U=-1,z=!1;while(W<P.length){let X=P[W];if(ps.test(X)){W++;continue}if(ma.test(X)||ys.test(X)){let ce=W;if(ys.test(X)){while(W<P.length&&!P[W].includes("*/"))W++;W++}else W++;if(!z){for(let Te=ce;Te<W&&Te<P.length;Te++)M.push(P[Te]);V=W}else if(U<0)U=ce;continue}if(!ha.test(X))break;let Q=X.trim(),Ee=W+1;while(!ws.test(Q)&&Ee<P.length&&Ee-W<50)Q+=` ${P[Ee].trim()}`,Ee++;if(!ws.test(Q))return C;let me=_a(Q);if(!me)return C;if(U>=0){for(let ce=U;ce<W;ce++)if(!ps.test(P[ce]))K.push(P[ce]);U=-1}x.push(me),W=Ee,V=W,z=!0}if(x.length===0)return C;let G=U>=0?U:V,J=P.slice(G).join(`
81
- `),q=Ia(J),Y=(X)=>q.has(X);for(let X of x){if(X.kind!=="value")continue;X.named=X.named.filter((Q)=>{if(Q.alias)return!0;return Y(Q.name)})}let ee=x.filter((X)=>{if(X.kind==="side-effect")return!0;if(X.kind==="type")return X.namedTypes.length>0;return Boolean(X.defaultName||X.namespaceName||X.named.length>0)}),H=new Map;for(let X of ee){let Q=H.get(X.source)||{};if(X.kind==="side-effect")Q.side=Q.side||[],Q.side.push(X);else if(X.kind==="type"){if(!Q.type)Q.type={kind:"type",source:X.source,named:[],namedTypes:[],original:""};Q.type.namedTypes=(Q.type.namedTypes||[]).concat(X.namedTypes)}else{if(!Q.value)Q.value={kind:"value",source:X.source,named:[],namedTypes:[],original:""};if(X.defaultName)Q.value.defaultName=X.defaultName;if(X.namespaceName)Q.value.namespaceName=X.namespaceName;if(Q.value.named=(Q.value.named||[]).concat(X.named),X.namedTypes.length>0){if(!Q.type)Q.type={kind:"type",source:X.source,named:[],namedTypes:[],original:""};Q.type.namedTypes=Q.type.namedTypes.concat(X.namedTypes)}}H.set(X.source,Q)}let Z=[];for(let[X,Q]of H){if(Q.side)Z.push(...Q.side);if(Q.value){let Ee=(me)=>{if(!me.alias)return me;return/^[A-Z]$/i.test(me.name)&&/^[A-Z]$/i.test(me.alias)?{name:me.alias,alias:me.name}:me};Q.value.named=Q.value.named.map(Ee),Q.value.named.sort((me,ce)=>me.name.localeCompare(ce.name)),Z.push(Q.value)}if(Q.type&&Q.type.namedTypes.length>0){let Ee=new Set,me=(ce)=>{if(!ce.alias)return ce;return/^[A-Z]$/i.test(ce.name)&&/^[A-Z]$/i.test(ce.alias)?{name:ce.alias,alias:ce.name}:ce};Q.type.namedTypes=Q.type.namedTypes.map(me).filter((ce)=>{let Te=`${ce.name}|${ce.alias||""}`;if(Ee.has(Te))return!1;return Ee.add(Te),!0}),Q.type.namedTypes.sort((ce,Te)=>ce.name.localeCompare(Te.name)),Z.push(Q.type)}}let te=(X)=>X.startsWith(".")?2:X.startsWith("node:")?0:1,re=(X)=>{if(X.kind!=="value")return 99;if(X.defaultName)return 0;if(X.namespaceName)return 1;return 2};Z.sort((X,Q)=>{if(X.kind!==Q.kind){if(X.kind==="type")return-1;if(Q.kind==="type")return 1;if(X.kind==="side-effect")return-1;if(Q.kind==="side-effect")return 1}if(X.kind==="type"&&Q.kind==="type"){let Ee=te(X.source),me=te(Q.source);if(Ee!==me)return Ee-me;return X.source.localeCompare(Q.source)}if(X.kind==="value"&&Q.kind==="value"){let Ee=te(X.source),me=te(Q.source);if(Ee!==me)return Ee-me;let ce=re(X),Te=re(Q);if(ce!==Te)return ce-Te;return X.source.localeCompare(Q.source)}return X.source.localeCompare(Q.source)});let fe=M.length>0?`${M.join(`
82
- `)}
83
- `:"";if(Z.length===0){let X=J.replace(/^\n+/,""),Q=[...K];if(fe||Q.length>0)return`${fe}${Q.length>0?`${Q.join(`
84
- `)}
85
- `:""}${X}`;return X}let Ce=Z.map(ja).join(`
86
- `),we=K.length>0?`
87
- ${K.join(`
88
- `)}`:"",Se=J.replace(/^\n+/,""),Fs=Se.length>0?`
89
-
90
- `:`
91
- `;return`${fe}${Ce}${we}${Fs}${Se}`}function ja(C){if(C.kind==="side-effect")return`import '${C.source}'`;if(C.kind==="type")return`import type { ${C.namedTypes.map((M)=>M.alias?`${M.name} as ${M.alias}`:M.name).join(", ")} } from '${C.source}'`;let E=[];if(C.defaultName)E.push(C.defaultName);if(C.namespaceName)E.push(`* as ${C.namespaceName}`);if(C.named.length>0){let x=C.named.map((M)=>M.alias?`${M.name} as ${M.alias}`:M.name).join(", ");E.push(`{ ${x} }`)}return`import ${E.join(", ")} from '${C.source}'`}function _a(C){let E=C.match(/^\s*import\s+['"]([^'"]+)['"]/);if(E)return{kind:"side-effect",source:E[1],named:[],namedTypes:[],original:C};if(E=C.match(/^\s*import\s+type\s+\{([^}]*)\}\s+from\s+['"]([^'"]+)['"]/),E){let q=E[1],Y=E[2],ee=q.split(",").map((H)=>H.trim()).filter(Boolean).map((H)=>{let Z=H.match(/^(\w+)(?:\s+as\s+(\w+))?$/);return{name:Z?.[1]||H,alias:Z?.[2]}});return{kind:"type",source:Y,named:[],namedTypes:ee,original:C}}let P=C.match(/^\s*import\s+/),x=new RegExp(`\\sfrom\\s+['"]([^'"]+)['"]\\s*;?$`),M=C.match(x);if(!P||!M)return;let K=M[1],W=C.slice(P[0].length,M.index).trim(),V,U,z=[],G=[],J=W.match(/\{([^}]*)\}/);if(J){let Y=J[1].split(",").map((ee)=>ee.trim()).filter(Boolean);for(let ee of Y){let H=/^type\s+/.test(ee),te=ee.replace(/^type\s+/,"").match(/^(\w+)(?:\s+as\s+(\w+))?$/);if(!te)continue;let re={name:te[1],alias:te[2]};if(H)G.push(re);else z.push(re)}W=W.replace(/\{[\s\S]*?\}/,"").trim()}if(W.length>0){let q=W.split(",").map((Y)=>Y.trim()).filter(Boolean);for(let Y of q)if(Y.startsWith("* as "))U=Y.slice(5).trim();else if(/^\w+$/.test(Y))V=Y}return{kind:"value",source:K,defaultName:V,namespaceName:U,named:z,namedTypes:G,original:C}}function Ba(C,E){if(da.test(E))return Ka(C);if(pa.test(E))return Wa(C);return null}function Ts(C){try{return JSON.parse(C)}catch{return null}}function lt(C,E,P=[]){let x={};for(let K of E)if(Object.prototype.hasOwnProperty.call(C,K))x[K]=C[K];for(let K of P){let W=Object.keys(C).filter((V)=>K.test(V)&&!(V in x)).sort();for(let V of W)x[V]=C[V]}let M=Object.keys(C).filter((K)=>!(K in x)).sort();for(let K of M)x[K]=C[K];return x}function $s(C){let E={};for(let P of Object.keys(C).sort())E[P]=C[P];return E}function Ka(C){let E=Ts(C);if(!E||typeof E!=="object")return C;let x=lt(E,["publisher","name","displayName","type","version","private","packageManager","description","author","contributors","license","funding","homepage","repository","bugs","keywords","categories","sideEffects","imports","exports","main","module","unpkg","jsdelivr","types","typesVersions","bin","icon","files","engines","activationEvents","contributes","scripts","peerDependencies","peerDependenciesMeta","dependencies","optionalDependencies","devDependencies","pnpm","overrides","resolutions","husky","simple-git-hooks","lint-staged","eslintConfig"]);if(Array.isArray(x.files)){if(x.files.every((W)=>typeof W==="string"))x.files=[...x.files].sort()}for(let K of Object.keys(x))if(/^(?:dev|peer|optional|bundled)?[Dd]ependencies(?:Meta)?$/.test(K)||/^(?:resolutions|overrides|pnpm\.overrides)$/.test(K)){if(x[K]&&typeof x[K]==="object")x[K]=$s(x[K])}if(x.pnpm&&typeof x.pnpm==="object"&&x.pnpm.overrides&&typeof x.pnpm.overrides==="object")x.pnpm.overrides=$s(x.pnpm.overrides);if(x.exports&&typeof x.exports==="object"){let K=x.exports,W=["types","import","require","default"];if(!Array.isArray(K)){let V={};for(let U of Object.keys(K)){let z=K[U];if(z&&typeof z==="object"&&!Array.isArray(z))V[U]=lt(z,W);else V[U]=z}x.exports=V}}let M=["pre-commit","prepare-commit-msg","commit-msg","post-commit","pre-rebase","post-rewrite","post-checkout","post-merge","pre-push","pre-auto-gc"];for(let K of["gitHooks","husky","simple-git-hooks"])if(x[K]&&typeof x[K]==="object")x[K]=lt(x[K],M);return JSON.stringify(x,null,2)}function Wa(C){let E=Ts(C);if(!E||typeof E!=="object")return C;let x=lt(E,["extends","compilerOptions","references","files","include","exclude"]);if(x.compilerOptions&&typeof x.compilerOptions==="object"){let M=["incremental","composite","tsBuildInfoFile","disableSourceOfProjectReferenceRedirect","disableSolutionSearching","disableReferencedProjectLoad","target","jsx","jsxFactory","jsxFragmentFactory","jsxImportSource","lib","moduleDetection","noLib","reactNamespace","useDefineForClassFields","emitDecoratorMetadata","experimentalDecorators","libReplacement","baseUrl","rootDir","rootDirs","customConditions","module","moduleResolution","moduleSuffixes","noResolve","paths","resolveJsonModule","resolvePackageJsonExports","resolvePackageJsonImports","typeRoots","types","allowArbitraryExtensions","allowImportingTsExtensions","allowUmdGlobalAccess","allowJs","checkJs","maxNodeModuleJsDepth","strict","strictBindCallApply","strictFunctionTypes","strictNullChecks","strictPropertyInitialization","allowUnreachableCode","allowUnusedLabels","alwaysStrict","exactOptionalPropertyTypes","noFallthroughCasesInSwitch","noImplicitAny","noImplicitOverride","noImplicitReturns","noImplicitThis","noPropertyAccessFromIndexSignature","noUncheckedIndexedAccess","noUnusedLocals","noUnusedParameters","useUnknownInCatchVariables","declaration","declarationDir","declarationMap","downlevelIteration","emitBOM","emitDeclarationOnly","importHelpers","importsNotUsedAsValues","inlineSourceMap","inlineSources","mapRoot","newLine","noEmit","noEmitHelpers","noEmitOnError","outDir","outFile","preserveConstEnums","preserveValueImports","removeComments","sourceMap","sourceRoot","stripInternal","allowSyntheticDefaultImports","esModuleInterop","forceConsistentCasingInFileNames","isolatedDeclarations","isolatedModules","preserveSymlinks","verbatimModuleSyntax","erasableSyntaxOnly","skipDefaultLibCheck","skipLibCheck"];x.compilerOptions=lt(x.compilerOptions,M)}return JSON.stringify(x,null,2)}import{readdirSync as Va,readFileSync as Ua,statSync as Os}from"fs";import{extname as za,isAbsolute as Wr,join as Vr,resolve as Ga}from"path";var b=5;function Ja(C){let E="",P=0;while(P<C.length){let x=C[P];if(x==="*")if(C[P+1]==="*"){if(E+=".*",P+=2,C[P]==="/")P++}else E+="[^/]*",P++;else if(x==="?")E+="[^/]",P++;else if(x==="["){let M=C.indexOf("]",P);if(M===-1)E+="\\[",P++;else E+=C.slice(P,M+1),P=M+1}else if(".+^${}()|\\".includes(x))E+=`\\${x}`,P++;else E+=x,P++}return new RegExp(`^${E}$`)}function*Rs(C,E,P){let x;try{x=Va(C)}catch{return}for(let M of x){if(!P&&M.startsWith("."))continue;let K=Vr(C,M);if(E(K))continue;let W;try{W=Os(K)}catch{continue}if(W.isDirectory())yield*Rs(K,E,P);else yield K}}function*As(C,E,P,x){yield*Rs(C,c(E,x),P)}async function i(C,E={}){let P=E.cwd??process.cwd(),x=E.ignore??[],M=E.dot??!1,K=E.absolute??!0,W=c(x,P);if(typeof globalThis.Bun?.Glob<"u"){let U=globalThis.Bun.Glob,z=[];for(let G of C){let J=new U(G);for await(let q of J.scan({cwd:P,dot:M,onlyFiles:E.onlyFiles??!0,followSymlinks:!1})){let Y=Wr(q)?q:Vr(P,q),ee=Y.startsWith(`${P}/`)?Y.slice(P.length+1):Y;if(W(Y))continue;z.push(K?Y:ee)}}return z}let V=[];for(let U of C){if(!/[*?[{]/.test(U)){let G=Wr(U)?U:Vr(P,U);try{if(!Os(G).isDirectory()){let q=G.startsWith(`${P}/`)?G.slice(P.length+1):G;if(!W(G))V.push(K?G:q)}else for(let q of As(G,x,M,P))V.push(K?q:q.startsWith(`${P}/`)?q.slice(P.length+1):q)}catch{}continue}let z=Ja(U);for(let G of As(P,x,M,P)){let J=G.startsWith(`${P}/`)?G.slice(P.length+1):G;if(z.test(J)||z.test(J.replace(/\\/g,"/")))V.push(K?G:J)}}return V}function D(C){let E=0,P=[],x=()=>{if(P.length>0&&E<C)E++,P.shift()()};return(M)=>new Promise((K,W)=>{let V=()=>{M().then((U)=>{E--,K(U),x()},(U)=>{E--,W(U),x()})};if(E<C)E++,V();else P.push(V)})}var n={get TRACE(){return process.env.PICKIER_TRACE==="1"},get TIMEOUT_MS(){return Number(process.env.PICKIER_TIMEOUT_MS||"8000")},get RULE_TIMEOUT_MS(){return Number(process.env.PICKIER_RULE_TIMEOUT_MS||"5000")},get CONCURRENCY(){return Number(process.env.PICKIER_CONCURRENCY)||8},get DIAGNOSTICS(){return process.env.PICKIER_DIAGNOSTICS==="1"},get FAIL_ON_WARNINGS(){return process.env.PICKIER_FAIL_ON_WARNINGS==="1"},get NO_AUTO_CONFIG(){return process.env.PICKIER_NO_AUTO_CONFIG==="1"}},R=["**/node_modules/**","**/.git/**"],o=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.vercel/**","**/.netlify/**","**/.cache/**","**/.turbo/**","**/.vscode/**","**/.idea/**","**/.zed/**","**/.cursor/**","**/.claude/**","**/.github/**","**/coverage/**","**/.nyc_output/**","**/.tmp/**","**/.temp/**","**/vendor/**","**/pantry/**","**/target/**","**/zig-cache/**","**/zig-out/**","**/.zig-cache/**","**/__pycache__/**","**/.pytest_cache/**","**/venv/**","**/.venv/**","**/out/**","**/.DS_Store","**/Thumbs.db"];function v(C,E){let P=C[E];if(P===void 0){let K=E.indexOf("/");if(K>0){let W=E.slice(0,K),V=E.slice(K+1),U=W==="general"?"pickier":W==="pickier"?"general":null;if(U)P=C[`${U}/${V}`];if(P===void 0)P=C[V]}}let x,M;if(typeof P==="string"){if(P==="error")x="error";else if(P==="warn"||P==="warning")x="warning"}else if(Array.isArray(P)&&typeof P[0]==="string"){let K=P[0];if(K==="error")x="error";else if(K==="warn"||K==="warning")x="warning";M=P[1]}return{enabled:!!x,severity:x,options:M}}function g(C){let E=Array.isArray(C)?C[0]:C;if(typeof E!=="string")return;if(E==="off")return"off";if(E==="error")return"error";if(E==="warn"||E==="warning")return"warning";return}function a(C,E,P=[],x){for(let K of[E,...P]){let W=g(C.rules?.[K])??g(C.pluginRules?.[K]);if(W)return W==="off"?void 0:W}let M=g(x);return M==="off"?void 0:M}function j(C,E){return g(C.rules?.[E])==="off"||g(C.pluginRules?.[E])==="off"}function h(C,E){return`\x1B[${C}m${E}\x1B[0m`}function T(C){return h("32",C)}function L(C){return h("31",C)}function A(C){return h("33",C)}function O(C){return h("34",C)}function _(C){return h("90",C)}function N(C){return h("1",C)}var e={green:T,red:L,yellow:A,blue:O,gray:_,bold:N};function m(C,E){let P=E.ignores?[...new Set([...C.ignores||[],...E.ignores])]:C.ignores,x={...C.pluginRules||{},...E.pluginRules||{}};if((E.tailwind??C.tailwind)?.enabled&&!Object.prototype.hasOwnProperty.call(x,"pickier/sort-tailwind-classes"))x["pickier/sort-tailwind-classes"]="warn";return{...C,...E,verbose:E.verbose??C.verbose,ignores:P,lint:{...C.lint,...E.lint||{}},format:{...C.format,...E.format||{}},rules:{...C.rules,...E.rules||{}},pluginRules:x}}var Kr=null;async function u(C){if(!C){if(n.NO_AUTO_CONFIG){if(!Kr)Kr=m(s,{});return Kr}try{let{getConfig:x}=await import("./chunk-ek25vxkw.js"),M=await x();return m(s,M)}catch{}return m(s,{})}let E=Wr(C)?C:Ga(process.cwd(),C);if(za(E).toLowerCase()===".json")try{let x=Ua(E,"utf8");return m(s,JSON.parse(x))}catch{return console.warn(`[pickier:warn] Config file not found: ${E}. Using default config values.`),m(s,{})}try{let x=await import(E);return m(s,x.default||x)}catch{return console.warn(`[pickier:warn] Config file not found: ${E}. Using default config values.`),m(s,{})}}function d(C){return C.map((E)=>{if(/[*?[\]{}()!]/.test(E))return E;if(/\.[A-Z0-9]+$/i.test(E))return E;return`${E.replace(/\/$/,"")}/**/*`})}function w(C,E){let P=C.lastIndexOf(".");if(P<0)return!1;let x=C.slice(P);return E.has(x)}function Ur(C){return C.replace(/\\/g,"/").replace(/\/+/g,"/")}function qa(C){let E=[];for(let P of C){let x=Ur(P.trim());if(!x)continue;let M=x.match(/\*\*\/\*\.(.+)$/);if(M){E.push({raw:x,kind:"extension",value:M[1]});continue}let K=x.match(/\*\*\/(.+?)\/\*\*$/);if(K){E.push({raw:x,kind:"segment",value:K[1]});continue}let W=x.match(/\*\*\/(.+)$/);if(W)E.push({raw:x,kind:"suffix",value:W[1].replace(/\/$/,"")})}return E}function l(C){return[...new Set([...R,...C])]}function c(C,E=process.cwd()){let P=qa([...R,...C]);if(P.length===0)return()=>!1;let x=new Set([...o,...R]);return(M)=>{let K=Ur(M),W=Ur(E).replace(/\/$/,""),V=K!==W&&!K.startsWith(`${W}/`),U=V?K:K.slice(W.length);for(let z of P){if(V&&!x.has(z.raw))continue;if(z.kind==="extension"){if(U.endsWith(`.${z.value}`))return!0;continue}if(z.kind==="segment"||z.kind==="suffix"){let G=z.value;if(U.includes(`/${G}/`)||U.endsWith(`/${G}`))return!0}}return!1}}function B(C,E){return c(E)(C)}async function I(C,E){let P=E.mode||"auto";if(P==="format"&&C.length===1&&!/[*?[\]{}()!]/.test(C[0]))try{let W=C[0],V=Xa(W)?W:Qa(process.cwd(),W);if(Ha(V).isFile()){let z=await u(E.config),G=Ya(V,"utf8"),J=f(G,z,V);if(E.check&&J!==G)return 1;if(E.write&&J!==G)Za(V,J,"utf8");return 0}}catch{}let{runLint:x}=await import("./chunk-5dpt7qv4.js");if(P==="lint")return x(C,E);if(P==="format"){let W={...E,fix:!0,dryRun:!!E.check,ext:E.ext,_formatOnly:!0};return x(C,W)}if(!(E.fix===!0||E.write===!0||E.check===!0))return x(C,E);let K={...E,fix:!0,dryRun:!!E.check,ext:E.ext};return x(C,K)}
92
- export{s,F,S,r,t,f,k,y,p,b,i,D,n,R,o,v,g,a,j,h,T,L,A,O,_,N,e,m,u,d,w,l,c,B,I};