@buddysh/buddy 0.11.17 → 0.11.19

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 (180) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +12 -0
  3. package/bin/cli.ts +92 -72
  4. package/dist/bin/cli.js +73 -107
  5. package/dist/bin/entry.d.ts +1 -0
  6. package/dist/bin/entry.js +3 -0
  7. package/dist/bin/stacks.d.ts +1 -0
  8. package/dist/bin/stacks.js +3 -0
  9. package/dist/chunk-05nyhkdp.js +2 -0
  10. package/dist/{chunk-hd74jxm2.js → chunk-065sjjzg.js} +2 -2
  11. package/dist/chunk-0796xk82.js +2 -0
  12. package/dist/{chunk-bnp0r4eh.js → chunk-0pf9vk80.js} +1 -1
  13. package/dist/chunk-11599831.js +2 -0
  14. package/dist/chunk-1et7ppg7.js +2 -0
  15. package/dist/chunk-20sxtyt7.js +3 -0
  16. package/dist/chunk-23cjwxjk.js +2 -0
  17. package/dist/{chunk-cj4d5ad7.js → chunk-2g8r8khw.js} +1 -1
  18. package/dist/{chunk-cb25v2mp.js → chunk-2v4b940m.js} +1 -1
  19. package/dist/{chunk-nk8wxxy7.js → chunk-33ymc651.js} +2 -2
  20. package/dist/{chunk-0kce7e60.js → chunk-3pg9420w.js} +1 -1
  21. package/dist/{chunk-1a14rx5n.js → chunk-47k0qdd5.js} +2 -2
  22. package/dist/chunk-4gf3a9pm.js +2 -0
  23. package/dist/chunk-4we8d2ys.js +2 -0
  24. package/dist/{chunk-1g43mpqn.js → chunk-539wp217.js} +1 -1
  25. package/dist/{chunk-j57716xw.js → chunk-58et72hc.js} +1 -1
  26. package/dist/{chunk-743mhx0e.js → chunk-5feeegzy.js} +2 -2
  27. package/dist/{chunk-1pecmenc.js → chunk-5nn5mms4.js} +1 -1
  28. package/dist/{chunk-j46f90n8.js → chunk-5q5tm30a.js} +1 -1
  29. package/dist/{chunk-t1r2ycn7.js → chunk-5qxs04gf.js} +1 -1
  30. package/dist/{chunk-9chq5m4p.js → chunk-5ytyahtm.js} +4 -4
  31. package/dist/chunk-6477cdgj.js +2 -0
  32. package/dist/{chunk-s3b3vrsj.js → chunk-6bdrm4ab.js} +2 -2
  33. package/dist/{chunk-psjrcpgb.js → chunk-6kmaj5br.js} +2 -2
  34. package/dist/chunk-6m03hqbw.js +3 -0
  35. package/dist/{chunk-whtdmv3p.js → chunk-73a090ce.js} +2 -2
  36. package/dist/chunk-78pxywjv.js +2 -0
  37. package/dist/{chunk-nznpzbq4.js → chunk-7bqy4enq.js} +1 -1
  38. package/dist/chunk-843907bh.js +2 -0
  39. package/dist/{chunk-dxd0eg4r.js → chunk-88jx1n4t.js} +1 -1
  40. package/dist/{chunk-gq9gkyah.js → chunk-89spjk6r.js} +2 -2
  41. package/dist/chunk-8fm0z13m.js +2 -0
  42. package/dist/{chunk-sj7n6xa1.js → chunk-8hstj0s3.js} +1 -1
  43. package/dist/{chunk-6w0n6c07.js → chunk-8y4szfd2.js} +1 -1
  44. package/dist/{chunk-2f7j0dmw.js → chunk-91q9x0df.js} +1 -1
  45. package/dist/chunk-9pt7kwmm.js +2 -0
  46. package/dist/{chunk-mthd2c8m.js → chunk-a5hevn6e.js} +2 -2
  47. package/dist/{chunk-sddaassq.js → chunk-agdvymzh.js} +1 -1
  48. package/dist/{chunk-8r2819xn.js → chunk-ar8skamr.js} +1 -1
  49. package/dist/chunk-b8n7zh62.js +2 -0
  50. package/dist/chunk-by2hfewp.js +2 -0
  51. package/dist/{chunk-4chtv4nh.js → chunk-c7ja1xmh.js} +1 -1
  52. package/dist/chunk-cfj98vmf.js +2 -0
  53. package/dist/{chunk-wk175yyw.js → chunk-cp3g2srn.js} +2 -2
  54. package/dist/chunk-cxbrnbcp.js +2 -0
  55. package/dist/{chunk-wfwrm4k3.js → chunk-dev3g0n3.js} +1 -1
  56. package/dist/{chunk-mr2d1zp0.js → chunk-dgcct70c.js} +2 -2
  57. package/dist/{chunk-16aeend1.js → chunk-dh8yykbg.js} +1 -1
  58. package/dist/{chunk-m3rftash.js → chunk-dkgz8hsd.js} +7 -7
  59. package/dist/{chunk-byqzhgzs.js → chunk-dmaxdw65.js} +1 -1
  60. package/dist/chunk-e0d1n3yn.js +2 -0
  61. package/dist/{chunk-1pdvjg0x.js → chunk-ebb90mp9.js} +1 -1
  62. package/dist/chunk-ece98jde.js +2 -0
  63. package/dist/{chunk-gg1ddvnf.js → chunk-ednwgr1b.js} +2 -2
  64. package/dist/{chunk-69qyr9ef.js → chunk-ejfyc7r8.js} +1 -1
  65. package/dist/{chunk-wfg3bp85.js → chunk-en525sf9.js} +1 -1
  66. package/dist/{chunk-d09qj570.js → chunk-eq5xb8k1.js} +2 -2
  67. package/dist/{chunk-h2f92qwd.js → chunk-ewnhhpak.js} +1 -1
  68. package/dist/{chunk-1jgh0ff1.js → chunk-f3fmewqb.js} +2 -2
  69. package/dist/chunk-f694pp35.js +2 -0
  70. package/dist/{chunk-r1jvyhhd.js → chunk-fcax5a60.js} +2 -2
  71. package/dist/{chunk-pxfrq43h.js → chunk-ffjp134d.js} +1 -1
  72. package/dist/{chunk-vs61069x.js → chunk-g763t4rr.js} +1 -1
  73. package/dist/chunk-h65g7hd0.js +2 -0
  74. package/dist/{chunk-c63e4ssc.js → chunk-h9deve0y.js} +3 -3
  75. package/dist/chunk-hfq56cgn.js +2 -0
  76. package/dist/chunk-hwpv7jhw.js +1043 -0
  77. package/dist/chunk-j9pe2np4.js +5 -0
  78. package/dist/chunk-jq846den.js +2 -0
  79. package/dist/{chunk-26yejy1v.js → chunk-jxmpwday.js} +1 -1
  80. package/dist/{chunk-wc2z7krw.js → chunk-jy1kbr1k.js} +2 -2
  81. package/dist/{chunk-6gvx1g6h.js → chunk-m6qym0ya.js} +2 -2
  82. package/dist/chunk-nezqdnp3.js +2 -0
  83. package/dist/{chunk-7m3pzkcj.js → chunk-ng9zksy3.js} +1 -1
  84. package/dist/{chunk-7p1b809h.js → chunk-nmrf0ydg.js} +1 -1
  85. package/dist/{chunk-0f1xye20.js → chunk-pxv58dh1.js} +1 -1
  86. package/dist/{chunk-2z9mh5y4.js → chunk-q3dg57xx.js} +1 -1
  87. package/dist/chunk-q9x936wq.js +2 -0
  88. package/dist/{chunk-jqh7vx2n.js → chunk-qbqk1jax.js} +2 -2
  89. package/dist/{chunk-ewhvahnb.js → chunk-qfm0eh6y.js} +2 -2
  90. package/dist/{chunk-g09atq0m.js → chunk-qn1g860m.js} +1 -1
  91. package/dist/{chunk-yh13j2af.js → chunk-r0jmwzr3.js} +1 -1
  92. package/dist/chunk-rmv4ajb2.js +2 -0
  93. package/dist/{chunk-wzncz6j5.js → chunk-rrm4x81p.js} +1 -1
  94. package/dist/chunk-rsvtnsmt.js +2 -0
  95. package/dist/{chunk-24xvskkf.js → chunk-rwzt9xvk.js} +1 -1
  96. package/dist/{chunk-qngnmrpw.js → chunk-ry21xmre.js} +1 -1
  97. package/dist/{chunk-67bjaw56.js → chunk-s6w47z4a.js} +3 -3
  98. package/dist/chunk-sek2e857.js +2 -0
  99. package/dist/{chunk-s0ps33ft.js → chunk-sg7bhtb7.js} +1 -1
  100. package/dist/{chunk-r7qa2ykf.js → chunk-snya72ah.js} +2 -2
  101. package/dist/{chunk-a8wcn3mh.js → chunk-t7grk0az.js} +2 -2
  102. package/dist/chunk-tes3e84x.js +2 -0
  103. package/dist/chunk-tgm4vbaq.js +2 -0
  104. package/dist/{chunk-142zh7e5.js → chunk-tqwek43e.js} +1 -1
  105. package/dist/{chunk-mtn4angk.js → chunk-tztc0r76.js} +1 -1
  106. package/dist/chunk-v0895nt9.js +2 -0
  107. package/dist/chunk-v6rrvfh4.js +2 -0
  108. package/dist/{chunk-k8sd78td.js → chunk-vn4c8fxq.js} +1 -1
  109. package/dist/{chunk-4r03rh93.js → chunk-vpz26asn.js} +2 -2
  110. package/dist/{chunk-x9vpk4kk.js → chunk-vxt1h0c4.js} +1 -1
  111. package/dist/chunk-vyckmje5.js +2 -0
  112. package/dist/{chunk-4dz5x4xw.js → chunk-wca85ahg.js} +1 -1
  113. package/dist/chunk-we1n57ze.js +2 -0
  114. package/dist/{chunk-5yfaptmp.js → chunk-wm6g7y1r.js} +1 -1
  115. package/dist/chunk-wnqqprmy.js +2 -0
  116. package/dist/chunk-wt8b3ywq.js +2 -0
  117. package/dist/{chunk-bw43q8k7.js → chunk-wx4qd9e9.js} +1 -1
  118. package/dist/chunk-x0mq8nn2.js +2 -0
  119. package/dist/{chunk-her5azyp.js → chunk-x9spxa46.js} +2 -2
  120. package/dist/chunk-xfk9a8az.js +2 -0
  121. package/dist/{chunk-gvpsbmeg.js → chunk-xmk24pz9.js} +2 -2
  122. package/dist/{chunk-6b0fmw0d.js → chunk-xn2xv07k.js} +2 -2
  123. package/dist/chunk-xntpzagn.js +3 -0
  124. package/dist/{chunk-bafzw99p.js → chunk-xqcmw7d0.js} +2 -2
  125. package/dist/chunk-xvq8w2jm.js +2 -0
  126. package/dist/{chunk-4wv5s3vr.js → chunk-xyry3bma.js} +2 -2
  127. package/dist/{chunk-hk4d7rky.js → chunk-y6292gbf.js} +2 -2
  128. package/dist/chunk-ye3aym4p.js +2 -0
  129. package/dist/{chunk-7hm46cej.js → chunk-yx9v94q5.js} +2 -2
  130. package/dist/chunk-yxt8294f.js +2 -0
  131. package/dist/{chunk-vckhctmr.js → chunk-yy8vb4yk.js} +1 -1
  132. package/dist/{chunk-fsghqtgf.js → chunk-z0avay86.js} +2 -2
  133. package/dist/{chunk-z2gcfvze.js → chunk-z906zp4k.js} +5 -5
  134. package/dist/chunk-zy6azdxt.js +2 -0
  135. package/dist/src/index.js +1 -1
  136. package/dist/src/setup.js +1 -1
  137. package/dist/src/stacks-cli.d.ts +7 -0
  138. package/package.json +5 -5
  139. package/dist/chunk-0n03s02h.js +0 -2
  140. package/dist/chunk-1k4p8wyx.js +0 -2
  141. package/dist/chunk-1mkwhnsf.js +0 -2
  142. package/dist/chunk-2309x9r7.js +0 -2
  143. package/dist/chunk-3jm67wxm.js +0 -2
  144. package/dist/chunk-3mnpvfg3.js +0 -2
  145. package/dist/chunk-485kgdtb.js +0 -2
  146. package/dist/chunk-51m5tgwp.js +0 -2
  147. package/dist/chunk-5t07s3dv.js +0 -2
  148. package/dist/chunk-6bqs7rtc.js +0 -2
  149. package/dist/chunk-6kd81nf9.js +0 -1070
  150. package/dist/chunk-8b7cwedf.js +0 -2
  151. package/dist/chunk-8wrbxhs3.js +0 -2
  152. package/dist/chunk-9fagkyrp.js +0 -2
  153. package/dist/chunk-9gabxm8n.js +0 -2
  154. package/dist/chunk-bgb44971.js +0 -2
  155. package/dist/chunk-bz5yx7g6.js +0 -2
  156. package/dist/chunk-dttp44vs.js +0 -2
  157. package/dist/chunk-fzs7vpps.js +0 -2
  158. package/dist/chunk-gkb0gja4.js +0 -2
  159. package/dist/chunk-hxkxset4.js +0 -2
  160. package/dist/chunk-jgq5d6s2.js +0 -2
  161. package/dist/chunk-km4aszfp.js +0 -2
  162. package/dist/chunk-kthwzc4p.js +0 -2
  163. package/dist/chunk-m9qtb4xj.js +0 -2
  164. package/dist/chunk-p9xksx9p.js +0 -2
  165. package/dist/chunk-pag93kz1.js +0 -2
  166. package/dist/chunk-q4j2f72t.js +0 -2
  167. package/dist/chunk-qbep9dk4.js +0 -2
  168. package/dist/chunk-rqj1vrfs.js +0 -2
  169. package/dist/chunk-s4fccg73.js +0 -2
  170. package/dist/chunk-tjj6ttj1.js +0 -2
  171. package/dist/chunk-tsd9jw07.js +0 -2
  172. package/dist/chunk-ttkjzy0m.js +0 -2
  173. package/dist/chunk-txe5z472.js +0 -2
  174. package/dist/chunk-vffz69jj.js +0 -2
  175. package/dist/chunk-wn9vr9ct.js +0 -2
  176. package/dist/chunk-y2ntnpdb.js +0 -2
  177. package/dist/chunk-y5fdq7cd.js +0 -2
  178. package/dist/chunk-yr6qyeab.js +0 -2
  179. package/dist/chunk-z18bksyr.js +0 -3
  180. package/dist/chunk-zj2pt1bx.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Rh as x}from"./chunk-wzncz6j5.js";import{lstat as R}from"fs/promises";import{join as W}from"path";var N=/^catalog:(.*)$/;function S(X){let J;try{J=Bun.YAML.parse(X)}catch{return{entries:[],hasCatalogs:!1}}if(typeof J!=="object"||J===null)return{entries:[],hasCatalogs:!1};let B=J,z=[],Z=!1,H=(M,U)=>{if(typeof M!=="object"||M===null||Array.isArray(M))return;Z=!0;for(let[j,q]of Object.entries(M))if(typeof q==="string"&&q.trim())z.push({name:j,version:q.trim(),catalog:U})};if(H(B.catalog,"default"),typeof B.catalogs==="object"&&B.catalogs!==null)for(let[M,U]of Object.entries(B.catalogs))H(U,M);return{entries:z,hasCatalogs:Z}}function w(X,J,B){let z=N.exec(X.trim());if(!z)return null;let Z=z[1].trim()||"default";return J.find((H)=>H.name===B&&H.catalog===Z)?.version??null}function f(X){return N.test(X.trim())}function V(X,J,B){let z=X.split(`
2
+ import{Wh as x}from"./chunk-rrm4x81p.js";import{lstat as R}from"fs/promises";import{join as W}from"path";var N=/^catalog:(.*)$/;function S(X){let J;try{J=Bun.YAML.parse(X)}catch{return{entries:[],hasCatalogs:!1}}if(typeof J!=="object"||J===null)return{entries:[],hasCatalogs:!1};let B=J,z=[],Z=!1,H=(M,U)=>{if(typeof M!=="object"||M===null||Array.isArray(M))return;Z=!0;for(let[j,q]of Object.entries(M))if(typeof q==="string"&&q.trim())z.push({name:j,version:q.trim(),catalog:U})};if(H(B.catalog,"default"),typeof B.catalogs==="object"&&B.catalogs!==null)for(let[M,U]of Object.entries(B.catalogs))H(U,M);return{entries:z,hasCatalogs:Z}}function w(X,J,B){let z=N.exec(X.trim());if(!z)return null;let Z=z[1].trim()||"default";return J.find((H)=>H.name===B&&H.catalog===Z)?.version??null}function f(X){return N.test(X.trim())}function V(X,J,B){let z=X.split(`
3
3
  `),Z=/^(\s*)(["']?)([^"':]+)\2(\s*:\s*)(["']?)(.+?)\5(\s*(?:#.*)?)$/,H=null,M=!1,U=0;for(let j=0;j<z.length;j++){let q=z[j],F=q.length-q.trimStart().length,Y=q.trim();if(/^catalog\s*:\s*$/.test(Y)){H="default",M=!1;continue}if(/^catalogs\s*:\s*$/.test(Y)){M=!0,U=F,H=null;continue}if(M&&F>U&&/^[\w@./-]+\s*:\s*$/.test(Y)){H=Y.replace(/\s*:\s*$/,"");continue}if(M&&Y&&F<=U)M=!1,H=null;if(H!==J.catalog)continue;let $=Z.exec(q);if(!$||$[3].trim()!==J.name||$[6].trim()!==J.version)continue;let[,D,G,E,P,K,,Q]=$;return z[j]=`${D}${G}${E}${G}${P}${K}${B}${K}${Q}`,z.join(`
4
4
  `)}return X}var I="pnpm-workspace.yaml",_="pnpm-workspace.yml";async function b(X,J,B={}){let z=B.logger??x(),Z=new Set(B.ignore??[]);for(let H of[I,_]){let M=W(X,H);if(!(await R(M).catch(()=>null))?.isFile())continue;let{entries:j,hasCatalogs:q}=S(await Bun.file(M).text());if(!q)return{updates:[],entries:[],file:H};return z.debug(`\uD83D\uDCE6 ${H}: ${j.length} catalog entr(ies)`),{updates:(await Promise.all(j.map(async(Y)=>{if(Z.has(Y.name))return null;try{let $=await J(Y.name);if(!$)return null;let D=Y.version.replace(/^[\^~>=<\s]+/,"").trim();if(!D||D===$)return null;return{name:Y.name,currentVersion:Y.version,newVersion:A(Y.version,$),updateType:k(D,$),dependencyType:"catalog",file:H,resolved:{catalog:Y.catalog}}}catch($){return z.debug(`Could not resolve catalog entry ${Y.name}: ${$}`),null}}))).filter((Y)=>Y!==null),entries:j,file:H}}return{updates:[],entries:[]}}function A(X,J){return`${/^([\^~]|>=|<=|>|<)?/.exec(X.trim())?.[1]??""}${J}`}function k(X,J){let B=(H)=>H.split(".").map((M)=>Number.parseInt(M,10)||0),z=B(X),Z=B(J);if((z[0]??0)!==(Z[0]??0))return"major";if((z[1]??0)!==(Z[1]??0))return"minor";return"patch"}function C(X,J){let B=X;for(let z of J){if(z.dependencyType!=="catalog")continue;B=V(B,{name:z.name,version:z.currentVersion,catalog:z.resolved?.catalog??"default"},z.newVersion)}return B}
5
5
  export{S as gc,w as hc,f as ic,V as jc,I as kc,_ as lc,b as mc,C as nc};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{dg as Y}from"./chunk-c63e4ssc.js";import{Rh as V}from"./chunk-wzncz6j5.js";import{gl as R}from"./chunk-16aeend1.js";import{spawn as T}from"child_process";import{existsSync as W}from"fs";import $ from"process";function S(){return["bun.lock","bun.lockb","package-lock.json","yarn.lock","pnpm-lock.yaml","composer.lock","pantry.lock"]}function _(z){switch(z){case"bun":return{command:"bun",args:["install"]};case"npm":return{command:"npm",args:["install"]};case"yarn":return{command:"yarn",args:["install"]};case"pnpm":return{command:"pnpm",args:["install"]};case"composer":return{command:"composer",args:["update","--lock"]};case"pantry":return{command:"pantry",args:["install","--ignore-scripts","--quiet"]}}}async function y(z,G,B=300000){let{command:K,args:Q}=_(z);return V().info(`\uD83D\uDD04 Regenerating lock file with ${z} (${K} ${Q.join(" ")})...`),new Promise((J)=>{let O=T(K,Q,{cwd:G,stdio:"pipe",env:{...$.env,CI:"true"}}),H="",X="",Z=!1,q=setTimeout(()=>{Z=!0,V().warn(`\u26A0\uFE0F ${z} install timed out after ${B/1000}s, sending SIGTERM...`),O.kill("SIGTERM"),setTimeout(()=>{if(!O.killed)V().warn(`\u26A0\uFE0F ${z} install did not exit after SIGTERM, sending SIGKILL...`),O.kill("SIGKILL")},1e4)},B);O.stdout?.on("data",(U)=>{H+=U.toString()}),O.stderr?.on("data",(U)=>{X+=U.toString()}),O.on("close",(U)=>{if(clearTimeout(q),Z){J({success:!1,packageManager:z,message:`Lock file regeneration timed out after ${B/1000}s`});return}if(U===0)V().info(`\u2705 Lock file regenerated successfully with ${z}`),J({success:!0,packageManager:z,message:"Lock file regenerated successfully"});else{if(V().warn(`\u26A0\uFE0F ${z} install exited with code ${U}`),X)V().warn(` stderr: ${X.slice(0,500)}`);J({success:!1,packageManager:z,message:`Install exited with code ${U}: ${X.slice(0,200)}`})}}),O.on("error",(U)=>{clearTimeout(q),V().warn(`\u26A0\uFE0F Failed to run ${K}: ${U.message}`),J({success:!1,packageManager:z,message:`Failed to run ${K}: ${U.message}`})})})}var C=new Set(["deps.yaml","deps.yml","pantry.jsonc","pantry.json","pantry.toml"]);function I(z,G=$.cwd()){let B=new Set,K=!1;for(let Q of z){let J=Q.split("/").pop()||"";if(J==="package.json")B.add(Y(G)),K=!0;if(J==="composer.json")B.add("composer");if(C.has(J))K=!0}if(K&&A("pantry",G))B.add("pantry");return Array.from(B)}function E(z,G=$.cwd()){let B=new Map;for(let K of z){let Q=K.replace(/^\.\//,"");if(!Q.endsWith("package.json")||!Q.includes("/"))continue;let J=Q.slice(0,Q.lastIndexOf("/"));if(B.has(J))continue;let O=`${G}/${J}`,H=["bun","pnpm","yarn","npm"].find((Z)=>A(Z,O));if(!H)continue;let X=b(H,O);if(X)B.set(J,{dir:J,manager:H,lockFile:`${J}/${X}`})}return[...B.values()]}function b(z,G){return{bun:["bun.lock","bun.lockb"],npm:["package-lock.json"],yarn:["yarn.lock"],pnpm:["pnpm-lock.yaml"],composer:["composer.lock"],pantry:["pantry.lock"]}[z].find((K)=>W(`${G}/${K}`))??null}function L(z,G=$.cwd()){let B=new Set(z.map((H)=>H.replace(/^\.\//,""))),K=new Set(E(z,G).map((H)=>H.dir)),Q=z.filter((H)=>!K.has(H.replace(/^\.\//,"").replace(/\/package\.json$/,""))),J=I(Q,G).map((H)=>b(H,G)),O=E(z,G).map((H)=>H.lockFile);return[...J,...O].filter((H)=>H!==null&&!B.has(H))}function A(z,G){let B=R("path");switch(z){case"bun":return W(B.join(G,"bun.lock"))||W(B.join(G,"bun.lockb"));case"npm":return W(B.join(G,"package-lock.json"));case"yarn":return W(B.join(G,"yarn.lock"));case"pnpm":return W(B.join(G,"pnpm-lock.yaml"));case"composer":return W(B.join(G,"composer.lock"));case"pantry":return W(B.join(G,"pantry.lock"))}}
2
+ import{eg as Y}from"./chunk-h9deve0y.js";import{Wh as V}from"./chunk-rrm4x81p.js";import{ll as R}from"./chunk-dh8yykbg.js";import{spawn as T}from"child_process";import{existsSync as W}from"fs";import $ from"process";function S(){return["bun.lock","bun.lockb","package-lock.json","yarn.lock","pnpm-lock.yaml","composer.lock","pantry.lock"]}function _(z){switch(z){case"bun":return{command:"bun",args:["install"]};case"npm":return{command:"npm",args:["install"]};case"yarn":return{command:"yarn",args:["install"]};case"pnpm":return{command:"pnpm",args:["install"]};case"composer":return{command:"composer",args:["update","--lock"]};case"pantry":return{command:"pantry",args:["install","--ignore-scripts","--quiet"]}}}async function y(z,G,B=300000){let{command:K,args:Q}=_(z);return V().info(`\uD83D\uDD04 Regenerating lock file with ${z} (${K} ${Q.join(" ")})...`),new Promise((J)=>{let O=T(K,Q,{cwd:G,stdio:"pipe",env:{...$.env,CI:"true"}}),H="",X="",Z=!1,q=setTimeout(()=>{Z=!0,V().warn(`\u26A0\uFE0F ${z} install timed out after ${B/1000}s, sending SIGTERM...`),O.kill("SIGTERM"),setTimeout(()=>{if(!O.killed)V().warn(`\u26A0\uFE0F ${z} install did not exit after SIGTERM, sending SIGKILL...`),O.kill("SIGKILL")},1e4)},B);O.stdout?.on("data",(U)=>{H+=U.toString()}),O.stderr?.on("data",(U)=>{X+=U.toString()}),O.on("close",(U)=>{if(clearTimeout(q),Z){J({success:!1,packageManager:z,message:`Lock file regeneration timed out after ${B/1000}s`});return}if(U===0)V().info(`\u2705 Lock file regenerated successfully with ${z}`),J({success:!0,packageManager:z,message:"Lock file regenerated successfully"});else{if(V().warn(`\u26A0\uFE0F ${z} install exited with code ${U}`),X)V().warn(` stderr: ${X.slice(0,500)}`);J({success:!1,packageManager:z,message:`Install exited with code ${U}: ${X.slice(0,200)}`})}}),O.on("error",(U)=>{clearTimeout(q),V().warn(`\u26A0\uFE0F Failed to run ${K}: ${U.message}`),J({success:!1,packageManager:z,message:`Failed to run ${K}: ${U.message}`})})})}var C=new Set(["deps.yaml","deps.yml","pantry.jsonc","pantry.json","pantry.toml"]);function I(z,G=$.cwd()){let B=new Set,K=!1;for(let Q of z){let J=Q.split("/").pop()||"";if(J==="package.json")B.add(Y(G)),K=!0;if(J==="composer.json")B.add("composer");if(C.has(J))K=!0}if(K&&A("pantry",G))B.add("pantry");return Array.from(B)}function E(z,G=$.cwd()){let B=new Map;for(let K of z){let Q=K.replace(/^\.\//,"");if(!Q.endsWith("package.json")||!Q.includes("/"))continue;let J=Q.slice(0,Q.lastIndexOf("/"));if(B.has(J))continue;let O=`${G}/${J}`,H=["bun","pnpm","yarn","npm"].find((Z)=>A(Z,O));if(!H)continue;let X=b(H,O);if(X)B.set(J,{dir:J,manager:H,lockFile:`${J}/${X}`})}return[...B.values()]}function b(z,G){return{bun:["bun.lock","bun.lockb"],npm:["package-lock.json"],yarn:["yarn.lock"],pnpm:["pnpm-lock.yaml"],composer:["composer.lock"],pantry:["pantry.lock"]}[z].find((K)=>W(`${G}/${K}`))??null}function L(z,G=$.cwd()){let B=new Set(z.map((H)=>H.replace(/^\.\//,""))),K=new Set(E(z,G).map((H)=>H.dir)),Q=z.filter((H)=>!K.has(H.replace(/^\.\//,"").replace(/\/package\.json$/,""))),J=I(Q,G).map((H)=>b(H,G)),O=E(z,G).map((H)=>H.lockFile);return[...J,...O].filter((H)=>H!==null&&!B.has(H))}function A(z,G){let B=R("path");switch(z){case"bun":return W(B.join(G,"bun.lock"))||W(B.join(G,"bun.lockb"));case"npm":return W(B.join(G,"package-lock.json"));case"yarn":return W(B.join(G,"yarn.lock"));case"pnpm":return W(B.join(G,"pnpm-lock.yaml"));case"composer":return W(B.join(G,"composer.lock"));case"pantry":return W(B.join(G,"pantry.lock"))}}
3
3
  export{S as Nc,y as Oc,I as Pc,E as Qc,b as Rc,L as Sc,A as Tc};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{gl as Z}from"./chunk-16aeend1.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-rqj1vrfs.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"bitbucket":{let{BitbucketProvider:Q}=await import("./chunk-485kgdtb.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"github":{let{GitHubProvider:Q}=await import("./chunk-dttp44vs.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};
2
+ import{ll as Z}from"./chunk-dh8yykbg.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-wt8b3ywq.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"bitbucket":{let{BitbucketProvider:Q}=await import("./chunk-843907bh.js");return new Q(X,j.owner,j.name,j.apiUrl,z.logger)}case"github":{let{GitHubProvider:Q}=await import("./chunk-rsvtnsmt.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 je,$ as ke,H as le,L as me,Y as ne,B as oe,A as pe,C as qe,M as re,W as se,S as te};
@@ -59,4 +59,4 @@ You cannot modify anything.
59
59
 
60
60
  Name the files that would change and why, the order of the work, the risks,
61
61
  and how the result would be verified.`},z={review:B,implement:F,"fix-ci":H,plan:I};function J(j){let q=z[j];if(!q)throw Error(`Unknown agent mode: ${j}. Available: ${Object.keys(z).join(", ")}`);return q}
62
- export{B as zf,F as Af,H as Bf,I as Cf,z as Df,J as Ef};
62
+ export{B as Af,F as Bf,H as Cf,I as Df,z as Ef,J as Ff};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var Y={node:{registry:"github",source:"nodejs/node"},bun:{registry:"npm",source:"bun"},npm:{registry:"npm",source:"npm"},pnpm:{registry:"npm",source:"pnpm"},yarn:{registry:"npm",source:"yarn"},deno:{registry:"github",source:"denoland/deno"}};function Z(A,F){if(typeof A!=="object"||A===null||Array.isArray(A))return[];let z=[];for(let[B,J]of Object.entries(A)){if(typeof J!=="string"||!J.trim())continue;if(!Y[B])continue;z.push({name:B,currentVersion:J.trim(),type:"engines",file:F,metadata:{engine:"true",source:Y[B].source}})}return z}function $(A){if(typeof A!=="object"||A===null)return[];let F=A,z=[],B=(J,L)=>{if(typeof J!=="object"||J===null||Array.isArray(J))return;for(let[U,H]of Object.entries(J)){if(typeof H==="string"&&H.trim()){z.push({name:U,version:H.trim(),field:L});continue}if(typeof H==="object"&&H!==null){let M=H;if(typeof M["."]==="string")z.push({name:U,version:M["."].trim(),field:L});B(H,L)}}};return B(F.overrides,"overrides"),B(F.resolutions,"resolutions"),B(F.pnpm?.overrides,"pnpm.overrides"),z}function q(A,F){let z=A.version.trim();try{if(/^[\^~><=]/.test(z))return!Bun.semver.satisfies(F,z)}catch{return!0}return z!==F}async function C(A,F){let z=Y[A];if(!z)return null;let B=z.registry==="npm"?await F.npm(z.source):await F.github(z.source);return B?B.replace(/^v/,""):null}function R(A,F){let z=/^\s*(>=|\^|~|>|=)?\s*v?(\d+(?:\.\d+)*)\s*$/.exec(A);if(!z)return null;let[,B="",J]=z,L=J.split(".").map(Number),H=F.split(".").map(Number).slice(0,L.length),M=!1;for(let Q=0;Q<H.length;Q++){let X=H[Q]-(L[Q]??0);if(X!==0){M=X>0;break}}if(!M)return null;return`${B}${H.join(".")}`}function T(A,F){let z=(L)=>(/(\d+(?:\.\d+)*)/.exec(L)?.[1]??"0").split(".").map(Number),B=z(A),J=z(F);if((J[0]??0)!==(B[0]??0))return"major";if((J[1]??0)!==(B[1]??0))return"minor";return"patch"}function P(A,F){let z=/("engines"\s*:\s*\{)([\s\S]*?)(\})/.exec(A);if(!z)return A;let[B,J,L,U]=z,H=L;for(let M of F){if(M.dependencyType!=="engines")continue;let Q=M.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),X=M.currentVersion.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");H=H.replace(new RegExp(`("${Q}"\\s*:\\s*")${X}(")`),`$1${M.newVersion}$2`)}return H===L?A:A.replace(B,`${J}${H}${U}`)}
3
- export{Y as Xe,Z as Ye,$ as Ze,q as _e,C as $e,R as af,T as bf,P as cf};
3
+ export{Y as Ye,Z as Ze,$ as _e,q as $e,C as af,R as bf,T as cf,P as df};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import"./chunk-16aeend1.js";var z={error:"error",warning:"warning",info:"notice"};function E(j){let q=[];for(let h of j.findings){let x=[`file=${h.file}`,`title=${h.ruleId}`];if(h.line!==void 0)x.push(`line=${h.line}`);let y=B(`${h.message}${h.fix?` \u2014 ${h.fix}`:""}`);q.push(`::${z[h.severity]} ${x.join(",")}::${y}`)}return q.join(`
2
+ import"./chunk-dh8yykbg.js";var z={error:"error",warning:"warning",info:"notice"};function E(j){let q=[];for(let h of j.findings){let x=[`file=${h.file}`,`title=${h.ruleId}`];if(h.line!==void 0)x.push(`line=${h.line}`);let y=B(`${h.message}${h.fix?` \u2014 ${h.fix}`:""}`);q.push(`::${z[h.severity]} ${x.join(",")}::${y}`)}return q.join(`
3
3
  `)}function B(j){return j.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
4
4
  `,"%0A")}export{E as formatGitHub};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ud as R}from"./chunk-s3b3vrsj.js";import{re as F,se as A}from"./chunk-743mhx0e.js";import{Bf as S}from"./chunk-1pecmenc.js";import{Rf as L}from"./chunk-hk4d7rky.js";import{Oh as K,Rh as O}from"./chunk-wzncz6j5.js";import{gl as P}from"./chunk-16aeend1.js";var b=[{kind:"lockfile-drift",mechanical:!0,patterns:[/lockfile had changes, but lockfile is frozen/i,/your lockfile does not satisfy your workspace/i,/the lockfile (?:is|was) out of date/i,/npm ci can only install packages when your package\.json and package-lock\.json .* are in sync/i,/composer\.lock is not up to date/i]},{kind:"flake",mechanical:!0,patterns:[/\bECONNRESET\b|\bETIMEDOUT\b|\bENOTFOUND\b|\bEAI_AGAIN\b/,/socket hang up/i,/502 Bad Gateway|503 Service Unavailable|504 Gateway Time-?out/i,/rate limit exceeded/i,/the runner has received a shutdown signal/i]},{kind:"install",mechanical:!1,patterns:[/could not resolve (?:dependency|host)/i,/no matching version found for/i,/unable to resolve dependency tree/i,/peer dep(?:endency)? .* conflict/i]},{kind:"type-error",mechanical:!1,patterns:[/error TS\d{4}:/,/\berror\[E\d+\]:/,/Type '.*' is not assignable to type/]},{kind:"test-failure",mechanical:!1,patterns:[/\d+ (?:tests? )?fail(?:ed|ing)\b/i,/\(fail\)/,/AssertionError|expect\(received\)/,/\u25CF .* \u203A /]},{kind:"lint",mechanical:!1,patterns:[/\b\d+ problems? \(\d+ errors?/i,/eslint|pickier|biome|oxlint/i]}];function N(x){if(!x.trim())return{kind:"unknown",mechanical:!1,evidence:[]};let H=x.split(`
2
+ import{Fd as R}from"./chunk-6bdrm4ab.js";import{se as F,te as A}from"./chunk-5feeegzy.js";import{Cf as S}from"./chunk-5nn5mms4.js";import{Sf as L}from"./chunk-y6292gbf.js";import{Th as K,Wh as O}from"./chunk-rrm4x81p.js";import{ll as P}from"./chunk-dh8yykbg.js";var b=[{kind:"lockfile-drift",mechanical:!0,patterns:[/lockfile had changes, but lockfile is frozen/i,/your lockfile does not satisfy your workspace/i,/the lockfile (?:is|was) out of date/i,/npm ci can only install packages when your package\.json and package-lock\.json .* are in sync/i,/composer\.lock is not up to date/i]},{kind:"flake",mechanical:!0,patterns:[/\bECONNRESET\b|\bETIMEDOUT\b|\bENOTFOUND\b|\bEAI_AGAIN\b/,/socket hang up/i,/502 Bad Gateway|503 Service Unavailable|504 Gateway Time-?out/i,/rate limit exceeded/i,/the runner has received a shutdown signal/i]},{kind:"install",mechanical:!1,patterns:[/could not resolve (?:dependency|host)/i,/no matching version found for/i,/unable to resolve dependency tree/i,/peer dep(?:endency)? .* conflict/i]},{kind:"type-error",mechanical:!1,patterns:[/error TS\d{4}:/,/\berror\[E\d+\]:/,/Type '.*' is not assignable to type/]},{kind:"test-failure",mechanical:!1,patterns:[/\d+ (?:tests? )?fail(?:ed|ing)\b/i,/\(fail\)/,/AssertionError|expect\(received\)/,/\u25CF .* \u203A /]},{kind:"lint",mechanical:!1,patterns:[/\b\d+ problems? \(\d+ errors?/i,/eslint|pickier|biome|oxlint/i]}];function N(x){if(!x.trim())return{kind:"unknown",mechanical:!1,evidence:[]};let H=x.split(`
3
3
  `);for(let z of b){let J=[];for(let V of H)if(z.patterns.some((Q)=>Q.test(V))){if(J.push(V.trim()),J.length>=5)break}if(J.length>0)return{kind:z.kind,mechanical:z.mechanical,evidence:J}}return{kind:"unknown",mechanical:!1,evidence:T(H)}}function T(x,H=40){let z=x.filter((J)=>/\b(?:error|failed|failure|exception|panic|fatal)\b/i.test(J)&&!/^\s*(?:at\s|\s*\.\.\.)/.test(J));return(z.length>0?z:x.slice(-H)).slice(-H).map((J)=>J.trim()).filter(Boolean)}function G(x){switch(x.kind){case"lockfile-drift":return"The lock file is out of step with its manifest.";case"flake":return"A network or runner problem, unrelated to the change.";case"install":return"Dependencies could not be resolved.";case"type-error":return"The change does not type-check.";case"test-failure":return"One or more tests failed.";case"lint":return"Lint or formatting checks failed.";default:return"The failure could not be classified automatically."}}var w=3;async function M(x,H,z,J){let V=J??O();try{let Q=await x.listWorkflowRuns(H,{status:"completed",limit:20});for(let Y of _(Q).slice(0,w)){let Z=await x.getWorkflowRunLogs(Y.id);if(!Z)continue;if(N(Z).kind===z)return V.info(`\uD83E\uDDED ${H} already fails the same way (run ${Y.id}) \u2014 not this pull request's to fix`),!0}return!1}catch(Q){return V.debug(`Could not check ${H} for a pre-existing failure: ${K(Q)}`),!1}}function _(x){let H=new Map;for(let z of x)if(!H.has(z.name))H.set(z.name,z);return[...H.values()].filter((z)=>z.conclusion==="failure")}function h(x,H){if(!x)return"Tried to regenerate the lock file, but the install did not succeed.";if(!H)return"Regenerated the lock file, but could not push it to the branch. The change is in the workspace only, so the run will still be red until someone commits it.";return"Regenerated the lock file and pushed the result. No model was needed."}function f(x){let H="Repairs run on the pull request's branch, and answering a comment runs on the default branch, so anything I changed here would land on the wrong tree. ";if(x.kind==="lockfile-drift")return`Regenerating the lock file would fix this, and no model would be needed. ${H}The \`fix-ci\` job will do it on the next failing run, or you can run \`buddy fix-ci --run-id <id> --pr <number>\` yourself.`;return`${H}The \`fix-ci\` job runs on the failing run itself and can repair this; this reply is the diagnosis it would start from.`}async function I(x){let H=x.logger??O(),z=N(x.log),J=x.maxAttempts??3;if(H.info(`\uD83E\uDE7A CI failure classified as ${z.kind}`),x.failsOnBase??(x.checkBase?await x.checkBase(z.kind):!1))return{failure:z,action:"skipped",fixed:!1,report:$(z,"This failure also occurs on the base branch, so it is not caused by this change. Fixing it here would only mask it.")};if((x.priorAttempts??0)>=J)return{failure:z,action:"skipped",fixed:!1,report:$(z,`Already attempted ${x.priorAttempts} time(s); stopping rather than looping.`)};if(x.analysisOnly&&z.kind!=="flake")return{failure:z,action:"reported",fixed:!1,report:$(z,f(z))};if(z.kind==="lockfile-drift"&&x.regenerateLockfile){if(x.dryRun)return{failure:z,action:"mechanical-fix",fixed:!1,report:$(z,"Regenerating the lock file would fix this. No model would be needed. Nothing was changed, because this was a dry run.")};H.info("\uD83D\uDD27 Regenerating the lock file");let{regenerated:Y,pushed:Z}=await x.regenerateLockfile();return{failure:z,action:"mechanical-fix",fixed:Z,report:$(z,h(Y,Z))}}if(z.kind==="flake"){if(x.dryRun)return{failure:z,action:"retry",fixed:!1,report:$(z,"This looks transient, and re-running the failed jobs would likely clear it. Nothing was changed, because this was a dry run.")};if(!x.rerun)return{failure:z,action:"retry",fixed:!1,report:$(z,"This looks transient. Re-running the failed job is likely to clear it.")};H.info("\uD83D\uDD01 Re-running the failed jobs");let Y=await x.rerun();return{failure:z,action:"retry",fixed:!1,report:$(z,Y?"This looks transient, so I re-ran the failed jobs. No model was needed.":"This looks transient, but I could not re-run the failed jobs \u2014 `actions: write` is the usual reason. "+"Re-running them from the Actions tab is likely to clear it.")}}if(!x.ai)return{failure:z,action:"reported",fixed:!1,report:$(z,"No AI provider is configured, so this needs a human. See https://buddy.sh/ai/providers to enable automatic repair.")};let Q=await L(x.ai,{mode:S,task:["A CI job on this branch is failing. Diagnose the root cause and fix it if the fix is clear.","",`Classification: ${z.kind} \u2014 ${G(z)}`,"","Relevant log lines:",z.evidence.join(`
4
4
  `),"","Verify your fix by running the project's tests or build before reporting it done.","If the fix is not clear, explain what you found rather than guessing."].join(`
5
5
  `),context:{workspace:x.workspace,baseBranch:x.baseBranch,...x.branch?{branch:x.branch}:{}},logger:H});return{failure:z,action:"agent-fix",fixed:Q.stopReason==="completed",report:$(z,Q.output||"The repair run ended without a conclusion.")}}function $(x,H){let z=`## \uD83E\uDE7A CI failure analysis
@@ -20,8 +20,8 @@ ${x.evidence.slice(0,20).join(`
20
20
  ${JSON.stringify(J)}
21
21
  -->`;return`${(x??"").replace(B,"").trimEnd()}
22
22
 
23
- ${V}`}async function m(x,H,z){if(!F(x,"ciRuns","listWorkflowRuns"))return null;try{let J=await x.getPullRequestHeadSha(H.number),V=await x.listWorkflowRuns(H.head,{status:"completed",limit:30}),Q=J?V.filter((Y)=>Y.headSha===J):V;return _(Q)[0]?.id??null}catch(J){return z.debug(`Could not resolve the failing run for #${H.number}: ${K(J)}`),null}}async function c(x){let H=x.logger??O(),{config:z,provider:J}=x,V=x.workspace??process.cwd();A(J,"ciLogs","getWorkflowRunLogs","reading CI logs");let Q;if(x.prNumber){if(Q=(await J.getPullRequests("open")).find((W)=>W.number===x.prNumber),!Q)return`Could not find open pull request #${x.prNumber}.`}let Y=x.runId??(Q?await m(J,Q,H):null);if(!Y)return Q?"Nothing is failing at the head of this pull request, so there is nothing to diagnose.":"No run to diagnose. Pass --run-id, or --pr so I can find the failing run myself.";let Z=await J.getWorkflowRunLogs(Y);if(!Z)return H.warn(`\u26A0\uFE0F Could not read the logs for run ${Y}; nothing to diagnose`),`Could not read the logs for run ${Y}. They may have expired.`;let U=E(Q?.body)?.attempts??0,j=z.repository?.baseBranch??"main",D=F(J,"ciRuns","listWorkflowRuns"),y=F(J,"ciRuns","rerunWorkflowRun"),{createAiClient:v}=await import("./chunk-8wrbxhs3.js"),C=await I({log:Z,priorAttempts:U,workspace:V,baseBranch:j,ai:x.analysisOnly?null:v(z,H),logger:H,dryRun:Boolean(x.dryRun),analysisOnly:Boolean(x.analysisOnly),...D?{checkBase:(X)=>M({listWorkflowRuns:(W,k)=>J.listWorkflowRuns(W,k),getWorkflowRunLogs:(W)=>J.getWorkflowRunLogs(W)},j,X,H)}:{},...y?{rerun:()=>J.rerunWorkflowRun(Y)}:{},...x.analysisOnly?{}:{regenerateLockfile:()=>g(V,H)}});if(H.info(`
23
+ ${V}`}async function m(x,H,z){if(!F(x,"ciRuns","listWorkflowRuns"))return null;try{let J=await x.getPullRequestHeadSha(H.number),V=await x.listWorkflowRuns(H.head,{status:"completed",limit:30}),Q=J?V.filter((Y)=>Y.headSha===J):V;return _(Q)[0]?.id??null}catch(J){return z.debug(`Could not resolve the failing run for #${H.number}: ${K(J)}`),null}}async function c(x){let H=x.logger??O(),{config:z,provider:J}=x,V=x.workspace??process.cwd();A(J,"ciLogs","getWorkflowRunLogs","reading CI logs");let Q;if(x.prNumber){if(Q=(await J.getPullRequests("open")).find((W)=>W.number===x.prNumber),!Q)return`Could not find open pull request #${x.prNumber}.`}let Y=x.runId??(Q?await m(J,Q,H):null);if(!Y)return Q?"Nothing is failing at the head of this pull request, so there is nothing to diagnose.":"No run to diagnose. Pass --run-id, or --pr so I can find the failing run myself.";let Z=await J.getWorkflowRunLogs(Y);if(!Z)return H.warn(`\u26A0\uFE0F Could not read the logs for run ${Y}; nothing to diagnose`),`Could not read the logs for run ${Y}. They may have expired.`;let U=E(Q?.body)?.attempts??0,j=z.repository?.baseBranch??"main",D=F(J,"ciRuns","listWorkflowRuns"),y=F(J,"ciRuns","rerunWorkflowRun"),{createAiClient:v}=await import("./chunk-6477cdgj.js"),C=await I({log:Z,priorAttempts:U,workspace:V,baseBranch:j,ai:x.analysisOnly?null:v(z,H),logger:H,dryRun:Boolean(x.dryRun),analysisOnly:Boolean(x.analysisOnly),...D?{checkBase:(X)=>M({listWorkflowRuns:(W,k)=>J.listWorkflowRuns(W,k),getWorkflowRunLogs:(W)=>J.getWorkflowRunLogs(W)},j,X,H)}:{},...y?{rerun:()=>J.rerunWorkflowRun(Y)}:{},...x.analysisOnly?{}:{regenerateLockfile:()=>g(V,H)}});if(H.info(`
24
24
  ${C.report}
25
- `),x.prNumber&&!x.dryRun){if(await J.createComment(x.prNumber,C.report),C.action!=="skipped"&&Q)try{await J.updatePullRequest(x.prNumber,{body:q(Q.body,U+1)})}catch(X){H.warn(`Could not record the fix attempt on PR #${x.prNumber}: ${K(X)}`)}}return await R(z.notifications,"fixci.completed",{...x.prNumber?{number:x.prNumber}:{},action:C.action,fixed:C.fixed}),`${C.action}${C.fixed?" (fixed)":""}`}async function g(x,H){let{regenerateLockFile:z,detectRequiredPackageManagers:J,getAllLockFilePaths:V,hasLockFile:Q}=await import("./chunk-3mnpvfg3.js"),{commitAndPush:Y}=await import("./chunk-qngnmrpw.js"),Z=J(["package.json","composer.json"],x).filter((j)=>Q(j,x)),U=!1;for(let j of Z){let D=await z(j,x);if(D.success)U=!0;else H.warn(`\u26A0\uFE0F ${D.message}`)}if(!U)return{regenerated:!1,pushed:!1};try{return{regenerated:!0,pushed:await Y(V(),`fix(deps): regenerate the lock file
25
+ `),x.prNumber&&!x.dryRun){if(await J.createComment(x.prNumber,C.report),C.action!=="skipped"&&Q)try{await J.updatePullRequest(x.prNumber,{body:q(Q.body,U+1)})}catch(X){H.warn(`Could not record the fix attempt on PR #${x.prNumber}: ${K(X)}`)}}return await R(z.notifications,"fixci.completed",{...x.prNumber?{number:x.prNumber}:{},action:C.action,fixed:C.fixed}),`${C.action}${C.fixed?" (fixed)":""}`}async function g(x,H){let{regenerateLockFile:z,detectRequiredPackageManagers:J,getAllLockFilePaths:V,hasLockFile:Q}=await import("./chunk-by2hfewp.js"),{commitAndPush:Y}=await import("./chunk-ry21xmre.js"),Z=J(["package.json","composer.json"],x).filter((j)=>Q(j,x)),U=!1;for(let j of Z){let D=await z(j,x);if(D.success)U=!0;else H.warn(`\u26A0\uFE0F ${D.message}`)}if(!U)return{regenerated:!1,pushed:!1};try{return{regenerated:!0,pushed:await Y(V(),`fix(deps): regenerate the lock file
26
26
 
27
- The lock file had drifted from the manifest, which failed CI.`,x)}}catch(j){return H.warn(`\u26A0\uFE0F Could not push the regenerated lock file: ${K(j)}`),{regenerated:!0,pushed:!1}}}export{N as Ea,T as Fa,G as Ga,M as Ha,_ as Ia,I as Ja,c as Ka};
27
+ The lock file had drifted from the manifest, which failed CI.`,x)}}catch(j){return H.warn(`\u26A0\uFE0F Could not push the regenerated lock file: ${K(j)}`),{regenerated:!0,pushed:!1}}}export{N as Ya,T as Za,G as _a,M as $a,_ as ab,I as bb,c as cb};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Qb as p,Rb as q,Sb as r,Tb as s,Ub as t,Vb as u,Wb as v,Xb as w,Yb as x}from"./chunk-g763t4rr.js";import{$b as i,Zb as g,_b as h,ac as j,bc as k,cc as l,dc as m,ec as n,fc as o}from"./chunk-dev3g0n3.js";import"./chunk-rwzt9xvk.js";import{Vf as e,Wf as f}from"./chunk-xntpzagn.js";import{Xf as a,Yf as b,Zf as c,_f as d}from"./chunk-20sxtyt7.js";import"./chunk-sg7bhtb7.js";import"./chunk-rrm4x81p.js";import"./chunk-dh8yykbg.js";export{s as serializeLearnings,v as selectLearnings,j as resolveModelAlias,n as resolveAiProvider,w as renderLearnings,d as redactError,c as redactDeep,b as redact,r as parseLearnings,x as loadLearnings,m as createOpenAiProvider,t as createLearning,l as createGoogleProvider,k as createAnthropicProvider,o as createAiClient,u as addLearning,a as REDACTED,i as PROVIDER_PRIORITY,h as PROVIDER_KEY_ENV,g as MODEL_ALIASES,q as DEFAULT_PROMPT_LIMIT,p as DEFAULT_LEARNINGS_FILE,f as AiProviderError,e as AiBudgetExceededError};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{wd as j,zd as q}from"./chunk-6gvx1g6h.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};
2
+ import{Hd as j,Kd as q}from"./chunk-m6qym0ya.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 Fd};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Rh as F}from"./chunk-wzncz6j5.js";var R=/^(?:build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(?:\([^)]+\))?!?: .+/;function Y(M,G){let P=R.test(M.trim());return{name:"title-format",mode:G,passed:P,summary:P?"Title follows conventional commit format":"Title does not follow conventional commit format",...P?{}:{detail:"Expected something like `feat(scope): add the thing` or `fix: correct the off-by-one`."}}}function B(M,G){let P=M.trim();if(P.length<20)return{name:"description",mode:G.mode,passed:!1,summary:"Description is missing or too short",detail:"Explain what changed and why, so a reviewer does not have to reconstruct it from the diff."};let z=(G.requireSections??[]).filter((j)=>!new RegExp(`^#{1,6}\\s*${w(j)}\\b`,"im").test(P));return{name:"description",mode:G.mode,passed:z.length===0,summary:z.length===0?"Description is complete":`Description is missing ${z.length} required section(s)`,...z.length>0?{detail:`Missing: ${z.map((j)=>`\`${j}\``).join(", ")}`}:{}}}function C(M,G){let P=[];for(let z of M??[]){if(G.blockVulnerable!==!1&&z.vulnerable)P.push(`\`${z.name}@${z.version}\` has a known vulnerability`);if(G.blockDeprecated!==!1&&z.deprecated)P.push(`\`${z.name}\` is deprecated`);if(G.blockEol!==!1&&z.eol)P.push(z.eol);if(G.licenseAllowlist?.length&&z.license){if(!G.licenseAllowlist.includes(z.license))P.push(`\`${z.name}\` is licensed \`${z.license}\`, which is not on the allowlist`)}}return{name:"dependency-gate",mode:G.mode,passed:P.length===0,summary:P.length===0?"Dependencies satisfy the configured policy":`${P.length} dependency policy violation(s)`,...P.length>0?{detail:P.map((z)=>`- ${z}`).join(`
2
+ import{Wh as F}from"./chunk-rrm4x81p.js";var R=/^(?:build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(?:\([^)]+\))?!?: .+/;function Y(M,G){let P=R.test(M.trim());return{name:"title-format",mode:G,passed:P,summary:P?"Title follows conventional commit format":"Title does not follow conventional commit format",...P?{}:{detail:"Expected something like `feat(scope): add the thing` or `fix: correct the off-by-one`."}}}function B(M,G){let P=M.trim();if(P.length<20)return{name:"description",mode:G.mode,passed:!1,summary:"Description is missing or too short",detail:"Explain what changed and why, so a reviewer does not have to reconstruct it from the diff."};let z=(G.requireSections??[]).filter((j)=>!new RegExp(`^#{1,6}\\s*${w(j)}\\b`,"im").test(P));return{name:"description",mode:G.mode,passed:z.length===0,summary:z.length===0?"Description is complete":`Description is missing ${z.length} required section(s)`,...z.length>0?{detail:`Missing: ${z.map((j)=>`\`${j}\``).join(", ")}`}:{}}}function C(M,G){let P=[];for(let z of M??[]){if(G.blockVulnerable!==!1&&z.vulnerable)P.push(`\`${z.name}@${z.version}\` has a known vulnerability`);if(G.blockDeprecated!==!1&&z.deprecated)P.push(`\`${z.name}\` is deprecated`);if(G.blockEol!==!1&&z.eol)P.push(z.eol);if(G.licenseAllowlist?.length&&z.license){if(!G.licenseAllowlist.includes(z.license))P.push(`\`${z.name}\` is licensed \`${z.license}\`, which is not on the allowlist`)}}return{name:"dependency-gate",mode:G.mode,passed:P.length===0,summary:P.length===0?"Dependencies satisfy the configured policy":`${P.length} dependency policy violation(s)`,...P.length>0?{detail:P.map((z)=>`- ${z}`).join(`
3
3
  `)}:{}}}function q(M,G){let P=[];if(G.titleFormat&&G.titleFormat!=="off")P.push(Y(M.title,G.titleFormat));if(G.description&&G.description.mode!=="off")P.push(B(M.body,G.description));if(G.dependencyGate&&G.dependencyGate.mode!=="off")P.push(C(M.dependencies,G.dependencyGate));return P}function S(M){if(M.length===0)return{conclusion:"neutral",title:"No checks configured",summary:"No pre-merge checks are enabled."};let G=M.filter((x)=>!x.passed&&x.mode==="error"),P=M.filter((x)=>!x.passed&&x.mode==="warning"),z=M.filter((x)=>x.neutral),j=M.map((x)=>{return`${H(x)} **${x.name}** \u2014 ${x.summary}${x.detail?`
4
4
 
5
5
  ${x.detail}
@@ -23,4 +23,4 @@ ${P}
23
23
  ${M}`;let j=z.index+z[0].length,Q=M.slice(0,j),J=M.slice(j);return`${Q}
24
24
 
25
25
  ${P}${J.replace(/^\n+/,`
26
- `)}`}async function T(M,G,P={},z={}){let j=z.logger??F(),Q=z.baseBranch??G.base??"main",J=[],x=[];if(P.changelog?.enabled){let $=P.changelog.path??"CHANGELOG.md";try{let X=await M.getFileContent($,Q),K=A(X??"",`${G.title} (#${G.number})`);if(K===X)x.push({action:"changelog",reason:"already recorded"});else await M.commitChanges(Q,`docs(changelog): record #${G.number}`,[{path:$,content:K,type:X===null?"create":"update"}],Q),J.push("changelog")}catch(X){j.warn(`\u26A0\uFE0F Could not update the changelog: ${X}`),x.push({action:"changelog",reason:"write failed"})}}if(P.commentOnIssues){let $=U(G.body??"");if($.length===0)x.push({action:"comment-on-issues",reason:"no linked issues"});else for(let X of $)try{await M.createComment(X,`Resolved by [#${G.number}](${G.url}) \u2014 ${G.title}`),J.push(`comment-on-issue-${X}`)}catch(K){j.warn(`\u26A0\uFE0F Could not comment on #${X}: ${K}`),x.push({action:`comment-on-issue-${X}`,reason:"comment failed"})}}if(P.refreshDashboard)if(!z.refreshDashboard)x.push({action:"refresh-dashboard",reason:"no dashboard refresher was supplied"});else try{await z.refreshDashboard(),J.push("refresh-dashboard")}catch($){j.warn(`\u26A0\uFE0F Could not refresh the dashboard: ${$}`),x.push({action:"refresh-dashboard",reason:"refresh failed"})}return{performed:J,skipped:x}}function D(M){if(typeof M!=="object"||M===null)return!1;let G=M;return G.action==="closed"&&G.pull_request?.merged===!0}export{Y as ka,B as la,C as ma,q as na,S as oa,H as pa,V as qa,W as ra,I as sa,U as ta,A as ua,T as va,D as wa};
26
+ `)}`}async function T(M,G,P={},z={}){let j=z.logger??F(),Q=z.baseBranch??G.base??"main",J=[],x=[];if(P.changelog?.enabled){let $=P.changelog.path??"CHANGELOG.md";try{let X=await M.getFileContent($,Q),K=A(X??"",`${G.title} (#${G.number})`);if(K===X)x.push({action:"changelog",reason:"already recorded"});else await M.commitChanges(Q,`docs(changelog): record #${G.number}`,[{path:$,content:K,type:X===null?"create":"update"}],Q),J.push("changelog")}catch(X){j.warn(`\u26A0\uFE0F Could not update the changelog: ${X}`),x.push({action:"changelog",reason:"write failed"})}}if(P.commentOnIssues){let $=U(G.body??"");if($.length===0)x.push({action:"comment-on-issues",reason:"no linked issues"});else for(let X of $)try{await M.createComment(X,`Resolved by [#${G.number}](${G.url}) \u2014 ${G.title}`),J.push(`comment-on-issue-${X}`)}catch(K){j.warn(`\u26A0\uFE0F Could not comment on #${X}: ${K}`),x.push({action:`comment-on-issue-${X}`,reason:"comment failed"})}}if(P.refreshDashboard)if(!z.refreshDashboard)x.push({action:"refresh-dashboard",reason:"no dashboard refresher was supplied"});else try{await z.refreshDashboard(),J.push("refresh-dashboard")}catch($){j.warn(`\u26A0\uFE0F Could not refresh the dashboard: ${$}`),x.push({action:"refresh-dashboard",reason:"refresh failed"})}return{performed:J,skipped:x}}function D(M){if(typeof M!=="object"||M===null)return!1;let G=M;return G.action==="closed"&&G.pull_request?.merged===!0}export{Y as qa,B as ra,C as sa,q as ta,S as ua,H as va,V as wa,W as xa,I as ya,U as za,A as Aa,T as Ba,D as Ca};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ var t="0.11.19";
3
+ export{t as Uc};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Rh as z}from"./chunk-wzncz6j5.js";function Y(q,F,M=""){if(typeof F!=="object"||F===null)return[];let C=F,Q=M||"(root)",N=[];if(typeof C.type==="string"){let K=D(q);if(!(C.type==="integer"?Number.isInteger(q):K===C.type||C.type==="number"&&K==="integer"))return N.push({path:Q,message:`expected ${C.type}, got ${K}`}),N}if(Array.isArray(C.enum)&&!C.enum.includes(q))N.push({path:Q,message:`expected one of ${C.enum.map((K)=>JSON.stringify(K)).join(", ")}`});if(Array.isArray(C.required)&&typeof q==="object"&&q!==null){for(let K of C.required)if(!(String(K)in q))N.push({path:M?`${M}.${K}`:String(K),message:"is required but missing"})}if(typeof C.properties==="object"&&C.properties!==null&&typeof q==="object"&&q!==null)for(let[K,V]of Object.entries(C.properties)){let X=q[K];if(X!==void 0)N.push(...Y(X,V,M?`${M}.${K}`:K))}if(C.items!==void 0&&Array.isArray(q))q.forEach((K,V)=>{N.push(...Y(K,C.items,`${M}[${V}]`))});return N}function D(q){if(q===null)return"null";if(Array.isArray(q))return"array";if(Number.isInteger(q))return"integer";return typeof q}async function B(q){let F=q.logger??z(),M=q.maxRetries??2,C=q.system??"You are running as a pipeline step. Answer the request directly and completely. There is no interactive user to ask follow-up questions of.",Q="";for(let N=1;N<=M+1;N++){let K=N===1?q.prompt:`${q.prompt}
2
+ import{Wh as z}from"./chunk-rrm4x81p.js";function Y(q,F,M=""){if(typeof F!=="object"||F===null)return[];let C=F,Q=M||"(root)",N=[];if(typeof C.type==="string"){let K=D(q);if(!(C.type==="integer"?Number.isInteger(q):K===C.type||C.type==="number"&&K==="integer"))return N.push({path:Q,message:`expected ${C.type}, got ${K}`}),N}if(Array.isArray(C.enum)&&!C.enum.includes(q))N.push({path:Q,message:`expected one of ${C.enum.map((K)=>JSON.stringify(K)).join(", ")}`});if(Array.isArray(C.required)&&typeof q==="object"&&q!==null){for(let K of C.required)if(!(String(K)in q))N.push({path:M?`${M}.${K}`:String(K),message:"is required but missing"})}if(typeof C.properties==="object"&&C.properties!==null&&typeof q==="object"&&q!==null)for(let[K,V]of Object.entries(C.properties)){let X=q[K];if(X!==void 0)N.push(...Y(X,V,M?`${M}.${K}`:K))}if(C.items!==void 0&&Array.isArray(q))q.forEach((K,V)=>{N.push(...Y(K,C.items,`${M}[${V}]`))});return N}function D(q){if(q===null)return"null";if(Array.isArray(q))return"array";if(Number.isInteger(q))return"integer";return typeof q}async function B(q){let F=q.logger??z(),M=q.maxRetries??2,C=q.system??"You are running as a pipeline step. Answer the request directly and completely. There is no interactive user to ask follow-up questions of.",Q="";for(let N=1;N<=M+1;N++){let K=N===1?q.prompt:`${q.prompt}
3
3
 
4
4
  Your previous answer did not satisfy the required schema:
5
5
  ${Q}
@@ -12,4 +12,4 @@ ${Q}`)}return{result:null,valid:!1,error:Q,attempts:M+1}}function J(q){let F=q.s
12
12
  ${F}
13
13
  ${M}
14
14
  `}async function H(q,F){if(!F)return!1;let M=typeof q==="string"?q:JSON.stringify(q),C=await Bun.file(F).exists()?await Bun.file(F).text():"";return await Bun.write(F,C+L("result",M)),!0}
15
- export{Y,B as Z,L as _,H as $};
15
+ export{Y as ca,B as da,L as ea,H as fa};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{dg as a,eg as b,fg as c,gg as d,hg as e,ig as f,jg as g,kg as h,lg as i,mg as j,ng as k,og as l,pg as m}from"./chunk-h9deve0y.js";import"./chunk-vxt1h0c4.js";import"./chunk-fcax5a60.js";import"./chunk-q3dg57xx.js";import"./chunk-r0jmwzr3.js";import"./chunk-sg7bhtb7.js";import"./chunk-rrm4x81p.js";import"./chunk-dkgz8hsd.js";import"./chunk-dh8yykbg.js";export{h as sortUpdatesByPriority,j as satisfiesRange,a as parsePackageFile,g as groupUpdates,i as getUpdateType,f as generateBranchName,d as formatPRTitle,e as formatPRBody,c as formatCommitMessage,l as extractPackageNamesFromPRBody,b as detectPackageManager,k as checkForRebaseRequests,m as checkForAutoClose};
@@ -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 yh};
503
+ export{K as Bh};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Kh as a}from"./chunk-89spjk6r.js";import"./chunk-8y4szfd2.js";import"./chunk-sg7bhtb7.js";import"./chunk-rrm4x81p.js";import"./chunk-dh8yykbg.js";export{a as BitbucketProvider};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Fg as mc,Gg as nc,Hg as oc,Ig as pc,Jg as qc,Kg as rc,Lg as sc,Mg as tc,Ng as uc,Og as vc,Pg as wc,Qg as xc,Rg as yc,Sg as zc,Tg as Ac,Ug as Bc,Vg as Cc,Wg as Dc,Xg as Ec,Yg as Fc}from"./chunk-2z9mh5y4.js";import{$h as i,$i as ha,$j as hb,$k as hc,Ai as I,Aj as Ia,Ak as Ib,Bi as J,Bj as Ja,Bk as Jb,Ci as K,Cj as Ka,Ck as Kb,Di as L,Dj as La,Dk as Lb,Ei as M,Ej as Ma,Ek as Mb,Fi as N,Fj as Na,Fk as Nb,Gi as O,Gj as Oa,Gk as Ob,Hi as P,Hj as Pa,Hk as Pb,Ii as Q,Ij as Qa,Ik as Qb,Ji as R,Jj as Ra,Jk as Rb,Ki as S,Kj as Sa,Kk as Sb,Li as T,Lj as Ta,Lk as Tb,Mi as U,Mj as Ua,Mk as Ub,Ni as V,Nj as Va,Nk as Vb,Oi as W,Oj as Wa,Ok as Wb,Pi as X,Pj as Xa,Pk as Xb,Qi as Y,Qj as Ya,Qk as Yb,Ri as Z,Rj as Za,Rk as Zb,Sh as a,Si as _,Sj as _a,Sk as _b,Th as b,Ti as $,Tj as $a,Tk as $b,Uh as c,Ui as aa,Uj as ab,Uk as ac,Vi as ba,Vj as bb,Vk as bc,Wh as d,Wi as ca,Wj as cb,Wk as cc,Xh as e,Xi as da,Xj as db,Xk as dc,Yh as f,Yi as ea,Yj as eb,Yk as ec,Zh as g,Zi as fa,Zj as fb,Zk as fc,_h as h,_i as ga,_j as gb,_k as gc,ai as j,aj as ia,ak as ib,al as ic,bi as k,bj as ja,bk as jb,bl as jc,ci as l,cj as ka,ck as kb,cl as kc,di as m,dj as la,dk as lb,dl as lc,ei as n,ej as ma,ek as mb,fi as o,fj as na,fk as nb,gi as p,gj as oa,gk as ob,hi as q,hj as pa,hk as pb,ii as r,ij as qa,ik as qb,ji as s,jj as ra,jk as rb,ki as t,kj as sa,kk as sb,li as u,lj as ta,lk as tb,mi as v,mj as ua,mk as ub,ni as w,nj as va,nk as vb,oi as x,oj as wa,ok as wb,pi as y,pj as xa,pk as xb,qi as z,qj as ya,qk as yb,ri as A,rj as za,rk as zb,si as B,sj as Aa,sk as Ab,ti as C,tj as Ba,tk as Bb,ui as D,uj as Ca,uk as Cb,vj as Da,vk as Db,wi as E,wj as Ea,wk as Eb,xi as F,xj as Fa,xk as Fb,yi as G,yj as Ga,yk as Gb,zi as H,zj as Ha,zk as Hb}from"./chunk-m3rftash.js";import"./chunk-16aeend1.js";export{Ta as ziglangOfficialDownload,ab as zigRegistryMirror,bb as zigPurgedDevBuildHint,eb as zigOriginVersions,Wb as writeOciLayout,Xb as writeDockerArchive,Cc as withTempDirSync,Bc as withTempDir,yc as withRedis,uc as withPostgres,qc as withMysql,ic as waitForAppStoreBuilds,ac as verifyBlob,n as validatePackageSpec,Aa as validatePackage,sa as v,xc as useRedis,tc as usePostgres,pc as useMysql,zb as updatePackageVersionMap,ca as updateApp,sb as uninstallShellInit,ub as toTypeName,tb as toSafeVarName,vb as toPackageVarName,Fc as testingRuntime,mb as supportedPackages,wc as stopRedis,sc as stopPostgres,oc as stopMysql,vc as startRedis,rc as startPostgres,S as startPeriodicCleanup,nc as startMysql,Ua as sqliteOfficialDownloadUrl,va as showPackageInfo,x as shouldProceedWithGitHubRequest,R as setupCleanupHandlers,Ub as serializeConfig,wa as searchPackagesCommand,j as searchPackages,V as scanPantryPackages,$ as scanInstalledApps,N as saveToCacheAndOutput,w as saveRateLimitInfo,K as savePackageAsTypeScript,z as saveGitHubPackageCache,db as satisfiesInstallerConstraint,ib as retryNetworkOperation,q as resolveVersionFromMetadata,Ka as resolveVersionConstraint,h as resolveVersion,Ma as resolveTransitiveDependencies,ka as resolvePackageName,G as resolvePackageDomain,Cb as resolvePackageDependencies,Xa as resolveLatestVersion,gb as resolveInstallerConstraintFromCandidates,Oa as resolveDependencyFile,Bb as resolveDependenciesFromYaml,Ab as resolveDependencies,Mb as resolveBuildStages,qb as renderShellSnippet,dc as renderDockerfile,Ac as removeTempDir,Za as registryVersionsForPlatform,Ya as registryPlatformKey,_a as registryDownloadSource,Eb as readProjectDependencies,W as readPantryPackageInfo,pb as rcFileFor,$b as pushImage,_b as pullImage,jc as provisionMacApp,ta as pkg,o as parseVersion,la as parsePackageSpec,cb as parseInstallerConstraint,Zb as parseImageRef,Nb as parseFreezer,Lb as parseExecForm,Kb as parseDockerfile,Ia as parseDepsYamlConfig,Ha as parseDependencyFile,b as pantry,c as packages,Qa as normalizeInstallerVersion,B as logPkgxProjects,Pb as loadFreezer,xa as listPopularPackages,za as listAliases,ya as listActivePackages,g as isVersionAvailable,fa as isValidPackageName,ga as isSupportedPlatform,ha as isSupportedArchitecture,kb as isSupported,hb as isRetryableNetworkError,ra as isPackageInCategory,ea as isPackageDomain,da as isPackageAlias,_ as isNewerVersion,I as isKnownAlias,lb as isInstallable,$a as installedRegistryBinaries,rb as installShellInit,Wa as installPackages,Va as installPackage,F as guessOriginalDomain,Ra as globalBinDir,Ca as getVersionInfo,M as getValidCachedPackage,Ga as getSystemInfo,nb as getPrimaryBinary,l as getPopularPackages,f as getPhpVersionsForWorkflow,k as getPackagesByPattern,qa as getPackagesByCategory,i as getPackageInfo,H as getPackageAliases,d as getLatestVersion,Db as getInstallCommand,y as getGitHubPackageCache,J as getCanonicalDomain,Ja as getAvailableVersionsForPackage,e as getAvailableVersions,ja as getAllPackageDomains,ia as getAllPackageAliases,m as getActivePackages,kc as generateMacCertificateRequests,wb as generateIndex,yb as generateDocs,ec as generateContainerFiles,xb as generateAliases,Ea as formatSearchResults,ma as formatPackageSpec,Da as formatPackageInfo,C as formatObjectWithoutQuotedKeys,Fa as formatInstallPlan,Pa as findDependencyFiles,P as fetchPkgxProjects,X as fetchPantryPackageWithMetadata,Q as fetchPantryPackage,A as fetchPackageListFromGitHub,aa as fetchDesktopCatalogue,U as fetchAndSavePackage,T as fetchAndSaveAllPackages,bc as extractLayer,lc as exportAppleCertificateP12,hc as ensureAppStoreVersions,jb as downloadFileReliably,Sb as digestHex,Rb as digest,ob as detectShell,Sa as detectPlatform,ua as dependencies,Ib as definePantryConfig,Gb as definePackageList,Fb as defineDependencies,Na as deduplicateDependencies,Dc as createTestFile,Ec as createTestDir,zc as createTempDir,Ob as createMatcher,na as createInstallationContext,Ba as createInstallPlan,D as convertDomainToVarName,E as convertDomainToFileName,p as compareVersionsDesc,La as compareVersions,fb as compareInstallerVersionsDesc,Jb as collectBuildContext,O as cleanupBrowserResources,L as cleanStaleOutputFiles,ba as checkAppUpdates,Vb as buildManifest,Tb as buildLayerFromRootfs,cc as buildImage,fc as appStoreConnectToken,a as aliases,oa as VERSION_SPECS,Y as SYSTEM_APPS,mc as PantryService,Yb as PANTRY_REGISTRY,pa as PACKAGE_CATEGORIES,u as PACKAGE_ALIASES,Qb as MEDIA_TYPE,Z as MAS_APPS,Hb as DISTRIBUTION_CONFIG,t as DEFAULT_TIMEOUT_MS,s as DEFAULT_CACHE_EXPIRATION_MINUTES,r as DEFAULT_CACHE_DIR,gc as AppStoreConnectClient,v as ALL_KNOWN_PACKAGES};
2
+ import{Gg as mc,Hg as nc,Ig as oc,Jg as pc,Kg as qc,Lg as rc,Mg as sc,Ng as tc,Og as uc,Pg as vc,Qg as wc,Rg as xc,Sg as yc,Tg as zc,Ug as Ac,Vg as Bc,Wg as Cc,Xg as Dc,Yg as Ec,Zg as Fc}from"./chunk-q3dg57xx.js";import{$h as d,$i as ca,$j as cb,$k as cc,Aj as Da,Ak as Db,Bi as E,Bj as Ea,Bk as Eb,Ci as F,Cj as Fa,Ck as Fb,Di as G,Dj as Ga,Dk as Gb,Ei as H,Ej as Ha,Ek as Hb,Fi as I,Fj as Ia,Fk as Ib,Gi as J,Gj as Ja,Gk as Jb,Hi as K,Hj as Ka,Hk as Kb,Ii as L,Ij as La,Ik as Lb,Ji as M,Jj as Ma,Jk as Mb,Ki as N,Kj as Na,Kk as Nb,Li as O,Lj as Oa,Lk as Ob,Mi as P,Mj as Pa,Mk as Pb,Ni as Q,Nj as Qa,Nk as Qb,Oi as R,Oj as Ra,Ok as Rb,Pi as S,Pj as Sa,Pk as Sb,Qi as T,Qj as Ta,Qk as Tb,Ri as U,Rj as Ua,Rk as Ub,Si as V,Sj as Va,Sk as Vb,Ti as W,Tj as Wa,Tk as Wb,Ui as X,Uj as Xa,Uk as Xb,Vi as Y,Vj as Ya,Vk as Yb,Wi as Z,Wj as Za,Wk as Zb,Xh as a,Xi as _,Xj as _a,Xk as _b,Yh as b,Yi as $,Yj as $a,Yk as $b,Zh as c,Zi as aa,Zj as ab,Zk as ac,_i as ba,_j as bb,_k as bc,ai as e,aj as da,ak as db,al as dc,bi as f,bj as ea,bk as eb,bl as ec,ci as g,cj as fa,ck as fb,cl as fc,di as h,dj as ga,dk as gb,dl as gc,ei as i,ej as ha,ek as hb,el as hc,fi as j,fj as ia,fk as ib,fl as ic,gi as k,gj as ja,gk as jb,gl as jc,hi as l,hj as ka,hk as kb,hl as kc,ii as m,ij as la,ik as lb,il as lc,ji as n,jj as ma,jk as mb,ki as o,kj as na,kk as nb,li as p,lj as oa,lk as ob,mi as q,mj as pa,mk as pb,ni as r,nj as qa,nk as qb,oi as s,oj as ra,ok as rb,pi as t,pj as sa,pk as sb,qi as u,qj as ta,qk as tb,ri as v,rj as ua,rk as ub,si as w,sj as va,sk as vb,ti as x,tj as wa,tk as wb,ui as y,uj as xa,uk as xb,vi as z,vj as ya,vk as yb,wi as A,wj as za,wk as zb,xi as B,xj as Aa,xk as Ab,yi as C,yj as Ba,yk as Bb,zi as D,zj as Ca,zk as Cb}from"./chunk-dkgz8hsd.js";import"./chunk-dh8yykbg.js";export{Ta as ziglangOfficialDownload,ab as zigRegistryMirror,bb as zigPurgedDevBuildHint,eb as zigOriginVersions,Wb as writeOciLayout,Xb as writeDockerArchive,Cc as withTempDirSync,Bc as withTempDir,yc as withRedis,uc as withPostgres,qc as withMysql,ic as waitForAppStoreBuilds,ac as verifyBlob,n as validatePackageSpec,Aa as validatePackage,sa as v,xc as useRedis,tc as usePostgres,pc as useMysql,zb as updatePackageVersionMap,ca as updateApp,sb as uninstallShellInit,ub as toTypeName,tb as toSafeVarName,vb as toPackageVarName,Fc as testingRuntime,mb as supportedPackages,wc as stopRedis,sc as stopPostgres,oc as stopMysql,vc as startRedis,rc as startPostgres,S as startPeriodicCleanup,nc as startMysql,Ua as sqliteOfficialDownloadUrl,va as showPackageInfo,x as shouldProceedWithGitHubRequest,R as setupCleanupHandlers,Ub as serializeConfig,wa as searchPackagesCommand,j as searchPackages,V as scanPantryPackages,$ as scanInstalledApps,N as saveToCacheAndOutput,w as saveRateLimitInfo,K as savePackageAsTypeScript,z as saveGitHubPackageCache,db as satisfiesInstallerConstraint,ib as retryNetworkOperation,q as resolveVersionFromMetadata,Ka as resolveVersionConstraint,h as resolveVersion,Ma as resolveTransitiveDependencies,ka as resolvePackageName,G as resolvePackageDomain,Cb as resolvePackageDependencies,Xa as resolveLatestVersion,gb as resolveInstallerConstraintFromCandidates,Oa as resolveDependencyFile,Bb as resolveDependenciesFromYaml,Ab as resolveDependencies,Mb as resolveBuildStages,qb as renderShellSnippet,dc as renderDockerfile,Ac as removeTempDir,Za as registryVersionsForPlatform,Ya as registryPlatformKey,_a as registryDownloadSource,Eb as readProjectDependencies,W as readPantryPackageInfo,pb as rcFileFor,$b as pushImage,_b as pullImage,jc as provisionMacApp,ta as pkg,o as parseVersion,la as parsePackageSpec,cb as parseInstallerConstraint,Zb as parseImageRef,Nb as parseFreezer,Lb as parseExecForm,Kb as parseDockerfile,Ia as parseDepsYamlConfig,Ha as parseDependencyFile,b as pantry,c as packages,Qa as normalizeInstallerVersion,B as logPkgxProjects,Pb as loadFreezer,xa as listPopularPackages,za as listAliases,ya as listActivePackages,g as isVersionAvailable,fa as isValidPackageName,ga as isSupportedPlatform,ha as isSupportedArchitecture,kb as isSupported,hb as isRetryableNetworkError,ra as isPackageInCategory,ea as isPackageDomain,da as isPackageAlias,_ as isNewerVersion,I as isKnownAlias,lb as isInstallable,$a as installedRegistryBinaries,rb as installShellInit,Wa as installPackages,Va as installPackage,F as guessOriginalDomain,Ra as globalBinDir,Ca as getVersionInfo,M as getValidCachedPackage,Ga as getSystemInfo,nb as getPrimaryBinary,l as getPopularPackages,f as getPhpVersionsForWorkflow,k as getPackagesByPattern,qa as getPackagesByCategory,i as getPackageInfo,H as getPackageAliases,d as getLatestVersion,Db as getInstallCommand,y as getGitHubPackageCache,J as getCanonicalDomain,Ja as getAvailableVersionsForPackage,e as getAvailableVersions,ja as getAllPackageDomains,ia as getAllPackageAliases,m as getActivePackages,kc as generateMacCertificateRequests,wb as generateIndex,yb as generateDocs,ec as generateContainerFiles,xb as generateAliases,Ea as formatSearchResults,ma as formatPackageSpec,Da as formatPackageInfo,C as formatObjectWithoutQuotedKeys,Fa as formatInstallPlan,Pa as findDependencyFiles,P as fetchPkgxProjects,X as fetchPantryPackageWithMetadata,Q as fetchPantryPackage,A as fetchPackageListFromGitHub,aa as fetchDesktopCatalogue,U as fetchAndSavePackage,T as fetchAndSaveAllPackages,bc as extractLayer,lc as exportAppleCertificateP12,hc as ensureAppStoreVersions,jb as downloadFileReliably,Sb as digestHex,Rb as digest,ob as detectShell,Sa as detectPlatform,ua as dependencies,Ib as definePantryConfig,Gb as definePackageList,Fb as defineDependencies,Na as deduplicateDependencies,Dc as createTestFile,Ec as createTestDir,zc as createTempDir,Ob as createMatcher,na as createInstallationContext,Ba as createInstallPlan,D as convertDomainToVarName,E as convertDomainToFileName,p as compareVersionsDesc,La as compareVersions,fb as compareInstallerVersionsDesc,Jb as collectBuildContext,O as cleanupBrowserResources,L as cleanStaleOutputFiles,ba as checkAppUpdates,Vb as buildManifest,Tb as buildLayerFromRootfs,cc as buildImage,fc as appStoreConnectToken,a as aliases,oa as VERSION_SPECS,Y as SYSTEM_APPS,mc as PantryService,Yb as PANTRY_REGISTRY,pa as PACKAGE_CATEGORIES,u as PACKAGE_ALIASES,Qb as MEDIA_TYPE,Z as MAS_APPS,Hb as DISTRIBUTION_CONFIG,t as DEFAULT_TIMEOUT_MS,s as DEFAULT_CACHE_EXPIRATION_MINUTES,r as DEFAULT_CACHE_DIR,gc as AppStoreConnectClient,v as ALL_KNOWN_PACKAGES};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Gh as V}from"./chunk-6w0n6c07.js";import{Lh as M}from"./chunk-s0ps33ft.js";import{Oh as K,Rh as Q}from"./chunk-wzncz6j5.js";class X{token;apiUrl;logger;slug;constructor(j,z,A,C,F){this.token=j;this.apiUrl=(C??"https://api.bitbucket.org/2.0").replace(/\/+$/,""),this.logger=F??Q(),this.slug=`${encodeURIComponent(z)}/${encodeURIComponent(A)}`}capabilities(){return{pinIssues:!1,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!1,nativeAutoMerge:!1,commentReactions:!1,ciLogs:!1,ciRuns:!1,reviewThreads:!1,teamReviewers:!1,draftPullRequests:!1,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!1,labels:!1}}async request(j,z,A,C={}){let F={Authorization:`Bearer ${this.token}`,Accept:C.raw?"text/plain":"application/json","User-Agent":"buddy"},H;if(C.form)F["Content-Type"]="application/x-www-form-urlencoded",H=new URLSearchParams(C.form).toString();else if(A)F["Content-Type"]="application/json",H=JSON.stringify(A);let G=await M(`${this.apiUrl}${z}`,{method:j,headers:F,...H?{body:H}:{}});if(!G.ok){let J=await G.text().catch(()=>"");throw Error(`Bitbucket ${j} ${z} failed: ${G.status} ${J.slice(0,200)}`)}let I=await G.text();if(C.raw)return I;return I.trim()?JSON.parse(I):void 0}async optional(j,z){try{return await this.request(j,z)}catch(A){if(String(A).includes("404"))return null;throw A}}async collect(j,z=10){let A=[],C=`${this.apiUrl}${j}`;for(let F=0;F<z&&C;F++){let H=C,G=await this.optional("GET",H.startsWith(this.apiUrl)?H.slice(this.apiUrl.length):H);if(!G)break;A.push(...G.values??[]),C=G.next}return A}async branchExists(j){return await this.optional("GET",`/repositories/${this.slug}/refs/branches/${encodeURIComponent(j)}`)!==null}async createBranch(j,z){await this.request("POST",`/repositories/${this.slug}/refs/branches`,{name:j,target:{hash:z}})}async deleteBranch(j){await this.request("DELETE",`/repositories/${this.slug}/refs/branches/${encodeURIComponent(j)}`)}async commitChanges(j,z,A,C="main"){if(A.length===0)return;let F={message:z,branch:j};for(let I of A)if(I.type==="delete")F.files=F.files?`${F.files},${I.path}`:I.path;else F[I.path]=I.content;let H=new URLSearchParams;for(let[I,J]of Object.entries(F)){if(I==="files")continue;H.append(I,J)}for(let I of A)if(I.type==="delete")H.append("files",I.path);let G=await this.headOf(C);if(G)H.append("parents",G);await this.request("POST",`/repositories/${this.slug}/src`,void 0,{form:Object.fromEntries(H.entries())})}async headOf(j){return(await this.optional("GET",`/repositories/${this.slug}/refs/branches/${encodeURIComponent(j)}`))?.target?.hash??null}async getFileContent(j,z){try{return await this.request("GET",`/repositories/${this.slug}/src/${encodeURIComponent(z)}/${j}`,void 0,{raw:!0})}catch(A){if(String(A).includes("404"))return null;throw A}}async createPullRequest(j){if(j.draft)this.logger.debug("Bitbucket has no draft pull requests; opening as ready");let z=await this.request("POST",`/repositories/${this.slug}/pullrequests`,{title:j.title,description:j.body,source:{branch:{name:j.head}},destination:{branch:{name:j.base}},close_source_branch:!0,...j.reviewers?.length?{reviewers:j.reviewers.map((A)=>({nickname:A}))}:{}});return this.toPullRequest(z)}async getPullRequests(j="open"){let A=(j==="open"?["OPEN"]:j==="closed"?["MERGED","DECLINED","SUPERSEDED"]:["OPEN","MERGED","DECLINED","SUPERSEDED"]).map((F)=>`state=${F}`).join("&");return(await this.collect(`/repositories/${this.slug}/pullrequests?${A}&pagelen=50`)).map((F)=>this.toPullRequest(F))}async updatePullRequest(j,z){let A=await this.request("PUT",`/repositories/${this.slug}/pullrequests/${j}`,{...z.title!==void 0?{title:z.title}:{},...z.body!==void 0?{description:z.body}:{},...z.base!==void 0?{destination:{branch:{name:z.base}}}:{}});return this.toPullRequest(A)}async closePullRequest(j){await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/decline`)}async reopenPullRequest(j){throw Error(`Bitbucket cannot reopen declined pull request #${j}; open a new one from the same branch.`)}async mergePullRequest(j,z="squash"){let A={merge:"merge_commit",squash:"squash",rebase:"fast_forward"};await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/merge`,{merge_strategy:A[z]??"squash",close_source_branch:!0})}async getPullRequestDiff(j){return await this.request("GET",`/repositories/${this.slug}/pullrequests/${j}/diff`,void 0,{raw:!0})}async getPullRequestHeadSha(j){return(await this.request("GET",`/repositories/${this.slug}/pullrequests/${j}`)).source?.commit?.hash??""}async createComment(j,z){await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/comments`,{content:{raw:z}})}async createIssue(j){let z=await this.request("POST",`/repositories/${this.slug}/issues`,{title:j.title,content:{raw:j.body},kind:"task"});return this.toIssue(z)}async getIssues(j="open"){let A=(await this.collect(`/repositories/${this.slug}/issues?pagelen=50`)).map((C)=>this.toIssue(C));return j==="all"?A:A.filter((C)=>C.state===j)}async updateIssue(j,z){let A=await this.request("PUT",`/repositories/${this.slug}/issues/${j}`,{...z.title!==void 0?{title:z.title}:{},...z.body!==void 0?{content:{raw:z.body}}:{}});return this.toIssue(A)}async closeIssue(j){await this.request("PUT",`/repositories/${this.slug}/issues/${j}`,{state:"closed"})}async unpinIssue(j){return!1}async getPullRequestChecksState(j){let z=await this.getPullRequestHeadSha(j);if(!z)return"none";let A=await this.collect(`/repositories/${this.slug}/commit/${z}/statuses?pagelen=50`);if(A.length===0)return"none";if(A.some((C)=>C.state==="FAILED"||C.state==="STOPPED"))return"failure";if(A.some((C)=>C.state==="INPROGRESS"))return"pending";if(A.every((C)=>C.state==="SUCCESSFUL"))return"success";return"pending"}async createReview(j,z){if(await this.createComment(j,z.body),!z.comments?.length)return{posted:!0,inlineComments:0};let A=0;for(let C of z.comments)try{await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/comments`,{content:{raw:C.body},inline:{path:C.path,...C.side==="RIGHT"?{to:C.line}:{from:C.line}}}),A++}catch(F){this.logger.debug(`Could not place a comment on ${C.path}:${C.line}: ${K(F)}`)}return{posted:!0,inlineComments:A}}async createCheckRun(j,z,A){try{await this.request("POST",`/repositories/${this.slug}/commit/${z}/statuses/build`,{key:j.replace(/[^\w-]/g,"-").slice(0,40),state:A.conclusion==="failure"?"FAILED":"SUCCESSFUL",name:A.title.slice(0,100),description:A.summary.slice(0,300),url:"https://buddy.sh"})}catch(C){this.logger.warn(`\u26A0\uFE0F Could not report build status ${j}: ${K(C)}`)}}async hasWriteAccess(j){let A=(await this.optional("GET",`/repositories/${this.slug}/permissions-config/users`))?.values?.find((C)=>C.user?.nickname===j);return A?.permission==="write"||A?.permission==="admin"}async getBuddyBranches(){return(await this.collect(`/repositories/${this.slug}/refs/branches?q=${encodeURIComponent('name ~ "buddy/"')}&pagelen=50`)).filter((z)=>V(z.name)).map((z)=>({name:z.name,sha:z.target?.hash??"",lastCommitDate:z.target?.date?new Date(z.target.date):new Date(0)}))}async getOrphanedBuddyBranches(){let[j,z]=await Promise.all([this.getBuddyBranches(),this.getPullRequests("open")]),A=new Set(z.map((C)=>C.head));return j.filter((C)=>!A.has(C.name))}async cleanupStaleBranches(j=7,z=!1){let A=new Date(Date.now()-j*24*60*60*1000),C=(await this.getOrphanedBuddyBranches()).filter((G)=>G.lastCommitDate<A);if(z)return{deleted:C.map((G)=>G.name),failed:[]};let F=[],H=[];for(let G of C)try{await this.deleteBranch(G.name),F.push(G.name)}catch{H.push(G.name)}return{deleted:F,failed:H}}toPullRequest(j){let z=j.state==="MERGED"?"merged":j.state==="OPEN"?"open":"closed";return{number:j.id,title:j.title,body:j.description??"",head:j.source?.branch?.name??"",base:j.destination?.branch?.name??"",state:z,url:j.links?.html?.href??"",createdAt:new Date(j.created_on),updatedAt:new Date(j.updated_on),...z==="merged"?{mergedAt:new Date(j.updated_on)}:{},author:j.author?.nickname??j.author?.display_name??"",reviewers:(j.reviewers??[]).map((A)=>A.nickname??A.display_name??"").filter(Boolean),assignees:[],labels:[],draft:!1}}toIssue(j){let z=["new","open","on hold"].includes(j.state);return{number:j.id,title:j.title,body:j.content?.raw??"",state:z?"open":"closed",url:j.links?.html?.href??"",createdAt:new Date(j.created_on),updatedAt:new Date(j.updated_on),...z?{}:{closedAt:new Date(j.updated_on)},author:j.reporter?.nickname??j.reporter?.display_name??"",assignees:[],labels:[]}}}
3
- export{X as Fh};
2
+ import{Lh as V}from"./chunk-8y4szfd2.js";import{Qh as M}from"./chunk-sg7bhtb7.js";import{Th as K,Wh as Q}from"./chunk-rrm4x81p.js";class X{token;apiUrl;logger;slug;constructor(j,z,A,C,F){this.token=j;this.apiUrl=(C??"https://api.bitbucket.org/2.0").replace(/\/+$/,""),this.logger=F??Q(),this.slug=`${encodeURIComponent(z)}/${encodeURIComponent(A)}`}capabilities(){return{pinIssues:!1,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!1,nativeAutoMerge:!1,commentReactions:!1,ciLogs:!1,ciRuns:!1,reviewThreads:!1,teamReviewers:!1,draftPullRequests:!1,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!1,labels:!1}}async request(j,z,A,C={}){let F={Authorization:`Bearer ${this.token}`,Accept:C.raw?"text/plain":"application/json","User-Agent":"buddy"},H;if(C.form)F["Content-Type"]="application/x-www-form-urlencoded",H=new URLSearchParams(C.form).toString();else if(A)F["Content-Type"]="application/json",H=JSON.stringify(A);let G=await M(`${this.apiUrl}${z}`,{method:j,headers:F,...H?{body:H}:{}});if(!G.ok){let J=await G.text().catch(()=>"");throw Error(`Bitbucket ${j} ${z} failed: ${G.status} ${J.slice(0,200)}`)}let I=await G.text();if(C.raw)return I;return I.trim()?JSON.parse(I):void 0}async optional(j,z){try{return await this.request(j,z)}catch(A){if(String(A).includes("404"))return null;throw A}}async collect(j,z=10){let A=[],C=`${this.apiUrl}${j}`;for(let F=0;F<z&&C;F++){let H=C,G=await this.optional("GET",H.startsWith(this.apiUrl)?H.slice(this.apiUrl.length):H);if(!G)break;A.push(...G.values??[]),C=G.next}return A}async branchExists(j){return await this.optional("GET",`/repositories/${this.slug}/refs/branches/${encodeURIComponent(j)}`)!==null}async createBranch(j,z){await this.request("POST",`/repositories/${this.slug}/refs/branches`,{name:j,target:{hash:z}})}async deleteBranch(j){await this.request("DELETE",`/repositories/${this.slug}/refs/branches/${encodeURIComponent(j)}`)}async commitChanges(j,z,A,C="main"){if(A.length===0)return;let F={message:z,branch:j};for(let I of A)if(I.type==="delete")F.files=F.files?`${F.files},${I.path}`:I.path;else F[I.path]=I.content;let H=new URLSearchParams;for(let[I,J]of Object.entries(F)){if(I==="files")continue;H.append(I,J)}for(let I of A)if(I.type==="delete")H.append("files",I.path);let G=await this.headOf(C);if(G)H.append("parents",G);await this.request("POST",`/repositories/${this.slug}/src`,void 0,{form:Object.fromEntries(H.entries())})}async headOf(j){return(await this.optional("GET",`/repositories/${this.slug}/refs/branches/${encodeURIComponent(j)}`))?.target?.hash??null}async getFileContent(j,z){try{return await this.request("GET",`/repositories/${this.slug}/src/${encodeURIComponent(z)}/${j}`,void 0,{raw:!0})}catch(A){if(String(A).includes("404"))return null;throw A}}async createPullRequest(j){if(j.draft)this.logger.debug("Bitbucket has no draft pull requests; opening as ready");let z=await this.request("POST",`/repositories/${this.slug}/pullrequests`,{title:j.title,description:j.body,source:{branch:{name:j.head}},destination:{branch:{name:j.base}},close_source_branch:!0,...j.reviewers?.length?{reviewers:j.reviewers.map((A)=>({nickname:A}))}:{}});return this.toPullRequest(z)}async getPullRequests(j="open"){let A=(j==="open"?["OPEN"]:j==="closed"?["MERGED","DECLINED","SUPERSEDED"]:["OPEN","MERGED","DECLINED","SUPERSEDED"]).map((F)=>`state=${F}`).join("&");return(await this.collect(`/repositories/${this.slug}/pullrequests?${A}&pagelen=50`)).map((F)=>this.toPullRequest(F))}async updatePullRequest(j,z){let A=await this.request("PUT",`/repositories/${this.slug}/pullrequests/${j}`,{...z.title!==void 0?{title:z.title}:{},...z.body!==void 0?{description:z.body}:{},...z.base!==void 0?{destination:{branch:{name:z.base}}}:{}});return this.toPullRequest(A)}async closePullRequest(j){await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/decline`)}async reopenPullRequest(j){throw Error(`Bitbucket cannot reopen declined pull request #${j}; open a new one from the same branch.`)}async mergePullRequest(j,z="squash"){let A={merge:"merge_commit",squash:"squash",rebase:"fast_forward"};await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/merge`,{merge_strategy:A[z]??"squash",close_source_branch:!0})}async getPullRequestDiff(j){return await this.request("GET",`/repositories/${this.slug}/pullrequests/${j}/diff`,void 0,{raw:!0})}async getPullRequestHeadSha(j){return(await this.request("GET",`/repositories/${this.slug}/pullrequests/${j}`)).source?.commit?.hash??""}async createComment(j,z){await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/comments`,{content:{raw:z}})}async createIssue(j){let z=await this.request("POST",`/repositories/${this.slug}/issues`,{title:j.title,content:{raw:j.body},kind:"task"});return this.toIssue(z)}async getIssues(j="open"){let A=(await this.collect(`/repositories/${this.slug}/issues?pagelen=50`)).map((C)=>this.toIssue(C));return j==="all"?A:A.filter((C)=>C.state===j)}async updateIssue(j,z){let A=await this.request("PUT",`/repositories/${this.slug}/issues/${j}`,{...z.title!==void 0?{title:z.title}:{},...z.body!==void 0?{content:{raw:z.body}}:{}});return this.toIssue(A)}async closeIssue(j){await this.request("PUT",`/repositories/${this.slug}/issues/${j}`,{state:"closed"})}async unpinIssue(j){return!1}async getPullRequestChecksState(j){let z=await this.getPullRequestHeadSha(j);if(!z)return"none";let A=await this.collect(`/repositories/${this.slug}/commit/${z}/statuses?pagelen=50`);if(A.length===0)return"none";if(A.some((C)=>C.state==="FAILED"||C.state==="STOPPED"))return"failure";if(A.some((C)=>C.state==="INPROGRESS"))return"pending";if(A.every((C)=>C.state==="SUCCESSFUL"))return"success";return"pending"}async createReview(j,z){if(await this.createComment(j,z.body),!z.comments?.length)return{posted:!0,inlineComments:0};let A=0;for(let C of z.comments)try{await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/comments`,{content:{raw:C.body},inline:{path:C.path,...C.side==="RIGHT"?{to:C.line}:{from:C.line}}}),A++}catch(F){this.logger.debug(`Could not place a comment on ${C.path}:${C.line}: ${K(F)}`)}return{posted:!0,inlineComments:A}}async createCheckRun(j,z,A){try{await this.request("POST",`/repositories/${this.slug}/commit/${z}/statuses/build`,{key:j.replace(/[^\w-]/g,"-").slice(0,40),state:A.conclusion==="failure"?"FAILED":"SUCCESSFUL",name:A.title.slice(0,100),description:A.summary.slice(0,300),url:"https://buddy.sh"})}catch(C){this.logger.warn(`\u26A0\uFE0F Could not report build status ${j}: ${K(C)}`)}}async hasWriteAccess(j){let A=(await this.optional("GET",`/repositories/${this.slug}/permissions-config/users`))?.values?.find((C)=>C.user?.nickname===j);return A?.permission==="write"||A?.permission==="admin"}async getBuddyBranches(){return(await this.collect(`/repositories/${this.slug}/refs/branches?q=${encodeURIComponent('name ~ "buddy/"')}&pagelen=50`)).filter((z)=>V(z.name)).map((z)=>({name:z.name,sha:z.target?.hash??"",lastCommitDate:z.target?.date?new Date(z.target.date):new Date(0)}))}async getOrphanedBuddyBranches(){let[j,z]=await Promise.all([this.getBuddyBranches(),this.getPullRequests("open")]),A=new Set(z.map((C)=>C.head));return j.filter((C)=>!A.has(C.name))}async cleanupStaleBranches(j=7,z=!1){let A=new Date(Date.now()-j*24*60*60*1000),C=(await this.getOrphanedBuddyBranches()).filter((G)=>G.lastCommitDate<A);if(z)return{deleted:C.map((G)=>G.name),failed:[]};let F=[],H=[];for(let G of C)try{await this.deleteBranch(G.name),F.push(G.name)}catch{H.push(G.name)}return{deleted:F,failed:H}}toPullRequest(j){let z=j.state==="MERGED"?"merged":j.state==="OPEN"?"open":"closed";return{number:j.id,title:j.title,body:j.description??"",head:j.source?.branch?.name??"",base:j.destination?.branch?.name??"",state:z,url:j.links?.html?.href??"",createdAt:new Date(j.created_on),updatedAt:new Date(j.updated_on),...z==="merged"?{mergedAt:new Date(j.updated_on)}:{},author:j.author?.nickname??j.author?.display_name??"",reviewers:(j.reviewers??[]).map((A)=>A.nickname??A.display_name??"").filter(Boolean),assignees:[],labels:[],draft:!1}}toIssue(j){let z=["new","open","on hold"].includes(j.state);return{number:j.id,title:j.title,body:j.content?.raw??"",state:z?"open":"closed",url:j.links?.html?.href??"",createdAt:new Date(j.created_on),updatedAt:new Date(j.updated_on),...z?{}:{closedAt:new Date(j.updated_on)},author:j.reporter?.nickname??j.reporter?.display_name??"",assignees:[],labels:[]}}}
3
+ export{X as Kh};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ue as a,ve as b,we as c,xe as d}from"./chunk-eq5xb8k1.js";import"./chunk-rrm4x81p.js";import"./chunk-dh8yykbg.js";export{c as updateZigManifest,b as parseZigManifest,a as isZigManifest,d as generateZigManifestUpdates};
@@ -1,2 +1,2 @@
1
1
  // @bun
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-16aeend1.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 d,Ye as a,Ze as b,_e as c,af as e,bf as f,cf as g,df as h}from"./chunk-5q5tm30a.js";import"./chunk-dh8yykbg.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
2
  var k=["buddy/","buddy-bot/"];function v(g){return typeof g==="string"&&k.some((j)=>g.startsWith(j))}
3
- export{v as Gh};
3
+ export{v as Lh};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import"./chunk-16aeend1.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-dh8yykbg.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};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ad as a,bd as b,cd as c,dd as d,ed as e,fd as f,gd as g,hd as h,id as i,jd as j}from"./chunk-ng9zksy3.js";import"./chunk-dh8yykbg.js";export{j as shouldFail,h as formatReview,d as formatPretty,e as formatGithub,f as formatAgent,b as diffArgsFor,g as countBySeverity,c as collectLocalDiff,i as applySuggestion,a as REVIEW_FORMATS};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{md as J}from"./chunk-bnp0r4eh.js";import{nd as Y}from"./chunk-0f1xye20.js";import{ue as _}from"./chunk-d09qj570.js";import{xe as x,ye as w}from"./chunk-wk175yyw.js";import{Qe as z,Re as M}from"./chunk-4wv5s3vr.js";import{Ye as N}from"./chunk-j46f90n8.js";import{Ag as L,Bg as S}from"./chunk-r1jvyhhd.js";import{Rh as G}from"./chunk-wzncz6j5.js";import{gl as j}from"./chunk-16aeend1.js";var{Glob:D}=globalThis.Bun;import{lstat as Z,readdir as A,readFile as U}from"fs/promises";import{join as R,relative as E,sep as H}from"path";async function I(q,K){try{let O=JSON.parse(K),V=[];if(O.packages){for(let Q of Object.values(O.packages))if(Q.name&&Q.version)V.push({name:Q.name,currentVersion:Q.version,type:"dependencies",file:q})}return{path:q,type:"pantry.lock",content:K,dependencies:V}}catch(O){return G().warn(`Failed to parse pantry.lock file ${q}:`,O),null}}class m{projectPath;logger;ignoreGlobs=[];constructor(q,K,O){this.projectPath=q;this.logger=K;if(O&&O.length>0)this.ignoreGlobs=O.map((V)=>new D(V)),this.logger.info(`Initialized ${this.ignoreGlobs.length} ignore patterns: ${O.join(", ")}`)}async scanProject(){this.logger.info("Scanning project for package files...");let q=Date.now(),K=[];try{let O=await this.findFiles("package.json");for(let X of O){if(this.shouldIgnorePath(X))continue;let $=await this.parsePackageJsonFile(X);if($)K.push($)}let V=await this.findDependencyFiles();for(let X of V){if(this.shouldIgnorePath(X))continue;let $=await this.parseDependencyFile(X);if($)K.push($)}let Q=await this.findLockFiles();for(let X of Q){if(this.shouldIgnorePath(X))continue;let $=await this.parseLockFile(X);if($)K.push($)}let W=await this.findComposerFiles();for(let X of W){if(this.shouldIgnorePath(X))continue;let $=await this.parseComposerFile(X);if($)K.push($)}let B=await this.findGitHubActionsFiles();for(let X of B){if(this.shouldIgnorePath(X))continue;let $=await this.parseGitHubActionsFile(X);if($)K.push($)}let C=await this.findDockerfiles();this.logger.info(`\uD83D\uDD0D Found ${C.length} Dockerfile(s): ${C.join(", ")}`);for(let X of C){if(this.shouldIgnorePath(X))continue;let $=await this.parseDockerfile(X);if($)K.push($),this.logger.info(`\uD83D\uDCE6 Parsed Dockerfile: ${X} with ${$.dependencies.length} dependencies`)}let T=await this.findZigManifests();this.logger.info(`\uD83D\uDD0D Found ${T.length} Zig manifest(s): ${T.join(", ")}`);for(let X of T){if(this.shouldIgnorePath(X))continue;let $=await this.parseZigManifestFile(X);if($)K.push($),this.logger.info(`\uD83D\uDCE6 Parsed Zig manifest: ${X} with ${$.dependencies.length} dependencies`)}let b=await this.findFiles("pantry.lock");for(let X of b){if(this.shouldIgnorePath(X))continue;let $=await this.parsePantryLockFile(X);if($)K.push($),this.logger.info(`\uD83D\uDCE6 Parsed pantry.lock: ${X} with ${$.dependencies.length} dependencies`)}let v=Date.now()-q;return this.logger.success(`Found ${K.length} package files in ${v}ms`),K}catch(O){throw this.logger.error("Failed to scan project:",O),new Y(`Failed to scan project: ${O instanceof Error?O.message:"Unknown error"}`)}}async parsePackageJsonFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8"),V=JSON.parse(O),Q=[];return this.extractDependencies(V.dependencies,"dependencies",q,Q),this.extractDependencies(V.devDependencies,"devDependencies",q,Q),this.extractDependencies(V.peerDependencies,"peerDependencies",q,Q),this.extractDependencies(V.optionalDependencies,"optionalDependencies",q,Q),Q.push(...N(V.engines,q)),{path:q,type:"package.json",content:O,dependencies:Q}}catch(K){return this.logger.warn(`Failed to parse package.json file ${q}:`,K),null}}async parseLockFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8"),V=q.split("/").pop()||"",Q;if(V==="bun.lockb")Q="bun.lockb";else if(V==="package-lock.json")Q="package-lock.json";else if(V==="yarn.lock")Q="yarn.lock";else if(V==="pnpm-lock.yaml")Q="pnpm-lock.yaml";else return null;let W=await this.extractLockFileDependencies(O,Q,q);return{path:q,type:Q,content:O,dependencies:W}}catch(K){return this.logger.warn(`Failed to parse lock file ${q}:`,K),null}}async parseDependencyFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await S(q,O)}catch(K){return this.logger.warn(`Failed to parse dependency file ${q}:`,K),null}}async findDependencyFiles(){let q=[],K=["deps.yaml","deps.yml","dependencies.yaml","dependencies.yml","pkgx.yaml","pkgx.yml",".deps.yaml",".deps.yml"];for(let Q of K){let W=await this.findFiles(Q);q.push(...W)}let O=await this.findFilesByPattern("*.yaml"),V=await this.findFilesByPattern("*.yml");for(let Q of[...O,...V])if(L(Q)&&!q.includes(Q))q.push(Q);return q}async findGitHubActionsFiles(){let q=[];try{if(!(await Z(R(this.projectPath,".github")).catch(()=>null))?.isDirectory())return q;let V=R(this.projectPath,".github","workflows");if((await Z(V).catch(()=>null))?.isDirectory()){let W=await this.findFilesByPatternInDir("*.yaml",V),B=await this.findFilesByPatternInDir("*.yml",V);for(let C of[...W,...B])if(x(C))q.push(C)}}catch{}return q}async findDockerfiles(){return this.findFilesMatching(z)}async findFilesMatching(q,K=this.projectPath){let O=[];try{let V=await A(K);for(let Q of V){let W=R(K,Q);try{let B=await Z(W);if(B.isFile()){if(q(Q))O.push(E(this.projectPath,W).split(H).join("/"))}else if(B.isDirectory()&&!J(Q))O.push(...await this.findFilesMatching(q,W))}catch{continue}}}catch{}return O}async parseGitHubActionsFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await w(q,O)}catch(K){return this.logger.warn(`Failed to parse GitHub Actions file ${q}:`,K),null}}async parseDockerfile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await M(q,O)}catch(K){return this.logger.warn(`Failed to parse Dockerfile ${q}:`,K),null}}async findZigManifests(){let q=[];try{let K=await this.findFiles("build.zig.zon");q.push(...K)}catch{}return q}async parseZigManifestFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await _(q,O)}catch(K){return this.logger.warn(`Failed to parse Zig manifest ${q}:`,K),null}}async findComposerFiles(){let q=[];try{let K=await this.findFiles("composer.json");q.push(...K);let O=await this.findFiles("composer.lock");q.push(...O)}catch{}return q}async parseComposerFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8"),{parseComposerFile:V}=await import("./chunk-1pdvjg0x.js");return await V(q,O)}catch(K){return this.logger.warn(`Failed to parse Composer file ${q}:`,K),null}}async parsePantryLockFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await I(q,O)}catch(K){return this.logger.warn(`Failed to parse pantry.lock file ${q}:`,K),null}}extractDependencies(q,K,O,V){if(!q)return;for(let[Q,W]of Object.entries(q))V.push({name:Q,currentVersion:W,type:K,file:this.getRelativePath(O)})}async extractLockFileDependencies(q,K,O){let V=[];if(K==="package-lock.json")try{let Q=JSON.parse(q);if(Q.packages){for(let[W,B]of Object.entries(Q.packages))if(W&&W!==""&&B&&typeof B==="object"){let C=B;if(C.version){let T=W.startsWith("node_modules/")?W.replace("node_modules/",""):W;V.push({name:T,currentVersion:C.version,type:C.dev?"devDependencies":"dependencies",file:this.getRelativePath(O)})}}}}catch(Q){this.logger.warn("Failed to parse package-lock.json:",Q)}return V}async findFiles(q,K=this.projectPath){let O=[];try{let V=await A(K);for(let Q of V){let W=R(K,Q);try{let B=await Z(W);if(B.isDirectory()){if(!J(Q)){let C=await this.findFiles(q,W);O.push(...C)}}else if(B.isFile()&&Q===q){let C=E(this.projectPath,W);O.push(C.split(H).join("/"))}}catch{continue}}}catch{}return O}async findLockFiles(){let q=["bun.lock","bun.lockb","package-lock.json","yarn.lock","pnpm-lock.yaml"],K=[];for(let O of q){let V=await this.findFiles(O);K.push(...V)}return K}async findFilesByPattern(q){let K=[],O=q.replace("*.","");try{let V=await A(this.projectPath);for(let Q of V){let W=R(this.projectPath,Q),B=await Z(W);if(B.isFile()&&Q.endsWith(`.${O}`)){let C=E(this.projectPath,W);K.push(C.split(H).join("/"))}else if(B.isDirectory()&&!J(Q)){let C=await this.findFilesByPatternInDir(q,W);K.push(...C)}}}catch{}return K}async findFilesByPatternInDir(q,K){let O=[],V=q.replace("*.","");try{let Q=await A(K);for(let W of Q){let B=R(K,W),C=await Z(B);if(C.isFile()&&W.endsWith(`.${V}`)){let T=E(this.projectPath,B);O.push(T.split(H).join("/"))}else if(C.isDirectory()&&!J(W)){let T=await this.findFilesByPatternInDir(q,B);O.push(...T)}}}catch{}return O}shouldIgnorePath(q){if(this.ignoreGlobs.length===0)return!1;let K=q;if(q.startsWith("/")||q.includes(":"))K=this.getRelativePath(q);for(let O of this.ignoreGlobs)if(O.match(K))return this.logger.debug(`Ignoring path: ${K} (matched pattern)`),!0;return!1}getRelativePath(q){return E(this.projectPath,q).split(H).join("/")}async getDependencyCount(){return(await this.scanProject()).reduce((K,O)=>K+O.dependencies.length,0)}async getUniqueDependencies(){return(await this.scanProject()).flatMap((V)=>V.dependencies).filter((V,Q,W)=>Q===W.findIndex((B)=>B.name===V.name))}}
3
- export{m as ld};
2
+ import{xd as J}from"./chunk-0pf9vk80.js";import{yd as Y}from"./chunk-pxv58dh1.js";import{ve as _}from"./chunk-eq5xb8k1.js";import{ye as x,ze as w}from"./chunk-cp3g2srn.js";import{Re as z,Se as M}from"./chunk-xyry3bma.js";import{Ze as N}from"./chunk-5q5tm30a.js";import{Bg as L,Cg as S}from"./chunk-fcax5a60.js";import{Wh as G}from"./chunk-rrm4x81p.js";import{ll as j}from"./chunk-dh8yykbg.js";var{Glob:D}=globalThis.Bun;import{lstat as Z,readdir as A,readFile as U}from"fs/promises";import{join as R,relative as E,sep as H}from"path";async function I(q,K){try{let O=JSON.parse(K),V=[];if(O.packages){for(let Q of Object.values(O.packages))if(Q.name&&Q.version)V.push({name:Q.name,currentVersion:Q.version,type:"dependencies",file:q})}return{path:q,type:"pantry.lock",content:K,dependencies:V}}catch(O){return G().warn(`Failed to parse pantry.lock file ${q}:`,O),null}}class m{projectPath;logger;ignoreGlobs=[];constructor(q,K,O){this.projectPath=q;this.logger=K;if(O&&O.length>0)this.ignoreGlobs=O.map((V)=>new D(V)),this.logger.info(`Initialized ${this.ignoreGlobs.length} ignore patterns: ${O.join(", ")}`)}async scanProject(){this.logger.info("Scanning project for package files...");let q=Date.now(),K=[];try{let O=await this.findFiles("package.json");for(let X of O){if(this.shouldIgnorePath(X))continue;let $=await this.parsePackageJsonFile(X);if($)K.push($)}let V=await this.findDependencyFiles();for(let X of V){if(this.shouldIgnorePath(X))continue;let $=await this.parseDependencyFile(X);if($)K.push($)}let Q=await this.findLockFiles();for(let X of Q){if(this.shouldIgnorePath(X))continue;let $=await this.parseLockFile(X);if($)K.push($)}let W=await this.findComposerFiles();for(let X of W){if(this.shouldIgnorePath(X))continue;let $=await this.parseComposerFile(X);if($)K.push($)}let B=await this.findGitHubActionsFiles();for(let X of B){if(this.shouldIgnorePath(X))continue;let $=await this.parseGitHubActionsFile(X);if($)K.push($)}let C=await this.findDockerfiles();this.logger.info(`\uD83D\uDD0D Found ${C.length} Dockerfile(s): ${C.join(", ")}`);for(let X of C){if(this.shouldIgnorePath(X))continue;let $=await this.parseDockerfile(X);if($)K.push($),this.logger.info(`\uD83D\uDCE6 Parsed Dockerfile: ${X} with ${$.dependencies.length} dependencies`)}let T=await this.findZigManifests();this.logger.info(`\uD83D\uDD0D Found ${T.length} Zig manifest(s): ${T.join(", ")}`);for(let X of T){if(this.shouldIgnorePath(X))continue;let $=await this.parseZigManifestFile(X);if($)K.push($),this.logger.info(`\uD83D\uDCE6 Parsed Zig manifest: ${X} with ${$.dependencies.length} dependencies`)}let b=await this.findFiles("pantry.lock");for(let X of b){if(this.shouldIgnorePath(X))continue;let $=await this.parsePantryLockFile(X);if($)K.push($),this.logger.info(`\uD83D\uDCE6 Parsed pantry.lock: ${X} with ${$.dependencies.length} dependencies`)}let v=Date.now()-q;return this.logger.success(`Found ${K.length} package files in ${v}ms`),K}catch(O){throw this.logger.error("Failed to scan project:",O),new Y(`Failed to scan project: ${O instanceof Error?O.message:"Unknown error"}`)}}async parsePackageJsonFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8"),V=JSON.parse(O),Q=[];return this.extractDependencies(V.dependencies,"dependencies",q,Q),this.extractDependencies(V.devDependencies,"devDependencies",q,Q),this.extractDependencies(V.peerDependencies,"peerDependencies",q,Q),this.extractDependencies(V.optionalDependencies,"optionalDependencies",q,Q),Q.push(...N(V.engines,q)),{path:q,type:"package.json",content:O,dependencies:Q}}catch(K){return this.logger.warn(`Failed to parse package.json file ${q}:`,K),null}}async parseLockFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8"),V=q.split("/").pop()||"",Q;if(V==="bun.lockb")Q="bun.lockb";else if(V==="package-lock.json")Q="package-lock.json";else if(V==="yarn.lock")Q="yarn.lock";else if(V==="pnpm-lock.yaml")Q="pnpm-lock.yaml";else return null;let W=await this.extractLockFileDependencies(O,Q,q);return{path:q,type:Q,content:O,dependencies:W}}catch(K){return this.logger.warn(`Failed to parse lock file ${q}:`,K),null}}async parseDependencyFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await S(q,O)}catch(K){return this.logger.warn(`Failed to parse dependency file ${q}:`,K),null}}async findDependencyFiles(){let q=[],K=["deps.yaml","deps.yml","dependencies.yaml","dependencies.yml","pkgx.yaml","pkgx.yml",".deps.yaml",".deps.yml"];for(let Q of K){let W=await this.findFiles(Q);q.push(...W)}let O=await this.findFilesByPattern("*.yaml"),V=await this.findFilesByPattern("*.yml");for(let Q of[...O,...V])if(L(Q)&&!q.includes(Q))q.push(Q);return q}async findGitHubActionsFiles(){let q=[];try{if(!(await Z(R(this.projectPath,".github")).catch(()=>null))?.isDirectory())return q;let V=R(this.projectPath,".github","workflows");if((await Z(V).catch(()=>null))?.isDirectory()){let W=await this.findFilesByPatternInDir("*.yaml",V),B=await this.findFilesByPatternInDir("*.yml",V);for(let C of[...W,...B])if(x(C))q.push(C)}}catch{}return q}async findDockerfiles(){return this.findFilesMatching(z)}async findFilesMatching(q,K=this.projectPath){let O=[];try{let V=await A(K);for(let Q of V){let W=R(K,Q);try{let B=await Z(W);if(B.isFile()){if(q(Q))O.push(E(this.projectPath,W).split(H).join("/"))}else if(B.isDirectory()&&!J(Q))O.push(...await this.findFilesMatching(q,W))}catch{continue}}}catch{}return O}async parseGitHubActionsFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await w(q,O)}catch(K){return this.logger.warn(`Failed to parse GitHub Actions file ${q}:`,K),null}}async parseDockerfile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await M(q,O)}catch(K){return this.logger.warn(`Failed to parse Dockerfile ${q}:`,K),null}}async findZigManifests(){let q=[];try{let K=await this.findFiles("build.zig.zon");q.push(...K)}catch{}return q}async parseZigManifestFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await _(q,O)}catch(K){return this.logger.warn(`Failed to parse Zig manifest ${q}:`,K),null}}async findComposerFiles(){let q=[];try{let K=await this.findFiles("composer.json");q.push(...K);let O=await this.findFiles("composer.lock");q.push(...O)}catch{}return q}async parseComposerFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8"),{parseComposerFile:V}=await import("./chunk-ebb90mp9.js");return await V(q,O)}catch(K){return this.logger.warn(`Failed to parse Composer file ${q}:`,K),null}}async parsePantryLockFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await I(q,O)}catch(K){return this.logger.warn(`Failed to parse pantry.lock file ${q}:`,K),null}}extractDependencies(q,K,O,V){if(!q)return;for(let[Q,W]of Object.entries(q))V.push({name:Q,currentVersion:W,type:K,file:this.getRelativePath(O)})}async extractLockFileDependencies(q,K,O){let V=[];if(K==="package-lock.json")try{let Q=JSON.parse(q);if(Q.packages){for(let[W,B]of Object.entries(Q.packages))if(W&&W!==""&&B&&typeof B==="object"){let C=B;if(C.version){let T=W.startsWith("node_modules/")?W.replace("node_modules/",""):W;V.push({name:T,currentVersion:C.version,type:C.dev?"devDependencies":"dependencies",file:this.getRelativePath(O)})}}}}catch(Q){this.logger.warn("Failed to parse package-lock.json:",Q)}return V}async findFiles(q,K=this.projectPath){let O=[];try{let V=await A(K);for(let Q of V){let W=R(K,Q);try{let B=await Z(W);if(B.isDirectory()){if(!J(Q)){let C=await this.findFiles(q,W);O.push(...C)}}else if(B.isFile()&&Q===q){let C=E(this.projectPath,W);O.push(C.split(H).join("/"))}}catch{continue}}}catch{}return O}async findLockFiles(){let q=["bun.lock","bun.lockb","package-lock.json","yarn.lock","pnpm-lock.yaml"],K=[];for(let O of q){let V=await this.findFiles(O);K.push(...V)}return K}async findFilesByPattern(q){let K=[],O=q.replace("*.","");try{let V=await A(this.projectPath);for(let Q of V){let W=R(this.projectPath,Q),B=await Z(W);if(B.isFile()&&Q.endsWith(`.${O}`)){let C=E(this.projectPath,W);K.push(C.split(H).join("/"))}else if(B.isDirectory()&&!J(Q)){let C=await this.findFilesByPatternInDir(q,W);K.push(...C)}}}catch{}return K}async findFilesByPatternInDir(q,K){let O=[],V=q.replace("*.","");try{let Q=await A(K);for(let W of Q){let B=R(K,W),C=await Z(B);if(C.isFile()&&W.endsWith(`.${V}`)){let T=E(this.projectPath,B);O.push(T.split(H).join("/"))}else if(C.isDirectory()&&!J(W)){let T=await this.findFilesByPatternInDir(q,B);O.push(...T)}}}catch{}return O}shouldIgnorePath(q){if(this.ignoreGlobs.length===0)return!1;let K=q;if(q.startsWith("/")||q.includes(":"))K=this.getRelativePath(q);for(let O of this.ignoreGlobs)if(O.match(K))return this.logger.debug(`Ignoring path: ${K} (matched pattern)`),!0;return!1}getRelativePath(q){return E(this.projectPath,q).split(H).join("/")}async getDependencyCount(){return(await this.scanProject()).reduce((K,O)=>K+O.dependencies.length,0)}async getUniqueDependencies(){return(await this.scanProject()).flatMap((V)=>V.dependencies).filter((V,Q,W)=>Q===W.findIndex((B)=>B.name===V.name))}}
3
+ export{m as wd};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{D as s,E as t,F as u,G as v,H as w,c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,l as j,m as k,n as l,o as m,p as n,q as o,u as p,v as q,w as r}from"./chunk-nk8wxxy7.js";import"./chunk-16aeend1.js";export{r as toFile,v as default,w as betaRefusalFallbackMiddleware,l as UnprocessableEntityError,f as RetryableError,m as RateLimitError,i as PermissionDeniedError,q as PagePromise,j as NotFoundError,n as InternalServerError,s as HUMAN_PROMPT,k as ConflictError,o as BetaFallbackState,u as BaseAnthropic,g as BadRequestError,h as AuthenticationError,a as AnthropicError,v as Anthropic,c as APIUserAbortError,p as APIPromise,b as APIError,e as APIConnectionTimeoutError,d as APIConnectionError,t as AI_PROMPT};
2
+ import{D as s,E as t,F as u,G as v,H as w,c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,l as j,m as k,n as l,o as m,p as n,q as o,u as p,v as q,w as r}from"./chunk-33ymc651.js";import"./chunk-dh8yykbg.js";export{r as toFile,v as default,w as betaRefusalFallbackMiddleware,l as UnprocessableEntityError,f as RetryableError,m as RateLimitError,i as PermissionDeniedError,q as PagePromise,j as NotFoundError,n as InternalServerError,s as HUMAN_PROMPT,k as ConflictError,o as BetaFallbackState,u as BaseAnthropic,g as BadRequestError,h as AuthenticationError,a as AnthropicError,v as Anthropic,c as APIUserAbortError,p as APIPromise,b as APIError,e as APIConnectionTimeoutError,d as APIConnectionError,t as AI_PROMPT};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{$a as e,Xa as a,Ya as b,Za as c,_a as d,ab as f,bb as g,cb as h,db as i,eb as j,fb as k,gb as l}from"./chunk-jqh7vx2n.js";import"./chunk-1pecmenc.js";import"./chunk-16aeend1.js";export{k as withTouchOffer,b as unitTestsTouch,d as simplifyTouch,i as renderTouchOffer,e as planTouch,l as parseTouchSelections,j as hasTouchOffer,g as getFinishingTouch,a as docstringsTouch,c as autofixTouch,h as TOUCH_OFFER_MARKER,f as FINISHING_TOUCHES};
2
+ import{Fa as a,Ga as b,Ha as c,Ia as d,Ja as e,Ka as f,La as g,Ma as h,Na as i,Oa as j,Pa as k,Qa as l}from"./chunk-qbqk1jax.js";import"./chunk-5nn5mms4.js";import"./chunk-dh8yykbg.js";export{k as withTouchOffer,b as unitTestsTouch,d as simplifyTouch,i as renderTouchOffer,e as planTouch,l as parseTouchSelections,j as hasTouchOffer,g as getFinishingTouch,a as docstringsTouch,c as autofixTouch,h as TOUCH_OFFER_MARKER,f as FINISHING_TOUCHES};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ca as a,da as b,ea as c,fa as d}from"./chunk-73a090ce.js";import"./chunk-rrm4x81p.js";import"./chunk-dh8yykbg.js";export{a as validateAgainstSchema,b as runHeadless,d as publishOutput,c as formatGithubOutput};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Nc as a,Oc as b,Pc as c,Qc as d,Rc as e,Sc as f,Tc as g}from"./chunk-58et72hc.js";import"./chunk-h9deve0y.js";import"./chunk-vxt1h0c4.js";import"./chunk-fcax5a60.js";import"./chunk-q3dg57xx.js";import"./chunk-r0jmwzr3.js";import"./chunk-sg7bhtb7.js";import"./chunk-rrm4x81p.js";import"./chunk-dkgz8hsd.js";import"./chunk-dh8yykbg.js";export{b as regenerateLockFile,d as nestedLockProjects,f as missingLockFiles,e as lockFileFor,g as hasLockFile,a as getAllLockFilePaths,c as detectRequiredPackageManagers};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Nc as v,Oc as F,Pc as B,Qc as k}from"./chunk-j57716xw.js";import{$f as I,_f as y,ag as W}from"./chunk-cj4d5ad7.js";import{zh as T}from"./chunk-yh13j2af.js";import{Gh as R}from"./chunk-6w0n6c07.js";import{Lh as U}from"./chunk-s0ps33ft.js";import{Nh as L,Oh as x,Rh as D}from"./chunk-wzncz6j5.js";import{Buffer as S}from"buffer";import{spawn as w}from"child_process";import j from"process";var g=/\b(?:gh[pousr]_[A-Z0-9_]{20,}|github_pat_[A-Z0-9_]{20,}|[A-Z0-9]{40,})\b/gi;function N(Q){return Q==="completed"||Q==="in_progress"?Q:"queued"}function f(Q){if(typeof Q!=="string")return null;if(Q==="success"||Q==="cancelled")return Q;if(Q==="failure"||Q==="timed_out"||Q==="action_required")return"failure";return"skipped"}function d(Q,X){let Y=Q.replace(g,"[REDACTED]");if(X&&X.length>=8)Y=Y.split(X).join("[REDACTED]");return Y}class P extends Error{constructor(Q){super(Q);this.name="LockfileRegenerationError"}}function h(Q,X){let Y=`http.${Q.replace(/\/+$/,"")}/.extraheader`,Z=S.from(`x-access-token:${X}`).toString("base64");return["-c",`${Y}=`,"-c",`${Y}=AUTHORIZATION: basic ${Z}`]}class E extends Error{constructor(Q){super(Q);this.name="WorkflowPermissionError"}}function l(Q){let X=`${x(Q)} ${Q?.message??""}`;return/refusing to allow (?:a GitHub App|an OAuth App|a Personal Access Token)[^\n]*workflow/i.test(X)}function m(Q){let X=`${x(Q)} ${Q?.message??""}`;return/not permitted to create or approve pull requests/i.test(X)||Q?.status===403&&/pull/i.test(X)}class b{token;owner;repo;hasWorkflowPermissions;workflowToken;apiUrl;cache={pullRequests:new Map,issues:new Map};cacheTTL=120000;logger;constructor(Q,X,Y,Z=!1,$,J,G){this.token=Q;this.owner=X;this.repo=Y;this.hasWorkflowPermissions=Z;this.workflowToken=$;this.apiUrl=J?J.replace(/\/+$/,""):T(),this.logger=G??D()}capabilities(){return{pinIssues:!0,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!0,nativeAutoMerge:!0,commentReactions:!0,ciLogs:!0,ciRuns:!0,reviewThreads:!0,teamReviewers:!0,draftPullRequests:!0,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!0,labels:!0}}isCacheValid(Q){return Date.now()-Q<this.cacheTTL}clearCache(){this.cache.pullRequests.clear(),this.cache.issues.clear()}async branchExists(Q){try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Q}`),!0}catch(X){if(X.message?.includes("404"))return!1;return this.logger.warn(`\u26A0\uFE0F Error checking branch ${Q}: ${x(X)}`),!1}}async createBranch(Q,X){try{let Z=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${X}`)).object.sha;await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/refs`,{ref:`refs/heads/${Q}`,sha:Z}),this.logger.info(`\u2705 Created branch ${Q} from ${X}`)}catch(Y){throw this.logger.error(`\u274C Failed to create branch ${Q}: ${x(Y)}`),Y}}async commitChanges(Q,X,Y,Z="main"){try{await this.commitChangesWithGit(Q,X,Y,Z)}catch($){if($ instanceof P||$ instanceof y)throw $;if(l($)){let J=Y.filter((_)=>!_.path.includes(".github/workflows/")),G=Y.length-J.length;if(J.length===0)throw new E(`The token may not update workflow files (${G} in this change). Grant the GitHub App the Workflows permission, or use a PAT with the workflow scope as BUDDY_TOKEN.`);this.logger.warn(`\u26A0\uFE0F The token may not update workflow files; committing the ${J.length} other file(s) without the ${G} workflow file(s)`),await this.commitChangesWithGit(Q,X,J,Z);return}this.logger.warn(`\u26A0\uFE0F Git CLI commit failed, falling back to GitHub API: ${$}`),await this.commitChangesWithAPI(Q,X,Y,Z)}}async commitChangesWithGit(Q,X,Y,Z="main"){try{let $=Y.filter((V)=>V.path.includes(".github/workflows/")),J=Y.filter((V)=>!V.path.includes(".github/workflows/"));if($.length>0&&!this.hasWorkflowPermissions)if(this.logger.warn(`\u26A0\uFE0F Detected ${$.length} workflow file(s). These require elevated permissions.`),this.logger.warn(`\u26A0\uFE0F Workflow files: ${$.map((V)=>V.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. BUDDY_TOKEN not detected or lacks workflow permissions."),J.length>0)this.logger.info(`\uD83D\uDCDD Committing ${J.length} non-workflow files...`),Y=J;else{this.logger.warn("\u26A0\uFE0F All files are workflow files. No files will be committed in this PR."),this.logger.warn("\uD83D\uDCA1 To update workflow files, ensure BUDDY_TOKEN is set with workflow:write permissions."),this.logger.info('\uD83D\uDCDD Creating empty commit to avoid "No commits between branches" error...');try{await this.runCommand("git",["commit","--allow-empty","-m","Workflow files require elevated permissions - no changes committed"]),this.logger.info("\u2705 Created empty commit for workflow-only PR")}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to create empty commit: ${V}`);try{let C=Bun.file("README.md");if(await C.exists()){let H=`${await C.text()}
2
+ import{Nc as v,Oc as F,Pc as B,Qc as k}from"./chunk-58et72hc.js";import{$f as y,ag as I,bg as W}from"./chunk-2g8r8khw.js";import{Ch as T}from"./chunk-r0jmwzr3.js";import{Lh as R}from"./chunk-8y4szfd2.js";import{Qh as U}from"./chunk-sg7bhtb7.js";import{Sh as L,Th as x,Wh as D}from"./chunk-rrm4x81p.js";import{Buffer as S}from"buffer";import{spawn as w}from"child_process";import j from"process";var g=/\b(?:gh[pousr]_[A-Z0-9_]{20,}|github_pat_[A-Z0-9_]{20,}|[A-Z0-9]{40,})\b/gi;function N(Q){return Q==="completed"||Q==="in_progress"?Q:"queued"}function f(Q){if(typeof Q!=="string")return null;if(Q==="success"||Q==="cancelled")return Q;if(Q==="failure"||Q==="timed_out"||Q==="action_required")return"failure";return"skipped"}function d(Q,X){let Y=Q.replace(g,"[REDACTED]");if(X&&X.length>=8)Y=Y.split(X).join("[REDACTED]");return Y}class P extends Error{constructor(Q){super(Q);this.name="LockfileRegenerationError"}}function h(Q,X){let Y=`http.${Q.replace(/\/+$/,"")}/.extraheader`,Z=S.from(`x-access-token:${X}`).toString("base64");return["-c",`${Y}=`,"-c",`${Y}=AUTHORIZATION: basic ${Z}`]}class E extends Error{constructor(Q){super(Q);this.name="WorkflowPermissionError"}}function l(Q){let X=`${x(Q)} ${Q?.message??""}`;return/refusing to allow (?:a GitHub App|an OAuth App|a Personal Access Token)[^\n]*workflow/i.test(X)}function m(Q){let X=`${x(Q)} ${Q?.message??""}`;return/not permitted to create or approve pull requests/i.test(X)||Q?.status===403&&/pull/i.test(X)}class b{token;owner;repo;hasWorkflowPermissions;workflowToken;apiUrl;cache={pullRequests:new Map,issues:new Map};cacheTTL=120000;logger;constructor(Q,X,Y,Z=!1,$,J,G){this.token=Q;this.owner=X;this.repo=Y;this.hasWorkflowPermissions=Z;this.workflowToken=$;this.apiUrl=J?J.replace(/\/+$/,""):T(),this.logger=G??D()}capabilities(){return{pinIssues:!0,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!0,nativeAutoMerge:!0,commentReactions:!0,ciLogs:!0,ciRuns:!0,reviewThreads:!0,teamReviewers:!0,draftPullRequests:!0,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!0,labels:!0}}isCacheValid(Q){return Date.now()-Q<this.cacheTTL}clearCache(){this.cache.pullRequests.clear(),this.cache.issues.clear()}async branchExists(Q){try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Q}`),!0}catch(X){if(X.message?.includes("404"))return!1;return this.logger.warn(`\u26A0\uFE0F Error checking branch ${Q}: ${x(X)}`),!1}}async createBranch(Q,X){try{let Z=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${X}`)).object.sha;await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/refs`,{ref:`refs/heads/${Q}`,sha:Z}),this.logger.info(`\u2705 Created branch ${Q} from ${X}`)}catch(Y){throw this.logger.error(`\u274C Failed to create branch ${Q}: ${x(Y)}`),Y}}async commitChanges(Q,X,Y,Z="main"){try{await this.commitChangesWithGit(Q,X,Y,Z)}catch($){if($ instanceof P||$ instanceof y)throw $;if(l($)){let J=Y.filter((_)=>!_.path.includes(".github/workflows/")),G=Y.length-J.length;if(J.length===0)throw new E(`The token may not update workflow files (${G} in this change). Grant the GitHub App the Workflows permission, or use a PAT with the workflow scope as BUDDY_TOKEN.`);this.logger.warn(`\u26A0\uFE0F The token may not update workflow files; committing the ${J.length} other file(s) without the ${G} workflow file(s)`),await this.commitChangesWithGit(Q,X,J,Z);return}this.logger.warn(`\u26A0\uFE0F Git CLI commit failed, falling back to GitHub API: ${$}`),await this.commitChangesWithAPI(Q,X,Y,Z)}}async commitChangesWithGit(Q,X,Y,Z="main"){try{let $=Y.filter((V)=>V.path.includes(".github/workflows/")),J=Y.filter((V)=>!V.path.includes(".github/workflows/"));if($.length>0&&!this.hasWorkflowPermissions)if(this.logger.warn(`\u26A0\uFE0F Detected ${$.length} workflow file(s). These require elevated permissions.`),this.logger.warn(`\u26A0\uFE0F Workflow files: ${$.map((V)=>V.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. BUDDY_TOKEN not detected or lacks workflow permissions."),J.length>0)this.logger.info(`\uD83D\uDCDD Committing ${J.length} non-workflow files...`),Y=J;else{this.logger.warn("\u26A0\uFE0F All files are workflow files. No files will be committed in this PR."),this.logger.warn("\uD83D\uDCA1 To update workflow files, ensure BUDDY_TOKEN is set with workflow:write permissions."),this.logger.info('\uD83D\uDCDD Creating empty commit to avoid "No commits between branches" error...');try{await this.runCommand("git",["commit","--allow-empty","-m","Workflow files require elevated permissions - no changes committed"]),this.logger.info("\u2705 Created empty commit for workflow-only PR")}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to create empty commit: ${V}`);try{let C=Bun.file("README.md");if(await C.exists()){let H=`${await C.text()}
3
3
 
4
4
  <!-- Updated by Buddy -->
5
5
  `;await Bun.write("README.md",H),await this.runCommand("git",["add","README.md"]),await this.runCommand("git",["commit","-m","Update README for workflow-only PR"]),this.logger.info("\u2705 Created README update for workflow-only PR")}}catch(K){this.logger.error(`\u274C Failed to create any commit: ${K}`)}}return}else if($.length>0)this.logger.info(`\u2705 Including ${$.length} workflow file(s) with elevated permissions`);try{await this.runCommand("git",["config","user.name","github-actions[bot]"]),await this.runCommand("git",["config","user.email","41898282+github-actions[bot]@users.noreply.github.com"]),this.logger.info("\u2705 Git identity configured for github-actions[bot]")}catch(V){this.logger.warn("\u26A0\uFE0F Failed to configure Git identity:",V)}await this.runCommand("git",["fetch","origin"]),this.logger.info(`\uD83D\uDD04 Recreating ${Q} from origin/${Z} (Renovate-style)...`);try{await this.runCommand("git",["checkout",Q])}catch{try{await this.runCommand("git",["checkout","-b",Q,`origin/${Q}`])}catch{await this.runCommand("git",["checkout","-b",Q])}}await this.runCommand("git",["reset","--hard",`origin/${Z}`]),await this.runCommand("git",["clean","-fd"]),this.logger.info(`\u2705 Reset ${Q} to origin/${Z}`),await W(Y,async(V)=>{try{return await this.runCommand("git",["cat-file","-e",`origin/${Z}:${V}`]),!0}catch{return!1}});for(let V of Y){let K=I(V.path);if(j.env.NODE_ENV==="test"||j.env.BUN_ENV==="test"){if(["package.json","bun.lock","bun.lockb","package-lock.json","yarn.lock"].includes(K)&&V.content==='{"name":"x"}'){this.logger.warn(`\u26A0\uFE0F Skipping test file write to ${K} to prevent overwriting project files`);continue}}if(V.type==="delete")try{await this.runCommand("git",["rm",K])}catch{}else await Bun.write(K,V.content),await this.runCommand("git",["add",K])}if(!(j.env.NODE_ENV==="test"||j.env.BUN_ENV==="test")){let V=Y.map((C)=>C.path.replace(/^\.\//,"").replace(/^\/+/,"")),K=B(V);if(K.length>0){this.logger.info(`\uD83D\uDD12 Regenerating lock files for: ${K.join(", ")}`);let C=j.cwd(),M=[];for(let H of K)try{let z=await F(H,C);if(z.success)for(let q of v())try{await this.runCommand("git",["add",q])}catch{}else M.push(`${H}: ${z.message}`)}catch(z){M.push(`${H}: ${z instanceof Error?z.message:String(z)}`)}for(let H of k(V,C))try{let z=await F(H.manager,`${C}/${H.dir}`);if(z.success)await this.runCommand("git",["add",H.lockFile]);else M.push(`${H.dir} (${H.manager}): ${z.message}`)}catch(z){M.push(`${H.dir} (${H.manager}): ${z instanceof Error?z.message:String(z)}`)}if(M.length>0){let H=M.map((z)=>` - ${z}`).join(`
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{qd as a}from"./chunk-t7grk0az.js";import"./chunk-r0jmwzr3.js";import"./chunk-sg7bhtb7.js";import"./chunk-rrm4x81p.js";import"./chunk-dh8yykbg.js";export{a as DeprecatedDependenciesChecker};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{zh as W}from"./chunk-yh13j2af.js";import{Lh as y}from"./chunk-s0ps33ft.js";import{Rh as J}from"./chunk-wzncz6j5.js";import{gl as F}from"./chunk-16aeend1.js";import S from"process";function G(E){let q=E.replace(/\\/g,"/");return q.includes(".github/workflows/")&&(q.endsWith(".yml")||q.endsWith(".yaml"))}async function L(E,q){try{if(!G(E))return null;let I=[],j=q.split(`
2
+ import{Ch as W}from"./chunk-r0jmwzr3.js";import{Qh as y}from"./chunk-sg7bhtb7.js";import{Wh as J}from"./chunk-rrm4x81p.js";import{ll as F}from"./chunk-dh8yykbg.js";import S from"process";function G(E){let q=E.replace(/\\/g,"/");return q.includes(".github/workflows/")&&(q.endsWith(".yml")||q.endsWith(".yaml"))}async function L(E,q){try{if(!G(E))return null;let I=[],j=q.split(`
3
3
  `);for(let K=0;K<j.length;K++){let Q=j[K].trim().match(/^-?\s*uses:\s*(.+)/);if(Q){let $=Q[1].trim().replace(/['"`]/g,"");if($.startsWith("./")||$.startsWith("docker://"))continue;let X=$.split("@");if(X.length===2){let[_,Y]=X;if(!_||!_.trim())continue;let[z,...k]=Y.split("#"),M=z.trim(),V={name:_.trim(),currentVersion:M,type:"github-actions",file:E};if(v(M)){let x=k.join("#").trim().split(/\s+/)[0];V.metadata=x?{pinnedSha:M,pinnedVersion:x}:{pinnedSha:M}}if(!I.find((x)=>x.name===V.name&&x.currentVersion===V.currentVersion))I.push(V)}}}return{path:E,type:"github-actions",content:q,dependencies:I}}catch(I){return J().warn(`Failed to parse GitHub Actions file ${E}:`,I),null}}function v(E){return/^[0-9a-f]{40}$/i.test(E)}function R(E,q){return E.replace(/^v/i,"")===q.replace(/^v/i,"")}async function U(E,q,I){try{if(!G(E))return q;let j=q;for(let K of I){let O=K.name.replace(/\s*\(.*\)$/,""),Z=O.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(K.resolved?.sha){let $=new RegExp(`((?:^\\s*-\\s*)?uses:\\s*["']?)(${Z})@(${K.currentVersion})(["']?)([ \\t]*#[^\\n]*)?`,"gm");j=j.replace($,`$1$2@${K.resolved.sha}$4 # ${K.newVersion}`);continue}let Q=new RegExp(`((?:^\\s*-\\s*)?uses:\\s*["']?)(${O.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})@(${K.currentVersion.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})(["']?)`,"gm");j=j.replace(Q,`$1$2@${K.newVersion}$4`)}return j}catch(j){return J().warn(`Failed to update GitHub Actions file ${E}:`,j),q}}async function D(E){let q=[],I=new Map;for(let j of E)if(G(j.file)){if(!I.has(j.file))I.set(j.file,[]);I.get(j.file).push(j)}for(let[j,K]of I)try{let O=await import("fs");if(O.existsSync(j)){let Z=O.readFileSync(j,"utf-8"),Q=await U(j,Z,K);q.push({path:j,content:Q,type:"update"})}}catch(O){J().warn(`Failed to generate updates for GitHub Actions file ${j}:`,O)}return q}async function b(E,q){let[I,j]=E.split("/");if(!I||!j)return null;let K={Accept:"application/vnd.github.v3+json","User-Agent":"buddy"},O=S.env.BUDDY_TOKEN||S.env.GITHUB_TOKEN||S.env.GH_TOKEN;if(O)K.Authorization=`Bearer ${O}`;try{let Z=await y(`${W()}/repos/${I}/${j}/commits/${encodeURIComponent(q)}`,{headers:K});if(!Z.ok)return null;let Q=await Z.json();return Q.sha&&v(Q.sha)?Q.sha:null}catch{return null}}async function P(E){try{if(!E.includes("/"))return J().info(`\u26A0\uFE0F Invalid action name format: ${E}`),null;let[q,I]=E.split("/");J().info(`\uD83D\uDD0D Fetching latest version for ${q}/${I}`);let j={Accept:"application/vnd.github.v3+json","User-Agent":"buddy"},K=S.env.BUDDY_TOKEN||S.env.GITHUB_TOKEN||S.env.GH_TOKEN;if(K)j.Authorization=`Bearer ${K}`;let O=W();J().info(`\uD83D\uDCE1 Trying latest release for ${q}/${I}`);let Z=await y(`${O}/repos/${q}/${I}/releases/latest`,{headers:j});if(Z.ok){let X=await Z.json();if(X.tag_name)return J().info(`\u2705 Found latest release: ${X.tag_name}`),X.tag_name}else J().info(`\u26A0\uFE0F Latest release not found: ${Z.status} ${Z.statusText}`);J().info(`\uD83D\uDCE1 Trying all releases for ${q}/${I}`);let Q=await y(`${O}/repos/${q}/${I}/releases?per_page=10`,{headers:j});if(Q.ok){let X=await Q.json();if(!Array.isArray(X))J().info("\u26A0\uFE0F Unexpected releases response format (expected array)");else{J().info(`\uD83D\uDCCB Found ${X.length} releases`);let _=X.filter((Y)=>Y.tag_name&&!Y.tag_name.includes("-")).sort((Y,z)=>{let k=Y.published_at?new Date(Y.published_at).getTime():0;return(z.published_at?new Date(z.published_at).getTime():0)-k});if(_.length>0)return J().info(`\u2705 Found latest stable release: ${_[0].tag_name}`),_[0].tag_name||null}}else J().info(`\u26A0\uFE0F Releases not found: ${Q.status} ${Q.statusText}`);J().info(`\uD83D\uDCE1 Trying tags for ${q}/${I}`);let $=await y(`${O}/repos/${q}/${I}/tags?per_page=10`,{headers:j});if($.ok){let X=await $.json();if(!Array.isArray(X))J().info("\u26A0\uFE0F Unexpected tags response format (expected array)");else{J().info(`\uD83D\uDCCB Found ${X.length} tags`);let _=X.filter((Y)=>Y.name&&!Y.name.includes("-")).map((Y)=>Y.name).sort((Y,z)=>{let k=Y.replace(/^v/,""),M=z.replace(/^v/,""),V=k.split(".").map(Number),B=M.split(".").map(Number);for(let x=0;x<Math.max(V.length,B.length);x++){let H=V[x]||0,T=B[x]||0;if(H!==T)return T-H}return 0});if(_.length>0)return J().info(`\u2705 Found latest stable tag: ${_[0]}`),_[0]}}else J().info(`\u26A0\uFE0F Tags not found: ${$.status} ${$.statusText}`);return J().info(`\u274C No version found for ${E}`),null}catch(q){return J().warn(`Failed to fetch latest version for ${E}:`,q),null}}
