@buddysh/buddy 0.11.0 → 0.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +121 -0
- package/README.md +54 -43
- package/bin/cli.ts +282 -135
- package/dist/bin/cli.d.ts +5 -1
- package/dist/bin/cli.js +84 -91
- package/dist/chunk-05me15qw.js +2 -0
- package/dist/{chunk-bxfc4g2x.js → chunk-08x5b93v.js} +2 -13
- package/dist/chunk-0eg3kxb5.js +5 -0
- package/dist/chunk-0hc97k0t.js +44 -0
- package/dist/chunk-0paakbpj.js +2 -0
- package/dist/{chunk-hfvezfxh.js → chunk-0scz1dv5.js} +1 -1
- package/dist/{chunk-sp818c27.js → chunk-0w695m54.js} +5 -5
- package/dist/{chunk-vyapg8ca.js → chunk-11hdrnf6.js} +3 -3
- package/dist/{chunk-1stt2whn.js → chunk-15r904nz.js} +2 -2
- package/dist/{chunk-5k40mwd4.js → chunk-193abzy6.js} +1 -1
- package/dist/chunk-19zyq15p.js +2 -0
- package/dist/chunk-1c4690h9.js +79 -0
- package/dist/{chunk-q9n79dd3.js → chunk-1cpdz49v.js} +1 -1
- package/dist/{chunk-thaxgm5p.js → chunk-1qgr52wx.js} +1 -1
- package/dist/chunk-24c2ab29.js +2 -0
- package/dist/chunk-25sz1y7j.js +16 -0
- package/dist/chunk-2et8yavs.js +3 -0
- package/dist/chunk-2wj5xtdn.js +2 -0
- package/dist/{chunk-7mgec8kb.js → chunk-3901s7h9.js} +1 -1
- package/dist/{chunk-xvptf9jy.js → chunk-3cvng2nz.js} +2 -2
- package/dist/chunk-3fzbvs2p.js +2 -0
- package/dist/chunk-3pqra420.js +2 -0
- package/dist/{chunk-yk23nc4t.js → chunk-40znfg3x.js} +1 -1
- package/dist/chunk-428c5652.js +2 -0
- package/dist/chunk-49znmbh8.js +2 -0
- package/dist/chunk-5044y9en.js +5 -0
- package/dist/chunk-5yfaptmp.js +7 -0
- package/dist/{chunk-h7hs95wn.js → chunk-61xecp1z.js} +2 -2
- package/dist/{chunk-x0ya2r4r.js → chunk-657nbbp7.js} +2 -2
- package/dist/chunk-68fw3ma0.js +2 -0
- package/dist/{chunk-9h04nskh.js → chunk-69qyr9ef.js} +1 -1
- package/dist/chunk-6bd8ghkz.js +27 -0
- package/dist/{chunk-vh504tcv.js → chunk-6p4qz8qv.js} +2 -2
- package/dist/chunk-847g7jde.js +2 -0
- package/dist/{chunk-r3zyw8x0.js → chunk-8fw0v7bv.js} +2 -2
- package/dist/chunk-8hjvthz4.js +92 -0
- package/dist/chunk-90zmqn5k.js +2 -0
- package/dist/{chunk-3zdcekfj.js → chunk-929h6hhp.js} +2 -2
- package/dist/chunk-96ht6hwd.js +4 -0
- package/dist/chunk-97qf7mdt.js +2 -0
- package/dist/chunk-a4hzzn28.js +2 -0
- package/dist/chunk-aa277p5r.js +2 -0
- package/dist/chunk-b357cgb0.js +2 -0
- package/dist/chunk-b9escac0.js +4 -0
- package/dist/{chunk-56q4pwb5.js → chunk-be629jhq.js} +2 -2
- package/dist/chunk-bffxf4xy.js +2 -0
- package/dist/chunk-brfyymhf.js +2 -0
- package/dist/{chunk-zs3jaj0g.js → chunk-bymwaezh.js} +165 -119
- package/dist/chunk-c3es7pgf.js +2 -0
- package/dist/{chunk-9750tenz.js → chunk-c8rzx3a1.js} +1 -1
- package/dist/{chunk-tzs22es2.js → chunk-cgvt98pd.js} +1 -1
- package/dist/chunk-cwfkm7h9.js +3 -0
- package/dist/chunk-cwqhxqv7.js +2 -0
- package/dist/chunk-dgfb8k0h.js +2 -0
- package/dist/chunk-dqbk3kcj.js +104 -0
- package/dist/chunk-ds4stft2.js +2 -0
- package/dist/{chunk-1h3ey7k5.js → chunk-e68nf7cm.js} +1 -1
- package/dist/chunk-emyvrx5t.js +2 -0
- package/dist/{chunk-16yqbccr.js → chunk-eseshkd0.js} +1 -1
- package/dist/chunk-f53y8ans.js +3 -0
- package/dist/chunk-fjp3a7hp.js +26 -0
- package/dist/chunk-fpnjpgrb.js +2 -0
- package/dist/chunk-fr5c326k.js +2 -0
- package/dist/chunk-g24hav8e.js +370 -0
- package/dist/{chunk-6md7qf2g.js → chunk-g30dr44w.js} +2 -2
- package/dist/chunk-gkpd5nw2.js +2 -0
- package/dist/chunk-hbhmns7s.js +2 -0
- package/dist/chunk-hd5j9e3c.js +2 -0
- package/dist/{chunk-akffynkc.js → chunk-hfjywbbc.js} +1 -1
- package/dist/chunk-hmskwy76.js +2 -0
- package/dist/chunk-hns85dqw.js +2 -0
- package/dist/{chunk-wtjhehz9.js → chunk-hptfq3rg.js} +1 -1
- package/dist/{chunk-54sc18p8.js → chunk-hsa07n7c.js} +1 -1
- package/dist/chunk-hwxmhkxp.js +2 -0
- package/dist/{chunk-52x8mvh4.js → chunk-jnb80k2x.js} +2 -2
- package/dist/chunk-jtxcr5yw.js +4 -0
- package/dist/{chunk-tn8prpny.js → chunk-k26wnmzk.js} +7 -7
- package/dist/{chunk-2bp7tqca.js → chunk-kprtsn8c.js} +1 -1
- package/dist/chunk-m4p7cnvk.js +2 -0
- package/dist/chunk-mcwxpdg9.js +2 -0
- package/dist/chunk-mkzmjg3f.js +4 -0
- package/dist/chunk-ncrq3fvv.js +2 -0
- package/dist/chunk-ng7px8gx.js +2 -0
- package/dist/{chunk-vagxqhef.js → chunk-nrr8z2z7.js} +2 -2
- package/dist/{chunk-g0w8n555.js → chunk-p6qbqsyp.js} +2 -2
- package/dist/chunk-p8tmms5h.js +3 -0
- package/dist/{chunk-hw70wbzg.js → chunk-phfmnnne.js} +2 -2
- package/dist/{chunk-tb5y0350.js → chunk-pkr6905p.js} +1 -1
- package/dist/chunk-ppmabn5h.js +2 -0
- package/dist/chunk-pskqrv5r.js +2 -0
- package/dist/{chunk-4xsq18p3.js → chunk-q2tjkhez.js} +1 -1
- package/dist/{chunk-6g1y9yqh.js → chunk-q4t568hv.js} +1 -1
- package/dist/chunk-qd2s51gc.js +2 -0
- package/dist/chunk-r763e19p.js +6 -0
- package/dist/{chunk-74pxb991.js → chunk-rc2mk5x6.js} +2 -2
- package/dist/{chunk-zb62jhwm.js → chunk-s4zb0fcj.js} +13 -9
- package/dist/chunk-s6z3gm2s.js +5 -0
- package/dist/chunk-sc7emb71.js +2 -0
- package/dist/chunk-sw2538r0.js +49 -0
- package/dist/chunk-t25apff9.js +2 -0
- package/dist/{chunk-p4zwy518.js → chunk-tjc2vgwn.js} +2 -2
- package/dist/{chunk-gngwjf70.js → chunk-tw047td6.js} +2 -2
- package/dist/chunk-tws3npt7.js +38 -0
- package/dist/{chunk-6d9hmjt8.js → chunk-txtrpypt.js} +2 -2
- package/dist/chunk-v1wfa758.js +2 -0
- package/dist/{chunk-dfesffnr.js → chunk-vckhctmr.js} +1 -1
- package/dist/chunk-vdd1cghr.js +2 -0
- package/dist/{chunk-fvpr07dn.js → chunk-vgtmrd4c.js} +1 -1
- package/dist/chunk-vj1sdxpp.js +2 -0
- package/dist/{chunk-fm8ckj9b.js → chunk-vqa6vte3.js} +1 -1
- package/dist/{chunk-82dv4p13.js → chunk-wn6pbyzn.js} +1 -1
- package/dist/chunk-x23a6szw.js +2 -0
- package/dist/{chunk-xqx460y2.js → chunk-xs12dtf1.js} +1 -1
- package/dist/chunk-xznnmhyt.js +2 -0
- package/dist/chunk-y3dd8v85.js +2 -0
- package/dist/chunk-yk183r6z.js +2 -0
- package/dist/{chunk-1c1gznm9.js → chunk-yngahb11.js} +2 -2
- package/dist/{chunk-qyf90zz3.js → chunk-yp1tgdh3.js} +1 -1
- package/dist/chunk-ys1qqcpp.js +2 -0
- package/dist/{chunk-8rc6042h.js → chunk-ytmxd5fk.js} +2 -2
- package/dist/chunk-zgkrhymn.js +2 -0
- package/dist/chunk-zxgkp71x.js +2 -0
- package/dist/src/agent/index.d.ts +6 -1
- package/dist/src/agent/modes.d.ts +0 -8
- package/dist/src/agent/plan.d.ts +28 -0
- package/dist/src/agent/tasks.d.ts +20 -0
- package/dist/src/agent/tools/issue.d.ts +19 -0
- package/dist/src/ci/attempts.d.ts +36 -0
- package/dist/src/ci/base.d.ts +55 -0
- package/dist/src/ci/fix.d.ts +27 -18
- package/dist/src/ci/index.d.ts +5 -1
- package/dist/src/ci/run.d.ts +28 -0
- package/dist/src/commands/handlers.d.ts +3 -0
- package/dist/src/dashboard/dashboard-generator.d.ts +4 -0
- package/dist/src/events/index.d.ts +12 -0
- package/dist/src/gates/checks.d.ts +10 -0
- package/dist/src/gates/index.d.ts +1 -0
- package/dist/src/gates/post-merge.d.ts +13 -1
- package/dist/src/git/github-provider.d.ts +5 -1
- package/dist/src/git/gitlab-provider.d.ts +5 -1
- package/dist/src/git/provider.d.ts +40 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +1 -1
- package/dist/src/registry/registry-client.d.ts +1 -1
- package/dist/src/reports/index.d.ts +1 -0
- package/dist/src/reports/publish-gate.d.ts +22 -0
- package/dist/src/review/filters.d.ts +36 -0
- package/dist/src/review/index.d.ts +4 -1
- package/dist/src/review/marker.d.ts +18 -0
- package/dist/src/review/poster.d.ts +11 -1
- package/dist/src/review/resolve.d.ts +20 -0
- package/dist/src/review/run.d.ts +35 -0
- package/dist/src/rules/engine.d.ts +19 -0
- package/dist/src/scanner/package-json-extras.d.ts +34 -1
- package/dist/src/setup.d.ts +49 -17
- package/dist/src/setup.js +1 -1
- package/dist/src/templates/github-actions.d.ts +2 -0
- package/dist/src/types.d.ts +4 -1
- package/dist/src/upgrades/migrate.d.ts +3 -0
- package/dist/src/upgrades/report.d.ts +1 -0
- package/dist/src/utils/dockerfile-parser.d.ts +2 -2
- package/dist/src/utils/helpers.d.ts +10 -1
- package/dist/src/version/version-resolver.d.ts +1 -0
- package/package.json +12 -10
- package/dist/chunk-0j7z87kh.js +0 -3
- package/dist/chunk-0r8zt3d7.js +0 -2
- package/dist/chunk-1a53wj0h.js +0 -1
- package/dist/chunk-1wjnd24b.js +0 -24
- package/dist/chunk-1xe07hzm.js +0 -2
- package/dist/chunk-2dbkpfy9.js +0 -2
- package/dist/chunk-3q6czqs4.js +0 -6
- package/dist/chunk-49ey79p0.js +0 -5
- package/dist/chunk-4c9m61yd.js +0 -5
- package/dist/chunk-4efbxdjr.js +0 -4
- package/dist/chunk-4f7panqj.js +0 -21
- package/dist/chunk-4hd3rre0.js +0 -2
- package/dist/chunk-5c3qf34r.js +0 -2
- package/dist/chunk-5kt03hx5.js +0 -2
- package/dist/chunk-63ept76v.js +0 -2
- package/dist/chunk-65b3vq52.js +0 -2
- package/dist/chunk-6k653r8w.js +0 -2
- package/dist/chunk-6patq6bw.js +0 -2
- package/dist/chunk-6sgh49z1.js +0 -2
- package/dist/chunk-7tfrww3v.js +0 -2
- package/dist/chunk-7xk28xrv.js +0 -2
- package/dist/chunk-8661pvb8.js +0 -3
- package/dist/chunk-887s0w81.js +0 -2
- package/dist/chunk-978wtejw.js +0 -44
- package/dist/chunk-9eqpaxfz.js +0 -2
- package/dist/chunk-9p1xkmjy.js +0 -2
- package/dist/chunk-agdesgzv.js +0 -2
- package/dist/chunk-ar01x04a.js +0 -2
- package/dist/chunk-ay43f085.js +0 -2
- package/dist/chunk-bk9bqd5j.js +0 -2
- package/dist/chunk-bm8d40j0.js +0 -69
- package/dist/chunk-c3fczawt.js +0 -2
- package/dist/chunk-c9r9nd4t.js +0 -1
- package/dist/chunk-ctsz0ynx.js +0 -3
- package/dist/chunk-czremqk7.js +0 -2
- package/dist/chunk-da3wbh04.js +0 -2
- package/dist/chunk-dat582cg.js +0 -2
- package/dist/chunk-djntbp7a.js +0 -105
- package/dist/chunk-eagjp0dh.js +0 -3
- package/dist/chunk-eht72nnj.js +0 -2
- package/dist/chunk-f4nv5x3z.js +0 -2
- package/dist/chunk-fdfk918n.js +0 -2
- package/dist/chunk-fdj0tewy.js +0 -20
- package/dist/chunk-fqj7e6xa.js +0 -2
- package/dist/chunk-frm8zz31.js +0 -2
- package/dist/chunk-g0nv8psv.js +0 -2
- package/dist/chunk-gkmvxjbe.js +0 -2
- package/dist/chunk-j8asz4hb.js +0 -15
- package/dist/chunk-k62w2v03.js +0 -2
- package/dist/chunk-mcrfxphm.js +0 -5
- package/dist/chunk-mh3x7j6h.js +0 -2
- package/dist/chunk-naq32yx3.js +0 -86
- package/dist/chunk-nsmcjkas.js +0 -2
- package/dist/chunk-p1xm1jvz.js +0 -2
- package/dist/chunk-p3wsm8kz.js +0 -2
- package/dist/chunk-p7zgy37f.js +0 -2
- package/dist/chunk-ph1b3vbp.js +0 -315
- package/dist/chunk-pkjm2r0a.js +0 -2
- package/dist/chunk-pkkwb0n0.js +0 -4
- package/dist/chunk-pnpx1kqn.js +0 -6
- package/dist/chunk-qpz9k66h.js +0 -2
- package/dist/chunk-qvn1rtgp.js +0 -2
- package/dist/chunk-r06ce5g6.js +0 -2
- package/dist/chunk-r2sbprdb.js +0 -49
- package/dist/chunk-rqdep14r.js +0 -2
- package/dist/chunk-s1km8cyq.js +0 -2
- package/dist/chunk-s4ms8zag.js +0 -2
- package/dist/chunk-ts35hc5t.js +0 -3
- package/dist/chunk-vkctfqpm.js +0 -3
- package/dist/chunk-wdwvt7gb.js +0 -43
- package/dist/chunk-x3kragh9.js +0 -12
- package/dist/chunk-x9ctz1qc.js +0 -1
- package/dist/chunk-xakpdqaq.js +0 -3
- package/dist/chunk-yncea6ty.js +0 -2
- package/dist/chunk-yq0gxtzv.js +0 -2
- package/dist/chunk-yqhs08ky.js +0 -2
- package/dist/chunk-zve5d96e.js +0 -2
package/dist/chunk-djntbp7a.js
DELETED
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$c as J0,Zc as O0,_c as l0,ad as q0}from"./chunk-1c1gznm9.js";import{bd as o0}from"./chunk-hw70wbzg.js";import{dd as C0,ed as N0,fd as x0,gd as c0}from"./chunk-3q6czqs4.js";import{hd as _0,id as z0,jd as f0}from"./chunk-vyapg8ca.js";import{Od as r,Pd as u}from"./chunk-ts35hc5t.js";import{$d as u0}from"./chunk-56q4pwb5.js";import{Ve as H0,We as m0,Xe as j0}from"./chunk-978wtejw.js";import{ni as g0}from"./chunk-naq32yx3.js";import{Ji as B0}from"./chunk-tzs22es2.js";import{Vi as m,Zi as h0,_i as y0}from"./chunk-7mgec8kb.js";import{Bj as Y0}from"./chunk-5k40mwd4.js";import{Lj as l}from"./chunk-1h3ey7k5.js";import{Nj as b0,Oj as P0,Pj as k0,Qj as v0,Rj as S0}from"./chunk-akffynkc.js";import{Fk as A}from"./chunk-6g1y9yqh.js";import J1 from"fs";import{join as R0}from"path";import c from"process";var p0={critical:"\uD83D\uDD34 Critical",high:"\uD83D\uDFE0 High",moderate:"\uD83D\uDFE1 Moderate",low:"\u26AA Low"};class $0{generateDashboard($,X={}){let{showOpenPRs:Q=!0,showDetectedDependencies:K=!0,showDeprecatedDependencies:Y=!0,showVulnerableDependencies:W=!0,bodyTemplate:Z}=X,_="Dependency Dashboard";if(Z)return{title:"Dependency Dashboard",body:this.applyTemplate(Z,$)};let O=this.generateDefaultHeader($);if(W&&$.vulnerableDependencies&&$.vulnerableDependencies.length>0)O+=this.generateVulnerableDependenciesSection($.vulnerableDependencies);if(Y&&$.deprecatedDependencies&&$.deprecatedDependencies.length>0)O+=this.generateDeprecatedDependenciesSection($.deprecatedDependencies);if(Q&&$.openPRs.length>0)O+=this.generateOpenPRsSection($.openPRs);if($.cappedDependencies&&$.cappedDependencies.length>0)O+=this.generateCappedDependenciesSection($.cappedDependencies);if(K)O+=this.generateDetectedDependenciesSection($.detectedDependencies);return O+=this.generateFooter(),{title:"Dependency Dashboard",body:O}}generateDefaultHeader($){return`This issue lists Buddy updates and detected dependencies. Read the [Dependency Dashboard](https://buddy.sh/features/dependency-dashboard) docs to learn more.
|
|
3
|
-
|
|
4
|
-
`}sanitizeReferences($){return $.replace(/(?<![`\w])#(\d+)(?!\d)/g,"`#$1`")}toRelativePrUrl($,X){try{let Q=new URL($);if(Q.hostname!=="github.com")return null;let K=Q.pathname.match(/^\/[^/]+\/[^/]+\/pull\/(\d+)$/);if(!K||Number(K[1])!==X)return null;return`../pull/${X}`}catch{return null}}generateCappedDependenciesSection($){let X=`## Capped dependencies
|
|
5
|
-
|
|
6
|
-
The following packages are held below their latest version by a range declared elsewhere in the dependency tree. Updating this repository cannot move them \u2014 the constraint has to be widened where it is declared.
|
|
7
|
-
|
|
8
|
-
| Package | Installed | Reachable | Latest | Capped by |
|
|
9
|
-
|---|---|---|---|---|
|
|
10
|
-
`;for(let Q of $){let K=Q.capping.map((Y)=>`\`${this.sanitizeReferences(Y.by)}\` (\`${Y.range}\`)`).join(", ");X+=`| \`${this.sanitizeReferences(Q.name)}\` | \`${Q.installed}\` | \`${Q.reachable}\` | \`${Q.latest}\` | ${K} |
|
|
11
|
-
`}return`${X}
|
|
12
|
-
`}generateOpenPRsSection($){let X=`## Open
|
|
13
|
-
|
|
14
|
-
The following updates have all been created. To force a retry/rebase of any, click on a checkbox below.
|
|
15
|
-
|
|
16
|
-
`;for(let Q of $){let K=this.extractPackageInfo(Q),Y=Q.head.replace(/[<>\s]|-->/g,""),W=this.toRelativePrUrl(Q.url,Q.number)??Q.url,Z=this.sanitizeReferences(Q.title);if(X+=` - [ ] <!-- rebase-branch=${Y} -->[${Z}](${W})`,K.length>0)X+=` (\`${K.join("`, `")}\`)`;X+=`
|
|
17
|
-
`}return X+=` - [ ] <!-- rebase-all-open-prs -->**Click on this checkbox to rebase all open PRs at once**
|
|
18
|
-
`,X+=`
|
|
19
|
-
`,X}generateDetectedDependenciesSection($){let X=`## Detected dependencies
|
|
20
|
-
|
|
21
|
-
`;if($.packageJson.length>0)X+=this.generatePackageJsonSection($.packageJson);let Q=$.dependencyFiles.filter((Z)=>Z.path==="composer.json"||Z.path.endsWith("/composer.json")),K=Q.filter((Z)=>Z.path==="composer.json"),Y=Q.filter((Z)=>Z.path!=="composer.json");if(K.length>0)X+=this.generateComposerSection(K);if($.githubActions.length>0)X+=this.generateGitHubActionsSection($.githubActions);let W=$.dependencyFiles.filter((Z)=>!Z.path.endsWith("/composer.json")&&Z.path!=="composer.json");if(W.length>0||Y.length>0)X+=this.generateDependencyFilesSection([...W,...Y]);return X}generatePackageJsonSection($){let X=`<details><summary>npm</summary>
|
|
22
|
-
<blockquote>
|
|
23
|
-
|
|
24
|
-
`;for(let Q of $){let K=Q.path.split("/").pop()||Q.path;X+=`<details><summary>${K}</summary>
|
|
25
|
-
|
|
26
|
-
`;let Y={dependencies:Q.dependencies.filter((W)=>W.type==="dependencies"),devDependencies:Q.dependencies.filter((W)=>W.type==="devDependencies"),peerDependencies:Q.dependencies.filter((W)=>W.type==="peerDependencies"),optionalDependencies:Q.dependencies.filter((W)=>W.type==="optionalDependencies")};for(let[W,Z]of Object.entries(Y))if(Z.length>0)for(let _ of Z)X+=` - \`${_.name} ${_.currentVersion}\`
|
|
27
|
-
`;X+=`
|
|
28
|
-
</details>
|
|
29
|
-
|
|
30
|
-
`}return X+=`</blockquote>
|
|
31
|
-
</details>
|
|
32
|
-
|
|
33
|
-
`,X}generateGitHubActionsSection($){let X=`<details><summary>github-actions</summary>
|
|
34
|
-
<blockquote>
|
|
35
|
-
|
|
36
|
-
`;for(let Q of $){X+=`<details><summary>${Q.path}</summary>
|
|
37
|
-
|
|
38
|
-
`;let K=new Map;for(let Y of Q.dependencies){let W=`${Y.name}@${Y.currentVersion}`;if(!K.has(W))K.set(W,{name:Y.name,currentVersion:Y.currentVersion})}for(let Y of K.values())X+=` - \`${Y.name} ${Y.currentVersion}\`
|
|
39
|
-
`;X+=`
|
|
40
|
-
</details>
|
|
41
|
-
|
|
42
|
-
`}return X+=`</blockquote>
|
|
43
|
-
</details>
|
|
44
|
-
|
|
45
|
-
`,X}generateDependencyFilesSection($){let X=`<details><summary>dependency-files</summary>
|
|
46
|
-
<blockquote>
|
|
47
|
-
|
|
48
|
-
`;for(let Q of $){X+=`<details><summary>${Q.path}</summary>
|
|
49
|
-
|
|
50
|
-
`;for(let K of Q.dependencies)X+=` - \`${K.name} ${K.currentVersion}\`
|
|
51
|
-
`;X+=`
|
|
52
|
-
</details>
|
|
53
|
-
|
|
54
|
-
`}return X+=`</blockquote>
|
|
55
|
-
</details>
|
|
56
|
-
|
|
57
|
-
`,X}generateComposerSection($){let X=`<details><summary>composer</summary>
|
|
58
|
-
<blockquote>
|
|
59
|
-
|
|
60
|
-
`;for(let Q of $){let K=Q.path.split("/").pop()||Q.path;X+=`<details><summary>${K}</summary>
|
|
61
|
-
|
|
62
|
-
`;let Y={require:Q.dependencies.filter((W)=>W.type==="require"),"require-dev":Q.dependencies.filter((W)=>W.type==="require-dev")};for(let[W,Z]of Object.entries(Y))if(Z.length>0)for(let _ of Z)X+=` - \`${_.name} ${_.currentVersion}\`
|
|
63
|
-
`;X+=`
|
|
64
|
-
</details>
|
|
65
|
-
|
|
66
|
-
`}return X+=`</blockquote>
|
|
67
|
-
</details>
|
|
68
|
-
|
|
69
|
-
`,X}generateVulnerableDependenciesSection($){let X=$.reduce((K,Y)=>K+Y.advisories.length,0),Q=`> [!CAUTION]
|
|
70
|
-
> ${X} known ${X===1?"vulnerability affects":"vulnerabilities affect"} ${$.length} ${$.length===1?"dependency":"dependencies"} in this repository.
|
|
71
|
-
|
|
72
|
-
| Severity | Package | Current | Advisory | Fixed in |
|
|
73
|
-
|----------|---------|---------|----------|----------|
|
|
74
|
-
`;for(let K of $)for(let Y of K.advisories){let W=p0[Y.severity]??Y.severity,Z=Y.url?`[${Y.id}](${Y.url})`:Y.id;Q+=`| ${W} | \`${K.name}\` | \`${K.currentVersion}\` | ${Z} | \`${Y.fixedVersion??"n/a"}\` |
|
|
75
|
-
`}return Q+=`
|
|
76
|
-
`,Q}generateDeprecatedDependenciesSection($){let X=`> [!WARNING]
|
|
77
|
-
> These dependencies are deprecated and should be updated to avoid potential security risks and compatibility issues.
|
|
78
|
-
|
|
79
|
-
| Datasource | Name | Replacement PR? |
|
|
80
|
-
|------------|------|-----------------|
|
|
81
|
-
`;for(let Q of $){let K=`\`${Q.name}\``,W=(Q.replacementAvailable?"available":"unavailable")==="available"?"":"";X+=`| ${Q.datasource} | ${K} | ${W} |
|
|
82
|
-
`}return X+=`
|
|
83
|
-
`,X}generateFooter(){return`---
|
|
84
|
-
|
|
85
|
-
- [ ] <!-- manual job -->Check this box to trigger a request for Buddy to run again on this repository
|
|
86
|
-
`}extractPackageInfo($){let X=[],Q=[/update.*?dependency\s+(\S+)/i,/update\s+require(?:-dev)?\s+(\S+)\s+to\s+v?\d+/i,/update\s+(\S+)\s+to\s+v?\d+/i,/bump\s+(\S+)\s+from/i,/chore\(deps\):\s*update\s+dependency\s+(\S+)/i];for(let Y of Q){let W=$.title.match(Y);if(W&&W[1]&&!X.includes(W[1]))X.push(W[1])}let K=[{name:"npm",pattern:/### npm Dependencies[\s\S]*?(?=###|\n\n---|z)/i},{name:"pkgx",pattern:/### Launchpad\/pkgx Dependencies[\s\S]*?(?=###|\n\n---|z)/i},{name:"actions",pattern:/### GitHub Actions[\s\S]*?(?=###|\n\n---|z)/i}];for(let Y of K){let W=$.body.match(Y.pattern);if(W){let _=W[0].match(/\|\s*\[([^\]]+)\]\([^)]+\)\s*\|/g);if(_)for(let O of _){let J=O.match(/\|\s*\[([^\]]+)\]/);if(J&&J[1]){let H=J[1].trim();if(H.includes("`")&&H.includes("->")){let j=O.match(/\]\(([^)]+)\)/);if(j&&j[1]){let q=j[1].match(/\/diffs\/npm\/([^/]+)\//);if(q&&q[1]){let B=decodeURIComponent(q[1]);if(B&&B.length>1&&!X.includes(B))X.push(B)}}continue}if(!H.includes("://")&&!H.includes("Compare Source")&&!H.includes("badge")&&!H.includes("!")&&!H.startsWith("[![")&&!H.includes("`")&&!H.includes("->")&&!H.includes(" -> ")&&!H.match(/^\d+\.\d+/)&&!H.includes(" ")&&H.length>0&&!X.includes(H))X.push(H)}}}}if(X.length<3){let Y=$.body.match(/`([^`]+)`/g);if(Y)for(let W of Y){let Z=W.replace(/`/g,"").trim();if(Z.includes("->")||Z.includes(" -> ")||Z.includes("` -> `")||Z.match(/^\d+\.\d+/)||Z.match(/^v\d+/)||Z.match(/[\d.]+\s*->\s*[\d.]+/)||Z.match(/^[\d.]+$/)||Z.match(/^\d+\.\d+\.\d+/)||Z.match(/^\d+\.\d+\.\d+\./)||Z.match(/^\^?\d+\.\d+/)||Z.match(/^~\d+\.\d+/)||Z.includes("://")||Z.includes("Compare Source")||Z.includes("badge")||Z.includes(" "))continue;if(Z=Z.split(",")[0].trim(),Z&&Z.length>1&&!X.includes(Z)&&(Z.startsWith("@")||Z.includes("/")||Z.match(/^[a-z][a-z0-9.-]*$/i)))X.push(Z)}}return X}applyTemplate($,X){return $.replace(/\{\{repository\.owner\}\}/g,X.repository.owner).replace(/\{\{repository\.name\}\}/g,X.repository.name).replace(/\{\{openPRs\.count\}\}/g,X.openPRs.length.toString()).replace(/\{\{lastUpdated\}\}/g,X.lastUpdated.toISOString()).replace(/\{\{detectedDependencies\.packageJson\.count\}\}/g,X.detectedDependencies.packageJson.length.toString()).replace(/\{\{detectedDependencies\.githubActions\.count\}\}/g,X.detectedDependencies.githubActions.length.toString()).replace(/\{\{detectedDependencies\.dependencyFiles\.count\}\}/g,X.detectedDependencies.dependencyFiles.length.toString())}}var i0="buddy/",s0="no-auto-merge";function g($){let X=$.pullRequest?.autoMerge;return{enabled:X?.enabled??!1,strategy:X?.strategy??"squash",conditions:X?.conditions??[],requireGreenCI:X?.requireGreenCI??!0,optOutLabel:X?.optOutLabel??s0,securityLabel:$.security?.label??"security"}}function D0($,X,Q){let K=g(X);if(!K.enabled)return{eligible:!1,reason:"auto-merge is disabled by config"};if(K.conditions.length===0)return{eligible:!1,reason:"no auto-merge conditions configured (set conditions to at least one of patch-only, minor-only, security-only, all)"};if(!$.head.startsWith(i0))return{eligible:!1,reason:`PR #${$.number} is not a buddy PR (branch: ${$.head})`};if($.draft)return{eligible:!1,reason:`PR #${$.number} is a draft`};let Y=$.labels??[];if(Y.includes(K.optOutLabel))return{eligible:!1,reason:`PR #${$.number} carries the ${K.optOutLabel} label`};if(K.requireGreenCI&&Q===!1)return{eligible:!1,reason:`PR #${$.number} has failing or pending checks`};let W=m($.body);if(!W)return{eligible:!1,reason:`PR #${$.number} has no metadata manifest to verify update types against`};if(W.truncated)return{eligible:!1,reason:`PR #${$.number} has a truncated manifest, so its full update set cannot be verified`};return I0(W,Y,K)}function I0($,X,Q){for(let Y of Q.conditions)switch(Y){case"all":return{eligible:!0,reason:"all updates qualify (condition: all)"};case"patch-only":if($.updates.length>0&&$.updates.every((W)=>X0(W)==="patch"))return{eligible:!0,reason:"every update is a patch"};break;case"minor-only":if($.updates.length>0&&$.updates.every((W)=>X0(W)!=="major"))return{eligible:!0,reason:"every update is minor or patch"};break;case"security-only":if(X.includes(Q.securityLabel))return{eligible:!0,reason:"PR resolves a security advisory"};break}return{eligible:!1,reason:`update types (${[...new Set($.updates.map(X0))].join(", ")||"none"}) do not satisfy conditions (${Q.conditions.join(", ")})`}}function X0($){if($.type==="major"||$.type==="minor"||$.type==="patch")return $.type;let X=E0($.current),Q=E0($.target);if(!X||!Q)return"major";if(X[0]!==Q[0])return"major";if(X[1]!==Q[1])return"minor";return"patch"}function E0($){let X=$.trim().match(/(\d+)\.(\d+)\.(\d+)/);if(!X)return null;return[Number(X[1]),Number(X[2]),Number(X[3])]}function M0($,X,Q){let K=g(Q);if(!K.enabled)return{eligible:!1,reason:"auto-merge is disabled by config"};if(K.conditions.length===0)return{eligible:!1,reason:"no auto-merge conditions configured"};if(X.includes(K.optOutLabel))return{eligible:!1,reason:`PR carries the ${K.optOutLabel} label`};let Y={schemaVersion:1,updates:$.map((W)=>({name:W.name,current:W.currentVersion,target:W.newVersion,type:W.updateType,file:W.file}))};return I0(Y,X,K)}var A1=["scan.completed","pr.created","pr.updated","pr.closed","pr.merged","security.advisories","dashboard.updated","review.completed","fixci.completed","gate.failed","run.failed"];class Q0{logger;sinks=[];constructor($=S0()){this.logger=$}register($){this.sinks.push($)}get size(){return this.sinks.length}async emit($,X){let Q=this.sinks.filter((K)=>!K.events?.length||K.events.includes($));if(Q.length===0)return;await Promise.all(Q.map(async(K)=>{try{await K.deliver($,X),this.logger.debug(`\uD83D\uDCE3 Delivered ${$} to ${K.name}`)}catch(Y){this.logger.warn(`\u26A0\uFE0F Could not deliver ${$} to ${K.name}: ${Y}`)}}))}}function d($,X){switch($){case"scan.completed":{let Q=X;return`Found ${Q.total} update(s): ${Q.major} major, ${Q.minor} minor, ${Q.patch} patch`}case"pr.created":{let Q=X;return`Opened #${Q.number}: ${Q.title}`}case"pr.merged":{let Q=X;return`Merged #${Q.number}: ${Q.title}`}case"security.advisories":return`${X.packages.length} dependency/dependencies with known advisories`;case"run.failed":{let Q=X;return`\`${Q.command}\` failed: ${Q.error}`}default:return $}}import{createHmac as r0}from"crypto";import t0 from"process";var a0=1;function w0($){if(!$)return[];let X=[],Q=Z0($.slack?.webhookEnv??"SLACK_WEBHOOK_URL");if(Q)X.push(e0(Q,$.slack?.events));let K=Z0($.discord?.webhookEnv??"DISCORD_WEBHOOK_URL");if(K)X.push($1(K,$.discord?.events));for(let[Y,W]of($.webhooks??[]).entries())X.push(X1(W,Y));return X}function e0($,X){return{name:"slack",...X?.length?{events:X}:{},async deliver(Q,K){await K0($,{text:`Buddy: ${d(Q,K)}`,blocks:[{type:"section",text:{type:"mrkdwn",text:`*Buddy*
|
|
87
|
-
${d(Q,K)}`}}]})}}}function $1($,X){return{name:"discord",...X?.length?{events:X}:{},async deliver(Q,K){await K0($,{embeds:[{title:"Buddy",description:d(Q,K),color:Q==="security.advisories"||Q==="run.failed"?14687834:3061373,timestamp:new Date().toISOString()}]})}}}function X1($,X=0){let Q=$.secretEnv?Z0($.secretEnv):void 0;return{name:`webhook[${X}]`,...$.events?.length?{events:$.events}:{},async deliver(K,Y){let W=JSON.stringify({version:a0,event:K,payload:Y,sentAt:new Date().toISOString()}),Z={"Content-Type":"application/json"};if(Q)Z["x-buddy-signature"]=`sha256=${Q1(W,Q)}`;await K0($.url,W,Z)}}}function Q1($,X){return r0("sha256",X).update($).digest("hex")}async function K0($,X,Q={}){let K=await l($,{method:"POST",headers:{"Content-Type":"application/json",...Q},body:typeof X==="string"?X:JSON.stringify(X)});if(!K.ok){let Y=await K.text().catch(()=>"");throw Error(`${K.status} ${K.statusText} ${B0(Y.slice(0,200))}`.trim())}}function Z0($){let X=t0.env[$];return X?.trim()?X.trim():void 0}var T0="https://api.osv.dev",Z1=1000,p={low:0,moderate:1,high:2,critical:3};function W0($){switch($){case"dependencies":case"devDependencies":case"peerDependencies":case"optionalDependencies":return"npm";case"require":case"require-dev":return"Packagist";case"python":return"PyPI";case"rust":return"crates.io";case"go":return"Go";case"ruby":return"RubyGems";case"github-actions":return"GitHub Actions";default:return null}}function K1($){let X=$.database_specific?.severity?.toLowerCase();if(X==="low"||X==="moderate"||X==="high"||X==="critical")return X;if(X==="medium")return"moderate";let Q=$.severity?.find((K)=>K.type?.startsWith("CVSS"))?.score;if(Q){let K=W1(Q);if(K!==null){if(K>=9)return"critical";if(K>=7)return"high";if(K>=4)return"moderate";return"low"}}return"moderate"}function W1($){let X=Number($);if(Number.isFinite(X))return X;let Q=$.match(/\/([0-9](?:\.[0-9])?)$/);if(Q){let K=Number(Q[1]);return Number.isFinite(K)?K:null}return null}function Y1($,X){for(let Q of $.affected??[]){if(Q.package?.name!==X)continue;for(let K of Q.ranges??[])for(let Y of K.events??[])if(Y.fixed)return Y.fixed}return}class s{logger;concurrency;detailCache=new x0;constructor($,X=8){this.logger=$;this.concurrency=X}async findAdvisories($){let X=new Map;if($.length===0)return X;let Q=await this.queryBatch($),K=[...new Set([...Q.values()].flat())];if(K.length===0)return X;this.logger.debug(`Fetching details for ${K.length} advisory record(s)`);let Y=await C0(K,(Z)=>this.fetchVulnerability(Z),this.concurrency),W=new Map;for(let Z of Y)if(Z)W.set(Z.id,Z);for(let[Z,_]of Q){let O=Z.slice(Z.indexOf(":")+1,Z.lastIndexOf("@")),J=[];for(let H of _){let j=W.get(H);if(!j)continue;J.push({id:j.id,aliases:j.aliases??[],summary:j.summary??j.details?.split(`
|
|
88
|
-
`)[0]??"No summary provided",severity:K1(j),url:`https://osv.dev/vulnerability/${j.id}`,fixedVersion:Y1(j,O)})}if(J.length>0)J.sort((H,j)=>p[j.severity]-p[H.severity]),X.set(Z,J)}return X}async annotateUpdates($,X="low"){let Q=[],K=[];if($.forEach((_,O)=>{let J=W0(_.dependencyType);if(!J)return;let H=F0(_.currentVersion);if(!H)return;let j=J==="GitHub Actions"?H.replace(/^v/i,""):H;if(!j)return;Q.push({name:_.name,version:j,ecosystem:J}),K.push(O)}),Q.length===0)return $;let Y=await this.findAdvisories(Q),W=p[X],Z=0;if(Q.forEach((_,O)=>{let J=Y.get(i(_));if(!J?.length)return;let H=$[K[O]],j=J.filter((z)=>{if(p[z.severity]<W)return!1;if(!z.fixedVersion)return!1;return H1(F0(H.newVersion),z.fixedVersion)});if(j.length>0)H.securityAdvisories=j,Z++}),Z>0)this.logger.info(`\uD83D\uDD12 ${Z} update(s) resolve known security advisories`);return $}async queryBatch($){let X=new Map,Q=N0($,Z1);for(let K of Q)try{let Y=await l(`${T0}/v1/querybatch`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"buddy"},body:JSON.stringify({queries:K.map((Z)=>({package:{name:Z.name,ecosystem:Z.ecosystem},version:Z.version}))}),retryNonIdempotent:!0,onRetry:({delayMs:Z,reason:_})=>this.logger.debug(`OSV batch retry in ${Math.round(Z/1000)}s (${_})`)});if(!Y.ok){this.logger.warn(`OSV advisory lookup failed: HTTP ${Y.status}`);continue}(await Y.json()).results?.forEach((Z,_)=>{let O=Z.vulns?.map((J)=>J.id)??[];if(O.length>0)X.set(i(K[_]),O)})}catch(Y){this.logger.warn("OSV advisory lookup failed:",Y)}return X}async fetchVulnerability($){return this.detailCache.get($,async()=>{try{let X=await l(`${T0}/v1/vulns/${encodeURIComponent($)}`,{headers:{"User-Agent":"buddy"}});if(!X.ok)return null;return await X.json()}catch(X){return this.logger.debug(`Failed to fetch advisory ${$}:`,X),null}})}}function i($){return`${$.ecosystem}:${$.name}@${$.version}`}function F0($){return $.replace(/^[\^~>=<\s]*v?/,"").trim()}function H1($,X){if(!$||!X)return!1;try{return Bun.semver.order($,X)>=0}catch{return!1}}import j1 from"process";function _1($){if(!$)return null;let X=$.split("/").filter(Boolean);if(X.length<2)return null;return{owner:X.slice(0,-1).join("/"),name:X[X.length-1]}}var z1=["GITHUB_REPOSITORY","CI_PROJECT_PATH","BITBUCKET_REPO_FULL_NAME"];function O1($){for(let X of z1){let Q=_1($[X]);if(Q)return Q}return null}function U0($,X=j1.env){if(!$.repository)return{source:"unresolved",overrodeConfig:!1};let Q=$.repository,K=O1(X),Y=Boolean(Q.owner&&Q.name);if(!K)return Y?{owner:Q.owner,name:Q.name,source:"config",overrodeConfig:!1}:{source:"unresolved",overrodeConfig:!1};if(Y&&(Q.owner!==K.owner||Q.name!==K.name)){let _=`Configured repository ${`${Q.owner}/${Q.name}`} does not match the checked-out repository ${K.owner}/${K.name}. Using ${K.owner}/${K.name} \u2014 buddy `+"operates on the checked-out repository. Update repository.owner/repository.name in your buddy config to silence this warning.";if(Q.owner=K.owner,Q.name=K.name,$.dashboard?.issueNumber!==void 0)$.dashboard.issueNumber=void 0;return{owner:K.owner,name:K.name,source:"environment",overrodeConfig:!0,warning:_}}if(!Y)return Q.owner||=K.owner,Q.name||=K.name,{owner:K.owner,name:K.name,source:"environment",overrodeConfig:!1};return{owner:Q.owner,name:Q.name,source:"config",overrodeConfig:!1}}class t{config;projectPath;logger;scanner;registryClient;eventBus=null;dashboardGenerator;constructor($,X=c.cwd()){this.config=$;this.projectPath=X;this.logger=new k0($.verbose??!1,$.logLevel),v0(this.logger),this.resolveRepositoryConfig(),this.scanner=new u0(this.projectPath,this.logger,this.config.packages?.ignorePaths),this.registryClient=new c0(this.projectPath,this.logger,this.config),this.dashboardGenerator=new $0}async analyzeMajors($,X){if(!this.config.ai?.majorUpgrades?.enabled)return{report:"",draft:!1};let{analyzeGroupMajors:Q}=await import("./chunk-agdesgzv.js"),{createAiClient:K}=await import("./chunk-54sc18p8.js"),{ReleaseNotesFetcher:Y}=await import("./chunk-g0nv8psv.js"),W=new Y(this.logger),Z=await Q({updates:$,config:this.config,workspace:this.projectPath,baseBranch:this.config.repository?.baseBranch||"main",files:X,ai:K(this.config,this.logger),fetchReleases:(_,O,J)=>W.fetchSpanReleases(_,O,J),logger:this.logger});return{report:Z.report,draft:Z.draft}}resolveRepositoryConfig(){let $=U0(this.config);if($.warning)this.logger.warn(`\u26A0\uFE0F ${$.warning}`);else if($.source==="environment")this.logger.info(`Auto-detected repository: ${$.owner}/${$.name} from GITHUB_REPOSITORY`)}async scanForUpdates(){let $=Date.now();this.logger.info("Starting dependency update scan...");try{let X=Date.now(),Q=await this.scanner.scanProject();this.logger.info(`\u23F1\uFE0F Package file scan took ${Date.now()-X}ms`);let K=Q.reduce((C,P)=>C+P.dependencies.length,0),Y=[],W=Date.now();if(this.config.packages?.ignore&&this.config.packages.ignore.length>0)Y=(await this.registryClient.getOutdatedPackages()).filter((P)=>!this.config.packages.ignore.includes(P.name));else Y=await this.registryClient.getOutdatedPackages();this.logger.info(`\u23F1\uFE0F bun outdated check took ${Date.now()-W}ms (found ${Y.length} updates)`);let Z=Date.now(),_=await this.checkDependencyFilesForUpdates(Q);this.logger.info(`\u23F1\uFE0F Dependency file checks took ${Date.now()-Z}ms (found ${_.length} updates)`);let O=Date.now(),J=await this.checkGitHubActionsForUpdates(Q);this.logger.info(`\u23F1\uFE0F GitHub Actions checks took ${Date.now()-O}ms (found ${J.length} updates)`);let H=Date.now(),j=await this.checkDockerfilesForUpdates(Q);this.logger.info(`\u23F1\uFE0F Docker image checks took ${Date.now()-H}ms (found ${j.length} updates)`);let z=Date.now(),q=await this.checkZigForUpdates(Q);this.logger.info(`\u23F1\uFE0F Zig dependency checks took ${Date.now()-z}ms (found ${q.length} updates)`);let{scanCatalogs:B}=await import("./chunk-65b3vq52.js"),S=await B(this.projectPath,(C)=>this.registryClient.getLatestVersion(C),{...this.config.packages?.ignore?{ignore:this.config.packages.ignore}:{},logger:this.logger});if(S.entries.length>0)this.logger.info(`\uD83D\uDCE6 pnpm catalogs: ${S.updates.length} update(s) across ${S.entries.length} entr(ies)`);let E=Date.now(),{scanEcosystems:D}=await import("./chunk-yncea6ty.js"),w=await D({dir:this.projectPath,...this.config.packages?.includePrerelease!==void 0?{includePrerelease:this.config.packages.includePrerelease}:{},...this.config.packages?.ignore?{ignore:this.config.packages.ignore}:{},logger:this.logger});if(w.manifests.length>0)this.logger.info(`\u23F1\uFE0F Ecosystem checks took ${Date.now()-E}ms (found ${w.updates.length} updates across ${w.manifests.map((C)=>C.ecosystem).join(", ")})`);let L=[...Y,..._,...J,...j,...q,...w.updates,...S.updates];if(this.config.packages?.ignore&&this.config.packages.ignore.length>0)L=L.filter((C)=>!this.config.packages.ignore.includes(C.name));let R=Date.now();if(this.config.packages?.strategy)L=this.filterUpdatesByStrategy(L,this.config.packages.strategy);this.logger.info(`\u23F1\uFE0F Strategy filtering took ${Date.now()-R}ms`);let b=Date.now();L=await this.filterUpdatesByMinimumReleaseAge(L),this.logger.info(`\u23F1\uFE0F Minimum release age filtering took ${Date.now()-b}ms`),L=this.applyPins(L),L=await this.dropOverriddenUpdates(L,Q),L=this.applyPackageRules(L);let h=Date.now();L=await this.annotateSecurityAdvisories(L),this.logger.info(`\u23F1\uFE0F Security advisory lookup took ${Date.now()-h}ms`);let y=this.config.security?.prioritize??!0,f=Date.now();L=m0(L,{prioritizeSecurity:y}),this.logger.info(`\u23F1\uFE0F Sorting took ${Date.now()-f}ms`);let I=Date.now(),F=this.config.packages?.groups?this.groupUpdatesByConfig(L):H0(L,{prioritizeSecurity:y});this.logger.info(`\u23F1\uFE0F Grouping took ${Date.now()-I}ms`);let a=Date.now()-$,o={totalPackages:K,updates:L,groups:F,scannedAt:new Date,duration:a};return this.logger.success(`Scan completed in ${a}ms. Found ${L.length} updates.`),await this.events.emit("scan.completed",{total:L.length,major:L.filter((C)=>C.updateType==="major").length,minor:L.filter((C)=>C.updateType==="minor").length,patch:L.filter((C)=>C.updateType==="patch").length}),o}catch(X){throw this.logger.error("Failed to scan for updates:",X),X}}prTitleFor($){let X=this.config.pullRequest?.titleFormat;if(!X)return $.title;return _0(X,z0($,{title:$.title},this.config.packages?.strategy))}commitMessageFor($,X){let Q=this.config.pullRequest?.commitMessageFormat,K=Q?_0(Q,z0($,{message:$.title,title:$.title},this.config.packages?.strategy)):$.title;return X?`${K} ${X}`:K}applyPackageRules($){let X=this.config.packages?.rules??[],K=[...q0(this.config.packages?.groups),...X];if(K.length===0)return $;let Y=l0($,K);if(Y.length<$.length)this.logger.info(`\uD83D\uDCCB Package rules dropped ${$.length-Y.length} update(s)`);return Y.map((W)=>W.update)}static mergeUnique($,X){let Q=[...new Set([...$??[],...X])];return Q.length>0?Q:void 0}activeRules(){return[...q0(this.config.packages?.groups),...this.config.packages?.rules??[]]}groupEffectsFor($){let X=this.activeRules();if(X.length===0)return J0([]);return J0($.map((Q)=>O0(Q,X)))}orderGroupsByPriority($){if(this.activeRules().length===0)return $;return $.map((Q,K)=>({group:Q,index:K,priority:this.groupEffectsFor(Q.updates).prPriority})).sort((Q,K)=>K.priority-Q.priority||Q.index-K.index).map((Q)=>Q.group)}async dropOverriddenUpdates($,X){let Q=X.filter((Z)=>Z.type==="package.json");if(Q.length===0)return $;let{collectResolutionPins:K,pinBlocksUpdate:Y}=await import("./chunk-5c3qf34r.js"),W=new Map;for(let Z of Q)try{for(let _ of K(JSON.parse(Z.content)))W.set(_.name,{version:_.version,field:_.field})}catch{continue}if(W.size===0)return $;return $.filter((Z)=>{let _=W.get(Z.name);if(!_)return!0;if(!Y({name:Z.name,version:_.version,field:_.field},Z.newVersion))return!0;return this.logger.info(`\uD83D\uDD12 Skipping ${Z.name} \u2192 ${Z.newVersion}: ${_.field} pins it to ${_.version}, which would win at install time`),!1})}applyPins($){let X=this.config.packages?.pin;if(!X||Object.keys(X).length===0)return $;let Q=[];for(let K of $){let Y=X[K.name];if(!Y){Q.push(K);continue}if(K.currentVersion===Y){this.logger.info(`\uD83D\uDCCC ${K.name} is pinned to ${Y}, skipping update to ${K.newVersion}`);continue}this.logger.info(`\uD83D\uDCCC ${K.name} is pinned to ${Y}, retargeting update from ${K.newVersion}`),Q.push({...K,newVersion:Y,updateType:j0(K.currentVersion,Y)})}return Q}async annotateSecurityAdvisories($){if(this.config.security?.enabled===!1||$.length===0)return $;try{return await new s(this.logger).annotateUpdates($,this.config.security?.minimumSeverity??"low")}catch(X){return this.logger.warn("Security advisory lookup failed, continuing without it:",X),$}}async createPullRequests($){let X=Date.now();this.logger.info("Creating pull requests for updates...");try{if(!this.config.repository){this.logger.error("\u274C Repository configuration required for PR creation"),this.logger.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts");return}if(!this.config.repository.owner||!this.config.repository.name){this.logger.error("\u274C Repository owner and name are required for PR creation"),this.logger.info("Set them in buddy.config.ts or ensure GITHUB_REPOSITORY env var is available");return}let Q=c.env.GITHUB_TOKEN,K=c.env.BUDDY_TOKEN;if(!Q&&!K){this.logger.error("\u274C GITHUB_TOKEN or BUDDY_TOKEN environment variable required for PR creation");return}let Y=Q||K,W=!!K;if(K)this.logger.info("\u2705 BUDDY_TOKEN detected - workflow file permissions enabled");else this.logger.info("\u2139\uFE0F No BUDDY_TOKEN \u2014 workflow file updates will be skipped");let Z=await r({provider:this.config.repository.provider,owner:this.config.repository.owner,name:this.config.repository.name,token:Y,...K?{workflowToken:K}:{},...this.config.repository.apiUrl?{apiUrl:this.config.repository.apiUrl}:{}},{logger:this.logger}),_=new f0(this.config),O=this.config.maxPRsPerRun??10,J=0,H=this.orderGroupsByPriority($.groups);for(let z of H)try{let q=Date.now();if(this.logger.info(`Creating PR for group: ${z.name} (${z.updates.length} updates)`),z.updates.length>0&&z.updates.every((G)=>G.file.includes(".github/workflows/"))&&!W){this.logger.warn(`\u26A0\uFE0F Skipping group ${z.name} \u2014 workflow-file updates require BUDDY_TOKEN with the workflow scope`);continue}try{let{spawn:G}=await import("child_process"),T=(M,x)=>{return new Promise((N,U)=>{let v=G(M,x,{stdio:"pipe"});v.on("close",(n)=>n===0?N():U(Error(`Git command failed with code ${n}`))),v.on("error",U)})},V=this.config.repository.baseBranch||"main";await T("git",["checkout",V]),await T("git",["reset","--hard","HEAD"]),await T("git",["clean","-fd"])}catch(G){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state for early file-change check, continuing anyway:",G)}let S=await this.generateAllFileUpdates(z.updates);if(S.length===0){this.logger.info(`\u2139\uFE0F No file changes for group ${z.name}, skipping \u2014 leaving branches untouched`);continue}let E=this.prTitleFor(z),D=Date.now(),w=await _.generateBody(z),L=Date.now()-D;this.logger.info(`\u23F1\uFE0F PR body generation took ${L}ms`);let R=await this.analyzeMajors(z.updates,S.map((G)=>G.path)),b=g0(w,R.report),h=await Z.getPullRequests("open"),y=this.generateBranchName(z),f=`buddy/update-${z.name.toLowerCase().replace(/\s+/g,"-")}-`,I=h.find((G)=>(G.head===y||G.title===E||G.head.startsWith(f)||this.isSimilarPRTitle(G.title,E))&&(G.author==="github-actions[bot]"||G.author.includes("buddy")||G.head.startsWith("buddy/"))&&!G.head.includes("renovate/")&&!G.head.includes("dependabot/")&&!G.author.toLowerCase().includes("renovate")&&!G.author.toLowerCase().includes("dependabot"));if(I){if(this.logger.info(`\uD83D\uDD04 Found existing PR #${I.number}: ${I.title}`),this.shouldAutoClosePR(I,z.updates)){this.logger.info(`\uD83D\uDD12 Auto-closing PR #${I.number} due to config change`);try{let V=this.generateCloseReason(I);try{await Z.createComment(I.number,V)}catch(M){this.logger.warn(`\u26A0\uFE0F Could not add close reason comment to PR #${I.number}:`,M)}await Z.closePullRequest(I.number),await Z.deleteBranch(I.head),this.logger.success(`\u2705 Auto-closed PR #${I.number} and deleted branch ${I.head}`);continue}catch(V){this.logger.error(`\u274C Failed to auto-close PR #${I.number}:`,V)}}if(this.checkIfUpdatesMatch(I.body,z.updates)){this.logger.info("\u2705 Existing PR has the same updates, skipping creation");continue}else{this.logger.info("\uD83D\uDD04 Updates differ, will update existing PR with new content");let V=I.head;try{let{spawn:N}=await import("child_process"),U=(v,n)=>{return new Promise((d0,G0)=>{let V0=N(v,n,{stdio:"pipe"});V0.on("close",(A0)=>{if(A0===0)d0();else G0(Error(`Git command failed with code ${A0}`))}),V0.on("error",G0)})};await U("git",["checkout","main"]),await U("git",["reset","--hard","HEAD"]),await U("git",["clean","-fd"]),this.logger.info(`\uD83E\uDDF9 Reset to clean main state before updating existing PR ${I.number}`)}catch(N){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state, continuing anyway:",N)}let M=await this.generateAllFileUpdates(z.updates);if(M.length===0)this.logger.warn(`\u2139\uFE0F No file changes generated for existing PR ${I.number}, updating metadata only`);else{this.logger.info(`\uD83D\uDCDD Regenerated ${M.length} file changes for existing PR ${I.number}`);try{let{hasBranchDifferences:N}=await import("./chunk-6sgh49z1.js");if(!await N(M,V))this.logger.info(`\u2139\uFE0F No content differences for ${V}; recreating from ${this.config.repository.baseBranch||"main"} with same dependency changes to keep branch up-to-date`),await Z.commitChanges(V,this.commitMessageFor(z,"(rebased)"),M,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated ${V} from ${this.config.repository.baseBranch||"main"} (dependency versions unchanged)`);else await Z.commitChanges(V,this.commitMessageFor(z,"(updated)"),M,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated branch ${V} with latest dependency versions`)}catch(N){this.logger.warn("\u26A0\uFE0F Failed to compare branch content, proceeding with commit:",N),await Z.commitChanges(V,this.commitMessageFor(z,"(updated)"),M,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated branch ${V} with latest dependency versions`)}}let x=_.generateLabels(z);await Z.updatePullRequest(I.number,{title:E,body:b,labels:x,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),this.logger.success(`\u2705 Updated existing PR #${I.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${I.url}`);continue}}if(J>=O){this.logger.warn(`\u26A0\uFE0F Rate limit reached: already created ${J} PRs this run (max: ${O}). Skipping remaining groups.`);break}let F=this.generateBranchName(z);if(await Z.branchExists(F)){this.logger.info(`\uD83D\uDD04 Branch ${F} already exists, checking for associated PR...`);let G=h.find((V)=>V.head===F);if(G){this.logger.info(`\u2705 Found existing PR #${G.number} for branch ${F}, updating it...`);let V=await this.generateAllFileUpdates(z.updates);if(V.length>0)await Z.commitChanges(F,this.commitMessageFor(z,"(updated)"),V,this.config.repository.baseBranch||"main");let M=_.generateLabels(z);await Z.updatePullRequest(G.number,{title:E,body:b,labels:M,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),this.logger.success(`\u2705 Updated existing PR #${G.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${G.url}`);continue}let T=!1;try{let M=(u(Z,"reopenPullRequests","reopenPullRequest")?await Z.getPullRequests("closed"):[]).find((x)=>{if(x.head!==F)return!1;if(x.mergedAt)return!1;return Date.now()-(x.updatedAt?.getTime()??0)<86400000});if(M){this.logger.info(`\uD83D\uDD04 Found recently-closed PR #${M.number} for branch ${F}, reopening...`);let x=await this.generateAllFileUpdates(z.updates);if(x.length>0)await Z.commitChanges(F,this.commitMessageFor(z,"(reopened)"),x,this.config.repository.baseBranch||"main");await Z.reopenPullRequest(M.number);let N=_.generateLabels(z);await Z.updatePullRequest(M.number,{title:E,body:b,labels:N,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),this.logger.success(`\u2705 Reopened and updated PR #${M.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${M.url}`),T=!0}}catch(V){this.logger.warn("\u26A0\uFE0F Failed to check/reopen closed PRs:",V)}if(T)continue;this.logger.info(`\uD83E\uDDF9 Branch ${F} exists but has no open PR, cleaning up...`);try{await Z.deleteBranch(F)}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to delete orphaned branch ${F}:`,V)}}let o=!1;try{let T=(u(Z,"reopenPullRequests","reopenPullRequest")?await Z.getPullRequests("closed"):[]).find((V)=>{if(V.head!==F&&!this.isSimilarPRTitle(V.title,E))return!1;if(!V.head.startsWith("buddy/")&&V.author!=="github-actions[bot]")return!1;if(V.mergedAt)return!1;return Date.now()-(V.updatedAt?.getTime()??0)<604800000});if(T){this.logger.info(`\uD83D\uDD04 Found recently-closed PR #${T.number} (branch may have been deleted), recreating branch and reopening...`),await Z.createBranch(F,this.config.repository.baseBranch||"main");let V=await this.generateAllFileUpdates(z.updates);if(V.length>0)await Z.commitChanges(F,this.commitMessageFor(z,"(reopened)"),V,this.config.repository.baseBranch||"main");await Z.reopenPullRequest(T.number);let M=_.generateLabels(z);await Z.updatePullRequest(T.number,{title:E,body:b,labels:M,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),this.logger.success(`\u2705 Reopened and updated PR #${T.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${T.url}`),o=!0}}catch(G){this.logger.warn("\u26A0\uFE0F Failed to check/reopen closed PRs:",G)}if(o)continue;await Z.createBranch(F,this.config.repository.baseBranch||"main");try{let{spawn:G}=await import("child_process"),T=(V,M)=>{return new Promise((x,N)=>{let U=G(V,M,{stdio:"pipe"});U.on("close",(v)=>{if(v===0)x();else N(Error(`Git command failed with code ${v}`))}),U.on("error",N)})};await T("git",["checkout","main"]),await T("git",["reset","--hard","HEAD"]),await T("git",["clean","-fd"]),this.logger.info(`\uD83E\uDDF9 Reset to clean main state before generating updates for ${z.name}`)}catch(G){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state, continuing anyway:",G)}let C=await this.generateAllFileUpdates(z.updates);if(C.length===0){this.logger.warn(`\u2139\uFE0F No file changes generated for group ${z.name}, skipping PR creation`);continue}let P=!1;for(let G of C)try{let T=await import("fs");if(T.existsSync(G.path)){if(T.readFileSync(G.path,"utf-8")!==G.content){P=!0;break}}else{P=!0;break}}catch{P=!0;break}if(!P){this.logger.warn(`\u2139\uFE0F No actual content changes for group ${z.name}, skipping PR creation`);continue}this.logger.info(`\uD83D\uDCDD Generated ${C.length} file changes for ${z.name}`),await Z.commitChanges(F,this.commitMessageFor(z),C,this.config.repository.baseBranch||"main");let e=this.groupEffectsFor(z.updates),L0=[...new Set([..._.generateLabels(z),...e.labels])],k=await Z.createPullRequest({title:E,body:b,head:F,base:this.config.repository.baseBranch||"main",draft:R.draft,reviewers:t.mergeUnique(this.config.pullRequest?.reviewers,e.reviewers),teamReviewers:this.config.pullRequest?.teamReviewers,assignees:t.mergeUnique(this.config.pullRequest?.assignees,e.assignees),labels:L0});J++,this.logger.success(`\u2705 Created PR #${k.number}: ${k.title} (${J}/${O} this run)`),this.logger.info(`\uD83D\uDD17 ${k.url}`),await this.events.emit("pr.created",{number:k.number,title:k.title,url:k.url,packages:z.updates.map((G)=>G.name)}),await this.queueAutoMerge(Z,k,z.updates,L0);let n0=Date.now()-q;this.logger.info(`\u23F1\uFE0F Total group processing took ${n0}ms`)}catch(q){this.logger.error(`\u274C Failed to create PR for group ${z.name}:`,q)}let j=Date.now()-X;this.logger.success(`\u2705 Completed PR creation for ${$.groups.length} group(s) in ${j}ms`)}catch(Q){throw this.logger.error("Failed to create pull requests:",Q),Q}}shouldRespectVersion($){if(!(this.config.packages?.respectLatest??!0))return!1;let Q=["latest","*","main","master","develop","dev"],K=$.toLowerCase().trim();return Q.includes(K)}async checkDependencyFilesForUpdates($){let{isDependencyFile:X}=await import("./chunk-ar01x04a.js"),{resolveDependencyFile:Q}=await import("./chunk-ay43f085.js"),K=[],Y=$.filter((_)=>X(_.path));this.logger.info(`\u26A1 Checking ${Y.length} dependency files in parallel...`);let W=Y.map(async(_)=>{try{this.logger.info(`Checking dependency file: ${_.path}`);let O=await Q(_.path),J=[];for(let H of O.allDependencies||[]){if(this.shouldRespectVersion(H.constraint)){this.logger.debug(`Skipping ${H.name} - version "${H.constraint}" should be respected`);continue}if(H.constraint!==H.version&&H.version){let j=H.constraint.replace(/^[\^~>=<]+/,"");if(!this.isNewerVersion(j,H.version)){this.logger.debug(`Skipping ${H.name} - latest (${H.version}) is not newer than constraint (${j})`);continue}let z=this.getUpdateType(j,H.version),q=H.version;J.push({name:H.name,currentVersion:H.constraint,newVersion:q,updateType:z,dependencyType:"dependencies",file:_.path,metadata:void 0,releaseNotesUrl:void 0,changelogUrl:void 0,homepage:void 0})}}return J}catch(O){return this.logger.error(`Failed to check dependency file ${_.path}:`,O),[]}}),Z=await Promise.all(W);return K.push(...Z.flat()),K}async checkZigForUpdates($){let{isZigManifest:X}=await import("./chunk-zve5d96e.js"),{fetchLatestZigVersion:Q,fetchZigHash:K,isZigAvailable:Y,parseZigSource:W,zigUrlForVersion:Z}=await import("./chunk-thaxgm5p.js"),_=$.filter((j)=>X(j.path));if(_.length===0)return[];if(!await Y())return this.logger.warn("\u26A0\uFE0F Found Zig manifests but the zig toolchain is not available. "+"Skipping Zig updates: their content-addressed hashes cannot be recomputed without `zig fetch`."),[];let O=c.env.GITHUB_TOKEN||c.env.BUDDY_TOKEN,J=_.flatMap((j)=>j.dependencies.filter((z)=>z.type==="zig-dependencies").map((z)=>({file:j,dep:z})));return this.logger.info(`\u26A1 Checking ${J.length} Zig dependencies...`),(await Promise.all(J.map(async({file:j,dep:z})=>{let q=z.metadata?.url;if(!q)return this.logger.debug(`Skipping ${z.name}: no URL recorded`),null;let B=W(q);if(!B)return this.logger.debug(`Skipping ${z.name}: only GitHub-hosted Zig dependencies can be checked`),null;let S=await Q(B,O);if(!S||S===z.currentVersion)return null;let E=Z(q,S),D=await K(E);if(!D)return this.logger.warn(`\u26A0\uFE0F Skipping ${z.name} ${z.currentVersion} \u2192 ${S}: could not compute its package hash`),null;return this.logger.info(`\uD83D\uDCE6 ${z.name}: ${z.currentVersion} \u2192 ${S}`),{name:z.name,currentVersion:z.currentVersion,newVersion:S,updateType:j0(z.currentVersion,S),dependencyType:"zig-dependencies",file:j.path,resolved:{url:E,hash:D}}}))).filter((j)=>j!==null)}async checkGitHubActionsForUpdates($){let{isGitHubActionsFile:X}=await import("./chunk-6k653r8w.js"),{fetchLatestActionVersion:Q}=await import("./chunk-6k653r8w.js"),K=[],Y=$.filter((H)=>X(H.path));this.logger.info(`\uD83D\uDD0D Found ${Y.length} GitHub Actions workflow files`);let W=[];for(let H of Y){let j=H.dependencies.filter((z)=>z.type==="github-actions");this.logger.info(`Found ${j.length} GitHub Actions in ${H.path}`),j.forEach((z)=>W.push({file:H,dep:z}))}this.logger.info(`\u26A1 Checking ${W.length} GitHub Actions in parallel...`);let Z=W.map(async({file:H,dep:j})=>{try{this.logger.info(`Checking action: ${j.name}@${j.currentVersion}`);let z=await Q(j.name);if(z)if(this.logger.info(`Latest version for ${j.name}: ${z}`),z!==j.currentVersion){let q=this.getUpdateType(j.currentVersion,z);return this.logger.info(`Update available: ${j.name} ${j.currentVersion} \u2192 ${z} (${q})`),{name:j.name,currentVersion:j.currentVersion,newVersion:z,updateType:q,dependencyType:"github-actions",file:H.path,metadata:void 0,releaseNotesUrl:`${Y0(this.config)}/${j.name}/releases`,changelogUrl:void 0,homepage:`${Y0(this.config)}/${j.name}`}}else this.logger.info(`No update needed for ${j.name}: already at ${z}`);else this.logger.warn(`Could not fetch latest version for ${j.name}`);return null}catch(z){return this.logger.warn(`Failed to check version for action ${j.name}:`,z),null}}),O=(await Promise.all(Z)).filter((H)=>H!==null);K.push(...O),this.logger.info(`Generated ${K.length} GitHub Actions updates`);let J=K.reduce((H,j)=>{if(!H.find((q)=>q.name===j.name&&q.currentVersion===j.currentVersion&&q.newVersion===j.newVersion&&q.file===j.file))H.push(j);return H},[]);return this.logger.info(`After deduplication: ${J.length} unique GitHub Actions updates`),J}async checkDockerfilesForUpdates($){let{isDockerfile:X}=await import("./chunk-5kt03hx5.js"),{fetchLatestDockerImageVersion:Q}=await import("./chunk-5kt03hx5.js"),K=[],Y=$.filter((H)=>X(H.path));this.logger.info(`\uD83D\uDD0D Found ${Y.length} Dockerfile(s)`);let W=[];for(let H of Y){let j=H.dependencies.filter((z)=>z.type==="docker-image");this.logger.info(`Found ${j.length} Docker images in ${H.path}`),j.forEach((z)=>W.push({file:H,dep:z}))}this.logger.info(`\u26A1 Checking ${W.length} Docker images in parallel...`);let Z=W.map(async({file:H,dep:j})=>{try{if(this.logger.info(`Checking Docker image: ${j.name}:${j.currentVersion}`),this.shouldRespectVersion(j.currentVersion))return this.logger.debug(`Skipping ${j.name} - version "${j.currentVersion}" should be respected`),null;let z=await Q(j.name,j.currentVersion,{...this.config.registries?.docker?{registries:this.config.registries.docker}:{},...this.config.packages?.includePrerelease!==void 0?{includePrerelease:this.config.packages.includePrerelease}:{}});if(z)if(this.logger.info(`Latest version for ${j.name}: ${z}`),z!==j.currentVersion){let q=this.getUpdateType(j.currentVersion,z);return this.logger.info(`Update available: ${j.name} ${j.currentVersion} \u2192 ${z} (${q})`),{name:j.name,currentVersion:j.currentVersion,newVersion:z,updateType:q,dependencyType:"docker-image",file:H.path,metadata:void 0,releaseNotesUrl:`https://hub.docker.com/r/${j.name}/tags`,changelogUrl:void 0,homepage:`https://hub.docker.com/r/${j.name}`}}else this.logger.info(`No update needed for ${j.name}: already at ${z}`);else this.logger.warn(`Could not fetch latest version for Docker image ${j.name}`);return null}catch(z){return this.logger.warn(`Failed to check version for Docker image ${j.name}:`,z),null}}),O=(await Promise.all(Z)).filter((H)=>H!==null);K.push(...O),this.logger.info(`Generated ${K.length} Docker image updates`);let J=K.reduce((H,j)=>{if(!H.find((q)=>q.name===j.name&&q.currentVersion===j.currentVersion&&q.newVersion===j.newVersion&&q.file===j.file))H.push(j);return H},[]);return this.logger.info(`After deduplication: ${J.length} unique Docker image updates`),J}getUpdateType($,X){try{let Q=$.replace(/^[v^~>=<@]+/,""),K=X.replace(/^[v^~>=<@]+/,""),Y=(_)=>{let O=_.split(".");while(O.length<3)O.push("0");return O.join(".")};if(Q=Y(Q),K=Y(K),Bun.semver.order(K,Q)<=0)return"patch";let W=Q.split(".").map(Number),Z=K.split(".").map(Number);if(Z[0]>W[0])return"major";if(Z[0]===W[0]&&Z[1]>W[1])return"minor";return"patch"}catch{return"patch"}}isNewerVersion($,X){try{return Bun.semver.order(X.replace(/^[v^~>=<@]+/,""),$.replace(/^[v^~>=<@]+/,""))>0}catch{return!1}}compareVersionsSafe($,X){try{let Q=X.replace(/^[v^~>=<@]+/,""),K=$.replace(/^[v^~>=<@]+/,"");if(!/^\d+\.\d+/.test(Q)||!/^\d+\.\d+/.test(K))return"failed";return Bun.semver.order(Q,K)>0?"behind":"at-or-beyond"}catch{return"failed"}}async generateAllFileUpdates($){let X=[],Q=$.filter((H)=>H.file.endsWith("package.json")&&!H.file.includes(".yaml")&&!H.file.includes(".yml")&&!H.file.includes(".github/workflows/")),K=new Map;for(let H of Q){if(!K.has(H.file))K.set(H.file,[]);K.get(H.file).push(H)}for(let[H,j]of K)try{let z=J1.readFileSync(H,"utf-8"),q=JSON.parse(z);for(let B of j){let S=!1,E=B.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,""),D=["dependencies","devDependencies","peerDependencies","optionalDependencies"];for(let w of D)if(q[w]&&q[w][E]){let R=q[w][E].match(/^(\D*)/),b=R?R[1]:"",h=E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),y=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),f=new RegExp(`("${y}"\\s*:\\s*\\{[^}]*?)("${h}"\\s*:\\s*")([^"]+)(")([^}]*?\\})`,"gs"),I=`${b}${B.newVersion}`;z=z.replace(f,`$1$2${I}$4$5`),S=!0;break}if(!S)this.logger.warn(`Package ${E} not found in ${H}`)}X.push({path:H,content:z,type:"update"})}catch(z){this.logger.warn(`Failed to update ${H}:`,z)}let Y=$.filter((H)=>{let j=H.file.toLowerCase();return(j.endsWith("deps.yaml")||j.endsWith("deps.yml")||j.endsWith("dependencies.yaml")||j.endsWith("dependencies.yml"))&&!H.file.includes(".github/workflows/")});if(Y.length>0)try{let{generateDependencyFileUpdates:H}=await import("./chunk-ar01x04a.js"),j=await H(Y);X.push(...j)}catch(H){this.logger.error("Failed to generate dependency file updates:",H)}let W=$.filter((H)=>H.file.endsWith("composer.json")||H.file.endsWith("composer.lock"));if(W.length>0)try{let{generateComposerUpdates:H}=await import("./chunk-fm8ckj9b.js"),j=await H(W);X.push(...j)}catch(H){this.logger.error("Failed to generate Composer updates:",H)}let Z=$.filter((H)=>H.file.includes(".github/workflows/"));if(Z.length>0)try{let{generateGitHubActionsUpdates:H}=await import("./chunk-6k653r8w.js"),j=await H(Z);X.push(...j)}catch(H){this.logger.error("Failed to generate GitHub Actions updates:",H)}let _=$.filter((H)=>H.dependencyType==="docker-image");if(_.length>0)try{let{generateDockerfileUpdates:H}=await import("./chunk-5kt03hx5.js"),j=await H(_);X.push(...j)}catch(H){this.logger.error("Failed to generate Dockerfile updates:",H)}let O=$.filter((H)=>H.dependencyType==="zig-dependencies");if(O.length>0)try{let{generateZigManifestUpdates:H}=await import("./chunk-zve5d96e.js"),j=await H(O);X.push(...j)}catch(H){this.logger.error("Failed to generate Zig manifest updates:",H)}let J=$.filter((H)=>H.dependencyType==="catalog");if(J.length>0)try{let{applyCatalogUpdates:H}=await import("./chunk-65b3vq52.js"),j=J[0].file,z=await Bun.file(R0(this.projectPath,j)).text(),q=H(z,J);if(q===z)this.logger.warn(`\u26A0\uFE0F No catalog changes written to ${j}`);else X.push({path:j,content:q,type:"update"})}catch(H){this.logger.error("Failed to generate pnpm catalog updates:",H)}return X.push(...await this.generateAdapterFileUpdates($)),X}async generateAdapterFileUpdates($){let{adapterNamed:X}=await import("./chunk-82dv4p13.js"),Q=new Map;for(let Y of $){if(!X(Y.dependencyType))continue;let W=Q.get(Y.file);if(W)W.push(Y);else Q.set(Y.file,[Y])}let K=[];for(let[Y,W]of Q){let Z=X(W[0].dependencyType);if(!Z)continue;try{let _=R0(this.projectPath,Y),O=await Bun.file(_).text(),J=O;for(let H of W)J=Z.applyUpdate(J,{name:H.name,currentVersion:H.currentVersion,newVersion:H.newVersion,section:H.dependencyType});if(J===O){this.logger.warn(`\u26A0\uFE0F ${Z.name}: no changes written to ${Y}`);continue}K.push({path:Y,content:J,type:"update"})}catch(_){this.logger.error(`Failed to write ${Z.name} updates to ${Y}:`,_)}}return K}async run(){let $=await this.scanForUpdates();if($.updates.length===0)return this.logger.info("No updates available!"),$;if(this.config.pullRequest)await this.createPullRequests($);return $}async checkPackages($){return this.logger.info(`Checking specific packages: ${$.join(", ")}`),this.registryClient.getUpdatesForPackages($)}async checkPackagesWithPattern($){return this.logger.info(`Checking packages with pattern: ${$}`),this.registryClient.getUpdatesWithPattern($)}filterUpdatesByStrategy($,X){if(X==="all")return $;return $.filter((Q)=>{switch(X){case"major":return Q.updateType==="major";case"minor":return Q.updateType==="major"||Q.updateType==="minor";case"patch":return!0;default:return!0}})}async filterUpdatesByMinimumReleaseAge($){let X=this.config.packages?.minimumReleaseAge??0;if(X===0)return $;this.logger.info(`Applying minimum release age filter (${X} minutes) in parallel...`);let Q=$.map(async(Z)=>{try{if(await this.registryClient.meetsMinimumReleaseAge(Z.name,Z.newVersion,Z.dependencyType))return Z;else return this.logger.debug(`Filtered out ${Z.name}@${Z.newVersion} (${Z.dependencyType}) due to minimum release age requirement`),null}catch(_){return this.logger.warn(`Error checking release age for ${Z.name}@${Z.newVersion} (${Z.dependencyType}), including update:`,_),Z}}),Y=(await Promise.all(Q)).filter((Z)=>Z!==null),W=$.length-Y.length;if(W>0)this.logger.info(`Filtered out ${W} updates due to minimum release age requirement`);return Y}groupUpdatesByConfig($){let X=[],{grouped:Q,remaining:K}=this.groupByRuleNames($);X.push(...Q);let Y=[...K];if(this.config.packages?.groups)for(let W of this.config.packages.groups){let Z=[],{Glob:_}=globalThis.Bun,O=new Set;for(let J of W.patterns){let H;try{H=new _(J)}catch(j){this.logger.warn(`Invalid group pattern '${J}':`,j);continue}Y.forEach((j,z)=>{if(!O.has(z)&&H.match(j.name))Z.push(j),O.add(z)})}if(O.size>0){for(let J=Y.length-1;J>=0;J--)if(O.has(J))Y.splice(J,1)}if(Z.length>0){let J=Z;if(W.strategy)J=this.filterUpdatesByStrategy(Z,W.strategy);X.push({name:W.name,updates:J,updateType:this.getHighestUpdateType(J),title:`chore(deps): update ${W.name}`,body:`Update ${J.length} packages in ${W.name} group`})}}if(Y.length>0){let W=H0(Y);X.push(...W)}return X}groupByRuleNames($){let X=this.config.packages?.rules??[];if(X.length===0)return{grouped:[],remaining:$};let Q=new Map,K=[];for(let W of $){let Z=O0(W,X).groupName;if(!Z){K.push(W);continue}let _=Q.get(Z);if(_)_.push(W);else Q.set(Z,[W])}return{grouped:[...Q.entries()].map(([W,Z])=>({name:W,updates:Z,updateType:this.getHighestUpdateType(Z),title:`chore(deps): update ${W}`,body:`Update ${Z.length} packages in ${W} group`})),remaining:K}}getHighestUpdateType($){if($.some((X)=>X.updateType==="major"))return"major";if($.some((X)=>X.updateType==="minor"))return"minor";return"patch"}generateBranchName($){return`buddy/update-${$.name.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}`}isSimilarPRTitle($,X){if($.toLowerCase()===X.toLowerCase())return!0;let Q=$.toLowerCase(),K=X.toLowerCase(),Y=Q.includes("github actions"),W=K.includes("github actions");if(Y&&W)return!0;if(Y!==W)return!1;let Z=Q.includes("docker image"),_=K.includes("docker image");if(Z&&_)return!0;if(Z!==_)return!1;let O=[/update all non-major/i,/update \d+ dependenc(y|ies)/i,/update.*\(minor\)/i,/update.*\(patch\)/i,/update.*\(major\)/i],J=O.some((j)=>j.test($)),H=O.some((j)=>j.test(X));if(J&&H){let j=Q.includes("(major)")||Q.includes("major update"),z=K.includes("(major)")||K.includes("major update");return j===z}if(K.includes("update dependency ")){let j=X.match(/update dependency (\S+)/i),z=$.match(/update dependency (\S+)/i);if(j&&z)return j[1]===z[1]}if(J!==H)return!1;if(Q.includes("dependency ")&&K.includes("dependency "))return!1;return!1}checkIfUpdatesMatch($,X){if(!$)return!1;let Q=this.extractPackageUpdatesFromPRBody($),K=new Map;for(let Y of Q)K.set(Y.name,{from:Y.currentVersion,to:Y.newVersion});for(let Y of X){let W=K.get(Y.name);if(!W)return!1;let Z=W.to.replace(/^[v^~>=<]+/,""),_=Y.newVersion.replace(/^[v^~>=<]+/,"");if(Z!==_)return!1}return K.size===X.length}generatePRLabels($){let X=new Set;X.add("dependencies");let Q=$.updates.map((W)=>W.updateType),K={major:Q.includes("major"),minor:Q.includes("minor"),patch:Q.includes("patch")};if(K.major)X.add("major");if(K.minor)X.add("minor");if(K.patch)X.add("patch");if($.updates.length>5)X.add("dependencies");if($.updates.some((W)=>(W.securityAdvisories?.length??0)>0))X.add(this.config.security?.label??"security");if(this.config.pullRequest?.labels)this.config.pullRequest.labels.forEach((W)=>{if(W!=="dependencies")X.add(W)});return Array.from(X)}shouldAutoClosePR($,X){if(this.shouldAutoCloseForRespectLatest($))return!0;if(this.shouldAutoCloseForIgnorePaths($))return!0;if(this.shouldAutoCloseForRemovedFiles($))return!0;return!1}shouldAutoCloseForRespectLatest($){if(!(this.config.packages?.respectLatest??!0))return!1;let Q=["latest","*","main","master","develop","dev"],K=this.extractPackageUpdatesFromPRBody($.body);if(K.length===0)return!1;return K.filter((W)=>{let Z=W.currentVersion.toLowerCase().trim();return Q.includes(Z)}).length>0}shouldAutoCloseForIgnorePaths($){let X=this.config.packages?.ignorePaths;if(!X||X.length===0)return!1;let Q=this.extractFilePathsFromPRBody($.body);if(Q.length===0)return!1;let{Glob:K}=globalThis.Bun,Y=Q.filter((W)=>{let Z=W.replace(/^\.\//,"");return X.some((_)=>{try{return new K(_).match(Z)}catch(O){return this.logger.debug(`Failed to match path ${Z} against pattern ${_}: ${O}`),!1}})});if(Y.length>0)return this.logger.debug(`PR #${$.number} contains files now in ignorePaths: ${Y.join(", ")}`),!0;return!1}shouldAutoCloseForRemovedFiles($){try{let X=this.extractFilePathsFromPRBody($.body);if(X.length===0)return!1;let Q=A("fs"),K=A("path"),Y=X.filter((W)=>{let Z=K.join(this.projectPath,W);return!Q.existsSync(Z)});if(Y.length>0){if(this.logger.info(`PR #${$.number} references removed files: ${Y.join(", ")}`),this.config.packages?.ignorePaths&&this.config.packages.ignorePaths.length>0){let{Glob:H}=globalThis.Bun;if(Y.filter((z)=>{return!this.config.packages.ignorePaths.some((q)=>{try{return new H(q).match(z)}catch(B){return this.logger.warn(`Invalid glob pattern '${q}':`,B),!1}})}).length>0)return this.logger.info(`Some removed files are outside ignored paths - not auto-closing PR #${$.number}`),!1}if(Y.some((H)=>H.endsWith("composer.json")))return this.logger.info(`composer.json was removed - PR #${$.number} should be auto-closed`),!0;let Z=$.body.toLowerCase(),_=Z.includes("composer")||Y.some((H)=>H.includes("composer")),O=Z.includes("package.json")||Y.some((H)=>H.includes("package.json")),J=Y.some((H)=>H.endsWith("deps.yaml")||H.endsWith("deps.yml")||H.endsWith("dependencies.yaml")||H.endsWith("dependencies.yml"));if(_||O||J)return this.logger.info(`PR #${$.number} is about removed dependency system - should be auto-closed`),!0}return!1}catch(X){return this.logger.debug(`Failed to check for removed files in PR #${$.number}: ${X}`),!1}}get events(){if(!this.eventBus){this.eventBus=new Q0(this.logger);for(let $ of w0(this.config.notifications))this.eventBus.register($)}return this.eventBus}async createGitProvider(){let $=this.config.repository;if(!$?.owner||!$.name)return this.logger.warn("\u26A0\uFE0F Repository owner and name are required for pull request operations"),null;try{return await r({provider:$.provider,owner:$.owner,name:$.name,...$.apiUrl?{apiUrl:$.apiUrl}:{}},{logger:this.logger})}catch(X){return this.logger.warn(`\u26A0\uFE0F ${P0(X)}`),null}}async queueAutoMerge($,X,Q,K){let Y=M0(Q,K,this.config);if(!Y.eligible){this.logger.debug(`\uD83D\uDD00 PR #${X.number} not auto-merged: ${Y.reason}`);return}let{strategy:W}=g(this.config);if(!u($,"nativeAutoMerge","enableAutoMerge")){this.logger.info(`\uD83D\uDD00 PR #${X.number} qualifies for auto-merge but this provider has no merge queue; update-check will merge it once checks pass`);return}try{if(await $.enableAutoMerge(X.number,W))this.logger.success(`\uD83D\uDD00 PR #${X.number} queued for auto-merge (${Y.reason})`);else this.logger.info(`\uD83D\uDD00 PR #${X.number} qualifies for auto-merge but the repository cannot queue it; update-check will merge it once checks pass`)}catch(Z){this.logger.warn(`\u26A0\uFE0F Failed to queue auto-merge for PR #${X.number}: ${Z}`)}}async mergeEligiblePullRequests($=!1){let X=g(this.config);if(!X.enabled)return[];let Q=await this.createGitProvider();if(!Q)return[];let K=[],Y=await Q.getPullRequests("open");for(let W of Y.filter((Z)=>Z.head.startsWith("buddy/"))){let Z=X.requireGreenCI&&Q.getPullRequestChecksState?await Q.getPullRequestChecksState(W.number):"none",_=Z==="success"||Z==="none",O=D0({number:W.number,title:W.title,body:W.body,head:W.head,labels:W.labels,draft:W.draft},this.config,_);if(!O.eligible){this.logger.debug(`\uD83D\uDD00 PR #${W.number} not merged: ${O.reason}`);continue}if($){this.logger.info(`\uD83D\uDD00 [DRY RUN] Would merge PR #${W.number} (${O.reason})`),K.push(W.number);continue}try{await Q.mergePullRequest(W.number,X.strategy),this.logger.success(`\uD83D\uDD00 Merged PR #${W.number}: ${O.reason}`),await this.events.emit("pr.merged",{number:W.number,title:W.title,strategy:X.strategy}),K.push(W.number)}catch(J){this.logger.warn(`\u26A0\uFE0F Failed to merge PR #${W.number}: ${J}`)}}return K}extractFilePathsFromPRBody($){let X=m($);if(X)return y0(X);let Q=[],K=/\|\s*\[[^\]]+\]\([^)]*\)\s*\|[^|]*\|\s*\*\*([^*]+)\*\*\s*\|/g,Y;while((Y=K.exec($))!==null){let O=Y[1].trim();if(O&&!Q.includes(O))Q.push(O)}let W=/\*\*([^*]+\.(?:json|yaml|yml|lock))\*\*/g;while((Y=W.exec($))!==null){let O=Y[1].trim();if(O&&!Q.includes(O))Q.push(O)}let Z=/\|[^|]+\|[^|]+\|([^|]+)\|[^|]*\|/g;while((Y=Z.exec($))!==null){let O=Y[1].trim();if(O&&(O.includes("/")||/\.(?:json|yaml|yml|lock)$/.test(O))&&!Q.includes(O))Q.push(O)}let _=/(?:^|\s)([\w-]+(?:\/[\w.-]+)*\/[\w.-]+\.(?:json|yaml|yml|lock))(?:\s|$)/gm;while((Y=_.exec($))!==null){let O=Y[1].trim();if(O&&!Q.includes(O))Q.push(O)}return Q}extractPackagesFromPRBody($){let X=m($);if(X)return[...new Set(X.updates.map((W)=>W.name))];let Q=[],K=$.match(/\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|/g);if(K)for(let W of K){let Z=W.match(/\[([^\]]+)\]\([^)]*\)/);if(Z)Q.push(Z[1])}let Y=$.match(/<summary>([^<]+)<\/summary>/g);if(Y)for(let W of Y){let Z=W.replace(/<summary>/,"").replace(/<\/summary>/,"").trim();if(Z&&!Q.includes(Z))Q.push(Z)}return Q}extractPackageUpdatesFromPRBody($){let X=m($);if(X)return h0(X);let Q=[],K=new Set,Y=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`?[v^~>=]*([^`|\s]+)`?\s*(?:->|\u2192)\s*`?[v^~>=]*([^`|\s]+)`?\]?/g,W;while((W=Y.exec($))!==null){let[,Z,_,O]=W;if(!K.has(Z))K.add(Z),Q.push({name:Z,currentVersion:_,newVersion:O})}return Q}getConfig(){return this.config}getProjectPath(){return this.projectPath}async checkAndCloseObsoletePRs($,X=!1){try{this.logger.info("\uD83D\uDD0D Scanning for obsolete PRs due to removed dependency files...");let K=(await $.getPullRequests("open")).filter((W)=>W.head.startsWith("buddy/")||W.author==="github-actions[bot]"&&W.labels.includes("dependencies"));this.logger.info(`Found ${K.length} dependency-related PRs to check`);let Y=0;for(let W of K)try{if(this.shouldAutoCloseForRemovedFiles(W))if(this.logger.info(`\uD83D\uDD12 PR #${W.number} should be auto-closed: ${W.title}`),X)this.logger.info(`\uD83D\uDD0D [DRY RUN] Would auto-close PR #${W.number}`),Y++;else try{let _=this.generateCloseReason(W);try{await $.createComment(W.number,_)}catch(O){this.logger.warn(`\u26A0\uFE0F Could not add close reason comment to PR #${W.number}:`,O)}if(await $.closePullRequest(W.number),W.head.startsWith("buddy/"))try{await $.deleteBranch(W.head),this.logger.success(`\u2705 Auto-closed PR #${W.number} and deleted branch ${W.head}`)}catch(O){this.logger.warn(`\u26A0\uFE0F Auto-closed PR #${W.number} but failed to delete branch: ${O}`)}else this.logger.success(`\u2705 Auto-closed PR #${W.number}`);Y++}catch(_){this.logger.error(`\u274C Failed to auto-close PR #${W.number}:`,_)}}catch(Z){this.logger.warn(`\u26A0\uFE0F Error checking PR #${W.number}:`,Z)}if(Y>0)this.logger.success(`\u2705 ${X?"Would auto-close":"Auto-closed"} ${Y} obsolete PR(s)`);else this.logger.info("\uD83D\uDCCB No obsolete PRs found")}catch(Q){throw this.logger.error("Failed to check for obsolete PRs:",Q),Q}}async checkAndCloseSatisfiedPRs($,X=!1){try{this.logger.info("\uD83D\uDD0D Checking for PRs where dependencies are already at target version...");let K=(await $.getPullRequests("open")).filter((J)=>J.head.startsWith("buddy/")||J.author==="github-actions[bot]"&&J.labels.includes("dependencies"));if(this.logger.info(`Found ${K.length} buddy dependency PRs to validate`),K.length===0){this.logger.info("\uD83D\uDCCB No buddy PRs to check");return}let Y=0,W={...this.config,packages:{...this.config.packages,strategy:"all"}},_=await new t(W).scanForUpdates(),O=new Map;for(let J of _.updates)O.set(J.name,J);if(_.updates.length===0){this.logger.warn("\u26A0\uFE0F Scan returned 0 updates \u2014 skipping satisfied PR check to avoid false-positive closures");return}for(let J of K)try{let H=this.extractPackageUpdatesFromPRBody(J.body);if(H.length===0){this.logger.debug(`PR #${J.number}: Could not extract package updates, skipping`);continue}let j=J.body.match(/\*\*Total\*\*\s*\|\s*\*\*(\d+)\*\*/),z=j?Number.parseInt(j[1],10):0;if(z>0&&H.length<z){this.logger.debug(`PR #${J.number}: Extracted ${H.length}/${z} updates \u2014 incomplete extraction, skipping satisfied check`);continue}let q=0,B=0,S=0;for(let D of H){let w=O.get(D.name);if(!w){this.logger.debug(`PR #${J.number}: ${D.name} not in current scan (unverifiable)`),S++;continue}if(w.newVersion===D.newVersion){this.logger.debug(`PR #${J.number}: ${D.name} still needs update to ${D.newVersion}`),B++;continue}let L=this.compareVersionsSafe(w.currentVersion,D.newVersion);if(L==="at-or-beyond")this.logger.debug(`PR #${J.number}: ${D.name} already at or beyond ${D.newVersion}`),q++;else if(L==="behind")this.logger.debug(`PR #${J.number}: ${D.name} still behind ${D.newVersion}`),B++;else this.logger.debug(`PR #${J.number}: ${D.name} version comparison inconclusive`),S++}let E=B===0&&S===0&&q>0;if(this.logger.debug(`PR #${J.number}: verified-satisfied=${q}, still-needed=${B}, unverifiable=${S} \u2192 ${E?"CLOSE":"KEEP"}`),E)if(this.logger.info(`\u2705 PR #${J.number} is satisfied (dependencies at target version): ${J.title}`),X)this.logger.info(`\uD83D\uDD0D [DRY RUN] Would close PR #${J.number}`),Y++;else try{let D=H.filter((L)=>{let R=O.get(L.name);if(!R)return!1;return this.compareVersionsSafe(R.currentVersion,L.newVersion)==="at-or-beyond"}),w=`\uD83E\uDD16 **Auto-closing satisfied PR**
|
|
89
|
-
|
|
90
|
-
`;if(D.length>0)w+=`The following packages are already at the target version or newer:
|
|
91
|
-
|
|
92
|
-
`,D.forEach((L)=>{w+=`- **${L.name}**: ${L.currentVersion} \u2192 ${L.newVersion}
|
|
93
|
-
`}),w+=`
|
|
94
|
-
`;w+="If this was closed in error, please reopen and add a comment explaining why.";try{await $.createComment(J.number,w)}catch(L){this.logger.warn(`\u26A0\uFE0F Could not add comment to PR #${J.number}:`,L)}if(await $.closePullRequest(J.number),J.head.startsWith("buddy/"))try{await $.deleteBranch(J.head),this.logger.success(`\u2705 Closed PR #${J.number} and deleted branch ${J.head}`)}catch(L){this.logger.warn(`\u26A0\uFE0F Closed PR #${J.number} but failed to delete branch: ${L}`)}else this.logger.success(`\u2705 Closed PR #${J.number}`);Y++}catch(D){this.logger.error(`\u274C Failed to close PR #${J.number}:`,D)}}catch(H){this.logger.warn(`\u26A0\uFE0F Error validating PR #${J.number}:`,H)}if(Y>0)this.logger.success(`\u2705 ${X?"Would close":"Closed"} ${Y} satisfied PR(s)`);else this.logger.info("\uD83D\uDCCB No satisfied PRs found")}catch(Q){throw this.logger.error("Failed to check for satisfied PRs:",Q),Q}}generateCloseReason($){let Q=this.extractFilePathsFromPRBody($.body).filter((_)=>{let O=A("fs"),H=A("path").join(this.projectPath,_);return!O.existsSync(H)}),K=Q.some((_)=>_.includes("composer")),Y=Q.some((_)=>_.includes("package.json")),W=Q.some((_)=>_.endsWith("deps.yaml")||_.endsWith("deps.yml")||_.endsWith("dependencies.yaml")||_.endsWith("dependencies.yml")),Z=`\uD83E\uDD16 **Auto-closing obsolete PR**
|
|
95
|
-
|
|
96
|
-
`;if(K)Z+="This PR was automatically closed because `composer.json` has been removed from the project, indicating that Composer is no longer used for dependency management.\n\n";else if(Y)Z+="This PR was automatically closed because `package.json` has been removed from the project, indicating that npm/yarn/pnpm is no longer used for dependency management.\n\n";else if(W)Z+=`This PR was automatically closed because the dependency files it references have been removed from the project.
|
|
97
|
-
|
|
98
|
-
`;else Z+=`This PR was automatically closed because the dependency files it references are no longer present in the project.
|
|
99
|
-
|
|
100
|
-
`;if(Q.length>0)Z+=`**Removed files:**
|
|
101
|
-
${Q.map((_)=>`- \`${_}\``).join(`
|
|
102
|
-
`)}
|
|
103
|
-
|
|
104
|
-
`;return Z+="If this was closed in error, please reopen the PR and update the dependency files accordingly.",Z}async createOrUpdateDashboard(){try{if(this.logger.info("Creating or updating dependency dashboard..."),!this.config.repository)throw Error("Repository configuration is required for dashboard");if(this.config.repository.provider!=="github")throw Error("Dashboard is currently only supported for GitHub repositories");if(!this.config.repository.owner||!this.config.repository.name)throw Error("Repository owner and name are required for dashboard. Set them in buddy.config.ts or ensure GITHUB_REPOSITORY env var is available.");let $=await r({provider:this.config.repository.provider,owner:this.config.repository.owner,name:this.config.repository.name,...this.config.repository.token?{token:this.config.repository.token}:{},...this.config.repository.apiUrl?{apiUrl:this.config.repository.apiUrl}:{}},{logger:this.logger}),X=await this.collectDashboardData($),Q=this.config.dashboard||{},{title:K,body:Y}=this.dashboardGenerator.generateDashboard(X,{showOpenPRs:Q.showOpenPRs??!0,showDetectedDependencies:Q.showDetectedDependencies??!0,showDeprecatedDependencies:Q.showDeprecatedDependencies??!0,bodyTemplate:Q.bodyTemplate}),W={title:Q.title||K,body:Y,labels:Q.labels||["dependencies","dashboard"],assignees:Q.assignees},Z=await this.findExistingDashboard($,Q.issueNumber),_=null;if(Z){if(this.logger.info(`Updating existing dashboard issue #${Z.number}`),_=await this.updateDashboardIssue($,Z.number,W),_)this.logger.success(`\u2705 Successfully updated dashboard issue #${_.number}`)}if(!_){this.logger.info("Creating new dashboard issue"),this.logger.info("Performing final check for existing dashboards before creation...");let O=await this.findExistingDashboard($,Q.issueNumber);if(O&&O.number!==Z?.number){if(this.logger.info(`Race condition detected! Found existing dashboard #${O.number} during final check`),_=await this.updateDashboardIssue($,O.number,W),_)this.logger.success(`\u2705 Updated existing dashboard issue #${_.number} (race condition avoided)`)}if(!_)_=await $.createIssue(W),this.logger.success(`\u2705 Successfully created new dashboard issue #${_.number}`)}if(Q.pin!==void 0)if(!Q.pin)await $.unpinIssue(_.number);else if(u($,"pinIssues","pinIssue"))await $.pinIssue(_.number);else this.logger.debug("\uD83D\uDCCC Provider does not support pinning issues; leaving the dashboard unpinned");return this.logger.success(`\u2705 Dashboard updated: ${_.url}`),_}catch($){throw this.logger.error("Failed to create or update dashboard:",$),$}}async collectDashboardData($){let[X,Q]=await Promise.all([this.scanner.scanProject(),$.getPullRequests("open")]),K=Q.filter((j)=>j.labels.includes("dependencies")||j.labels.includes("dependency")||j.labels.includes("deps")||j.title.toLowerCase().includes("update")||j.title.toLowerCase().includes("chore(deps)")||j.title.toLowerCase().includes("bump")||j.title.toLowerCase().includes("upgrade")||j.title.toLowerCase().includes("renovate")||j.head.includes("renovate/")||j.head.includes("dependabot/")||j.head.includes("buddy/")||j.head.includes("update-")||j.head.includes("bump-")),Y=X.filter((j)=>j.type==="package.json"),W=X.filter((j)=>j.path.includes(".github/workflows/")&&(j.path.endsWith(".yml")||j.path.endsWith(".yaml"))),Z=X.filter((j)=>!j.path.includes(".github/workflows/")&&j.type!=="package.json"),O=await new o0().checkDeprecatedDependencies(X),J=await this.findVulnerableDependencies(X),H=await this.findCappedDependencies(X);return{openPRs:K,detectedDependencies:{packageJson:Y,dependencyFiles:Z,githubActions:W},deprecatedDependencies:O,vulnerableDependencies:J,cappedDependencies:H,repository:{owner:this.config.repository.owner,name:this.config.repository.name,provider:this.config.repository.provider},lastUpdated:new Date}}async findCappedDependencies($){if(this.config.packages?.detectResolutionDrift===!1)return[];try{let{collectDriftInputs:X}=await import("./chunk-qyf90zz3.js"),{findDrift:Q}=await import("./chunk-gkmvxjbe.js"),K=await X($,this.registryClient,this.projectPath,this.logger),Y=Q(K).filter((W)=>W.kind==="capped");if(Y.length>0)this.logger.info(`\uD83D\uDD17 ${Y.length} package(s) capped by a dependant's range`);return Y}catch(X){return this.logger.warn("Resolution drift analysis failed, continuing without it:",X),[]}}async findVulnerableDependencies($){if(this.config.security?.enabled===!1)return[];let X=[],Q=new Map;for(let K of $)for(let Y of K.dependencies){let W=W0(Y.type);if(!W)continue;let Z=Y.currentVersion.replace(/^[\^~>=<\s]*v?/,"").trim();if(!Z)continue;let _={name:Y.name,version:Z,ecosystem:W},O=i(_);if(Q.has(O))continue;Q.set(O,{name:Y.name,currentVersion:Y.currentVersion,ecosystem:W,file:K.path}),X.push(_)}if(X.length===0)return[];try{let Y=await new s(this.logger).findAdvisories(X),W=this.config.security?.minimumSeverity??"low",Z={low:0,moderate:1,high:2,critical:3},_=[];for(let[O,J]of Y){let H=Q.get(O);if(!H)continue;let j=J.filter((z)=>Z[z.severity]>=Z[W]);if(j.length>0)_.push({...H,advisories:j})}return _.sort((O,J)=>Z[J.advisories[0].severity]-Z[O.advisories[0].severity]),_}catch(K){return this.logger.warn("Vulnerability check failed, dashboard will omit it:",K),[]}}async updateDashboardIssue($,X,Q){try{return await $.updateIssue(X,Q)}catch(K){if(K instanceof b0&&K.isNotFound)return this.logger.warn(`Dashboard issue #${X} no longer exists in ${K.repository} (${K.status}); creating a replacement dashboard instead.`),null;throw K}}async findExistingDashboard($,X){try{if(this.logger.info("Searching for existing dashboard issue..."),X){this.logger.info(`Looking for specific dashboard issue #${X}`);let _=(await $.getIssues("open")).find((O)=>O.number===X);if(_)return this.logger.info(`Found specified dashboard issue #${_.number}: ${_.title}`),_;else return this.logger.warn(`Specified dashboard issue #${X} not found`),null}let Q=await $.getIssues("open");this.logger.info(`Found ${Q.length} open issues to search through`);for(let Z of Q){let _=Z.labels.includes("dashboard")&&Z.labels.includes("dependencies"),O=Z.title.toLowerCase().includes("dependency dashboard"),J=Z.body.includes("This issue lists Buddy updates and detected dependencies");if(J||_&&O)return this.logger.info(`Found existing dashboard issue #${Z.number}: ${Z.title}`),this.logger.info(` - Labels: ${Z.labels.join(", ")}`),this.logger.info(` - Title matches: ${O}`),this.logger.info(` - Body has marker: ${J}`),Z}let K=Q.filter((Z)=>Z.labels.includes("dashboard")),Y=Q.filter((Z)=>Z.labels.includes("dependencies")),W=Q.filter((Z)=>Z.title.toLowerCase().includes("dependency dashboard"));if(this.logger.info("Dashboard search results:"),this.logger.info(` - Issues with 'dashboard' label: ${K.length}`),this.logger.info(` - Issues with 'dependencies' label: ${Y.length}`),this.logger.info(` - Issues with 'dependency dashboard' in title: ${W.length}`),K.length>0){this.logger.info("Issues with 'dashboard' label:");for(let Z of K)this.logger.info(` - #${Z.number}: ${Z.title} (labels: ${Z.labels.join(", ")})`)}return this.logger.info("No existing dashboard issue found"),null}catch(Q){return this.logger.warn(`Failed to search for existing dashboard: ${Q}`),null}}}
|
|
105
|
-
export{A1 as Ic,Q0 as Jc,d as Kc,a0 as Lc,w0 as Mc,e0 as Nc,$1 as Oc,X1 as Pc,Q1 as Qc,W0 as Rc,K1 as Sc,s as Tc,i as Uc,U0 as Vc,t as Wc};
|
package/dist/chunk-eagjp0dh.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
var L={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 Q(q,y){if(typeof q!=="object"||q===null||Array.isArray(q))return[];let j=[];for(let[z,B]of Object.entries(q)){if(typeof B!=="string"||!B.trim())continue;if(!L[z])continue;j.push({name:z,currentVersion:B.trim(),type:"engines",file:y,metadata:{engine:"true",source:L[z].source}})}return j}function R(q){if(typeof q!=="object"||q===null)return[];let y=q,j=[],z=(B,C)=>{if(typeof B!=="object"||B===null||Array.isArray(B))return;for(let[J,A]of Object.entries(B)){if(typeof A==="string"&&A.trim()){j.push({name:J,version:A.trim(),field:C});continue}if(typeof A==="object"&&A!==null){let F=A;if(typeof F["."]==="string")j.push({name:J,version:F["."].trim(),field:C});z(A,C)}}};return z(y.overrides,"overrides"),z(y.resolutions,"resolutions"),z(y.pnpm?.overrides,"pnpm.overrides"),j}function T(q,y){let j=q.version.trim();try{if(/^[\^~><=]/.test(j))return!Bun.semver.satisfies(y,j)}catch{return!0}return j!==y}async function U(q,y){let j=L[q];if(!j)return null;let z=j.registry==="npm"?await y.npm(j.source):await y.github(j.source);return z?z.replace(/^v/,""):null}function X(q,y){let j=/^\s*(>=|\^|~|>|=)?\s*v?(\d+(?:\.\d+)*)\s*$/.exec(q);if(!j)return null;let[,z="",B]=j,C=B.split(".").map(Number),A=y.split(".").map(Number).slice(0,C.length),F=!1;for(let H=0;H<A.length;H++){let M=A[H]-(C[H]??0);if(M!==0){F=M>0;break}}if(!F)return null;return`${z}${A.join(".")}`}
|
|
3
|
-
export{L as Ee,Q as Fe,R as Ge,T as He,U as Ie,X as Je};
|
package/dist/chunk-eht72nnj.js
DELETED
package/dist/chunk-f4nv5x3z.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$d as a}from"./chunk-56q4pwb5.js";import"./chunk-tb5y0350.js";import"./chunk-16yqbccr.js";import"./chunk-8rc6042h.js";import"./chunk-4efbxdjr.js";import"./chunk-eagjp0dh.js";import"./chunk-6d9hmjt8.js";import"./chunk-pkkwb0n0.js";import"./chunk-ph1b3vbp.js";import"./chunk-0j7z87kh.js";import"./chunk-5k40mwd4.js";import"./chunk-1h3ey7k5.js";import"./chunk-akffynkc.js";import"./chunk-x3kragh9.js";import"./chunk-wdwvt7gb.js";import"./chunk-8661pvb8.js";import"./chunk-ctsz0ynx.js";import"./chunk-vkctfqpm.js";import"./chunk-6g1y9yqh.js";export{a as PackageScanner};
|
package/dist/chunk-fdfk918n.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{V as a,W as b}from"./chunk-3zdcekfj.js";import"./chunk-p4zwy518.js";import"./chunk-mcrfxphm.js";import"./chunk-vagxqhef.js";import"./chunk-xqx460y2.js";import"./chunk-ts35hc5t.js";import"./chunk-16yqbccr.js";import"./chunk-q9n79dd3.js";import"./chunk-tzs22es2.js";import"./chunk-1h3ey7k5.js";import"./chunk-akffynkc.js";import"./chunk-6g1y9yqh.js";export{b as renderDoctorReport,a as diagnose};
|
package/dist/chunk-fdj0tewy.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{qi as P}from"./chunk-bxfc4g2x.js";import{Hi as Q}from"./chunk-g0w8n555.js";import{Rj as O}from"./chunk-akffynkc.js";var V=[{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 K(k){if(!k.trim())return{kind:"unknown",mechanical:!1,evidence:[]};let q=k.split(`
|
|
3
|
-
`);for(let j of V){let w=[];for(let B of q)if(j.patterns.some((H)=>H.test(B))){if(w.push(B.trim()),w.length>=5)break}if(w.length>0)return{kind:j.kind,mechanical:j.mechanical,evidence:w}}return{kind:"unknown",mechanical:!1,evidence:W(q)}}function W(k,q=40){let j=k.filter((w)=>/\b(?:error|failed|failure|exception|panic|fatal)\b/i.test(w)&&!/^\s*(?:at\s|\s*\.\.\.)/.test(w));return(j.length>0?j:k.slice(-q)).slice(-q).map((w)=>w.trim()).filter(Boolean)}function J(k){switch(k.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."}}async function C(k){let q=k.logger??O(),j=K(k.log),w=k.maxAttempts??3;if(q.info(`\uD83E\uDE7A CI failure classified as ${j.kind}`),k.failsOnBase)return{failure:j,action:"skipped",fixed:!1,report:z(j,"This failure also occurs on the base branch, so it is not caused by this change. Fixing it here would only mask it.")};if((k.priorAttempts??0)>=w)return{failure:j,action:"skipped",fixed:!1,report:z(j,`Already attempted ${k.priorAttempts} time(s); stopping rather than looping.`)};if(j.kind==="lockfile-drift"&&k.regenerateLockfile){q.info("\uD83D\uDD27 Regenerating the lock file");let H=await k.regenerateLockfile();return{failure:j,action:"mechanical-fix",fixed:H,report:z(j,H?"Regenerated the lock file and pushed the result. No model was needed.":"Tried to regenerate the lock file, but the install did not succeed.")}}if(j.kind==="flake")return{failure:j,action:"retry",fixed:!1,report:z(j,"This looks transient. Re-running the failed job is likely to clear it.")};if(!k.ai)return{failure:j,action:"reported",fixed:!1,report:z(j,"No AI provider is configured, so this needs a human. See https://buddy.sh/ai/providers to enable automatic repair.")};let B=await Q(k.ai,{mode:P,task:["A CI job on this branch is failing. Diagnose the root cause and fix it if the fix is clear.","",`Classification: ${j.kind} \u2014 ${J(j)}`,"","Relevant log lines:",j.evidence.join(`
|
|
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
|
-
`),context:{workspace:k.workspace,baseBranch:k.baseBranch,...k.branch?{branch:k.branch}:{}},logger:q});return{failure:j,action:"agent-fix",fixed:B.stopReason==="completed",report:z(j,B.output||"The repair run ended without a conclusion.")}}function z(k,q){let j=`## \uD83E\uDE7A CI failure analysis
|
|
6
|
-
|
|
7
|
-
**Diagnosis:** ${J(k)}
|
|
8
|
-
|
|
9
|
-
${q}
|
|
10
|
-
`;if(k.evidence.length>0)j+=`
|
|
11
|
-
<details><summary>Relevant log lines</summary>
|
|
12
|
-
|
|
13
|
-
\`\`\`
|
|
14
|
-
${k.evidence.slice(0,20).join(`
|
|
15
|
-
`)}
|
|
16
|
-
\`\`\`
|
|
17
|
-
|
|
18
|
-
</details>
|
|
19
|
-
`;return j}
|
|
20
|
-
export{K as _a,W as $a,J as ab,C as bb};
|
package/dist/chunk-fqj7e6xa.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$ as a,aa as b,ba as c,ca as d,da as e,ea as f,fa as g,ga as h,ha as i,ia as j}from"./chunk-9h04nskh.js";import"./chunk-6g1y9yqh.js";export{d as similarity,j as renderQuickLinks,b as renderPackageContext,h as parseQuickSelection,a as findMentionedPackages,e as findDuplicates,c as constrainLabels,i as clearQuickSelection,f as QUICK_LINKS_MARKER,g as QUICK_ACTIONS};
|
package/dist/chunk-frm8zz31.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Ri as a,Si as b,Ti as c,Ui as d,Vi as e,Wi as f,Xi as g,Yi as h,Zi as i,_i as j}from"./chunk-7mgec8kb.js";import"./chunk-6g1y9yqh.js";export{h as withManifest,g as stripManifest,c as serializeManifest,d as serializeGroupManifest,e as parseManifest,i as manifestUpdates,j as manifestFiles,f as hasManifest,a as MANIFEST_SCHEMA_VERSION,b as MANIFEST_MAX_LENGTH};
|
package/dist/chunk-g0nv8psv.js
DELETED
package/dist/chunk-gkmvxjbe.js
DELETED
package/dist/chunk-j8asz4hb.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{A as lQ,B as aQ,C as IQ,a as w,b as X,c as R,r as gQ,s as iQ,t as $Q,x as F,y as C,z as JQ}from"./chunk-r2sbprdb.js";import"./chunk-6g1y9yqh.js";import*as B from"fs/promises";import*as WQ from"fs";import*as y from"path";import*as BQ from"child_process";import*as z0 from"crypto";import*as q0 from"readline";function u(V){if(V.inputSchema.type!=="object")throw Error(`JSON schema for tool "${V.name}" must be an object, but got ${V.inputSchema.type}`);return{type:"custom",name:V.name,input_schema:V.inputSchema,description:V.description,run:V.run,parse:(Q)=>Q,...V.close?{close:V.close}:{}}}import*as x from"fs/promises";import*as A from"path";import{randomUUID as U0}from"crypto";var a=493,D0=420;function QQ(V,Q){let $=A.relative(V,Q);return $===""||!$.startsWith(".."+A.sep)&&$!==".."&&!A.isAbsolute($)}async function UQ(V,Q){for(let $ of V)if(QQ(await l(A.resolve($)),Q))return $;return}var G0=40;function o(V){let Q=V?.code;return typeof Q==="string"?Q:void 0}async function l(V){let Q=[],$=V,Z=0;for(;;){let z;try{z=await x.realpath($)}catch(q){let K;try{K=(await x.lstat($)).isSymbolicLink()}catch(Y){let H=o(Y);if(H!=="ENOENT"&&H!=="ENOTDIR")throw Y;let W=A.dirname($);if(W===$)throw Y;Q.push(A.basename($)),$=W;continue}if(!K)throw q;if(++Z>G0)throw Object.assign(Error("too many levels of symbolic links"),{code:"ELOOP"});$=A.resolve(A.dirname($),await x.readlink($));continue}return Q.length?A.join(z,...Q.reverse()):z}}async function OQ(V,Q,$){let Z=$?.allowedRoots??[],z=await l(A.resolve(V)),q;try{q=await l(A.resolve(z,Q))}catch(Y){throw new C(p(Y,`path ${JSON.stringify(Q)}`))}if(QQ(z,q)||await UQ(Z,q)!==void 0)return q;let K=Z.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new C(`path ${JSON.stringify(Q)} is outside ${K}`)}async function DQ(V,Q){let $=A.dirname(V),Z=A.join($,`.tmp-${process.pid}-${U0()}`),z;try{z=await x.open(Z,"wx",D0),await z.writeFile(Q,"utf-8"),await z.sync(),await z.close(),z=void 0,await x.rename(Z,V)}catch(q){if(z)await z.close().catch(()=>{});throw await x.unlink(Z).catch(()=>{}),q}}function p(V,Q){let $=o(V);switch($){case"ENOENT":return`${Q}: no such file or directory`;case"EACCES":case"EPERM":return`${Q}: permission denied`;case"ENOTDIR":return`${Q}: not a directory`;case"EISDIR":return`${Q}: is a directory`;case"ELOOP":return`${Q}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${Q}: file name too long`;case"ENOSPC":return`${Q}: no space left on device`;case"EMFILE":case"ENFILE":return`${Q}: too many open files`;default:return`${Q}: ${$!==void 0?`i/o error (${$})`:"i/o error"}`}}import*as I from"fs/promises";import*as yQ from"fs";import*as M from"path";import{execFile as N0}from"child_process";import{promisify as k0}from"util";import{Readable as L0}from"stream";import{pipeline as w0}from"stream/promises";var A0=k0(N0);async function M0(V){let{client:Q,sessionId:$}=V;if(!Q)return async()=>{};let Z=$Q(Q),z=V.session;if(!z){if($===void 0)return async()=>{};Z.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),z=await Q.beta.sessions.retrieve($)}let q=M.resolve(V.workdir,"skills"),K=[];for(let Y of z.agent.skills)try{let H=await TQ(Q,Y.skill_id,Y.version),W=await Q.beta.skills.versions.retrieve(H,{skill_id:Y.skill_id}),J=M.basename(W.name.trim());if(J===""||J==="."||J==="..")J=Y.skill_id;let U=M.resolve(q,J);if(U!==q&&!U.startsWith(q+M.sep)){Z.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:W.name});continue}let O=await Q.beta.skills.versions.download(H,{skill_id:Y.skill_id});await I.rm(U,{recursive:!0,force:!0}),await I.mkdir(U,{recursive:!0,mode:a}),K.push(U),await vQ(O,U),Z.info("downloaded skill",{component:"agent-tool-context",skill_id:Y.skill_id,version:H,dest:U})}catch(H){Z.warn("failed to download skill",{component:"agent-tool-context",skill_id:Y.skill_id,error:String(H)})}return async()=>{for(let Y of K)await I.rm(Y,{recursive:!0,force:!0}).catch((H)=>{Z.warn("failed to clean up skill",{component:"agent-tool-context",dest:Y,error:String(H)})})}}async function TQ(V,Q,$){if(/^\d+$/.test($))return $;let Z;for await(let z of V.beta.skills.versions.list(Q))if(/^\d+$/.test(z.version)&&(Z===void 0||BigInt(z.version)>BigInt(Z)))Z=z.version;if(Z===void 0)throw new R(`skill ${JSON.stringify(Q)} has no concrete version to resolve ${JSON.stringify($)} against`);return Z}function R0(V){for(let Q of V){let $=Q.trim();if(!$)continue;if(M.isAbsolute($)||$.split(/[\\/]/).includes(".."))throw new R(`refusing to extract unsafe archive member: ${$}`)}}var NQ="skill archive listing is inconsistent; refusing to extract",I0={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function jQ(V){let Q=V.split(`
|
|
3
|
-
`);if(Q[Q.length-1]==="")Q.pop();return Q}function B0(V,Q){return/^[\x20-\x7E]+$/.test(Q)&&!/[\\^#]/.test(Q)&&!(V==="unzip"&&Q.startsWith("-"))}function O0(V,Q,$){let Z=jQ(Q),z=jQ($);if(Z.length!==z.length)throw new R(NQ);let q=[],K=[];return Z.forEach((Y,H)=>{if(I0[V].has(z[H].charAt(0))){q.push(Y);return}if(!B0(V,Y))throw new R(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(Y)}`);K.push(Y)}),{plain:q,special:K}}async function xQ(V){for(let Q of await I.readdir(V,{withFileTypes:!0}))if(Q.isDirectory())await xQ(M.join(V,Q.name));else if(!Q.isFile())throw new R(NQ)}async function GQ(V,Q){try{let{stdout:$}=await A0(V,Q);return $}catch($){if(o($)==="ENOENT")throw new R(`skill extraction requires the \`${V}\` command, but it was not found on PATH`);throw $}}function j0(V){let Q,$=!1;for(let Z of V){let z=Z.trim().split("/").filter((K)=>K!==""&&K!==".");if(z.length===0)continue;let q=z[0];if(Q===void 0)Q=q;else if(q!==Q)return"";if(z.length>1)$=!0}return Q!==void 0&&$?Q:""}async function vQ(V,Q){let $=M.join(Q,`.skill-archive-${process.pid}-${Date.now()}`);if(!V.body)throw new R("skill download response had no body");await w0(L0.fromWeb(V.body),yQ.createWriteStream($));let Z=M.join(M.dirname(Q),`.skill-stage-${process.pid}-${Date.now()}`),z=M.join(M.dirname(Q),`.skill-exclude-${process.pid}-${Date.now()}`);try{let q=await T0($,4),K=q.length>=4&&q[0]===80&&q[1]===75&&q[2]===3&&q[3]===4,Y=K?"unzip":"tar",H=await GQ(Y,K?["-Z1",$]:["-tf",$]),W=await GQ(Y,K?["-Z","--h","--t",$]:["-tvf",$]),{plain:J,special:U}=O0(Y,H,W);R0([...J,...U]);let O=j0(J);if(await I.mkdir(Z,{recursive:!0,mode:a}),J.length>0)await GQ(Y,await y0(Y,$,Z,U,z));await xQ(Z);let g=O?M.join(Z,O):Z,b=await I.readdir(g).catch((P)=>{throw o(P)==="ENOENT"?new R(NQ):P});for(let P of b)await I.rename(M.join(g,P),M.join(Q,P))}finally{await I.rm($,{force:!0}),await I.rm(z,{force:!0}),await I.rm(Z,{recursive:!0,force:!0})}}async function y0(V,Q,$,Z,z){let q=Z.map((K)=>K.replace(/[*?[\\]/g,"\\$&"));if(V==="unzip")return["-oq",Q,"-d",$,...q.length>0?["-x",...q]:[]];if(q.length===0)return["-xf",Q,"-C",$];return await I.writeFile(z,q.join(`
|
|
4
|
-
`)+`
|
|
5
|
-
`,{flag:"wx",mode:384}),["-xf",Q,"-C",$,"-X",z]}async function T0(V,Q){let $=await I.open(V,"r");try{let Z=Buffer.alloc(Q),{bytesRead:z}=await $.read(Z,0,Q,0);return Z.subarray(0,z)}finally{await $.close()}}import*as rQ from"path";import{createHash as h0}from"crypto";import*as N from"fs/promises";import*as L from"path";import{constants as d}from"fs";import{createHash as x0,randomBytes as v0}from"crypto";var EQ=448,b0=384,P0=448,kQ=d.O_NOFOLLOW??0,F0=d.O_NONBLOCK??0;class D extends Error{constructor(V,Q){super(`path ${JSON.stringify(Q)} ${V}`);this.name="FileStoreError",this.reason=V,this.relPath=Q}}D.ESCAPES_ROOT="escapes the store root";D.IS_A_SYMLINK="is a symlink";D.NOT_A_FILE="is not a regular file";D.NOT_A_DIRECTORY="is not a directory";D.NOT_UTF8="is not valid utf-8";D.MOVE_DESTINATION_EXISTS="already exists";function LQ(V){return V.startsWith("/")&&!V.split("/").includes("..")}class h{constructor(V,Q,$=!1){this.hashes=new Map,this.rootPath=V,this.removedOnDispose=Q,this.decoder=$?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(V,Q){if(!g0())throw Error("FileStore requires O_NOFOLLOW support on this platform");let $=!1;try{await N.lstat(V)}catch(Z){if(Z.code!=="ENOENT")throw Z;$=!0}return new h(L.resolve(V),$,Q?.utf8??!1)}async createRoot(){await E0(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){if(!this.removedOnDispose)return;await N.rm(this.rootPath,{recursive:!0,force:!0})}async put(V,Q,$){let Z=V.replace(/\\/g,"/");if(Z.endsWith("/")||Z.endsWith("/.")||Z===""||Z===".")throw new D(D.NOT_A_FILE,V);let z=this.resolveUnderRoot(V),q=typeof Q==="string"?gQ(Q):Q;this.requireUtf8(V,q),await bQ(this.rootPath,L.dirname(z)),await f0(z,q,$?.executable??!1)}async get(V){let Q=this.resolveUnderRoot(V),$;try{$=await fQ(V,Q)}catch(z){if(z.code==="ENOENT")return null;throw z}let Z;try{let z=await $.readFile();Z=new Uint8Array(z.buffer,z.byteOffset,z.byteLength)}finally{await $.close()}return this.requireUtf8(V,Z),Z}async ls(V="/"){let Q=this.resolveUnderRoot(V);return new Set((await PQ(this.rootPath,V,Q)).map(([$])=>$))}async findSymlinks(V="/"){let Q=this.resolveUnderRoot(V);return m0(this.rootPath,V,Q)}async hashtree(V="/"){let Q=this.resolveUnderRoot(V),$=VQ.nowNs(),Z=Object.create(null);for(let[z,q]of await PQ(this.rootPath,V,Q)){let K=await this.hashViaCache(z,q,$);if(K!==null)Z[z]=K}return Z}async hashFile(V){let Q=this.resolveUnderRoot(V),$;try{$=await N.lstat(Q,{bigint:!0})}catch(z){if(z.code==="ENOENT")return null;throw z}if($.isSymbolicLink())throw new D(D.IS_A_SYMLINK,V);if(!$.isFile())throw new D(D.NOT_A_FILE,V);let Z=L.relative(this.rootPath,Q).split(L.sep).join("/");return this.hashViaCache(Z,Q,VQ.nowNs())}async move(V,Q){let $=this.resolveUnderRoot(V),Z=this.resolveUnderRoot(Q);if($===this.rootPath||Z===this.rootPath)return;if(await N.stat(Z).then(()=>!0,()=>!1))throw new D(D.MOVE_DESTINATION_EXISTS,Q);await bQ(this.rootPath,L.dirname(Z)),await N.rename($,Z)}async remove(V){let Q=this.resolveUnderRoot(V);if(Q===this.rootPath)return;let $;try{$=await N.lstat(Q,{bigint:!0})}catch(Z){if(Z.code==="ENOENT")return;throw Z}if($.isDirectory())await N.rm(Q,{recursive:!0,force:!0});else try{await N.unlink(Q)}catch(Z){if(Z.code!=="ENOENT")throw Z}}resolveUnderRoot(V){let Q=V.replace(/\\/g,"/").replace(/^\/+/,""),$=Q.split("/").filter((Z)=>Z!==""&&Z!==".");if(L.posix.isAbsolute(Q)||$.includes(".."))throw new D(D.ESCAPES_ROOT,V);return $.length===0?this.rootPath:L.join(this.rootPath,...$)}requireUtf8(V,Q){if(!this.decoder)return;try{this.decoder.decode(Q)}catch{throw new D(D.NOT_UTF8,V)}}async hashViaCache(V,Q,$){let Z;try{Z=await N.lstat(Q,{bigint:!0})}catch(K){if(K.code==="ENOENT")return null;throw K}if(!Z.isFile())return null;let z=this.hashes.get(V),q;if(z!==void 0&&S0(z,Z))q=z.sha;else try{q=await VQ.hashFile(Q)}catch(K){let Y=K.code;if(Y==="ENOENT"||K instanceof D)return null;if(Y==="ELOOP"||Y==="EMLINK")return null;throw K}if(p0(Z,$))this.hashes.set(V,{mtimeNs:Z.mtimeNs,ctimeNs:Z.ctimeNs,size:Z.size,sha:q});return q}}h.isPathLegal=LQ;function g0(){return kQ!==0}async function E0(V){let Q=[],$=V;for(;;){try{await N.stat($);break}catch(z){let q=z.code;if(q!=="ENOENT"&&q!=="ENOTDIR"&&q!=="ELOOP")throw z}Q.push($);let Z=L.dirname($);if(Z===$)break;$=Z}for(let Z of Q.reverse())try{await N.mkdir(Z,{mode:EQ})}catch(z){if(z.code!=="EEXIST")throw z}}async function bQ(V,Q){let $=L.relative(V,Q);if($==="")return;let Z=V;for(let z of $.split(L.sep)){Z=L.join(Z,z);try{await N.mkdir(Z,{mode:EQ})}catch(q){if(q.code!=="EEXIST")throw q}}}async function f0(V,Q,$){let Z=$?P0:b0,z=L.join(L.dirname(V),`.fs-${v0(8).toString("hex")}.tmp`),q;try{q=await N.open(z,d.O_WRONLY|d.O_CREAT|d.O_EXCL|kQ,Z),await q.writeFile(Q),await q.close(),q=void 0,await N.rename(z,V)}catch(K){if(q)await q.close().catch(()=>{});throw await N.unlink(z).catch(()=>{}),K}}async function fQ(V,Q){let $;try{$=await N.open(Q,d.O_RDONLY|kQ|F0)}catch(Z){let z=Z.code;if(z==="ELOOP"||z==="EMLINK")throw new D(D.IS_A_SYMLINK,V);throw Z}try{if(!(await $.stat()).isFile())throw new D(D.NOT_A_FILE,V)}catch(Z){throw await $.close().catch(()=>{}),Z}return $}async function u0(V){let Q=x0("sha256"),$=await fQ(L.basename(V),V),Z=new Uint8Array(1048576);try{for(;;){let{bytesRead:z}=await $.read(Z,0,Z.length);if(z===0)break;Q.update(Z.subarray(0,z))}}finally{await $.close()}return Q.digest("hex")}async function PQ(V,Q,$){if(!await _0(Q,$))return[];let Z=[];return await uQ($,(z,q)=>{if(q.isFile())Z.push([L.relative(V,z).split(L.sep).join("/"),z])}),Z.sort(),Z}async function m0(V,Q,$){let Z=(K)=>L.relative(V,K).split(L.sep).join("/"),z;try{z=await N.lstat($,{bigint:!0})}catch(K){let Y=K.code;if(Y==="ENOENT"||Y==="ENOTDIR")return new Set;throw K}if(z.isSymbolicLink())return new Set([Z($)]);if(!z.isDirectory())throw new D(D.NOT_A_DIRECTORY,Q);let q=new Set;return await uQ($,(K,Y)=>{if(Y.isSymbolicLink())q.add(Z(K))}),q}async function _0(V,Q){let $;try{$=await N.lstat(Q,{bigint:!0})}catch(Z){let z=Z.code;if(z==="ENOENT"||z==="ENOTDIR")return!1;throw Z}if(!$.isDirectory())throw new D(D.NOT_A_DIRECTORY,V);return!0}async function uQ(V,Q){let $=[V];while($.length){let Z=$.pop(),z;try{z=await N.readdir(Z,{withFileTypes:!0})}catch(q){if(q.code==="ENOENT")continue;throw q}for(let q of z){let K=L.join(Z,q.name);if(Q(K,q),q.isDirectory()&&!q.isSymbolicLink())$.push(K)}}}function S0(V,Q){return Q.mtimeNs===V.mtimeNs&&Q.ctimeNs===V.ctimeNs&&Q.size===V.size}function p0(V,Q){return(V.mtimeNs>V.ctimeNs?V.mtimeNs:V.ctimeNs)<Q-VQ.timestampTrustMarginNs}var d0=2000000000n,VQ={hashFile:u0,timestampTrustMarginNs:d0,nowNs:()=>BigInt(Date.now())*1000000n},mQ=h,FQ=Symbol.asyncDispose;if(FQ)Object.defineProperty(h.prototype,FQ,{value:h.prototype.dispose,configurable:!0,writable:!0});var k,f,XQ,s,YQ,G,c,qQ,E,oQ,KQ,sQ,tQ,wQ,MQ,_Q,SQ,AQ,pQ,dQ,ZQ,zQ,hQ,cQ,c0=30000,n=".anthropic-memory-store",eQ=1;function nQ(V){return h0("sha256").update(`version ${eQ}
|
|
6
|
-
${V}`,"utf-8").digest("hex")}var n0=30000,i0=100,l0=20,a0=16,o0=32,s0=8,t0=50;class m extends R{constructor(V,Q){super(V);if(this.name="SessionMemoryError",Q!==void 0)this.cause=Q}}class Q0{constructor(V,Q,$){this.mode=V,this.cap=Q,this.waiveWindow=$,this.attempted=0,this.capped=0,this.suppressed=0}takeSlot(){if(this.attempted>=this.cap)return this.capped++,!1;return this.attempted++,!0}}class $0{constructor(V,Q){k.add(this),f.set(this,void 0),XQ.set(this,void 0),s.set(this,void 0),YQ.set(this,void 0),G.set(this,void 0),c.set(this,void 0),qQ.set(this,!1),E.set(this,[]),w(this,f,V,"f"),w(this,XQ,Q.workdir,"f"),w(this,s,Q.syncIntervalMs??JQ,"f"),aQ(X(this,s,"f"),"syncIntervalMs"),w(this,YQ,Q.syncDeletions??"enabled","f"),w(this,G,$Q(V),"f"),w(this,c,Date.now(),"f")}get roots(){return X(this,E,"f").map((V)=>V.files.root().path)}get readOnlyRoots(){return X(this,E,"f").filter((V)=>V.readOnly).map((V)=>V.files.root().path)}async download(V){for(let Q of V.resources){if(Q.type!=="memory_store")continue;let $=X(this,k,"m",oQ).call(this,Q),Z;try{if(Z={memoryStoreId:Q.memory_store_id,files:await mQ.open($,{utf8:!0}),readOnly:Q.access==="read_only",baseline:new Map,refusedShas:new Map,pendingDeletes:new Map},!Z.files.root().removedOnDispose)throw new m(`something already exists at the memory store's path: ${$} (memory_store_id=${Q.memory_store_id}); it must not exist when the session starts`);try{await Z.files.createRoot()}catch(z){if(!i(z))throw z;throw new m(`cannot create the memory store's folder: ${$} (memory_store_id=${Q.memory_store_id}): ${z}; the worker host must make this mount path writable`,z)}await X(this,k,"m",MQ).call(this,Z),X(this,G,"f").info("downloaded memories",{count:Z.baseline.size,memory_store_id:Z.memoryStoreId,dest:Z.files.root().path}),X(this,E,"f").push(Z)}catch(z){if(Z)await Z.files.dispose().catch(()=>{});if(z instanceof m)throw z;throw new m(`failed to download memory store memory_store_id=${Q.memory_store_id}: ${z}`,z)}}w(this,c,Date.now(),"f")}async finish(){if(X(this,qQ,"f"))throw new R("finish() was already called: it is the session's last sync and runs once");w(this,qQ,!0,"f"),await this.syncAll(!0)}async syncAll(V){await Promise.all(X(this,E,"f").map((Q)=>X(this,k,"m",sQ).call(this,Q,V))),w(this,c,Date.now(),"f")}async syncIfDue(){if(Date.now()-X(this,c,"f")<X(this,s,"f"))return;await this.syncAll(!1)}async flushWrites(V){await Promise.all(X(this,E,"f").map((Q)=>X(this,k,"m",tQ).call(this,Q,V)))}async dispose(){for(let V of X(this,E,"f")){let Q=V.files.root();try{let $=await X(this,k,"m",KQ).call(this,V);if(!$.markerOk&&Object.keys($.files).length>0){X(this,G,"f").warn(`${$.distrustReason}; leaving the memory store folder on disk`,{root:Q.path,memory_store_id:V.memoryStoreId});continue}await V.files.dispose()}catch($){if(!($ instanceof D)&&!i($))throw $;X(this,G,"f").warn("failed to remove the memory store folder",{root:V.files.root().path,memory_store_id:V.memoryStoreId,error:String($)});continue}if(Q.removedOnDispose)X(this,G,"f").info("removed memory store dir",{dest:Q.path,memory_store_id:V.memoryStoreId})}}}f=new WeakMap,XQ=new WeakMap,s=new WeakMap,YQ=new WeakMap,G=new WeakMap,c=new WeakMap,qQ=new WeakMap,E=new WeakMap,k=new WeakSet,oQ=function(Q){if(Q.mount_path){if(!LQ(Q.mount_path))throw new m(`memory store mount_path is not a clean absolute path: ${JSON.stringify(Q.mount_path)} (memory_store_id=${Q.memory_store_id})`);return Q.mount_path}return rQ.join(X(this,XQ,"f"),"memory",Q.name||Q.memory_store_id)},KQ=async function(Q){let $=await Q.files.hashtree(),Z=$[n];if(delete $[n],Z===nQ(Q.memoryStoreId))return{files:$,markerOk:!0,distrustReason:null};return{files:$,markerOk:!1,distrustReason:Z!==void 0?"the marker file does not match this store":"the marker file is gone"}},sQ=async function(Q,$){try{let Z=await X(this,k,"m",KQ).call(this,Q),z=Z.files;if(!Z.markerOk){if(Object.keys(z).length>0){X(this,G,"f").warn(`${Z.distrustReason}; leaving the memory store folder as found and not syncing`,{root:Q.files.root().path,memory_store_id:Q.memoryStoreId});return}await X(this,k,"m",wQ).call(this,Q,"the folder or its marker is gone");return}if(Object.keys(z).length===0&&Q.baseline.size>1){await X(this,k,"m",wQ).call(this,Q,"every memory file is gone at once");return}let q=new Map;for await(let[J,U]of X(this,k,"m",ZQ).call(this,Q.memoryStoreId))q.set(J,U);let K=new Q0(X(this,YQ,"f"),Math.max(s0,Math.min(t0,Math.floor(Q.baseline.size/4))),$),Y=[],H=new Map,W=[...new Set([...q.keys(),...Object.keys(z),...Q.baseline.keys()])].sort();for(let J of W){let U=q.get(J),O=z[J],g=Q.baseline.get(J),b;if(O===void 0&&g!==void 0&&U!==void 0&&U.content_sha256===g&&!Q.readOnly)b=await X(this,k,"m",hQ).call(this,Q,J,U,g,K);else b=await X(this,k,"m",_Q).call(this,Q,J,U,O,Y);if(b!==void 0)H.set(J,b)}if(Q.baseline=H,await X(this,k,"m",pQ).call(this,Q,Y),K.suppressed>0)X(this,G,"f").debug("remote deletes are disabled; locally deleted memories stay on the server",{count:K.suppressed,memory_store_id:Q.memoryStoreId});if(K.capped>0)X(this,G,"f").warn(`delete cap reached: ${K.mode==="log_only"?"would send":"sent"} ${K.attempted} deletes, held ${K.capped} for later syncs`,{memory_store_id:Q.memoryStoreId})}catch(Z){X(this,G,"f").warn("memory sync failed",{memory_store_id:Q.memoryStoreId,error:String(Z)})}},tQ=async function(Q,$){let Z=new Map,z=new Set,q=async()=>{if(Q.readOnly)return;let K=await X(this,k,"m",KQ).call(this,Q);if(!K.markerOk){X(this,G,"f").warn(`${K.distrustReason}; not uploading anything from the memory store folder`,{root:Q.files.root().path,memory_store_id:Q.memoryStoreId});return}for(let[W,J]of Object.entries(K.files))if(J!==Q.baseline.get(W)&&Q.refusedShas.get(W)!==J)Z.set(W,J),z.add(W);if(Z.size===0||$?.aborted)return;let Y=new Map;for await(let[W,J]of X(this,k,"m",ZQ).call(this,Q.memoryStoreId)){if($?.aborted)return;Y.set(W,J)}let H=[];for(let W of[...Z.keys()].sort()){let J=Z.get(W),U=Q.baseline.get(W),O=Y.get(W);if(O!==void 0&&O.content_sha256===J){Q.baseline.set(W,O.content_sha256),z.delete(W);continue}if(O!==void 0&&O.content_sha256!==U){X(this,G,"f").warn("memory changed both locally and remotely; the flush leaves the remote version",{path:W,memory_store_id:Q.memoryStoreId}),z.delete(W);continue}H.push([W,J,O])}await X(this,k,"m",dQ).call(this,Q,H,z,$)};try{if(await r0(q(),$),$?.aborted&&z.size>0)X(this,G,"f").warn(`memory flush cut off part-way; ${z.size} of ${Z.size} changed files had not finished uploading`,{memory_store_id:Q.memoryStoreId})}catch(K){X(this,G,"f").warn("memory flush failed",{memory_store_id:Q.memoryStoreId,error:String(K)})}},wQ=async function(Q,$){X(this,G,"f").warn(`${$}; re-downloading the memory store folder instead of syncing`,{root:Q.files.root().path,memory_store_id:Q.memoryStoreId}),await Q.files.createRoot(),await X(this,k,"m",MQ).call(this,Q)},MQ=async function(Q){Q.baseline=new Map,Q.pendingDeletes.clear(),await Q.files.put(n,`version ${eQ}
|
|
7
|
-
${Q.memoryStoreId}`);for await(let[$,Z]of X(this,k,"m",ZQ).call(this,Q.memoryStoreId,"full"))if(await X(this,k,"m",AQ).call(this,Q,$,Z.content??""))Q.baseline.set($,Z.content_sha256)},_Q=async function(Q,$,Z,z,q){let K=Q.baseline.get($);if(z!==void 0)Q.pendingDeletes.delete($);if(!Z){if(z===void 0){Q.pendingDeletes.delete($);return}if(K!==void 0){if(z===K){let U=await X(this,k,"m",SQ).call(this,Q,$,K);if(U===void 0)return;if(U===K)return K;z=U}if(Q.readOnly)X(this,G,"f").warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:$,memory_store_id:Q.memoryStoreId});else if(Q.refusedShas.get($)!==z)X(this,G,"f").info("memory deleted remotely but edited locally; re-creating it from the file",{path:$,memory_store_id:Q.memoryStoreId})}if(Q.readOnly)return;if(Q.refusedShas.get($)===z)return;return await X(this,k,"m",zQ).call(this,Q,$,z,void 0)}let Y=Z.content_sha256,H=Y!==K,W=z!==void 0&&z!==K&&z!==Y,J=!Q.readOnly&&W;if(z===void 0&&K!==void 0){if(H)X(this,G,"f").warn("memory deleted locally but changed remotely; restoring the remote version",{path:$,memory_store_id:Q.memoryStoreId}),Q.pendingDeletes.delete($),q.push([$,Z]);return K}if(H){if(z===Y)return Y;if(W)X(this,G,"f").warn("memory changed both locally and remotely; keeping the remote version",{path:$,memory_store_id:Q.memoryStoreId});return q.push([$,Z]),K}if(J){if(Q.refusedShas.get($)===z)return Y;return await X(this,k,"m",zQ).call(this,Q,$,z,Z)??Y}return Y},SQ=async function(Q,$,Z){let z;try{z=await Q.files.hashFile($)}catch(q){if(!(q instanceof D)&&!i(q))throw q;return Z}if(z===null)return;if(z!==Z)return z;try{await Q.files.remove($)}catch(q){if(!(q instanceof D)&&!i(q))throw q;return X(this,G,"f").warn("failed to remove memory deleted remotely",{path:$,memory_store_id:Q.memoryStoreId,error:String(q)}),Z}return},AQ=async function(Q,$,Z){try{await Q.files.put($,Z)}catch(z){if(!(z instanceof D)&&!i(z))throw z;return X(this,G,"f").warn("failed to write memory",{path:$,memory_store_id:Q.memoryStoreId,error:String(z)}),!1}return!0},pQ=async function(Q,$){if($.length===0)return;let Z=async(K,Y)=>{let H;try{H=await X(this,f,"f").beta.memoryStores.memories.retrieve(Y.id,{memory_store_id:Q.memoryStoreId,view:"full"})}catch(W){if(F(W,404))return;X(this,G,"f").warn("failed to fetch memory content",{path:K,memory_store_id:Q.memoryStoreId,error:String(W)});return}if(await X(this,k,"m",AQ).call(this,Q,K,H.content??""))Q.baseline.set(K,H.content_sha256)},z=$[Symbol.iterator](),q=async()=>{for(let[K,Y]of z)await Z(K,Y)};await Promise.all(Array.from({length:Math.min(a0,$.length)},q))},dQ=async function(Q,$,Z,z){let q=$[Symbol.iterator](),K=async()=>{for(let[Y,H,W]of q){if(z?.aborted)return;let J=await X(this,k,"m",zQ).call(this,Q,Y,H,W);if(Z.delete(Y),J!==void 0)Q.baseline.set(Y,J)}};await Promise.all(Array.from({length:Math.min(o0,$.length)},K))},ZQ=async function*(Q,$="basic"){let Z=$==="basic"?i0:l0;for await(let z of X(this,f,"f").beta.memoryStores.memories.list(Q,{view:$,limit:Z})){if(z.type!=="memory")continue;let q=z.path.replace(/^\/+/,"");if(q===n){X(this,G,"f").warn("the server listed the reserved marker path; skipping",{path:z.path,memory_store_id:Q});continue}yield[q,z]}},zQ=async function V(Q,$,Z,z){try{let q=await Q.files.get($);if(q===null)return;let K=iQ(q),Y=z?await X(this,f,"f").beta.memoryStores.memories.update(z.id,{memory_store_id:Q.memoryStoreId,content:K,precondition:{type:"content_sha256",content_sha256:z.content_sha256}}):await X(this,f,"f").beta.memoryStores.memories.create(Q.memoryStoreId,{path:"/"+$,content:K});return Q.refusedShas.delete($),Y.content_sha256}catch(q){if(z&&F(q,404))return await X(this,k,"m",V).call(this,Q,$,Z,void 0);let K=q instanceof D||F(q,400)||F(q,413);if(z&&F(q,409))X(this,G,"f").warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:$,memory_store_id:Q.memoryStoreId});else if(K&&Z!==void 0)Q.refusedShas.set($,Z),X(this,G,"f").warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:$,memory_store_id:Q.memoryStoreId,rejection:String(q)});else X(this,G,"f").warn("failed to upload memory",{path:$,memory_store_id:Q.memoryStoreId,error:String(q)});return}},hQ=async function(Q,$,Z,z,q){if(q.mode==="disabled")return q.suppressed++,z;let K=Q.pendingDeletes.get($);if(K===void 0)K=Date.now(),Q.pendingDeletes.set($,K);if(!q.waiveWindow&&Date.now()-K<n0)return z;let Y,H;try{Y=await Q.files.hashFile(n)===nQ(Q.memoryStoreId),H=await Q.files.hashFile($)===null}catch(J){if(!(J instanceof D)&&!i(J))throw J;Y=H=!1}if(!Y)return z;if(!H)return Q.pendingDeletes.delete($),z;if(!q.takeSlot())return z;if(q.mode==="log_only")return X(this,G,"f").info("log-only: sync would delete this memory on the server",{path:$,memory_store_id:Q.memoryStoreId}),z;let W=await X(this,k,"m",cQ).call(this,Q,$,Z,z);if(W===void 0)Q.pendingDeletes.delete($);return W},cQ=async function(Q,$,Z,z){try{await X(this,f,"f").beta.memoryStores.memories.delete(Z.id,{memory_store_id:Q.memoryStoreId,expected_content_sha256:z})}catch(q){if(F(q,404))return;if(F(q,409)||F(q,412))X(this,G,"f").warn("memory deleted locally but changed remotely; keeping the remote version",{path:$,memory_store_id:Q.memoryStoreId});else X(this,G,"f").warn("failed to delete memory",{path:$,memory_store_id:Q.memoryStoreId,error:String(q)});return z}X(this,G,"f").info("propagated local deletion",{path:$,memory_store_id:Q.memoryStoreId});return};function i(V){return typeof V==="object"&&V!==null&&typeof V.code==="string"}async function r0(V,Q){if(!Q){await V;return}let $,Z=new Promise((z)=>{if($=z,Q.aborted)z()});Q.addEventListener("abort",$,{once:!0});try{await Promise.race([V,Z])}finally{Q.removeEventListener("abort",$)}}var HQ,j,T,t,_,v,RQ,V0=102400,K0=120000,e0=262144,r=102400,Q1=2000,$1=200;class X0 extends R{constructor(V){super(`bash command timed out after ${V}ms`);this.name="BashTimeoutError",this.timeoutMs=V}}var V1=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,Z1=B.glob;function Y0(V){return V===void 0?e0:V}function S(V){if(V===void 0)return;throw new R("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function $2(V){return[q1(V),K1(V),X1(V),Y1(V),H1(V),W1(V)]}async function e(V,Q){return S(V.unrestrictedPaths),OQ(V.workdir,Q,{allowedRoots:V.allowedRoots??[]})}function J0(V,Q){return UQ(V.readOnlyRoots??[],Q)}function z1(){let V={};for(let[Q,$]of Object.entries(process.env)){if(Q.startsWith("ANTHROPIC_"))continue;V[Q]=$}return V}class H0{constructor(V,Q=z1()){HQ.add(this),j.set(this,void 0),T.set(this,""),t.set(this,!1),_.set(this,!1),v.set(this,null),w(this,j,BQ.spawn("/bin/bash",["--noprofile","--norc"],{cwd:V,env:{...Q,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),X(this,j,"f").stdout.setEncoding("utf8"),X(this,j,"f").stderr.setEncoding("utf8"),X(this,j,"f").stdout.on("data",($)=>X(this,HQ,"m",RQ).call(this,$)),X(this,j,"f").stderr.on("data",($)=>X(this,HQ,"m",RQ).call(this,$)),X(this,j,"f").once("close",()=>{w(this,_,!0,"f");let $=X(this,v,"f");w(this,v,null,"f"),$?.resolve()})}get closed(){return X(this,_,"f")}async exec(V,Q={}){if(X(this,_,"f"))throw new R("bash session terminated");let $=Q.timeoutMs??K0,Z=Q.signal;Z?.throwIfAborted(),w(this,T,"","f"),w(this,t,!1,"f");let z=`__ANT_CMD_${z0.randomUUID()}_DONE__`,q=`${z.slice(0,8)}''${z.slice(8)}`,K=`{ ${V}
|
|
8
|
-
} </dev/null 2>&1; printf '\\n${q}%d\\n' $?
|
|
9
|
-
`;if(X(this,j,"f").stdin.write(K),X(this,T,"f").indexOf(z)<0){let{promise:O,resolve:g}=IQ();w(this,v,{sentinel:z,resolve:g},"f");let b,P;try{await Promise.race([O,new Promise((C0,CQ)=>{b=setTimeout(()=>CQ(new X0($)),$)}),new Promise((C0,CQ)=>{if(!Z)return;P=()=>CQ(Z.reason),Z.addEventListener("abort",P,{once:!0})})])}finally{if(b)clearTimeout(b);if(P&&Z)Z.removeEventListener("abort",P);w(this,v,null,"f")}}let Y=X(this,T,"f").indexOf(z);if(Y<0)throw new R("bash session terminated");let W=X(this,T,"f").slice(Y+z.length).match(/^(-?\d+)/),J=W?parseInt(W[1],10):-1,U=X(this,T,"f").slice(0,Y).replace(V1,"").replace(/\n+$/,"");if(X(this,t,"f"))U=`[output truncated]
|
|
10
|
-
${U}`;return{output:U,exitCode:J}}close(){if(X(this,_,"f"))return;w(this,_,!0,"f");let V=X(this,v,"f");w(this,v,null,"f"),V?.resolve(),X(this,j,"f").stdout.destroy(),X(this,j,"f").stderr.destroy(),X(this,j,"f").stdin.destroy();try{process.kill(-X(this,j,"f").pid,"SIGKILL")}catch{X(this,j,"f").kill("SIGKILL")}X(this,j,"f").unref()}}j=new WeakMap,T=new WeakMap,t=new WeakMap,_=new WeakMap,v=new WeakMap,HQ=new WeakSet,RQ=function(Q){if(w(this,T,X(this,T,"f")+Q,"f"),X(this,T,"f").length>V0)w(this,T,X(this,T,"f").slice(X(this,T,"f").length-V0),"f"),w(this,t,!0,"f");if(X(this,v,"f")&&X(this,T,"f").indexOf(X(this,v,"f").sentinel)>=0){let $=X(this,v,"f");w(this,v,null,"f"),$.resolve()}};function q1(V){S(V.unrestrictedPaths);let Q,$=Promise.resolve();return u({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command:Z,restart:z,timeout_ms:q},K)=>{let Y=$,H=IQ();$=H.promise;try{await Y}catch{}try{if(z)Q?.close(),Q=void 0;if(!Z){if(z)return"bash session restarted";throw new C("bash: command is required")}Q??(Q=new H0(V.workdir,V.env));try{let{output:W,exitCode:J}=await Q.exec(Z,{timeoutMs:q??K0,signal:K?.signal});if(J!==0)throw new C(W||`exit ${J}`);return W}catch(W){if(W instanceof C)throw W;throw Q.close(),Q=void 0,new C(`bash: ${W instanceof Error?W.message:String(W)}`)}}finally{H.resolve()}},close:()=>{Q?.close(),Q=void 0}})}function K1(V){return S(V.unrestrictedPaths),u({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path:Q,view_range:$})=>{if(!Q)throw new C("read: file_path is required");let Z=await e(V,Q),z;try{let J=await B.stat(Z);if(!J.isFile())throw new C(`read: ${Q} is not a regular file`);let U=Y0(V.maxFileBytes);if(U!==null&&J.size>U)throw new C(`read: ${Q} is ${J.size} bytes, exceeds ${U}-byte limit. Use bash (head/tail/sed) to read a slice.`);z=await B.readFile(Z,"utf8")}catch(J){if(J instanceof C)throw J;throw new C(`read: ${p(J,Q)}`)}if(!$?.length)return z;if($.length!==2)throw new C("read: view_range must be [start_line, end_line]");let[q,K]=$,Y=z.split(`
|
|
11
|
-
`),H=Math.max(0,q-1),W=K>0?K:Y.length;return Y.slice(H,W).join(`
|
|
12
|
-
`)}})}function X1(V){return S(V.unrestrictedPaths),u({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path:Q,content:$})=>{if(!Q)throw new C("write: file_path is required");let Z=await e(V,Q),z=await J0(V,Z);if(z!==void 0)throw new C(`write: ${Q} is inside read-only directory ${z}`);try{await B.mkdir(y.dirname(Z),{recursive:!0,mode:a}),await DQ(Z,$??"")}catch(q){throw new C(`write: ${p(q,Q)}`)}return`wrote ${Buffer.byteLength($??"")} bytes to ${Q}`}})}function Y1(V){return S(V.unrestrictedPaths),u({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path:Q,old_string:$,new_string:Z,replace_all:z})=>{if(!Q)throw new C("edit: file_path is required");if(!$)throw new C("edit: old_string is required");let q=await e(V,Q),K=await J0(V,q);if(K!==void 0)throw new C(`edit: ${Q} is inside read-only directory ${K}`);let Y;try{let J=await B.stat(q);if(!J.isFile())throw new C(`edit: ${Q} is not a regular file`);let U=Y0(V.maxFileBytes);if(U!==null&&J.size>U)throw new C(`edit: ${Q} is ${J.size} bytes, exceeds ${U}-byte limit. Use bash (sed/awk) to edit a large file.`);Y=await B.readFile(q,"utf8")}catch(J){if(J instanceof C)throw J;throw new C(`edit: ${p(J,Q)}`)}let H=Y.split($).length-1;if(H===0)throw new C(`edit: old_string not found in ${Q}`);let W;if(z)W=Y.split($).join(Z);else{if(H>1)throw new C(`edit: old_string appears ${H} times in ${Q} (must be unique)`);W=Y.replace($,()=>Z)}try{await DQ(q,W)}catch(J){throw new C(`edit: write: ${p(J,Q)}`)}return`edited ${Q} (${z?H:1} replacement(s))`}})}function J1(V){return V.split(/[\\/{},]/).includes("..")}function H1(V){return S(V.unrestrictedPaths),u({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern:Q,path:$})=>{if(!Q)throw new C("glob: pattern is required");if(y.isAbsolute(Q))throw new C("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(J1(Q))throw new C('glob: ".." is not permitted in the pattern');let Z=$?await e(V,$):y.resolve(V.workdir),z=$?Z:await l(Z),q=[],K=W0;try{for await(let Y of Z1(Q,{cwd:Z,withFileTypes:!0,exclude:(H)=>H.name===".git"||H.name==="node_modules"})){if(K--<=0)break;if(!Y.isFile())continue;let H=y.join(Y.parentPath,Y.name),W;try{W=await B.realpath(H)}catch{continue}if(!QQ(z,W))continue;let J=0;try{J=(await B.stat(H)).mtimeMs}catch{}q.push({path:H,mtime:J})}}catch(Y){throw new C(`glob: ${Y instanceof Error?Y.message:String(Y)}`)}if(q.length===0)return"no matches";return q.sort((Y,H)=>H.mtime-Y.mtime),q.slice(0,$1).map((Y)=>Y.path).join(`
|
|
13
|
-
`)}})}function W1(V){return S(V.unrestrictedPaths),u({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern:Q,path:$},Z)=>{if(!Q)throw new C("grep: pattern is required");let z=y.resolve(V.workdir);if($)z=await e(V,$);let q=await N1();return q?C1(q,Q,z,Z?.signal):U1(Q,z,Z?.signal)}})}function C1(V,Q,$,Z){return new Promise((z,q)=>{let K=BQ.spawn(V,["-n","--no-heading","-e",Q,"--",$],{...Z?{signal:Z}:{}}),Y="",H="",W=!1;K.stdout.on("data",(J)=>{if(W)return;if(Y+=J,Y.length>r)W=!0,Y=Y.slice(0,r),K.kill("SIGKILL")}),K.stderr.on("data",(J)=>H+=J),K.on("close",(J)=>{if(Z?.aborted)return q(new C("grep: aborted"));if(W)return z(Y+`
|
|
14
|
-
[output truncated at ${r} bytes]`);if(J===0)return z(Y);if(J===1)return z("no matches");q(new C(`grep: rg failed: ${H||`exit ${J}`}`))}),K.on("error",(J)=>{if(Z?.aborted)return q(new C("grep: aborted"));q(new C(`grep: rg failed: ${J.message}`))})})}async function U1(V,Q,$){let Z;try{Z=new RegExp(V)}catch(H){throw new C(`grep: invalid regex: ${H instanceof Error?H.message:String(H)}`)}let z=[],q=r,K=(H)=>{if(q-=H.length+1,q<0)return z.push(`[output truncated at ${r} bytes]`),!1;return z.push(H),!0};if((await B.stat(Q).catch(()=>null))?.isFile())await Z0(Q,Z,K);else await G1(Q,"",(H)=>Z0(y.join(Q,H),Z,K),$);if($?.aborted)throw new C("grep: aborted");if(z.length===0)return"no matches";return z.join(`
|
|
15
|
-
`)}async function Z0(V,Q,$){let Z=WQ.createReadStream(V,{encoding:"utf8"}),z=q0.createInterface({input:Z,crlfDelay:1/0}),q=0;try{for await(let K of z){if(q++,K.length>Q1)continue;if(Q.test(K)&&!$(`${V}:${q}:${K}`))return!1}}catch{}finally{Z.destroy()}return!0}var D1=40,W0=50000;async function G1(V,Q,$,Z){let z=W0;async function q(K,Y){if(Y>D1)return!0;if(Z?.aborted)return!1;let H;try{H=await B.readdir(y.join(V,K),{withFileTypes:!0})}catch{return!0}for(let W of H){if(W.name===".git"||W.name==="node_modules")continue;if(z--<=0)return!1;if(Z?.aborted)return!1;let J=K?y.join(K,W.name):W.name;if(W.isDirectory()){if(!await q(J,Y+1))return!1}else if(W.isFile()){if(await $(J)===!1)return!1}}return!0}await q(Q,0)}async function N1(){let V=(process.env.PATH??"").split(y.delimiter);for(let Q of V){let $=y.join(Q,"rg");try{return await B.access($,WQ.constants.X_OK),$}catch{}}return null}export{M0 as setupSkills,TQ as resolveSkillVersion,e as resolvePath,vQ as extractSkillArchive,X1 as betaWriteTool,K1 as betaReadTool,W1 as betaGrepTool,H1 as betaGlobTool,Y1 as betaEditTool,q1 as betaBashTool,$2 as betaAgentToolset20260401,$0 as SessionMemoryStores,m as SessionMemoryError,lQ as MIN_MEMORY_SYNC_INTERVAL_MS,c0 as MEMORY_FLUSH_TIMEOUT_MS,n as MARKER_PATH,JQ as DEFAULT_MEMORY_SYNC_INTERVAL_MS,X0 as BashTimeoutError,H0 as BashSession};
|
package/dist/chunk-k62w2v03.js
DELETED
package/dist/chunk-mcrfxphm.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Cd as _}from"./chunk-vagxqhef.js";import{Hd as C,Id as I}from"./chunk-ts35hc5t.js";import{ee as N}from"./chunk-16yqbccr.js";var x=["major","minor","patch","all"],M=["merge","squash","rebase"],T=["patch-only","minor-only","security-only","all"],O=["anthropic","openai","google","openrouter","openai-compatible"],m=["low","medium","high"],P=["chill","assertive"],R=["never","critical"],A=["low","moderate","high","critical"],S=["silent","error","warn","info","debug"],d=["npm","composer","github-actions","docker","pkgx","zig","python","rust","go","ruby"],b=["major","minor","patch"],L=_.map((J)=>J.name);function K(J){return JSON.stringify(J)}function H(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}function F(J,B,X,$){if(X===void 0)return;if(typeof X!=="string"||!$.includes(X))J.push({path:B,message:`expected one of ${$.map(K).join(", ")}, got ${K(X)}`})}function V(J,B,X,$={}){let Q=$.min??0,W=$.integer??!1;if(X===void 0)return;if(typeof X!=="number"||!Number.isFinite(X)||X<Q){J.push({path:B,message:`expected a number >= ${Q}, got ${K(X)}`});return}if(W&&!Number.isInteger(X))J.push({path:B,message:`expected a whole number, got ${K(X)}`})}function U(J,B,X,$){if(X===void 0)return;if(!Array.isArray(X)){J.push({path:B,message:`expected an array, got ${K(X)}`});return}X.forEach((Q,W)=>F(J,`${B}[${W}]`,Q,$))}function z(J,B,X){if(X===void 0)return;if(!Array.isArray(X)){J.push({path:B,message:`expected an array of strings, got ${K(X)}`});return}X.forEach(($,Q)=>{if(typeof $!=="string"||!$.trim())J.push({path:`${B}[${Q}]`,message:`expected a non-empty string, got ${K($)}`})})}function G(J,B,X){if(X===void 0)return;if(typeof X!=="string"){J.push({path:B,message:`expected a URL string, got ${K(X)}`});return}try{let $=new URL(X);if($.protocol!=="http:"&&$.protocol!=="https:")J.push({path:B,message:`expected an http(s) URL, got ${K(X)}`})}catch{J.push({path:B,message:`expected a valid absolute URL, got ${K(X)}`})}}function D(J,B,X){if(X===void 0)return;if(typeof X!=="string"||!X.trim()){J.push({path:B,message:`expected a cron expression string, got ${K(X)}`});return}let $=X.trim().split(/\s+/);if($.length!==5&&$.length!==6)J.push({path:B,message:`expected 5 or 6 whitespace-separated fields, got ${$.length} (${K(X)})`})}function w(J){let B=[];if(J.verbose!==void 0&&typeof J.verbose!=="boolean")B.push({path:"verbose",message:`expected a boolean, got ${K(J.verbose)}`});return F(B,"logLevel",J.logLevel,S),V(B,"maxPRsPerRun",J.maxPRsPerRun,{min:1,integer:!0}),p(B,J),f(B,J),v(B,J),g(B,J),n(B,J),c(B,J),l(B,J),t(B,J),k(B,J),q(B,J),B}function E(J,B){if(B===void 0)return;if(!H(B)){J.push({path:"registries.docker",message:`expected an object keyed by registry host, got ${K(B)}`});return}for(let[X,$]of Object.entries(B)){let Q=`registries.docker.${X}`;if(!H($)){J.push({path:Q,message:`expected an object, got ${K($)}`});continue}for(let W of["username","passwordEnv","tokenEnv"]){let Y=$[W];if(Y!==void 0&&(typeof Y!=="string"||!Y.trim()))J.push({path:`${Q}.${W}`,message:`expected a non-empty string, got ${K(Y)}`})}if($.username&&!$.passwordEnv&&!$.tokenEnv)J.push({path:`${Q}.passwordEnv`,message:"is required when a username is given"});if($.passwordEnv&&!$.username)J.push({path:`${Q}.username`,message:"is required when passwordEnv is given"})}}function q(J,B){let X=B.analysis;if(X===void 0)return;if(!H(X)){J.push({path:"analysis",message:`expected an object, got ${K(X)}`});return}if(X.enabled!==void 0&&typeof X.enabled!=="boolean")J.push({path:"analysis.enabled",message:`expected a boolean, got ${K(X.enabled)}`});if(X.tools===void 0)return;if(!H(X.tools)){J.push({path:"analysis.tools",message:`expected an object mapping analyzer names to booleans, got ${K(X.tools)}`});return}for(let[$,Q]of Object.entries(X.tools))if(typeof Q!=="boolean")J.push({path:`analysis.tools.${$}`,message:`expected a boolean, got ${K(Q)}`});else if(!L.includes($))J.push({path:`analysis.tools.${$}`,message:`unknown analyzer; expected one of ${L.map(K).join(", ")}`})}function p(J,B){let X=B.repository;if(X===void 0)return;if(!H(X)){J.push({path:"repository",message:`expected an object, got ${K(X)}`});return}if(X.provider!==void 0&&!C.includes(X.provider)){let $=I[String(X.provider)];J.push({path:"repository.provider",message:$?`${K(X.provider)} support is not implemented yet \u2014 follow ${$}`:`only ${C.map(K).join(", ")} is supported, got ${K(X.provider)}`})}for(let $ of["owner","name","baseBranch","token"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="string")J.push({path:`repository.${$}`,message:`expected a string, got ${K(Q)}`})}G(J,"repository.apiUrl",X.apiUrl),G(J,"repository.serverUrl",X.serverUrl)}function f(J,B){let X=B.packages;if(X===void 0)return;if(!H(X)){J.push({path:"packages",message:`expected an object, got ${K(X)}`});return}F(J,"packages.strategy",X.strategy,x),z(J,"packages.ignore",X.ignore),z(J,"packages.ignorePaths",X.ignorePaths),z(J,"packages.minimumReleaseAgeExclude",X.minimumReleaseAgeExclude),V(J,"packages.minimumReleaseAge",X.minimumReleaseAge,{min:0});for(let $ of["includePrerelease","excludeMajor","respectLatest"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`packages.${$}`,message:`expected a boolean, got ${K(Q)}`})}if(X.pin!==void 0){if(!H(X.pin))J.push({path:"packages.pin",message:`expected an object mapping package names to versions, got ${K(X.pin)}`});else for(let[$,Q]of Object.entries(X.pin))if(typeof Q!=="string"||!Q.trim())J.push({path:`packages.pin.${$}`,message:`expected a version string, got ${K(Q)}`})}if(X.groups!==void 0){if(!Array.isArray(X.groups)){J.push({path:"packages.groups",message:`expected an array of groups, got ${K(X.groups)}`});return}X.groups.forEach(($,Q)=>{let W=`packages.groups[${Q}]`;if(!H($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}if(typeof $.name!=="string"||!$.name.trim())J.push({path:`${W}.name`,message:`expected a non-empty string, got ${K($.name)}`});if(!Array.isArray($.patterns)||$.patterns.length===0)J.push({path:`${W}.patterns`,message:`expected a non-empty array of patterns, got ${K($.patterns)}`});else z(J,`${W}.patterns`,$.patterns);F(J,`${W}.strategy`,$.strategy,x)})}y(J,X.rules)}var j=["matchPackages","matchEcosystems","matchDepTypes","matchUpdateTypes","matchFiles","matchCurrentVersion","schedule"],h=["enabled","strategy","groupName","labels","reviewers","assignees","autoMerge","autoMigrate","minimumReleaseAge","prPriority","scheduleTimezone"];function y(J,B){if(B===void 0)return;if(!Array.isArray(B)){J.push({path:"packages.rules",message:`expected an array of rules, got ${K(B)}`});return}let X=new Set([...j,...h]);B.forEach(($,Q)=>{let W=`packages.rules[${Q}]`;if(!H($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}for(let Z of Object.keys($))if(!X.has(Z))J.push({path:`${W}.${Z}`,message:`unknown key; expected one of ${[...X].map(K).join(", ")}`});if(!j.some((Z)=>$[Z]!==void 0))J.push({path:W,message:'has no matchers, so it applies to every update \u2014 add `matchPackages: ["*"]` if that is intended'});if(z(J,`${W}.matchPackages`,$.matchPackages),z(J,`${W}.matchDepTypes`,$.matchDepTypes),z(J,`${W}.matchFiles`,$.matchFiles),z(J,`${W}.labels`,$.labels),z(J,`${W}.reviewers`,$.reviewers),z(J,`${W}.assignees`,$.assignees),U(J,`${W}.matchEcosystems`,$.matchEcosystems,d),U(J,`${W}.matchUpdateTypes`,$.matchUpdateTypes,b),F(J,`${W}.strategy`,$.strategy,x),V(J,`${W}.minimumReleaseAge`,$.minimumReleaseAge,{min:0}),$.prPriority!==void 0&&typeof $.prPriority!=="number")J.push({path:`${W}.prPriority`,message:`expected a number, got ${K($.prPriority)}`});for(let Z of["enabled","autoMerge","autoMigrate"])if($[Z]!==void 0&&typeof $[Z]!=="boolean")J.push({path:`${W}.${Z}`,message:`expected a boolean, got ${K($[Z])}`});for(let Z of["groupName","matchCurrentVersion","scheduleTimezone"])if($[Z]!==void 0&&(typeof $[Z]!=="string"||!String($[Z]).trim()))J.push({path:`${W}.${Z}`,message:`expected a non-empty string, got ${K($[Z])}`});D(J,`${W}.schedule`,$.schedule)})}function v(J,B){let X=B.pullRequest;if(X===void 0)return;if(!H(X)){J.push({path:"pullRequest",message:`expected an object, got ${K(X)}`});return}z(J,"pullRequest.reviewers",X.reviewers),z(J,"pullRequest.assignees",X.assignees),z(J,"pullRequest.labels",X.labels);let $=X.autoMerge;if($!==void 0){if(!H($)){J.push({path:"pullRequest.autoMerge",message:`expected an object, got ${K($)}`});return}if($.enabled!==void 0&&typeof $.enabled!=="boolean")J.push({path:"pullRequest.autoMerge.enabled",message:`expected a boolean, got ${K($.enabled)}`});if(F(J,"pullRequest.autoMerge.strategy",$.strategy,M),z(J,"pullRequest.autoMerge.conditions",$.conditions),Array.isArray($.conditions))for(let[Q,W]of $.conditions.entries())F(J,`pullRequest.autoMerge.conditions[${Q}]`,W,T);if($.requireGreenCI!==void 0&&typeof $.requireGreenCI!=="boolean")J.push({path:"pullRequest.autoMerge.requireGreenCI",message:`expected a boolean, got ${K($.requireGreenCI)}`});if($.optOutLabel!==void 0&&typeof $.optOutLabel!=="string")J.push({path:"pullRequest.autoMerge.optOutLabel",message:`expected a string, got ${K($.optOutLabel)}`})}}function k(J,B){let X=B.ai;if(X===void 0)return;if(!H(X)){J.push({path:"ai",message:`expected an object, got ${K(X)}`});return}if(X.enabled!==void 0&&typeof X.enabled!=="boolean")J.push({path:"ai.enabled",message:`expected a boolean, got ${K(X.enabled)}`});F(J,"ai.provider",X.provider,O),F(J,"ai.effort",X.effort,m);for(let Q of["model","apiKeyEnv","baseUrl"])if(X[Q]!==void 0&&typeof X[Q]!=="string")J.push({path:`ai.${Q}`,message:`expected a string, got ${K(X[Q])}`});if(typeof X.apiKeyEnv==="string"&&/^sk-|^AIza/.test(X.apiKeyEnv))J.push({path:"ai.apiKeyEnv",message:"expected the NAME of an environment variable, not an API key"});let $=X.review;if($!==void 0)if(!H($))J.push({path:"ai.review",message:`expected an object, got ${K($)}`});else{for(let Q of["enabled","drafts","autoReview","summaryOnly"])if($[Q]!==void 0&&typeof $[Q]!=="boolean")J.push({path:`ai.review.${Q}`,message:`expected a boolean, got ${K($[Q])}`});if(F(J,"ai.review.profile",$.profile,P),F(J,"ai.review.requestChangesOn",$.requestChangesOn,R),z(J,"ai.review.ignoreTitleKeywords",$.ignoreTitleKeywords),z(J,"ai.review.ignoreUsernames",$.ignoreUsernames),z(J,"ai.review.pathFilters",$.pathFilters),$.instructions!==void 0&&typeof $.instructions!=="string")J.push({path:"ai.review.instructions",message:`expected a string, got ${K($.instructions)}`});if($.guidelineFiles!==void 0&&$.guidelineFiles!==!1)z(J,"ai.review.guidelineFiles",$.guidelineFiles);if($.pathInstructions!==void 0)if(!Array.isArray($.pathInstructions))J.push({path:"ai.review.pathInstructions",message:`expected an array, got ${K($.pathInstructions)}`});else $.pathInstructions.forEach((Q,W)=>{let Y=`ai.review.pathInstructions[${W}]`;if(!H(Q)){J.push({path:Y,message:`expected an object, got ${K(Q)}`});return}for(let Z of["path","instructions"])if(typeof Q[Z]!=="string"||!Q[Z].trim())J.push({path:`${Y}.${Z}`,message:`expected a non-empty string, got ${K(Q[Z])}`})})}if(X.maxTokensPerRun!==void 0){if(typeof X.maxTokensPerRun!=="number"||!Number.isFinite(X.maxTokensPerRun)||X.maxTokensPerRun<=0)J.push({path:"ai.maxTokensPerRun",message:`expected a positive number, got ${K(X.maxTokensPerRun)}`})}}function g(J,B){let X=B.registries;if(X===void 0)return;if(!H(X)){J.push({path:"registries",message:`expected an object, got ${K(X)}`});return}if(E(J,X.docker),G(J,"registries.npm",X.npm),G(J,"registries.composer",X.composer),X.npmScopes!==void 0){if(!H(X.npmScopes)){J.push({path:"registries.npmScopes",message:`expected an object keyed by scope, got ${K(X.npmScopes)}`});return}for(let[$,Q]of Object.entries(X.npmScopes)){if(!$.startsWith("@"))J.push({path:`registries.npmScopes.${$}`,message:`scope keys must start with "@", got ${K($)}`});G(J,`registries.npmScopes.${$}`,Q)}}}function n(J,B){let X=B.security;if(X===void 0)return;if(!H(X)){J.push({path:"security",message:`expected an object, got ${K(X)}`});return}for(let $ of["enabled","prioritize"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`security.${$}`,message:`expected a boolean, got ${K(Q)}`})}if(X.label!==void 0&&(typeof X.label!=="string"||!X.label.trim()))J.push({path:"security.label",message:`expected a non-empty string, got ${K(X.label)}`});F(J,"security.minimumSeverity",X.minimumSeverity,A)}function c(J,B){if(B.schedule!==void 0){if(!H(B.schedule))J.push({path:"schedule",message:`expected an object, got ${K(B.schedule)}`});else if(D(J,"schedule.cron",B.schedule.cron),B.schedule.timezone!==void 0&&typeof B.schedule.timezone!=="string")J.push({path:"schedule.timezone",message:`expected a string, got ${K(B.schedule.timezone)}`})}let X=B.workflows?.custom;if(X===void 0)return;if(!Array.isArray(X)){J.push({path:"workflows.custom",message:`expected an array, got ${K(X)}`});return}X.forEach(($,Q)=>{let W=`workflows.custom[${Q}]`;if(!H($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}if(typeof $.name!=="string"||!$.name.trim())J.push({path:`${W}.name`,message:`expected a non-empty string, got ${K($.name)}`});D(J,`${W}.schedule`,$.schedule),F(J,`${W}.strategy`,$.strategy,x),z(J,`${W}.reviewers`,$.reviewers),z(J,`${W}.assignees`,$.assignees),z(J,`${W}.labels`,$.labels)})}function l(J,B){let X=B.releaseNotes;if(X===void 0)return;if(!H(X)){J.push({path:"releaseNotes",message:`expected an object, got ${K(X)}`});return}for(let $ of["enabled","sanitizeReferences","includeCompareLinks"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`releaseNotes.${$}`,message:`expected a boolean, got ${K(Q)}`})}V(J,"releaseNotes.maxReleases",X.maxReleases,{min:1,integer:!0}),V(J,"releaseNotes.maxBodyLength",X.maxBodyLength,{min:1,integer:!0})}function t(J,B){let X=B.dashboard;if(X===void 0)return;if(!H(X)){J.push({path:"dashboard",message:`expected an object, got ${K(X)}`});return}if(z(J,"dashboard.labels",X.labels),z(J,"dashboard.assignees",X.assignees),V(J,"dashboard.issueNumber",X.issueNumber,{min:1,integer:!0}),X.title!==void 0&&(typeof X.title!=="string"||!X.title.trim()))J.push({path:"dashboard.title",message:`expected a non-empty string, got ${K(X.title)}`})}function o(J){return J.map((B)=>` \u2022 ${B.path}: ${B.message}`).join(`
|
|
3
|
-
`)}function u(J){let B=w(J);if(B.length===0)return;throw new N(`Invalid buddy configuration (${B.length} issue${B.length===1?"":"s"}):
|
|
4
|
-
${o(B)}`,B[0].path)}
|
|
5
|
-
export{w as Fc,o as Gc,u as Hc};
|
package/dist/chunk-mh3x7j6h.js
DELETED