@buddysh/buddy 0.11.10 → 0.11.12

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 (159) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/bin/cli.js +19 -19
  3. package/dist/{chunk-p9z0hzej.js → chunk-08daxhzx.js} +2 -2
  4. package/dist/{chunk-ja3rvd6y.js → chunk-0f1xye20.js} +1 -1
  5. package/dist/{chunk-be059ncv.js → chunk-0g4ybxwj.js} +2 -2
  6. package/dist/{chunk-2m0134q8.js → chunk-0m1z85m9.js} +1 -1
  7. package/dist/chunk-0m6b7bac.js +2 -0
  8. package/dist/{chunk-6xzzs109.js → chunk-0rbxek2f.js} +2 -2
  9. package/dist/chunk-0sm25gee.js +2 -0
  10. package/dist/chunk-11p0az6f.js +2 -0
  11. package/dist/{chunk-xny4kgcc.js → chunk-142zh7e5.js} +1 -1
  12. package/dist/chunk-16fr8xqp.js +2 -0
  13. package/dist/{chunk-jpdd59fh.js → chunk-1pecmenc.js} +1 -1
  14. package/dist/chunk-1w1h2tsf.js +2 -0
  15. package/dist/{chunk-nwrr6jas.js → chunk-1xe0960b.js} +2 -2
  16. package/dist/chunk-225s199d.js +2 -0
  17. package/dist/{chunk-a34szd4r.js → chunk-24xnjkvz.js} +3 -3
  18. package/dist/{chunk-emygmh7r.js → chunk-24xvskkf.js} +1 -1
  19. package/dist/{chunk-6wxwewbh.js → chunk-2e4e6zjs.js} +1 -1
  20. package/dist/{chunk-7bctsv0x.js → chunk-2hb8dan0.js} +1 -1
  21. package/dist/{chunk-z21tw4fz.js → chunk-2jjrxgs1.js} +2 -2
  22. package/dist/chunk-2z2gh050.js +44 -0
  23. package/dist/{chunk-6k6dgwmy.js → chunk-2z9pkk1y.js} +1 -1
  24. package/dist/{chunk-9m0epv44.js → chunk-33h1me7n.js} +2 -2
  25. package/dist/{chunk-khn11t39.js → chunk-3c114myc.js} +1 -1
  26. package/dist/{chunk-xffrrs85.js → chunk-3n4w3ak9.js} +11 -11
  27. package/dist/{chunk-rg996jqw.js → chunk-40pvn33p.js} +1 -1
  28. package/dist/{chunk-k3x0mabj.js → chunk-42xvqxdw.js} +2 -2
  29. package/dist/{chunk-1m5wprvm.js → chunk-54er1whp.js} +2 -2
  30. package/dist/{chunk-y7z0br2x.js → chunk-59993g25.js} +1 -1
  31. package/dist/{chunk-7crh00m7.js → chunk-5jvde2as.js} +2 -2
  32. package/dist/{chunk-y9senfb6.js → chunk-5pheqk23.js} +1 -1
  33. package/dist/{chunk-drkzf2gz.js → chunk-62j8q7sg.js} +1 -1
  34. package/dist/chunk-64kt1w23.js +2 -0
  35. package/dist/{chunk-4akhxmfk.js → chunk-65by8f14.js} +1 -1
  36. package/dist/chunk-6gdenphk.js +2 -0
  37. package/dist/{chunk-gzjxhd7a.js → chunk-750ae48c.js} +2 -2
  38. package/dist/{chunk-mdbf728w.js → chunk-77qe887p.js} +1 -1
  39. package/dist/{chunk-mg3em5qj.js → chunk-7b4jsg36.js} +2 -2
  40. package/dist/{chunk-hkb714k3.js → chunk-7c1284fb.js} +1 -1
  41. package/dist/chunk-7m1ab6p8.js +2 -0
  42. package/dist/{chunk-bggpgbdx.js → chunk-7m3pzkcj.js} +1 -1
  43. package/dist/chunk-81y75fg7.js +2 -0
  44. package/dist/{chunk-04qvf24t.js → chunk-89jytkd6.js} +1 -1
  45. package/dist/{chunk-bjymeq7e.js → chunk-8swwcx7w.js} +1 -1
  46. package/dist/{chunk-yxb1jwxp.js → chunk-9sdgy9nm.js} +2 -2
  47. package/dist/chunk-a30cyqr0.js +2 -0
  48. package/dist/{chunk-ysgex7h7.js → chunk-a3zgenkh.js} +1 -1
  49. package/dist/chunk-a56s1xrt.js +2 -0
  50. package/dist/{chunk-7ds5q6j3.js → chunk-apdrg3r7.js} +1 -1
  51. package/dist/chunk-axazt516.js +2 -0
  52. package/dist/{chunk-88xaexj1.js → chunk-b3s185kp.js} +1 -1
  53. package/dist/chunk-b59zbkfx.js +2 -0
  54. package/dist/{chunk-a3bnhq58.js → chunk-b9szrnxw.js} +1 -1
  55. package/dist/{chunk-89s9f3mf.js → chunk-bnp0r4eh.js} +1 -1
  56. package/dist/{chunk-se4g70q2.js → chunk-bsh3kp53.js} +1 -1
  57. package/dist/{chunk-k7x9af5r.js → chunk-c6ptrc0v.js} +2 -2
  58. package/dist/{chunk-vckn5ate.js → chunk-cj4d5ad7.js} +1 -1
  59. package/dist/{chunk-6w8vxy7s.js → chunk-cm6devhe.js} +1 -1
  60. package/dist/{chunk-34rmja4x.js → chunk-ctdfppxk.js} +2 -2
  61. package/dist/{chunk-jxd64dzs.js → chunk-cvwkdfvr.js} +1 -1
  62. package/dist/{chunk-amj037yy.js → chunk-d4gk9awk.js} +3 -3
  63. package/dist/{chunk-61gfjcqt.js → chunk-dd895pm0.js} +1 -1
  64. package/dist/{chunk-h8e796qs.js → chunk-ddky3026.js} +1 -1
  65. package/dist/{chunk-rrnvxj90.js → chunk-dsnd6ndd.js} +1 -1
  66. package/dist/{chunk-3waqfh3y.js → chunk-enq0gm64.js} +2 -2
  67. package/dist/{chunk-pmszvhja.js → chunk-esm5jjgf.js} +1 -1
  68. package/dist/chunk-esveeark.js +2 -0
  69. package/dist/chunk-ffbbc38r.js +2 -0
  70. package/dist/{chunk-fpzgxg8a.js → chunk-fmkb816y.js} +1 -1
  71. package/dist/chunk-g4803nvq.js +2 -0
  72. package/dist/{chunk-kh6v93yb.js → chunk-gpjde0j6.js} +2 -2
  73. package/dist/{chunk-4wbbbcs2.js → chunk-gweqk008.js} +2 -2
  74. package/dist/{chunk-kpdz73mc.js → chunk-hc651afv.js} +1 -1
  75. package/dist/{chunk-88j356ng.js → chunk-j46f90n8.js} +1 -1
  76. package/dist/chunk-jhz202wk.js +2 -0
  77. package/dist/{chunk-1szfwcst.js → chunk-jqh7vx2n.js} +1 -1
  78. package/dist/{chunk-qdmr84mc.js → chunk-k3r7v3dp.js} +2 -2
  79. package/dist/{chunk-s3ksf6s5.js → chunk-kbvj6qxc.js} +1 -1
  80. package/dist/{chunk-gvnsr72j.js → chunk-knpdntnh.js} +1 -1
  81. package/dist/chunk-kq0n3x2e.js +2 -0
  82. package/dist/{chunk-ktmgq0ja.js → chunk-ktn47bq8.js} +1 -1
  83. package/dist/chunk-ktzvchps.js +2 -0
  84. package/dist/chunk-m1zv8db4.js +2 -0
  85. package/dist/{chunk-d7jpbw1z.js → chunk-mt53v4sx.js} +1 -1
  86. package/dist/{chunk-90q6r1j7.js → chunk-nbyxgt9c.js} +1 -1
  87. package/dist/chunk-njrezpsw.js +2 -0
  88. package/dist/{chunk-gyf7psxg.js → chunk-nkztawjh.js} +1 -1
  89. package/dist/chunk-pegk4jhq.js +2 -0
  90. package/dist/{chunk-q90s02qc.js → chunk-q7y8dvbz.js} +1 -1
  91. package/dist/{chunk-wjmp2hsj.js → chunk-qdr900z7.js} +1 -1
  92. package/dist/chunk-rphwf28s.js +2 -0
  93. package/dist/chunk-rr8apsh5.js +2 -0
  94. package/dist/{chunk-db9rffcf.js → chunk-rxf8h1e5.js} +1 -1
  95. package/dist/{chunk-jj1gjkb7.js → chunk-ry5zh9cx.js} +1 -1
  96. package/dist/{chunk-785rgtn5.js → chunk-rygtb1x3.js} +5 -5
  97. package/dist/chunk-s1cgwkkr.js +3 -0
  98. package/dist/{chunk-7rjrea9g.js → chunk-sxfk3naz.js} +2 -2
  99. package/dist/chunk-tjvvb919.js +2 -0
  100. package/dist/chunk-tzmj8w3x.js +2 -0
  101. package/dist/{chunk-tx9m7y1z.js → chunk-v0y8eens.js} +2 -2
  102. package/dist/chunk-v9fnbdgr.js +2 -0
  103. package/dist/{chunk-ggzjv4s0.js → chunk-va3k91tf.js} +1 -1
  104. package/dist/{chunk-hdqmcp3n.js → chunk-vmt1bed1.js} +1 -1
  105. package/dist/chunk-vpsvtb9v.js +2 -0
  106. package/dist/{chunk-pxdrwhxx.js → chunk-vpw7adwd.js} +1 -1
  107. package/dist/{chunk-8tsw3cjk.js → chunk-vs68hsbp.js} +1 -1
  108. package/dist/{chunk-2145m12g.js → chunk-vtr2vbk0.js} +1 -1
  109. package/dist/{chunk-4hd1mryc.js → chunk-w55x2g9n.js} +2 -2
  110. package/dist/{chunk-hyp0wfta.js → chunk-wjfw6rx8.js} +2 -2
  111. package/dist/chunk-wt83nzn3.js +2 -0
  112. package/dist/{chunk-8dj94fsy.js → chunk-x1w6q9tk.js} +1 -1
  113. package/dist/{chunk-s3q7g2hy.js → chunk-xqveh8a5.js} +1 -1
  114. package/dist/chunk-xxwevpnr.js +2 -0
  115. package/dist/{chunk-wd8w0vjs.js → chunk-y3w8h4sy.js} +1 -1
  116. package/dist/{chunk-4c3dws2k.js → chunk-ycbk7tg9.js} +1 -1
  117. package/dist/chunk-yf01hyxn.js +2 -0
  118. package/dist/{chunk-srz5kgyg.js → chunk-yqfwvk9z.js} +1 -1
  119. package/dist/{chunk-0apd8zqn.js → chunk-z05djfac.js} +7 -7
  120. package/dist/{chunk-kpqez1ht.js → chunk-z18bksyr.js} +1 -1
  121. package/dist/{chunk-1tg7dfq5.js → chunk-zk8zdv23.js} +1 -1
  122. package/dist/src/index.js +1 -1
  123. package/dist/src/setup.js +1 -1
  124. package/dist/src/utils/lock-file.d.ts +19 -0
  125. package/package.json +1 -1
  126. package/dist/chunk-00vbhh0z.js +0 -2
  127. package/dist/chunk-0y706m2d.js +0 -2
  128. package/dist/chunk-1aee33aa.js +0 -2
  129. package/dist/chunk-1vhqtq6m.js +0 -2
  130. package/dist/chunk-2fx0tbc0.js +0 -2
  131. package/dist/chunk-3ggd7z2f.js +0 -2
  132. package/dist/chunk-3xbx315d.js +0 -2
  133. package/dist/chunk-4k9f9vn2.js +0 -2
  134. package/dist/chunk-4zvjzesh.js +0 -2
  135. package/dist/chunk-5dw0q5ng.js +0 -2
  136. package/dist/chunk-5qtdc2mb.js +0 -2
  137. package/dist/chunk-6gttmvww.js +0 -2
  138. package/dist/chunk-7f6mpphq.js +0 -2
  139. package/dist/chunk-7mmdxbcm.js +0 -2
  140. package/dist/chunk-7ze1qrmt.js +0 -2
  141. package/dist/chunk-9634xcvq.js +0 -2
  142. package/dist/chunk-97csq21c.js +0 -2
  143. package/dist/chunk-ea6rtyvy.js +0 -2
  144. package/dist/chunk-gs5b2ssa.js +0 -2
  145. package/dist/chunk-gw69sjx2.js +0 -2
  146. package/dist/chunk-j0fcqty9.js +0 -2
  147. package/dist/chunk-kszbmpw1.js +0 -2
  148. package/dist/chunk-mzb7cg8a.js +0 -2
  149. package/dist/chunk-pjq0qxst.js +0 -2
  150. package/dist/chunk-pksrcdh6.js +0 -2
  151. package/dist/chunk-tf9nqr0p.js +0 -2
  152. package/dist/chunk-tq1w2wwa.js +0 -2
  153. package/dist/chunk-w93akf6h.js +0 -2
  154. package/dist/chunk-wreexgkb.js +0 -44
  155. package/dist/chunk-x5jfh372.js +0 -2
  156. package/dist/chunk-ydt2sn0j.js +0 -2
  157. package/dist/chunk-z0qbkvyz.js +0 -2
  158. package/dist/chunk-zefqbamj.js +0 -2
  159. package/dist/chunk-zrg5ss0x.js +0 -3
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Zc as oX}from"./chunk-tx9m7y1z.js";import{cd as sX}from"./chunk-785rgtn5.js";import{Oh as iX}from"./chunk-8dj94fsy.js";import{dl as n}from"./chunk-s3ksf6s5.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{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(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 UQ(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 UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){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 H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
2
+ import{_c as oX}from"./chunk-v0y8eens.js";import{dd as sX}from"./chunk-rygtb1x3.js";import{Ph as iX}from"./chunk-x1w6q9tk.js";import{el as n}from"./chunk-kbvj6qxc.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{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(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 UQ(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 UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){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 H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
3
3
  `);for(let W of z)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:M.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let J=`${H} ${this.environment}.${Q.toUpperCase()}: ${U}
