@buddysh/buddy 0.11.11 → 0.11.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/bin/cli.js +13 -13
- package/dist/{chunk-6pcnvdj9.js → chunk-11p0az6f.js} +1 -1
- package/dist/{chunk-tbt8btwf.js → chunk-16fr8xqp.js} +1 -1
- package/dist/{chunk-hmymd6m2.js → chunk-225s199d.js} +1 -1
- package/dist/{chunk-gzkwszsg.js → chunk-24xnjkvz.js} +2 -2
- package/dist/chunk-2z2gh050.js +44 -0
- package/dist/{chunk-afstgmb4.js → chunk-3n4w3ak9.js} +1 -1
- package/dist/{chunk-d9m42wym.js → chunk-750ae48c.js} +1 -1
- package/dist/{chunk-2h90wcxe.js → chunk-81y75fg7.js} +1 -1
- package/dist/{chunk-g0x10e1d.js → chunk-9sdgy9nm.js} +1 -1
- package/dist/{chunk-18xha279.js → chunk-a30cyqr0.js} +1 -1
- package/dist/{chunk-m63hkte2.js → chunk-a56s1xrt.js} +1 -1
- package/dist/{chunk-sd5xqd44.js → chunk-axazt516.js} +1 -1
- package/dist/{chunk-pq115qkn.js → chunk-c6ptrc0v.js} +1 -1
- package/dist/{chunk-4kr6evh6.js → chunk-cm6devhe.js} +1 -1
- package/dist/{chunk-b6a5txek.js → chunk-ctdfppxk.js} +1 -1
- package/dist/{chunk-h8wskvjv.js → chunk-cvwkdfvr.js} +1 -1
- package/dist/{chunk-jsf2322c.js → chunk-d4gk9awk.js} +2 -2
- package/dist/{chunk-naz864cb.js → chunk-enq0gm64.js} +1 -1
- package/dist/{chunk-z4btj7s0.js → chunk-esveeark.js} +1 -1
- package/dist/{chunk-be7g40yf.js → chunk-fmkb816y.js} +1 -1
- package/dist/{chunk-1tx3t9ke.js → chunk-g4803nvq.js} +1 -1
- package/dist/{chunk-83yea9pk.js → chunk-ktzvchps.js} +1 -1
- package/dist/{chunk-5vekh5w1.js → chunk-rxf8h1e5.js} +1 -1
- package/dist/{chunk-25sjd6zk.js → chunk-rygtb1x3.js} +2 -2
- package/dist/{chunk-csqh2ca4.js → chunk-s1cgwkkr.js} +1 -1
- package/dist/{chunk-9exbsfz5.js → chunk-tzmj8w3x.js} +1 -1
- package/dist/{chunk-raj75r4h.js → chunk-v0y8eens.js} +1 -1
- package/dist/{chunk-qxf3f6ks.js → chunk-v9fnbdgr.js} +1 -1
- package/dist/{chunk-mpb1g0xk.js → chunk-xqveh8a5.js} +1 -1
- package/dist/src/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-xdrvb89m.js +0 -44
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
[Compare changes](https://github.com/stacksjs/buddy/compare/v0.11.11...v0.11.12)
|
|
4
|
+
|
|
5
|
+
## 🐛 Bug Fixes
|
|
6
|
+
|
|
7
|
+
- **groups**: bump every manifest that declares a dependency ([39982a4](https://github.com/stacksjs/buddy/commit/39982a4)) _(by Chris <chrisbreuer93@gmail.com>)_
|
|
8
|
+
|
|
9
|
+
## 🔧 Chores
|
|
10
|
+
|
|
11
|
+
- release v0.11.12 ([61de34c](https://github.com/stacksjs/buddy/commit/61de34c)) _(by Chris <chrisbreuer93@gmail.com>)_
|
|
12
|
+
|
|
13
|
+
## Contributors
|
|
14
|
+
|
|
15
|
+
- _Chris <chrisbreuer93@gmail.com>_
|
|
16
|
+
|
|
3
17
|
[Compare changes](https://github.com/stacksjs/buddy/compare/v0.11.10...v0.11.11)
|
|
4
18
|
|
|
5
19
|
## 🐛 Bug Fixes
|
package/dist/bin/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{Vc as C1}from"../chunk-
|
|
3
|
+
import{Vc as C1}from"../chunk-750ae48c.js";import"../chunk-v0y8eens.js";import{ed as m}from"../chunk-rygtb1x3.js";import"../chunk-08daxhzx.js";import"../chunk-d4gk9awk.js";import"../chunk-gweqk008.js";import"../chunk-bnp0r4eh.js";import"../chunk-0f1xye20.js";import"../chunk-9sdgy9nm.js";import{ud as g}from"../chunk-7b4jsg36.js";import"../chunk-5jvde2as.js";import{Ed as R1,Md as z0}from"../chunk-7m3pzkcj.js";import"../chunk-0g4ybxwj.js";import"../chunk-142zh7e5.js";import{qe as Q0,re as Q1,se as z1}from"../chunk-ctdfppxk.js";import"../chunk-wjfw6rx8.js";import"../chunk-w55x2g9n.js";import"../chunk-1xe0960b.js";import"../chunk-gpjde0j6.js";import"../chunk-j46f90n8.js";import"../chunk-enq0gm64.js";import"../chunk-c6ptrc0v.js";import"../chunk-1pecmenc.js";import"../chunk-sxfk3naz.js";import"../chunk-24xvskkf.js";import"../chunk-z18bksyr.js";import"../chunk-cj4d5ad7.js";import"../chunk-2z2gh050.js";import{tg as $0,xg as J0}from"../chunk-knpdntnh.js";import"../chunk-54er1whp.js";import"../chunk-ktn47bq8.js";import{$g as SZ,ah as Y0,bh as X0,ch as j0,dh as G0,eh as K0,fh as f,gh as y,ih as q0,jh as H0,kh as U0,lh as V0,mh as W0,ph as F0,qh as M0,rh as D0,sh as O0,th as W1,uh as L0,vh as T0}from"../chunk-33h1me7n.js";import"../chunk-7c1284fb.js";import"../chunk-2z9pkk1y.js";import{Eh as S1}from"../chunk-vpw7adwd.js";import"../chunk-b9szrnxw.js";import{Mh as r,Nh as O}from"../chunk-x1w6q9tk.js";import"../chunk-z05djfac.js";import{cl as CZ,el as D}from"../chunk-kbvj6qxc.js";import e1 from"fs";import V from"process";import{EventEmitter as E0}from"events";import c from"process";import _1 from"process";import T1 from"process";import q1 from"process";import Z1 from"process";import d1 from"tty";import KZ,{stdin as iZ,stdout as aZ}from"process";import g1,{stdin as UZ,stdout as VZ}from"process";import WZ from"readline";import{existsSync as PZ}from"fs";import D1 from"fs/promises";import l1 from"os";import O1 from"path";import n from"process";function L1(Z){return Z.replace(/[<[].+/,"").trim()}function I0(Z){let $=/<([^>]+)>/g,J=/\[([^\]]+)\]/g,Q=[],z=(X)=>{let G=!1,j=X[1];if(j.startsWith("..."))j=j.slice(3),G=!0;else if(j.endsWith("..."))j=j.slice(0,-3),G=!0;return{required:X[0].startsWith("<"),value:j.trim(),variadic:G}},Y;while(Y=$.exec(Z))Q.push(z(Y));let U;while(U=J.exec(Z))Q.push(z(U));return Q}function B0(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((X)=>Q.names.includes(X))&&typeof Y.required==="boolean"}))$.boolean.push(Q.names[0])}else $.boolean.push(Q.names[0])}return $}function f1(Z){return Z.reduce(($,J)=>$.length>=J.length?$:J,"")}function F1(Z,$){return Z.length>=$?Z:`${Z}${" ".repeat($-Z.length)}`}function K1(Z){return Z.replace(/([a-z])-([a-z])/g,($,J,Q)=>{return J+Q.toUpperCase()})}function P0(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 N0(Z,$){for(let J of Object.keys($)){let Q=$[J];if(Z[J]===void 0)continue;if(Q.shouldTransform){if(Z[J]=Array.prototype.concat.call([],Z[J]),typeof Q.transformFunction==="function")Z[J]=Z[J].map(Q.transformFunction)}}}function A0(Z){let $=/([^\\/]+)$/.exec(Z);return $?$[1]:""}function $1(Z){return Z.split(".").map(($,J)=>{return J===0?K1($):$}).join(".")}class J1 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
4
|
|
|
5
5
|
Stack trace:
|
|
6
6
|
${this.stack}`;return this.message}}function x0(Z){if(Z instanceof J1)return!0;return!!Z&&typeof Z==="object"&&Z.name==="ClappError"&&typeof Z.message==="string"}function R0(){let{env:Z}=_1,{TERM:$,TERM_PROGRAM:J}=Z;if(_1.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 V1="\x1B",S=`${V1}[`;var u={to(Z,$){if(!$)return`${S}${Z+1}G`;return`${S}${$+1};${Z+1}H`},move(Z,$){let J="";if(Z<0)J+=`${S}${-Z}D`;else if(Z>0)J+=`${S}${Z}C`;if($<0)J+=`${S}${-$}A`;else if($>0)J+=`${S}${$}B`;return J},up:(Z=1)=>`${S}${Z}A`,down:(Z=1)=>`${S}${Z}B`,forward:(Z=1)=>`${S}${Z}C`,backward:(Z=1)=>`${S}${Z}D`,nextLine:(Z=1)=>`${S}E`.repeat(Z),prevLine:(Z=1)=>`${S}F`.repeat(Z),left:`${S}G`,hide:`${S}?25l`,show:`${S}?25h`,save:`${V1}7`,restore:`${V1}8`};var M1={screen:`${S}2J`,up:(Z=1)=>`${S}1J`.repeat(Z),down:(Z=1)=>`${S}J`.repeat(Z),line:`${S}2K`,lineEnd:`${S}K`,lineStart:`${S}1K`,lines(Z){let $="";for(let J=0;J<Z;J++)$+=this.line+(J<Z-1?u.up():"");if(Z)$+=u.left;return $}},mZ={screen:`${V1}c`};function C0(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 p1(Z,$,J=2,Q=3){return $.map((z)=>({cmd:z,distance:C0(Z,z)})).filter(({distance:z})=>z<=J).sort((z,Y)=>z.distance-Y.distance).slice(0,Q).map(({cmd:z})=>z)}function S0(Z,$={}){let J={_:[]},Q=$.alias||{},z=new Set($.boolean||[]),Y={};for(let G of Object.keys(Q))for(let j of Q[G])Y[j]=G;for(let G of z)if(Q[G])for(let j of Q[G])z.add(j);function U(G,j){if(G===void 0)return j;if(typeof j==="boolean")return j;return Array.isArray(G)?[...G,j]:[G,j]}function X(G,j){let H=Y[G]||G,q=U(J[H],j);if(J[H]=q,Q[H])for(let K of Q[H])J[K]=q;if(Y[G]&&Q[Y[G]])for(let K of Q[Y[G]])J[K]=q;J[G]=q}for(let G=0;G<Z.length;G++){let j=Z[G];if(j==="--"){J._.push(...Z.slice(G+1));break}if(j.startsWith("--")){let H=j.indexOf("=");if(H!==-1){let q=K1(j.slice(2,H)),K=j.slice(H+1);X(q,K)}else{let q=j.slice(2);if(q.startsWith("no-")){let W=K1(q.slice(3));X(W,!1);continue}let K=K1(q),F=Y[K]||K;if(z.has(F)||z.has(K))X(K,!0);else{let W=Z[G+1];if(W!==void 0&&!W.startsWith("-"))X(K,W),G++;else X(K,!0)}}}else if(j.startsWith("-")&&j.length>1){let H=j.slice(1);for(let q=0;q<H.length;q++){let K=H[q],F=Y[K]||K;if(q===H.length-1&&!z.has(F)&&!z.has(K)){let W=Z[G+1];if(W!==void 0&&!W.startsWith("-"))X(K,W),G++;else X(K,!0)}else X(K,!0)}}else J._.push(j)}return J}class n1{rawName;description;name;names;isBoolean;required;config;negated;variadic;constructor(Z,$,J){if(this.rawName=Z,this.description=$,this.config=Object.assign({},J),Z=Z.replace(/\.\*/g,""),this.negated=!1,this.variadic=/[<[](?:\.\.\.[^\]>]+|[^\]>]+\.\.\.)[\]>]/.test(Z),this.names=L1(Z).split(",").map((Q)=>{let z=Q.trim().replace(/^-{1,2}/,"");if(z.startsWith("no-"))this.negated=!0,z=z.replace(/^no-/,"");return $1(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 uZ=T1.argv,k0=`${T1.platform}-${T1.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,m1=q1.argv,b0=`${q1.platform}-${q1.arch} node-${q1.version}`;class w1{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=L1(Z);let z=L1(Z),Y=z.indexOf(":");if(Y>0)this.namespace=z.substring(0,Y),this.name=z.substring(Y+1);if(this.args=I0(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 n1(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 E1}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(Z){let $=$1(Z.split(".")[0]);return!!this.options.find((J)=>{return J.names.some((Q)=>$1(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 j=f1($.map((W)=>W.rawName)),H=new Map,q=[];for(let W of $)if(W.namespace){if(!H.has(W.namespace))H.set(W.namespace,[]);H.get(W.namespace).push(W)}else q.push(W);let K="";if(q.sort((W,T)=>W.rawName<T.rawName?-1:W.rawName>T.rawName?1:0),q.length>0)K+=q.map((W)=>{return` ${F1(W.rawName,j.length)} ${W.description}`}).join(`
|
|
@@ -38,7 +38,7 @@ Run \`${this.name??"cli"} --help\` for usage.`;c.stderr.write(`${J}${$}${Q}
|
|
|
38
38
|
`).length-1;this.output.write(u.move(-999,Z*-1))}render(){let Z=c1(this._render(this)??"",g1.stdout.columns,{hard:!0,trim:!1});if(Z===this._prevFrame)return;if(this.state==="initial")this.output.write(u.hide);else{let $=HZ(this._prevFrame,Z);if(this.restoreCursor(),$&&$?.length===1){let J=$[0];this.output.write(u.move(0,J)),this.output.write(M1.lines(1));let Q=Z.split(`
|
|
39
39
|
`);this.output.write(Q[J]),this._prevFrame=Z,this.output.write(u.move(0,Q.length-J-1));return}if($&&$?.length>1){let J=$[0];this.output.write(u.move(0,J)),this.output.write(M1.down());let z=Z.split(`
|
|
40
40
|
`).slice(J);this.output.write(z.join(`
|
|
41
|
-
`)),this._prevFrame=Z;return}this.output.write(M1.down())}if(this.output.write(Z),this.state==="initial")this.state="active";this._prevFrame=Z}}function DZ(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 OZ(Z,$){return($.label??String($.value)).toLowerCase().includes(Z.toLowerCase())}function LZ(Z,$){if(!$)return;if(Z)return $;return $[0]}class TZ extends B1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#J="";#Q;#$;get cursor(){return this.#Z}get userInputWithCursor(){if(!this.userInput)return H1.inverse(H1.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}${H1.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??OZ;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=LZ(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=DZ(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 wZ extends B1{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 EZ=R0();var x=(Z,$)=>EZ?Z:$,oZ=x("\u25C6","*"),eZ=x("\u25A0","x"),Z$=x("\u25B2","x"),$$=x("\u25C7","o"),J$=x("\u250C","T"),IZ=x("\u2502","|"),Q$=x("\u2514","\u2014"),z$=x("\u25CF",">"),Y$=x("\u25CB"," "),X$=x("\u25FB","[\u2022]"),j$=x("\u25FC","[+]"),G$=x("\u25FB","[ ]"),K$=x("\u25AA","\u2022"),q$=x("\u2500","-"),H$=x("\u256E","+"),U$=x("\u251C","+"),V$=x("\u256F","+"),W$=x("\u25CF","\u2022"),F$=x("\u25C6","*"),M$=x("\u25B2","!"),D$=x("\u25A0","x");var O$={light:x("\u2500","-"),heavy:x("\u2501","="),block:x("\u2588","#")};function BZ(){return`${H1.gray(IZ)} `}var L$=BZ();class s1{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let Z=l1.homedir(),$=O1.join(Z,".config","clapp");this.configPath=O1.join($,"telemetry.json")}async isEnabled(){if(n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true")return!1;if(n.env.NO_TELEMETRY==="1"||n.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:l1.platform(),nodeVersion:n.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:n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:Z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(PZ(this.configPath)){let Z=await D1.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 $=O1.dirname(this.configPath);await D1.mkdir($,{recursive:!0}),await D1.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 P$=new s1;var a=CZ(SZ(),1);var P1="0.11.
|
|
41
|
+
`)),this._prevFrame=Z;return}this.output.write(M1.down())}if(this.output.write(Z),this.state==="initial")this.state="active";this._prevFrame=Z}}function DZ(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 OZ(Z,$){return($.label??String($.value)).toLowerCase().includes(Z.toLowerCase())}function LZ(Z,$){if(!$)return;if(Z)return $;return $[0]}class TZ extends B1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#J="";#Q;#$;get cursor(){return this.#Z}get userInputWithCursor(){if(!this.userInput)return H1.inverse(H1.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}${H1.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??OZ;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=LZ(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=DZ(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 wZ extends B1{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 EZ=R0();var x=(Z,$)=>EZ?Z:$,oZ=x("\u25C6","*"),eZ=x("\u25A0","x"),Z$=x("\u25B2","x"),$$=x("\u25C7","o"),J$=x("\u250C","T"),IZ=x("\u2502","|"),Q$=x("\u2514","\u2014"),z$=x("\u25CF",">"),Y$=x("\u25CB"," "),X$=x("\u25FB","[\u2022]"),j$=x("\u25FC","[+]"),G$=x("\u25FB","[ ]"),K$=x("\u25AA","\u2022"),q$=x("\u2500","-"),H$=x("\u256E","+"),U$=x("\u251C","+"),V$=x("\u256F","+"),W$=x("\u25CF","\u2022"),F$=x("\u25C6","*"),M$=x("\u25B2","!"),D$=x("\u25A0","x");var O$={light:x("\u2500","-"),heavy:x("\u2501","="),block:x("\u2588","#")};function BZ(){return`${H1.gray(IZ)} `}var L$=BZ();class s1{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let Z=l1.homedir(),$=O1.join(Z,".config","clapp");this.configPath=O1.join($,"telemetry.json")}async isEnabled(){if(n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true")return!1;if(n.env.NO_TELEMETRY==="1"||n.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:l1.platform(),nodeVersion:n.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:n.env.DO_NOT_TRACK==="1"||n.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:Z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(PZ(this.configPath)){let Z=await D1.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 $=O1.dirname(this.configPath);await D1.mkdir($,{recursive:!0}),await D1.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 P$=new s1;var a=CZ(SZ(),1);var P1="0.11.12";var N1=String.raw`^\s*-\s*\[[xX]\]\s*`,AZ=new RegExp(`${N1}<!--\\s*rebase-branch=([^>]*?)\\s*-->`,"gm"),xZ=new RegExp(`${N1}<!--\\s*rebase-all-open-prs\\s*-->`,"m"),RZ=new RegExp(`${N1}<!--\\s*manual job\\s*-->`,"m");function t1(Z){if(!Z)return{rebaseBranches:[],rebaseAll:!1,manualRun:!1};let $=[];for(let J of Z.matchAll(AZ)){let Q=J[1].trim();if(Q&&!$.includes(Q))$.push(Q)}return{rebaseBranches:$,rebaseAll:xZ.test(Z),manualRun:RZ.test(Z)}}function A1(Z){return Z.rebaseBranches.length>0||Z.rebaseAll||Z.manualRun}function o1(Z){return Z.replace(/^(\s*-\s*)\[[xX]\](\s*<!--\s*(?:rebase-branch=[^>]*?|rebase-all-open-prs|manual job)\s*-->)/gm,"$1[ ]$2")}var x1=null;async function k(Z){if(Z)return await C1(Z);if(!x1)x1=await C1();return x1}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 Q0({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 ${r(Q)}`),V.exit(1)}}async function Z0(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 X=z.get(U.path);if(X)X.push(U);else z.set(U.path,[U])}let Y=0;for(let[U,X]of z){let G=Bun.file(U);if(!await G.exists()){J.warn(`\u26A0\uFE0F Skipping ${U}: not in the working tree`);continue}let j=await G.text();for(let H of[...X].sort((q,K)=>K.line-q.line)){if(!$){if(!(await a.default({type:"confirm",name:"apply",message:`${U}:${H.line} \u2014 ${H.message}
|
|
42
42
|
${H.suggestion}
|
|
43
43
|
Apply?`,initial:!1})).apply)continue}let q=z0(j,H.line,H.suggestion);if(q===null){J.warn(`\u26A0\uFE0F Skipping ${U}:${H.line}: the file changed since the review`);continue}j=q,Y++}await Bun.write(U,j)}return Y}async function kZ(Z,$){try{let{PackageScanner:J}=await import("../chunk-6gdenphk.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: ${r(J)}`),[]}}var w=new I1("buddy");w.usage(`[command] [options]
|
|
44
44
|
|
|
@@ -138,24 +138,24 @@ Scan Results:`),$.info(`\uD83D\uDCE6 Total packages: ${X.totalPackages}`),$.info
|
|
|
138
138
|
\uD83D\uDEA8 Major updates (${G.length}):`);for(let q of G)$.info(` ${q.name}: ${q.currentVersion} \u2192 ${q.newVersion}`)}if(j.length>0){$.info(`
|
|
139
139
|
\u2728 Minor updates (${j.length}):`);for(let q of j)$.info(` ${q.name}: ${q.currentVersion} \u2192 ${q.newVersion}`)}if(H.length>0){$.info(`
|
|
140
140
|
\uD83D\uDD27 Patch updates (${H.length}):`);for(let q of H)$.info(` ${q.name}: ${q.currentVersion} \u2192 ${q.newVersion}`)}if(X.groups.length>0){$.info(`
|
|
141
|
-
\uD83D\uDCCB Update groups (${X.groups.length}):`);for(let q of X.groups)$.info(` ${q.name}: ${q.updates.length} updates`)}}catch(Q){$.error("Scan failed:",Q),await g(J.notifications,"run.failed",{command:"scan",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await k(Z.config);if(J.dashboard?.enabled===!1){$.info("\u2139\uFE0F Dashboard is disabled by config (dashboard.enabled: false)");return}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 m(Q).createOrUpdateDashboard();$.success(`\u2705 Dashboard updated: ${Y.url}`),$.info(`\uD83D\uDCCA Issue #${Y.number}: ${Y.title}`)}catch(Q){$.error("Dashboard creation failed:",Q),await g(J.notifications,"run.failed",{command:"dashboard",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("update","Update dependencies and create PRs").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").option("--ignore <names>","Comma-separated list of packages to ignore").option("--dry-run","Preview changes without making them").option("--reviewers <names>","Comma-separated reviewers to assign (overrides pullRequest.reviewers)").option("--assignees <names>","Comma-separated assignees to assign (overrides pullRequest.assignees)").option("--labels <names>","Comma-separated labels to add (overrides pullRequest.labels)").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?O.verbose():O.quiet(),J=await k(Z.config);try{$.info("Starting dependency update process...");let Q;if(Z.ignore)Q=Z.ignore.split(",").map((K)=>K.trim());let z=(K)=>K?K.split(",").map((F)=>F.trim()).filter(Boolean):void 0,Y=z(Z.reviewers),U=z(Z.assignees),X=z(Z.labels),G={...Y?{reviewers:Y}:{},...U?{assignees:U}:{},...X?{labels:X}:{}},j={...J,verbose:Z.verbose??J.verbose,...Object.keys(G).length?{pullRequest:{...J.pullRequest,...G}}:{},packages:{...J.packages,strategy:Z.strategy??J.packages?.strategy??"all",ignore:Q??J.packages?.ignore,respectLatest:Z.respectLatest??J.packages?.respectLatest??!0}},H=new m(j),q=await H.scanForUpdates();if(q.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 ${q.groups.length} pull request(s):`);for(let K of q.groups)$.info(` \uD83D\uDCDD ${K.title} (${K.updates.length} updates)`);return}await H.createPullRequests(q),$.success("Update process completed!")}catch(Q){$.error("Update failed:",Q),await g(J.notifications,"run.failed",{command:"update",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.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?O.verbose():O.quiet(),Q=await k($.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 X=(await z.getPullRequests("open")).find((M)=>M.number===Y);if(!X)J.error(`\u274C Could not find open PR #${Y}`),V.exit(1);if(!S1(X.head))J.error(`\u274C PR #${Y} is not a buddy PR (branch: ${X.head})`),V.exit(1);J.info(`\uD83D\uDCCB Found PR: ${X.title}`),J.info(`\uD83C\uDF3F Branch: ${X.head}`);let G=await bZ(X.body);if(G.length===0)J.error("\u274C Could not extract package updates from PR body"),V.exit(1);if(J.info(`\uD83D\uDCE6 Found ${G.length} packages to update`),!$.force){J.info("\uD83D\uDD0D Checking if rebase is needed...");let E=(await new m(Q).scanForUpdates()).updates.filter((R)=>G.some((h)=>h.name===R.name)),B=G.every((R)=>E.some((h)=>h.name===R.name&&h.newVersion===R.newVersion)),N=Q.repository.baseBranch||"main",b=B&&z.isBranchBehind?await z.isBranchBehind(X.head,N).catch(()=>!1):!1;if(b)J.info(`\uD83D\uDD04 ${X.head} is behind ${N}; rebasing`);if(B&&!b){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 j=new m({...Q,verbose:$.verbose??Q.verbose}),H=await j.scanForUpdates();if(H.updates.length===0){J.success("\u2705 All dependencies are now up to date!");return}let q=H.groups.find((M)=>M.updates.length===G.length&&M.updates.every((L)=>G.some((E)=>E.name===L.name))&&G.every((L)=>M.updates.some((E)=>E.name===L.name)));if(!q){J.error("\u274C Could not find matching update group. This likely means the package grouping has changed."),J.info(`\uD83D\uDCCB PR packages: ${G.map((M)=>M.name).join(", ")}`),J.info(`\uD83D\uDCCB Available groups: ${H.groups.map((M)=>`${M.name} (${M.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 j.generateAllFileUpdates(q.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 M=X.body||"",L=M.replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");if(L!==M)await z.updatePullRequest(Y,{body:L}),J.info("\u2705 Unticked rebase checkbox to prevent the next update-check run from re-triggering this no-op rebase.");return}let F=Q.repository?.baseBranch||"main";await z.commitChanges(X.head,q.title,K,F),J.info(`\u2705 Recreated branch ${X.head} from ${F} with latest changes`);let{PullRequestGenerator:W}=await import("../chunk-2h90wcxe.js"),I=(await new W({verbose:$.verbose}).generateBody(q)).replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");await z.updatePullRequest(Y,{title:q.title,body:I}),J.success("\uD83D\uDD04 PR rebase completed! Updated existing PR in place.")}catch(z){J.error("Rebase failed:",z),V.exit(1)}});async function bZ(Z){let $=$0(Z);if($?.truncated)return[];if($)return J0($);let J=[],Q=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`\^?([^`]+)`\s*->\s*`\^?([^`]+)`\]?/g,z;while((z=Q.exec(Z))!==null){let[,Y,U,X]=z;J.push({name:Y,currentVersion:U,newVersion:X})}return J}w.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?O.verbose():O.quiet(),J=await k(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 hZ(Q,J,$),Y=t1(z?.body);if(A1(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 X=0,G=0;try{let K=(await Q.getPullRequests("open")).filter((F)=>S1(F.head));$.info(`\uD83D\uDCCB Found ${K.length} buddy PRs to check for rebase requests`);for(let F of K){G++;let W=Y.rebaseAll||U.has(F.head);if(yZ(F.body||"")||W)if($.info(`\uD83D\uDD04 PR #${F.number} has rebase ${W?"requested from the dashboard":"checkbox checked"}`),Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would rebase PR #${F.number}`),X++;else{$.info(`\uD83D\uDD04 Rebasing PR #${F.number} via rebase command...`);try{let{spawn:A}=await import("child_process"),I=A("bunx",["@buddysh/buddy","rebase",F.number.toString(),"--force"],{stdio:"inherit",cwd:V.cwd()});await new Promise((M,L)=>{I.on("close",(E)=>{if(E===0)X++,M(E);else L(Error(`Rebase failed with code ${E}`))})}),$.success(`\u2705 Successfully rebased PR #${F.number}`)}catch(A){$.error(`\u274C Failed to rebase PR #${F.number}:`,A)}}}if(X>0)$.success(`\u2705 ${Z.dryRun?"Would rebase":"Successfully rebased"} ${X} PR(s)`);else if(G>0)$.info("\uD83D\uDCCB No PRs have rebase checkbox enabled")}catch(q){$.warn("\u26A0\uFE0F Could not check for rebase requests:",q)}if(A1(Y)&&z){if(Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would clear dashboard checkboxes");else try{await Q.updateIssue(z.number,{body:o1(z.body||"")}),$.success("\u2705 Cleared dashboard checkboxes")}catch(q){$.warn("\u26A0\uFE0F Could not clear dashboard checkboxes:",q)}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 q=new m(J),K=await q.scanForUpdates();if(K.updates.length>0)await q.createPullRequests(K);else $.info("\u2705 No updates found during the requested run")}catch(q){$.error("\u274C Requested update run failed:",q)}}$.info(`
|
|
142
|
-
\u2705 Checking for PRs with satisfied dependencies...`);try{let{Buddy:q}=await import("../chunk-
|
|
143
|
-
\uD83D\uDD0D Checking for obsolete PRs due to removed dependency files...`);try{let{Buddy:q}=await import("../chunk-
|
|
141
|
+
\uD83D\uDCCB Update groups (${X.groups.length}):`);for(let q of X.groups)$.info(` ${q.name}: ${q.updates.length} updates`)}}catch(Q){$.error("Scan failed:",Q),await g(J.notifications,"run.failed",{command:"scan",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await k(Z.config);if(J.dashboard?.enabled===!1){$.info("\u2139\uFE0F Dashboard is disabled by config (dashboard.enabled: false)");return}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 m(Q).createOrUpdateDashboard();$.success(`\u2705 Dashboard updated: ${Y.url}`),$.info(`\uD83D\uDCCA Issue #${Y.number}: ${Y.title}`)}catch(Q){$.error("Dashboard creation failed:",Q),await g(J.notifications,"run.failed",{command:"dashboard",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.command("update","Update dependencies and create PRs").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").option("--ignore <names>","Comma-separated list of packages to ignore").option("--dry-run","Preview changes without making them").option("--reviewers <names>","Comma-separated reviewers to assign (overrides pullRequest.reviewers)").option("--assignees <names>","Comma-separated assignees to assign (overrides pullRequest.assignees)").option("--labels <names>","Comma-separated labels to add (overrides pullRequest.labels)").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?O.verbose():O.quiet(),J=await k(Z.config);try{$.info("Starting dependency update process...");let Q;if(Z.ignore)Q=Z.ignore.split(",").map((K)=>K.trim());let z=(K)=>K?K.split(",").map((F)=>F.trim()).filter(Boolean):void 0,Y=z(Z.reviewers),U=z(Z.assignees),X=z(Z.labels),G={...Y?{reviewers:Y}:{},...U?{assignees:U}:{},...X?{labels:X}:{}},j={...J,verbose:Z.verbose??J.verbose,...Object.keys(G).length?{pullRequest:{...J.pullRequest,...G}}:{},packages:{...J.packages,strategy:Z.strategy??J.packages?.strategy??"all",ignore:Q??J.packages?.ignore,respectLatest:Z.respectLatest??J.packages?.respectLatest??!0}},H=new m(j),q=await H.scanForUpdates();if(q.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 ${q.groups.length} pull request(s):`);for(let K of q.groups)$.info(` \uD83D\uDCDD ${K.title} (${K.updates.length} updates)`);return}await H.createPullRequests(q),$.success("Update process completed!")}catch(Q){$.error("Update failed:",Q),await g(J.notifications,"run.failed",{command:"update",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.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?O.verbose():O.quiet(),Q=await k($.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 X=(await z.getPullRequests("open")).find((M)=>M.number===Y);if(!X)J.error(`\u274C Could not find open PR #${Y}`),V.exit(1);if(!S1(X.head))J.error(`\u274C PR #${Y} is not a buddy PR (branch: ${X.head})`),V.exit(1);J.info(`\uD83D\uDCCB Found PR: ${X.title}`),J.info(`\uD83C\uDF3F Branch: ${X.head}`);let G=await bZ(X.body);if(G.length===0)J.error("\u274C Could not extract package updates from PR body"),V.exit(1);if(J.info(`\uD83D\uDCE6 Found ${G.length} packages to update`),!$.force){J.info("\uD83D\uDD0D Checking if rebase is needed...");let E=(await new m(Q).scanForUpdates()).updates.filter((R)=>G.some((h)=>h.name===R.name)),B=G.every((R)=>E.some((h)=>h.name===R.name&&h.newVersion===R.newVersion)),N=Q.repository.baseBranch||"main",b=B&&z.isBranchBehind?await z.isBranchBehind(X.head,N).catch(()=>!1):!1;if(b)J.info(`\uD83D\uDD04 ${X.head} is behind ${N}; rebasing`);if(B&&!b){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 j=new m({...Q,verbose:$.verbose??Q.verbose}),H=await j.scanForUpdates();if(H.updates.length===0){J.success("\u2705 All dependencies are now up to date!");return}let q=H.groups.find((M)=>M.updates.length===G.length&&M.updates.every((L)=>G.some((E)=>E.name===L.name))&&G.every((L)=>M.updates.some((E)=>E.name===L.name)));if(!q){J.error("\u274C Could not find matching update group. This likely means the package grouping has changed."),J.info(`\uD83D\uDCCB PR packages: ${G.map((M)=>M.name).join(", ")}`),J.info(`\uD83D\uDCCB Available groups: ${H.groups.map((M)=>`${M.name} (${M.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 j.generateAllFileUpdates(q.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 M=X.body||"",L=M.replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");if(L!==M)await z.updatePullRequest(Y,{body:L}),J.info("\u2705 Unticked rebase checkbox to prevent the next update-check run from re-triggering this no-op rebase.");return}let F=Q.repository?.baseBranch||"main";await z.commitChanges(X.head,q.title,K,F),J.info(`\u2705 Recreated branch ${X.head} from ${F} with latest changes`);let{PullRequestGenerator:W}=await import("../chunk-81y75fg7.js"),I=(await new W({verbose:$.verbose}).generateBody(q)).replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");await z.updatePullRequest(Y,{title:q.title,body:I}),J.success("\uD83D\uDD04 PR rebase completed! Updated existing PR in place.")}catch(z){J.error("Rebase failed:",z),V.exit(1)}});async function bZ(Z){let $=$0(Z);if($?.truncated)return[];if($)return J0($);let J=[],Q=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`\^?([^`]+)`\s*->\s*`\^?([^`]+)`\]?/g,z;while((z=Q.exec(Z))!==null){let[,Y,U,X]=z;J.push({name:Y,currentVersion:U,newVersion:X})}return J}w.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?O.verbose():O.quiet(),J=await k(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 hZ(Q,J,$),Y=t1(z?.body);if(A1(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 X=0,G=0;try{let K=(await Q.getPullRequests("open")).filter((F)=>S1(F.head));$.info(`\uD83D\uDCCB Found ${K.length} buddy PRs to check for rebase requests`);for(let F of K){G++;let W=Y.rebaseAll||U.has(F.head);if(yZ(F.body||"")||W)if($.info(`\uD83D\uDD04 PR #${F.number} has rebase ${W?"requested from the dashboard":"checkbox checked"}`),Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would rebase PR #${F.number}`),X++;else{$.info(`\uD83D\uDD04 Rebasing PR #${F.number} via rebase command...`);try{let{spawn:A}=await import("child_process"),I=A("bunx",["@buddysh/buddy","rebase",F.number.toString(),"--force"],{stdio:"inherit",cwd:V.cwd()});await new Promise((M,L)=>{I.on("close",(E)=>{if(E===0)X++,M(E);else L(Error(`Rebase failed with code ${E}`))})}),$.success(`\u2705 Successfully rebased PR #${F.number}`)}catch(A){$.error(`\u274C Failed to rebase PR #${F.number}:`,A)}}}if(X>0)$.success(`\u2705 ${Z.dryRun?"Would rebase":"Successfully rebased"} ${X} PR(s)`);else if(G>0)$.info("\uD83D\uDCCB No PRs have rebase checkbox enabled")}catch(q){$.warn("\u26A0\uFE0F Could not check for rebase requests:",q)}if(A1(Y)&&z){if(Z.dryRun)$.info("\uD83D\uDD0D [DRY RUN] Would clear dashboard checkboxes");else try{await Q.updateIssue(z.number,{body:o1(z.body||"")}),$.success("\u2705 Cleared dashboard checkboxes")}catch(q){$.warn("\u26A0\uFE0F Could not clear dashboard checkboxes:",q)}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 q=new m(J),K=await q.scanForUpdates();if(K.updates.length>0)await q.createPullRequests(K);else $.info("\u2705 No updates found during the requested run")}catch(q){$.error("\u274C Requested update run failed:",q)}}$.info(`
|
|
142
|
+
\u2705 Checking for PRs with satisfied dependencies...`);try{let{Buddy:q}=await import("../chunk-a30cyqr0.js");await new q(J).checkAndCloseSatisfiedPRs(Q,!!Z.dryRun)}catch(q){$.error("\u26A0\uFE0F Could not check for satisfied PRs:",q)}$.info(`
|
|
143
|
+
\uD83D\uDD0D Checking for obsolete PRs due to removed dependency files...`);try{let{Buddy:q}=await import("../chunk-a30cyqr0.js");await new q(J).checkAndCloseObsoletePRs(Q,!!Z.dryRun)}catch(q){$.error("\u26A0\uFE0F Could not check for obsolete PRs:",q)}let j=0;try{if(j=(await new m(J).mergeEligiblePullRequests(!!Z.dryRun)).length,j>0)$.success(`\uD83D\uDD00 ${Z.dryRun?"Would merge":"Merged"} ${j} PR(s)`)}catch(q){$.warn("\u26A0\uFE0F Could not process auto-merge:",q)}$.info(`
|
|
144
144
|
\uD83E\uDDF9 Running branch cleanup...`),z1(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(X>0||j>0||H.deleted.length>0)$.success(`
|
|
145
|
-
\uD83C\uDF89 Update-check complete: ${X} PR(s) rebased, ${j} merged, ${H.deleted.length} branches cleaned`)}catch(Q){$.error("update-check failed:",Q),await g(J.notifications,"run.failed",{command:"update-check",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});async function hZ(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 yZ(Z){return/\s*-\s*\[x\]\s*<!--\s*rebase-check\s*-->.*(?:rebase|update)\/retry/i.test(Z)}w.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?O.verbose():O.quiet(),J=await k(Z.config);try{let Q=await d(J,"this command",$),{runFixCi:z}=await import("../chunk-
|
|
145
|
+
\uD83C\uDF89 Update-check complete: ${X} PR(s) rebased, ${j} merged, ${H.deleted.length} branches cleaned`)}catch(Q){$.error("update-check failed:",Q),await g(J.notifications,"run.failed",{command:"update-check",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});async function hZ(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 yZ(Z){return/\s*-\s*\[x\]\s*<!--\s*rebase-check\s*-->.*(?:rebase|update)\/retry/i.test(Z)}w.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?O.verbose():O.quiet(),J=await k(Z.config);try{let Q=await d(J,"this command",$),{runFixCi:z}=await import("../chunk-axazt516.js"),Y=await z({config:J,provider:Q,logger:$,dryRun:Boolean(Z.dryRun),...Z.runId?{runId:Number.parseInt(Z.runId,10)}:{},...Z.pr?{prNumber:Number.parseInt(Z.pr,10)}:{}});$.success(`\u2705 ${Y}`)}catch(Q){$.error("fix-ci failed:",Q),await g(J.notifications,"run.failed",{command:"fix-ci",error:Q instanceof Error?Q.message:String(Q)}),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await k(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:X,parseCommand:G}=await import("../chunk-q7y8dvbz.js");if(!X(Y.body)){$.info("\u2139\uFE0F Comment does not mention buddy; nothing to do");return}let j=G(Y.body);if(!j){$.info("\u2139\uFE0F Mention is not a command (quoted or inside code); nothing to do");return}let H=await d(J,"this command",$),q=Y.user?.login??"",K=Y.user?.type==="Bot"||q.endsWith("[bot]"),F={login:q,isBot:K,canWrite:!K&&Q1(H,"permissionLookup","hasWriteAccess")?await H.hasWriteAccess(q):!1},W=Boolean(z.pull_request??z.issue?.pull_request);if($.info(`\uD83E\uDD16 Handling \`${j.name}\` from @${q} on #${U.number}`),Z.dryRun){$.info(`\uD83D\uDD0D [DRY RUN] Would run ${j.name} (canWrite: ${F.canWrite})`);return}if(Q1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,"eyes");let{createHandlers:T,dispatchCommand:A}=await import("../chunk-q7y8dvbz.js"),{runReviewForPR:I}=await import("../chunk-11p0az6f.js"),M=await A({command:j,actor:F,number:U.number,isPullRequest:W,commentId:Y.id,logger:$},T({config:J,provider:H,review:async(L,E)=>await I({config:J,provider:H,prNumber:L,logger:$,...E}),rebase:async(L)=>{let{spawn:E}=await import("child_process");return await new Promise((B,N)=>{E("bunx",["@buddysh/buddy","rebase",String(L)],{stdio:"inherit"}).on("close",(R)=>R===0?B():N(Error(`rebase exited ${R}`)))}),"Rebased."},merge:async()=>await new m(J).mergeEligiblePullRequests(!1),fixCi:async(L)=>{let{runFixCi:E}=await import("../chunk-axazt516.js");return await E({config:J,provider:H,prNumber:L,analysisOnly:!0,logger:$})},plan:async(L,E,B)=>{let{runPlan:N}=await import("../chunk-65by8f14.js");return await N({config:J,provider:H,number:L,isPullRequest:E,request:B,logger:$})},resolve:async(L)=>{let{resolveBuddyThreads:E}=await import("../chunk-cvwkdfvr.js");return await E({provider:H,prNumber:L,logger:$})},remember:async(L,E)=>{let{addLearning:B,createLearning:N,loadLearnings:b,serializeLearnings:R,DEFAULT_LEARNINGS_FILE:h}=await import("../chunk-vtr2vbk0.js"),v=J.repository?.baseBranch??"main",P=await b((s,p)=>H.getFileContent(s,p),v,h,$),_=N(L,{source:E.isPullRequest?{pr:E.number}:{issue:E.number}}),i=`buddy/learning-${_.id}`;return await H.commitChanges(i,"chore(buddy): record a learning",[{path:h,content:R(B(P,_)),type:"update"}],v),await H.createPullRequest({title:"chore(buddy): record a learning",body:`Recorded from #${E.number}:
|
|
146
146
|
|
|
147
|
-
> ${L}`,head:i,base:v,draft:!1}),`Noted. I opened a pull request adding it to \`${h}\` so it gets reviewed like any other change.`}}));if(M.reply)await H.createComment(U.number,M.reply);if(Q1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,M.handled?"rocket":"confused");$.success(M.handled?`\u2705 Handled \`${j.name}\``:`\u2139\uFE0F Did not run: ${M.refusal}`)}catch(Q){$.error("handle-comment failed:",Q),V.exit(1)}});w.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("--auto","Treat this as an automatic trigger, honouring the ai.review filters").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?O.verbose():O.quiet(),Q=await k($.config),z=$.format??"pretty";if(!R1.includes(z))J.error(`\u274C Unknown format '${z}'. Expected one of ${R1.join(", ")}.`),V.exit(1);let Y=z!=="pretty",U=Y?O.silent():J;try{let{createAiClient:X}=await import("../chunk-vtr2vbk0.js"),G=X(Q,U);if(!G&&(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:j,reviewDiff:H}=await import("../chunk-
|
|
147
|
+
> ${L}`,head:i,base:v,draft:!1}),`Noted. I opened a pull request adding it to \`${h}\` so it gets reviewed like any other change.`}}));if(M.reply)await H.createComment(U.number,M.reply);if(Q1(H,"commentReactions","reactToComment"))await H.reactToComment(Y.id,M.handled?"rocket":"confused");$.success(M.handled?`\u2705 Handled \`${j.name}\``:`\u2139\uFE0F Did not run: ${M.refusal}`)}catch(Q){$.error("handle-comment failed:",Q),V.exit(1)}});w.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("--auto","Treat this as an automatic trigger, honouring the ai.review filters").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?O.verbose():O.quiet(),Q=await k($.config),z=$.format??"pretty";if(!R1.includes(z))J.error(`\u274C Unknown format '${z}'. Expected one of ${R1.join(", ")}.`),V.exit(1);let Y=z!=="pretty",U=Y?O.silent():J;try{let{createAiClient:X}=await import("../chunk-vtr2vbk0.js"),G=X(Q,U);if(!G&&(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:j,reviewDiff:H}=await import("../chunk-cvwkdfvr.js"),{collectLocalDiff:q,formatReview:K,shouldFail:F}=await import("../chunk-wt83nzn3.js"),{runAnalyzers:W}=await import("../chunk-kq0n3x2e.js");if(Z){let B=await d(Q,"reviewing a pull request",U),{reviewPullRequest:N}=await import("../chunk-11p0az6f.js"),{status:b,result:R}=await N({config:Q,provider:B,prNumber:Number.parseInt(Z,10),trigger:$.auto?"automatic":"requested",...$.auto?{skipIfReviewed:!0}:{},logger:U,dryRun:Boolean($.dryRun),...$.summaryOnly?{summaryOnly:!0}:{},...$.profile?{profile:$.profile}:{}});if(J.success(`\u2705 ${b}`),await g(Q.notifications,"review.completed",{number:Number.parseInt(Z,10),findings:R?.findings.length??0}),R&&z!=="pretty")V.stdout.write(K(R,z));if(R&&$.failOn&&F(R.findings,$.failOn))V.exit(1);return}let T;{let B=$.base||Q.repository?.baseBranch||"main",N=$.staged?"staged":$.branch?"branch":"working";U.info(`\uD83D\uDD0D Reviewing ${N} changes${N==="branch"?` against ${B}`:""}...`),T=await q(N,B)}if(!T.trim()){if(!Y)J.success("\u2705 No changes to review");return}let{parseUnifiedDiff:A}=await import("../chunk-apdrg3r7.js"),I=A(T).files.map((B)=>B.path),M=Q.analysis?.enabled===!1?{findings:[],ran:[],skipped:[]}:await W({files:I,root:V.cwd(),...Q.analysis?.tools?{enabled:Q.analysis.tools}:{},logger:U});if($.light){let B={summary:`Static analysis of ${I.length} changed file(s).`,walkthrough:[],findings:M.findings,effort:1,omittedFiles:M.skipped.map((N)=>`${N.name} (${N.reason})`)};if(V.stdout.write(K(B,z)),$.fix){let N=await Z0(B.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${N} suggestion(s)`)}if($.failOn&&F(B.findings,$.failOn))V.exit(1);return}let L=await H(G,{diff:T,profile:$.profile??Q.ai?.review?.profile,summaryOnly:$.summaryOnly??Q.ai?.review?.summaryOnly,instructions:j({global:Q.ai?.review?.instructions}),pathFilters:Q.ai?.review?.pathFilters,pathInstructions:Q.ai?.review?.pathInstructions,seenFingerprints:[],logger:U}),E={...L,findings:[...M.findings,...L.findings],omittedFiles:[...L.omittedFiles,...M.skipped.map((B)=>`${B.name} (${B.reason})`)]};if(V.stdout.write(K(E,z)),$.fix){let B=await Z0(E.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${B} suggestion(s)`)}if($.failOn&&F(E.findings,$.failOn))V.exit(1)}catch(X){J.error("Review failed:",X),await g(Q.notifications,"run.failed",{command:"review",error:X instanceof Error?X.message:String(X)}),V.exit(1)}});w.command("check <packages...>","Check specific packages for updates").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else 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?O.verbose():O.quiet(),z=await k($.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"}},X=await new m(Y).checkPackages(J);if(X.length===0)Q.success("All specified packages are up to date!");else{Q.info(`Found ${X.length} updates:`);for(let G of X)Q.info(` ${G.name}: ${G.currentVersion} \u2192 ${G.newVersion} (${G.updateType})`)}}catch(Y){Q.error("Check failed:",Y),V.exit(1)}});w.command("schedule","Run automated dependency updates on schedule").option("--verbose, -v","Enable verbose logging").option("--strategy <type>","Update strategy: major|minor|patch|all (default: packages.strategy from config, else all)").example("buddy schedule").example("buddy schedule --verbose").example("buddy schedule --strategy patch").action(async(Z)=>{let{Scheduler:$}=await import("../chunk-16fr8xqp.js"),J=Z.verbose?O.verbose():O.quiet(),Q=await k(Z.config);try{J.info("\uD83D\uDD52 Starting Buddy Scheduler...");let z;if(Z.ignore)z=Z.ignore.split(",").map((G)=>G.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),X=$.createJobFromConfig(Y,"cli-schedule");if(Z.strategy)switch(Z.strategy){case"major":X.schedule.cron=$.PRESETS.WEEKLY;break;case"minor":X.schedule.cron=$.PRESETS.TWICE_WEEKLY;break;case"patch":X.schedule.cron=$.PRESETS.DAILY;break;default:X.schedule.cron=$.PRESETS.WEEKLY}U.addJob(X),U.start(),J.success(`\u2705 Scheduler started with cron: ${X.schedule.cron}`),J.info("\uD83D\uDCC5 Next run:",X.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)}});w.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-64kt1w23.js"),{writeFileSync:J,mkdirSync:Q}=await import("fs"),{resolve:z}=await import("path"),Y=Z.verbose?O.verbose():O.quiet(),U=await k(Z.config);if(U.workflows?.enabled===!1){Y.info("\u2139\uFE0F Workflow generation is disabled by config (workflows.enabled: false)");return}console.log('\u26A0\uFE0F The "generate-workflows" command is deprecated.'),console.log(`\uD83D\uDCA1 Use "buddy setup" for a better interactive experience.
|
|
148
148
|
`);try{let X={...U,verbose:Z.verbose??U.verbose},G=X.workflows?.outputDir?z(V.cwd(),X.workflows.outputDir):z(V.cwd(),".github","workflows");Y.info("\uD83D\uDE80 Generating GitHub Actions workflow templates...");try{Q(G,{recursive:!0})}catch{}let j=X.workflows?.templates||{comprehensive:!0,daily:!0,weekly:!0,monthly:!0,docker:!0,monorepo:!0},H=0;if(j.daily||j.weekly||j.monthly){let q=$.generateScheduledWorkflows(X);for(let[K,F]of Object.entries(q))if(K.includes("daily")&&j.daily||K.includes("weekly")&&j.weekly||K.includes("monthly")&&j.monthly){let T=z(G,K);J(T,F),Y.success(`Generated: ${K}`),H++}}if(j.comprehensive){let q=$.generateComprehensiveWorkflow(X);J(z(G,"buddy-comprehensive.yml"),q),Y.success("Generated: buddy-comprehensive.yml"),H++}if(j.docker){let q=$.generateDockerWorkflow(X);J(z(G,"buddy-docker.yml"),q),Y.success("Generated: buddy-docker.yml"),H++}if(j.monorepo){let q=$.generateMonorepoWorkflow(X);J(z(G,"buddy-monorepo.yml"),q),Y.success("Generated: buddy-monorepo.yml"),H++}if(X.workflows?.custom?.length)for(let q of X.workflows.custom){let K=$.generateCustomWorkflow(q,X),F=`buddy-${q.name.toLowerCase().replace(/\s+/g,"-")}.yml`;J(z(G,F),K),Y.success(`Generated: ${F}`),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(`
|
|
149
149
|
\uD83C\uDF89 ${H} GitHub Actions workflow(s) generated!`),Y.info(`\uD83D\uDCC1 Location: ${G}`),Y.info(`
|
|
150
150
|
\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(`
|
|
151
|
-
\uD83D\uDD17 Learn more: https://docs.github.com/en/actions`)}catch(X){Y.error("Failed to generate workflows:",X),V.exit(1)}});w.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-
|
|
152
|
-
\uD83D\uDCCB Recent versions:`),Y.versions.slice(-U).reverse().forEach((G,j)=>{let q=G===Y.latestVersion?"\u2B50":" ";console.log(`${q} ${G}`)}),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)}});w.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-
|
|
151
|
+
\uD83D\uDD17 Learn more: https://docs.github.com/en/actions`)}catch(X){Y.error("Failed to generate workflows:",X),V.exit(1)}});w.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-a56s1xrt.js"),Q=$.verbose?O.verbose():O.quiet();try{let z=new J(V.cwd(),Q,void 0);if($.json){let{spawn:X}=await import("child_process");X("bun",["info",Z,"--json"],{stdio:"inherit"}).on("close",(j)=>{V.exit(j||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)}});w.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-a56s1xrt.js"),Q=$.verbose?O.verbose():O.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(`
|
|
152
|
+
\uD83D\uDCCB Recent versions:`),Y.versions.slice(-U).reverse().forEach((G,j)=>{let q=G===Y.latestVersion?"\u2B50":" ";console.log(`${q} ${G}`)}),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)}});w.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-a56s1xrt.js"),Q=$.verbose?O.verbose():O.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)}});w.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-a56s1xrt.js"),Q=$.verbose?O.verbose():O.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)}});w.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-a56s1xrt.js"),Q=$.verbose?O.verbose():O.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,X=$.dev||$.all,G=$.peer||$.all;if(U||$.all){let j=Y.dependencies||{},H=Object.keys(j).length;if(console.log(`
|
|
153
153
|
\uD83D\uDCCB Production Dependencies (${H}):`),H>0)Object.entries(j).forEach(([q,K])=>{console.log(` ${q}: ${K}`)});else console.log(" No production dependencies")}if(X){let j=Y.devDependencies||{},H=Object.keys(j).length;if(console.log(`
|
|
154
154
|
\uD83D\uDEE0\uFE0F Dev Dependencies (${H}):`),H>0)Object.entries(j).forEach(([q,K])=>{console.log(` ${q}: ${K}`)});else console.log(" No dev dependencies")}if(G){let j=Y.peerDependencies||{},H=Object.keys(j).length;if(console.log(`
|
|
155
|
-
\uD83E\uDD1D Peer Dependencies (${H}):`),H>0)Object.entries(j).forEach(([q,K])=>{console.log(` ${q}: ${K}`)});else console.log(" No peer dependencies")}}catch(z){Q.error("Failed to get package dependencies:",z),V.exit(1)}});w.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?O.verbose():O.quiet();try{console.log(`\uD83D\uDCCA Comparing ${Z}: ${$} vs ${J}`);let{RegistryClient:Y}=await import("../chunk-
|
|
155
|
+
\uD83E\uDD1D Peer Dependencies (${H}):`),H>0)Object.entries(j).forEach(([q,K])=>{console.log(` ${q}: ${K}`)});else console.log(" No peer dependencies")}}catch(z){Q.error("Failed to get package dependencies:",z),V.exit(1)}});w.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?O.verbose():O.quiet();try{console.log(`\uD83D\uDCCA Comparing ${Z}: ${$} vs ${J}`);let{RegistryClient:Y}=await import("../chunk-a56s1xrt.js"),X=await new Y(V.cwd(),z,void 0).getPackageMetadata(Z);if(!X)z.error(`Package "${Z}" not found`),V.exit(1);let G=X.versions||[];if(!G.includes($))console.log(`\u26A0\uFE0F Version ${$} not found in available versions`);if(!G.includes(J))console.log(`\u26A0\uFE0F Version ${J} not found in available versions`);let{getUpdateType:j}=await import("../chunk-esveeark.js"),H=j($,J);console.log(`
|
|
156
156
|
\uD83D\uDD0D Version Analysis:`),console.log(` From: ${$}`),console.log(` To: ${J}`),console.log(` Type: ${H} update`);let q=G.indexOf($),K=G.indexOf(J);if(q!==-1&&K!==-1){let F=Math.abs(K-q)-1;if(console.log(` Gap: ${F} versions between them`),K>q)console.log(` \uD83D\uDCC8 ${J} is newer than ${$}`);else console.log(` \uD83D\uDCC9 ${J} is older than ${$}`)}console.log(`
|
|
157
157
|
\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)}});w.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?O.verbose():O.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
|
|
158
|
-
`),Q("which",["npm"],{stdio:"pipe"}).on("close",async(U)=>{if(U!==0){console.log("\uD83D\uDCE1 Using npm registry API search...");try{let{RegistryClient:j}=await import("../chunk-
|
|
158
|
+
`),Q("which",["npm"],{stdio:"pipe"}).on("close",async(U)=>{if(U!==0){console.log("\uD83D\uDCE1 Using npm registry API search...");try{let{RegistryClient:j}=await import("../chunk-a56s1xrt.js"),q=await new j(V.cwd(),J,void 0).searchPackages(Z,z);if(q.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}q.forEach((K,F)=>{if(console.log(`${F+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 X=Q("npm",["search",Z,"--json"],{stdio:"pipe"}),G="";X.stdout?.on("data",(j)=>{G+=j.toString()}),X.stderr?.on("data",(j)=>{if($.verbose)J.warn("npm search stderr:",j.toString())}),X.on("close",(j)=>{if(j===0)try{let q=JSON.parse(G).slice(0,z);if(q.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}q.forEach((K,F)=>{if(console.log(`${F+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)}`)}});w.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?O.verbose():O.quiet(),J=await k(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...`),z1(Q,"branchHousekeeping","getOrphanedBuddyBranches","branch cleanup");let Y=await Q.getOrphanedBuddyBranches(),U=new Date;U.setDate(U.getDate()-z);let X=Y.filter((j)=>j.lastCommitDate<U);if(X.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 ${X.length} stale branches to clean up:`),X.forEach((j)=>{let H=Math.floor((Date.now()-j.lastCommitDate.getTime())/86400000);$.info(` - ${j.name} (${H} days old)`)}),Z.dryRun){$.info(`
|
|
159
159
|
\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 a.default({type:"confirm",name:"confirmed",message:`Are you sure you want to delete ${X.length} stale branches?`,initial:!1})).confirmed){$.info("\u274C Cleanup cancelled");return}}z1(Q,"branchHousekeeping","cleanupStaleBranches","branch cleanup");let G=await Q.cleanupStaleBranches(z,!1);if(G.deleted.length>0)$.success(`\u2705 Successfully deleted ${G.deleted.length} stale branches`);if(G.failed.length>0)$.warn(`\u26A0\uFE0F Failed to delete ${G.failed.length} branches`),G.failed.forEach((j)=>$.warn(` - ${j}`));$.info(`
|
|
160
160
|
\uD83D\uDCCA Cleanup Summary:`),$.info(` \u2705 Deleted: ${G.deleted.length}`),$.info(` \u274C Failed: ${G.failed.length}`),$.info(` \uD83D\uDCCA Total processed: ${X.length}`)}catch(Q){$.error("Branch cleanup failed:",Q),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await k(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),z1(Q,"branchHousekeeping","getBuddyBranches","branch listing");let[U,X]=await Promise.all([Q.getBuddyBranches(),Q.getPullRequests("open")]),G=new Set(X.map((K)=>K.head)),j=U;if(Z.orphanedOnly)j=j.filter((K)=>!G.has(K.name));if(Z.staleOnly)j=j.filter((K)=>K.lastCommitDate<Y&&!G.has(K.name));if(j.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(`
|
|
161
161
|
\uD83D\uDCCA Found ${j.length} buddy branch${j.length!==1?"es":""}:
|
|
@@ -169,9 +169,9 @@ For manual setup, visit:`),$.info("\uD83D\uDD17 Repository settings: https://git
|
|
|
169
169
|
`),V.exit(2);return}if(j)V.stdout.write(`${j}
|
|
170
170
|
`);V.exit(X.failed?1:0)});w.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("--offer","Post the checkboxes on the pull request rather than running one").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 --offer").example("buddy touch 42 --name unit-tests").action(async(Z,$)=>{let J=$.verbose?O.verbose():O.quiet(),Q=await k($.config);try{let z=Number.parseInt(Z,10),Y=await d(Q,"finishing touches",J),X=(await Y.getPullRequests("open")).find((M)=>M.number===z);if(!X)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let{FINISHING_TOUCHES:G,getFinishingTouch:j,hasTouchOffer:H,parseTouchSelections:q,withTouchOffer:K}=await import("../chunk-vs68hsbp.js");if($.offer){if(H(X.body)){J.info(`\u2139\uFE0F PR #${X.number} already carries the finishing-touch offer`);return}let M=K(X.body);if($.dryRun){J.info(`\uD83D\uDD0D [DRY RUN] Would offer finishing touches on PR #${X.number}`);return}await Y.updatePullRequest(X.number,{body:M}),J.success(`\u2705 Offered finishing touches on PR #${X.number}`);return}let F=$.name?[$.name]:q(X.body);if(F.length===0){J.info("\u2139\uFE0F No finishing touches are ticked on this pull request");return}let{createAiClient:W}=await import("../chunk-vtr2vbk0.js"),T=W(Q,J);if(!T)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: ${F.join(", ")}`);return}let{runStackedTouch:A}=await import("../chunk-b59zbkfx.js");for(let M of F){if(!G[M]){J.warn(`\u26A0\uFE0F Unknown finishing touch '${M}', skipping`);continue}let L=await A({provider:Y,pullRequest:X,touch:j(M),ai:T,workspace:V.cwd(),...$.testCommand?{testCommand:$.testCommand.split(" ")}:{},logger:J});await Y.createComment(z,L.comment),J.success(`\u2705 ${M}: ${L.mode}`)}let I=X.body.replace(/^(\s*-\s*)\[[xX]\](\s*<!--\s*buddy:touch=)/gm,"$1[ ]$2");if(I!==X.body)await Y.updatePullRequest(z,{body:I})}catch(z){J.error("Finishing touch failed:",z),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await k(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 W=Z.payload||V.env.GITHUB_EVENT_PATH;if(!W)$.error("\u274C No event payload. Pass --issue or --payload, or run inside CI."),V.exit(1);let T=await Bun.file(W).json();if(Q=Number(T?.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((W)=>W.number===Q);if(!U){$.info(`\u2139\uFE0F Issue #${Q} is not open`);return}let{clearQuickSelection:X,parseQuickSelection:G,QUICK_LINKS_MARKER:j,renderQuickLinks:H}=await import("../chunk-zk8zdv23.js"),q=G(U.body);if(q.actions.length>0){if($.info(`\uD83E\uDD16 Requested: ${q.actions.join(", ")}`),Z.dryRun)return;let{createAiClient:W}=await import("../chunk-vtr2vbk0.js"),T=W(J,$);if(!T){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:X(U.body)});for(let A of q.actions){if(A==="plan"){let{runPlan:b}=await import("../chunk-65by8f14.js"),R=await b({config:J,provider:z,number:Q,isPullRequest:!1,logger:$});await z.createComment(Q,R),$.success("\u2705 Ran plan");continue}let{BUILTIN_TOOLS:I,createReadIssueTool:M,getFinishingTouch:L,runAgent:E}=await import("../chunk-65by8f14.js"),B=L("autofix"),N=await E(T,{mode:B.mode,task:`${B.buildTask({files:[]})}
|
|
171
171
|
|
|
172
|
-
Call \`read_issue\` to see what was asked for.`,tools:[...I,M(z,Q,!1)],context:{workspace:V.cwd(),baseBranch:J.repository?.baseBranch??"main"},logger:$});await z.createComment(Q,N.output||`I could not finish that (${N.stopReason}).`),$.success(`\u2705 Ran ${A}`)}return}if(U.body.includes(j)){$.debug("Quick-links already posted on this issue");return}let K=J.issues?.dependencyContext?await kZ(J,$):[],F=H({body:U.body,packages:K});if(Z.dryRun){$.info(F);return}await z.createComment(Q,F),$.success(`\u2705 Posted quick-links on #${Q}`)}catch(Q){$.error("handle-issue failed:",Q),V.exit(1)}});w.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?O.verbose():O.quiet(),Q=await k($.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:X,runGates:G,gateIcon:j,summarizeGates:H}=await import("../chunk-vmt1bed1.js"),{parseManifest:q}=await import("../chunk-xxwevpnr.js"),F=(await Y.getPullRequests("open")).find((P)=>P.number===z);if(!F)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let W=Q.gates??{},T=q(F.body),{manifestUpdates:A}=await import("../chunk-xxwevpnr.js"),I=T?await Promise.all(A(T).map(async(P)=>{let _={name:P.name,version:P.newVersion};if(W.dependencyGate?.blockEol===!1)return _;if(T.updates.find((k1)=>k1.name===P.name)?.dependencyType!=="docker-image")return _;let{checkEol:s,describeEol:p}=await import("../chunk-dd895pm0.js"),Y1=await s(P.name,P.newVersion,{logger:J}),t=p(Y1);return Y1?.eol&&t?{..._,eol:t}:_})):[],M=G({title:F.title,body:F.body,manifest:T,dependencies:I},{...W.titleFormat?{titleFormat:W.titleFormat}:{},...W.description?{description:W.description}:{},...W.dependencyGate?{dependencyGate:W.dependencyGate}:{}}),L=U(F.body??""),E=L.length>0?await Y.getIssues("all"):[],B=L.map((P)=>E.find((_)=>_.number===P)).filter((P)=>Boolean(P)).map((P)=>({number:P.number,title:P.title,body:P.body})),{createAiClient:N}=await import("../chunk-vtr2vbk0.js"),b=await X(N(Q,J),{title:F.title,body:F.body,diff:await Y.getPullRequestDiff(z),linkedIssues:B},{...W.linkedIssue?{linkedIssue:W.linkedIssue}:{},...W.custom?{custom:W.custom}:{}},J),R=[...M,...b],h=H(R);for(let P of R)J.info(`${j(P)} ${P.name}: ${P.summary}`);let v=h.conclusion==="failure";if(v)await g(Q.notifications,"gate.failed",{number:z,checks:R.filter((P)=>!P.passed).map((P)=>P.name)});if($.dryRun||!Q1(Y,"checkRuns","createCheckRun")){if(J.info(h.summary),v)V.exit(1);return}if(await Y.createCheckRun("buddy/gates",await Y.getPullRequestHeadSha(z),h),v)V.exit(1)}catch(z){J.error("Gate run failed:",z),V.exit(1)}});w.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?O.verbose():O.quiet(),Q=await k($.config);try{let z=Number.parseInt(Z,10),Y=await d(Q,"post-merge actions",J),X=(await Y.getPullRequests("all")).find((H)=>H.number===z);if(!X)J.error(`\u274C Pull request #${z} not found`),V.exit(1);if(X.state!=="merged"){J.info(`\u2139\uFE0F PR #${z} was closed without merging; nothing to do`);return}let{runPostMerge:G}=await import("../chunk-vmt1bed1.js"),j=await G(Y,X,Q.gates?.postMerge??{},{baseBranch:Q.repository?.baseBranch??X.base,logger:J,refreshDashboard:async()=>{if(Q.dashboard?.enabled===!1)throw Error("dashboard.enabled is false");await new m(Q).createOrUpdateDashboard()}});for(let H of j.performed)J.success(`\u2705 ${H}`);for(let H of j.skipped)J.info(`\u23ED\uFE0F ${H.action}: ${H.reason}`)}catch(z){J.error("Post-merge actions failed:",z),V.exit(1)}});w.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("--scheduled","This is the workflow's scheduled run; honour reports.enabled").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?O.verbose():$?O.silent():O.quiet(),Q=await k(Z.config);try{let{appendHistory:z,computeDeltas:Y,computeMetrics:U,findPrevious:X,HISTORY_PATH:G,loadHistory:j,REPORT_MARKER:H,REPORT_PERIODS:q,renderReport:K,withNarrative:F}=await import("../chunk-y3w8h4sy.js"),W=Z.period??Q.reports?.period??"30d";if(!q.includes(W))J.error(`\u274C Unknown period '${W}'. Expected one of ${q.join(", ")}.`),V.exit(1);let T=await d(Q,"reporting",J),A=new m(Q,V.cwd()),{PackageScanner:I}=await import("../chunk-6gdenphk.js"),M=new I(V.cwd(),J,Q.packages?.ignorePaths),[L,E,B]=await Promise.all([A.scanForUpdates(),T.getPullRequests("all"),M.scanProject()]),{ecosystemOf:N}=await import("../chunk-
|
|
172
|
+
Call \`read_issue\` to see what was asked for.`,tools:[...I,M(z,Q,!1)],context:{workspace:V.cwd(),baseBranch:J.repository?.baseBranch??"main"},logger:$});await z.createComment(Q,N.output||`I could not finish that (${N.stopReason}).`),$.success(`\u2705 Ran ${A}`)}return}if(U.body.includes(j)){$.debug("Quick-links already posted on this issue");return}let K=J.issues?.dependencyContext?await kZ(J,$):[],F=H({body:U.body,packages:K});if(Z.dryRun){$.info(F);return}await z.createComment(Q,F),$.success(`\u2705 Posted quick-links on #${Q}`)}catch(Q){$.error("handle-issue failed:",Q),V.exit(1)}});w.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?O.verbose():O.quiet(),Q=await k($.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:X,runGates:G,gateIcon:j,summarizeGates:H}=await import("../chunk-vmt1bed1.js"),{parseManifest:q}=await import("../chunk-xxwevpnr.js"),F=(await Y.getPullRequests("open")).find((P)=>P.number===z);if(!F)J.error(`\u274C Pull request #${z} is not open`),V.exit(1);let W=Q.gates??{},T=q(F.body),{manifestUpdates:A}=await import("../chunk-xxwevpnr.js"),I=T?await Promise.all(A(T).map(async(P)=>{let _={name:P.name,version:P.newVersion};if(W.dependencyGate?.blockEol===!1)return _;if(T.updates.find((k1)=>k1.name===P.name)?.dependencyType!=="docker-image")return _;let{checkEol:s,describeEol:p}=await import("../chunk-dd895pm0.js"),Y1=await s(P.name,P.newVersion,{logger:J}),t=p(Y1);return Y1?.eol&&t?{..._,eol:t}:_})):[],M=G({title:F.title,body:F.body,manifest:T,dependencies:I},{...W.titleFormat?{titleFormat:W.titleFormat}:{},...W.description?{description:W.description}:{},...W.dependencyGate?{dependencyGate:W.dependencyGate}:{}}),L=U(F.body??""),E=L.length>0?await Y.getIssues("all"):[],B=L.map((P)=>E.find((_)=>_.number===P)).filter((P)=>Boolean(P)).map((P)=>({number:P.number,title:P.title,body:P.body})),{createAiClient:N}=await import("../chunk-vtr2vbk0.js"),b=await X(N(Q,J),{title:F.title,body:F.body,diff:await Y.getPullRequestDiff(z),linkedIssues:B},{...W.linkedIssue?{linkedIssue:W.linkedIssue}:{},...W.custom?{custom:W.custom}:{}},J),R=[...M,...b],h=H(R);for(let P of R)J.info(`${j(P)} ${P.name}: ${P.summary}`);let v=h.conclusion==="failure";if(v)await g(Q.notifications,"gate.failed",{number:z,checks:R.filter((P)=>!P.passed).map((P)=>P.name)});if($.dryRun||!Q1(Y,"checkRuns","createCheckRun")){if(J.info(h.summary),v)V.exit(1);return}if(await Y.createCheckRun("buddy/gates",await Y.getPullRequestHeadSha(z),h),v)V.exit(1)}catch(z){J.error("Gate run failed:",z),V.exit(1)}});w.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?O.verbose():O.quiet(),Q=await k($.config);try{let z=Number.parseInt(Z,10),Y=await d(Q,"post-merge actions",J),X=(await Y.getPullRequests("all")).find((H)=>H.number===z);if(!X)J.error(`\u274C Pull request #${z} not found`),V.exit(1);if(X.state!=="merged"){J.info(`\u2139\uFE0F PR #${z} was closed without merging; nothing to do`);return}let{runPostMerge:G}=await import("../chunk-vmt1bed1.js"),j=await G(Y,X,Q.gates?.postMerge??{},{baseBranch:Q.repository?.baseBranch??X.base,logger:J,refreshDashboard:async()=>{if(Q.dashboard?.enabled===!1)throw Error("dashboard.enabled is false");await new m(Q).createOrUpdateDashboard()}});for(let H of j.performed)J.success(`\u2705 ${H}`);for(let H of j.skipped)J.info(`\u23ED\uFE0F ${H.action}: ${H.reason}`)}catch(z){J.error("Post-merge actions failed:",z),V.exit(1)}});w.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("--scheduled","This is the workflow's scheduled run; honour reports.enabled").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?O.verbose():$?O.silent():O.quiet(),Q=await k(Z.config);try{let{appendHistory:z,computeDeltas:Y,computeMetrics:U,findPrevious:X,HISTORY_PATH:G,loadHistory:j,REPORT_MARKER:H,REPORT_PERIODS:q,renderReport:K,withNarrative:F}=await import("../chunk-y3w8h4sy.js"),W=Z.period??Q.reports?.period??"30d";if(!q.includes(W))J.error(`\u274C Unknown period '${W}'. Expected one of ${q.join(", ")}.`),V.exit(1);let T=await d(Q,"reporting",J),A=new m(Q,V.cwd()),{PackageScanner:I}=await import("../chunk-6gdenphk.js"),M=new I(V.cwd(),J,Q.packages?.ignorePaths),[L,E,B]=await Promise.all([A.scanForUpdates(),T.getPullRequests("all"),M.scanProject()]),{ecosystemOf:N}=await import("../chunk-g4803nvq.js"),b={};for(let X1 of B)for(let j1 of X1.dependencies){let v1=N({name:j1.name,currentVersion:j1.currentVersion,newVersion:j1.currentVersion,updateType:"patch",dependencyType:j1.type,file:X1.path});b[v1]=(b[v1]??0)+1}let{DeprecatedDependenciesChecker:R}=await import("../chunk-ffbbc38r.js"),h=await new R().checkDeprecatedDependencies(B).catch(()=>[]),v=U({period:W,now:new Date,pullRequests:E,updates:L.updates,dependenciesByEcosystem:b,deprecated:h.length}),P=Q.repository?.baseBranch||"main",_=await j(T,P,J),i=Y(v,X(_,W));if(Z.format==="json"){V.stdout.write(`${JSON.stringify({metrics:v,deltas:i},null,2)}
|
|
173
173
|
`);return}let{createAiClient:s}=await import("../chunk-vtr2vbk0.js"),p=await F(K(v,i),v,s(Q,J),Z.prompt??Q.reports?.prompt,J),{shouldPublishReport:Y1}=await import("../chunk-y3w8h4sy.js"),t=Y1({scheduled:Boolean(Z.scheduled),enabled:Q.reports?.enabled});if(Z.publish&&!t.publish){J.info(`\u2139\uFE0F Not publishing: ${t.reason}`);return}if(!Z.publish){V.stdout.write(`${p}
|
|
174
|
-
`);return}let b1=(await T.getIssues("open")).find((X1)=>X1.body.includes(H)),h1=Q.reports?.title??"Dependency Report",y1=Q.reports?.labels??["dependencies","report"],w0=b1?await T.updateIssue(b1.number,{title:h1,body:p,labels:y1}):await T.createIssue({title:h1,body:p,labels:y1});J.success(`\u2705 Report published: ${w0.url}`),await T.commitChanges(P,"chore(reports): record dependency metrics snapshot",[{path:G,content:z(_,v),type:_.length>0?"update":"create"}],P)}catch(z){J.error("Report failed:",z),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await k(Z.config).catch((U)=>{return $.warn(`\u26A0\uFE0F Could not load configuration: ${r(U)}`),{}}),{diagnose:Q,renderDoctorReport:z}=await import("../chunk-
|
|
174
|
+
`);return}let b1=(await T.getIssues("open")).find((X1)=>X1.body.includes(H)),h1=Q.reports?.title??"Dependency Report",y1=Q.reports?.labels??["dependencies","report"],w0=b1?await T.updateIssue(b1.number,{title:h1,body:p,labels:y1}):await T.createIssue({title:h1,body:p,labels:y1});J.success(`\u2705 Report published: ${w0.url}`),await T.commitChanges(P,"chore(reports): record dependency metrics snapshot",[{path:G,content:z(_,v),type:_.length>0?"update":"create"}],P)}catch(z){J.error("Report failed:",z),V.exit(1)}});w.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?O.verbose():O.quiet(),J=await k(Z.config).catch((U)=>{return $.warn(`\u26A0\uFE0F Could not load configuration: ${r(U)}`),{}}),{diagnose:Q,renderDoctorReport:z}=await import("../chunk-v9fnbdgr.js"),Y=await Q(J);if(V.stdout.write(z(Y)),!Y.healthy)V.exit(1)});w.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?O.verbose():O.silent(),J=await k(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
|
|
175
175
|
`),V.exit(1);let z=Z.outputSchemaFile?await Bun.file(Z.outputSchemaFile).text():Z.outputSchema,Y;if(z)try{Y=JSON.parse(z)}catch(F){V.stderr.write(`\u274C --output-schema is not valid JSON: ${r(F)}
|
|
176
176
|
`),V.exit(1)}let{createAiClient:U}=await import("../chunk-vtr2vbk0.js"),X=U(Z.model?{...J,ai:{...J.ai,model:Z.model}}:J,$);if(!X)V.stderr.write(`\u274C No AI provider configured. See https://buddy.sh/ai/providers
|
|
177
177
|
`),V.exit(1);let{publishOutput:G,runHeadless:j}=await import("../chunk-1w1h2tsf.js"),H=await j({prompt:Q,ai:X,...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):
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Cb as a,Db as b}from"./chunk-
|
|
2
|
+
import{Cb as a,Db as b}from"./chunk-xqveh8a5.js";import"./chunk-q2tjkhez.js";import"./chunk-5yfaptmp.js";import"./chunk-59993g25.js";import"./chunk-va3k91tf.js";import"./chunk-0g4ybxwj.js";import"./chunk-142zh7e5.js";import"./chunk-ctdfppxk.js";import"./chunk-24xvskkf.js";import"./chunk-z18bksyr.js";import"./chunk-b9szrnxw.js";import"./chunk-x1w6q9tk.js";import"./chunk-kbvj6qxc.js";export{b as runReviewForPR,a as reviewPullRequest};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Da as a}from"./chunk-
|
|
2
|
+
import{Da as a}from"./chunk-cm6devhe.js";import"./chunk-rygtb1x3.js";import"./chunk-08daxhzx.js";import"./chunk-d4gk9awk.js";import"./chunk-gweqk008.js";import"./chunk-bnp0r4eh.js";import"./chunk-0f1xye20.js";import"./chunk-9sdgy9nm.js";import"./chunk-5jvde2as.js";import"./chunk-ctdfppxk.js";import"./chunk-wjfw6rx8.js";import"./chunk-w55x2g9n.js";import"./chunk-1xe0960b.js";import"./chunk-gpjde0j6.js";import"./chunk-j46f90n8.js";import"./chunk-enq0gm64.js";import"./chunk-c6ptrc0v.js";import"./chunk-1pecmenc.js";import"./chunk-sxfk3naz.js";import"./chunk-24xvskkf.js";import"./chunk-z18bksyr.js";import"./chunk-cj4d5ad7.js";import"./chunk-2z2gh050.js";import"./chunk-knpdntnh.js";import"./chunk-54er1whp.js";import"./chunk-ktn47bq8.js";import"./chunk-2z9pkk1y.js";import"./chunk-vpw7adwd.js";import"./chunk-b9szrnxw.js";import"./chunk-x1w6q9tk.js";import"./chunk-z05djfac.js";import"./chunk-kbvj6qxc.js";export{a as Scheduler};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Nc as a,Oc as b,Pc as c,Qc as d,Rc as e,Sc as f,Tc as g}from"./chunk-
|
|
2
|
+
import{Nc as a,Oc as b,Pc as c,Qc as d,Rc as e,Sc as f,Tc as g}from"./chunk-s1cgwkkr.js";import"./chunk-2z2gh050.js";import"./chunk-knpdntnh.js";import"./chunk-54er1whp.js";import"./chunk-ktn47bq8.js";import"./chunk-2z9pkk1y.js";import"./chunk-b9szrnxw.js";import"./chunk-x1w6q9tk.js";import"./chunk-z05djfac.js";import"./chunk-kbvj6qxc.js";export{b as regenerateLockFile,d as nestedLockProjects,f as missingLockFiles,e as lockFileFor,g as hasLockFile,a as getAllLockFilePaths,c as detectRequiredPackageManagers};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ud as R}from"./chunk-7b4jsg36.js";import{re as F,se as A}from"./chunk-
|
|
2
|
+
import{ud as R}from"./chunk-7b4jsg36.js";import{re as F,se as A}from"./chunk-ctdfppxk.js";import{Bf as S}from"./chunk-1pecmenc.js";import{Rf as L}from"./chunk-sxfk3naz.js";import{Mh as K,Ph as O}from"./chunk-x1w6q9tk.js";import{el as P}from"./chunk-kbvj6qxc.js";var b=[{kind:"lockfile-drift",mechanical:!0,patterns:[/lockfile had changes, but lockfile is frozen/i,/your lockfile does not satisfy your workspace/i,/the lockfile (?:is|was) out of date/i,/npm ci can only install packages when your package\.json and package-lock\.json .* are in sync/i,/composer\.lock is not up to date/i]},{kind:"flake",mechanical:!0,patterns:[/\bECONNRESET\b|\bETIMEDOUT\b|\bENOTFOUND\b|\bEAI_AGAIN\b/,/socket hang up/i,/502 Bad Gateway|503 Service Unavailable|504 Gateway Time-?out/i,/rate limit exceeded/i,/the runner has received a shutdown signal/i]},{kind:"install",mechanical:!1,patterns:[/could not resolve (?:dependency|host)/i,/no matching version found for/i,/unable to resolve dependency tree/i,/peer dep(?:endency)? .* conflict/i]},{kind:"type-error",mechanical:!1,patterns:[/error TS\d{4}:/,/\berror\[E\d+\]:/,/Type '.*' is not assignable to type/]},{kind:"test-failure",mechanical:!1,patterns:[/\d+ (?:tests? )?fail(?:ed|ing)\b/i,/\(fail\)/,/AssertionError|expect\(received\)/,/\u25CF .* \u203A /]},{kind:"lint",mechanical:!1,patterns:[/\b\d+ problems? \(\d+ errors?/i,/eslint|pickier|biome|oxlint/i]}];function N(x){if(!x.trim())return{kind:"unknown",mechanical:!1,evidence:[]};let H=x.split(`
|
|
3
3
|
`);for(let z of b){let J=[];for(let V of H)if(z.patterns.some((Q)=>Q.test(V))){if(J.push(V.trim()),J.length>=5)break}if(J.length>0)return{kind:z.kind,mechanical:z.mechanical,evidence:J}}return{kind:"unknown",mechanical:!1,evidence:T(H)}}function T(x,H=40){let z=x.filter((J)=>/\b(?:error|failed|failure|exception|panic|fatal)\b/i.test(J)&&!/^\s*(?:at\s|\s*\.\.\.)/.test(J));return(z.length>0?z:x.slice(-H)).slice(-H).map((J)=>J.trim()).filter(Boolean)}function G(x){switch(x.kind){case"lockfile-drift":return"The lock file is out of step with its manifest.";case"flake":return"A network or runner problem, unrelated to the change.";case"install":return"Dependencies could not be resolved.";case"type-error":return"The change does not type-check.";case"test-failure":return"One or more tests failed.";case"lint":return"Lint or formatting checks failed.";default:return"The failure could not be classified automatically."}}var w=3;async function M(x,H,z,J){let V=J??O();try{let Q=await x.listWorkflowRuns(H,{status:"completed",limit:20});for(let Y of _(Q).slice(0,w)){let Z=await x.getWorkflowRunLogs(Y.id);if(!Z)continue;if(N(Z).kind===z)return V.info(`\uD83E\uDDED ${H} already fails the same way (run ${Y.id}) \u2014 not this pull request's to fix`),!0}return!1}catch(Q){return V.debug(`Could not check ${H} for a pre-existing failure: ${K(Q)}`),!1}}function _(x){let H=new Map;for(let z of x)if(!H.has(z.name))H.set(z.name,z);return[...H.values()].filter((z)=>z.conclusion==="failure")}function h(x,H){if(!x)return"Tried to regenerate the lock file, but the install did not succeed.";if(!H)return"Regenerated the lock file, but could not push it to the branch. The change is in the workspace only, so the run will still be red until someone commits it.";return"Regenerated the lock file and pushed the result. No model was needed."}function f(x){let H="Repairs run on the pull request's branch, and answering a comment runs on the default branch, so anything I changed here would land on the wrong tree. ";if(x.kind==="lockfile-drift")return`Regenerating the lock file would fix this, and no model would be needed. ${H}The \`fix-ci\` job will do it on the next failing run, or you can run \`buddy fix-ci --run-id <id> --pr <number>\` yourself.`;return`${H}The \`fix-ci\` job runs on the failing run itself and can repair this; this reply is the diagnosis it would start from.`}async function I(x){let H=x.logger??O(),z=N(x.log),J=x.maxAttempts??3;if(H.info(`\uD83E\uDE7A CI failure classified as ${z.kind}`),x.failsOnBase??(x.checkBase?await x.checkBase(z.kind):!1))return{failure:z,action:"skipped",fixed:!1,report:$(z,"This failure also occurs on the base branch, so it is not caused by this change. Fixing it here would only mask it.")};if((x.priorAttempts??0)>=J)return{failure:z,action:"skipped",fixed:!1,report:$(z,`Already attempted ${x.priorAttempts} time(s); stopping rather than looping.`)};if(x.analysisOnly&&z.kind!=="flake")return{failure:z,action:"reported",fixed:!1,report:$(z,f(z))};if(z.kind==="lockfile-drift"&&x.regenerateLockfile){if(x.dryRun)return{failure:z,action:"mechanical-fix",fixed:!1,report:$(z,"Regenerating the lock file would fix this. No model would be needed. Nothing was changed, because this was a dry run.")};H.info("\uD83D\uDD27 Regenerating the lock file");let{regenerated:Y,pushed:Z}=await x.regenerateLockfile();return{failure:z,action:"mechanical-fix",fixed:Z,report:$(z,h(Y,Z))}}if(z.kind==="flake"){if(x.dryRun)return{failure:z,action:"retry",fixed:!1,report:$(z,"This looks transient, and re-running the failed jobs would likely clear it. Nothing was changed, because this was a dry run.")};if(!x.rerun)return{failure:z,action:"retry",fixed:!1,report:$(z,"This looks transient. Re-running the failed job is likely to clear it.")};H.info("\uD83D\uDD01 Re-running the failed jobs");let Y=await x.rerun();return{failure:z,action:"retry",fixed:!1,report:$(z,Y?"This looks transient, so I re-ran the failed jobs. No model was needed.":"This looks transient, but I could not re-run the failed jobs \u2014 `actions: write` is the usual reason. "+"Re-running them from the Actions tab is likely to clear it.")}}if(!x.ai)return{failure:z,action:"reported",fixed:!1,report:$(z,"No AI provider is configured, so this needs a human. See https://buddy.sh/ai/providers to enable automatic repair.")};let Q=await L(x.ai,{mode:S,task:["A CI job on this branch is failing. Diagnose the root cause and fix it if the fix is clear.","",`Classification: ${z.kind} \u2014 ${G(z)}`,"","Relevant log lines:",z.evidence.join(`
|
|
4
4
|
`),"","Verify your fix by running the project's tests or build before reporting it done.","If the fix is not clear, explain what you found rather than guessing."].join(`
|
|
5
5
|
`),context:{workspace:x.workspace,baseBranch:x.baseBranch,...x.branch?{branch:x.branch}:{}},logger:H});return{failure:z,action:"agent-fix",fixed:Q.stopReason==="completed",report:$(z,Q.output||"The repair run ended without a conclusion.")}}function $(x,H){let z=`## \uD83E\uDE7A CI failure analysis
|
|
@@ -22,6 +22,6 @@ ${JSON.stringify(J)}
|
|
|
22
22
|
|
|
23
23
|
${V}`}async function m(x,H,z){if(!F(x,"ciRuns","listWorkflowRuns"))return null;try{let J=await x.getPullRequestHeadSha(H.number),V=await x.listWorkflowRuns(H.head,{status:"completed",limit:30}),Q=J?V.filter((Y)=>Y.headSha===J):V;return _(Q)[0]?.id??null}catch(J){return z.debug(`Could not resolve the failing run for #${H.number}: ${K(J)}`),null}}async function c(x){let H=x.logger??O(),{config:z,provider:J}=x,V=x.workspace??process.cwd();A(J,"ciLogs","getWorkflowRunLogs","reading CI logs");let Q;if(x.prNumber){if(Q=(await J.getPullRequests("open")).find((W)=>W.number===x.prNumber),!Q)return`Could not find open pull request #${x.prNumber}.`}let Y=x.runId??(Q?await m(J,Q,H):null);if(!Y)return Q?"Nothing is failing at the head of this pull request, so there is nothing to diagnose.":"No run to diagnose. Pass --run-id, or --pr so I can find the failing run myself.";let Z=await J.getWorkflowRunLogs(Y);if(!Z)return H.warn(`\u26A0\uFE0F Could not read the logs for run ${Y}; nothing to diagnose`),`Could not read the logs for run ${Y}. They may have expired.`;let U=E(Q?.body)?.attempts??0,j=z.repository?.baseBranch??"main",D=F(J,"ciRuns","listWorkflowRuns"),y=F(J,"ciRuns","rerunWorkflowRun"),{createAiClient:v}=await import("./chunk-vtr2vbk0.js"),C=await I({log:Z,priorAttempts:U,workspace:V,baseBranch:j,ai:x.analysisOnly?null:v(z,H),logger:H,dryRun:Boolean(x.dryRun),analysisOnly:Boolean(x.analysisOnly),...D?{checkBase:(X)=>M({listWorkflowRuns:(W,k)=>J.listWorkflowRuns(W,k),getWorkflowRunLogs:(W)=>J.getWorkflowRunLogs(W)},j,X,H)}:{},...y?{rerun:()=>J.rerunWorkflowRun(Y)}:{},...x.analysisOnly?{}:{regenerateLockfile:()=>g(V,H)}});if(H.info(`
|
|
24
24
|
${C.report}
|
|
25
|
-
`),x.prNumber&&!x.dryRun){if(await J.createComment(x.prNumber,C.report),C.action!=="skipped"&&Q)try{await J.updatePullRequest(x.prNumber,{body:q(Q.body,U+1)})}catch(X){H.warn(`Could not record the fix attempt on PR #${x.prNumber}: ${K(X)}`)}}return await R(z.notifications,"fixci.completed",{...x.prNumber?{number:x.prNumber}:{},action:C.action,fixed:C.fixed}),`${C.action}${C.fixed?" (fixed)":""}`}async function g(x,H){let{regenerateLockFile:z,detectRequiredPackageManagers:J,getAllLockFilePaths:V,hasLockFile:Q}=await import("./chunk-
|
|
25
|
+
`),x.prNumber&&!x.dryRun){if(await J.createComment(x.prNumber,C.report),C.action!=="skipped"&&Q)try{await J.updatePullRequest(x.prNumber,{body:q(Q.body,U+1)})}catch(X){H.warn(`Could not record the fix attempt on PR #${x.prNumber}: ${K(X)}`)}}return await R(z.notifications,"fixci.completed",{...x.prNumber?{number:x.prNumber}:{},action:C.action,fixed:C.fixed}),`${C.action}${C.fixed?" (fixed)":""}`}async function g(x,H){let{regenerateLockFile:z,detectRequiredPackageManagers:J,getAllLockFilePaths:V,hasLockFile:Q}=await import("./chunk-225s199d.js"),{commitAndPush:Y}=await import("./chunk-ry5zh9cx.js"),Z=J(["package.json","composer.json"],x).filter((j)=>Q(j,x)),U=!1;for(let j of Z){let D=await z(j,x);if(D.success)U=!0;else H.warn(`\u26A0\uFE0F ${D.message}`)}if(!U)return{regenerated:!1,pushed:!1};try{return{regenerated:!0,pushed:await Y(V(),`fix(deps): regenerate the lock file
|
|
26
26
|
|
|
27
27
|
The lock file had drifted from the manifest, which failed CI.`,x)}}catch(j){return H.warn(`\u26A0\uFE0F Could not push the regenerated lock file: ${K(j)}`),{regenerated:!0,pushed:!1}}}export{N as Ea,T as Fa,G as Ga,M as Ha,_ as Ia,I as Ja,c as Ka};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{tg as C,yg as B}from"./chunk-knpdntnh.js";import{Ag as x,zg as v}from"./chunk-54er1whp.js";import{xh as w}from"./chunk-2z9pkk1y.js";import{Jh as S}from"./chunk-b9szrnxw.js";import{el as T}from"./chunk-kbvj6qxc.js";var R={critical:"\uD83D\uDD34 Critical",high:"\uD83D\uDFE0 High",moderate:"\uD83D\uDFE1 Moderate",low:"\u26AA Low"};function F(J){let Q=J.filter((O)=>(O.securityAdvisories?.length??0)>0);if(Q.length===0)return"";let q=Q.reduce((O,Z)=>O+(Z.securityAdvisories?.length??0),0),X=`## \uD83D\uDD12 Security Advisories
|
|
3
|
+
|
|
4
|
+
`;X+=`This PR resolves ${q} known ${q===1?"vulnerability":"vulnerabilities"} `,X+=`across ${Q.length} ${Q.length===1?"package":"packages"}.
|
|
5
|
+
|
|
6
|
+
`,X+=`| Package | Severity | Advisory | Fixed in | Summary |
|
|
7
|
+
`,X+=`|---|---|---|---|---|
|
|
8
|
+
`;for(let O of Q)for(let Z of O.securityAdvisories??[]){let L=R[Z.severity]??Z.severity,_=Z.url?`[${Z.id}](${Z.url})`:Z.id,$=Z.aliases.length>0?` (${Z.aliases.join(", ")})`:"",G=Z.summary.replace(/\|/g,"\\|").replace(/\s*\n\s*/g," ").trim();X+=`| \`${O.name}\` | ${L} | ${_}${$} | \`${Z.fixedVersion??"n/a"}\` | ${G} |
|
|
9
|
+
`}return`${X}
|
|
10
|
+
`}async function u(J,Q){try{let q=Q.split("/").pop()||"";if(q==="package.json"){let X=JSON.parse(J),O=[];return W(X.dependencies,"dependencies",Q,O),W(X.devDependencies,"devDependencies",Q,O),W(X.peerDependencies,"peerDependencies",Q,O),W(X.optionalDependencies,"optionalDependencies",Q,O),{path:Q,type:"package.json",content:J,dependencies:O}}if(v(Q))return await x(Q,J);if(q==="composer.json"||q==="composer.lock"){let{parseComposerFile:X}=await import("./chunk-hc651afv.js");return await X(Q,J)}return null}catch{return null}}function W(J,Q,q,X){if(!J)return;for(let[O,Z]of Object.entries(J))X.push({name:O,currentVersion:Z,type:Q,file:q})}function n(J){let{existsSync:Q}=T("fs"),{join:q}=T("path");if(Q(q(J,"bun.lockb"))||Q(q(J,"bun.lock")))return"bun";if(Q(q(J,"pnpm-lock.yaml")))return"pnpm";if(Q(q(J,"yarn.lock")))return"yarn";if(Q(q(J,"package-lock.json")))return"npm";return"bun"}function d(J,Q){if(Q)return Q;if(J.length===1){let Z=J[0];return`chore(deps): update dependency ${Z.name} to ${Z.newVersion}`}let q=J.filter((Z)=>Z.updateType==="major"),X=J.filter((Z)=>Z.updateType==="minor"),O=J.filter((Z)=>Z.updateType==="patch");if(q.length>0)return`chore(deps): update ${q.length} major dependencies`;else if(X.length>0)return`chore(deps): update ${X.length} minor dependencies`;else return`chore(deps): update ${O.length} patch dependencies`}function o(J,Q){if(Q)return Q;if(J.length===1){let X=J[0];return`chore(deps): update dependency ${X.name} to v${X.newVersion}`}let q=J.filter((X)=>X.updateType==="major");if(q.length>0)return`chore(deps): update ${q.length} major dependencies`;else return"chore(deps): update all non-major dependencies"}function z(J,Q){if(Q)return Q;let q=`This PR contains the following updates:
|
|
11
|
+
|
|
12
|
+
`;q+=F(J),q+=`| Package | Change | Age | Adoption | Passing | Confidence |
|
|
13
|
+
`,q+=`|---|---|---|---|---|---|
|
|
14
|
+
`;for(let O of J){let Z=`\`${O.currentVersion}\` -> \`${O.newVersion}\``,L=O.metadata?.homepage?`[${O.name}](${O.metadata.homepage})`:O.name;q+=`| ${L} | ${Z} | [](https://docs.renovatebot.com/merge-confidence/) | [](https://docs.renovatebot.com/merge-confidence/) | [](https://docs.renovatebot.com/merge-confidence/) | [](https://docs.renovatebot.com/merge-confidence/) |
|
|
15
|
+
`}q+=`
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
`;let X=J.filter((O)=>O.releaseNotesUrl);if(X.length>0){q+=`### Release Notes
|
|
19
|
+
|
|
20
|
+
`;for(let O of X)if(O.releaseNotesUrl)q+=`<details>
|
|
21
|
+
<summary>${O.name}</summary>
|
|
22
|
+
|
|
23
|
+
`,q+=`[Release Notes](${O.releaseNotesUrl})
|
|
24
|
+
|
|
25
|
+
`,q+=`</details>
|
|
26
|
+
|
|
27
|
+
`}return q+=`### Configuration
|
|
28
|
+
|
|
29
|
+
`,q+=`\uD83D\uDCC5 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).
|
|
30
|
+
|
|
31
|
+
`,q+=`\uD83D\uDEA6 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.
|
|
32
|
+
|
|
33
|
+
`,q+=`\u267B **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.
|
|
34
|
+
|
|
35
|
+
`,q+=`\uD83D\uDD15 **Ignore**: Close this PR and you won't be reminded about this update again.
|
|
36
|
+
|
|
37
|
+
`,q+=`---
|
|
38
|
+
|
|
39
|
+
`,q+=` - [ ] <!-- rebase-check -->If you want to update/retry this PR, check this box
|
|
40
|
+
|
|
41
|
+
`,q+=`---
|
|
42
|
+
|
|
43
|
+
`,q+="This PR was generated by [Buddy](https://github.com/stacksjs/buddy).",q}function i(J,Q="buddy"){if(J.length===1){let X=J[0],O=X.name.replace(/[^a-z0-9-]/gi,"-");return`${Q}/update-${O}-to-${X.newVersion}`}if(J.filter((X)=>X.updateType==="major").length>0)return`${Q}/update-major-dependencies`;return`${Q}/update-dependencies`}function j(J){let Q=new Map;for(let X of J){let O=`${X.name}:${X.currentVersion}:${X.newVersion}`;Q.set(O,[...Q.get(O)??[],X])}let q=[];for(let X of Q.values()){let O=X.filter((L)=>k(L.file));if(O.length>0){let L=new Set;for(let _ of O)if(!L.has(_.file))L.add(_.file),q.push(_);continue}let Z=X[0];for(let L of X.slice(1))if(N(L.file)>N(Z.file))Z=L;q.push(Z)}return q}function k(J){let Q=J.split("/").pop()??"";return Q==="package.json"||Q==="composer.json"}function N(J){if(J==="package.json")return 3;if(J.endsWith("composer.json"))return 2;if(J.includes(".github/workflows/"))return 1;return 0}function s(J,Q={}){let{prioritizeSecurity:q=!0}=Q,X=[],O=j(J),Z=q?O.filter((Y)=>(Y.securityAdvisories?.length??0)>0):[],L=q?O.filter((Y)=>(Y.securityAdvisories?.length??0)===0):O;if(Z.length>0)X.push({name:"Security Updates",updates:Z,updateType:D(Z),title:"fix(deps): update vulnerable dependencies",body:z(Z)});let _=L.filter((Y)=>Y.dependencyType==="github-actions"),$=L.filter((Y)=>Y.dependencyType==="docker-image"),G=L.filter((Y)=>Y.dependencyType!=="github-actions"&&Y.dependencyType!=="docker-image");if(_.length>0)X.push({name:"GitHub Actions",updates:_,updateType:D(_),title:"chore(deps): update github actions",body:z(_)});if($.length>0)X.push({name:"Docker Images",updates:$,updateType:D($),title:"chore(deps): update docker images",body:z($)});let H=G.filter((Y)=>Y.updateType==="major"),K=G.filter((Y)=>Y.updateType==="minor"),I=G.filter((Y)=>Y.updateType==="patch");if(K.length>0||I.length>0){let Y=[...K,...I];X.push({name:"Non-Major Updates",updates:Y,updateType:K.length>0?"minor":"patch",title:"chore(deps): update all non-major dependencies",body:z(Y)})}let A=new Map;for(let Y of H){let E=`${Y.name}@${Y.newVersion}`;A.set(E,[...A.get(E)??[],Y])}for(let Y of A.values()){let E=Y[0];X.push({name:`Major Update - ${E.name}`,updates:Y,updateType:"major",title:`chore(deps): update dependency ${E.name} to ${E.newVersion}`,body:z(Y)})}return X}function D(J){if(J.some((Q)=>Q.updateType==="major"))return"major";if(J.some((Q)=>Q.updateType==="minor"))return"minor";return"patch"}var U={critical:4,high:3,moderate:2,low:1};function V(J){let Q=0;for(let q of J.securityAdvisories??[])Q=Math.max(Q,U[q.severity]??0);return Q}function r(J,Q={}){let{prioritizeSecurity:q=!0}=Q,X={major:3,minor:2,patch:1};return J.sort((O,Z)=>{let L=q?V(O):0,_=q?V(Z):0;if(L!==_)return _-L;let $=X[O.updateType],G=X[Z.updateType];if($!==G)return G-$;return O.name.localeCompare(Z.name)})}function p(J,Q){let q=M(J.replace(/^[v^~>=<@]+/,"")),X=M(Q.replace(/^[v^~>=<@]+/,""));try{if(Bun.semver.order(X,q)<=0)return"patch"}catch{return"patch"}let O=q.split(".").map((H)=>Number.parseInt(H,10)),Z=X.split(".").map((H)=>Number.parseInt(H,10));while(O.length<3)O.push(0);while(Z.length<3)Z.push(0);let[L,_]=O,[$,G]=Z;if($>L)return"major";if($===L&&G>_)return"minor";return"patch"}function M(J){let Q=J.split(".");if(Q.length>=3||!Q.every((q)=>/^\d+$/.test(q)))return J;while(Q.length<3)Q.push("0");return Q.join(".")}function a(J,Q){try{return Bun.semver.satisfies(J,Q)}catch{return!1}}async function t(J,Q,q){if(!J)throw Error("GitHub token is required");try{let X=await S(`${w()}/repos/${Q}/${q}/pulls?state=open`,{headers:{Authorization:`Bearer ${J}`,Accept:"application/vnd.github+json","User-Agent":"buddy"}});if(!X.ok)throw Error(`GitHub API error: ${X.status} ${X.statusText}`);return(await X.json()).filter((L)=>{if(!L.body)return!1;return/\s*-\s*\[x\]\s*<!--\s*rebase-check\s*-->.*(?:rebase|update)\/retry/i.test(L.body)}).map((L)=>({number:L.number,branchName:L.head.ref}))}catch(X){throw Error(`Failed to check for rebase requests: ${X}`)}}function e(J){let Q=C(J);if(Q)return[...new Set(Q.updates.map((O)=>O.name))];let q=[],X=J.match(/\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|/g);if(X)for(let O of X){let Z=O.match(/\[([^\]]+)\]\([^)]*\)/);if(Z)q.push(Z[1])}return q}async function qq(J,Q,q){if(await b(J,Q,q))return!0;if(await m(J,Q,q))return!0;return!1}async function b(J,Q,q){if(!(Q.packages?.respectLatest??!0))return q.debug(`\uD83D\uDD0D PR #${J.number}: respectLatest is false, skipping auto-close`),!1;let O=["latest","*","main","master","develop","dev"],Z=C(J.body);if(Z){let H=Z.updates.filter((K)=>O.includes(K.current.toLowerCase().trim()));for(let K of H)q.debug(`\uD83D\uDD0D PR #${J.number}: Package ${K.name} has dynamic version "${K.current}"`);return q.debug(`\uD83D\uDD0D PR #${J.number}: Should auto-close: ${H.length>0}`),H.length>0}let L=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`?[v^~>=]*([^`|\s]+)`?\s*(?:->|\u2192)\s*`?[v^~>=]*([^`|\s]+)`?\]?/g,_,$=[];while((_=L.exec(J.body))!==null){let[,H,K]=_,I=K.toLowerCase().trim();if(O.includes(I))$.push(H),q.debug(`\uD83D\uDD0D PR #${J.number}: Package ${H} has dynamic version "${I}"`)}let G=$.length>0;return q.debug(`\uD83D\uDD0D PR #${J.number}: Packages with dynamic versions: ${$.join(", ")}`),q.debug(`\uD83D\uDD0D PR #${J.number}: Should auto-close: ${G}`),G}async function m(J,Q,q){let X=Q.packages?.ignorePaths;if(!X||X.length===0)return q.debug(`\uD83D\uDD0D PR #${J.number}: No ignorePaths configured, skipping auto-close`),!1;let O=P(J.body);if(O.length===0)return q.debug(`\uD83D\uDD0D PR #${J.number}: No file paths found in PR body`),!1;q.debug(`\uD83D\uDD0D PR #${J.number}: Found file paths: ${O.join(", ")}`);let{Glob:Z}=globalThis.Bun,L=O.filter((_)=>{let $=_.replace(/^\.\//,"");return X.some((G)=>{try{return new Z(G).match($)}catch(H){return q.debug(`Failed to match path ${$} against pattern ${G}: ${H}`),!1}})});if(L.length>0)return q.debug(`\uD83D\uDD0D PR #${J.number}: Contains files now in ignorePaths: ${L.join(", ")}`),!0;return q.debug(`\uD83D\uDD0D PR #${J.number}: No files match ignorePaths patterns`),!1}function P(J){let Q=C(J);if(Q)return B(Q);let q=[],X=/\|\s*\[[^\]]+\]\([^)]*\)\s*\|[^|]*\|\s*\*\*([^*]+)\*\*\s*\|/g,O;while((O=X.exec(J))!==null){let $=O[1].trim();if($&&!q.includes($))q.push($)}let Z=/\*\*([^*]+\.(?:json|yaml|yml|lock))\*\*/g;while((O=Z.exec(J))!==null){let $=O[1].trim();if($&&!q.includes($))q.push($)}let L=/\|[^|]+\|[^|]+\|([^|]+)\|[^|]*\|/g;while((O=L.exec(J))!==null){let $=O[1].trim();if($&&($.includes("/")||/\.(?:json|yaml|yml|lock)$/.test($))&&!q.includes($))q.push($)}let _=/(?:^|\s)([\w-]+(?:\/[\w.-]+)*\/[\w.-]+\.(?:json|yaml|yml|lock))(?:\s|$)/gm;while((O=_.exec(J))!==null){let $=O[1].trim();if($&&!q.includes($))q.push($)}return q}
|
|
44
|
+
export{F as bg,u as cg,n as dg,d as eg,o as fg,z as gg,i as hg,s as ig,r as jg,p as kg,a as lg,t as mg,e as ng,qq as og};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Nc as v,Oc as F,Pc as B,Qc as k}from"./chunk-
|
|
2
|
+
import{Nc as v,Oc as F,Pc as B,Qc as k}from"./chunk-s1cgwkkr.js";import{$f as I,_f as y,ag as W}from"./chunk-cj4d5ad7.js";import{xh as T}from"./chunk-2z9pkk1y.js";import{Eh as R}from"./chunk-vpw7adwd.js";import{Jh as U}from"./chunk-b9szrnxw.js";import{Lh as L,Mh as x,Ph as D}from"./chunk-x1w6q9tk.js";import{Buffer as S}from"buffer";import{spawn as w}from"child_process";import j from"process";var g=/\b(?:gh[pousr]_[A-Z0-9_]{20,}|github_pat_[A-Z0-9_]{20,}|[A-Z0-9]{40,})\b/gi;function N(Q){return Q==="completed"||Q==="in_progress"?Q:"queued"}function f(Q){if(typeof Q!=="string")return null;if(Q==="success"||Q==="cancelled")return Q;if(Q==="failure"||Q==="timed_out"||Q==="action_required")return"failure";return"skipped"}function d(Q,X){let Y=Q.replace(g,"[REDACTED]");if(X&&X.length>=8)Y=Y.split(X).join("[REDACTED]");return Y}class P extends Error{constructor(Q){super(Q);this.name="LockfileRegenerationError"}}function h(Q,X){let Y=`http.${Q.replace(/\/+$/,"")}/.extraheader`,Z=S.from(`x-access-token:${X}`).toString("base64");return["-c",`${Y}=`,"-c",`${Y}=AUTHORIZATION: basic ${Z}`]}class E extends Error{constructor(Q){super(Q);this.name="WorkflowPermissionError"}}function l(Q){let X=`${x(Q)} ${Q?.message??""}`;return/refusing to allow (?:a GitHub App|an OAuth App|a Personal Access Token)[^\n]*workflow/i.test(X)}function m(Q){let X=`${x(Q)} ${Q?.message??""}`;return/not permitted to create or approve pull requests/i.test(X)||Q?.status===403&&/pull/i.test(X)}class b{token;owner;repo;hasWorkflowPermissions;workflowToken;apiUrl;cache={pullRequests:new Map,issues:new Map};cacheTTL=120000;logger;constructor(Q,X,Y,Z=!1,$,J,G){this.token=Q;this.owner=X;this.repo=Y;this.hasWorkflowPermissions=Z;this.workflowToken=$;this.apiUrl=J?J.replace(/\/+$/,""):T(),this.logger=G??D()}capabilities(){return{pinIssues:!0,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!0,nativeAutoMerge:!0,commentReactions:!0,ciLogs:!0,ciRuns:!0,reviewThreads:!0,teamReviewers:!0,draftPullRequests:!0,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!0,labels:!0}}isCacheValid(Q){return Date.now()-Q<this.cacheTTL}clearCache(){this.cache.pullRequests.clear(),this.cache.issues.clear()}async branchExists(Q){try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Q}`),!0}catch(X){if(X.message?.includes("404"))return!1;return this.logger.warn(`\u26A0\uFE0F Error checking branch ${Q}: ${x(X)}`),!1}}async createBranch(Q,X){try{let Z=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${X}`)).object.sha;await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/refs`,{ref:`refs/heads/${Q}`,sha:Z}),this.logger.info(`\u2705 Created branch ${Q} from ${X}`)}catch(Y){throw this.logger.error(`\u274C Failed to create branch ${Q}: ${x(Y)}`),Y}}async commitChanges(Q,X,Y,Z="main"){try{await this.commitChangesWithGit(Q,X,Y,Z)}catch($){if($ instanceof P||$ instanceof y)throw $;if(l($)){let J=Y.filter((_)=>!_.path.includes(".github/workflows/")),G=Y.length-J.length;if(J.length===0)throw new E(`The token may not update workflow files (${G} in this change). Grant the GitHub App the Workflows permission, or use a PAT with the workflow scope as BUDDY_TOKEN.`);this.logger.warn(`\u26A0\uFE0F The token may not update workflow files; committing the ${J.length} other file(s) without the ${G} workflow file(s)`),await this.commitChangesWithGit(Q,X,J,Z);return}this.logger.warn(`\u26A0\uFE0F Git CLI commit failed, falling back to GitHub API: ${$}`),await this.commitChangesWithAPI(Q,X,Y,Z)}}async commitChangesWithGit(Q,X,Y,Z="main"){try{let $=Y.filter((V)=>V.path.includes(".github/workflows/")),J=Y.filter((V)=>!V.path.includes(".github/workflows/"));if($.length>0&&!this.hasWorkflowPermissions)if(this.logger.warn(`\u26A0\uFE0F Detected ${$.length} workflow file(s). These require elevated permissions.`),this.logger.warn(`\u26A0\uFE0F Workflow files: ${$.map((V)=>V.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. BUDDY_TOKEN not detected or lacks workflow permissions."),J.length>0)this.logger.info(`\uD83D\uDCDD Committing ${J.length} non-workflow files...`),Y=J;else{this.logger.warn("\u26A0\uFE0F All files are workflow files. No files will be committed in this PR."),this.logger.warn("\uD83D\uDCA1 To update workflow files, ensure BUDDY_TOKEN is set with workflow:write permissions."),this.logger.info('\uD83D\uDCDD Creating empty commit to avoid "No commits between branches" error...');try{await this.runCommand("git",["commit","--allow-empty","-m","Workflow files require elevated permissions - no changes committed"]),this.logger.info("\u2705 Created empty commit for workflow-only PR")}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to create empty commit: ${V}`);try{let C=Bun.file("README.md");if(await C.exists()){let H=`${await C.text()}
|
|
3
3
|
|
|
4
4
|
<!-- Updated by Buddy -->
|
|
5
5
|
`;await Bun.write("README.md",H),await this.runCommand("git",["add","README.md"]),await this.runCommand("git",["commit","-m","Update README for workflow-only PR"]),this.logger.info("\u2705 Created README update for workflow-only PR")}}catch(K){this.logger.error(`\u274C Failed to create any commit: ${K}`)}}return}else if($.length>0)this.logger.info(`\u2705 Including ${$.length} workflow file(s) with elevated permissions`);try{await this.runCommand("git",["config","user.name","github-actions[bot]"]),await this.runCommand("git",["config","user.email","41898282+github-actions[bot]@users.noreply.github.com"]),this.logger.info("\u2705 Git identity configured for github-actions[bot]")}catch(V){this.logger.warn("\u26A0\uFE0F Failed to configure Git identity:",V)}await this.runCommand("git",["fetch","origin"]),this.logger.info(`\uD83D\uDD04 Recreating ${Q} from origin/${Z} (Renovate-style)...`);try{await this.runCommand("git",["checkout",Q])}catch{try{await this.runCommand("git",["checkout","-b",Q,`origin/${Q}`])}catch{await this.runCommand("git",["checkout","-b",Q])}}await this.runCommand("git",["reset","--hard",`origin/${Z}`]),await this.runCommand("git",["clean","-fd"]),this.logger.info(`\u2705 Reset ${Q} to origin/${Z}`),await W(Y,async(V)=>{try{return await this.runCommand("git",["cat-file","-e",`origin/${Z}:${V}`]),!0}catch{return!1}});for(let V of Y){let K=I(V.path);if(j.env.NODE_ENV==="test"||j.env.BUN_ENV==="test"){if(["package.json","bun.lock","bun.lockb","package-lock.json","yarn.lock"].includes(K)&&V.content==='{"name":"x"}'){this.logger.warn(`\u26A0\uFE0F Skipping test file write to ${K} to prevent overwriting project files`);continue}}if(V.type==="delete")try{await this.runCommand("git",["rm",K])}catch{}else await Bun.write(K,V.content),await this.runCommand("git",["add",K])}if(!(j.env.NODE_ENV==="test"||j.env.BUN_ENV==="test")){let V=Y.map((C)=>C.path.replace(/^\.\//,"").replace(/^\/+/,"")),K=B(V);if(K.length>0){this.logger.info(`\uD83D\uDD12 Regenerating lock files for: ${K.join(", ")}`);let C=j.cwd(),M=[];for(let H of K)try{let z=await F(H,C);if(z.success)for(let q of v())try{await this.runCommand("git",["add",q])}catch{}else M.push(`${H}: ${z.message}`)}catch(z){M.push(`${H}: ${z instanceof Error?z.message:String(z)}`)}for(let H of k(V,C))try{let z=await F(H.manager,`${C}/${H.dir}`);if(z.success)await this.runCommand("git",["add",H.lockFile]);else M.push(`${H.dir} (${H.manager}): ${z.message}`)}catch(z){M.push(`${H.dir} (${H.manager}): ${z instanceof Error?z.message:String(z)}`)}if(M.length>0){let H=M.map((z)=>` - ${z}`).join(`
|