4
- export{G as xe,L as ye,v as ze,R as Ae,U as Be,D as Ce,b as De,P as Ee};
4
+ export{G as ye,L as ze,v as Ae,R as Be,U as Ce,D as De,b as Ee,P as Fe};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{I as a,J as b,K as c,L as d,M as e,N as f}from"./chunk-47k0qdd5.js";import"./chunk-sg7bhtb7.js";import"./chunk-rrm4x81p.js";import"./chunk-dh8yykbg.js";export{b as productFor,f as describeEol,c as cycleFor,d as checkEol,e as EOL_WARNING_DAYS,a as EOL_PRODUCTS};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Vf as K,Xf as T,Yf as S,Zf as F}from"./chunk-z18bksyr.js";import{Lh as N}from"./chunk-s0ps33ft.js";import{Rh as C}from"./chunk-wzncz6j5.js";import{gl as _}from"./chunk-16aeend1.js";var x={claude:"claude-opus-5","claude-opus":"claude-opus-5",opus:"claude-opus-5","claude-sonnet":"claude-sonnet-5",sonnet:"claude-sonnet-5","claude-haiku":"claude-haiku-4-5",haiku:"claude-haiku-4-5","claude-fable":"claude-fable-5",fable:"claude-fable-5"},L={anthropic:"claude-opus-5"},w={anthropic:["ANTHROPIC_API_KEY"],openai:["OPENAI_API_KEY"],google:["GOOGLE_API_KEY","GEMINI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],"openai-compatible":["OPENAI_COMPATIBLE_API_KEY","OPENAI_API_KEY"]},D=["anthropic","openai","google","openrouter"];function M(j){return x[j.toLowerCase().trim()]??j}var b=16000;function k(j){let Z;async function $(){if(Z)return Z;let H;try{H=(await import("./chunk-sddaassq.js")).default}catch{throw new F(`The Anthropic provider needs @anthropic-ai/sdk, which is an optional peer dependency.
2
+ import{Vf as S,Wf as F}from"./chunk-xntpzagn.js";import{Yf as K,_f as T}from"./chunk-20sxtyt7.js";import{Qh as N}from"./chunk-sg7bhtb7.js";import{Wh as C}from"./chunk-rrm4x81p.js";import{ll as _}from"./chunk-dh8yykbg.js";var x={claude:"claude-opus-5","claude-opus":"claude-opus-5",opus:"claude-opus-5","claude-sonnet":"claude-sonnet-5",sonnet:"claude-sonnet-5","claude-haiku":"claude-haiku-4-5",haiku:"claude-haiku-4-5","claude-fable":"claude-fable-5",fable:"claude-fable-5"},L={anthropic:"claude-opus-5"},w={anthropic:["ANTHROPIC_API_KEY"],openai:["OPENAI_API_KEY"],google:["GOOGLE_API_KEY","GEMINI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],"openai-compatible":["OPENAI_COMPATIBLE_API_KEY","OPENAI_API_KEY"]},D=["anthropic","openai","google","openrouter"];function M(j){return x[j.toLowerCase().trim()]??j}var b=16000;function k(j){let Z;async function $(){if(Z)return Z;let H;try{H=(await import("./chunk-agdvymzh.js")).default}catch{throw new F(`The Anthropic provider needs @anthropic-ai/sdk, which is an optional peer dependency.
3
3
  Install it with: bun add @anthropic-ai/sdk`,"anthropic")}return Z=new H({apiKey:j.apiKey,...j.baseUrl?{baseURL:j.baseUrl}:{}}),Z}return{name:"anthropic",async complete(H,G){let W={};if(H.effort)W.effort=H.effort;if(H.jsonSchema)W.format={type:"json_schema",schema:H.jsonSchema};let z=await(await $()).messages.create({model:G,max_tokens:H.maxTokens??b,...H.system?{system:H.system}:{},messages:H.messages.map((Q)=>({role:Q.role,content:Q.content})),...H.tools?.length?{tools:H.tools.map((Q)=>({name:Q.name,description:Q.description,input_schema:Q.parameters}))}:{},...Object.keys(W).length>0?{output_config:W}:{}}),X="",J=[];for(let Q of z.content)if(Q.type==="text")X+=Q.text;else if(Q.type==="tool_use")J.push({id:Q.id,name:Q.name,input:Q.input});return{text:X,toolCalls:J,json:y(X,H.jsonSchema!==void 0),stopReason:P(z.stop_reason),usage:{inputTokens:z.usage.input_tokens,outputTokens:z.usage.output_tokens,...z.usage.cache_read_input_tokens!=null?{cachedInputTokens:z.usage.cache_read_input_tokens}:{}},model:z.model}}}}function P(j){switch(j){case"end_turn":case"stop_sequence":return"end";case"tool_use":return"tool_use";case"max_tokens":return"max_tokens";case"refusal":return"refusal";default:return"other"}}function y(j,Z){if(!Z)return;try{return JSON.parse(j)}catch{throw new F("Model returned malformed JSON for a schema-constrained request","anthropic")}}var f=16000,A="https://generativelanguage.googleapis.com/v1beta";function U(j){let Z=(j.baseUrl??A).replace(/\/+$/,"");return{name:"google",async complete($,H){let G={contents:$.messages.map((Y)=>({role:Y.role==="assistant"?"model":"user",parts:[{text:Y.content}]})),generationConfig:{maxOutputTokens:$.maxTokens??f,...$.jsonSchema?{responseMimeType:"application/json",responseSchema:$.jsonSchema}:{}}};if($.system)G.systemInstruction={parts:[{text:$.system}]};if($.tools?.length)G.tools=[{functionDeclarations:$.tools.map((Y)=>({name:Y.name,description:Y.description,parameters:Y.parameters}))}];let W=await N(`${Z}/models/${encodeURIComponent(H)}:generateContent`,{method:"POST",headers:{"x-goog-api-key":j.apiKey,"Content-Type":"application/json"},body:JSON.stringify(G)});if(!W.ok){let Y=await W.text().catch(()=>"");throw new F(`google request failed: ${W.status} ${W.statusText} ${K(Y.slice(0,500))}`.trim(),"google",W.status)}let z=await W.json(),X=z.candidates?.[0],J="",Q=[];for(let[Y,V]of(X?.content?.parts??[]).entries()){if(V.text)J+=V.text;if(V.functionCall?.name)Q.push({id:`${V.functionCall.name}-${Y}`,name:V.functionCall.name,input:V.functionCall.args??{}})}return{text:J,toolCalls:Q,json:$.jsonSchema?h(J):void 0,stopReason:E(X?.finishReason,Q.length>0),usage:{inputTokens:z.usageMetadata?.promptTokenCount??0,outputTokens:z.usageMetadata?.candidatesTokenCount??0,...z.usageMetadata?.cachedContentTokenCount!=null?{cachedInputTokens:z.usageMetadata.cachedContentTokenCount}:{}},model:z.modelVersion??H}}}}function E(j,Z){if(Z)return"tool_use";switch(j){case"STOP":return"end";case"MAX_TOKENS":return"max_tokens";case"SAFETY":case"PROHIBITED_CONTENT":case"BLOCKLIST":return"refusal";default:return"other"}}function h(j){try{return JSON.parse(j)}catch{throw new F("Model returned malformed JSON for a schema-constrained request","google")}}var g=16000,v="https://api.openai.com/v1",m="https://openrouter.ai/api/v1";function O(j){let Z=j.provider??"openai",$=(j.baseUrl??q(Z)).replace(/\/+$/,"");return{name:Z,async complete(H,G){let W=[];if(H.system)W.push({role:"system",content:H.system});for(let B of H.messages)W.push({role:B.role,content:B.content});let z={model:G,messages:W,max_completion_tokens:H.maxTokens??g};if(H.tools?.length)z.tools=H.tools.map((B)=>({type:"function",function:{name:B.name,description:B.description,parameters:B.parameters}}));if(H.jsonSchema)z.response_format={type:"json_schema",json_schema:{name:"response",schema:H.jsonSchema,strict:!0}};if(H.effort)z.reasoning_effort=H.effort;let X={Authorization:`Bearer ${j.apiKey}`,"Content-Type":"application/json"};if(Z==="openrouter")X["HTTP-Referer"]="https://github.com/stacksjs/buddy",X["X-Title"]="buddy";let J=await N(`${$}/chat/completions`,{method:"POST",headers:X,body:JSON.stringify(z)});if(!J.ok){let B=await J.text().catch(()=>"");throw new F(`${Z} request failed: ${J.status} ${J.statusText} ${K(B.slice(0,500))}`.trim(),Z,J.status)}let Q=await J.json(),Y=Q.choices?.[0],V=Y?.message?.content??"",I=(Y?.message?.tool_calls??[]).map((B)=>({id:B.id,name:B.function?.name??"",input:p(B.function?.arguments,Z)}));return{text:V,toolCalls:I,json:H.jsonSchema?d(V,Z):void 0,stopReason:c(Y?.finish_reason,I.length>0),usage:{inputTokens:Q.usage?.prompt_tokens??0,outputTokens:Q.usage?.completion_tokens??0,...Q.usage?.prompt_tokens_details?.cached_tokens!=null?{cachedInputTokens:Q.usage.prompt_tokens_details.cached_tokens}:{}},model:Q.model??G}}}}function q(j){return j==="openrouter"?m:v}function c(j,Z){if(Z||j==="tool_calls")return"tool_use";switch(j){case"stop":return"end";case"length":return"max_tokens";case"content_filter":return"refusal";default:return"other"}}function p(j,Z){if(!j)return{};try{return JSON.parse(j)}catch{throw new F("Model returned malformed JSON tool arguments",Z)}}function d(j,Z){try{return JSON.parse(j)}catch{throw new F("Model returned malformed JSON for a schema-constrained request",Z)}}import R from"process";function u(j,Z=R.env){let $=j.ai;if($?.enabled===!1)return null;let H=$?.provider?[$.provider]:D;for(let G of H){let W=i(G,$?.apiKeyEnv,Z);if(!W)continue;let{key:z,source:X}=W,J=a(G,$?.model);if(!J)continue;return{provider:G,model:J,apiKey:z,apiKeyEnv:X,...$?.baseUrl?{baseUrl:$.baseUrl}:{}}}return null}function Vj(j,Z=C()){let $=u(j);if(!$)return Z.debug("AI disabled: no provider configured with an available API key"),null;let H=n($),G=j.ai?.maxTokensPerRun,W=j.ai?.effort,z=0;return{provider:$.provider,model:$.model,get tokensUsed(){return z},async complete(X){if(G!==void 0&&z>=G)throw new S(z,G);let J=X.model?M(X.model):$.model;try{let Q=await H.complete({...X,effort:X.effort??W},J);return z+=Q.usage.outputTokens,Z.debug(`AI ${$.provider}/${Q.model}: ${Q.usage.inputTokens} in, ${Q.usage.outputTokens} out (${Q.stopReason})`),Q}catch(Q){if(Q instanceof S)throw Q;let Y=T(Q);throw Z.warn(`\u26A0\uFE0F AI request failed (${$.provider}): ${Y}`),Q instanceof F?Q:new F(Y,$.provider)}}}}function n(j){switch(j.provider){case"anthropic":return k({apiKey:j.apiKey,baseUrl:j.baseUrl});case"google":return U({apiKey:j.apiKey,baseUrl:j.baseUrl});case"openai":case"openrouter":case"openai-compatible":return O({apiKey:j.apiKey,baseUrl:j.baseUrl,provider:j.provider})}}function i(j,Z,$){let H=Z?[Z,...w[j]]:w[j];for(let G of H){let W=$[G];if(W&&W.trim().length>0)return{key:W.trim(),source:G}}return}function a(j,Z){let $=R.env.BUDDY_MODEL||Z;if($)return M($);return L[j]}
4
4
  export{x as Zb,w as _b,D as $b,M as ac,k as bc,U as cc,O as dc,u as ec,Vj as fc};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ge as N}from"./chunk-142zh7e5.js";import{Sf as E}from"./chunk-24xvskkf.js";import{Rh as v}from"./chunk-wzncz6j5.js";import U from"process";var x=60000;async function D(q,K,$){let G=Bun.spawn([q,...K],{cwd:$,stdout:"pipe",stderr:"pipe",env:{PATH:U.env.PATH??"",HOME:U.env.HOME??"",LANG:"C"}}),Q=setTimeout(()=>G.kill(),x);try{let[W,V,X]=await Promise.all([new Response(G.stdout).text(),new Response(G.stderr).text(),G.exited]);return{stdout:W,stderr:V,exitCode:X}}finally{clearTimeout(Q)}}function F(q){switch(String(q??"").toLowerCase()){case"error":case"fatal":case"2":return"major";case"warning":case"warn":case"1":return"minor";default:return"nit"}}function j(q){let K=q.search(/[[{]/);if(K===-1)return null;try{return JSON.parse(q.slice(K))}catch{return null}}function H(q,K){let $=K.endsWith("/")?K:`${K}/`;return q.startsWith($)?q.slice($.length):q.replace(/^\.\//,"")}async function B(q){try{return await Bun.spawn(["which",q],{stdout:"ignore",stderr:"ignore",env:{PATH:U.env.PATH??""}}).exited===0}catch{return!1}}var y=/^(.+?):(\d+):(\d+):\s*(.*?)\s*\[([\w-]+)\]$/,I={name:"actionlint",filePatterns:[".github/workflows/*.yml",".github/workflows/*.yaml"],async available(){return B("actionlint")},async run(q,K){let{stdout:$}=await D("actionlint",["-oneline","-no-color",...q],K),G=[];for(let Q of $.split(`
2
+ import{he as N}from"./chunk-tqwek43e.js";import{Tf as E}from"./chunk-rwzt9xvk.js";import{Wh as v}from"./chunk-rrm4x81p.js";import U from"process";var x=60000;async function D(q,K,$){let G=Bun.spawn([q,...K],{cwd:$,stdout:"pipe",stderr:"pipe",env:{PATH:U.env.PATH??"",HOME:U.env.HOME??"",LANG:"C"}}),Q=setTimeout(()=>G.kill(),x);try{let[W,V,X]=await Promise.all([new Response(G.stdout).text(),new Response(G.stderr).text(),G.exited]);return{stdout:W,stderr:V,exitCode:X}}finally{clearTimeout(Q)}}function F(q){switch(String(q??"").toLowerCase()){case"error":case"fatal":case"2":return"major";case"warning":case"warn":case"1":return"minor";default:return"nit"}}function j(q){let K=q.search(/[[{]/);if(K===-1)return null;try{return JSON.parse(q.slice(K))}catch{return null}}function H(q,K){let $=K.endsWith("/")?K:`${K}/`;return q.startsWith($)?q.slice($.length):q.replace(/^\.\//,"")}async function B(q){try{return await Bun.spawn(["which",q],{stdout:"ignore",stderr:"ignore",env:{PATH:U.env.PATH??""}}).exited===0}catch{return!1}}var y=/^(.+?):(\d+):(\d+):\s*(.*?)\s*\[([\w-]+)\]$/,I={name:"actionlint",filePatterns:[".github/workflows/*.yml",".github/workflows/*.yaml"],async available(){return B("actionlint")},async run(q,K){let{stdout:$}=await D("actionlint",["-oneline","-no-color",...q],K),G=[];for(let Q of $.split(`
3
3
  `)){let W=y.exec(Q.trim());if(!W)continue;let[,V,X,,Z,Y]=W;G.push({path:H(V,K),line:Number(X),severity:"major",category:"workflow",message:`${Z} (${Y})`,tool:"actionlint"})}return G}};function u(q){switch(q){case"error":return"major";case"warning":return"minor";default:return"nit"}}var O={name:"workflow-audit",filePatterns:[".github/workflows/*.yml",".github/workflows/*.yaml"],async available(){return!0},async run(q,K){if(q.length===0)return[];let $=await N(K),G=new Set(q);return $.findings.filter((Q)=>G.has(Q.file)).map((Q)=>({path:Q.file,line:Q.line??1,severity:u(Q.severity),category:Q.ruleId,message:Q.fix?`${Q.message}
4
4
 
5
5
  ${Q.fix}`:Q.message,tool:"workflow-audit"}))}};var _={name:"hadolint",filePatterns:["**/Dockerfile","**/Dockerfile.*","**/*.dockerfile","**/Containerfile"],async available(){return B("hadolint")},async run(q,K){let{stdout:$}=await D("hadolint",["--format","json","--no-fail",...q],K),G=j($);if(!Array.isArray(G))return[];return G.filter((Q)=>Q.level==="error"||Q.level==="warning").map((Q)=>({path:H(Q.file,K),line:Math.max(1,Q.line),severity:F(Q.level),category:"docker",message:`${Q.message} (${Q.code})`,tool:"hadolint"}))}};import{join as b}from"path";import h from"process";async function J(q,K){let $=j(q);if(!Array.isArray($))return[];let G=[];for(let Q of $)for(let W of Q.messages??[]){if(!W.line)continue;G.push({path:H(Q.filePath,K),line:W.line,severity:F(W.severity),category:"lint",message:W.ruleId?`${W.message} (${W.ruleId})`:W.message})}return G}function f(q,K){if(K<0||K>q.length)return null;let $=1;for(let G=0;G<K;G++)if(q[G]===`
@@ -10,4 +10,4 @@ ${Q}`.split(`
10
10
  `)W++;continue}if(V==="/"&&q[W+1]==="*"){W+=2;while(W<q.length&&!(q[W]==="*"&&q[W+1]==="/")){if(q[W]===`
11
11
  `)$+=`
12
12
  `;W++}W+=2;continue}$+=V,W++}return $}var qq=[L,O,T,k,I,w,_,A];async function vq(q){let K=q.logger??v(),$=q.analyzers??qq,G=[],Q=[],W=[];for(let V of $){if(q.enabled?.[V.name]===!1)continue;let X=E(V.filePatterns),Z=q.files.filter((Y)=>X.matches(Y));if(Z.length===0)continue;if(!await V.available(q.root)){W.push({name:V.name,reason:"tool not available on this runner"}),K.debug(`\u23ED\uFE0F Skipping ${V.name}: not available`);continue}try{let Y=await V.run(Z,q.root);G.push(...Y),Q.push({name:V.name,findings:Y.length}),K.debug(`\uD83D\uDD0E ${V.name}: ${Y.length} finding(s) over ${Z.length} file(s)`)}catch(Y){W.push({name:V.name,reason:Y instanceof Error?Y.message:String(Y)}),K.warn(`\u26A0\uFE0F ${V.name} failed: ${Y}`)}}return{findings:G,ran:Q,skipped:W}}
13
- export{x as Od,D as Pd,F as Qd,j as Rd,H as Sd,B as Td,I as Ud,O as Vd,_ as Wd,f as Xd,P as Yd,R as Zd,k as _d,A as $d,a as ae,L as be,w as ce,T as de,qq as ee,vq as fe};
13
+ export{x as Pd,D as Qd,F as Rd,j as Sd,H as Td,B as Ud,I as Vd,O as Wd,_ as Xd,f as Yd,P as Zd,R as _d,k as $d,A as ae,a as be,L as ce,w as de,T as ee,qq as fe,vq as ge};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var j=Object.create;var{getPrototypeOf:k,defineProperty:i,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,q=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?j(k(a)):{};let c=b||!a||!a.__esModule?i(d,"default",{value:a,enumerable:!0}):d;for(let e of l(a))if(!m.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0});if(f)g.set(a,c);return c};var r=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var s=import.meta.require;
3
- export{q as el,r as fl,s as gl};
3
+ export{q as jl,r as kl,s as ll};