@buddysh/buddy 0.11.0
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 +1633 -0
- package/LICENSE.md +21 -0
- package/README.md +1087 -0
- package/bin/cli.ts +3401 -0
- package/dist/bin/cli.d.ts +1 -0
- package/dist/bin/cli.js +188 -0
- package/dist/chunk-0j7z87kh.js +3 -0
- package/dist/chunk-0r8zt3d7.js +2 -0
- package/dist/chunk-16yqbccr.js +3 -0
- package/dist/chunk-1a53wj0h.js +1 -0
- package/dist/chunk-1c1gznm9.js +3 -0
- package/dist/chunk-1h3ey7k5.js +3 -0
- package/dist/chunk-1stt2whn.js +62 -0
- package/dist/chunk-1wjnd24b.js +24 -0
- package/dist/chunk-1xe07hzm.js +2 -0
- package/dist/chunk-2bp7tqca.js +2 -0
- package/dist/chunk-2dbkpfy9.js +2 -0
- package/dist/chunk-3q6czqs4.js +6 -0
- package/dist/chunk-3zdcekfj.js +5 -0
- package/dist/chunk-49ey79p0.js +5 -0
- package/dist/chunk-4c9m61yd.js +5 -0
- package/dist/chunk-4efbxdjr.js +4 -0
- package/dist/chunk-4f7panqj.js +21 -0
- package/dist/chunk-4hd3rre0.js +2 -0
- package/dist/chunk-4xsq18p3.js +9 -0
- package/dist/chunk-52x8mvh4.js +15 -0
- package/dist/chunk-54sc18p8.js +2 -0
- package/dist/chunk-56q4pwb5.js +3 -0
- package/dist/chunk-5c3qf34r.js +2 -0
- package/dist/chunk-5k40mwd4.js +4 -0
- package/dist/chunk-5kt03hx5.js +2 -0
- package/dist/chunk-63ept76v.js +2 -0
- package/dist/chunk-65b3vq52.js +2 -0
- package/dist/chunk-6d9hmjt8.js +3 -0
- package/dist/chunk-6g1y9yqh.js +3 -0
- package/dist/chunk-6k653r8w.js +2 -0
- package/dist/chunk-6md7qf2g.js +4 -0
- package/dist/chunk-6patq6bw.js +2 -0
- package/dist/chunk-6sgh49z1.js +2 -0
- package/dist/chunk-74pxb991.js +7 -0
- package/dist/chunk-7mgec8kb.js +7 -0
- package/dist/chunk-7tfrww3v.js +2 -0
- package/dist/chunk-7xk28xrv.js +2 -0
- package/dist/chunk-82dv4p13.js +2 -0
- package/dist/chunk-8661pvb8.js +3 -0
- package/dist/chunk-887s0w81.js +2 -0
- package/dist/chunk-8rc6042h.js +4 -0
- package/dist/chunk-9750tenz.js +3 -0
- package/dist/chunk-978wtejw.js +44 -0
- package/dist/chunk-9eqpaxfz.js +2 -0
- package/dist/chunk-9h04nskh.js +8 -0
- package/dist/chunk-9p1xkmjy.js +2 -0
- package/dist/chunk-agdesgzv.js +2 -0
- package/dist/chunk-akffynkc.js +3 -0
- package/dist/chunk-ar01x04a.js +2 -0
- package/dist/chunk-ay43f085.js +2 -0
- package/dist/chunk-bk9bqd5j.js +2 -0
- package/dist/chunk-bm8d40j0.js +69 -0
- package/dist/chunk-bxfc4g2x.js +73 -0
- package/dist/chunk-c3fczawt.js +2 -0
- package/dist/chunk-c9r9nd4t.js +1 -0
- package/dist/chunk-ctsz0ynx.js +3 -0
- package/dist/chunk-czremqk7.js +2 -0
- package/dist/chunk-da3wbh04.js +2 -0
- package/dist/chunk-dat582cg.js +2 -0
- package/dist/chunk-dfesffnr.js +3 -0
- package/dist/chunk-djntbp7a.js +105 -0
- package/dist/chunk-eagjp0dh.js +3 -0
- package/dist/chunk-eht72nnj.js +2 -0
- package/dist/chunk-f4nv5x3z.js +2 -0
- package/dist/chunk-fdfk918n.js +2 -0
- package/dist/chunk-fdj0tewy.js +20 -0
- package/dist/chunk-fm8ckj9b.js +2 -0
- package/dist/chunk-fqj7e6xa.js +2 -0
- package/dist/chunk-frm8zz31.js +2 -0
- package/dist/chunk-fvpr07dn.js +16 -0
- package/dist/chunk-g0nv8psv.js +2 -0
- package/dist/chunk-g0w8n555.js +19 -0
- package/dist/chunk-gkmvxjbe.js +2 -0
- package/dist/chunk-gngwjf70.js +7 -0
- package/dist/chunk-h7hs95wn.js +5 -0
- package/dist/chunk-hfvezfxh.js +3 -0
- package/dist/chunk-hw70wbzg.js +3 -0
- package/dist/chunk-j8asz4hb.js +15 -0
- package/dist/chunk-k62w2v03.js +2 -0
- package/dist/chunk-mcrfxphm.js +5 -0
- package/dist/chunk-mh3x7j6h.js +2 -0
- package/dist/chunk-naq32yx3.js +86 -0
- package/dist/chunk-nsmcjkas.js +2 -0
- package/dist/chunk-p1xm1jvz.js +2 -0
- package/dist/chunk-p3wsm8kz.js +2 -0
- package/dist/chunk-p4zwy518.js +4 -0
- package/dist/chunk-p7zgy37f.js +2 -0
- package/dist/chunk-ph1b3vbp.js +315 -0
- package/dist/chunk-pkjm2r0a.js +2 -0
- package/dist/chunk-pkkwb0n0.js +4 -0
- package/dist/chunk-pnpx1kqn.js +6 -0
- package/dist/chunk-q9n79dd3.js +3 -0
- package/dist/chunk-qpz9k66h.js +2 -0
- package/dist/chunk-qvn1rtgp.js +2 -0
- package/dist/chunk-qyf90zz3.js +2 -0
- package/dist/chunk-r06ce5g6.js +2 -0
- package/dist/chunk-r2sbprdb.js +49 -0
- package/dist/chunk-r3zyw8x0.js +3 -0
- package/dist/chunk-rb1fh9vd.js +1 -0
- package/dist/chunk-rqdep14r.js +2 -0
- package/dist/chunk-s1km8cyq.js +2 -0
- package/dist/chunk-s4ms8zag.js +2 -0
- package/dist/chunk-sp818c27.js +9 -0
- package/dist/chunk-tb5y0350.js +3 -0
- package/dist/chunk-thaxgm5p.js +2 -0
- package/dist/chunk-tn8prpny.js +503 -0
- package/dist/chunk-ts35hc5t.js +3 -0
- package/dist/chunk-tzs22es2.js +3 -0
- package/dist/chunk-vagxqhef.js +13 -0
- package/dist/chunk-vh504tcv.js +6 -0
- package/dist/chunk-vkctfqpm.js +3 -0
- package/dist/chunk-vyapg8ca.js +186 -0
- package/dist/chunk-wdwvt7gb.js +43 -0
- package/dist/chunk-wtjhehz9.js +4 -0
- package/dist/chunk-x0ya2r4r.js +3 -0
- package/dist/chunk-x3kragh9.js +12 -0
- package/dist/chunk-x9ctz1qc.js +1 -0
- package/dist/chunk-xakpdqaq.js +3 -0
- package/dist/chunk-xqx460y2.js +3 -0
- package/dist/chunk-xvptf9jy.js +3 -0
- package/dist/chunk-yk23nc4t.js +2 -0
- package/dist/chunk-yncea6ty.js +2 -0
- package/dist/chunk-yq0gxtzv.js +2 -0
- package/dist/chunk-yqhs08ky.js +2 -0
- package/dist/chunk-zb62jhwm.js +31 -0
- package/dist/chunk-zs3jaj0g.js +1023 -0
- package/dist/chunk-zve5d96e.js +2 -0
- package/dist/src/agent/index.d.ts +44 -0
- package/dist/src/agent/modes.d.ts +33 -0
- package/dist/src/agent/runner.d.ts +44 -0
- package/dist/src/agent/stacked.d.ts +83 -0
- package/dist/src/agent/tasks.d.ts +41 -0
- package/dist/src/agent/toolbelt.d.ts +19 -0
- package/dist/src/agent/tools/fs.d.ts +26 -0
- package/dist/src/agent/tools/shell.d.ts +32 -0
- package/dist/src/agent/types.d.ts +56 -0
- package/dist/src/ai/aliases.d.ts +62 -0
- package/dist/src/ai/client.d.ts +42 -0
- package/dist/src/ai/index.d.ts +35 -0
- package/dist/src/ai/learnings.d.ts +78 -0
- package/dist/src/ai/providers/anthropic.d.ts +12 -0
- package/dist/src/ai/providers/google.d.ts +12 -0
- package/dist/src/ai/providers/openai.d.ts +15 -0
- package/dist/src/ai/redact.d.ts +30 -0
- package/dist/src/ai/types.d.ts +75 -0
- package/dist/src/analysis/analyzers/actionlint.d.ts +11 -0
- package/dist/src/analysis/analyzers/external.d.ts +57 -0
- package/dist/src/analysis/analyzers/github-actions.d.ts +9 -0
- package/dist/src/analysis/analyzers/hadolint.d.ts +9 -0
- package/dist/src/analysis/analyzers/linter.d.ts +53 -0
- package/dist/src/analysis/analyzers/markdownlint.d.ts +11 -0
- package/dist/src/analysis/analyzers/secrets.d.ts +23 -0
- package/dist/src/analysis/analyzers/shellcheck.d.ts +8 -0
- package/dist/src/analysis/analyzers/syntax.d.ts +13 -0
- package/dist/src/analysis/engine.d.ts +38 -0
- package/dist/src/analysis/index.d.ts +13 -0
- package/dist/src/analysis/types.d.ts +14 -0
- package/dist/src/buddy.d.ts +17 -0
- package/dist/src/ci/classify.d.ts +49 -0
- package/dist/src/ci/fix.d.ts +42 -0
- package/dist/src/ci/index.d.ts +8 -0
- package/dist/src/commands/dispatcher.d.ts +49 -0
- package/dist/src/commands/handlers.d.ts +23 -0
- package/dist/src/commands/index.d.ts +22 -0
- package/dist/src/commands/parser.d.ts +71 -0
- package/dist/src/config-validation.d.ts +38 -0
- package/dist/src/config.d.ts +22 -0
- package/dist/src/dashboard/dashboard-generator.d.ts +10 -0
- package/dist/src/doctor.d.ts +44 -0
- package/dist/src/ecosystems/go.d.ts +10 -0
- package/dist/src/ecosystems/index.d.ts +60 -0
- package/dist/src/ecosystems/pep440.d.ts +57 -0
- package/dist/src/ecosystems/python.d.ts +12 -0
- package/dist/src/ecosystems/ruby.d.ts +9 -0
- package/dist/src/ecosystems/rust.d.ts +8 -0
- package/dist/src/ecosystems/scan.d.ts +49 -0
- package/dist/src/ecosystems/shared.d.ts +45 -0
- package/dist/src/ecosystems/types.d.ts +58 -0
- package/dist/src/events/bus.d.ts +41 -0
- package/dist/src/events/index.d.ts +11 -0
- package/dist/src/events/sinks.d.ts +33 -0
- package/dist/src/gates/ai-checks.d.ts +77 -0
- package/dist/src/gates/checks.d.ts +84 -0
- package/dist/src/gates/index.d.ts +17 -0
- package/dist/src/gates/post-merge.d.ts +56 -0
- package/dist/src/git/bitbucket-provider.d.ts +50 -0
- package/dist/src/git/github-provider.d.ts +50 -0
- package/dist/src/git/gitlab-provider.d.ts +51 -0
- package/dist/src/git/provider.d.ts +210 -0
- package/dist/src/headless/run.d.ts +78 -0
- package/dist/src/index.d.ts +243 -0
- package/dist/src/index.js +2 -0
- package/dist/src/issues/enrichment.d.ts +76 -0
- package/dist/src/issues/index.d.ts +16 -0
- package/dist/src/issues/quick-links.d.ts +55 -0
- package/dist/src/pr/auto-merge.d.ts +75 -0
- package/dist/src/pr/pr-generator.d.ts +9 -0
- package/dist/src/pr/pr-manifest.d.ts +82 -0
- package/dist/src/pr/templates.d.ts +44 -0
- package/dist/src/registry/docker-tags.d.ts +56 -0
- package/dist/src/registry/eol.d.ts +87 -0
- package/dist/src/registry/oci-client.d.ts +98 -0
- package/dist/src/registry/registry-client.d.ts +39 -0
- package/dist/src/reports/history.d.ts +51 -0
- package/dist/src/reports/index.d.ts +23 -0
- package/dist/src/reports/metrics.d.ts +89 -0
- package/dist/src/reports/render.d.ts +33 -0
- package/dist/src/review/diff.d.ts +50 -0
- package/dist/src/review/engine.d.ts +49 -0
- package/dist/src/review/findings.d.ts +102 -0
- package/dist/src/review/guidelines.d.ts +46 -0
- package/dist/src/review/index.d.ts +48 -0
- package/dist/src/review/local.d.ts +81 -0
- package/dist/src/review/marker.d.ts +34 -0
- package/dist/src/review/poster.d.ts +39 -0
- package/dist/src/review/run.d.ts +24 -0
- package/dist/src/rules/engine.d.ts +108 -0
- package/dist/src/rules/index.d.ts +9 -0
- package/dist/src/rules/renovate.d.ts +25 -0
- package/dist/src/rules/schedule.d.ts +44 -0
- package/dist/src/scanner/catalog-scan.d.ts +39 -0
- package/dist/src/scanner/package-json-extras.d.ts +101 -0
- package/dist/src/scanner/package-scanner.d.ts +17 -0
- package/dist/src/scanner/resolution-drift.d.ts +81 -0
- package/dist/src/scanner/workspace-catalog.d.ts +53 -0
- package/dist/src/scheduler/scheduler.d.ts +27 -0
- package/dist/src/security/engine.d.ts +12 -0
- package/dist/src/security/loader.d.ts +7 -0
- package/dist/src/security/parser.d.ts +15 -0
- package/dist/src/security/rules/bash-injection.d.ts +18 -0
- package/dist/src/security/rules/dangerous-pull-request-target.d.ts +18 -0
- package/dist/src/security/rules/excessive-permissions.d.ts +14 -0
- package/dist/src/security/rules/index.d.ts +16 -0
- package/dist/src/security/rules/missing-timeout.d.ts +9 -0
- package/dist/src/security/rules/self-hosted-exposure.d.ts +13 -0
- package/dist/src/security/rules/unpinned-action.d.ts +10 -0
- package/dist/src/security/rules/walk.d.ts +13 -0
- package/dist/src/security/types.d.ts +64 -0
- package/dist/src/services/deprecated-dependencies-checker.d.ts +16 -0
- package/dist/src/services/release-notes-fetcher.d.ts +70 -0
- package/dist/src/services/security-advisories.d.ts +59 -0
- package/dist/src/setup.d.ts +162 -0
- package/dist/src/setup.js +2 -0
- package/dist/src/templates/github-actions.d.ts +31 -0
- package/dist/src/templates/gitlab-ci.d.ts +46 -0
- package/dist/src/types.d.ts +449 -0
- package/dist/src/upgrades/index.d.ts +18 -0
- package/dist/src/upgrades/migrate.d.ts +45 -0
- package/dist/src/upgrades/plan.d.ts +112 -0
- package/dist/src/upgrades/report.d.ts +22 -0
- package/dist/src/upgrades/span.d.ts +47 -0
- package/dist/src/upgrades/usage.d.ts +30 -0
- package/dist/src/upgrades/wire.d.ts +61 -0
- package/dist/src/utils/concurrency.d.ts +50 -0
- package/dist/src/utils/dependency-file-parser.d.ts +17 -0
- package/dist/src/utils/dockerfile-parser.d.ts +69 -0
- package/dist/src/utils/endpoints.d.ts +58 -0
- package/dist/src/utils/errors.d.ts +35 -0
- package/dist/src/utils/file-changes.d.ts +14 -0
- package/dist/src/utils/github-actions-parser.d.ts +21 -0
- package/dist/src/utils/globs.d.ts +22 -0
- package/dist/src/utils/helpers.d.ts +73 -0
- package/dist/src/utils/http.d.ts +81 -0
- package/dist/src/utils/lock-file.d.ts +28 -0
- package/dist/src/utils/logger.d.ts +45 -0
- package/dist/src/utils/package-paths.d.ts +6 -0
- package/dist/src/utils/pantry-parser.d.ts +30 -0
- package/dist/src/utils/repository.d.ts +41 -0
- package/dist/src/utils/security-format.d.ts +18 -0
- package/dist/src/utils/zig-parser.d.ts +18 -0
- package/dist/src/version/version-resolver.d.ts +9 -0
- package/package.json +115 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/bin/cli.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
import{Cc as C0}from"../chunk-1stt2whn.js";import"../chunk-mcrfxphm.js";import{Wc as g}from"../chunk-djntbp7a.js";import"../chunk-1c1gznm9.js";import"../chunk-hw70wbzg.js";import"../chunk-3q6czqs4.js";import"../chunk-vyapg8ca.js";import"../chunk-vagxqhef.js";import"../chunk-xqx460y2.js";import{Od as o0,Pd as z0,Qd as r}from"../chunk-ts35hc5t.js";import{Rd as R0,Zd as e0}from"../chunk-fvpr07dn.js";import"../chunk-56q4pwb5.js";import"../chunk-tb5y0350.js";import"../chunk-16yqbccr.js";import"../chunk-8rc6042h.js";import"../chunk-4efbxdjr.js";import"../chunk-q9n79dd3.js";import"../chunk-6md7qf2g.js";import"../chunk-eagjp0dh.js";import"../chunk-6d9hmjt8.js";import"../chunk-978wtejw.js";import"../chunk-pkkwb0n0.js";import"../chunk-ph1b3vbp.js";import"../chunk-0j7z87kh.js";import"../chunk-naq32yx3.js";import"../chunk-bxfc4g2x.js";import"../chunk-g0w8n555.js";import"../chunk-tzs22es2.js";import"../chunk-9750tenz.js";import{Vi as s0,Zi as t0}from"../chunk-7mgec8kb.js";import{dj as NZ,ej as Z1,fj as $1,gj as J1,hj as Q1,ij as z1,jj as m,kj as f,mj as Y1,nj as X1,oj as j1,pj as q1,qj as G1,sj as K1,tj as H1,uj as U1,vj as V1,wj as W0,xj as W1,yj as F1}from"../chunk-zs3jaj0g.js";import"../chunk-tn8prpny.js";import"../chunk-5k40mwd4.js";import"../chunk-1h3ey7k5.js";import{Oj as t,Pj as M}from"../chunk-akffynkc.js";import"../chunk-x3kragh9.js";import"../chunk-wdwvt7gb.js";import"../chunk-8661pvb8.js";import"../chunk-ctsz0ynx.js";import"../chunk-vkctfqpm.js";import{Dk as PZ,Fk as D}from"../chunk-6g1y9yqh.js";import r0 from"fs";import V from"process";import{existsSync as D1}from"fs";import F0 from"fs/promises";import b0 from"os";import M0 from"path";import a from"process";import{EventEmitter as O1}from"events";import p from"process";import h0 from"process";import T0 from"process";import K0 from"process";import $0 from"process";import _0 from"tty";import YZ,{stdin as rZ,stdout as sZ}from"process";import m0,{stdin as qZ,stdout as GZ}from"process";import KZ from"readline";class u0{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let Z=b0.homedir(),$=M0.join(Z,".config","clapp");this.configPath=M0.join($,"telemetry.json")}async isEnabled(){if(a.env.DO_NOT_TRACK==="1"||a.env.DO_NOT_TRACK==="true")return!1;if(a.env.NO_TELEMETRY==="1"||a.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let Z=await this.loadConfig();if(Z.enabled=!0,!Z.userId)Z.userId=this.generateUserId();await this.saveConfig(Z)}async disable(){let Z=await this.loadConfig();Z.enabled=!1,await this.saveConfig(Z)}async track(Z,$){if(!await this.isEnabled())return;let Q={event:Z,...$,timestamp:Date.now(),platform:b0.platform(),nodeVersion:a.version};if(this.events.push(Q),this.events.length>=10)await this.send()}async trackCommand(Z,$){await this.track("command",{command:Z,duration:$})}async trackError(Z,$){await this.track("error",{error:Z,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(Z){return new Promise(($)=>setTimeout($,Z))}async status(){let Z=await this.loadConfig();return{enabled:Z.enabled,doNotTrack:a.env.DO_NOT_TRACK==="1"||a.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:Z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(D1(this.configPath)){let Z=await F0.readFile(this.configPath,"utf-8");return this.config=JSON.parse(Z),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(Z){this.config=Z;try{let $=M0.dirname(this.configPath);await F0.mkdir($,{recursive:!0}),await F0.writeFile(this.configPath,JSON.stringify(Z,null,2),"utf-8")}catch{}}generateUserId(){let Z=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${Z}-${$}`}}var _Z=new u0;function L0(Z){return Z.replace(/[<[].+/,"").trim()}function L1(Z){let $=/<([^>]+)>/g,J=/\[([^\]]+)\]/g,Q=[],z=(j)=>{let q=!1,X=j[1];if(X.startsWith("..."))X=X.slice(3),q=!0;return{required:j[0].startsWith("<"),value:X,variadic:q}},Y;while(Y=$.exec(Z))Q.push(z(Y));let U;while(U=J.exec(Z))Q.push(z(U));return Q}function T1(Z){let $={alias:{},boolean:[]};for(let[J,Q]of Z.entries()){if(Q.names.length>1)$.alias[Q.names[0]]=Q.names.slice(1);if(Q.isBoolean)if(Q.negated){if(!Z.some((Y,U)=>{return U!==J&&Y.names.some((j)=>Q.names.includes(j))&&typeof Y.required==="boolean"}))$.boolean.push(Q.names[0])}else $.boolean.push(Q.names[0])}return $}function y0(Z){return Z.reduce(($,J)=>$.length>=J.length?$:J,"")}function D0(Z,$){return Z.length>=$?Z:`${Z}${" ".repeat($-Z.length)}`}function G0(Z){return Z.replace(/([a-z])-([a-z])/g,($,J,Q)=>{return J+Q.toUpperCase()})}function w1(Z,$,J){let Q=0,z=$.length,Y=Z,U;for(;Q<z;++Q)U=Y[$[Q]],Y=Y[$[Q]]=Q===z-1?J:U!=null?U:!!~$[Q+1].indexOf(".")||!(+$[Q+1]>-1)?{}:[]}function E1(Z,$){for(let J of Object.keys($)){let Q=$[J];if(Q.shouldTransform){if(Z[J]=Array.prototype.concat.call([],Z[J]),typeof Q.transformFunction==="function")Z[J]=Z[J].map(Q.transformFunction)}}}function B1(Z){let $=/([^\\/]+)$/.exec(Z);return $?$[1]:""}function J0(Z){return Z.split(".").map(($,J)=>{return J===0?G0($):$}).join(".")}class Q0 extends Error{exitCode=2;isUsageError=!0;usage;constructor(Z,$){super(Z);if(this.name=this.constructor.name,$!==void 0)this.usage=$;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(Z).stack}format(Z=!1){if(Z&&this.stack)return`${this.message}
|
|
4
|
+
|
|
5
|
+
Stack trace:
|
|
6
|
+
${this.stack}`;return this.message}}function I1(Z){if(Z instanceof Q0)return!0;return!!Z&&typeof Z==="object"&&Z.name==="ClappError"&&typeof Z.message==="string"}function P1(){let{env:Z}=h0,{TERM:$,TERM_PROGRAM:J}=Z;if(h0.platform!=="win32")return $!=="linux";return Boolean(Z.WT_SESSION)||Boolean(Z.TERMINUS_SUBLIME)||Z.ConEmuTask==="{cmd::Cmder}"||J==="Terminus-Sublime"||J==="vscode"||$==="xterm-256color"||$==="alacritty"||$==="rxvt-unicode"||$==="rxvt-unicode-256color"||Z.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var V0="\x1B",R=`${V0}[`;var l={to(Z,$){if(!$)return`${R}${Z+1}G`;return`${R}${$+1};${Z+1}H`},move(Z,$){let J="";if(Z<0)J+=`${R}${-Z}D`;else if(Z>0)J+=`${R}${Z}C`;if($<0)J+=`${R}${-$}A`;else if($>0)J+=`${R}${$}B`;return J},up:(Z=1)=>`${R}${Z}A`,down:(Z=1)=>`${R}${Z}B`,forward:(Z=1)=>`${R}${Z}C`,backward:(Z=1)=>`${R}${Z}D`,nextLine:(Z=1)=>`${R}E`.repeat(Z),prevLine:(Z=1)=>`${R}F`.repeat(Z),left:`${R}G`,hide:`${R}?25l`,show:`${R}?25h`,save:`${V0}7`,restore:`${V0}8`};var O0={screen:`${R}2J`,up:(Z=1)=>`${R}1J`.repeat(Z),down:(Z=1)=>`${R}J`.repeat(Z),line:`${R}2K`,lineEnd:`${R}K`,lineStart:`${R}1K`,lines(Z){let $="";for(let J=0;J<Z;J++)$+=this.line+(J<Z-1?l.up():"");if(Z)$+=l.left;return $}},uZ={screen:`${V0}c`};function N1(Z,$){let J=[];for(let Q=0;Q<=$.length;Q++)J[Q]=[Q];for(let Q=0;Q<=Z.length;Q++)J[0][Q]=Q;for(let Q=1;Q<=$.length;Q++)for(let z=1;z<=Z.length;z++)if($.charAt(Q-1)===Z.charAt(z-1))J[Q][z]=J[Q-1][z-1];else J[Q][z]=Math.min(J[Q-1][z-1]+1,J[Q][z-1]+1,J[Q-1][z]+1);return J[$.length][Z.length]}function g0(Z,$,J=2,Q=3){return $.map((z)=>({cmd:z,distance:N1(Z,z)})).filter(({distance:z})=>z<=J).sort((z,Y)=>z.distance-Y.distance).slice(0,Q).map(({cmd:z})=>z)}function A1(Z,$={}){let J={_:[]},Q=$.alias||{},z=new Set($.boolean||[]),Y={};for(let q of Object.keys(Q))for(let X of Q[q])Y[X]=q;for(let q of z)if(Q[q])for(let X of Q[q])z.add(X);function U(q,X){if(q===void 0)return X;if(typeof X==="boolean")return X;return Array.isArray(q)?[...q,X]:[q,X]}function j(q,X){let H=Y[q]||q,G=U(J[H],X);if(J[H]=G,Q[H])for(let K of Q[H])J[K]=G;if(Y[q]&&Q[Y[q]])for(let K of Q[Y[q]])J[K]=G;J[q]=G}for(let q=0;q<Z.length;q++){let X=Z[q];if(X==="--"){J._.push(...Z.slice(q+1));break}if(X.startsWith("--")){let H=X.indexOf("=");if(H!==-1){let G=G0(X.slice(2,H)),K=X.slice(H+1);j(G,K)}else{let G=X.slice(2);if(G.startsWith("no-")){let F=G0(G.slice(3));j(F,!1);continue}let K=G0(G),W=Y[K]||K;if(z.has(W)||z.has(K))j(K,!0);else{let F=Z[q+1];if(F!==void 0&&!F.startsWith("-"))j(K,F),q++;else j(K,!0)}}}else if(X.startsWith("-")&&X.length>1){let H=X.slice(1);for(let G=0;G<H.length;G++){let K=H[G],W=Y[K]||K;if(G===H.length-1&&!z.has(W)&&!z.has(K)){let F=Z[q+1];if(F!==void 0&&!F.startsWith("-"))j(K,F),q++;else j(K,!0)}else j(K,!0)}}else J._.push(X)}return J}class c0{rawName;description;name;names;isBoolean;required;config;negated;constructor(Z,$,J){if(this.rawName=Z,this.description=$,this.config=Object.assign({},J),Z=Z.replace(/\.\*/g,""),this.negated=!1,this.names=L0(Z).split(",").map((Q)=>{let z=Q.trim().replace(/^-{1,2}/,"");if(z.startsWith("no-"))this.negated=!0,z=z.replace(/^no-/,"");return J0(z)}).sort((Q,z)=>Q.length>z.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(Z.includes("<"))this.required=!0;else if(Z.includes("["))this.required=!1;else this.isBoolean=!0}}var cZ=T0.argv,x1=`${T0.platform}-${T0.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,v0=K0.argv,R1=`${K0.platform}-${K0.arch} node-${K0.version}`;class w0{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(Z,$,J,Q){this.rawName=Z,this.description=$,this.config=J,this.cli=Q,this.options=[],this.aliasNames=[],this.name=L0(Z);let z=L0(Z),Y=z.indexOf(":");if(Y>0)this.namespace=z.substring(0,Y),this.name=z.substring(Y+1);if(this.args=L1(Z),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!J)this.config={}}usage(Z){return this.usageText=Z,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(Z,$="-v, --version"){return this.versionNumber=Z,this.option($,"Display version number"),this}example(Z){return this.examples.push(Z),this}option(Z,$,J){let Q=new c0(Z,$,J);return this.options.push(Q),this}alias(Z){return this.aliasNames.push(Z),this}action(Z){return this.commandAction=Z,this}before(Z){return this.beforeHooks.push(Z),this}after(Z){return this.afterHooks.push(Z),this}use(Z){return this.middleware.push(Z),this}isMatched(Z){if(this.aliasNames.includes(Z))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===Z;return this.name===Z}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof E0}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(Z){let $=J0(Z.split(".")[0]);return!!this.options.find((J)=>{return J.names.some((Q)=>J0(Q)===$)})}outputHelp(){let{name:Z,commands:$}=this.cli,{versionNumber:J,options:Q,helpCallback:z}=this.cli.globalCommand,Y=[{body:`${Z}${J?`/${J}`:""}`}];if(Y.push({title:"Usage",body:` $ ${Z} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let X=y0($.map((F)=>F.rawName)),H=new Map,G=[];for(let F of $)if(F.namespace){if(!H.has(F.namespace))H.set(F.namespace,[]);H.get(F.namespace).push(F)}else G.push(F);let K="";if(G.sort((F,L)=>F.rawName<L.rawName?-1:F.rawName>L.rawName?1:0),G.length>0)K+=G.map((F)=>{return` ${D0(F.rawName,X.length)} ${F.description}`}).join(`
|
|
7
|
+
`);let W=Array.from(H.keys()).sort();for(let F of W){let L=H.get(F);if(K.length>0)K+=`
|
|
8
|
+
|
|
9
|
+
`;K+=` ${F}:
|
|
10
|
+
`,K+=L.map((B)=>{return` ${D0(B.rawName,X.length-2)} ${B.description}`}).join(`
|
|
11
|
+
`)}Y.push({title:"Commands",body:K}),Y.push({body:`Run \`${Z} <command> --help\` for command details.`})}let j=new Set(this.options.flatMap((X)=>X.names)),q=this.isGlobalCommand?Q:[...this.options,...(Q||[]).filter((X)=>!X.names.some((H)=>j.has(H)))];if(!this.isGlobalCommand&&!this.isDefaultCommand)q=q.filter((X)=>X.name!=="version");if(q.length>0){let X=y0(q.map((H)=>H.rawName));Y.push({title:"Options",body:q.map((H)=>{return` ${D0(H.rawName,X.length)} ${H.description} ${H.config.default===void 0?"":`(default: ${H.config.default})`}`}).join(`
|
|
12
|
+
`)})}if(this.examples.length>0)Y.push({title:"Examples",body:this.examples.map((X)=>{if(typeof X==="function")return X(Z);return X}).join(`
|
|
13
|
+
`)});if(z)Y=z(Y)||Y;console.log(Y.map((X)=>{return X.title?`${X.title}:
|
|
14
|
+
${X.body}`:X.body}).join(`
|
|
15
|
+
|
|
16
|
+
`))}outputVersion(){let{name:Z}=this.cli,{versionNumber:$}=this.cli.globalCommand;if($)console.log(`${Z}/${$} ${typeof Bun<"u"?x1:R1}`)}get usageLine(){return`$ ${this.cli.name} ${this.usageText||this.rawName}`}checkRequiredArgs(){let Z=this.args.filter(($)=>$.required).length;if(this.cli.args.length<Z){let J=this.args.filter((z)=>z.required).slice(this.cli.args.length),Q=J.map((z)=>`<${z.value}>`).join(" ");throw new Q0(`Missing required argument${J.length>1?"s":""}: ${Q}
|
|
17
|
+
|
|
18
|
+
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`,this.usageLine)}}checkUnknownOptions(){let{options:Z,globalCommand:$}=this.cli;if(!this.config.allowUnknownOptions){for(let J of Object.keys(Z))if(J!=="--"&&!this.hasOption(J)&&!$.hasOption(J)){let z=[...$.options,...this.options].flatMap((X)=>X.names),Y=J0(J.split(".")[0]),U=J.length>1?`--${J}`:`-${J}`,j=g0(Y,z),q=`Unknown option \`${U}\``;if(j.length>0)q+=`
|
|
19
|
+
|
|
20
|
+
Did you mean one of these?`,j.forEach((X)=>{let H=X.length>1?`--${X}`:`-${X}`;q+=`
|
|
21
|
+
\u2022 ${H}`});throw q+=`
|
|
22
|
+
|
|
23
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new Q0(q,this.usageLine)}}}checkOptionValue(){let{options:Z,globalCommand:$}=this.cli,J=[...$.options,...this.options];for(let Q of J){let z=Z[Q.name.split(".")[0]];if(Q.required){let Y=J.some((U)=>U.negated&&U.names.includes(Q.name));if(z===!0||z===!1&&!Y)throw new Q0(`Option \`${Q.rawName}\` requires a value.
|
|
24
|
+
|
|
25
|
+
Example: ${this.cli.name} ${this.rawName} ${Q.rawName} <value>`,this.usageLine)}}}}class E0 extends w0{constructor(Z){super("@@global@@","",{},Z)}}var C1=w0,i={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var e={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function S1(){return!0}function k1(){let Z={};Z.supportsColor=S1();function $(Q,z=[]){let Y=Q===""?[]:[...z,Q],U=function(q){if(!Z.supportsColor)return q;let X="",H="";for(let G of Y)if(G in e&&e[G]in i){let K=e[G];X+=i[K][0],H=i[K][1]+H}else if(G in i)X+=i[G][0],H=i[G][1]+H;return X+q+H},j=[...Object.keys(i),...Object.keys(e)];for(let q of j)if(!(q in U))Object.defineProperty(U,q,{get(){return $(q,Y)}});return U}let J=[...Object.keys(i),...Object.keys(e)];for(let Q of J)if(!(Q in Z))Object.defineProperty(Z,Q,{get(){return $(Q)}});return Z}var Z0=k1();class B0 extends O1{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(Z=""){super();this.name=Z,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new E0(this),this.globalCommand.usage("<command> [options]")}handleSignals(Z){if(this.signalHandlersSet)return this;let $=async(J)=>{if(console.log(`
|
|
26
|
+
|
|
27
|
+
Received ${J}, cleaning up...`),Z)try{await Z()}catch(Q){console.error("Error during cleanup:",Q)}p.exit(0)};return p.on("SIGINT",()=>$("SIGINT")),p.on("SIGTERM",()=>$("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(Z=!0){return this.enableDidYouMean=Z,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(Z){return this.globalCommand.usage(Z),this}command(Z,$,J){if(!J)J={};let Q=new C1(Z,$||"",J,this);return Q.globalCommand=this.globalCommand,this.commands.push(Q),Q}option(Z,$,J){return this.globalCommand.option(Z,$,J),this}help(Z){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=Z,this.showHelpOnExit=!0,this}version(Z,$="-v, --version"){return this.globalCommand.version(Z,$),this.showVersionOnExit=!0,this}example(Z){return this.globalCommand.example(Z),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:Z,options:$},J,Q){if(this.args=Z,this.options=$,J)this.matchedCommand=J;if(Q)this.matchedCommandName=Q;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(Z){if(console.log(Z0.red(`
|
|
28
|
+
\u2717 Command "${Z}" not found.
|
|
29
|
+
`)),this.enableDidYouMean){let $=[];for(let Q of this.commands){if(Q.displayName)$.push(Q.displayName);if(Q.aliasNames)$.push(...Q.aliasNames)}let J=g0(Z,$);if(J.length>0)console.log(Z0.yellow("Did you mean one of these?")),J.forEach((Q)=>console.log(` ${Z0.dim("\u2022")} ${this.name} ${Q}`)),console.log("")}console.log(Z0.dim("Run"),`${this.name} --help`,Z0.dim("to see all available commands")),p.exit(1)}async parse(Z=v0,$={}){let{run:J=!0,exitOnError:Q=!1}=$;if(Q)try{return await this.parse(Z,{run:J})}catch(q){throw this.handleUsageError(q),q}if(this.rawArgs=Z,!this.name)this.name=Z[1]?B1(Z[1]):"cli";let z=!0,Y=Z.slice(2),U=Y[0];if(U&&!U.startsWith("-")){for(let q of this.commands)if(q.isMatched(U)){let X=this.mri(Y,q);z=!1;let H={...X,args:X.args.slice(1)};this.setParsedInfo(H,q,U),this.emit(`command:${U}`,q);break}if(z){let q=Y[1];if(q&&!q.startsWith("-")){let X=`${U}:${q}`;for(let H of this.commands)if(H.isMatched(X)){let G=this.mri(Y,H);z=!1;let K={...G,args:G.args.slice(2)};this.setParsedInfo(K,H,X),this.emit(`command:${X}`,H);break}}}}if(z){for(let q of this.commands)if(q.name===""){z=!1;let X=this.mri(Y,q);this.setParsedInfo(X,q),this.emit("command:!",q);break}}if(z){let q=this.mri(Z.slice(2));this.setParsedInfo(q)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction||this.options.interaction===!1)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji||this.options.emoji===!1)this.useEmoji=!1;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache||this.options.cache===!1)this.isNoCache=!0;if(this.options.help&&this.showHelpOnExit)this.outputHelp(),J=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),J=!1,this.unsetMatchedCommand();let j={args:this.args,options:this.options};if(J)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return j}mri(Z,$){let J=[...this.globalCommand.options,...$?$.options:[]],Q=T1(J),z=[],Y=Z.indexOf("--");if(Y>-1)z=Z.slice(Y+1),Z=Z.slice(0,Y);let U=A1(Z,Q),j={_:U._};for(let K of Object.keys(U))if(K!=="_")j[J0(K)]=U[K];let q=j._,X={"--":z},H=$&&$.config.ignoreOptionDefaultValue?$.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,G=Object.create(null);for(let K of J){if(!H&&K.config.default!==void 0)for(let W of K.names)X[W]=K.config.default;if(Array.isArray(K.config.type)){if(G[K.name]===void 0)G[K.name]={shouldTransform:!0,transformFunction:K.config.type[0]}}}for(let K of Object.keys(j))if(K!=="_"){let W=K.split(".");w1(X,W,j[K]),E1(X,G)}return{args:q,options:X}}async run(Z=v0){return this.parse(Z,{run:!0,exitOnError:!0})}handleUsageError(Z){if(!I1(Z)||Z.isUsageError===!1)return;let $=Z.message||"command-line error",J=this.name?`${this.name}: `:"",Q=/--help/.test($)?"":Z.usage?`
|
|
30
|
+
Usage: ${Z.usage}`:`
|
|
31
|
+
Run \`${this.name??"cli"} --help\` for usage.`;p.stderr.write(`${J}${$}${Q}
|
|
32
|
+
`),p.exit(Z.exitCode??2)}async runMatchedCommand(){let{args:Z,options:$,matchedCommand:J}=this;if(!J||!J.commandAction)return;J.checkUnknownOptions(),J.checkOptionValue(),J.checkRequiredArgs();let Q=[];J.args.forEach((j,q)=>{if(j.variadic)Q.push(Z.slice(q));else Q.push(Z[q])}),Q.push($);let z={command:J,args:Q,options:$};for(let j of J.beforeHooks)await j(z);let Y,U=async()=>{let j=J.commandAction.apply(this,Q);if(j instanceof Promise)Y=await j;else Y=j;return Y};if(J.middleware.length>0){let j=0,q=async()=>{if(j<J.middleware.length){let X=J.middleware[j++];await X({...z,next:q})}else await U()};await q()}else await U();for(let j of J.afterHooks)await j(z);return Y}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return p.removeAllListeners("SIGINT"),p.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class l0{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(Z){if(!this.enabled){this.misses++;return}let $=this.cache.get(Z);if(!$){this.misses++;return}if(Date.now()-$.timestamp>$.ttl){this.cache.delete(Z),this.misses++;return}return this.hits++,$.value}set(Z,$,J=5000){if(!this.enabled)return;this.cache.set(Z,{value:$,timestamp:Date.now(),ttl:J})}has(Z){if(!this.enabled)return!1;let $=this.cache.get(Z);if(!$)return!1;if(Date.now()-$.timestamp>$.ttl)return this.cache.delete(Z),!1;return!0}delete(Z){this.cache.delete(Z)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let Z=Date.now();for(let[$,J]of this.cache.entries())if(Z-J.timestamp>J.ttl)this.cache.delete($)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var pZ=new l0;function b1(){if("FORCE_COLOR"in $0.env)return $0.env.FORCE_COLOR!=="0";if("NO_COLOR"in $0.env||$0.env.TERM==="dumb")return!1;if($0.platform==="win32")return!0;return _0.isatty(1)&&_0.isatty(2)}var p0=b1();function x(Z,$){if(!p0)return(J)=>J;return(J)=>Z+J+$}var h1=x("\x1B[0m","\x1B[0m"),y1=x("\x1B[31m","\x1B[39m"),v1=x("\x1B[32m","\x1B[39m"),_1=x("\x1B[33m","\x1B[39m"),f1=x("\x1B[34m","\x1B[39m"),m1=x("\x1B[35m","\x1B[39m"),d1=x("\x1B[36m","\x1B[39m"),u1=x("\x1B[37m","\x1B[39m"),g1=x("\x1B[90m","\x1B[39m"),c1=x("\x1B[1m","\x1B[22m"),l1=x("\x1B[3m","\x1B[23m"),p1=x("\x1B[4m","\x1B[24m"),i1=x("\x1B[2m","\x1B[22m"),n1=x("\x1B[7m","\x1B[27m"),a1=x("\x1B[8m","\x1B[28m"),r1=x("\x1B[9m","\x1B[29m"),s1=x("\x1B[41m","\x1B[49m"),t1=x("\x1B[42m","\x1B[49m"),o1=x("\x1B[43m","\x1B[49m"),e1=x("\x1B[44m","\x1B[49m"),ZZ=x("\x1B[45m","\x1B[49m"),$Z=x("\x1B[46m","\x1B[49m"),JZ=x("\x1B[47m","\x1B[49m"),QZ=p0,zZ={reset:h1,red:y1,green:v1,yellow:_1,blue:f1,magenta:m1,cyan:d1,white:u1,gray:g1,bold:c1,italic:l1,underline:p1,dim:i1,inverse:n1,hidden:a1,strikethrough:r1,bgRed:s1,bgGreen:t1,bgYellow:o1,bgBlue:e1,bgMagenta:ZZ,bgCyan:$Z,bgWhite:JZ,isColorSupported:QZ},H0=zZ,XZ=["up","down","left","right","space","enter","cancel"],U0={actions:new Set(XZ),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function i0(Z,$){if(typeof Z==="string")return U0.aliases.get(Z)===$;for(let J of Z){if(J===void 0)continue;if(i0(J,$))return!0}return!1}function jZ(Z,$){if(Z===$)return[];let J=Z.split(`
|
|
33
|
+
`),Q=$.split(`
|
|
34
|
+
`),z=[];for(let Y=0;Y<Math.max(J.length,Q.length);Y++)if(J[Y]!==Q[Y])z.push(Y);return z}var tZ=YZ.platform.startsWith("win"),f0=Symbol("clapp:cancel");function q0(Z,$){let J=Z;if(J.isTTY)J.setRawMode($)}function HZ(Z){return Z.replace(/\x1b\[[0-9;]*m/g,"")}function UZ(Z){return HZ(Z).length}function d0(Z,$,J){if(!$||$<1)return Z;let Q=J?.hard??!1,z=J?.trim??!0,Y=Z.split(`
|
|
35
|
+
`),U=[];for(let j of Y){if(UZ(j)<=$){U.push(z?j.trimEnd():j);continue}if(Q){let q="",X=0,H=0;while(H<j.length){let G=j.slice(H).match(/^\x1b\[[0-9;]*m/);if(G){q+=G[0],H+=G[0].length;continue}if(X>=$)U.push(z?q.trimEnd():q),q="",X=0;q+=j[H],X++,H++}if(q)U.push(z?q.trimEnd():q)}else U.push(z?j.trimEnd():j)}return U.join(`
|
|
36
|
+
`)}class I0{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor(Z,$=!0){let{input:J=qZ,output:Q=GZ,render:z,signal:Y,...U}=Z;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=z.bind(this),this._track=$,this._abortSignal=Y,this.input=J,this.output=Q}unsubscribe(){this._subscribers.clear()}setSubscriber(Z,$){let J=this._subscribers.get(Z)??[];J.push($),this._subscribers.set(Z,J)}on(Z,$){return this.setSubscriber(Z,{cb:$}),this}once(Z,$){return this.setSubscriber(Z,{cb:$,once:!0}),this}emit(Z,...$){let J=this._subscribers.get(Z)??[],Q=[];for(let z of J)if(z.cb(...$),z.once)Q.push(()=>J.splice(J.indexOf(z),1));for(let z of Q)z();return this}prompt(){return new Promise((Z)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),Z(f0);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=KZ.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),q0(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(l.show),this.output.off("resize",this.render),q0(this.input,!1),Z(this.value)}),this.once("cancel",()=>{this.output.write(l.show),this.output.off("resize",this.render),q0(this.input,!1),Z(f0)})})}_isActionKey(Z,$){return Z==="\t"}_setValue(Z){this.value=Z,this.emit("value",this.value)}_setUserInput(Z,$){if(this.userInput=Z??"",this.emit("userInput",this.userInput),$&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(Z,$){if(this._track&&$.name!=="return"){if($.name&&this._isActionKey(Z,$))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let J=$.name==="tab"||$.name==="escape"||$.name==="backspace"||$.name==="delete"||$.name==="enter"||$.name==="return"||$.name&&["up","down","left","right"].includes($.name);if(Z&&!J&&Z.length===1&&Z>=" ")this._manualLine+=Z;else if($.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let Q=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(Q)}if(this.state==="error")this.state="active",this.error="";if($?.name){if(!this._track&&U0.aliases.has($.name))this.emit("cursor",U0.aliases.get($.name));if(U0.actions.has($.name))this.emit("cursor",$.name)}if(Z&&(Z.toLowerCase()==="y"||Z.toLowerCase()==="n"))this.emit("confirm",Z.toLowerCase()==="y");if(this.emit("key",Z?.toLowerCase(),$),$?.name==="return"){if(this.opts.validate){let J=this.opts.validate(this.value);if(J)this.error=J instanceof Error?J.message:J,this.state="error"}if(this.state!=="error")this.state="submit"}if(i0([Z,$?.name,$?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
37
|
+
`),q0(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let Z=d0(this._prevFrame,m0.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
38
|
+
`).length-1;this.output.write(l.move(-999,Z*-1))}render(){let Z=d0(this._render(this)??"",m0.stdout.columns,{hard:!0,trim:!1});if(Z===this._prevFrame)return;if(this.state==="initial")this.output.write(l.hide);else{let $=jZ(this._prevFrame,Z);if(this.restoreCursor(),$&&$?.length===1){let J=$[0];this.output.write(l.move(0,J)),this.output.write(O0.lines(1));let Q=Z.split(`
|
|
39
|
+
`);this.output.write(Q[J]),this._prevFrame=Z,this.output.write(l.move(0,Q.length-J-1));return}if($&&$?.length>1){let J=$[0];this.output.write(l.move(0,J)),this.output.write(O0.down());let z=Z.split(`
|
|
40
|
+
`).slice(J);this.output.write(z.join(`
|
|
41
|
+
`)),this._prevFrame=Z;return}this.output.write(O0.down())}if(this.output.write(Z),this.state==="initial")this.state="active";this._prevFrame=Z}}function VZ(Z,$){if(Z===void 0)return 0;if($.length===0)return 0;let Q=$.findIndex((z)=>z.value===Z);return Q!==-1?Q:0}function WZ(Z,$){return($.label??String($.value)).toLowerCase().includes(Z.toLowerCase())}function FZ(Z,$){if(!$)return;if(Z)return $;return $[0]}class MZ extends I0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#J="";#Q;#$;get cursor(){return this.#Z}get userInputWithCursor(){if(!this.userInput)return H0.inverse(H0.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let Z=this.userInput.slice(0,this._cursor),[$,...J]=this.userInput.slice(this._cursor);return`${Z}${H0.inverse($)}${J.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(Z){super(Z);this.#$=Z.options;let $=this.options;this.filteredOptions=[...$],this.multiple=Z.multiple===!0,this.#Q=Z.filter??WZ;let J;if(Z.initialValue&&Array.isArray(Z.initialValue))if(this.multiple)J=Z.initialValue;else J=Z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)J=[this.options[0].value];if(J)for(let Q of J){let z=$.findIndex((Y)=>Y.value===Q);if(z!==-1)this.toggleSelected(Q),this.#Z=z}this.focusedValue=this.options[this.#Z]?.value,this.on("key",(Q,z)=>this.#z(Q,z)),this.on("userInput",(Q)=>this.#Y(Q))}_isActionKey(Z,$){return Z==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&Z!==void 0&&Z!==""}#z(Z,$){let J=$.name==="up",Q=$.name==="down",z=$.name==="return";if(J||Q){if(this.#Z=Math.max(0,Math.min(this.#Z+(J?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#Z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(z)this.value=FZ(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(Z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(Z))this.selectedValues=this.selectedValues.filter(($)=>$!==Z);else this.selectedValues=[...this.selectedValues,Z];else this.selectedValues=[Z]}#Y(Z){if(Z!==this.#J){this.#J=Z;let $=this.options;if(Z)this.filteredOptions=$.filter((J)=>this.#Q(Z,J));else this.filteredOptions=[...$];if(this.#Z=VZ(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#Z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class DZ extends I0{options;cursor=0;#Z;getGroupItems(Z){return this.options.filter(($)=>$.group===Z)}isGroupSelected(Z){let $=this.getGroupItems(Z),J=this.value;if(J===void 0)return!1;return $.every((Q)=>J.includes(Q.value))}toggleValue(){let Z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(Z.group===!0){let $=String(Z.value),J=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((Q)=>J.findIndex((z)=>z.value===Q)===-1);else this.value=[...this.value,...J.map((Q)=>Q.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(Z.value);this.value=$?this.value.filter((J)=>J!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:$}=Z;this.#Z=Z.selectableGroups!==!1,this.options=Object.entries($).flatMap(([J,Q])=>[{value:J,group:!0,label:J},...Q.map((z)=>({...z,group:J}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:J})=>J===Z.cursorAt),this.#Z?0:1),this.on("cursor",(J)=>{switch(J){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Q=this.options[this.cursor]?.group===!0;if(!this.#Z&&Q)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Q=this.options[this.cursor]?.group===!0;if(!this.#Z&&Q)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var OZ=P1();var A=(Z,$)=>OZ?Z:$,Z$=A("\u25C6","*"),$$=A("\u25A0","x"),J$=A("\u25B2","x"),Q$=A("\u25C7","o"),z$=A("\u250C","T"),LZ=A("\u2502","|"),Y$=A("\u2514","\u2014"),X$=A("\u25CF",">"),j$=A("\u25CB"," "),q$=A("\u25FB","[\u2022]"),G$=A("\u25FC","[+]"),K$=A("\u25FB","[ ]"),H$=A("\u25AA","\u2022"),U$=A("\u2500","-"),V$=A("\u256E","+"),W$=A("\u251C","+"),F$=A("\u256F","+"),M$=A("\u25CF","\u2022"),D$=A("\u25C6","*"),O$=A("\u25B2","!"),L$=A("\u25A0","x");var T$={light:A("\u2500","-"),heavy:A("\u2501","="),block:A("\u2588","#")};function TZ(){return`${H0.gray(LZ)} `}var w$=TZ();var s=PZ(NZ(),1);var P0="0.11.0";var N0=String.raw`^\s*-\s*\[[xX]\]\s*`,EZ=new RegExp(`${N0}<!--\\s*rebase-branch=([^>]*?)\\s*-->`,"gm"),BZ=new RegExp(`${N0}<!--\\s*rebase-all-open-prs\\s*-->`,"m"),IZ=new RegExp(`${N0}<!--\\s*manual job\\s*-->`,"m");function n0(Z){if(!Z)return{rebaseBranches:[],rebaseAll:!1,manualRun:!1};let $=[];for(let J of Z.matchAll(EZ)){let Q=J[1].trim();if(Q&&!$.includes(Q))$.push(Q)}return{rebaseBranches:$,rebaseAll:BZ.test(Z),manualRun:IZ.test(Z)}}function A0(Z){return Z.rebaseBranches.length>0||Z.rebaseAll||Z.manualRun}function a0(Z){return Z.replace(/^(\s*-\s*)\[[xX]\](\s*<!--\s*(?:rebase-branch=[^>]*?|rebase-all-open-prs|manual job)\s*-->)/gm,"$1[ ]$2")}var x0=null;async function C(Z){if(Z)return await C0(Z);if(!x0)x0=await C0();return x0}async function d(Z,$,J){if(!Z.repository?.owner||!Z.repository.name)J.error(`\u274C Repository owner and name are required for ${$}`),J.info("Configure repository.owner and repository.name in buddy.config.ts"),V.exit(1);try{return await o0({provider:Z.repository.provider,owner:Z.repository.owner,name:Z.repository.name,...Z.repository.token?{token:Z.repository.token}:{},...Z.repository.apiUrl?{apiUrl:Z.repository.apiUrl}:{}},{logger:J})}catch(Q){J.error(`\u274C ${t(Q)}`),V.exit(1)}}async function AZ(Z,$,J){let Q=Z.filter((U)=>U.suggestion);if(Q.length===0)return J.info("No committable suggestions in this review"),0;let z=new Map;for(let U of Q){let j=z.get(U.path);if(j)j.push(U);else z.set(U.path,[U])}let Y=0;for(let[U,j]of z){let q=Bun.file(U);if(!await q.exists()){J.warn(`\u26A0\uFE0F Skipping ${U}: not in the working tree`);continue}let X=await q.text();for(let H of[...j].sort((G,K)=>K.line-G.line)){if(!$){if(!(await s.default({type:"confirm",name:"apply",message:`${U}:${H.line} \u2014 ${H.message}
|
|
42
|
+
${H.suggestion}
|
|
43
|
+
Apply?`,initial:!1})).apply)continue}let G=e0(X,H.line,H.suggestion);if(G===null){J.warn(`\u26A0\uFE0F Skipping ${U}:${H.line}: the file changed since the review`);continue}X=G,Y++}await Bun.write(U,X)}return Y}async function xZ(Z,$){try{let{PackageScanner:J}=await import("../chunk-f4nv5x3z.js"),Q=await new J(V.cwd(),$,Z.packages?.ignorePaths).scanProject(),z=new Map;for(let Y of Q)for(let U of Y.dependencies)if(!z.has(U.name))z.set(U.name,U.currentVersion);return[...z].map(([Y,U])=>({name:Y,declaredVersion:U}))}catch(J){return $.debug(`Could not collect dependency context: ${t(J)}`),[]}}var T=new B0("buddy");T.usage(`[command] [options]
|
|
44
|
+
|
|
45
|
+
\uD83D\uDC36 Buddy - AI code review and dependency updates, in one teammate
|
|
46
|
+
|
|
47
|
+
Reviews pull requests and local changes, answers @buddy comments, gates merges,
|
|
48
|
+
repairs failing CI, and keeps dependencies current across npm, Bun, yarn, pnpm,
|
|
49
|
+
Composer, pkgx, Launchpad, GitHub Actions, Docker, Go, Rust, Python and Ruby.
|
|
50
|
+
|
|
51
|
+
CODE REVIEW & AI:
|
|
52
|
+
review \uD83D\uDD0D Review a pull request, or local changes when no number is given
|
|
53
|
+
gate \uD83D\uDEA6 Run pre-merge gates and publish the result as a check run
|
|
54
|
+
fix-ci \uD83D\uDEE0\uFE0F Diagnose a failing workflow run and repair it when the fix is clear
|
|
55
|
+
handle-comment \uD83D\uDCAC Handle an @buddy command from a GitHub event payload
|
|
56
|
+
handle-issue \uD83C\uDFAB Post quick-links on a new issue, or run a ticked action
|
|
57
|
+
post-merge \u2705 Run post-merge actions for a merged pull request
|
|
58
|
+
run \u26A1 Run a prompt headlessly, with optional schema-validated output
|
|
59
|
+
|
|
60
|
+
DEPENDENCY MANAGEMENT:
|
|
61
|
+
setup \uD83D\uDE80 Interactive setup for automated updates (recommended)
|
|
62
|
+
scan \uD83D\uDD0D Scan for dependency updates
|
|
63
|
+
dashboard \uD83D\uDCCA Create or update dependency dashboard issue
|
|
64
|
+
update \u2B06\uFE0F Update dependencies and create PRs
|
|
65
|
+
rebase \uD83D\uDD04 Rebase/retry a pull request with latest updates
|
|
66
|
+
update-check \uD83D\uDD0D Auto-detect and rebase PRs with checked rebase box
|
|
67
|
+
check \uD83D\uDCCB Check specific packages for updates
|
|
68
|
+
schedule \u23F0 Run automated updates on schedule
|
|
69
|
+
|
|
70
|
+
PACKAGE INFORMATION:
|
|
71
|
+
info \uD83D\uDCE6 Show detailed package information
|
|
72
|
+
versions \uD83D\uDCC8 Show all available versions of a package
|
|
73
|
+
latest \u2B50 Get the latest version of a package
|
|
74
|
+
exists \u2705 Check if a package exists in the registry
|
|
75
|
+
deps \uD83D\uDD17 Show package dependencies
|
|
76
|
+
compare \u2696\uFE0F Compare two versions of a package
|
|
77
|
+
search \uD83D\uDD0D Search for packages in the registry
|
|
78
|
+
|
|
79
|
+
BRANCH MANAGEMENT:
|
|
80
|
+
cleanup \uD83E\uDDF9 Clean up stale buddy branches
|
|
81
|
+
list-branches \uD83D\uDCCB List all buddy branches and their status
|
|
82
|
+
|
|
83
|
+
REPORTING & DIAGNOSTICS:
|
|
84
|
+
report \uD83D\uDCC8 Generate a dependency-health and activity report
|
|
85
|
+
doctor \uD83E\uDE7A Diagnose credentials, git state and analyzer tooling
|
|
86
|
+
|
|
87
|
+
CONFIGURATION & SETUP:
|
|
88
|
+
open-settings \uD83D\uDD27 Open GitHub repository and organization settings pages
|
|
89
|
+
|
|
90
|
+
Examples:
|
|
91
|
+
buddy review # Review your working tree before pushing
|
|
92
|
+
buddy review --staged --light # Analyzers only, no API key, for a git hook
|
|
93
|
+
buddy review 128 --format github # Review PR #128 as Actions annotations
|
|
94
|
+
buddy gate 128 # Run pre-merge gates on PR #128
|
|
95
|
+
buddy fix-ci --run-id 42 # Explain and repair a failing run
|
|
96
|
+
buddy setup # Interactive setup with migration
|
|
97
|
+
buddy setup --non-interactive # Automated setup for CI/CD
|
|
98
|
+
buddy scan --verbose # Scan for updates (npm + Composer + Dockerfiles)
|
|
99
|
+
buddy rebase 17 # Rebase PR #17
|
|
100
|
+
buddy update-check # Auto-rebase checked PRs
|
|
101
|
+
buddy cleanup # Clean up stale branches
|
|
102
|
+
buddy info laravel/framework # Get Composer package info
|
|
103
|
+
buddy versions react --latest 5 # Show recent versions
|
|
104
|
+
buddy doctor # Check this environment
|
|
105
|
+
|
|
106
|
+
In a pull request, talk to Buddy directly:
|
|
107
|
+
@buddy review | full-review | summary | resolve | pause | resume
|
|
108
|
+
@buddy fix-ci | plan | rebase | merge | remember <text> | help
|
|
109
|
+
Anything else after the mention is treated as a question.
|
|
110
|
+
|
|
111
|
+
Migration:
|
|
112
|
+
- Automatically detects Renovate and Dependabot configurations
|
|
113
|
+
- Converts settings to Buddy format with compatibility report
|
|
114
|
+
- Generates optimized GitHub Actions workflows
|
|
115
|
+
- Provides migration guidance and best practices`);T.command("setup","\uD83D\uDE80 Interactive setup for automated dependency updates (recommended)").option("--verbose, -v","Enable verbose logging").option("--non-interactive","Run setup without prompts (use defaults)").option("--preset <type>","Workflow preset: standard|high-frequency|security|minimal|testing",{default:"standard"}).option("--token-setup <type>","Token setup: existing-secret|new-pat|default-token",{default:"default-token"}).example("buddy setup").example("buddy setup --verbose").example("buddy setup --non-interactive").example("buddy setup --non-interactive --preset testing --verbose").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet();try{console.log("\uD83E\uDD16 Welcome to Buddy Setup!"),console.log(`Let's configure automated dependency updates for your project.
|
|
116
|
+
`);let J=z1(10);f(J),m(J,"Detecting existing configurations"),f(J);let Q=new Z1,z=await Q.detectExistingTools(),Y=[];if(z.length>0&&!Z.nonInteractive){if(console.log(`
|
|
117
|
+
\uD83D\uDD0D Configuration Migration Detection:`),console.log(`Found ${z.length} existing dependency management tool(s):`),z.forEach((O)=>console.log(` \u2022 ${O.name} (${O.configFile})`)),(await s.default({type:"confirm",name:"migrate",message:"Would you like to migrate existing configurations to Buddy?",initial:!0})).migrate){console.log(`
|
|
118
|
+
\uD83D\uDCCB Migrating configurations...`);for(let O of z)try{let w;if(O.name==="renovate")w=await Q.migrateFromRenovate(O.configFile);else if(O.name==="dependabot")w=await Q.migrateFromDependabot(O.configFile);else continue;Y.push(w),console.log(`\u2705 Migrated ${O.name} configuration`)}catch(w){console.log(`\u26A0\uFE0F Failed to migrate ${O.name}: ${w instanceof Error?w.message:"Unknown error"}`)}if(Y.length>0){let O=await Q.generateMigrationReport(Y);console.log(`
|
|
119
|
+
${O}`)}}}else if(z.length>0&&Z.nonInteractive)console.log(`
|
|
120
|
+
\uD83D\uDD0D Found ${z.length} existing tool(s), skipping migration in non-interactive mode`);m(J,"Discovering integrations",!0),f(J);let U=new $1,j=await U.discoverPlugins();if(j.length>0&&!Z.nonInteractive){if(console.log(`
|
|
121
|
+
\uD83D\uDD0C Integration Discovery:`),console.log(`Found ${j.length} available integration(s):`),j.forEach((O)=>console.log(` \u2022 ${O.name} v${O.version}`)),(await s.default({type:"confirm",name:"enablePlugins",message:"Would you like to enable these integrations?",initial:!0})).enablePlugins)for(let O of j)await U.loadPlugin(O)}else if(j.length>0&&Z.nonInteractive)console.log(`
|
|
122
|
+
\uD83D\uDD0C Found ${j.length} integration(s), skipping in non-interactive mode`);m(J,"Running pre-flight checks",!0),f(J);let q=await J1();if(W0(q,"\uD83D\uDD0D Pre-flight Validation"),!q.success)console.log(`
|
|
123
|
+
\u274C Pre-flight checks failed. Please fix the errors above and try again.`),V.exit(1);m(J,"Analyzing project",!0),f(J);let X=await Q1();if(console.log(`
|
|
124
|
+
\uD83D\uDD0D Project Analysis:`),console.log(`\uD83D\uDCE6 Project Type: ${X.type}`),console.log(`\u2699\uFE0F Package Manager: ${X.packageManager}`),console.log(`\uD83D\uDD12 Lock File: ${X.hasLockFile?"Found":"Not found"}`),console.log(`\uD83D\uDCC4 Dependency Files: ${X.hasDependencyFiles?"Found":"None"}`),console.log(`\uD83D\uDD04 GitHub Actions: ${X.hasGitHubActions?"Found":"None"}`),console.log(`\uD83D\uDCA1 Recommended Preset: ${X.recommendedPreset}`),X.recommendations.length>0)console.log(`
|
|
125
|
+
\uD83D\uDCCB Recommendations:`),X.recommendations.forEach((P)=>console.log(` \u2022 ${P}`));m(J,"Repository Detection",!0),f(J),console.log(`
|
|
126
|
+
\uD83D\uDCCD Repository Detection`);let H=await Y1();if(!H)console.log("\u274C Could not detect repository. Please ensure you're in a Git repository."),V.exit(1);console.log(`\u2705 Detected repository: ${H.owner}/${H.name}`),console.log(`\uD83D\uDD17 GitHub URL: https://github.com/${H.owner}/${H.name}`);let G=await V1(H);if(G.warnings.length>0||G.suggestions.length>0)W0(G,"\uD83D\uDD0D Repository Validation");m(J,"GitHub Token Setup",!0),f(J),console.log(`
|
|
127
|
+
\uD83D\uDD11 GitHub Token Setup`),console.log("For full functionality, Buddy needs appropriate GitHub permissions."),console.log(`This enables workflow file updates and advanced GitHub Actions features.
|
|
128
|
+
`);let K;if(Z.nonInteractive)switch(Z.tokenSetup){case"existing-secret":K={hasCustomToken:!0,needsGuide:!1},console.log("\u2705 Using existing organization/repository secrets");break;case"new-pat":K={hasCustomToken:!0,needsGuide:!0},console.log("\u26A0\uFE0F Non-interactive mode: Will use custom token but skip setup guide");break;case"default-token":default:K={hasCustomToken:!1,needsGuide:!1},console.log("\u2705 Using default GITHUB_TOKEN (limited functionality)");break}else if(K=await j1(),K.needsGuide)await X1(H);m(J,"Repository Settings",!0),f(J),console.log(`
|
|
129
|
+
\uD83D\uDD27 Repository Settings`),await q1(H),m(J,"Workflow Configuration",!0),f(J),console.log(`
|
|
130
|
+
\u2699\uFE0F Workflow Configuration`);let W;if(Z.nonInteractive)W={useCase:Z.preset},console.log(`\u2705 Using ${Z.preset} preset for workflow configuration`);else if(W=await s.default([{type:"select",name:"useCase",message:"What type of update schedule would you like?",choices:[{title:"Standard Setup (Recommended)",description:"Dashboard updates 3x/week, dependency updates on schedule",value:"standard"},{title:"High Frequency",description:"Check for updates multiple times per day",value:"high-frequency"},{title:"Security Focused",description:"Frequent patch updates with security-first approach",value:"security"},{title:"Minimal Updates",description:"Weekly checks, lower frequency",value:"minimal"},{title:"Development/Testing",description:"Manual triggers + frequent checks for testing",value:"testing"},{title:"Custom Configuration",description:"Create your own schedule",value:"custom"}]}]),!W.useCase){console.log("Setup cancelled.");return}m(J,"Configuration File",!0),f(J),console.log(`
|
|
131
|
+
\uD83D\uDCDD Configuration File`),await G1(H,K.hasCustomToken),m(J,"Workflow Generation",!0),f(J),console.log(`
|
|
132
|
+
\uD83D\uDD04 Workflow Generation`);let F=H1(W.useCase);if(W.useCase==="custom"&&!Z.nonInteractive)await W1(F,$);else console.log(`\u2728 Setting up ${F.name}...`),console.log(`\uD83D\uDCCB ${F.description}`);await K1(F,H,K.hasCustomToken,$),m(J,"Workflow Validation",!0),f(J),console.log(`
|
|
133
|
+
\uD83D\uDD0D Validating Generated Workflows`);let L=[{name:"buddy-dashboard.yml",content:""},{name:"buddy-check.yml",content:""},{name:"buddy-update.yml",content:""}],B=!0;for(let P of L)try{let O=`.github/workflows/${P.name}`;if(r0.existsSync(O)){let w=r0.readFileSync(O,"utf8"),I=await U1(w);if(!I.success)console.log(`\u274C ${P.name} validation failed`),W0(I,`${P.name} Issues`),B=!1;else console.log(`\u2705 ${P.name} validated successfully`)}}catch{console.log(`\u26A0\uFE0F Could not validate ${P.name}`)}if(!B)console.log(`
|
|
134
|
+
\u26A0\uFE0F Some workflows have validation issues. Please review the warnings above.`);if(m(J,"Setup Complete",!0),f(J),console.log(`
|
|
135
|
+
\uD83C\uDF89 Setup Complete!`),await F1(H,K.hasCustomToken),j.length>0){console.log(`
|
|
136
|
+
\uD83D\uDD0C Executing integration hooks...`);let P={step:"setup_complete",progress:J,config:Y.length>0?Y[0].migratedSettings:{},repository:H,analysis:X,plugins:j};U.setContext(P),await U.executePluginHooks({event:"setup_complete"})}}catch(J){$.error("Setup failed:",J),V.exit(1)}});T.command("scan","Scan for dependency updates").option("--verbose, -v","Enable verbose logging").option("--packages <names>","Comma-separated list of packages to check").option("--pattern <pattern>","Glob pattern to match packages").option("--strategy <type>","Update strategy: major|minor|patch|all",{default:"all"}).option("--ignore <names>","Comma-separated list of packages to ignore").option("--respect-latest",'Respect "latest", "*", and other dynamic version indicators (default: true)').option("--no-respect-latest",'Allow updating "latest", "*", and other dynamic version indicators').example("buddy scan").example("buddy scan --verbose").example('buddy scan --packages "react,typescript,laravel/framework"').example('buddy scan --pattern "@types/*"').example("buddy scan --strategy minor").example("buddy scan --no-respect-latest").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{$.info("Loading configuration...");let Q;if(Z.packages)Q=Z.packages.split(",").map((G)=>G.trim());let z;if(Z.ignore)z=Z.ignore.split(",").map((G)=>G.trim());let Y={...J,verbose:Z.verbose??J.verbose,packages:{...J.packages,strategy:Z.strategy??J.packages?.strategy??"all",ignore:z??J.packages?.ignore,respectLatest:Z.respectLatest??J.packages?.respectLatest??!0}},U=new g(Y);if(Q?.length){$.info(`Checking specific packages: ${Q.join(", ")}`);let G=await U.checkPackages(Q);if(G.length===0)$.success("All specified packages are up to date!");else{$.info(`Found ${G.length} updates:`);for(let K of G)$.info(` ${K.name}: ${K.currentVersion} \u2192 ${K.newVersion} (${K.updateType})`)}return}if(Z.pattern){$.info(`Checking packages with pattern: ${Z.pattern}`);let G=await U.checkPackagesWithPattern(Z.pattern);if(G.length===0)$.success("All matching packages are up to date!");else{$.info(`Found ${G.length} updates:`);for(let K of G)$.info(` ${K.name}: ${K.currentVersion} \u2192 ${K.newVersion} (${K.updateType})`)}return}let j=await U.scanForUpdates();if(j.updates.length===0){$.success("All dependencies are up to date!");return}$.info(`
|
|
137
|
+
Scan Results:`),$.info(`\uD83D\uDCE6 Total packages: ${j.totalPackages}`),$.info(`\uD83D\uDD04 Available updates: ${j.updates.length}`),$.info(`\u23F1\uFE0F Scan duration: ${j.duration}ms`);let q=j.updates.filter((G)=>G.updateType==="major"),X=j.updates.filter((G)=>G.updateType==="minor"),H=j.updates.filter((G)=>G.updateType==="patch");if(q.length>0){$.warn(`
|
|
138
|
+
\uD83D\uDEA8 Major updates (${q.length}):`);for(let G of q)$.info(` ${G.name}: ${G.currentVersion} \u2192 ${G.newVersion}`)}if(X.length>0){$.info(`
|
|
139
|
+
\u2728 Minor updates (${X.length}):`);for(let G of X)$.info(` ${G.name}: ${G.currentVersion} \u2192 ${G.newVersion}`)}if(H.length>0){$.info(`
|
|
140
|
+
\uD83D\uDD27 Patch updates (${H.length}):`);for(let G of H)$.info(` ${G.name}: ${G.currentVersion} \u2192 ${G.newVersion}`)}if(j.groups.length>0){$.info(`
|
|
141
|
+
\uD83D\uDCCB Update groups (${j.groups.length}):`);for(let G of j.groups)$.info(` ${G.name}: ${G.updates.length} updates`)}}catch(Q){$.error("Scan failed:",Q),V.exit(1)}});T.command("dashboard","Create or update dependency dashboard issue").option("--verbose, -v","Enable verbose logging").option("--title <title>","Custom dashboard title").option("--issue-number <number>","Update specific issue number").option("--pin","Pin the dashboard issue to the top of the issue list").option("--no-pin","Unpin the dashboard issue").example("buddy dashboard").example('buddy dashboard --title "My Dependencies"').example("buddy dashboard --issue-number 42").example("buddy dashboard --pin").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{if($.info("Creating or updating dependency dashboard..."),!J.repository)$.error("\u274C Repository configuration required for dashboard"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q={...J,verbose:Z.verbose??J.verbose,dashboard:{...J.dashboard,enabled:!0,title:Z.title??J.dashboard?.title,issueNumber:Z.issueNumber?Number.parseInt(Z.issueNumber,10):J.dashboard?.issueNumber,pin:Z.pin??J.dashboard?.pin}},Y=await new g(Q).createOrUpdateDashboard();$.success(`\u2705 Dashboard updated: ${Y.url}`),$.info(`\uD83D\uDCCA Issue #${Y.number}: ${Y.title}`)}catch(Q){$.error("Dashboard creation failed:",Q),V.exit(1)}});T.command("update","Update dependencies and create PRs").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all",{default:"all"}).option("--ignore <names>","Comma-separated list of packages to ignore").option("--dry-run","Preview changes without making them").option("--respect-latest",'Respect "latest", "*", and other dynamic version indicators (default: true)').option("--no-respect-latest",'Allow updating "latest", "*", and other dynamic version indicators').example("buddy update").example("buddy update --dry-run").example("buddy update --strategy patch").example("buddy update --verbose").example("buddy update --no-respect-latest").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{$.info("Starting dependency update process...");let Q;if(Z.ignore)Q=Z.ignore.split(",").map((j)=>j.trim());let z={...J,verbose:Z.verbose??J.verbose,packages:{...J.packages,strategy:Z.strategy??J.packages?.strategy??"all",ignore:Q??J.packages?.ignore,respectLatest:Z.respectLatest??J.packages?.respectLatest??!0}},Y=new g(z),U=await Y.scanForUpdates();if(U.updates.length===0){$.success("All dependencies are up to date!");return}if(Z.dryRun){$.info("\uD83D\uDD0D Dry run mode - no changes will be made"),$.info(`Would create ${U.groups.length} pull request(s):`);for(let j of U.groups)$.info(` \uD83D\uDCDD ${j.title} (${j.updates.length} updates)`);return}await Y.createPullRequests(U),$.success("Update process completed!")}catch(Q){$.error("Update failed:",Q),V.exit(1)}});T.command("rebase <pr-number>","Rebase/retry a pull request by recreating it with latest updates").option("--verbose, -v","Enable verbose logging").option("--force","Force rebase even if PR appears to be up to date").example("buddy rebase 17").example("buddy rebase 17 --verbose").example("buddy rebase 17 --force").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config);try{if(J.info(`\uD83D\uDD04 Rebasing/retrying PR #${Z}...`),!Q.repository)J.error("\u274C Repository configuration required for PR operations"),J.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let z=await d(Q,"PR operations",J),Y=Number.parseInt(Z,10);if(Number.isNaN(Y))J.error("\u274C Invalid PR number provided"),V.exit(1);let j=(await z.getPullRequests("open")).find((O)=>O.number===Y);if(!j)J.error(`\u274C Could not find open PR #${Y}`),V.exit(1);if(!j.head.startsWith("buddy/"))J.error(`\u274C PR #${Y} is not a buddy PR (branch: ${j.head})`),V.exit(1);J.info(`\uD83D\uDCCB Found PR: ${j.title}`),J.info(`\uD83C\uDF3F Branch: ${j.head}`);let q=await RZ(j.body);if(q.length===0)J.error("\u274C Could not extract package updates from PR body"),V.exit(1);if(J.info(`\uD83D\uDCE6 Found ${q.length} packages to update`),!$.force){J.info("\uD83D\uDD0D Checking if rebase is needed...");let I=(await new g(Q).scanForUpdates()).updates.filter((v)=>q.some((b)=>b.name===v.name));if(q.every((v)=>I.some((b)=>b.name===v.name&&b.newVersion===v.newVersion))){J.success("\u2705 PR is already up to date, no rebase needed"),J.info("\uD83D\uDCA1 Use --force to rebase anyway");return}}J.info("\uD83D\uDD04 Updating PR with latest updates...");let X=new g({...Q,verbose:$.verbose??Q.verbose}),H=await X.scanForUpdates();if(H.updates.length===0){J.success("\u2705 All dependencies are now up to date!");return}let G=H.groups.find((O)=>O.updates.length===q.length&&O.updates.every((w)=>q.some((I)=>I.name===w.name))&&q.every((w)=>O.updates.some((I)=>I.name===w.name)));if(!G){J.error("\u274C Could not find matching update group. This likely means the package grouping has changed."),J.info(`\uD83D\uDCCB PR packages: ${q.map((O)=>O.name).join(", ")}`),J.info(`\uD83D\uDCCB Available groups: ${H.groups.map((O)=>`${O.name} (${O.updates.length} packages)`).join(", ")}`),J.info("\uD83D\uDCA1 Close this PR manually and let buddy create new ones with correct grouping");return}let K=await X.generateAllFileUpdates(G.updates);if(K.length===0){J.info(`\u2139\uFE0F No file changes generated for PR #${Y} \u2014 likely a pantry/pkgx-style dep with no JS writer. Skipping commit to avoid an empty force-push.`);let O=j.body||"",w=O.replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");if(w!==O)await z.updatePullRequest(Y,{body:w}),J.info("\u2705 Unticked rebase checkbox to prevent the next update-check run from re-triggering this no-op rebase.");return}let W=Q.repository?.baseBranch||"main";await z.commitChanges(j.head,G.title,K,W),J.info(`\u2705 Recreated branch ${j.head} from ${W} with latest changes`);let{PullRequestGenerator:F}=await import("../chunk-9p1xkmjy.js"),P=(await new F({verbose:$.verbose}).generateBody(G)).replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");await z.updatePullRequest(Y,{title:G.title,body:P}),J.success("\uD83D\uDD04 PR rebase completed! Updated existing PR in place.")}catch(z){J.error("Rebase failed:",z),V.exit(1)}});async function RZ(Z){let $=s0(Z);if($?.truncated)return[];if($)return t0($);let J=[],Q=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`\^?([^`]+)`\s*->\s*`\^?([^`]+)`\]?/g,z;while((z=Q.exec(Z))!==null){let[,Y,U,j]=z;J.push({name:Y,currentVersion:U,newVersion:j})}return J}T.command("update-check","Check all open buddy PRs for rebase checkbox and auto-rebase if checked").option("--verbose, -v","Enable verbose logging").option("--dry-run","Check but don't actually rebase").example("buddy update-check").example("buddy update-check --verbose").example("buddy update-check --dry-run").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{if(!J.repository)$.error("\u274C Repository configuration required for PR operations"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q=await d(J,"PR operations",$),z=await CZ(Q,J,$),Y=n0(z?.body);if(A0(Y))$.info(`\uD83D\uDCCB Dashboard requests: ${Y.rebaseBranches.length} branch(es)${Y.rebaseAll?", rebase all":""}${Y.manualRun?", manual run":""}`);let U=new Set(Y.rebaseBranches);$.info("\uD83D\uDD0D Checking for PRs with rebase checkbox enabled...");let j=0,q=0;try{let K=(await Q.getPullRequests("open")).filter((W)=>W.head.startsWith("buddy/"));$.info(`\uD83D\uDCCB Found ${K.length} buddy PRs to check for rebase requests`);for(let W of K){q++;let F=Y.rebaseAll||U.has(W.head);if(SZ(W.body||"")||F)if($.info(`\uD83D\uDD04 PR #${W.number} has rebase ${F?"requested from the dashboard":"checkbox checked"}`),Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would rebase PR #${W.number}`),j++;else{$.info(`\uD83D\uDD04 Rebasing PR #${W.number} via rebase command...`);try{let{spawn:B}=await import("child_process"),P=B("bunx",["@buddysh/buddy","rebase",W.number.toString()],{stdio:"inherit",cwd:V.cwd()});await new Promise((O,w)=>{P.on("close",(I)=>{if(I===0)j++,O(I);else w(Error(`Rebase failed with code ${I}`))})}),$.success(`\u2705 Successfully rebased PR #${W.number}`)}catch(B){$.error(`\u274C Failed to rebase PR #${W.number}:`,B)}}}if(j>0)$.success(`\u2705 ${Z.dryRun?"Would rebase":"Successfully rebased"} ${j} PR(s)`);else if(q>0)$.info("\uD83D\uDCCB No PRs have rebase checkbox enabled")}catch(G){$.warn("\u26A0\uFE0F Could not check for rebase requests:",G)}if(A0(Y)&&z){if(Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would clear dashboard checkboxes");else try{await Q.updateIssue(z.number,{body:a0(z.body||"")}),$.success("\u2705 Cleared dashboard checkboxes")}catch(G){$.warn("\u26A0\uFE0F Could not clear dashboard checkboxes:",G)}if(Y.manualRun)if($.info("\uD83D\uDD04 Dashboard requested a full update run..."),Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would run a full scan and create PRs");else try{let G=new g(J),K=await G.scanForUpdates();if(K.updates.length>0)await G.createPullRequests(K);else $.info("\u2705 No updates found during the requested run")}catch(G){$.error("\u274C Requested update run failed:",G)}}$.info(`
|
|
142
|
+
\u2705 Checking for PRs with satisfied dependencies...`);try{let{Buddy:G}=await import("../chunk-0r8zt3d7.js");await new G(J).checkAndCloseSatisfiedPRs(Q,!!Z.dryRun)}catch(G){$.error("\u26A0\uFE0F Could not check for satisfied PRs:",G)}$.info(`
|
|
143
|
+
\uD83D\uDD0D Checking for obsolete PRs due to removed dependency files...`);try{let{Buddy:G}=await import("../chunk-0r8zt3d7.js");await new G(J).checkAndCloseObsoletePRs(Q,!!Z.dryRun)}catch(G){$.error("\u26A0\uFE0F Could not check for obsolete PRs:",G)}let X=0;try{if(X=(await new g(J).mergeEligiblePullRequests(!!Z.dryRun)).length,X>0)$.success(`\uD83D\uDD00 ${Z.dryRun?"Would merge":"Merged"} ${X} PR(s)`)}catch(G){$.warn("\u26A0\uFE0F Could not process auto-merge:",G)}$.info(`
|
|
144
|
+
\uD83E\uDDF9 Running branch cleanup...`),r(Q,"branchHousekeeping","cleanupStaleBranches","branch cleanup");let H=await Q.cleanupStaleBranches(2,!!Z.dryRun);if(Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would delete ${H.deleted.length} stale branches`);else $.success(`\uD83C\uDF89 Cleanup complete: ${H.deleted.length} branches deleted, ${H.failed.length} failed`);if(j>0||X>0||H.deleted.length>0)$.success(`
|
|
145
|
+
\uD83C\uDF89 Update-check complete: ${j} PR(s) rebased, ${X} merged, ${H.deleted.length} branches cleaned`)}catch(Q){$.error("update-check failed:",Q),V.exit(1)}});async function CZ(Z,$,J){try{let Q=await Z.getIssues("open"),z=$.dashboard?.issueNumber;if(z)return Q.find((U)=>U.number===z)??null;let Y=$.dashboard?.title??"Dependency Dashboard";return Q.find((U)=>U.title===Y)??Q.find((U)=>U.title.includes("Dependency Dashboard"))??null}catch(Q){return J.warn("\u26A0\uFE0F Could not load the dependency dashboard:",Q),null}}function SZ(Z){return/\s*-\s*\[x\]\s*<!--\s*rebase-check\s*-->.*(?:rebase|update)\/retry/i.test(Z)}T.command("fix-ci","Diagnose a failing workflow run and repair it when the fix is clear").option("--verbose, -v","Enable verbose logging").option("--run-id <id>","Workflow run to diagnose").option("--pr <number>","Pull request to comment on").option("--dry-run","Report the diagnosis without acting").example("buddy fix-ci --run-id 12345").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{let Q=await d(J,"this command",$);r(Q,"ciLogs","getWorkflowRunLogs","reading CI logs");let z=Z.runId?Number.parseInt(Z.runId,10):void 0,Y=z?await Q.getWorkflowRunLogs(z):null;if(!Y){$.warn("\u26A0\uFE0F Could not read the run logs; nothing to diagnose");return}let{attemptFix:U}=await import("../chunk-nsmcjkas.js"),{createAiClient:j}=await import("../chunk-54sc18p8.js"),q=await U({log:Y,workspace:V.cwd(),baseBranch:J.repository?.baseBranch??"main",ai:j(J,$),logger:$,regenerateLockfile:async()=>{let{regenerateLockFile:H,detectRequiredPackageManagers:G}=await import("../chunk-887s0w81.js"),K=G(["package.json","composer.json"]),W=!1;for(let F of K){let L=await H(F,V.cwd());if(L.success)W=!0;else $.warn(`\u26A0\uFE0F ${L.message}`)}return W}});$.info(`
|
|
146
|
+
${q.report}
|
|
147
|
+
`);let X=Z.pr?Number.parseInt(Z.pr,10):void 0;if(X&&!Z.dryRun)await Q.createComment(X,q.report);$.success(`\u2705 ${q.action}${q.fixed?" (fixed)":""}`)}catch(Q){$.error("fix-ci failed:",Q),V.exit(1)}});T.command("handle-comment","Handle an @buddy command from a GitHub event payload").option("--verbose, -v","Enable verbose logging").option("--payload <path>","Path to the event payload (default: GITHUB_EVENT_PATH)").option("--dry-run","Report what would run without acting").example("buddy handle-comment").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{let Q=Z.payload||V.env.GITHUB_EVENT_PATH;if(!Q)$.error("\u274C No event payload. Pass --payload or run inside GitHub Actions."),V.exit(1);let z=await Bun.file(Q).json(),Y=z.comment,U=z.issue??z.pull_request;if(!Y?.body||!U?.number){$.info("\u2139\uFE0F Event carries no comment; nothing to do");return}let{mentionsBot:j,parseCommand:q}=await import("../chunk-qvn1rtgp.js");if(!j(Y.body)){$.info("\u2139\uFE0F Comment does not mention buddy; nothing to do");return}let X=q(Y.body);if(!X){$.info("\u2139\uFE0F Mention is not a command (quoted or inside code); nothing to do");return}let H=await d(J,"this command",$),G=Y.user?.login??"",K=Y.user?.type==="Bot"||G.endsWith("[bot]"),W={login:G,isBot:K,canWrite:!K&&z0(H,"permissionLookup","hasWriteAccess")?await H.hasWriteAccess(G):!1},F=Boolean(z.pull_request??z.issue?.pull_request);if($.info(`\uD83E\uDD16 Handling \`${X.name}\` from @${G} on #${U.number}`),Z.dryRun){$.info(`\uD83D\uDD0D [DRY RUN] Would run ${X.name} (canWrite: ${W.canWrite})`);return}if(z0(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,"eyes");let{createHandlers:L,dispatchCommand:B}=await import("../chunk-qvn1rtgp.js"),{runReviewForPR:P}=await import("../chunk-pkjm2r0a.js"),O=await B({command:X,actor:W,number:U.number,isPullRequest:F,commentId:Y.id,logger:$},L({config:J,provider:H,review:async(w,I)=>await P({config:J,provider:H,prNumber:w,logger:$,...I}),rebase:async(w)=>{let{spawn:I}=await import("child_process");return await new Promise((k,v)=>{I("bunx",["@buddysh/buddy","rebase",String(w)],{stdio:"inherit"}).on("close",(y)=>y===0?k():v(Error(`rebase exited ${y}`)))}),"Rebased."},merge:async()=>await new g(J).mergeEligiblePullRequests(!1),remember:async(w,I)=>{let{addLearning:k,createLearning:v,loadLearnings:b,serializeLearnings:y,DEFAULT_LEARNINGS_FILE:c}=await import("../chunk-54sc18p8.js"),E=J.repository?.baseBranch??"main",h=await b((N,S)=>H.getFileContent(N,S),E,c,$),_=v(w,{source:I.isPullRequest?{pr:I.number}:{issue:I.number}}),u=`buddy/learning-${_.id}`;return await H.commitChanges(u,"chore(buddy): record a learning",[{path:c,content:y(k(h,_)),type:"update"}],E),await H.createPullRequest({title:"chore(buddy): record a learning",body:`Recorded from #${I.number}:
|
|
148
|
+
|
|
149
|
+
> ${w}`,head:u,base:E,draft:!1}),`Noted. I opened a pull request adding it to \`${c}\` so it gets reviewed like any other change.`}}));if(O.reply)await H.createComment(U.number,O.reply);if(z0(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,O.handled?"rocket":"confused");$.success(O.handled?`\u2705 Handled \`${X.name}\``:`\u2139\uFE0F Did not run: ${O.refusal}`)}catch(Q){$.error("handle-comment failed:",Q),V.exit(1)}});T.command("review [pr-number]","Review a pull request, or local changes when no PR is given").option("--verbose, -v","Enable verbose logging").option("--base <branch>","Base branch to diff against for a local review").option("--staged","Review staged changes only").option("--branch","Review this branch against its base, rather than the working tree").option("--light","Analyzers only \u2014 no AI call, fast enough for a pre-commit hook").option("--format <name>","Output format: pretty|json|github|agent",{default:"pretty"}).option("--fix","Apply committable suggestions to the working tree").option("--yes","Apply fixes without confirming each one").option("--fail-on <severity>","Exit non-zero when a finding at or above this severity is found").option("--profile <name>","Review profile: chill|assertive").option("--summary-only","Post only the summary, without inline findings").option("--dry-run","Print the review instead of posting it").example("buddy review 42").example("buddy review --staged --light").example("buddy review --format agent | claude").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config),z=$.format??"pretty";if(!R0.includes(z))J.error(`\u274C Unknown format '${z}'. Expected one of ${R0.join(", ")}.`),V.exit(1);let Y=z!=="pretty",U=Y?M.silent():J;try{let{createAiClient:j}=await import("../chunk-54sc18p8.js"),q=j(Q,U);if(!q&&(Z||!$.light))J.error("\u274C AI review needs an API key, or use --light for analyzers only. See https://buddy.sh/ai/providers"),V.exit(1);let{composeInstructions:X,loadGuidelines:H,parseReviewState:G,prepareReview:K,reviewDiff:W}=await import("../chunk-p3wsm8kz.js"),{collectLocalDiff:F,formatReview:L,shouldFail:B}=await import("../chunk-63ept76v.js"),{runAnalyzers:P}=await import("../chunk-4hd3rre0.js"),O,w="",I=[],k=null;if(Z){k=await d(Q,"reviewing a pull request",U);let N=Number.parseInt(Z,10);O=await k.getPullRequestDiff(N);let o=(await k.getPullRequests("open")).find((Y0)=>Y0.number===N),n=G(o?.body);I=n?.fingerprints??[],w=n?.reviewedSha??""}else{let N=$.base||Q.repository?.baseBranch||"main",S=$.staged?"staged":$.branch?"branch":"working";U.info(`\uD83D\uDD0D Reviewing ${S} changes${S==="branch"?` against ${N}`:""}...`),O=await F(S,N)}if(!O.trim()){if(!Y)J.success("\u2705 No changes to review");return}let{parseUnifiedDiff:v}=await import("../chunk-mh3x7j6h.js"),b=v(O).files.map((N)=>N.path),y=Q.analysis?.enabled===!1||Z?{findings:[],ran:[],skipped:[]}:await P({files:b,root:V.cwd(),...Q.analysis?.tools?{enabled:Q.analysis.tools}:{},logger:U});if($.light){let N={summary:`Static analysis of ${b.length} changed file(s).`,walkthrough:[],findings:y.findings,effort:1,omittedFiles:y.skipped.map((S)=>`${S.name} (${S.reason})`)};if(V.stdout.write(L(N,z)),$.failOn&&B(N.findings,$.failOn))V.exit(1);return}let c=Q.repository?.baseBranch||$.base||"main",E=k?await H((N,S)=>k.getFileContent(N,S),c,Q.ai?.review?.guidelineFiles,J):"",h=await W(q,{diff:O,profile:$.profile??Q.ai?.review?.profile,summaryOnly:$.summaryOnly??Q.ai?.review?.summaryOnly,instructions:X({global:Q.ai?.review?.instructions,guidelines:E}),pathFilters:Q.ai?.review?.pathFilters,pathInstructions:Q.ai?.review?.pathInstructions,seenFingerprints:I,logger:U}),_={...h,findings:[...y.findings,...h.findings],omittedFiles:[...h.omittedFiles,...y.skipped.map((N)=>`${N.name} (${N.reason})`)]},u=K(_,{headSha:w,requestChangesOn:Q.ai?.review?.requestChangesOn,seenFingerprints:I});if(!Z){if(V.stdout.write(L(_,z)),$.fix){let N=await AZ(_.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${N} suggestion(s)`)}if($.failOn&&B(_.findings,$.failOn))V.exit(1);return}if($.dryRun){J.info(`
|
|
150
|
+
${u.body}
|
|
151
|
+
`);for(let N of u.comments)J.info(`${N.path}:${N.line}
|
|
152
|
+
${N.body}
|
|
153
|
+
`);J.success(`\u2705 Review complete: ${_.findings.length} finding(s)`);return}r(k,"inlineReviewComments","createReview","posting a review"),await k.createReview(Number.parseInt(Z,10),u),J.success(`\u2705 Reviewed PR #${Z}: ${_.findings.length} finding(s)`)}catch(j){J.error("Review failed:",j),V.exit(1)}});T.command("check <packages...>","Check specific packages for updates").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all",{default:"all"}).example("buddy check react typescript").example("buddy check react --verbose").action(async(...Z)=>{let $=Z[Z.length-1],J=Z.slice(0,-1),Q=$.verbose?M.verbose():M.quiet(),z=await C($.config);if(!J.length)Q.error("No packages specified to check"),V.exit(1);try{Q.info(`Checking specific packages: ${J.join(", ")}`);let Y={...z,verbose:$.verbose??z.verbose,packages:{...z.packages,strategy:$.strategy??z.packages?.strategy??"all"}},j=await new g(Y).checkPackages(J);if(j.length===0)Q.success("All specified packages are up to date!");else{Q.info(`Found ${j.length} updates:`);for(let q of j)Q.info(` ${q.name}: ${q.currentVersion} \u2192 ${q.newVersion} (${q.updateType})`)}}catch(Y){Q.error("Check failed:",Y),V.exit(1)}});T.command("schedule","Run automated dependency updates on schedule").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all",{default:"all"}).example("buddy schedule").example("buddy schedule --verbose").example("buddy schedule --strategy patch").action(async(Z)=>{let{Scheduler:$}=await import("../chunk-1xe07hzm.js"),J=Z.verbose?M.verbose():M.quiet(),Q=await C(Z.config);try{J.info("\uD83D\uDD52 Starting Buddy Scheduler...");let z;if(Z.ignore)z=Z.ignore.split(",").map((q)=>q.trim());let Y={...Q,verbose:Z.verbose??Q.verbose,packages:{...Q.packages,strategy:Z.strategy??Q.packages?.strategy??"all",ignore:z??Q.packages?.ignore}};if(!Y.repository?.provider||!Y.repository?.owner||!Y.repository?.name)J.error("\u274C Repository configuration required for scheduling. Please configure:"),J.info(" - repository.provider (github)"),J.info(" - repository.owner"),J.info(" - repository.name"),J.info(" - repository.token (via environment variable)"),V.exit(1);let U=new $(Z.verbose),j=$.createJobFromConfig(Y,"cli-schedule");if(Z.strategy)switch(Z.strategy){case"major":j.schedule.cron=$.PRESETS.WEEKLY;break;case"minor":j.schedule.cron=$.PRESETS.TWICE_WEEKLY;break;case"patch":j.schedule.cron=$.PRESETS.DAILY;break;default:j.schedule.cron=$.PRESETS.WEEKLY}U.addJob(j),U.start(),J.success(`\u2705 Scheduler started with cron: ${j.schedule.cron}`),J.info("\uD83D\uDCC5 Next run:",j.nextRun?.toISOString()||"Unknown"),J.info("\uD83D\uDED1 Press Ctrl+C to stop the scheduler"),V.stdin.resume()}catch(z){J.error("Scheduler failed:",z),V.exit(1)}});T.command("generate-workflows",'Generate GitHub Actions workflow templates (deprecated - use "setup" instead)').option("--verbose, -v","Enable verbose logging").example("buddy generate-workflows").example("buddy generate-workflows --verbose").action(async(Z)=>{let{GitHubActionsTemplate:$}=await import("../chunk-k62w2v03.js"),{writeFileSync:J,mkdirSync:Q}=await import("fs"),{resolve:z}=await import("path"),Y=Z.verbose?M.verbose():M.quiet(),U=await C(Z.config);console.log('\u26A0\uFE0F The "generate-workflows" command is deprecated.'),console.log(`\uD83D\uDCA1 Use "buddy setup" for a better interactive experience.
|
|
154
|
+
`);try{let j={...U,verbose:Z.verbose??U.verbose},q=j.workflows?.outputDir?z(V.cwd(),j.workflows.outputDir):z(V.cwd(),".github","workflows");Y.info("\uD83D\uDE80 Generating GitHub Actions workflow templates...");try{Q(q,{recursive:!0})}catch{}let X=j.workflows?.templates||{comprehensive:!0,daily:!0,weekly:!0,monthly:!0,docker:!0,monorepo:!0},H=0;if(X.daily||X.weekly||X.monthly){let G=$.generateScheduledWorkflows(j);for(let[K,W]of Object.entries(G))if(K.includes("daily")&&X.daily||K.includes("weekly")&&X.weekly||K.includes("monthly")&&X.monthly){let L=z(q,K);J(L,W),Y.success(`Generated: ${K}`),H++}}if(X.comprehensive){let G=$.generateComprehensiveWorkflow(j);J(z(q,"buddy-comprehensive.yml"),G),Y.success("Generated: buddy-comprehensive.yml"),H++}if(X.docker){let G=$.generateDockerWorkflow(j);J(z(q,"buddy-docker.yml"),G),Y.success("Generated: buddy-docker.yml"),H++}if(X.monorepo){let G=$.generateMonorepoWorkflow(j);J(z(q,"buddy-monorepo.yml"),G),Y.success("Generated: buddy-monorepo.yml"),H++}if(j.workflows?.custom?.length)for(let G of j.workflows.custom){let K=$.generateCustomWorkflow(G,j),W=`buddy-${G.name.toLowerCase().replace(/\s+/g,"-")}.yml`;J(z(q,W),K),Y.success(`Generated: ${W}`),H++}if(H===0){Y.warn("No workflows were generated. Check your configuration in buddy.config.ts"),Y.info("Set workflows.templates to enable specific templates or add custom workflows.");return}Y.success(`
|
|
155
|
+
\uD83C\uDF89 ${H} GitHub Actions workflow(s) generated!`),Y.info(`\uD83D\uDCC1 Location: ${q}`),Y.info(`
|
|
156
|
+
\uD83D\uDCA1 Next steps:`),Y.info(" 1. Review and customize the workflows for your project"),Y.info(" 2. Ensure GITHUB_TOKEN is available as a secret"),Y.info(" 3. Configure buddy.config.ts with your repository settings"),Y.info(" 4. Enable GitHub Actions in your repository settings"),Y.info(`
|
|
157
|
+
\uD83D\uDD17 Learn more: https://docs.github.com/en/actions`)}catch(j){Y.error("Failed to generate workflows:",j),V.exit(1)}});T.command("info <package>","Show detailed package information").option("--verbose, -v","Enable verbose logging").option("--json","Output in JSON format").example("buddy info react").example("buddy info react --json").example("buddy info typescript@latest").action(async(Z,$)=>{let{RegistryClient:J}=await import("../chunk-s4ms8zag.js"),Q=$.verbose?M.verbose():M.quiet();try{let z=new J(V.cwd(),Q,void 0);if($.json){let{spawn:j}=await import("child_process");j("bun",["info",Z,"--json"],{stdio:"inherit"}).on("close",(X)=>{V.exit(X||0)});return}let Y=await z.getPackageMetadata(Z);if(!Y)Q.error(`Package "${Z}" not found or failed to fetch metadata`),V.exit(1);if(console.log(`\uD83D\uDCE6 ${Y.name}@${Y.latestVersion}`),Y.description)console.log(`\uD83D\uDCDD ${Y.description}`);if(Y.homepage)console.log(`\uD83C\uDF10 ${Y.homepage}`);if(Y.repository)console.log(`\uD83D\uDCC1 ${Y.repository}`);if(Y.license)console.log(`\u2696\uFE0F License: ${Y.license}`);if(Y.author)console.log(`\uD83D\uDC64 Author: ${Y.author}`);if(Y.keywords&&Y.keywords.length>0)console.log(`\uD83C\uDFF7\uFE0F Keywords: ${Y.keywords.join(", ")}`);let U={deps:Object.keys(Y.dependencies||{}).length,devDeps:Object.keys(Y.devDependencies||{}).length,peerDeps:Object.keys(Y.peerDependencies||{}).length};if(console.log(`\uD83D\uDCCA Dependencies: ${U.deps} | Dev: ${U.devDeps} | Peer: ${U.peerDeps}`),Y.versions&&Y.versions.length>1){if(console.log(`\uD83D\uDCC8 ${Y.versions.length} versions available`),$.verbose&&Y.versions.length<=10)console.log(` Latest versions: ${Y.versions.slice(-5).join(", ")}`)}}catch(z){Q.error("Failed to get package info:",z),V.exit(1)}});T.command("versions <package>","Show all available versions of a package").option("--verbose, -v","Enable verbose logging").option("--latest <count>","Show only the latest N versions",{default:"10"}).example("buddy versions react").example("buddy versions react --latest 5").action(async(Z,$)=>{let{RegistryClient:J}=await import("../chunk-s4ms8zag.js"),Q=$.verbose?M.verbose():M.quiet();try{let Y=await new J(V.cwd(),Q,void 0).getPackageMetadata(Z);if(!Y)Q.error(`Package "${Z}" not found`),V.exit(1);let U=Number.parseInt($.latest||"10",10);if(console.log(`\uD83D\uDCE6 ${Y.name} - Available Versions`),console.log(`\uD83D\uDCC8 Total: ${Y.versions?.length||0} versions`),console.log(`\u2B50 Latest: ${Y.latestVersion}`),Y.versions&&Y.versions.length>0){if(console.log(`
|
|
158
|
+
\uD83D\uDCCB Recent versions:`),Y.versions.slice(-U).reverse().forEach((q,X)=>{let G=q===Y.latestVersion?"\u2B50":" ";console.log(`${G} ${q}`)}),Y.versions.length>U)console.log(` ... and ${Y.versions.length-U} older versions`)}}catch(z){Q.error("Failed to get package versions:",z),V.exit(1)}});T.command("exists <package>","Check if a package exists in the registry").option("--verbose, -v","Enable verbose logging").example("buddy exists react").example("buddy exists nonexistent-package-xyz").action(async(Z,$)=>{let{RegistryClient:J}=await import("../chunk-s4ms8zag.js"),Q=$.verbose?M.verbose():M.quiet();try{if(await new J(V.cwd(),Q,void 0).packageExists(Z))console.log(`\u2705 Package "${Z}" exists in the registry`),V.exit(0);else console.log(`\u274C Package "${Z}" does not exist in the registry`),V.exit(1)}catch(z){Q.error("Failed to check package existence:",z),V.exit(1)}});T.command("latest <package>","Get the latest version of a package").option("--verbose, -v","Enable verbose logging").example("buddy latest react").example("buddy latest @types/node").action(async(Z,$)=>{let{RegistryClient:J}=await import("../chunk-s4ms8zag.js"),Q=$.verbose?M.verbose():M.quiet();try{let Y=await new J(V.cwd(),Q,void 0).getLatestVersion(Z);if(Y)console.log(`\uD83D\uDCE6 ${Z}@${Y}`);else Q.error(`Package "${Z}" not found`),V.exit(1)}catch(z){Q.error("Failed to get latest version:",z),V.exit(1)}});T.command("deps <package>","Show dependencies of a package").option("--verbose, -v","Enable verbose logging").option("--dev","Show dev dependencies").option("--peer","Show peer dependencies").option("--all","Show all dependency types").example("buddy deps react").example("buddy deps react --dev").example("buddy deps react --all").action(async(Z,$)=>{let{RegistryClient:J}=await import("../chunk-s4ms8zag.js"),Q=$.verbose?M.verbose():M.quiet();try{let Y=await new J(V.cwd(),Q,void 0).getPackageMetadata(Z);if(!Y)Q.error(`Package "${Z}" not found`),V.exit(1);console.log(`\uD83D\uDCE6 ${Y.name}@${Y.latestVersion} - Dependencies`);let U=!$.dev&&!$.peer,j=$.dev||$.all,q=$.peer||$.all;if(U||$.all){let X=Y.dependencies||{},H=Object.keys(X).length;if(console.log(`
|
|
159
|
+
\uD83D\uDCCB Production Dependencies (${H}):`),H>0)Object.entries(X).forEach(([G,K])=>{console.log(` ${G}: ${K}`)});else console.log(" No production dependencies")}if(j){let X=Y.devDependencies||{},H=Object.keys(X).length;if(console.log(`
|
|
160
|
+
\uD83D\uDEE0\uFE0F Dev Dependencies (${H}):`),H>0)Object.entries(X).forEach(([G,K])=>{console.log(` ${G}: ${K}`)});else console.log(" No dev dependencies")}if(q){let X=Y.peerDependencies||{},H=Object.keys(X).length;if(console.log(`
|
|
161
|
+
\uD83E\uDD1D Peer Dependencies (${H}):`),H>0)Object.entries(X).forEach(([G,K])=>{console.log(` ${G}: ${K}`)});else console.log(" No peer dependencies")}}catch(z){Q.error("Failed to get package dependencies:",z),V.exit(1)}});T.command("compare <package> <version1> <version2>","Compare two versions of a package").option("--verbose, -v","Enable verbose logging").example("buddy compare react 17.0.0 18.0.0").example("buddy compare typescript 4.9.0 5.0.0").action(async(Z,$,J,Q)=>{let z=Q.verbose?M.verbose():M.quiet();try{console.log(`\uD83D\uDCCA Comparing ${Z}: ${$} vs ${J}`);let{RegistryClient:Y}=await import("../chunk-s4ms8zag.js"),j=await new Y(V.cwd(),z,void 0).getPackageMetadata(Z);if(!j)z.error(`Package "${Z}" not found`),V.exit(1);let q=j.versions||[];if(!q.includes($))console.log(`\u26A0\uFE0F Version ${$} not found in available versions`);if(!q.includes(J))console.log(`\u26A0\uFE0F Version ${J} not found in available versions`);let{getUpdateType:X}=await import("../chunk-yqhs08ky.js"),H=X($,J);console.log(`
|
|
162
|
+
\uD83D\uDD0D Version Analysis:`),console.log(` From: ${$}`),console.log(` To: ${J}`),console.log(` Type: ${H} update`);let G=q.indexOf($),K=q.indexOf(J);if(G!==-1&&K!==-1){let W=Math.abs(K-G)-1;if(console.log(` Gap: ${W} versions between them`),K>G)console.log(` \uD83D\uDCC8 ${J} is newer than ${$}`);else console.log(` \uD83D\uDCC9 ${J} is older than ${$}`)}console.log(`
|
|
163
|
+
\uD83D\uDCA1 Use 'buddy versions ${Z}' to see all available versions`),console.log(`\uD83D\uDCA1 Use 'buddy info ${Z}' for detailed package information`)}catch(Y){z.error("Failed to compare versions:",Y),V.exit(1)}});T.command("search <query>","Search for packages in the registry").option("--verbose, -v","Enable verbose logging").option("--limit <count>","Limit number of results",{default:"10"}).example("buddy search react").example('buddy search "test framework" --limit 5').action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet();try{let{spawn:Q}=await import("child_process"),z=Number.parseInt($.limit||"10",10);console.log(`\uD83D\uDD0D Searching for: "${Z}"`),console.log(`\uD83D\uDCCA Showing top ${z} results
|
|
164
|
+
`),Q("which",["npm"],{stdio:"pipe"}).on("close",async(U)=>{if(U!==0){console.log("\uD83D\uDCE1 Using npm registry API search...");try{let{RegistryClient:X}=await import("../chunk-s4ms8zag.js"),G=await new X(V.cwd(),J,void 0).searchPackages(Z,z);if(G.length===0){console.log(`\u274C No packages found for "${Z}"`),console.log("\uD83D\uDCA1 Try different search terms or browse https://www.npmjs.com");return}G.forEach((K,W)=>{if(console.log(`${W+1}. \uD83D\uDCE6 ${K.name}@${K.version}`),K.description)console.log(` \uD83D\uDCDD ${K.description}`);if(K.keywords&&K.keywords.length>0)console.log(` \uD83C\uDFF7\uFE0F ${K.keywords.slice(0,3).join(", ")}${K.keywords.length>3?"...":""}`);console.log()}),console.log("\u2728 Use 'buddy info <package>' for detailed information")}catch{console.log("\u274C Registry API search failed"),console.log("\uD83D\uDCA1 Alternative search options:"),console.log(` \u2022 Visit https://www.npmjs.com/search?q=${encodeURIComponent(Z)}`),console.log(" \u2022 Use: bun add <package-name> to test if a package exists"),console.log(" \u2022 Use: buddy exists <package-name> to check existence")}return}let j=Q("npm",["search",Z,"--json"],{stdio:"pipe"}),q="";j.stdout?.on("data",(X)=>{q+=X.toString()}),j.stderr?.on("data",(X)=>{if($.verbose)J.warn("npm search stderr:",X.toString())}),j.on("close",(X)=>{if(X===0)try{let G=JSON.parse(q).slice(0,z);if(G.length===0){console.log(`\u274C No packages found for "${Z}"`),console.log("\uD83D\uDCA1 Try different search terms or browse https://www.npmjs.com");return}G.forEach((K,W)=>{if(console.log(`${W+1}. \uD83D\uDCE6 ${K.name}@${K.version}`),K.description)console.log(` \uD83D\uDCDD ${K.description}`);if(K.keywords&&K.keywords.length>0)console.log(` \uD83C\uDFF7\uFE0F ${K.keywords.slice(0,3).join(", ")}${K.keywords.length>3?"...":""}`);console.log()}),console.log("\u2728 Use 'buddy info <package>' for detailed information")}catch(H){J.error("Failed to parse search results:",H),console.log(`\uD83D\uDCA1 Try searching at https://www.npmjs.com/search?q=${encodeURIComponent(Z)}`)}else console.log("\u274C Search failed"),console.log(`\uD83D\uDCA1 Try searching at https://www.npmjs.com/search?q=${encodeURIComponent(Z)}`)})})}catch(Q){J.error("Failed to search packages:",Q),console.log(`\uD83D\uDCA1 Try searching at https://www.npmjs.com/search?q=${encodeURIComponent(Z)}`)}});T.command("cleanup","Clean up stale buddy branches that don't have associated open PRs").option("--verbose, -v","Enable verbose logging").option("--dry-run","Show what would be deleted without actually deleting").option("--days <number>","Delete branches older than N days (default: 7)",{default:"7"}).option("--force","Force cleanup without confirmation prompt").example("buddy cleanup").example("buddy cleanup --dry-run").example("buddy cleanup --days 14").example("buddy cleanup --force").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{if($.info("\uD83E\uDDF9 Starting buddy branch cleanup..."),!J.repository)$.error("\u274C Repository configuration required for branch cleanup"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q=await d(J,"branch operations",$),z=Number.parseInt(Z.days||"7",10);if(Number.isNaN(z)||z<1)$.error("\u274C Invalid days value. Must be a positive number."),V.exit(1);$.info(`\uD83D\uDD0D Looking for buddy branches older than ${z} days...`),r(Q,"branchHousekeeping","getOrphanedBuddyBranches","branch cleanup");let Y=await Q.getOrphanedBuddyBranches(),U=new Date;U.setDate(U.getDate()-z);let j=Y.filter((X)=>X.lastCommitDate<U);if(j.length===0){$.success("\u2705 No stale branches found!"),$.info(`\uD83D\uDCCA Total buddy branches: ${Y.length}`),$.info(`\uD83D\uDCCA Stale branches (>${z} days): 0`);return}if($.info(`\uD83D\uDCCA Found ${j.length} stale branches to clean up:`),j.forEach((X)=>{let H=Math.floor((Date.now()-X.lastCommitDate.getTime())/86400000);$.info(` - ${X.name} (${H} days old)`)}),Z.dryRun){$.info(`
|
|
165
|
+
\uD83D\uDD0D [DRY RUN] These branches would be deleted`),$.info("\uD83D\uDCA1 Run without --dry-run to actually delete them");return}if(!Z.force){if(!(await s.default({type:"confirm",name:"confirmed",message:`Are you sure you want to delete ${j.length} stale branches?`,initial:!1})).confirmed){$.info("\u274C Cleanup cancelled");return}}r(Q,"branchHousekeeping","cleanupStaleBranches","branch cleanup");let q=await Q.cleanupStaleBranches(z,!1);if(q.deleted.length>0)$.success(`\u2705 Successfully deleted ${q.deleted.length} stale branches`);if(q.failed.length>0)$.warn(`\u26A0\uFE0F Failed to delete ${q.failed.length} branches`),q.failed.forEach((X)=>$.warn(` - ${X}`));$.info(`
|
|
166
|
+
\uD83D\uDCCA Cleanup Summary:`),$.info(` \u2705 Deleted: ${q.deleted.length}`),$.info(` \u274C Failed: ${q.failed.length}`),$.info(` \uD83D\uDCCA Total processed: ${j.length}`)}catch(Q){$.error("Branch cleanup failed:",Q),V.exit(1)}});T.command("list-branches","List all buddy branches and their status").option("--verbose, -v","Enable verbose logging").option("--orphaned-only","Show only branches without associated open PRs").option("--stale-only","Show only stale branches (older than 7 days)").option("--days <number>","Define stale threshold in days (default: 7)",{default:"7"}).example("buddy list-branches").example("buddy list-branches --orphaned-only").example("buddy list-branches --stale-only --days 14").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{if($.info("\uD83D\uDCCB Listing buddy branches..."),!J.repository)$.error("\u274C Repository configuration required for branch listing"),$.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts"),V.exit(1);let Q=await d(J,"branch operations",$),z=Number.parseInt(Z.days||"7",10),Y=new Date;Y.setDate(Y.getDate()-z),r(Q,"branchHousekeeping","getBuddyBranches","branch listing");let[U,j]=await Promise.all([Q.getBuddyBranches(),Q.getPullRequests("open")]),q=new Set(j.map((K)=>K.head)),X=U;if(Z.orphanedOnly)X=X.filter((K)=>!q.has(K.name));if(Z.staleOnly)X=X.filter((K)=>K.lastCommitDate<Y&&!q.has(K.name));if(X.length===0){if(Z.orphanedOnly&&Z.staleOnly)$.success("\u2705 No stale orphaned branches found!");else if(Z.orphanedOnly)$.success("\u2705 No orphaned branches found!");else if(Z.staleOnly)$.success("\u2705 No stale branches found!");else $.info("\uD83D\uDCCB No buddy branches found");return}console.log(`
|
|
167
|
+
\uD83D\uDCCA Found ${X.length} buddy branch${X.length!==1?"es":""}:
|
|
168
|
+
`),X.sort((K,W)=>W.lastCommitDate.getTime()-K.lastCommitDate.getTime()),X.forEach((K)=>{let W=q.has(K.name),F=Math.floor((Date.now()-K.lastCommitDate.getTime())/86400000),L=K.lastCommitDate<Y,B=W?"\uD83D\uDD34 Open PR":L?"\uD83D\uDFE1 Stale":"\uD83D\uDFE2 Recent",P=K.sha.substring(0,7);console.log(`${B} ${K.name}`),console.log(` \uD83D\uDCC5 ${F} days old | \uD83D\uDCDD ${P} | \uD83D\uDDD3\uFE0F ${K.lastCommitDate.toISOString().split("T")[0]}`),console.log()});let H=X.filter((K)=>!q.has(K.name)).length,G=X.filter((K)=>K.lastCommitDate<Y&&!q.has(K.name)).length;if(console.log("\uD83D\uDCCA Summary:"),console.log(` \uD83D\uDCCB Total buddy branches: ${U.length}`),console.log(` \uD83D\uDD34 With open PRs: ${U.length-H}`),console.log(` \uD83D\uDFE1 Orphaned: ${H}`),console.log(` \uD83D\uDDD1\uFE0F Stale (>${z} days): ${G}`),G>0)console.log(`
|
|
169
|
+
\uD83D\uDCA1 Run 'buddy cleanup' to clean up stale branches`)}catch(Q){$.error("Branch listing failed:",Q),V.exit(1)}});T.command("open-settings","Open GitHub repository and organization settings pages").option("--verbose, -v","Enable verbose logging").example("buddy open-settings").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);try{let{exec:Q}=await import("child_process"),{promisify:z}=await import("util"),Y=z(Q),U=J.repository?.owner,j=J.repository?.name;if(!U||!j)try{let{stdout:G}=await Y("git remote get-url origin"),W=G.trim().match(/github\.com[/:]([\w-]+)\/([\w-]+)(?:\.git)?/);if(W)U=W[1],j=W[2],$.info(`\uD83D\uDCE1 Detected repository: ${U}/${j}`)}catch{}if(!U||!j){$.warn("\u26A0\uFE0F Could not determine repository information."),$.info("\uD83D\uDCA1 Please configure repository settings in buddy.config.ts or run from a Git repository."),$.info(`
|
|
170
|
+
For manual setup, visit:`),$.info("\uD83D\uDD17 Repository settings: https://github.com/YOUR_ORG/YOUR_REPO/settings/actions"),$.info("\uD83D\uDD17 Organization settings: https://github.com/organizations/YOUR_ORG/settings/actions");return}let q=`https://github.com/${U}/${j}/settings/actions`,X=`https://github.com/organizations/${U}/settings/actions`;$.info("\uD83D\uDD27 Opening GitHub Actions settings pages..."),$.info(`\uD83D\uDCE6 Repository: ${U}/${j}`);let H=async(G,K)=>{try{let W;switch(V.platform){case"darwin":W=`open "${G}"`;break;case"win32":W=`start "" "${G}"`;break;default:W=`xdg-open "${G}"`}await Y(W),$.success(`\u2705 Opened ${K}: ${G}`)}catch{$.warn(`\u26A0\uFE0F Could not auto-open ${K}. Please visit manually:`),$.info(`\uD83D\uDD17 ${G}`)}};await H(q,"repository settings"),setTimeout(async()=>{$.info(`
|
|
171
|
+
\uD83C\uDFE2 Attempting to open organization settings...`),await H(X,"organization settings"),$.info(`
|
|
172
|
+
\uD83D\uDCCB Required Settings:`),$.info(' 1. Under "Workflow permissions":'),$.info(' \u2705 Select "Read and write permissions"'),$.info(' \u2705 Check "Allow GitHub Actions to create and approve pull requests"'),$.info(' 2. Click "Save"'),$.info(`
|
|
173
|
+
\uD83D\uDCA1 Note: Organization settings may override repository settings.`)},1000)}catch(Q){$.error("Failed to open settings:",Q),$.info(`
|
|
174
|
+
\uD83D\uDCCB Manual Setup:`),$.info("\uD83D\uDD17 Repository: https://github.com/YOUR_ORG/YOUR_REPO/settings/actions"),$.info("\uD83D\uDD17 Organization: https://github.com/organizations/YOUR_ORG/settings/actions")}});T.command("security [path]","\uD83D\uDEE1 Static-analyse GitHub Actions workflows for supply-chain footguns").option("-f, --format <format>","Reporter (pretty | json | github). Defaults to github on a runner, pretty otherwise.").option("--ignore <ids>","Comma-separated rule ids to skip (e.g. missing-timeout,unpinned-action)").option("--no-color","Disable ANSI colours in pretty output").action(async(Z,$)=>{let{audit:J}=await import("../chunk-7tfrww3v.js"),{formatPretty:Q}=await import("../chunk-hfvezfxh.js"),{formatJson:z}=await import("../chunk-2bp7tqca.js"),{formatGitHub:Y}=await import("../chunk-wtjhehz9.js"),U=$.ignore?.split(",").filter(Boolean)??[],j=await J(Z??".",{ignore:U}),q=$.format??(V.env.GITHUB_ACTIONS==="true"?"github":"pretty"),X;switch(q){case"json":X=z(j);break;case"github":X=Y(j);break;case"pretty":X=Q(j,{color:$.color!==!1});break;default:V.stderr.write(`Unknown --format ${q}. Use pretty | json | github.
|
|
175
|
+
`),V.exit(2);return}if(X)V.stdout.write(`${X}
|
|
176
|
+
`);V.exit(j.failed?1:0)});T.command("touch <pr-number>","Run a finishing touch ticked on a pull request, as a stacked PR").option("--name <touch>","Run a specific touch rather than reading the checkboxes").option("--test-command <command>","Command that verifies the change").option("--dry-run","Report what would run without acting").option("--verbose, -v","Enable verbose logging").example("buddy touch 42").example("buddy touch 42 --name unit-tests").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config);try{let z=Number.parseInt(Z,10),Y=await d(Q,"finishing touches",J),j=(await Y.getPullRequests("open")).find((B)=>B.number===z);if(!j)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let{FINISHING_TOUCHES:q,getFinishingTouch:X,parseTouchSelections:H}=await import("../chunk-7xk28xrv.js"),G=$.name?[$.name]:H(j.body);if(G.length===0){J.info("\u2139\uFE0F No finishing touches are ticked on this pull request");return}let{createAiClient:K}=await import("../chunk-54sc18p8.js"),W=K(Q,J);if(!W)J.error("\u274C Finishing touches need an API key. See https://buddy.sh/ai/providers"),V.exit(1);if($.dryRun){J.info(`\uD83D\uDD0D [DRY RUN] Would run: ${G.join(", ")}`);return}let{runStackedTouch:F}=await import("../chunk-c3fczawt.js");for(let B of G){if(!q[B]){J.warn(`\u26A0\uFE0F Unknown finishing touch '${B}', skipping`);continue}let P=await F({provider:Y,pullRequest:j,touch:X(B),ai:W,workspace:V.cwd(),...$.testCommand?{testCommand:$.testCommand.split(" ")}:{},logger:J});await Y.createComment(z,P.comment),J.success(`\u2705 ${B}: ${P.mode}`)}let L=j.body.replace(/^(\s*-\s*)\[[xX]\](\s*<!--\s*buddy:touch=)/gm,"$1[ ]$2");if(L!==j.body)await Y.updatePullRequest(z,{body:L})}catch(z){J.error("Finishing touch failed:",z),V.exit(1)}});T.command("handle-issue","Post Buddy quick-links on a new issue, or run a ticked action").option("--payload <path>","Path to the event payload (default: GITHUB_EVENT_PATH)").option("--issue <number>","Act on an issue directly rather than reading an event").option("--dry-run","Report what would happen without acting").option("--verbose, -v","Enable verbose logging").example("buddy handle-issue").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config);if(J.issues?.quickLinks!==!0){$.info("\u2139\uFE0F Issue quick-links are off (set issues.quickLinks to enable)");return}try{let Q=Z.issue?Number.parseInt(Z.issue,10):Number.NaN;if(Number.isNaN(Q)){let F=Z.payload||V.env.GITHUB_EVENT_PATH;if(!F)$.error("\u274C No event payload. Pass --issue or --payload, or run inside CI."),V.exit(1);let L=await Bun.file(F).json();if(Q=Number(L?.issue?.number),Number.isNaN(Q)){$.info("\u2139\uFE0F Event carries no issue; nothing to do");return}}let z=await d(J,"issue quick-links",$),U=(await z.getIssues("open")).find((F)=>F.number===Q);if(!U){$.info(`\u2139\uFE0F Issue #${Q} is not open`);return}let{clearQuickSelection:j,parseQuickSelection:q,QUICK_LINKS_MARKER:X,renderQuickLinks:H}=await import("../chunk-fqj7e6xa.js"),G=q(U.body);if(G.actions.length>0){if($.info(`\uD83E\uDD16 Requested: ${G.actions.join(", ")}`),Z.dryRun)return;let{createAiClient:F}=await import("../chunk-54sc18p8.js"),L=F(J,$);if(!L){await z.createComment(Q,"Buddy needs an AI provider configured to act on this. See https://buddy.sh/ai/providers");return}await z.updateIssue(Q,{body:j(U.body)});for(let B of G.actions){let{getFinishingTouch:P,runAgent:O}=await import("../chunk-2dbkpfy9.js"),w=P(B==="build"?"autofix":"plan"),I=await O(L,{mode:w.mode,task:`${w.buildTask({summary:U.title,files:[]})}
|
|
177
|
+
|
|
178
|
+
Issue:
|
|
179
|
+
${U.body}`,context:{workspace:V.cwd(),baseBranch:J.repository?.baseBranch??"main"},logger:$});await z.createComment(Q,I.output),$.success(`\u2705 Ran ${B}`)}return}if(U.body.includes(X)){$.debug("Quick-links already posted on this issue");return}let K=J.issues?.dependencyContext?await xZ(J,$):[],W=H({body:U.body,packages:K});if(Z.dryRun){$.info(W);return}await z.createComment(Q,W),$.success(`\u2705 Posted quick-links on #${Q}`)}catch(Q){$.error("handle-issue failed:",Q),V.exit(1)}});T.command("gate <pr-number>","Run pre-merge gates on a pull request and publish the result").option("--dry-run","Print the result instead of publishing a check run").option("--verbose, -v","Enable verbose logging").example("buddy gate 42").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config);try{let z=Number.parseInt(Z,10);if(Number.isNaN(z))J.error("\u274C Invalid PR number"),V.exit(1);let Y=await d(Q,"running gates",J),{findLinkedIssues:U,runAiGates:j,runGates:q,summarizeGates:X}=await import("../chunk-r06ce5g6.js"),{parseManifest:H}=await import("../chunk-frm8zz31.js"),K=(await Y.getPullRequests("open")).find((E)=>E.number===z);if(!K)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let W=Q.gates??{},F=H(K.body),{manifestUpdates:L}=await import("../chunk-frm8zz31.js"),B=F?await Promise.all(L(F).map(async(E)=>{let h={name:E.name,version:E.newVersion};if(W.dependencyGate?.blockEol===!1)return h;if(F.updates.find((n)=>n.name===E.name)?.dependencyType!=="docker-image")return h;let{checkEol:u,describeEol:N}=await import("../chunk-p1xm1jvz.js"),S=await u(E.name,E.newVersion,{logger:J}),o=N(S);return S?.eol&&o?{...h,eol:o}:h})):[],P=q({title:K.title,body:K.body,manifest:F,dependencies:B},{...W.titleFormat?{titleFormat:W.titleFormat}:{},...W.description?{description:W.description}:{},...W.dependencyGate?{dependencyGate:W.dependencyGate}:{}}),O=U(K.body??""),w=O.length>0?await Y.getIssues("all"):[],I=O.map((E)=>w.find((h)=>h.number===E)).filter((E)=>Boolean(E)).map((E)=>({number:E.number,title:E.title,body:E.body})),{createAiClient:k}=await import("../chunk-54sc18p8.js"),v=await j(k(Q,J),{title:K.title,body:K.body,diff:await Y.getPullRequestDiff(z),linkedIssues:I},{...W.linkedIssue?{linkedIssue:W.linkedIssue}:{},...W.custom?{custom:W.custom}:{}},J),b=[...P,...v],y=X(b);for(let E of b)J.info(`${E.passed?"\u2705":E.mode==="error"?"\u274C":"\u26A0\uFE0F"} ${E.name}: ${E.summary}`);let c=y.conclusion==="failure";if($.dryRun||!z0(Y,"checkRuns","createCheckRun")){if(J.info(y.summary),c)V.exit(1);return}if(await Y.createCheckRun("buddy/gates",await Y.getPullRequestHeadSha(z),y),c)V.exit(1)}catch(z){J.error("Gate run failed:",z),V.exit(1)}});T.command("post-merge <pr-number>","Run post-merge actions for a merged pull request").option("--verbose, -v","Enable verbose logging").example("buddy post-merge 42").action(async(Z,$)=>{let J=$.verbose?M.verbose():M.quiet(),Q=await C($.config);try{let z=Number.parseInt(Z,10),Y=await d(Q,"post-merge actions",J),j=(await Y.getPullRequests("all")).find((H)=>H.number===z);if(!j)J.error(`\u274C Pull request #${z} not found`),V.exit(1);if(j.state!=="merged"){J.info(`\u2139\uFE0F PR #${z} was closed without merging; nothing to do`);return}let{runPostMerge:q}=await import("../chunk-r06ce5g6.js"),X=await q(Y,j,Q.gates?.postMerge??{},{baseBranch:Q.repository?.baseBranch??j.base,logger:J});for(let H of X.performed)J.success(`\u2705 ${H}`);for(let H of X.skipped)J.info(`\u23ED\uFE0F ${H.action}: ${H.reason}`)}catch(z){J.error("Post-merge actions failed:",z),V.exit(1)}});T.command("report","Generate a dependency-health and activity report").option("--period <window>","Reporting window: 7d|30d|90d",{default:"30d"}).option("--format <name>","Output format: markdown|json",{default:"markdown"}).option("--prompt <focus>","Focus for the AI narrative, when a provider is configured").option("--publish","Publish to the repository's report issue").option("--verbose, -v","Enable verbose logging").example("buddy report --period 7d").example('buddy report --prompt "focus on security posture" --publish').action(async(Z)=>{let $=Z.format==="json",J=Z.verbose?M.verbose():$?M.silent():M.quiet(),Q=await C(Z.config);try{let{appendHistory:z,computeDeltas:Y,computeMetrics:U,findPrevious:j,HISTORY_PATH:q,loadHistory:X,REPORT_MARKER:H,REPORT_PERIODS:G,renderReport:K,withNarrative:W}=await import("../chunk-czremqk7.js"),F=Z.period??"30d";if(!G.includes(F))J.error(`\u274C Unknown period '${F}'. Expected one of ${G.join(", ")}.`),V.exit(1);let L=await d(Q,"reporting",J),B=new g(Q,V.cwd()),{PackageScanner:P}=await import("../chunk-f4nv5x3z.js"),O=new P(V.cwd(),J,Q.packages?.ignorePaths),[w,I,k]=await Promise.all([B.scanForUpdates(),L.getPullRequests("all"),O.scanProject()]),{ecosystemOf:v}=await import("../chunk-p7zgy37f.js"),b={};for(let X0 of k)for(let j0 of X0.dependencies){let k0=v({name:j0.name,currentVersion:j0.currentVersion,newVersion:j0.currentVersion,updateType:"patch",dependencyType:j0.type,file:X0.path});b[k0]=(b[k0]??0)+1}let{DeprecatedDependenciesChecker:y}=await import("../chunk-6patq6bw.js"),c=await new y().checkDeprecatedDependencies(k).catch(()=>[]),E=U({period:F,now:new Date,pullRequests:I,updates:w.updates,dependenciesByEcosystem:b,deprecated:c.length}),h=Q.repository?.baseBranch||"main",_=await X(L,h,J),u=Y(E,j(_,F));if(Z.format==="json"){V.stdout.write(`${JSON.stringify({metrics:E,deltas:u},null,2)}
|
|
180
|
+
`);return}let{createAiClient:N}=await import("../chunk-54sc18p8.js"),S=await W(K(E,u),E,N(Q,J),Z.prompt??Q.reports?.prompt,J);if(!Z.publish){V.stdout.write(`${S}
|
|
181
|
+
`);return}let n=(await L.getIssues("open")).find((X0)=>X0.body.includes(H)),Y0=Q.reports?.title??"Dependency Report",S0=Q.reports?.labels??["dependencies","report"],M1=n?await L.updateIssue(n.number,{title:Y0,body:S,labels:S0}):await L.createIssue({title:Y0,body:S,labels:S0});J.success(`\u2705 Report published: ${M1.url}`),await L.commitChanges(h,"chore(reports): record dependency metrics snapshot",[{path:q,content:z(_,E),type:_.length>0?"update":"create"}],h)}catch(z){J.error("Report failed:",z),V.exit(1)}});T.command("doctor","Diagnose this environment: credentials, git state and analyzer tooling").option("--verbose, -v","Enable verbose logging").example("buddy doctor").action(async(Z)=>{let $=Z.verbose?M.verbose():M.quiet(),J=await C(Z.config).catch((U)=>{return $.warn(`\u26A0\uFE0F Could not load configuration: ${t(U)}`),{}}),{diagnose:Q,renderDoctorReport:z}=await import("../chunk-fdfk918n.js"),Y=await Q(J);if(V.stdout.write(z(Y)),!Y.healthy)V.exit(1)});T.command("run","Run a prompt headlessly, with optional schema-validated output").option("--prompt <text>","The prompt to run").option("--prompt-file <path>","Read the prompt from a file").option("--output-schema <json>","JSON Schema the output must satisfy").option("--output-schema-file <path>","Read the schema from a file").option("--model <name>","Model override").option("--retries <n>","Schema retries before failing",{default:"2"}).option("--verbose, -v","Enable verbose logging").example(`buddy run --prompt "Summarize this week's dependency updates"`).example(`buddy run --prompt-file p.txt --output-schema '{"type":"object"}'`).action(async(Z)=>{let $=Z.verbose?M.verbose():M.silent(),J=await C(Z.config);try{let Q=Z.promptFile?await Bun.file(Z.promptFile).text():Z.prompt;if(!Q?.trim())V.stderr.write(`\u274C Provide --prompt or --prompt-file
|
|
182
|
+
`),V.exit(1);let z=Z.outputSchemaFile?await Bun.file(Z.outputSchemaFile).text():Z.outputSchema,Y;if(z)try{Y=JSON.parse(z)}catch(W){V.stderr.write(`\u274C --output-schema is not valid JSON: ${t(W)}
|
|
183
|
+
`),V.exit(1)}let{createAiClient:U}=await import("../chunk-54sc18p8.js"),j=U(Z.model?{...J,ai:{...J.ai,model:Z.model}}:J,$);if(!j)V.stderr.write(`\u274C No AI provider configured. See https://buddy.sh/ai/providers
|
|
184
|
+
`),V.exit(1);let{publishOutput:q,runHeadless:X}=await import("../chunk-9eqpaxfz.js"),H=await X({prompt:Q,ai:j,...Y?{schema:Y}:{},maxRetries:Number.parseInt(Z.retries??"2",10),logger:$});if(!H.valid)V.stderr.write(`\u274C Output did not satisfy the schema after ${H.attempts} attempt(s):
|
|
185
|
+
${H.error}
|
|
186
|
+
`),V.exit(1);let G=await q(H.result,V.env.GITHUB_OUTPUT),K=typeof H.result==="string"?H.result:JSON.stringify(H.result,null,2);if(V.stdout.write(`${K}
|
|
187
|
+
`),G)$.info("\uD83D\uDCE4 Wrote `result` to $GITHUB_OUTPUT")}catch(Q){V.stderr.write(`\u274C ${t(Q)}
|
|
188
|
+
`),V.exit(1)}});T.command("version","Show the version of Buddy").action(()=>{console.log(P0)});T.option("--config <path>","Path to a buddy config file");T.version(P0);T.help();T.parse();
|