4
4
  `;if(G)J+=`${G}
5
5
  `;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!S()){let Y=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:M.blue("\u25D0"),tag:Y,message:`${M.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
@@ -59,4 +59,4 @@ export type ConfigOf = Config
59
59
  `,Y+=`|----------|------|-------------|----------|
60
60
  `;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
61
61
  `;return Y}}function nX(Q,X,Y={}){return LZ(Q,X,Y,new WeakMap)}function LZ(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:U}=Y;if(X===null||X===void 0)return H?Q:X;if(U){let G=U(Q,X);if(G!==void 0)return G}if(Array.isArray(X)||Array.isArray(Q))return KZ(Q,X,$,Z);if(!f(X)||!f(Q))return X;return C8(Q,X,Y,Z)}function KZ(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return T8(Q,X);case"smart":return O8(Q,X,Z);default:return X}return X}function T8(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>yX($,Z)))Y.push(Z);return Y}function O8(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(f(X[0])&&f(Q[0]))return N8(Q,X,Y);if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}function N8(Q,X,Y){let Z=[...X];for(let $ of Q){if(!f($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let G of H)if(G in $){if(Z.find((_)=>f(_)&&(G in _)&&_[G]===$[G])){U=!0;break}}if(!U)Z.push($)}return Z}function C8(Q,X,Y,Z){let $=X;if(f($)&&Z.has($))return Z.get($);let H={...Q};if(f($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let G=$[U],J=H[U];if(Y.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){H[U]=G;continue}if(f(G)&&f(J))H[U]=LZ(J,G,Y,Z);else if(Array.isArray(G)||Array.isArray(J))H[U]=KZ(J,G,Y.arrayMergeMode||"smart",Z);else H[U]=G}return H}function jZ(Q,X,Y="replace"){return nX(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function yX(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!yX(Q[Y],X[Y]))return!1;return!0}if(f(Q)&&f(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!yX(Q[$],X[$]))return!1}return!0}return!1}function f(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class IZ{extensions=mY;async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:U=!0,verbose:G=!1}=Y;if($){let _=pQ.getWithFileCheck("file",Q);if(_){if(G)console.log(`Configuration loaded from cache: ${Q}`);return _}}let J=async()=>{if(!bQ(Q))return null;try{let _=`?t=${Date.now()}`,q=await import(Q+_),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new aQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new aQ(Q,Error("Configuration must export a valid object"),"unknown");let R={config:jZ(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)pQ.setWithFileCheck("file",R,Q,H);return R}catch(_){throw _ instanceof Error?XQ.configLoad(Q,_):XQ.configLoad(Q,Error(String(_)))}};if(U)return vX.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){return VZ({name:Q,directory:X,alias:Y})}generateNamePatterns(Q,X){return uY({name:Q,alias:X})}checkFileAccess(Q){return E8(async()=>{return bQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!bQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let G=dY(Q,`${H}${U}`);if(await this.checkFileAccess(G))Z.push(G)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let G=dY(Q,U);if(await this.checkFileAccess(G))Z.push(G)}}catch{return[]}return Z}looksLikeConfigFile(Q){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((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!bQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),H=$(Q,"utf8");JSON.parse(H)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}var k8=/^https?:\/\//;class FZ{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:G=!0,verbose:J=!1}=Y,_=async()=>{let q=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:G,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...U],z);else return this.validateWithJSONSchema(Q,X,z)}catch(W){return q.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:q,warnings:A}}};if(G)return await vX.track("validateConfiguration",_);return _()}async validateWithSchemaFile(Q,X,Y){try{if(!x8(X))throw new eQ(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new eQ(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,H){if(H.validateTypes&&X.type){let U=Array.isArray(Q)?"array":typeof Q,G=Array.isArray(X.type)?X.type:[X.type];if(!G.includes(U)){if(Z.push({path:Y,message:`Expected type ${G.join(" or ")}, got ${U}`,expected:G.join(" or "),actual:U,rule:"type"}),H.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),H.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let U=0;U<Q.length;U++){let G=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let U=Q;if(H.validateRequired&&X.required){for(let G of X.required)if(!(G in U)){if(Z.push({path:Y?`${Y}.${G}`:G,message:`Missing required property '${G}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[G,J]of Object.entries(X.properties))if(G in U){let _=Y?`${Y}.${G}`:G;if(this.validateObjectAgainstSchema(U[G],J,_,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let G=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!G.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let U=this.getValueByPath(Q,H.path),G=this.validateWithRule(U,H,H.path);if(Z.push(...G),Y.stopOnFirstError&&Z.length>0)break}catch(U){Z.push({path:H.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,H,U]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(U)})}return X}mapTypeScriptType(Q){switch(Q.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:k8},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var u=new ZX("bunfig",{showTags:!0});function P8(Q){if(!Q)return"";let X=Array.isArray(Q)?Q.filter(Boolean):[Q];if(X.length===0)return"";if(X.length===1)return` or alias "${X[0]}"`;return` or aliases ${X.map((Y)=>`"${Y}"`).join(", ")}`}class MZ{fileLoader=new IZ;envProcessor=new lX;validator=new FZ;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...U}=Q;try{if(Y?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let G;try{G=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){if(U.configFile)throw J;let _=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(_)throw J;G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let q=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!q&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),z=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(_&&(z||q))throw J;if(A&&(!_||!z))G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!_)G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||H)await this.validateConfiguration(G.config,$,H,U.name);if(Y?.enabled&&G)this.cacheResult(U.name||"",G,Y,U);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:U.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)u.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);G.metrics=J}return G}catch(G){if(G instanceof Error&&G.name==="ConfigNotFoundError")throw G;let J=Date.now()-X;throw u.error(`Configuration loading failed after ${J}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,configFile:H,cwd:U,configDir:G,defaultConfig:J,checkEnv:_=!0,arrayStrategy:q="replace",verbose:A=!1}=Q,z=U||QX.cwd(),W=[];if(H){let V=l(z,H);W.push(V);let p=_?RQ(Z,J,A):J,v=await this.fileLoader.tryLoadFromPaths([V],p,{arrayStrategy:q,verbose:A,cacheTtl:Y?.ttl,useCache:!Y?.ttl||Y.ttl>100});if(!v)throw XQ.configNotFound(Z||H,W,$);if(A)u.success(`Configuration loaded from explicit path: ${V}`);return this.finalizeResult(v,W,_,Z,A)}let I=await this.loadLocalConfiguration(Z,$,z,G,J,q,A,_,Y);if(I)return W.push(...this.getLocalSearchPaths(Z,$,z,G)),this.finalizeResult(I,W,_,Z,A);let B=await this.loadHomeConfiguration(Z,$,J,q,A,_);if(B)return W.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(B,W,_,Z,A);let R=await this.loadPackageJsonConfiguration(Z,$,z,J,q,A,_);if(R)return W.push(l(z,"package.json")),this.finalizeResult(R,W,_,Z,A);if(W.push(...this.getAllSearchPaths(Z,$,z,G)),X)throw XQ.configNotFound(Z,W,$);return{...await this.applyEnvironmentVariables(Z,J,_,A),warnings:[`No configuration file found for "${Z}"${P8($)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,G,J){let _=G?RQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let A of q){if(U)u.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,_,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(W){if(U)u.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let U=H?RQ(Q,Y,$):Y,G=[l(ZQ(),".config",Q),l(ZQ(),".config"),ZQ()];for(let J of G){if($)u.info(`Checking home directory: ${J}`);let _=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(_,U,{arrayStrategy:Z,verbose:$});if(q){if($)u.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let G=U?RQ(Q,Z,H):Z;try{let J=l(Y,"package.json");if(!TZ(J))return null;let _={};try{_=JSON.parse(OZ(J,"utf8"))}catch(z){if(H)u.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let q=_[Q],A=Q;if(!q&&X){let z=Array.isArray(X)?X:[X];for(let W of z){if(!W)continue;if(_[W]){q=_[W],A=W;break}}}if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)u.success(`Configuration loaded from package.json: ${A}`);return{config:jZ(G,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)u.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:RQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let H=Y(Q);if(H)$.push(...H)}if(X){let H=await this.validator.validateConfiguration(Q,X);if(!H.isValid)$.push(...H.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if($.length>0)throw XQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return pQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);pQ.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias){let Z=Array.isArray(X.alias)?X.alias.join(","):X.alias;Y.push(`alias:${Z}`)}if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configFile)Y.push(`configFile:${X.configFile}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return EZ({cwd:Q,configDir:X})}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(l(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),H=[];for(let U of $)H.push(...this.fileLoader.generateConfigPaths(Q,U,X));return H}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[l(ZQ(),".config",Q),l(ZQ(),".config"),ZQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var DX=new MZ;async function DZ(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await DX.loadConfig(Q);else Z=await DX.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){if(Q.configFile)throw Z;let $=Z instanceof Error?Z.name:"UnknownError",H=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||H.includes("config"))&&Q.verbose)u.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let G=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await DX.applyEnvironmentVariables(G.name||"",X,!0,G.verbose||!1))?.config??X;return X}}function RQ(Q,X,Y=!1){let Z=new lX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let A=[...G,_],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,I;for(let B of z)if(W=QX.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof q==="boolean")J[_]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))J[_]=B}else if(Array.isArray(q))try{J[_]=JSON.parse(W)}catch{J[_]=W.split(",").map((B)=>B.trim())}else J[_]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))J[_]=H(q,A)}return J}return H(X)}var I$=l(QX.cwd(),"config"),F$=l(QX.cwd(),"src/generated");var rX={verbose:!0,repository:{owner:"",name:"",provider:"github"},security:{enabled:!0,prioritize:!0,label:"security",minimumSeverity:"low"},dashboard:{enabled:!1,title:"Dependency Dashboard"},workflows:{enabled:!1,outputDir:".github/workflows",templates:{daily:!1,weekly:!1,monthly:!1},custom:[]},packages:{strategy:"all",ignore:[],ignorePaths:[],pin:{},groups:[],includePrerelease:!1,excludeMajor:!1,respectLatest:!0,minimumReleaseAge:0,minimumReleaseAgeExclude:[]}},$X=null;async function v8(Q){let X=b8(Q),Y=Bun.file(X);if(!await Y.exists())throw Error(`Config file not found: ${X}`);let Z;if(X.endsWith(".json"))Z=await Y.json();else{let $=await import(X);Z=$.default??$.config}if(typeof Z!=="object"||Z===null)throw Error(`Config file ${X} does not export a configuration object`);return nX(rX,Z)}async function N$(Q){if(Q){let X=await v8(Q),Y=sX(X);if(Y.warning)iX().warn(`\u26A0\uFE0F ${Y.warning}`);return oX(X),X}if(!$X){let X=await DZ({name:"buddy",alias:"buddy-bot",cwd:y8.cwd(),defaultConfig:rX}),Y=sX(X);if(Y.warning)iX().warn(`\u26A0\uFE0F ${Y.warning}`);oX(X),$X=X}return $X}function C$(){$X=null}var x$=rX;
62
- export{rX as Tc,N$ as Uc,C$ as Vc,x$ as Wc};
62
+ export{rX as Uc,N$ as Vc,C$ as Wc,x$ as Xc};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ki as a,li as e,mi as o,ni as s,oi as t,pi as i,qi as c,ri as r,si as n,ti as g,ui as m,vi as u,wi as P,xi as l,yi as h}from"./chunk-0apd8zqn.js";import"./chunk-s3ksf6s5.js";export{n as toPropertyKey,e as shouldProceedWithGitHubRequest,a as saveRateLimitInfo,s as saveGitHubPackageCache,u as resolvePackageDomain,i as logPkgxProjects,l as isKnownAlias,m as guessOriginalDomain,P as getPackageAliases,o as getGitHubPackageCache,h as getCanonicalDomain,c as formatObjectWithoutQuotedKeys,t as fetchPackageListFromGitHub,r as convertDomainToVarName,g as convertDomainToFileName};
2
+ import{li as a,mi as e,ni as o,oi as s,pi as t,qi as i,ri as c,si as r,ti as n,ui as g,vi as m,wi as u,xi as P,yi as l,zi as h}from"./chunk-z05djfac.js";import"./chunk-kbvj6qxc.js";export{n as toPropertyKey,e as shouldProceedWithGitHubRequest,a as saveRateLimitInfo,s as saveGitHubPackageCache,u as resolvePackageDomain,i as logPkgxProjects,l as isKnownAlias,m as guessOriginalDomain,P as getPackageAliases,o as getGitHubPackageCache,h as getCanonicalDomain,c as formatObjectWithoutQuotedKeys,t as fetchPackageListFromGitHub,r as convertDomainToVarName,g as convertDomainToFileName};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{vd as j,yd as q}from"./chunk-7crh00m7.js";async function U(A,D,G){let x=q(A);if(x.length===0)return;let z=new j;for(let H of x)z.register(H);await z.emit(D,G)}
3
- export{U as td};
2
+ import{wd as j,zd as q}from"./chunk-5jvde2as.js";async function U(A,D,G){let x=q(A);if(x.length===0)return;let z=new j;for(let H of x)z.register(H);await z.emit(D,G)}
3
+ export{U as ud};
@@ -500,4 +500,4 @@ jobs:
500
500
  - name: Run buddy security
501
501
  run: bunx --bun @buddysh/buddy security
502
502
  `}}
503
- export{K as vh};
503
+ export{K as wh};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Ag as b,Bg as c,Cg as d,zg as a}from"./chunk-54er1whp.js";import"./chunk-ktn47bq8.js";import"./chunk-x1w6q9tk.js";import"./chunk-z05djfac.js";import"./chunk-kbvj6qxc.js";export{c as updateDependencyFile,b as parseDependencyFile,a as isDependencyFile,d as generateDependencyFileUpdates};
@@ -13,4 +13,4 @@ var G=["pretty","json","github","agent"];function Q(k,j){switch(k){case"staged":
13
13
  `);if(j<1||j>z.length)return null;return z.splice(j-1,1,...q.split(`
14
14
  `)),z.join(`
15
15
  `)}function P(k,j="major"){let q=["critical","major","minor","nit"],z=q.indexOf(j);return k.some((D)=>q.indexOf(D.severity)<=z)}
16
- export{G as Dd,Q as Ed,L as Fd,X as Gd,Z as Hd,$ as Id,B as Jd,N as Kd,O as Ld,P as Md};
16
+ export{G as Ed,Q as Fd,L as Gd,X as Hd,Z as Id,$ as Jd,B as Kd,N as Ld,O as Md,P as Nd};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{td as a}from"./chunk-9sdgy9nm.js";import"./chunk-gpjde0j6.js";import"./chunk-2z2gh050.js";import"./chunk-knpdntnh.js";import"./chunk-54er1whp.js";import"./chunk-ktn47bq8.js";import"./chunk-2z9pkk1y.js";import"./chunk-b9szrnxw.js";import"./chunk-x1w6q9tk.js";import"./chunk-z05djfac.js";import"./chunk-kbvj6qxc.js";export{a as PullRequestGenerator};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import"./chunk-s3ksf6s5.js";function f(i){return JSON.stringify({ok:!i.failed,summary:{workflows:i.workflows.length,findings:i.findings.length,errors:i.findings.filter((n)=>n.severity==="error").length,warnings:i.findings.filter((n)=>n.severity==="warning").length,info:i.findings.filter((n)=>n.severity==="info").length},findings:i.findings},null,2)}export{f as formatJson};
2
+ import"./chunk-kbvj6qxc.js";function f(i){return JSON.stringify({ok:!i.failed,summary:{workflows:i.workflows.length,findings:i.findings.length,errors:i.findings.filter((n)=>n.severity==="error").length,warnings:i.findings.filter((n)=>n.severity==="warning").length,info:i.findings.filter((n)=>n.severity==="info").length},findings:i.findings},null,2)}export{f as formatJson};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import"./chunk-s3ksf6s5.js";var $={error:"\x1B[31m",warning:"\x1B[33m",info:"\x1B[34m"},R={error:"error",warning:"warn ",info:"info "};function a(i,g={}){let l=g.color??!0,r=(n,t)=>l?`${n}${t}\x1B[0m`:t;if(i.workflows.length===0)return r("\x1B[90m","buddy security: no workflows found under .github/workflows.");if(i.findings.length===0)return r("\x1B[32m",`buddy security: ${i.workflows.length} workflow${i.workflows.length===1?"":"s"} clean.`);let e=new Map;for(let n of i.findings){if(!e.has(n.file))e.set(n.file,[]);e.get(n.file).push(n)}let s=[];for(let[n,t]of e){s.push(r("\x1B[1m",n));for(let o of t){let u=r($[o.severity],R[o.severity]),w=o.line!==void 0?r("\x1B[90m",`:${o.line}`):"",E=r("\x1B[90m",`(${o.ruleId})`);if(s.push(` ${u}${w} ${o.message} ${E}`),o.detail)s.push(r("\x1B[2m",` ${o.detail}`));if(o.fix)s.push(r("\x1B[2m",` fix: ${o.fix}`))}s.push("")}let f=i.findings.filter((n)=>n.severity==="error").length,c=i.findings.filter((n)=>n.severity==="warning").length,d=`${f} error${f===1?"":"s"}, ${c} warning${c===1?"":"s"} across ${e.size} workflow${e.size===1?"":"s"}`;return s.push(r(i.failed?"\x1B[31m":"\x1B[33m",d)),s.join(`
2
+ import"./chunk-kbvj6qxc.js";var $={error:"\x1B[31m",warning:"\x1B[33m",info:"\x1B[34m"},R={error:"error",warning:"warn ",info:"info "};function a(i,g={}){let l=g.color??!0,r=(n,t)=>l?`${n}${t}\x1B[0m`:t;if(i.workflows.length===0)return r("\x1B[90m","buddy security: no workflows found under .github/workflows.");if(i.findings.length===0)return r("\x1B[32m",`buddy security: ${i.workflows.length} workflow${i.workflows.length===1?"":"s"} clean.`);let e=new Map;for(let n of i.findings){if(!e.has(n.file))e.set(n.file,[]);e.get(n.file).push(n)}let s=[];for(let[n,t]of e){s.push(r("\x1B[1m",n));for(let o of t){let u=r($[o.severity],R[o.severity]),w=o.line!==void 0?r("\x1B[90m",`:${o.line}`):"",E=r("\x1B[90m",`(${o.ruleId})`);if(s.push(` ${u}${w} ${o.message} ${E}`),o.detail)s.push(r("\x1B[2m",` ${o.detail}`));if(o.fix)s.push(r("\x1B[2m",` fix: ${o.fix}`))}s.push("")}let f=i.findings.filter((n)=>n.severity==="error").length,c=i.findings.filter((n)=>n.severity==="warning").length,d=`${f} error${f===1?"":"s"}, ${c} warning${c===1?"":"s"} across ${e.size} workflow${e.size===1?"":"s"}`;return s.push(r(i.failed?"\x1B[31m":"\x1B[33m",d)),s.join(`
3
3
  `)}export{a as formatPretty};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ve as c}from"./chunk-kh6v93yb.js";import{ag as l,jg as A}from"./chunk-wreexgkb.js";import{rg as y}from"./chunk-gvnsr72j.js";import{xh as k}from"./chunk-6k6dgwmy.js";import{Oh as i}from"./chunk-8dj94fsy.js";import u from"process";var d=/\{([a-z_]+)\}/gi,b={title:"title",message:"message",group:"group",count:"count",strategy:"strategy",update_type:"updateType",updateType:"updateType",packages:"packages",updates_table:"updatesTable",release_notes:"releaseNotes",footer:"footer",package_count:"packageCount"};function h(W,$){return W.replace(d,(Y,R)=>{let K=b[R]??b[R.toLowerCase()];if(!K)return Y;let H=$[K];return H===void 0?Y:String(H)})}function f(W,$={},Y){return{...$,group:W.name,count:W.updates.length,packageCount:W.updates.length,updateType:W.updateType,packages:W.updates.map((R)=>R.name).join(", "),...Y?{strategy:Y}:{}}}class p{config;releaseNotesFetcher=new c;verbose=!1;logger;constructor(W,$){this.config=W;this.verbose=W?.verbose||u.env.BUDDY_VERBOSE==="true",this.logger=$??i()}get releaseNotesSettings(){let W=this.config?.releaseNotes;return{enabled:W?.enabled??!0,maxReleases:W?.maxReleases??3,maxBodyLength:W?.maxBodyLength??1000,includeCompareLinks:W?.includeCompareLinks??!0}}repositoryFileUrl(W){let $=k(this.config),{owner:Y,name:R,baseBranch:K}=this.config?.repository??{};return`${$}/${Y}/${R}/blob/${K||"main"}/${W}`}log(W,$){if(this.verbose){let Y=new Date().toISOString();if(this.logger.info(`[${Y}] PR-GEN: ${W}`),$)this.logger.info(JSON.stringify($,null,2))}}async generatePullRequests(W){let $=[];for(let Y of W){let R=this.generateTitle(Y),K=await this.generateBody(Y),H={number:0,title:R,body:K,head:`buddy/update-${Y.name.toLowerCase().replace(/\s+/g,"-")}`,base:"main",state:"open",url:"",createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:[],assignees:[],labels:this.generateLabels(Y),draft:!1};$.push(H)}return $}generateLabels(W){let $=["dependencies"];if(W.updateType==="major")$.push("major");else if(W.updateType==="minor")$.push("minor");else if(W.updateType==="patch")$.push("patch");let Y=W.updates.filter((D)=>D.file==="package.json"||D.file.endsWith("/package.json")||D.file.endsWith("\\package.json")).length,R=W.updates.filter((D)=>D.file.endsWith("composer.json")||D.file.endsWith("composer.lock")).length,K=W.updates.filter((D)=>D.file.endsWith("build.zig.zon")).length,H=W.updates.filter((D)=>(D.file.includes(".yaml")||D.file.includes(".yml"))&&!D.file.includes(".github/workflows/")).length,Z=W.updates.filter((D)=>D.file.includes(".github/workflows/")).length;if(Y>0)$.push("npm");if(R>0)$.push("composer");if(K>0)$.push("zig");if(H>0)$.push("system");if(Z>0)$.push("github-actions");if(W.updates.length===1){let D=W.updates[0];$.push(D.name)}if(W.updates.length>=5)$.push("bulk-update");return $}generateTitle(W){let $=this.config?.pullRequest?.titleFormat;if($)return h($,f(W,{title:this.defaultTitle(W)},this.config?.packages?.strategy));return this.defaultTitle(W)}defaultTitle(W){if(W.updates.length===1){let R=W.updates[0];return`chore(deps): update dependency ${R.name} to v${R.newVersion}`}let $=W.updates.filter((R)=>R.updateType==="major").length,Y=W.updates.filter((R)=>R.updateType==="minor").length;if($>0)return`chore(deps): update ${W.updates.length} dependencies (major)`;else if(Y>0)return`chore(deps): update ${W.updates.length} dependencies (minor)`;else return`chore(deps): update ${W.updates.length} dependencies (patch)`}async generateBody(W){if(this.log("\uD83D\uDE80 Starting PR body generation",{groupName:W.name,totalUpdates:W.updates.length,updates:W.updates.map((Q)=>({name:Q.name,file:Q.file,dependencyType:Q.dependencyType,currentVersion:Q.currentVersion,newVersion:Q.newVersion,updateType:Q.updateType}))}),W.updates.length===0)this.log("\u26A0\uFE0F WARNING: No updates in group - this will result in sparse PR body",{groupName:W.name,groupTitle:W.title});let $=W.updates.filter((Q)=>Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")).length,Y=W.updates.filter((Q)=>(Q.file.includes(".yaml")||Q.file.includes(".yml"))&&!Q.file.includes(".github/workflows/")).length,R=W.updates.filter((Q)=>Q.file.includes(".github/workflows/")).length,K=W.updates.filter((Q)=>Q.file.endsWith("composer.json")||Q.file.endsWith("composer.lock")).length,H=W.updates.filter((Q)=>Q.file.endsWith("build.zig.zon")).length;if(this.log("\uD83D\uDCCA Package type counts",{packageJsonCount:$,dependencyFileCount:Y,githubActionsCount:R,composerCount:K,total:W.updates.length}),W.updates.length>0)this.log("\uD83D\uDD0D File path analysis",{files:W.updates.map((Q)=>({name:Q.name,file:Q.file,isExactMatch:Q.file==="package.json",endsWithSlash:Q.file.endsWith("/package.json"),endsWithBackslash:Q.file.endsWith("\\package.json"),matchesAny:Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")}))});let Z=`This PR contains the following updates:
2
+ import{We as c}from"./chunk-gpjde0j6.js";import{bg as l,kg as A}from"./chunk-2z2gh050.js";import{sg as y}from"./chunk-knpdntnh.js";import{yh as k}from"./chunk-2z9pkk1y.js";import{Ph as i}from"./chunk-x1w6q9tk.js";import u from"process";var d=/\{([a-z_]+)\}/gi,b={title:"title",message:"message",group:"group",count:"count",strategy:"strategy",update_type:"updateType",updateType:"updateType",packages:"packages",updates_table:"updatesTable",release_notes:"releaseNotes",footer:"footer",package_count:"packageCount"};function h(W,$){return W.replace(d,(Y,R)=>{let K=b[R]??b[R.toLowerCase()];if(!K)return Y;let H=$[K];return H===void 0?Y:String(H)})}function f(W,$={},Y){return{...$,group:W.name,count:W.updates.length,packageCount:W.updates.length,updateType:W.updateType,packages:W.updates.map((R)=>R.name).join(", "),...Y?{strategy:Y}:{}}}class p{config;releaseNotesFetcher=new c;verbose=!1;logger;constructor(W,$){this.config=W;this.verbose=W?.verbose||u.env.BUDDY_VERBOSE==="true",this.logger=$??i()}get releaseNotesSettings(){let W=this.config?.releaseNotes;return{enabled:W?.enabled??!0,maxReleases:W?.maxReleases??3,maxBodyLength:W?.maxBodyLength??1000,includeCompareLinks:W?.includeCompareLinks??!0}}repositoryFileUrl(W){let $=k(this.config),{owner:Y,name:R,baseBranch:K}=this.config?.repository??{};return`${$}/${Y}/${R}/blob/${K||"main"}/${W}`}log(W,$){if(this.verbose){let Y=new Date().toISOString();if(this.logger.info(`[${Y}] PR-GEN: ${W}`),$)this.logger.info(JSON.stringify($,null,2))}}async generatePullRequests(W){let $=[];for(let Y of W){let R=this.generateTitle(Y),K=await this.generateBody(Y),H={number:0,title:R,body:K,head:`buddy/update-${Y.name.toLowerCase().replace(/\s+/g,"-")}`,base:"main",state:"open",url:"",createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:[],assignees:[],labels:this.generateLabels(Y),draft:!1};$.push(H)}return $}generateLabels(W){let $=["dependencies"];if(W.updateType==="major")$.push("major");else if(W.updateType==="minor")$.push("minor");else if(W.updateType==="patch")$.push("patch");let Y=W.updates.filter((D)=>D.file==="package.json"||D.file.endsWith("/package.json")||D.file.endsWith("\\package.json")).length,R=W.updates.filter((D)=>D.file.endsWith("composer.json")||D.file.endsWith("composer.lock")).length,K=W.updates.filter((D)=>D.file.endsWith("build.zig.zon")).length,H=W.updates.filter((D)=>(D.file.includes(".yaml")||D.file.includes(".yml"))&&!D.file.includes(".github/workflows/")).length,Z=W.updates.filter((D)=>D.file.includes(".github/workflows/")).length;if(Y>0)$.push("npm");if(R>0)$.push("composer");if(K>0)$.push("zig");if(H>0)$.push("system");if(Z>0)$.push("github-actions");if(W.updates.length===1){let D=W.updates[0];$.push(D.name)}if(W.updates.length>=5)$.push("bulk-update");return $}generateTitle(W){let $=this.config?.pullRequest?.titleFormat;if($)return h($,f(W,{title:this.defaultTitle(W)},this.config?.packages?.strategy));return this.defaultTitle(W)}defaultTitle(W){if(W.updates.length===1){let R=W.updates[0];return`chore(deps): update dependency ${R.name} to v${R.newVersion}`}let $=W.updates.filter((R)=>R.updateType==="major").length,Y=W.updates.filter((R)=>R.updateType==="minor").length;if($>0)return`chore(deps): update ${W.updates.length} dependencies (major)`;else if(Y>0)return`chore(deps): update ${W.updates.length} dependencies (minor)`;else return`chore(deps): update ${W.updates.length} dependencies (patch)`}async generateBody(W){if(this.log("\uD83D\uDE80 Starting PR body generation",{groupName:W.name,totalUpdates:W.updates.length,updates:W.updates.map((Q)=>({name:Q.name,file:Q.file,dependencyType:Q.dependencyType,currentVersion:Q.currentVersion,newVersion:Q.newVersion,updateType:Q.updateType}))}),W.updates.length===0)this.log("\u26A0\uFE0F WARNING: No updates in group - this will result in sparse PR body",{groupName:W.name,groupTitle:W.title});let $=W.updates.filter((Q)=>Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")).length,Y=W.updates.filter((Q)=>(Q.file.includes(".yaml")||Q.file.includes(".yml"))&&!Q.file.includes(".github/workflows/")).length,R=W.updates.filter((Q)=>Q.file.includes(".github/workflows/")).length,K=W.updates.filter((Q)=>Q.file.endsWith("composer.json")||Q.file.endsWith("composer.lock")).length,H=W.updates.filter((Q)=>Q.file.endsWith("build.zig.zon")).length;if(this.log("\uD83D\uDCCA Package type counts",{packageJsonCount:$,dependencyFileCount:Y,githubActionsCount:R,composerCount:K,total:W.updates.length}),W.updates.length>0)this.log("\uD83D\uDD0D File path analysis",{files:W.updates.map((Q)=>({name:Q.name,file:Q.file,isExactMatch:Q.file==="package.json",endsWithSlash:Q.file.endsWith("/package.json"),endsWithBackslash:Q.file.endsWith("\\package.json"),matchesAny:Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")}))});let Z=`This PR contains the following updates:
3
3
 
4
4
  `;Z+=l(W.updates);let D=W.updates.length>1;if(D){if(Z+=`## Package Updates Summary
5
5
 
@@ -187,4 +187,4 @@ import{Ve as c}from"./chunk-kh6v93yb.js";import{ag as l,jg as A}from"./chunk-wre
187
187
  `).trim();$=this.sanitizeMentions($),$=this.sanitizeGitHubReferences($);let Y=this.config?.releaseNotes?.maxBodyLength??1000;if($.length>Y)$=`${$.substring(0,Y)}...
188
188
 
189
189
  *[View full release notes]*`;return $}sanitizeMentions(W){let $=[],Y=[],R=W.replace(/```[\s\S]*?```/g,(K)=>{return $.push(K),`__FENCE_PLACEHOLDER_${$.length-1}__`});return R=R.replace(/`[^`\n]+`/g,(K)=>{return Y.push(K),`__INLINE_CODE_PLACEHOLDER_${Y.length-1}__`}),R=R.replace(/(?<![\w./])@([A-Z0-9-]+)(?![A-Z0-9-])/gi,(K,H)=>{return`[${H}](https://github.com/${H})`}),R=R.replace(/__INLINE_CODE_PLACEHOLDER_(\d+)__/g,(K,H)=>Y[Number(H)]),R=R.replace(/__FENCE_PLACEHOLDER_(\d+)__/g,(K,H)=>$[Number(H)]),R}sanitizeGitHubReferences(W){if(this.config?.releaseNotes?.sanitizeReferences===!1)return W;let $=[],Y=[],R=W.replace(/```[\s\S]*?```/g,(K)=>{return $.push(K),`__FENCE_PLACEHOLDER_${$.length-1}__`});return R=R.replace(/`[^`\n]+`/g,(K)=>{return Y.push(K),`__INLINE_CODE_PLACEHOLDER_${Y.length-1}__`}),R=R.replace(/https?:\/\/github\.com\/([^/]+)\/([^/]+)\/(?:pull|issues)\/(\d+)/g,(K,H,Z,D)=>`\`${H}/${Z}#${D}\``),R=R.replace(/(?<![`\w])#(\d+)(?!\d)/g,"`#$1`"),R=R.replace(/__INLINE_CODE_PLACEHOLDER_(\d+)__/g,(K,H)=>Y[Number(H)]),R=R.replace(/__FENCE_PLACEHOLDER_(\d+)__/g,(K,H)=>$[Number(H)]),R}generateCustomTemplate(W,$,Y={}){let R=$,H={...{"{title}":this.generateTitle(W),"{package_count}":W.updates.length.toString(),"{update_type}":W.updateType,"{packages}":W.updates.map((Z)=>Z.name).join(", "),"{date}":new Date().toISOString().split("T")[0]},...Y};for(let[Z,D]of Object.entries(H))R=R.replace(new RegExp(Z,"g"),D);return R}formatVersionChange(W,$){let Y=W.match(/^(\D+)/),R=Y?Y[1]:"";if(R){let K=W.replace(/^\D+/,""),H=$.replace(/^\D+/,"");return`\`${R}${K}\` \u2192 \`${R}${H}\``}return`\`${W}\` \u2192 \`${$}\``}getVersionChangeDescription(W,$,Y){return{major:"\uD83D\uDD34 Breaking changes possible",minor:"\uD83D\uDFE1 New features added",patch:"\uD83D\uDFE2 Bug fixes & patches"}[Y]}}
190
- export{h as qd,f as rd,p as sd};
190
+ export{h as rd,f as sd,p as td};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ed as a}from"./chunk-rygtb1x3.js";import"./chunk-08daxhzx.js";import"./chunk-d4gk9awk.js";import"./chunk-gweqk008.js";import"./chunk-bnp0r4eh.js";import"./chunk-0f1xye20.js";import"./chunk-9sdgy9nm.js";import"./chunk-5jvde2as.js";import"./chunk-ctdfppxk.js";import"./chunk-wjfw6rx8.js";import"./chunk-w55x2g9n.js";import"./chunk-1xe0960b.js";import"./chunk-gpjde0j6.js";import"./chunk-j46f90n8.js";import"./chunk-enq0gm64.js";import"./chunk-c6ptrc0v.js";import"./chunk-1pecmenc.js";import"./chunk-sxfk3naz.js";import"./chunk-24xvskkf.js";import"./chunk-z18bksyr.js";import"./chunk-cj4d5ad7.js";import"./chunk-2z2gh050.js";import"./chunk-knpdntnh.js";import"./chunk-54er1whp.js";import"./chunk-ktn47bq8.js";import"./chunk-2z9pkk1y.js";import"./chunk-vpw7adwd.js";import"./chunk-b9szrnxw.js";import"./chunk-x1w6q9tk.js";import"./chunk-z05djfac.js";import"./chunk-kbvj6qxc.js";export{a as Buddy};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Ih as X}from"./chunk-a3bnhq58.js";import{Oh as Z}from"./chunk-8dj94fsy.js";var V={node:"nodejs","library/node":"nodejs",python:"python","library/python":"python",debian:"debian","library/debian":"debian",ubuntu:"ubuntu","library/ubuntu":"ubuntu",alpine:"alpine","library/alpine":"alpine",php:"php","library/php":"php",ruby:"ruby","library/ruby":"ruby",golang:"go","library/golang":"go",postgres:"postgresql","library/postgres":"postgresql",mysql:"mysql","library/mysql":"mysql",redis:"redis","library/redis":"redis",nginx:"nginx","library/nginx":"nginx"};function q(j){let x=j.replace(/^(?:docker\.io|registry-1\.docker\.io)\//,"");return V[x]??V[x.split("/").pop()??""]??null}function G(j,x){let z=/^v?(\d+(?:\.\d+)*)/.exec(j.trim());if(!z)return null;let H=z[1].split(".");for(let k=H.length;k>=1;k--){let K=H.slice(0,k).join("."),B=x.find((J)=>J.cycle===K);if(B)return B}return null}async function F(j,x,z={}){let H=z.logger??Z(),k=q(j);if(!k)return null;let K=z.baseUrl??"https://endoflife.date",B=await X(`${K}/api/${k}.json`,{headers:{"User-Agent":"buddy",Accept:"application/json"}}).catch(()=>null);if(!B?.ok)return H.debug(`Could not read the support window for ${k}`),null;let J=await B.json().catch(()=>null);if(!Array.isArray(J))return null;let v=G(x,J);if(!v)return null;if(v.eol===!1)return{product:k,cycle:v.cycle,eol:!1};if(v.eol===!0)return{product:k,cycle:v.cycle,eol:!0};let M=new Date(v.eol);if(Number.isNaN(M.getTime()))return{product:k,cycle:v.cycle,eol:!1};let $=z.now??new Date,Q=Math.round((M.getTime()-$.getTime())/86400000);return{product:k,cycle:v.cycle,eol:Q<0,date:v.eol,daysRemaining:Q}}var I=90;function N(j){if(!j)return"";if(j.eol)return j.date?`\`${j.product} ${j.cycle}\` reached end of life on ${j.date} and no longer receives security fixes.`:`\`${j.product} ${j.cycle}\` has reached end of life and no longer receives security fixes.`;if(j.daysRemaining!==void 0&&j.daysRemaining<=I)return`\`${j.product} ${j.cycle}\` reaches end of life in ${j.daysRemaining} day(s), on ${j.date}.`;return""}
2
+ import{Jh as X}from"./chunk-b9szrnxw.js";import{Ph as Z}from"./chunk-x1w6q9tk.js";var V={node:"nodejs","library/node":"nodejs",python:"python","library/python":"python",debian:"debian","library/debian":"debian",ubuntu:"ubuntu","library/ubuntu":"ubuntu",alpine:"alpine","library/alpine":"alpine",php:"php","library/php":"php",ruby:"ruby","library/ruby":"ruby",golang:"go","library/golang":"go",postgres:"postgresql","library/postgres":"postgresql",mysql:"mysql","library/mysql":"mysql",redis:"redis","library/redis":"redis",nginx:"nginx","library/nginx":"nginx"};function q(j){let x=j.replace(/^(?:docker\.io|registry-1\.docker\.io)\//,"");return V[x]??V[x.split("/").pop()??""]??null}function G(j,x){let z=/^v?(\d+(?:\.\d+)*)/.exec(j.trim());if(!z)return null;let H=z[1].split(".");for(let k=H.length;k>=1;k--){let K=H.slice(0,k).join("."),B=x.find((J)=>J.cycle===K);if(B)return B}return null}async function F(j,x,z={}){let H=z.logger??Z(),k=q(j);if(!k)return null;let K=z.baseUrl??"https://endoflife.date",B=await X(`${K}/api/${k}.json`,{headers:{"User-Agent":"buddy",Accept:"application/json"}}).catch(()=>null);if(!B?.ok)return H.debug(`Could not read the support window for ${k}`),null;let J=await B.json().catch(()=>null);if(!Array.isArray(J))return null;let v=G(x,J);if(!v)return null;if(v.eol===!1)return{product:k,cycle:v.cycle,eol:!1};if(v.eol===!0)return{product:k,cycle:v.cycle,eol:!0};let M=new Date(v.eol);if(Number.isNaN(M.getTime()))return{product:k,cycle:v.cycle,eol:!1};let $=z.now??new Date,Q=Math.round((M.getTime()-$.getTime())/86400000);return{product:k,cycle:v.cycle,eol:Q<0,date:v.eol,daysRemaining:Q}}var I=90;function N(j){if(!j)return"";if(j.eol)return j.date?`\`${j.product} ${j.cycle}\` reached end of life on ${j.date} and no longer receives security fixes.`:`\`${j.product} ${j.cycle}\` has reached end of life and no longer receives security fixes.`;if(j.daysRemaining!==void 0&&j.daysRemaining<=I)return`\`${j.product} ${j.cycle}\` reaches end of life in ${j.daysRemaining} day(s), on ${j.date}.`;return""}
3
3
  export{V as xa,q as ya,G as za,F as Aa,I as Ba,N as Ca};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{kd as a}from"./chunk-d4gk9awk.js";import"./chunk-bnp0r4eh.js";import"./chunk-0f1xye20.js";import"./chunk-2z2gh050.js";import"./chunk-knpdntnh.js";import"./chunk-54er1whp.js";import"./chunk-ktn47bq8.js";import"./chunk-2z9pkk1y.js";import"./chunk-b9szrnxw.js";import"./chunk-x1w6q9tk.js";import"./chunk-z05djfac.js";import"./chunk-kbvj6qxc.js";export{a as RegistryClient};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Eb as a,Fb as b,Gb as c}from"./chunk-q2tjkhez.js";import"./chunk-s3ksf6s5.js";export{b as renderDiffForReview,a as parseUnifiedDiff,c as collectGitDiff};
2
+ import{Eb as a,Fb as b,Gb as c}from"./chunk-q2tjkhez.js";import"./chunk-kbvj6qxc.js";export{b as renderDiffForReview,a as parseUnifiedDiff,c as collectGitDiff};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Ea as a,Fa as b,Ga as c,Ha as d,Ia as e,Ja as f,Ka as g}from"./chunk-24xnjkvz.js";import"./chunk-7b4jsg36.js";import"./chunk-5jvde2as.js";import"./chunk-ctdfppxk.js";import"./chunk-1pecmenc.js";import"./chunk-sxfk3naz.js";import"./chunk-z18bksyr.js";import"./chunk-cj4d5ad7.js";import"./chunk-b9szrnxw.js";import"./chunk-x1w6q9tk.js";import"./chunk-kbvj6qxc.js";export{g as runFixCi,e as latestFailurePerWorkflow,d as failsOnBaseBranch,b as extractErrorLines,c as describeFailure,a as classifyFailure,f as attemptFix};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Qf as Z}from"./chunk-7rjrea9g.js";import{Oh as Y}from"./chunk-8dj94fsy.js";import W from"process";var $=[["bun","test"],["npm","test","--silent"]];async function E(G,H){let I=H?[H]:await L(G);for(let z of I){let j=Bun.spawn(z,{cwd:G,stdout:"pipe",stderr:"pipe",env:{PATH:W.env.PATH??"",HOME:W.env.HOME??"",CI:"1"}}),[J,K,Q]=await Promise.all([new Response(j.stdout).text(),new Response(j.stderr).text(),j.exited]);return{ran:!0,passed:Q===0,output:`${J}
2
+ import{Rf as Z}from"./chunk-sxfk3naz.js";import{Ph as Y}from"./chunk-x1w6q9tk.js";import W from"process";var $=[["bun","test"],["npm","test","--silent"]];async function E(G,H){let I=H?[H]:await L(G);for(let z of I){let j=Bun.spawn(z,{cwd:G,stdout:"pipe",stderr:"pipe",env:{PATH:W.env.PATH??"",HOME:W.env.HOME??"",CI:"1"}}),[J,K,Q]=await Promise.all([new Response(j.stdout).text(),new Response(j.stderr).text(),j.exited]);return{ran:!0,passed:Q===0,output:`${J}
3
3
  ${K}`.trim().slice(-4000)}}return{ran:!1,passed:!1,output:""}}async function L(G){let H=Bun.file(`${G}/package.json`);if(!await H.exists())return[];try{return(await H.json()).scripts?.test?$:[]}catch{return[]}}function O(G,H){return`${G.head}/buddy-${H}`}async function N(G){let H=G.logger??Y(),{provider:I,pullRequest:z,touch:j}=G;H.info(`\u2728 Running finishing touch '${j.name}' on PR #${z.number}`);let J=await Z(G.ai,{mode:j.mode,task:j.buildTask({summary:z.title,files:G.files??[]}),context:{workspace:G.workspace,baseBranch:z.base,branch:z.head},logger:H}),K=await _(G.workspace);if(K.length===0)return{mode:"none",changedFiles:[],verified:!1,comment:J.stopReason==="completed"?`**${j.description}** \u2014 nothing to change.`:`**${j.description}** \u2014 stopped before finishing (${J.stopReason}), and left nothing behind.`};let Q=J.stopReason==="completed",P=await E(G.workspace,G.testCommand);if(!(Q&&j.defaultOutput!=="suggestion"&&(P.passed||!P.ran)))return{mode:"suggestions",changedFiles:K,verified:P.passed,comment:X(j,K,P,J.stopReason)};let V=O(z,j.name);try{await I.createBranch(V,z.head),await I.commitChanges(V,`chore: ${j.description.toLowerCase()} for #${z.number}`,await x(G.workspace,K),z.head);let U=await I.createPullRequest({title:`${j.description} for #${z.number}`,body:y(j,z,K,P),head:V,base:z.head,labels:["buddy","finishing-touch"]});return{mode:"stacked-pr",pullRequest:U,changedFiles:K,verified:P.passed,comment:`**${j.description}** \u2014 opened [#${U.number}](${U.url}) targeting this branch.`+(P.ran?"":" No test script was found, so this is unverified.")}}catch(U){return H.warn(`\u26A0\uFE0F Could not open a stacked pull request: ${U}`),{mode:"suggestions",changedFiles:K,verified:P.passed,comment:X(j,K,P,J.stopReason)}}}async function _(G){let H=Bun.spawn(["git","status","--porcelain"],{cwd:G,stdout:"pipe",stderr:"ignore"}),[I,z]=await Promise.all([new Response(H.stdout).text(),H.exited]);if(z!==0)return[];let j=[];for(let J of I.split(`
4
4
  `)){if(!J.trim())continue;let K=J.slice(0,2),Q=J.slice(3).trim();if(K.includes("D"))continue;j.push(Q.includes(" -> ")?Q.split(" -> ")[1]:Q)}return j}async function x(G,H){let I=[];for(let z of H){let j=Bun.file(`${G}/${z}`);if(await j.exists())I.push({path:z,content:await j.text(),type:"update"})}return I}function y(G,H,I,z){return[`${G.description}, requested on #${H.number}.`,"",`This targets \`${H.head}\` rather than \`${H.base}\`, so merging it`,"adds these changes to that pull request.","",z.ran?z.passed?"\u2705 The repository's tests pass with these changes.":"\u26A0\uFE0F The repository's tests do **not** pass with these changes.":"\u2139\uFE0F No test script was found, so these changes are unverified.","","### Files changed","",...I.map((j)=>`- \`${j}\``)].join(`
5
5
  `)}function X(G,H,I,z){let j=[`**${G.description}**`,""];if(z&&z!=="completed")j.push(`The agent stopped before finishing (${z}), so what follows is`,"partial work rather than a complete change.","");if(I.ran&&!I.passed)j.push("The repository's tests do not pass with these changes, so no branch was","opened. Treat what follows as a starting point rather than a result.","");if(j.push("Files that would change:","",...H.map((J)=>`- \`${J}\``)),I.output)j.push("","<details><summary>Test output</summary>","","```",I.output,"```","","</details>");return j.join(`
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{hb as a,ib as b,jb as c,kb as d,lb as e}from"./chunk-b3s185kp.js";import"./chunk-sxfk3naz.js";import"./chunk-z18bksyr.js";import"./chunk-cj4d5ad7.js";import"./chunk-x1w6q9tk.js";import"./chunk-kbvj6qxc.js";export{b as verifyChanges,c as stackedBranchName,d as runStackedTouch,e as detectChangedFiles,a as TEST_COMMANDS};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  import _ from"process";var g=30000,b=2,D=500,A=30000,R=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),S=new Set([408,425,429,500,502,503,504]);class w extends Error{url;method;attempts;timedOut;constructor(z,C,K,G,V,$){super(z,$);this.url=C;this.method=K;this.attempts=G;this.timedOut=V;this.name="HttpRequestError"}}function I(z){return new Promise((C)=>setTimeout(C,z))}function x(z){if(typeof z==="number"&&z>0)return z;let C=Number(_.env.BUDDY_HTTP_TIMEOUT_MS);if(Number.isFinite(C)&&C>0)return C;return g}function M(z,C=Date.now()){let K=z.get("retry-after");if(K){let G=Number(K);if(Number.isFinite(G)&&G>=0)return G*1000;let V=Date.parse(K);if(!Number.isNaN(V))return Math.max(0,V-C)}if(z.get("x-ratelimit-remaining")==="0"){let G=Number(z.get("x-ratelimit-reset"));if(Number.isFinite(G)&&G>0)return Math.max(0,G*1000-C)}return null}function h(z){if(S.has(z.status))return!0;if(z.status===403)return z.headers.get("x-ratelimit-remaining")==="0"||z.headers.has("retry-after");return!1}function f(z){return z.status===429||z.status===403}function L(z,C,K){let G=C*2**(z-1),V=Math.random()*C;return Math.min(G+V,K)}async function E(z,C={}){let{timeoutMs:K,retries:G=b,retryBaseMs:V=D,maxDelayMs:$=A,retryNonIdempotent:O=!1,onRetry:q,signal:W,...H}=C,Y=(H.method??"GET").toUpperCase(),N=O||R.has(Y),B=x(K),j=Math.max(1,G+1),J,P=!1;for(let Z=1;Z<=j;Z++){let k=AbortSignal.timeout(B),v=W?AbortSignal.any([W,k]):k;try{let Q=await fetch(z,{...H,signal:v});if(Z<j&&h(Q)){if(N||f(Q)){let F=M(Q.headers),X=Math.min(F??L(Z,V,$),$);q?.({attempt:Z,delayMs:X,reason:`HTTP ${Q.status}`}),await I(X);continue}}return Q}catch(Q){if(J=Q,W?.aborted)throw Q;if(P=Q instanceof Error&&(Q.name==="TimeoutError"||Q.name==="AbortError"),!(Z<j&&N))break;let X=L(Z,V,$);q?.({attempt:Z,delayMs:X,reason:P?`timeout after ${B}ms`:"network error"}),await I(X)}}let U=P?`timed out after ${B}ms`:`network error: ${J instanceof Error?J.message:String(J)}`;throw new w(`${Y} ${z} failed after ${j} attempt(s): ${U}`,z,Y,j,P,{cause:J})}async function c(z,C={}){try{let K=await E(z,C);if(!K.ok)return null;return await K.json()}catch{return null}}
3
- export{g as Eh,b as Fh,w as Gh,M as Hh,E as Ih,c as Jh};
3
+ export{g as Fh,b as Gh,w as Hh,M as Ih,E as Jh,c as Kh};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var c=new Set(["bower_components","node_modules","pantry","ts-pantry","vendor"]),f=new Set([".cache",".idea",".next",".nuxt",".nyc_output",".vscode","build","coverage","dist","temp","tmp"]);function g(b){return b.startsWith(".")||c.has(b)||f.has(b)}
3
- export{g as ld};
3
+ export{g as md};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{$e as f,We as a,Xe as b,Ye as c,Ze as d,_e as e,af as g,bf as h}from"./chunk-88j356ng.js";import"./chunk-s3ksf6s5.js";export{e as resolveEngineVersion,d as pinBlocksUpdate,b as extractEngines,g as engineUpdateType,c as collectResolutionPins,f as bumpEngineConstraint,h as applyEngineUpdates,a as KNOWN_ENGINES};
2
+ import{$e as e,Xe as a,Ye as b,Ze as c,_e as d,af as f,bf as g,cf as h}from"./chunk-j46f90n8.js";import"./chunk-kbvj6qxc.js";export{e as resolveEngineVersion,d as pinBlocksUpdate,b as extractEngines,g as engineUpdateType,c as collectResolutionPins,f as bumpEngineConstraint,h as applyEngineUpdates,a as KNOWN_ENGINES};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Rf as K}from"./chunk-emygmh7r.js";import{kg as D}from"./chunk-wreexgkb.js";var F=[[0,59],[0,23],[1,31],[1,12],[0,6]];function I(j,J){let[U,B]=F[J],H=new Set;for(let Q of j.split(",")){let[X,Z]=Q.split("/"),q=Z===void 0?1:Number(Z);if(!Number.isInteger(q)||q<1)return null;let $,G;if(X==="*")$=U,G=B;else if(X.includes("-")){let[Y,_]=X.split("-").map(Number);if(!Number.isInteger(Y)||!Number.isInteger(_))return null;$=Y,G=_}else{let Y=Number(X);if(!Number.isInteger(Y))return null;$=Y,G=Y}if($<U||G>B||$>G)return null;for(let Y=$;Y<=G;Y+=q)H.add(Y)}return H.size>0?H:null}function L(j){let J=j.trim().split(/\s+/);if(J.length!==5)return null;let U=J.map((Z,q)=>I(Z,q));if(U.some((Z)=>Z===null))return null;let[,B,H,Q,X]=U;return{hours:B,daysOfMonth:H,months:Q,daysOfWeek:X}}function N(j,J){if(!J)return{hour:j.getHours(),day:j.getDate(),month:j.getMonth()+1,weekday:j.getDay()};let U=new Intl.DateTimeFormat("en-US",{timeZone:J,hour:"numeric",hour12:!1,day:"numeric",month:"numeric",weekday:"short"}),B=Object.fromEntries(U.formatToParts(j).map((Q)=>[Q.type,Q.value])),H=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return{hour:Number(B.hour)%24,day:Number(B.day),month:Number(B.month),weekday:Math.max(0,H.indexOf(B.weekday))}}function C(j,J=new Date,U){let B=L(j);if(!B)return!1;let{hour:H,day:Q,month:X,weekday:Z}=N(J,U);if(!B.hours.has(H)||!B.months.has(X))return!1;let q=B.daysOfMonth.size<31,$=B.daysOfWeek.size<7;if(q&&$)return B.daysOfMonth.has(Q)||B.daysOfWeek.has(Z);return B.daysOfMonth.has(Q)&&B.daysOfWeek.has(Z)}function W(j){if(j.dependencyType==="github-actions")return"github-actions";if(j.dependencyType==="docker-image")return"docker";if(j.dependencyType==="zig-dependencies")return"zig";if(j.dependencyType==="python"||j.dependencyType==="rust"||j.dependencyType==="go"||j.dependencyType==="ruby")return j.dependencyType;if(j.file.endsWith("composer.json")||j.file.endsWith("composer.lock"))return"composer";if(j.file.endsWith("package.json"))return"npm";return"pkgx"}function A(j,J,U=new Date){if(j.matchPackages?.length){if(!K(j.matchPackages).matches(J.name))return!1}if(j.matchEcosystems?.length&&!j.matchEcosystems.includes(W(J)))return!1;if(j.matchDepTypes?.length&&!j.matchDepTypes.includes(J.dependencyType))return!1;if(j.matchUpdateTypes?.length&&!j.matchUpdateTypes.includes(J.updateType))return!1;if(j.matchFiles?.length){if(!K(j.matchFiles).matches(J.file))return!1}if(j.matchCurrentVersion&&!E(J.currentVersion,j.matchCurrentVersion))return!1;if(j.schedule&&!C(j.schedule,U,j.scheduleTimezone))return!1;return!0}function E(j,J){let U=j.replace(/^[\^~>=<\s]+/,"").trim();return U?D(U,J):!1}function S(j,J=[],U=new Date){let B={enabled:!0,labels:[],reviewers:[],assignees:[],prPriority:0};for(let H of J){if(!A(H,j,U))continue;if(H.enabled!==void 0)B.enabled=H.enabled;if(H.strategy!==void 0)B.strategy=H.strategy;if(H.groupName!==void 0)B.groupName=H.groupName;if(H.autoMerge!==void 0)B.autoMerge=H.autoMerge;if(H.minimumReleaseAge!==void 0)B.minimumReleaseAge=H.minimumReleaseAge;if(H.prPriority!==void 0)B.prPriority=H.prPriority;if(H.autoMigrate!==void 0)B.autoMigrate=H.autoMigrate;for(let Q of H.labels??[])if(!B.labels.includes(Q))B.labels.push(Q);for(let Q of H.reviewers??[])if(!B.reviewers.includes(Q))B.reviewers.push(Q);for(let Q of H.assignees??[])if(!B.assignees.includes(Q))B.assignees.push(Q)}return B}function k(j,J=[],U=new Date){let B=[];for(let H of j){let Q=S(H,J,U);if(!Q.enabled)continue;if(Q.strategy&&!V(Q.strategy,H.updateType))continue;B.push({update:H,effects:Q})}return B}function T(j){let J=new Set,U=new Set,B=new Set,H=0;for(let Q of j)Q.labels.forEach((X)=>J.add(X)),Q.reviewers.forEach((X)=>U.add(X)),Q.assignees.forEach((X)=>B.add(X)),H=Math.max(H,Q.prPriority);return{labels:[...J],reviewers:[...U],assignees:[...B],autoMerge:j.length>0&&j.every((Q)=>Q.autoMerge===!0),prPriority:H,autoMigrate:j.some((Q)=>Q.autoMigrate===!0)}}function V(j,J){switch(j){case"all":return!0;case"major":return J==="major";case"minor":return J==="minor"||J==="patch";case"patch":return J==="patch"}}function b(j=[]){return j.map((J)=>({matchPackages:J.patterns,groupName:J.name,...J.strategy?{strategy:J.strategy}:{}}))}
3
- export{W as rf,A as sf,S as tf,k as uf,T as vf,V as wf,b as xf};
2
+ import{Sf as K}from"./chunk-24xvskkf.js";import{lg as D}from"./chunk-2z2gh050.js";var F=[[0,59],[0,23],[1,31],[1,12],[0,6]];function I(j,J){let[U,B]=F[J],H=new Set;for(let Q of j.split(",")){let[X,Z]=Q.split("/"),q=Z===void 0?1:Number(Z);if(!Number.isInteger(q)||q<1)return null;let $,G;if(X==="*")$=U,G=B;else if(X.includes("-")){let[Y,_]=X.split("-").map(Number);if(!Number.isInteger(Y)||!Number.isInteger(_))return null;$=Y,G=_}else{let Y=Number(X);if(!Number.isInteger(Y))return null;$=Y,G=Y}if($<U||G>B||$>G)return null;for(let Y=$;Y<=G;Y+=q)H.add(Y)}return H.size>0?H:null}function L(j){let J=j.trim().split(/\s+/);if(J.length!==5)return null;let U=J.map((Z,q)=>I(Z,q));if(U.some((Z)=>Z===null))return null;let[,B,H,Q,X]=U;return{hours:B,daysOfMonth:H,months:Q,daysOfWeek:X}}function N(j,J){if(!J)return{hour:j.getHours(),day:j.getDate(),month:j.getMonth()+1,weekday:j.getDay()};let U=new Intl.DateTimeFormat("en-US",{timeZone:J,hour:"numeric",hour12:!1,day:"numeric",month:"numeric",weekday:"short"}),B=Object.fromEntries(U.formatToParts(j).map((Q)=>[Q.type,Q.value])),H=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return{hour:Number(B.hour)%24,day:Number(B.day),month:Number(B.month),weekday:Math.max(0,H.indexOf(B.weekday))}}function C(j,J=new Date,U){let B=L(j);if(!B)return!1;let{hour:H,day:Q,month:X,weekday:Z}=N(J,U);if(!B.hours.has(H)||!B.months.has(X))return!1;let q=B.daysOfMonth.size<31,$=B.daysOfWeek.size<7;if(q&&$)return B.daysOfMonth.has(Q)||B.daysOfWeek.has(Z);return B.daysOfMonth.has(Q)&&B.daysOfWeek.has(Z)}function W(j){if(j.dependencyType==="github-actions")return"github-actions";if(j.dependencyType==="docker-image")return"docker";if(j.dependencyType==="zig-dependencies")return"zig";if(j.dependencyType==="python"||j.dependencyType==="rust"||j.dependencyType==="go"||j.dependencyType==="ruby")return j.dependencyType;if(j.file.endsWith("composer.json")||j.file.endsWith("composer.lock"))return"composer";if(j.file.endsWith("package.json"))return"npm";return"pkgx"}function A(j,J,U=new Date){if(j.matchPackages?.length){if(!K(j.matchPackages).matches(J.name))return!1}if(j.matchEcosystems?.length&&!j.matchEcosystems.includes(W(J)))return!1;if(j.matchDepTypes?.length&&!j.matchDepTypes.includes(J.dependencyType))return!1;if(j.matchUpdateTypes?.length&&!j.matchUpdateTypes.includes(J.updateType))return!1;if(j.matchFiles?.length){if(!K(j.matchFiles).matches(J.file))return!1}if(j.matchCurrentVersion&&!E(J.currentVersion,j.matchCurrentVersion))return!1;if(j.schedule&&!C(j.schedule,U,j.scheduleTimezone))return!1;return!0}function E(j,J){let U=j.replace(/^[\^~>=<\s]+/,"").trim();return U?D(U,J):!1}function S(j,J=[],U=new Date){let B={enabled:!0,labels:[],reviewers:[],assignees:[],prPriority:0};for(let H of J){if(!A(H,j,U))continue;if(H.enabled!==void 0)B.enabled=H.enabled;if(H.strategy!==void 0)B.strategy=H.strategy;if(H.groupName!==void 0)B.groupName=H.groupName;if(H.autoMerge!==void 0)B.autoMerge=H.autoMerge;if(H.minimumReleaseAge!==void 0)B.minimumReleaseAge=H.minimumReleaseAge;if(H.prPriority!==void 0)B.prPriority=H.prPriority;if(H.autoMigrate!==void 0)B.autoMigrate=H.autoMigrate;for(let Q of H.labels??[])if(!B.labels.includes(Q))B.labels.push(Q);for(let Q of H.reviewers??[])if(!B.reviewers.includes(Q))B.reviewers.push(Q);for(let Q of H.assignees??[])if(!B.assignees.includes(Q))B.assignees.push(Q)}return B}function k(j,J=[],U=new Date){let B=[];for(let H of j){let Q=S(H,J,U);if(!Q.enabled)continue;if(Q.strategy&&!V(Q.strategy,H.updateType))continue;B.push({update:H,effects:Q})}return B}function T(j){let J=new Set,U=new Set,B=new Set,H=0;for(let Q of j)Q.labels.forEach((X)=>J.add(X)),Q.reviewers.forEach((X)=>U.add(X)),Q.assignees.forEach((X)=>B.add(X)),H=Math.max(H,Q.prPriority);return{labels:[...J],reviewers:[...U],assignees:[...B],autoMerge:j.length>0&&j.every((Q)=>Q.autoMerge===!0),prPriority:H,autoMigrate:j.some((Q)=>Q.autoMigrate===!0)}}function V(j,J){switch(j){case"all":return!0;case"major":return J==="major";case"minor":return J==="minor"||J==="patch";case"patch":return J==="patch"}}function b(j=[]){return j.map((J)=>({matchPackages:J.patterns,groupName:J.name,...J.strategy?{strategy:J.strategy}:{}}))}
3
+ export{W as sf,A as tf,S as uf,k as vf,T as wf,V as xf,b as yf};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  import{posix as G}from"path";class v extends Error{constructor(q){super(q);this.name="FileChangeValidationError"}}function H(q){let j=G.normalize(q.replaceAll("\\","/").replace(/^\.\/+/,""));if(!j||j==="."||j===".."||j.startsWith("../")||G.isAbsolute(j))throw new v(`Refusing unsafe repository path: ${JSON.stringify(q)}`);return j}async function J(q,j){for(let B of q){let D=H(B.path);if(B.type==="update"&&!await j(D))throw new v(`Refusing to create missing update target: ${D}. Use change type "create" for intentional new files.`)}}
3
- export{v as Zf,H as _f,J as $f};
3
+ export{v as _f,H as $f,J as ag};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{dd as Z}from"./chunk-785rgtn5.js";import{Mh as _}from"./chunk-8dj94fsy.js";import Y from"process";class L{jobs=new Map;timers=new Map;logger;isRunning=!1;constructor(q=!1){this.logger=q?_.verbose():_.quiet()}addJob(q){this.jobs.set(q.id,q),this.scheduleJob(q),this.logger.info(`Scheduled job '${q.name}' with cron: ${q.schedule.cron}`)}removeJob(q){let C=this.timers.get(q);if(C)clearTimeout(C),this.timers.delete(q);this.jobs.delete(q),this.logger.info(`Removed scheduled job: ${q}`)}start(){if(this.isRunning){this.logger.warn("Scheduler is already running");return}this.isRunning=!0,this.logger.info("\uD83D\uDD52 Buddy Scheduler started");for(let q of this.jobs.values())if(this.scheduleJob(q),q.schedule.runOnStartup)this.logger.info(`Running startup job: ${q.name}`),setImmediate(()=>this.runJob(q));Y.on("SIGINT",()=>this.stop()),Y.on("SIGTERM",()=>this.stop())}stop(){if(!this.isRunning)return;this.isRunning=!1,this.logger.info("\uD83D\uDED1 Stopping Buddy Scheduler...");for(let q of this.timers.values())clearTimeout(q);this.timers.clear(),this.logger.success("\u2705 Buddy Scheduler stopped"),Y.exit(0)}getJobStatus(q){return this.jobs.get(q)}getAllJobs(){return Array.from(this.jobs.values())}scheduleJob(q){let C=this.timers.get(q.id);if(C)clearTimeout(C);let D=this.getNextRunTime(q.schedule.cron,q.schedule.timezone);if(q.nextRun=D||void 0,D){let G=D.getTime()-Date.now(),F=setTimeout(()=>{this.runJob(q),this.scheduleJob(q)},G);this.timers.set(q.id,F),this.logger.debug(`Job '${q.name}' scheduled for ${D.toISOString()}`)}}async runJob(q){if(q.status==="running"){this.logger.warn(`Job '${q.name}' is already running, skipping`);return}q.status="running",q.lastRun=new Date,this.logger.info(`\uD83D\uDE80 Running scheduled job: ${q.name}`);let C=Date.now(),D=q.schedule.maxRuntime||1800000;try{let G=new Promise((Q,U)=>{setTimeout(()=>U(Error("Job timeout")),D)}),F=this.executeJob(q);await Promise.race([F,G]);let J=Date.now()-C;q.status="idle",this.logger.success(`\u2705 Job '${q.name}' completed in ${J}ms`)}catch(G){q.status="error",this.logger.error(`\u274C Job '${q.name}' failed:`,G)}}async executeJob(q){let C=new Z(q.config),D=await C.scanForUpdates();if(D.updates.length===0){this.logger.info("No dependency updates found");return}if(this.logger.info(`Found ${D.updates.length} dependency updates`),q.config.repository&&q.config.pullRequest)await C.createPullRequests(D),this.logger.success(`Created pull requests for ${D.groups.length} update groups`);else this.logger.info("Repository not configured, skipping PR creation")}getNextRunTime(q,C){try{return this.parseCronExpression(q,C)}catch(D){return this.logger.error(`Invalid cron expression '${q}':`,D),null}}parseCronExpression(q,C){let D=q.trim().split(/\s+/);if(D.length!==5)throw Error("Cron expression must have 5 parts: minute hour day month dayOfWeek");let[G,F,J,Q,U]=D,K=new Date,V=C?this.timezoneOffsetMinutes(K,C):0;if(C)this.logger.debug(`Using timezone: ${C} (offset ${V} minutes)`);let X=new Date(K.getTime()+V*60*1000);X.setSeconds(0,0);let $=this.parseCronField(F,0,23),B=this.parseCronField(G,0,59);if($.length>0&&B.length>0){if(X.setHours($[0],B[0],0,0),X.getTime()-V*60*1000<=K.getTime())X.setDate(X.getDate()+1);return new Date(X.getTime()-V*60*1000)}return new Date(K.getTime()+3600000)}timezoneOffsetMinutes(q,C){try{let D=new Date(q.toLocaleString("en-US",{timeZone:C})),G=new Date(q.toLocaleString("en-US"));return Math.round((D.getTime()-G.getTime())/60000)}catch{return this.logger.warn(`\u26A0\uFE0F Unknown timezone "${C}", scheduling in host time instead`),0}}parseCronField(q,C,D){if(q==="*")return Array.from({length:D-C+1},(F,J)=>C+J);if(q.includes(","))return q.split(",").map(Number).filter((F)=>Number.isFinite(F)&&F>=C&&F<=D);if(q.includes("-")){let F=q.split("-").map(Number),J=F[0],Q=F[1];if(F.length!==2||!Number.isFinite(J)||!Number.isFinite(Q)||Q<J)return[];return Array.from({length:Q-J+1},(U,K)=>J+K).filter((U)=>U>=C&&U<=D)}if(q.includes("/")){let[F,J]=q.split("/"),Q=Number(J);if(!Number.isFinite(Q)||Q<=0)return[];if(F==="*")return Array.from({length:D-C+1},(K,V)=>C+V).filter((K,V)=>V%Q===0);let U=Number(F);return Number.isFinite(U)?[U].filter((K)=>K>=C&&K<=D):[]}let G=Number(q);return Number.isFinite(G)&&G>=C&&G<=D?[G]:[]}static createJobFromConfig(q,C="default"){let D={cron:q.schedule?.cron||"0 2 * * 1",timezone:q.schedule?.timezone,runOnStartup:!1,maxRuntime:1800000};return{id:C,name:`Buddy Dependency Updates (${C})`,schedule:D,status:"idle",config:q}}static PRESETS={DAILY:"0 2 * * *",WEEKLY:"0 2 * * 1",WEEKDAYS:"0 2 * * 1-5",TWICE_WEEKLY:"0 2 * * 1,4",MONTHLY:"0 2 1 * *",HOURLY:"0 * * * *",CUSTOM:(q,C,D="*")=>`${q} ${C} * * ${D}`}}
2
+ import{ed as Z}from"./chunk-rygtb1x3.js";import{Nh as _}from"./chunk-x1w6q9tk.js";import Y from"process";class L{jobs=new Map;timers=new Map;logger;isRunning=!1;constructor(q=!1){this.logger=q?_.verbose():_.quiet()}addJob(q){this.jobs.set(q.id,q),this.scheduleJob(q),this.logger.info(`Scheduled job '${q.name}' with cron: ${q.schedule.cron}`)}removeJob(q){let C=this.timers.get(q);if(C)clearTimeout(C),this.timers.delete(q);this.jobs.delete(q),this.logger.info(`Removed scheduled job: ${q}`)}start(){if(this.isRunning){this.logger.warn("Scheduler is already running");return}this.isRunning=!0,this.logger.info("\uD83D\uDD52 Buddy Scheduler started");for(let q of this.jobs.values())if(this.scheduleJob(q),q.schedule.runOnStartup)this.logger.info(`Running startup job: ${q.name}`),setImmediate(()=>this.runJob(q));Y.on("SIGINT",()=>this.stop()),Y.on("SIGTERM",()=>this.stop())}stop(){if(!this.isRunning)return;this.isRunning=!1,this.logger.info("\uD83D\uDED1 Stopping Buddy Scheduler...");for(let q of this.timers.values())clearTimeout(q);this.timers.clear(),this.logger.success("\u2705 Buddy Scheduler stopped"),Y.exit(0)}getJobStatus(q){return this.jobs.get(q)}getAllJobs(){return Array.from(this.jobs.values())}scheduleJob(q){let C=this.timers.get(q.id);if(C)clearTimeout(C);let D=this.getNextRunTime(q.schedule.cron,q.schedule.timezone);if(q.nextRun=D||void 0,D){let G=D.getTime()-Date.now(),F=setTimeout(()=>{this.runJob(q),this.scheduleJob(q)},G);this.timers.set(q.id,F),this.logger.debug(`Job '${q.name}' scheduled for ${D.toISOString()}`)}}async runJob(q){if(q.status==="running"){this.logger.warn(`Job '${q.name}' is already running, skipping`);return}q.status="running",q.lastRun=new Date,this.logger.info(`\uD83D\uDE80 Running scheduled job: ${q.name}`);let C=Date.now(),D=q.schedule.maxRuntime||1800000;try{let G=new Promise((Q,U)=>{setTimeout(()=>U(Error("Job timeout")),D)}),F=this.executeJob(q);await Promise.race([F,G]);let J=Date.now()-C;q.status="idle",this.logger.success(`\u2705 Job '${q.name}' completed in ${J}ms`)}catch(G){q.status="error",this.logger.error(`\u274C Job '${q.name}' failed:`,G)}}async executeJob(q){let C=new Z(q.config),D=await C.scanForUpdates();if(D.updates.length===0){this.logger.info("No dependency updates found");return}if(this.logger.info(`Found ${D.updates.length} dependency updates`),q.config.repository&&q.config.pullRequest)await C.createPullRequests(D),this.logger.success(`Created pull requests for ${D.groups.length} update groups`);else this.logger.info("Repository not configured, skipping PR creation")}getNextRunTime(q,C){try{return this.parseCronExpression(q,C)}catch(D){return this.logger.error(`Invalid cron expression '${q}':`,D),null}}parseCronExpression(q,C){let D=q.trim().split(/\s+/);if(D.length!==5)throw Error("Cron expression must have 5 parts: minute hour day month dayOfWeek");let[G,F,J,Q,U]=D,K=new Date,V=C?this.timezoneOffsetMinutes(K,C):0;if(C)this.logger.debug(`Using timezone: ${C} (offset ${V} minutes)`);let X=new Date(K.getTime()+V*60*1000);X.setSeconds(0,0);let $=this.parseCronField(F,0,23),B=this.parseCronField(G,0,59);if($.length>0&&B.length>0){if(X.setHours($[0],B[0],0,0),X.getTime()-V*60*1000<=K.getTime())X.setDate(X.getDate()+1);return new Date(X.getTime()-V*60*1000)}return new Date(K.getTime()+3600000)}timezoneOffsetMinutes(q,C){try{let D=new Date(q.toLocaleString("en-US",{timeZone:C})),G=new Date(q.toLocaleString("en-US"));return Math.round((D.getTime()-G.getTime())/60000)}catch{return this.logger.warn(`\u26A0\uFE0F Unknown timezone "${C}", scheduling in host time instead`),0}}parseCronField(q,C,D){if(q==="*")return Array.from({length:D-C+1},(F,J)=>C+J);if(q.includes(","))return q.split(",").map(Number).filter((F)=>Number.isFinite(F)&&F>=C&&F<=D);if(q.includes("-")){let F=q.split("-").map(Number),J=F[0],Q=F[1];if(F.length!==2||!Number.isFinite(J)||!Number.isFinite(Q)||Q<J)return[];return Array.from({length:Q-J+1},(U,K)=>J+K).filter((U)=>U>=C&&U<=D)}if(q.includes("/")){let[F,J]=q.split("/"),Q=Number(J);if(!Number.isFinite(Q)||Q<=0)return[];if(F==="*")return Array.from({length:D-C+1},(K,V)=>C+V).filter((K,V)=>V%Q===0);let U=Number(F);return Number.isFinite(U)?[U].filter((K)=>K>=C&&K<=D):[]}let G=Number(q);return Number.isFinite(G)&&G>=C&&G<=D?[G]:[]}static createJobFromConfig(q,C="default"){let D={cron:q.schedule?.cron||"0 2 * * 1",timezone:q.schedule?.timezone,runOnStartup:!1,maxRuntime:1800000};return{id:C,name:`Buddy Dependency Updates (${C})`,schedule:D,status:"idle",config:q}}static PRESETS={DAILY:"0 2 * * *",WEEKLY:"0 2 * * 1",WEEKDAYS:"0 2 * * 1-5",TWICE_WEEKLY:"0 2 * * 1,4",MONTHLY:"0 2 1 * *",HOURLY:"0 * * * *",CUSTOM:(q,C,D="*")=>`${q} ${C} * * ${D}`}}
3
3
  export{L as Da};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{dl as Z}from"./chunk-s3ksf6s5.js";import x from"process";var K=["github","gitlab","bitbucket"],$=["github","gitlab","bitbucket"],H={},L={pinIssues:!1,checkRuns:!1,inlineReviewComments:!1,reviewSuggestions:!1,nativeAutoMerge:!1,commentReactions:!1,ciLogs:!1,ciRuns:!1,reviewThreads:!1,teamReviewers:!1,draftPullRequests:!1,permissionLookup:!1,branchHousekeeping:!1,reopenPullRequests:!1,labels:!1};class Y extends Error{provider;trackingIssue;constructor(j,z,F){super(j);this.provider=z;this.trackingIssue=F;this.name="UnsupportedProviderError"}}var B={github:["GITHUB_TOKEN","BUDDY_TOKEN"],gitlab:["CI_JOB_TOKEN","GITLAB_TOKEN","BUDDY_TOKEN"],bitbucket:["BITBUCKET_TOKEN","BUDDY_TOKEN"]};function A(j,z=x.env){for(let F of B[j]??[]){let J=z[F]?.trim();if(J)return{token:J,source:F}}return null}function C(j){if($.includes(j))return;let z=H[j];if(z)throw new Y(`'${j}' support is not implemented yet \u2014 follow ${z}. Supported today: ${$.join(", ")}.`,j,z);throw new Y(`Unknown git provider '${j}'. Supported: ${$.join(", ")}.`,j)}async function M(j,z={}){let F=j.provider??"github";C(F);let J=z.env??x.env,X=j.token??A(F,J)?.token;if(!X)throw Error(`No token for ${F}. Set one of: ${B[F].join(", ")}.`);switch(F){case"gitlab":{let{GitLabProvider:Q}=await import("./chunk-00vbhh0z.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"bitbucket":{let{BitbucketProvider:Q}=await import("./chunk-gw69sjx2.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"github":{let{GitHubProvider:Q}=await import("./chunk-9634xcvq.js"),q=j.workflowToken??J.BUDDY_TOKEN;return new Q(X,j.owner,j.name,Boolean(q),q,j.apiUrl,z.logger)}}}function W(j,z,F){return j.capabilities()[z]===!0&&typeof j[F]==="function"}function S(j,z,F,J){if(W(j,z,F))return;throw new Y(`This provider does not support ${J} (missing capability '${z}').`,"unknown")}
3
- export{K as he,$ as ie,H as je,L as ke,Y as le,B as me,A as ne,C as oe,M as pe,W as qe,S as re};
2
+ import{el as Z}from"./chunk-kbvj6qxc.js";import x from"process";var K=["github","gitlab","bitbucket"],$=["github","gitlab","bitbucket"],H={},L={pinIssues:!1,checkRuns:!1,inlineReviewComments:!1,reviewSuggestions:!1,nativeAutoMerge:!1,commentReactions:!1,ciLogs:!1,ciRuns:!1,reviewThreads:!1,teamReviewers:!1,draftPullRequests:!1,permissionLookup:!1,branchHousekeeping:!1,reopenPullRequests:!1,labels:!1};class Y extends Error{provider;trackingIssue;constructor(j,z,F){super(j);this.provider=z;this.trackingIssue=F;this.name="UnsupportedProviderError"}}var B={github:["GITHUB_TOKEN","BUDDY_TOKEN"],gitlab:["CI_JOB_TOKEN","GITLAB_TOKEN","BUDDY_TOKEN"],bitbucket:["BITBUCKET_TOKEN","BUDDY_TOKEN"]};function A(j,z=x.env){for(let F of B[j]??[]){let J=z[F]?.trim();if(J)return{token:J,source:F}}return null}function C(j){if($.includes(j))return;let z=H[j];if(z)throw new Y(`'${j}' support is not implemented yet \u2014 follow ${z}. Supported today: ${$.join(", ")}.`,j,z);throw new Y(`Unknown git provider '${j}'. Supported: ${$.join(", ")}.`,j)}async function M(j,z={}){let F=j.provider??"github";C(F);let J=z.env??x.env,X=j.token??A(F,J)?.token;if(!X)throw Error(`No token for ${F}. Set one of: ${B[F].join(", ")}.`);switch(F){case"gitlab":{let{GitLabProvider:Q}=await import("./chunk-rphwf28s.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"bitbucket":{let{BitbucketProvider:Q}=await import("./chunk-vpsvtb9v.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"github":{let{GitHubProvider:Q}=await import("./chunk-ktzvchps.js"),q=j.workflowToken??J.BUDDY_TOKEN;return new Q(X,j.owner,j.name,Boolean(q),q,j.apiUrl,z.logger)}}}function W(j,z,F){return j.capabilities()[z]===!0&&typeof j[F]==="function"}function S(j,z,F,J){if(W(j,z,F))return;throw new Y(`This provider does not support ${J} (missing capability '${z}').`,"unknown")}
3
+ export{K as ie,$ as je,H as ke,L as le,Y as me,B as ne,A as oe,C as pe,M as qe,W as re,S as se};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{mb as w}from"./chunk-fpzgxg8a.js";import{Ab as u,Bb as v,Cb as x,Db as y,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,vb as l,wb as q,xb as r,yb as s,zb as t}from"./chunk-s3q7g2hy.js";import{Eb as a,Fb as b,Gb as c}from"./chunk-q2tjkhez.js";import{Lb as m,Mb as n,Nb as o,Pb as p}from"./chunk-5yfaptmp.js";import"./chunk-y7z0br2x.js";import"./chunk-ggzjv4s0.js";import{Dd as z,Ed as A,Fd as B,Gd as C,Hd as D,Id as E,Jd as F,Kd as G,Ld as H,Md as I}from"./chunk-bggpgbdx.js";import"./chunk-be059ncv.js";import"./chunk-xny4kgcc.js";import"./chunk-34rmja4x.js";import"./chunk-emygmh7r.js";import"./chunk-kpqez1ht.js";import"./chunk-a3bnhq58.js";import"./chunk-8dj94fsy.js";import"./chunk-s3ksf6s5.js";export{g as validateFindings,I as shouldFail,n as serializeReviewState,y as runReviewForPR,x as reviewPullRequest,j as reviewDiff,w as resolveBuddyThreads,u as renderFinding,b as renderDiffForReview,v as prepareReview,a as parseUnifiedDiff,o as parseReviewState,p as needsReview,s as loadGuidelines,G as formatReview,C as formatPretty,D as formatGithub,E as formatAgent,f as fingerprint,A as diffArgsFor,l as defaultIncludePath,h as dedupeFindings,F as countBySeverity,t as composeInstructions,B as collectLocalDiff,c as collectGitDiff,H as applySuggestion,k as anchorMap,d as SEVERITY_ORDER,m as REVIEW_STATE_VERSION,e as REVIEW_SCHEMA,z as REVIEW_FORMATS,r as MAX_GUIDELINE_CHARS,q as DEFAULT_GUIDELINE_FILES,i as DEFAULT_EXCLUDED_PATHS};
2
+ import{mb as w}from"./chunk-fmkb816y.js";import{Ab as u,Bb as v,Cb as x,Db as y,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,vb as l,wb as q,xb as r,yb as s,zb as t}from"./chunk-xqveh8a5.js";import{Eb as a,Fb as b,Gb as c}from"./chunk-q2tjkhez.js";import{Lb as m,Mb as n,Nb as o,Pb as p}from"./chunk-5yfaptmp.js";import"./chunk-59993g25.js";import"./chunk-va3k91tf.js";import{Ed as z,Fd as A,Gd as B,Hd as C,Id as D,Jd as E,Kd as F,Ld as G,Md as H,Nd as I}from"./chunk-7m3pzkcj.js";import"./chunk-0g4ybxwj.js";import"./chunk-142zh7e5.js";import"./chunk-ctdfppxk.js";import"./chunk-24xvskkf.js";import"./chunk-z18bksyr.js";import"./chunk-b9szrnxw.js";import"./chunk-x1w6q9tk.js";import"./chunk-kbvj6qxc.js";export{g as validateFindings,I as shouldFail,n as serializeReviewState,y as runReviewForPR,x as reviewPullRequest,j as reviewDiff,w as resolveBuddyThreads,u as renderFinding,b as renderDiffForReview,v as prepareReview,a as parseUnifiedDiff,o as parseReviewState,p as needsReview,s as loadGuidelines,G as formatReview,C as formatPretty,D as formatGithub,E as formatAgent,f as fingerprint,A as diffArgsFor,l as defaultIncludePath,h as dedupeFindings,F as countBySeverity,t as composeInstructions,B as collectLocalDiff,c as collectGitDiff,H as applySuggestion,k as anchorMap,d as SEVERITY_ORDER,m as REVIEW_STATE_VERSION,e as REVIEW_SCHEMA,z as REVIEW_FORMATS,r as MAX_GUIDELINE_CHARS,q as DEFAULT_GUIDELINE_FILES,i as DEFAULT_EXCLUDED_PATHS};