@buddysh/buddy 0.11.16 → 0.11.17
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 +15 -0
- package/dist/bin/cli.js +9 -9
- package/dist/{chunk-nzk13c4q.js → chunk-1jgh0ff1.js} +1 -1
- package/dist/{chunk-knhvdm94.js → chunk-67bjaw56.js} +1 -1
- package/dist/{chunk-20ex3fxc.js → chunk-6b0fmw0d.js} +1 -1
- package/dist/{chunk-aann4nkc.js → chunk-6bqs7rtc.js} +1 -1
- package/dist/{chunk-4jgf7sfa.js → chunk-bz5yx7g6.js} +1 -1
- package/dist/chunk-k8sd78td.js +2 -0
- package/dist/{chunk-kpsvwjac.js → chunk-z2gcfvze.js} +2 -2
- package/dist/{chunk-n960rjcr.js → chunk-zj2pt1bx.js} +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/registry/registry-client.d.ts +1 -0
- package/package.json +1 -1
- package/dist/chunk-pa7pav6h.js +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
[Compare changes](https://github.com/stacksjs/buddy/compare/v0.11.16...v0.11.17)
|
|
4
|
+
|
|
5
|
+
## 🐛 Bug Fixes
|
|
6
|
+
|
|
7
|
+
- **dashboard**: respect the configured release line when reporting caps ([f15e09c](https://github.com/stacksjs/buddy/commit/f15e09c)) _(by Chris Breuer <chrisbreuer93@gmail.com>)_
|
|
8
|
+
|
|
9
|
+
## 🔧 Chores
|
|
10
|
+
|
|
11
|
+
- release v0.11.17 ([6a4df8e](https://github.com/stacksjs/buddy/commit/6a4df8e)) _(by Chris <chrisbreuer93@gmail.com>)_
|
|
12
|
+
|
|
13
|
+
## Contributors
|
|
14
|
+
|
|
15
|
+
- _Chris <chrisbreuer93@gmail.com>_
|
|
16
|
+
- _Chris Breuer <chrisbreuer93@gmail.com>_
|
|
17
|
+
|
|
3
18
|
[Compare changes](https://github.com/stacksjs/buddy/compare/v0.11.15...v0.11.16)
|
|
4
19
|
|
|
5
20
|
## 🐛 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-6b0fmw0d.js";import"../chunk-4r03rh93.js";import{ed as m}from"../chunk-z2gcfvze.js";import"../chunk-a8wcn3mh.js";import"../chunk-67bjaw56.js";import"../chunk-mthd2c8m.js";import"../chunk-bnp0r4eh.js";import"../chunk-0f1xye20.js";import"../chunk-hd74jxm2.js";import{ud as g}from"../chunk-s3b3vrsj.js";import"../chunk-6gvx1g6h.js";import{Ed as R1,Md as Y0}from"../chunk-7m3pzkcj.js";import"../chunk-mr2d1zp0.js";import"../chunk-142zh7e5.js";import{qe as z0,re as Q1,se as z1}from"../chunk-743mhx0e.js";import"../chunk-d09qj570.js";import"../chunk-wk175yyw.js";import"../chunk-4wv5s3vr.js";import"../chunk-gvpsbmeg.js";import"../chunk-j46f90n8.js";import"../chunk-7hm46cej.js";import"../chunk-wc2z7krw.js";import"../chunk-1pecmenc.js";import"../chunk-hk4d7rky.js";import"../chunk-24xvskkf.js";import"../chunk-z18bksyr.js";import"../chunk-cj4d5ad7.js";import"../chunk-c63e4ssc.js";import{tg as $0,xg as J0,zg as Q0}from"../chunk-x9vpk4kk.js";import"../chunk-r1jvyhhd.js";import"../chunk-2z9mh5y4.js";import{bh as kZ,ch as X0,dh as j0,eh as G0,fh as K0,gh as U0,hh as f,ih as y,kh as q0,lh as H0,mh as V0,nh as W0,oh as F0,rh as M0,sh as D0,th as O0,uh as L0,vh as W1,wh as T0,xh as w0}from"../chunk-6kd81nf9.js";import"../chunk-nznpzbq4.js";import"../chunk-yh13j2af.js";import{Gh as S1}from"../chunk-6w0n6c07.js";import"../chunk-s0ps33ft.js";import{Oh as r,Ph as D}from"../chunk-wzncz6j5.js";import"../chunk-m3rftash.js";import{el as SZ,gl as M}from"../chunk-16aeend1.js";import e1 from"fs";import V from"process";import{EventEmitter as I0}from"events";import c from"process";import _1 from"process";import T1 from"process";import U1 from"process";import Z1 from"process";import d1 from"tty";import UZ,{stdin as aZ,stdout as rZ}from"process";import g1,{stdin as VZ,stdout as WZ}from"process";import FZ from"readline";import{existsSync as NZ}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 B0(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 H;while(H=J.exec(Z))Q.push(z(H));return Q}function P0(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,H)=>{return H!==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 N0(Z,$,J){let Q=0,z=$.length,Y=Z,H;for(;Q<z;++Q)H=Y[$[Q]],Y=Y[$[Q]]=Q===z-1?J:H!=null?H:!!~$[Q+1].indexOf(".")||!(+$[Q+1]>-1)?{}:[]}function A0(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 x0(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 R0(Z){if(Z instanceof J1)return!0;return!!Z&&typeof Z==="object"&&Z.name==="ClappError"&&typeof Z.message==="string"}function C0(){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 $}},dZ={screen:`${V1}c`};function S0(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:S0(Z,z)})).filter(({distance:z})=>z<=J).sort((z,Y)=>z.distance-Y.distance).slice(0,Q).map(({cmd:z})=>z)}function k0(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 H(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 q=Y[G]||G,U=H(J[q],j);if(J[q]=U,Q[q])for(let K of Q[q])J[K]=U;if(Y[G]&&Q[Y[G]])for(let K of Q[Y[G]])J[K]=U;J[G]=U}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 q=j.indexOf("=");if(q!==-1){let U=K1(j.slice(2,q)),K=j.slice(q+1);X(U,K)}else{let U=j.slice(2);if(U.startsWith("no-")){let W=K1(U.slice(3));X(W,!1);continue}let K=K1(U),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 q=j.slice(1);for(let U=0;U<q.length;U++){let K=q[U],F=Y[K]||K;if(U===q.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 gZ=T1.argv,b0=`${T1.platform}-${T1.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,m1=U1.argv,h0=`${U1.platform}-${U1.arch} node-${U1.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=B0(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)),q=new Map,U=[];for(let W of $)if(W.namespace){if(!q.has(W.namespace))q.set(W.namespace,[]);q.get(W.namespace).push(W)}else U.push(W);let K="";if(U.sort((W,T)=>W.rawName<T.rawName?-1:W.rawName>T.rawName?1:0),U.length>0)K+=U.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 OZ(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 LZ(Z,$){return($.label??String($.value)).toLowerCase().includes(Z.toLowerCase())}function TZ(Z,$){if(!$)return;if(Z)return $;return $[0]}class wZ extends B1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#J="";#Q;#$;get cursor(){return this.#Z}get userInputWithCursor(){if(!this.userInput)return q1.inverse(q1.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}${q1.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??LZ;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=TZ(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=OZ(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 EZ 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 IZ=C0();var x=(Z,$)=>IZ?Z:$,eZ=x("\u25C6","*"),Z$=x("\u25A0","x"),$$=x("\u25B2","x"),J$=x("\u25C7","o"),Q$=x("\u250C","T"),BZ=x("\u2502","|"),z$=x("\u2514","\u2014"),Y$=x("\u25CF",">"),X$=x("\u25CB"," "),j$=x("\u25FB","[\u2022]"),G$=x("\u25FC","[+]"),K$=x("\u25FB","[ ]"),U$=x("\u25AA","\u2022"),q$=x("\u2500","-"),H$=x("\u256E","+"),V$=x("\u251C","+"),W$=x("\u256F","+"),F$=x("\u25CF","\u2022"),M$=x("\u25C6","*"),D$=x("\u25B2","!"),O$=x("\u25A0","x");var L$={light:x("\u2500","-"),heavy:x("\u2501","="),block:x("\u2588","#")};function PZ(){return`${q1.gray(BZ)} `}var T$=PZ();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(NZ(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 N$=new s1;var a=SZ(kZ(),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 OZ(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 LZ(Z,$){return($.label??String($.value)).toLowerCase().includes(Z.toLowerCase())}function TZ(Z,$){if(!$)return;if(Z)return $;return $[0]}class wZ extends B1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#J="";#Q;#$;get cursor(){return this.#Z}get userInputWithCursor(){if(!this.userInput)return q1.inverse(q1.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}${q1.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??LZ;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=TZ(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=OZ(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 EZ 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 IZ=C0();var x=(Z,$)=>IZ?Z:$,eZ=x("\u25C6","*"),Z$=x("\u25A0","x"),$$=x("\u25B2","x"),J$=x("\u25C7","o"),Q$=x("\u250C","T"),BZ=x("\u2502","|"),z$=x("\u2514","\u2014"),Y$=x("\u25CF",">"),X$=x("\u25CB"," "),j$=x("\u25FB","[\u2022]"),G$=x("\u25FC","[+]"),K$=x("\u25FB","[ ]"),U$=x("\u25AA","\u2022"),q$=x("\u2500","-"),H$=x("\u256E","+"),V$=x("\u251C","+"),W$=x("\u256F","+"),F$=x("\u25CF","\u2022"),M$=x("\u25C6","*"),D$=x("\u25B2","!"),O$=x("\u25A0","x");var L$={light:x("\u2500","-"),heavy:x("\u2501","="),block:x("\u2588","#")};function PZ(){return`${q1.gray(BZ)} `}var T$=PZ();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(NZ(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 N$=new s1;var a=SZ(kZ(),1);var P1="0.11.17";var N1=String.raw`^\s*-\s*\[[xX]\]\s*`,xZ=new RegExp(`${N1}<!--\\s*rebase-branch=([^>]*?)\\s*-->`,"gm"),RZ=new RegExp(`${N1}<!--\\s*rebase-all-open-prs\\s*-->`,"m"),CZ=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(xZ)){let Q=J[1].trim();if(Q&&!$.includes(Q))$.push(Q)}return{rebaseBranches:$,rebaseAll:RZ.test(Z),manualRun:CZ.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 z0({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((H)=>H.suggestion);if(Q.length===0)return J.info("No committable suggestions in this review"),0;let z=new Map;for(let H of Q){let X=z.get(H.path);if(X)X.push(H);else z.set(H.path,[H])}let Y=0;for(let[H,X]of z){let G=Bun.file(H);if(!await G.exists()){J.warn(`\u26A0\uFE0F Skipping ${H}: not in the working tree`);continue}let j=await G.text();for(let q of[...X].sort((U,K)=>K.line-U.line)){if(!$){if(!(await a.default({type:"confirm",name:"apply",message:`${H}:${q.line} \u2014 ${q.message}
|
|
42
42
|
${q.suggestion}
|
|
43
43
|
Apply?`,initial:!1})).apply)continue}let U=Y0(j,q.line,q.suggestion);if(U===null){J.warn(`\u26A0\uFE0F Skipping ${H}:${q.line}: the file changed since the review`);continue}j=U,Y++}await Bun.write(H,j)}return Y}async function bZ(Z,$){try{let{PackageScanner:J}=await import("../chunk-5t07s3dv.js"),Q=await new J(V.cwd(),$,Z.packages?.ignorePaths).scanProject(),z=new Map;for(let Y of Q)for(let H of Y.dependencies)if(!z.has(H.name))z.set(H.name,H.currentVersion);return[...z].map(([Y,H])=>({name:Y,declaredVersion:H}))}catch(J){return $.debug(`Could not collect dependency context: ${r(J)}`),[]}}var w=new I1("buddy");w.usage(`[command] [options]
|
|
44
44
|
|
|
@@ -139,23 +139,23 @@ Scan Results:`),$.info(`\uD83D\uDCE6 Total packages: ${X.totalPackages}`),$.info
|
|
|
139
139
|
\u2728 Minor updates (${j.length}):`);for(let U of j)$.info(` ${U.name}: ${U.currentVersion} \u2192 ${U.newVersion}`)}if(q.length>0){$.info(`
|
|
140
140
|
\uD83D\uDD27 Patch updates (${q.length}):`);for(let U of q)$.info(` ${U.name}: ${U.currentVersion} \u2192 ${U.newVersion}`)}if(X.groups.length>0){$.info(`
|
|
141
141
|
\uD83D\uDCCB Update groups (${X.groups.length}):`);for(let U of X.groups)$.info(` ${U.name}: ${U.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?D.verbose():D.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?D.verbose():D.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),H=z(Z.assignees),X=z(Z.labels),G={...Y?{reviewers:Y}:{},...H?{assignees:H}:{},...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}},q=new m(j),U=await q.scanForUpdates();if(U.updates.length===0){$.success("All dependencies are up to date!");return}if(Z.dryRun){$.info("\uD83D\uDD0D Dry run mode - no changes will be made"),$.info(`Would create ${U.groups.length} pull request(s):`);for(let K of U.groups)$.info(` \uD83D\uDCDD ${K.title} (${K.updates.length} updates)`);return}await q.createPullRequests(U),$.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?D.verbose():D.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((O)=>O.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 hZ(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 I=(await new m(Q).scanForUpdates()).updates.filter((R)=>G.some((h)=>h.name===R.name)),B=G.every((R)=>I.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}),q=await j.scanForUpdates();if(q.updates.length===0){J.success("\u2705 All dependencies are now up to date!");return}let U=Q0(q.groups,X.body,G.map((O)=>O.name));if(!U)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((O)=>O.name).join(", ")}`),J.info(`\uD83D\uDCCB Available groups: ${q.groups.map((O)=>`${O.name} (${O.updates.length} packages)`).join(", ")}`),J.info("\uD83D\uDCA1 Close this PR manually and let buddy create new ones with correct grouping"),V.exit(1);let K=await j.generateAllFileUpdates(U.updates);if(K.length===0){J.info(`\u2139\uFE0F No file changes generated for PR #${Y} \u2014 likely a pantry/pkgx-style dep with no JS writer. Skipping commit to avoid an empty force-push.`);let O=X.body||"",L=O.replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");if(L!==O)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,U.title,K,F),J.info(`\u2705 Recreated branch ${X.head} from ${F} with latest changes`);let{PullRequestGenerator:W}=await import("../chunk-q4j2f72t.js"),E=(await new W({verbose:$.verbose}).generateBody(U)).replace(/- \[x\] <!-- rebase-check -->/g,"- [ ] <!-- rebase-check -->");await z.updatePullRequest(Y,{title:U.title,body:E}),J.success("\uD83D\uDD04 PR rebase completed! Updated existing PR in place.")}catch(z){J.error("Rebase failed:",z),V.exit(1)}});async function hZ(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,H,X]=z;J.push({name:Y,currentVersion:H,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?D.verbose():D.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 yZ(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 H=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||H.has(F.head);if(vZ(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"),E=A("bunx",["@buddysh/buddy","rebase",F.number.toString(),"--force"],{stdio:"inherit",cwd:V.cwd()});await new Promise((O,L)=>{E.on("close",(I)=>{if(I===0)X++,O(I);else L(Error(`Rebase failed with code ${I}`))})}),$.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(U){$.warn("\u26A0\uFE0F Could not check for rebase requests:",U)}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(U){$.warn("\u26A0\uFE0F Could not clear dashboard checkboxes:",U)}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 U=new m(J),K=await U.scanForUpdates();if(K.updates.length>0)await U.createPullRequests(K);else $.info("\u2705 No updates found during the requested run")}catch(U){$.error("\u274C Requested update run failed:",U)}}$.info(`
|
|
142
|
-
\u2705 Checking for PRs with satisfied dependencies...`);try{let{Buddy:U}=await import("../chunk-
|
|
143
|
-
\uD83D\uDD0D Checking for obsolete PRs due to removed dependency files...`);try{let{Buddy:U}=await import("../chunk-
|
|
142
|
+
\u2705 Checking for PRs with satisfied dependencies...`);try{let{Buddy:U}=await import("../chunk-6bqs7rtc.js");await new U(J).checkAndCloseSatisfiedPRs(Q,!!Z.dryRun)}catch(U){$.error("\u26A0\uFE0F Could not check for satisfied PRs:",U)}$.info(`
|
|
143
|
+
\uD83D\uDD0D Checking for obsolete PRs due to removed dependency files...`);try{let{Buddy:U}=await import("../chunk-6bqs7rtc.js");await new U(J).checkAndCloseObsoletePRs(Q,!!Z.dryRun)}catch(U){$.error("\u26A0\uFE0F Could not check for obsolete PRs:",U)}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(U){$.warn("\u26A0\uFE0F Could not process auto-merge:",U)}$.info(`
|
|
144
144
|
\uD83E\uDDF9 Running branch cleanup...`),z1(Q,"branchHousekeeping","cleanupStaleBranches","branch cleanup");let q=await Q.cleanupStaleBranches(2,!!Z.dryRun);if(Z.dryRun)$.info(`\uD83D\uDD0D [DRY RUN] Would delete ${q.deleted.length} stale branches`);else $.success(`\uD83C\uDF89 Cleanup complete: ${q.deleted.length} branches deleted, ${q.failed.length} failed`);if(X>0||j>0||q.deleted.length>0)$.success(`
|
|
145
145
|
\uD83C\uDF89 Update-check complete: ${X} PR(s) rebased, ${j} merged, ${q.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 yZ(Z,$,J){try{let Q=await Z.getIssues("open"),z=$.dashboard?.issueNumber;if(z)return Q.find((H)=>H.number===z)??null;let Y=$.dashboard?.title??"Dependency Dashboard";return Q.find((H)=>H.title===Y)??Q.find((H)=>H.title.includes("Dependency Dashboard"))??null}catch(Q){return J.warn("\u26A0\uFE0F Could not load the dependency dashboard:",Q),null}}function vZ(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?D.verbose():D.quiet(),J=await k(Z.config);try{let Q=await d(J,"this command",$),{runFixCi:z}=await import("../chunk-yr6qyeab.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?D.verbose():D.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,H=z.issue??z.pull_request;if(!Y?.body||!H?.number){$.info("\u2139\uFE0F Event carries no comment; nothing to do");return}let{mentionsBot:X,parseCommand:G}=await import("../chunk-p9xksx9p.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 q=await d(J,"this command",$),U=Y.user?.login??"",K=Y.user?.type==="Bot"||U.endsWith("[bot]"),F={login:U,isBot:K,canWrite:!K&&Q1(q,"permissionLookup","hasWriteAccess")?await q.hasWriteAccess(U):!1},W=Boolean(z.pull_request??z.issue?.pull_request);if($.info(`\uD83E\uDD16 Handling \`${j.name}\` from @${U} on #${H.number}`),Z.dryRun){$.info(`\uD83D\uDD0D [DRY RUN] Would run ${j.name} (canWrite: ${F.canWrite})`);return}if(Q1(q,"commentReactions","reactToComment"))await q.reactToComment(Y.id,"eyes");let{createHandlers:T,dispatchCommand:A}=await import("../chunk-p9xksx9p.js"),{runReviewForPR:E}=await import("../chunk-vffz69jj.js"),O=await A({command:j,actor:F,number:H.number,isPullRequest:W,commentId:Y.id,logger:$},T({config:J,provider:q,review:async(L,I)=>await E({config:J,provider:q,prNumber:L,logger:$,...I}),rebase:async(L)=>{let{spawn:I}=await import("child_process");return await new Promise((B,N)=>{I("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:I}=await import("../chunk-yr6qyeab.js");return await I({config:J,provider:q,prNumber:L,analysisOnly:!0,logger:$})},plan:async(L,I,B)=>{let{runPlan:N}=await import("../chunk-y2ntnpdb.js");return await N({config:J,provider:q,number:L,isPullRequest:I,request:B,logger:$})},resolve:async(L)=>{let{resolveBuddyThreads:I}=await import("../chunk-y5fdq7cd.js");return await I({provider:q,prNumber:L,logger:$})},remember:async(L,I)=>{let{addLearning:B,createLearning:N,loadLearnings:b,serializeLearnings:R,DEFAULT_LEARNINGS_FILE:h}=await import("../chunk-8wrbxhs3.js"),v=J.repository?.baseBranch??"main",P=await b((s,p)=>q.getFileContent(s,p),v,h,$),_=N(L,{source:I.isPullRequest?{pr:I.number}:{issue:I.number}}),i=`buddy/learning-${_.id}`;return await q.commitChanges(i,"chore(buddy): record a learning",[{path:h,content:R(B(P,_)),type:"update"}],v),await q.createPullRequest({title:"chore(buddy): record a learning",body:`Recorded from #${I.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(O.reply)await q.createComment(H.number,O.reply);if(Q1(q,"commentReactions","reactToComment"))await q.reactToComment(Y.id,O.handled?"rocket":"confused");$.success(O.handled?`\u2705 Handled \`${j.name}\``:`\u2139\uFE0F Did not run: ${O.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?D.verbose():D.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",H=Y?D.silent():J;try{let{createAiClient:X}=await import("../chunk-8wrbxhs3.js"),G=X(Q,H);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:q}=await import("../chunk-y5fdq7cd.js"),{collectLocalDiff:U,formatReview:K,shouldFail:F}=await import("../chunk-m9qtb4xj.js"),{runAnalyzers:W}=await import("../chunk-pag93kz1.js");if(Z){let B=await d(Q,"reviewing a pull request",H),{reviewPullRequest:N}=await import("../chunk-vffz69jj.js"),{status:b,result:R}=await N({config:Q,provider:B,prNumber:Number.parseInt(Z,10),trigger:$.auto?"automatic":"requested",...$.auto?{skipIfReviewed:!0}:{},logger:H,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";H.info(`\uD83D\uDD0D Reviewing ${N} changes${N==="branch"?` against ${B}`:""}...`),T=await U(N,B)}if(!T.trim()){if(!Y)J.success("\u2705 No changes to review");return}let{parseUnifiedDiff:A}=await import("../chunk-wfg3bp85.js"),E=A(T).files.map((B)=>B.path),O=Q.analysis?.enabled===!1?{findings:[],ran:[],skipped:[]}:await W({files:E,root:V.cwd(),...Q.analysis?.tools?{enabled:Q.analysis.tools}:{},logger:H});if($.light){let B={summary:`Static analysis of ${E.length} changed file(s).`,walkthrough:[],findings:O.findings,effort:1,omittedFiles:O.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 q(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:H}),I={...L,findings:[...O.findings,...L.findings],omittedFiles:[...L.omittedFiles,...O.skipped.map((B)=>`${B.name} (${B.reason})`)]};if(V.stdout.write(K(I,z)),$.fix){let B=await Z0(I.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${B} suggestion(s)`)}if($.failOn&&F(I.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?D.verbose():D.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-
|
|
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(O.reply)await q.createComment(H.number,O.reply);if(Q1(q,"commentReactions","reactToComment"))await q.reactToComment(Y.id,O.handled?"rocket":"confused");$.success(O.handled?`\u2705 Handled \`${j.name}\``:`\u2139\uFE0F Did not run: ${O.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?D.verbose():D.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",H=Y?D.silent():J;try{let{createAiClient:X}=await import("../chunk-8wrbxhs3.js"),G=X(Q,H);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:q}=await import("../chunk-y5fdq7cd.js"),{collectLocalDiff:U,formatReview:K,shouldFail:F}=await import("../chunk-m9qtb4xj.js"),{runAnalyzers:W}=await import("../chunk-pag93kz1.js");if(Z){let B=await d(Q,"reviewing a pull request",H),{reviewPullRequest:N}=await import("../chunk-vffz69jj.js"),{status:b,result:R}=await N({config:Q,provider:B,prNumber:Number.parseInt(Z,10),trigger:$.auto?"automatic":"requested",...$.auto?{skipIfReviewed:!0}:{},logger:H,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";H.info(`\uD83D\uDD0D Reviewing ${N} changes${N==="branch"?` against ${B}`:""}...`),T=await U(N,B)}if(!T.trim()){if(!Y)J.success("\u2705 No changes to review");return}let{parseUnifiedDiff:A}=await import("../chunk-wfg3bp85.js"),E=A(T).files.map((B)=>B.path),O=Q.analysis?.enabled===!1?{findings:[],ran:[],skipped:[]}:await W({files:E,root:V.cwd(),...Q.analysis?.tools?{enabled:Q.analysis.tools}:{},logger:H});if($.light){let B={summary:`Static analysis of ${E.length} changed file(s).`,walkthrough:[],findings:O.findings,effort:1,omittedFiles:O.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 q(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:H}),I={...L,findings:[...O.findings,...L.findings],omittedFiles:[...L.omittedFiles,...O.skipped.map((B)=>`${B.name} (${B.reason})`)]};if(V.stdout.write(K(I,z)),$.fix){let B=await Z0(I.findings,Boolean($.yes),J);J.success(`\uD83D\uDD27 Applied ${B} suggestion(s)`)}if($.failOn&&F(I.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?D.verbose():D.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-zj2pt1bx.js"),J=Z.verbose?D.verbose():D.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 H=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}H.addJob(X),H.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-kthwzc4p.js"),{writeFileSync:J,mkdirSync:Q}=await import("fs"),{resolve:z}=await import("path"),Y=Z.verbose?D.verbose():D.quiet(),H=await k(Z.config);if(H.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={...H,verbose:Z.verbose??H.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},q=0;if(j.daily||j.weekly||j.monthly){let U=$.generateScheduledWorkflows(X);for(let[K,F]of Object.entries(U))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}`),q++}}if(j.comprehensive){let U=$.generateComprehensiveWorkflow(X);J(z(G,"buddy-comprehensive.yml"),U),Y.success("Generated: buddy-comprehensive.yml"),q++}if(j.docker){let U=$.generateDockerWorkflow(X);J(z(G,"buddy-docker.yml"),U),Y.success("Generated: buddy-docker.yml"),q++}if(j.monorepo){let U=$.generateMonorepoWorkflow(X);J(z(G,"buddy-monorepo.yml"),U),Y.success("Generated: buddy-monorepo.yml"),q++}if(X.workflows?.custom?.length)for(let U of X.workflows.custom){let K=$.generateCustomWorkflow(U,X),F=`buddy-${U.name.toLowerCase().replace(/\s+/g,"-")}.yml`;J(z(G,F),K),Y.success(`Generated: ${F}`),q++}if(q===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 ${q} 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(-H).reverse().forEach((G,j)=>{let U=G===Y.latestVersion?"\u2B50":" ";console.log(`${U} ${G}`)}),Y.versions.length>H)console.log(` ... and ${Y.versions.length-H} 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-bz5yx7g6.js"),Q=$.verbose?D.verbose():D.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 H={deps:Object.keys(Y.dependencies||{}).length,devDeps:Object.keys(Y.devDependencies||{}).length,peerDeps:Object.keys(Y.peerDependencies||{}).length};if(console.log(`\uD83D\uDCCA Dependencies: ${H.deps} | Dev: ${H.devDeps} | Peer: ${H.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-bz5yx7g6.js"),Q=$.verbose?D.verbose():D.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 H=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(-H).reverse().forEach((G,j)=>{let U=G===Y.latestVersion?"\u2B50":" ";console.log(`${U} ${G}`)}),Y.versions.length>H)console.log(` ... and ${Y.versions.length-H} 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-bz5yx7g6.js"),Q=$.verbose?D.verbose():D.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-bz5yx7g6.js"),Q=$.verbose?D.verbose():D.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-bz5yx7g6.js"),Q=$.verbose?D.verbose():D.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 H=!$.dev&&!$.peer,X=$.dev||$.all,G=$.peer||$.all;if(H||$.all){let j=Y.dependencies||{},q=Object.keys(j).length;if(console.log(`
|
|
153
153
|
\uD83D\uDCCB Production Dependencies (${q}):`),q>0)Object.entries(j).forEach(([U,K])=>{console.log(` ${U}: ${K}`)});else console.log(" No production dependencies")}if(X){let j=Y.devDependencies||{},q=Object.keys(j).length;if(console.log(`
|
|
154
154
|
\uD83D\uDEE0\uFE0F Dev Dependencies (${q}):`),q>0)Object.entries(j).forEach(([U,K])=>{console.log(` ${U}: ${K}`)});else console.log(" No dev dependencies")}if(G){let j=Y.peerDependencies||{},q=Object.keys(j).length;if(console.log(`
|
|
155
|
-
\uD83E\uDD1D Peer Dependencies (${q}):`),q>0)Object.entries(j).forEach(([U,K])=>{console.log(` ${U}: ${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?D.verbose():D.quiet();try{console.log(`\uD83D\uDCCA Comparing ${Z}: ${$} vs ${J}`);let{RegistryClient:Y}=await import("../chunk-
|
|
155
|
+
\uD83E\uDD1D Peer Dependencies (${q}):`),q>0)Object.entries(j).forEach(([U,K])=>{console.log(` ${U}: ${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?D.verbose():D.quiet();try{console.log(`\uD83D\uDCCA Comparing ${Z}: ${$} vs ${J}`);let{RegistryClient:Y}=await import("../chunk-bz5yx7g6.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-51m5tgwp.js"),q=j($,J);console.log(`
|
|
156
156
|
\uD83D\uDD0D Version Analysis:`),console.log(` From: ${$}`),console.log(` To: ${J}`),console.log(` Type: ${q} update`);let U=G.indexOf($),K=G.indexOf(J);if(U!==-1&&K!==-1){let F=Math.abs(K-U)-1;if(console.log(` Gap: ${F} versions between them`),K>U)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?D.verbose():D.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(H)=>{if(H!==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(H)=>{if(H!==0){console.log("\uD83D\uDCE1 Using npm registry API search...");try{let{RegistryClient:j}=await import("../chunk-bz5yx7g6.js"),U=await new j(V.cwd(),J,void 0).searchPackages(Z,z);if(U.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}U.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 U=JSON.parse(G).slice(0,z);if(U.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}U.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(q){J.error("Failed to parse search results:",q),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?D.verbose():D.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(),H=new Date;H.setDate(H.getDate()-z);let X=Y.filter((j)=>j.lastCommitDate<H);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 q=Math.floor((Date.now()-j.lastCommitDate.getTime())/86400000);$.info(` - ${j.name} (${q} 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?D.verbose():D.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[H,X]=await Promise.all([Q.getBuddyBranches(),Q.getPullRequests("open")]),G=new Set(X.map((K)=>K.head)),j=H;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":""}:
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ed as Z}from"./chunk-
|
|
2
|
+
import{ed as Z}from"./chunk-z2gcfvze.js";import{Ph as _}from"./chunk-wzncz6j5.js";import Y from"process";class L{jobs=new Map;timers=new Map;logger;isRunning=!1;constructor(q=!1){this.logger=q?_.verbose():_.quiet()}addJob(q){this.jobs.set(q.id,q),this.scheduleJob(q),this.logger.info(`Scheduled job '${q.name}' with cron: ${q.schedule.cron}`)}removeJob(q){let C=this.timers.get(q);if(C)clearTimeout(C),this.timers.delete(q);this.jobs.delete(q),this.logger.info(`Removed scheduled job: ${q}`)}start(){if(this.isRunning){this.logger.warn("Scheduler is already running");return}this.isRunning=!0,this.logger.info("\uD83D\uDD52 Buddy Scheduler started");for(let q of this.jobs.values())if(this.scheduleJob(q),q.schedule.runOnStartup)this.logger.info(`Running startup job: ${q.name}`),setImmediate(()=>this.runJob(q));Y.on("SIGINT",()=>this.stop()),Y.on("SIGTERM",()=>this.stop())}stop(){if(!this.isRunning)return;this.isRunning=!1,this.logger.info("\uD83D\uDED1 Stopping Buddy Scheduler...");for(let q of this.timers.values())clearTimeout(q);this.timers.clear(),this.logger.success("\u2705 Buddy Scheduler stopped"),Y.exit(0)}getJobStatus(q){return this.jobs.get(q)}getAllJobs(){return Array.from(this.jobs.values())}scheduleJob(q){let C=this.timers.get(q.id);if(C)clearTimeout(C);let D=this.getNextRunTime(q.schedule.cron,q.schedule.timezone);if(q.nextRun=D||void 0,D){let G=D.getTime()-Date.now(),F=setTimeout(()=>{this.runJob(q),this.scheduleJob(q)},G);this.timers.set(q.id,F),this.logger.debug(`Job '${q.name}' scheduled for ${D.toISOString()}`)}}async runJob(q){if(q.status==="running"){this.logger.warn(`Job '${q.name}' is already running, skipping`);return}q.status="running",q.lastRun=new Date,this.logger.info(`\uD83D\uDE80 Running scheduled job: ${q.name}`);let C=Date.now(),D=q.schedule.maxRuntime||1800000;try{let G=new Promise((Q,U)=>{setTimeout(()=>U(Error("Job timeout")),D)}),F=this.executeJob(q);await Promise.race([F,G]);let J=Date.now()-C;q.status="idle",this.logger.success(`\u2705 Job '${q.name}' completed in ${J}ms`)}catch(G){q.status="error",this.logger.error(`\u274C Job '${q.name}' failed:`,G)}}async executeJob(q){let C=new Z(q.config),D=await C.scanForUpdates();if(D.updates.length===0){this.logger.info("No dependency updates found");return}if(this.logger.info(`Found ${D.updates.length} dependency updates`),q.config.repository&&q.config.pullRequest)await C.createPullRequests(D),this.logger.success(`Created pull requests for ${D.groups.length} update groups`);else this.logger.info("Repository not configured, skipping PR creation")}getNextRunTime(q,C){try{return this.parseCronExpression(q,C)}catch(D){return this.logger.error(`Invalid cron expression '${q}':`,D),null}}parseCronExpression(q,C){let D=q.trim().split(/\s+/);if(D.length!==5)throw Error("Cron expression must have 5 parts: minute hour day month dayOfWeek");let[G,F,J,Q,U]=D,K=new Date,V=C?this.timezoneOffsetMinutes(K,C):0;if(C)this.logger.debug(`Using timezone: ${C} (offset ${V} minutes)`);let X=new Date(K.getTime()+V*60*1000);X.setSeconds(0,0);let $=this.parseCronField(F,0,23),B=this.parseCronField(G,0,59);if($.length>0&&B.length>0){if(X.setHours($[0],B[0],0,0),X.getTime()-V*60*1000<=K.getTime())X.setDate(X.getDate()+1);return new Date(X.getTime()-V*60*1000)}return new Date(K.getTime()+3600000)}timezoneOffsetMinutes(q,C){try{let D=new Date(q.toLocaleString("en-US",{timeZone:C})),G=new Date(q.toLocaleString("en-US"));return Math.round((D.getTime()-G.getTime())/60000)}catch{return this.logger.warn(`\u26A0\uFE0F Unknown timezone "${C}", scheduling in host time instead`),0}}parseCronField(q,C,D){if(q==="*")return Array.from({length:D-C+1},(F,J)=>C+J);if(q.includes(","))return q.split(",").map(Number).filter((F)=>Number.isFinite(F)&&F>=C&&F<=D);if(q.includes("-")){let F=q.split("-").map(Number),J=F[0],Q=F[1];if(F.length!==2||!Number.isFinite(J)||!Number.isFinite(Q)||Q<J)return[];return Array.from({length:Q-J+1},(U,K)=>J+K).filter((U)=>U>=C&&U<=D)}if(q.includes("/")){let[F,J]=q.split("/"),Q=Number(J);if(!Number.isFinite(Q)||Q<=0)return[];if(F==="*")return Array.from({length:D-C+1},(K,V)=>C+V).filter((K,V)=>V%Q===0);let U=Number(F);return Number.isFinite(U)?[U].filter((K)=>K>=C&&K<=D):[]}let G=Number(q);return Number.isFinite(G)&&G>=C&&G<=D?[G]:[]}static createJobFromConfig(q,C="default"){let D={cron:q.schedule?.cron||"0 2 * * 1",timezone:q.schedule?.timezone,runOnStartup:!1,maxRuntime:1800000};return{id:C,name:`Buddy Dependency Updates (${C})`,schedule:D,status:"idle",config:q}}static PRESETS={DAILY:"0 2 * * *",WEEKLY:"0 2 * * 1",WEEKDAYS:"0 2 * * 1-5",TWICE_WEEKLY:"0 2 * * 1,4",MONTHLY:"0 2 1 * *",HOURLY:"0 * * * *",CUSTOM:(q,C,D="*")=>`${q} ${C} * * ${D}`}}
|
|
3
3
|
export{L as Da};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{md as h}from"./chunk-bnp0r4eh.js";import{od as B}from"./chunk-0f1xye20.js";import{kg as E}from"./chunk-c63e4ssc.js";import{Ch as w,Dh as f,zh as y}from"./chunk-yh13j2af.js";import{Lh as A,Mh as V}from"./chunk-s0ps33ft.js";import{gl as v}from"./chunk-16aeend1.js";import{spawn as N}from"child_process";import q from"fs";import F from"path";import T from"process";var P=8;async function M(X,Z,$=8){if(X.length===0)return[];let K=Math.max(1,Math.min($,X.length)),Y=Array.from({length:X.length}),H=0;async function Q(){while(!0){let z=H++;if(z>=X.length)return;Y[z]=await Z(X[z],z)}}return await Promise.all(Array.from({length:K},Q)),Y}function m(X,Z){let $=Math.max(1,Z),K=[];for(let Y=0;Y<X.length;Y+=$)K.push(X.slice(Y,Y+$));return K}class J{entries=new Map;async get(X,Z){let $=this.entries.get(X);if($)return $;let K=Z().catch((Y)=>{throw this.entries.delete(X),Y});return this.entries.set(X,K),K}clear(){this.entries.clear()}get size(){return this.entries.size}}var d=/^[\w.@/*+-]+$/;function C(X,Z){if(!d.test(X))throw new B(`Refusing to pass untrusted ${Z} to bun: ${JSON.stringify(X)}`)}function g(X){let Z={Accept:"application/vnd.github.v3+json","User-Agent":"buddy"},$=X?.repository?.token||T.env.BUDDY_TOKEN||T.env.GITHUB_TOKEN||T.env.GH_TOKEN;if($)Z.Authorization=`Bearer ${$}`;return Z}function R(X){if(typeof X==="string")return X.trim();if(X&&typeof X==="object"&&"version"in X){let Z=X.version;if(typeof Z==="string")return Z.trim()}return""}class k{projectPath;logger;config;concurrency;packumentCache=new J;composerCache=new J;constructor(X,Z,$=void 0,K=P){this.projectPath=X;this.logger=Z;this.config=$;this.concurrency=K}clearCache(){this.packumentCache.clear(),this.composerCache.clear()}async fetchPackument(X){return this.packumentCache.get(X,async()=>{let $=`${w(X,this.config,this.projectPath)}/${encodeURIComponent(X).replace("%40","@")}`;try{let K=await A($,{headers:{"User-Agent":"buddy"},onRetry:({delayMs:Y,reason:H})=>this.logger.debug(`Retrying ${X} in ${Math.round(Y/1000)}s (${H})`)});if(!K.ok)return(K.status===404?this.logger.debug:this.logger.warn).call(this.logger,`No registry data for ${X}: HTTP ${K.status}`),null;return await K.json()}catch(K){return this.logger.warn(`Failed to fetch registry data for ${X}:`,K),null}})}async fetchComposerPackage(X){return this.composerCache.get(X,async()=>{let Z=f(this.config);try{let $=await A(`${Z}/packages/${X}.json`,{headers:{"User-Agent":"buddy"}});if(!$.ok)return null;return await $.json()}catch($){return this.logger.warn(`Failed to get Composer metadata for ${X}:`,$),null}})}shouldRespectVersion(X){if(!(this.config?.packages?.respectLatest??!0))return!1;let $=["latest","*","main","master","develop","dev"],K=X.toLowerCase().trim();return $.includes(K)}async getOutdatedPackages(X){this.logger.info("Checking for outdated packages...");try{let Z=await this.runBunOutdated(X),$=await this.getWorkspaceOutdatedPackages(),K=await this.getPackageJsonOutdated(X),Y=new Map;for(let G of Z)Y.set(G.name,G);for(let G of $)if(!Y.has(G.name))Y.set(G.name,G);for(let G of K)if(!Y.get(G.name))Y.set(G.name,G);let H=[...Y.values()].filter((G)=>{if(this.shouldRespectVersion(G.current))return this.logger.debug(`Skipping ${G.name} - version "${G.current}" should be respected`),!1;return!0}),Q=await M(H,async(G)=>{let[_,I]=await Promise.all([this.getPackageMetadata(G.name),this.findPackageLocation(G.name)]);return{name:G.name,currentVersion:G.current,newVersion:G.latest,updateType:E(G.current,G.latest),dependencyType:"dependencies",file:I||"package.json",metadata:_,releaseNotesUrl:this.getReleaseNotesUrl(G.name,_),changelogUrl:this.getChangelogUrl(G.name,_),homepage:_?.homepage}},this.concurrency),z=F.join(this.projectPath,"composer.json");if(q.existsSync(z))try{let G=await this.getComposerOutdatedPackages();Q.push(...G)}catch(G){this.logger.warn("Failed to check Composer packages:",G)}return this.logger.success(`Found ${Q.length} package updates`),Q}catch(Z){throw this.logger.error("Failed to check for outdated packages:",Z),new B(`Failed to check for outdated packages: ${Z instanceof Error?Z.message:"Unknown error"}`)}}async getUpdatesForPackages(X){let Z=X.join(" ");return this.getOutdatedPackages(Z)}async getUpdatesWithPattern(X){return this.getOutdatedPackages(X)}async getPackageMetadata(X){try{C(X,"package name");let Z=await this.fetchPackument(X);if(!Z)return;let $=Object.keys(Z.versions??{}),K=Z["dist-tags"]?.latest??$[$.length-1]??"",Y=Z.versions?.[K]??{},H=Y.repository??Z.repository,Q=Y.license??Z.license,z=Y.author??Z.author;return{name:Y.name??Z.name??X,description:Y.description??Z.description,repository:typeof H==="string"?H:H?.url,homepage:Y.homepage??Z.homepage,license:typeof Q==="string"?Q:Q?.type,author:typeof z==="string"?z:z?.name,keywords:Y.keywords??Z.keywords,latestVersion:K,versions:$,weeklyDownloads:void 0,dependencies:Y.dependencies,devDependencies:Y.devDependencies,peerDependencies:Y.peerDependencies}}catch(Z){this.logger.warn(`Failed to get metadata for ${X}:`,Z);return}}async packageExists(X){try{return C(X,"package name"),await this.fetchPackument(X)!==null}catch{return!1}}async getLatestVersion(X){try{return await this.getLatestVersionFromNpm(X)}catch{return null}}async getLatestVersionFromNpm(X){let Z=await this.fetchPackument(X);if(!Z)return null;let $=Object.keys(Z.versions??{});if($.length===0)return null;let K=this.config?.packages?.includePrerelease??!1,Y=Z["dist-tags"]?.latest;if(Y&&(K||!this.isPrerelease(Y)))return Y;let H=K?$:$.filter((z)=>!this.isPrerelease(z));if(H.length===0)return null;return[...H].sort((z,G)=>{try{return Bun.semver.order(G,z)}catch{return 0}})[0]||null}isPrerelease(X){return/-(?:alpha|beta|rc|dev|canary|next|experimental|snapshot|nightly)/i.test(X)}async runBunOutdated(X){let Z=[];if(X)for(let $ of X.split(/\s+/).filter(Boolean))C($,"package filter"),Z.push($);try{let $=await this.runCommand("bun",["outdated","--json",...Z]),K=this.parseBunOutdatedJson($);if(K)return K;this.logger.debug("bun outdated --json produced unrecognized output, falling back to table parsing")}catch($){this.logger.debug("bun outdated --json unavailable, falling back to table parsing:",$)}try{let $=await this.runCommand("bun",["outdated",...Z]);return this.parseBunOutdatedOutput($)}catch($){this.logger.error("Failed to run bun outdated:",$);let K=$ instanceof Error?$.message:String($);throw new B(`bun outdated command failed: ${K}`)}}parseBunOutdatedJson(X){let Z=X.trim();if(!Z||!Z.startsWith("[")&&!Z.startsWith("{"))return null;let $;try{$=JSON.parse(Z)}catch{return null}let K=Array.isArray($)?$:Object.entries($).map(([H,Q])=>({name:H,...Q&&typeof Q==="object"?Q:{}})),Y=[];for(let H of K){let Q=typeof H.name==="string"?H.name:void 0,z=R(H.current),G=R(H.latest);if(!Q||!z||!G)continue;let _={name:Q,current:z,update:R(H.update)||G,latest:G},I=typeof H.workspace==="string"?H.workspace:void 0;if(I)_.workspace=I;Y.push(_)}return Y}parseBunOutdatedOutput(X){let Z=[],$=`${String.fromCharCode(27)}[`,Y=X.replace(new RegExp(`${$}[0-9;]*m`,"g"),"").split(`
|
|
2
|
+
import{md as h}from"./chunk-bnp0r4eh.js";import{od as B}from"./chunk-0f1xye20.js";import{kg as E}from"./chunk-c63e4ssc.js";import{Ch as w,Dh as f,zh as y}from"./chunk-yh13j2af.js";import{Lh as A,Mh as V}from"./chunk-s0ps33ft.js";import{gl as v}from"./chunk-16aeend1.js";import{spawn as N}from"child_process";import q from"fs";import F from"path";import T from"process";var P=8;async function M(X,Z,$=8){if(X.length===0)return[];let K=Math.max(1,Math.min($,X.length)),Y=Array.from({length:X.length}),H=0;async function Q(){while(!0){let z=H++;if(z>=X.length)return;Y[z]=await Z(X[z],z)}}return await Promise.all(Array.from({length:K},Q)),Y}function m(X,Z){let $=Math.max(1,Z),K=[];for(let Y=0;Y<X.length;Y+=$)K.push(X.slice(Y,Y+$));return K}class J{entries=new Map;async get(X,Z){let $=this.entries.get(X);if($)return $;let K=Z().catch((Y)=>{throw this.entries.delete(X),Y});return this.entries.set(X,K),K}clear(){this.entries.clear()}get size(){return this.entries.size}}var d=/^[\w.@/*+-]+$/;function C(X,Z){if(!d.test(X))throw new B(`Refusing to pass untrusted ${Z} to bun: ${JSON.stringify(X)}`)}function g(X){let Z={Accept:"application/vnd.github.v3+json","User-Agent":"buddy"},$=X?.repository?.token||T.env.BUDDY_TOKEN||T.env.GITHUB_TOKEN||T.env.GH_TOKEN;if($)Z.Authorization=`Bearer ${$}`;return Z}function R(X){if(typeof X==="string")return X.trim();if(X&&typeof X==="object"&&"version"in X){let Z=X.version;if(typeof Z==="string")return Z.trim()}return""}class k{projectPath;logger;config;concurrency;packumentCache=new J;composerCache=new J;constructor(X,Z,$=void 0,K=P){this.projectPath=X;this.logger=Z;this.config=$;this.concurrency=K}clearCache(){this.packumentCache.clear(),this.composerCache.clear()}async fetchPackument(X){return this.packumentCache.get(X,async()=>{let $=`${w(X,this.config,this.projectPath)}/${encodeURIComponent(X).replace("%40","@")}`;try{let K=await A($,{headers:{"User-Agent":"buddy"},onRetry:({delayMs:Y,reason:H})=>this.logger.debug(`Retrying ${X} in ${Math.round(Y/1000)}s (${H})`)});if(!K.ok)return(K.status===404?this.logger.debug:this.logger.warn).call(this.logger,`No registry data for ${X}: HTTP ${K.status}`),null;return await K.json()}catch(K){return this.logger.warn(`Failed to fetch registry data for ${X}:`,K),null}})}async fetchComposerPackage(X){return this.composerCache.get(X,async()=>{let Z=f(this.config);try{let $=await A(`${Z}/packages/${X}.json`,{headers:{"User-Agent":"buddy"}});if(!$.ok)return null;return await $.json()}catch($){return this.logger.warn(`Failed to get Composer metadata for ${X}:`,$),null}})}shouldRespectVersion(X){if(!(this.config?.packages?.respectLatest??!0))return!1;let $=["latest","*","main","master","develop","dev"],K=X.toLowerCase().trim();return $.includes(K)}async getOutdatedPackages(X){this.logger.info("Checking for outdated packages...");try{let Z=await this.runBunOutdated(X),$=await this.getWorkspaceOutdatedPackages(),K=await this.getPackageJsonOutdated(X),Y=new Map;for(let G of Z)Y.set(G.name,G);for(let G of $)if(!Y.has(G.name))Y.set(G.name,G);for(let G of K)if(!Y.get(G.name))Y.set(G.name,G);let H=[...Y.values()].filter((G)=>{if(this.shouldRespectVersion(G.current))return this.logger.debug(`Skipping ${G.name} - version "${G.current}" should be respected`),!1;return!0}),Q=await M(H,async(G)=>{let[_,I]=await Promise.all([this.getPackageMetadata(G.name),this.findPackageLocation(G.name)]);return{name:G.name,currentVersion:G.current,newVersion:G.latest,updateType:E(G.current,G.latest),dependencyType:"dependencies",file:I||"package.json",metadata:_,releaseNotesUrl:this.getReleaseNotesUrl(G.name,_),changelogUrl:this.getChangelogUrl(G.name,_),homepage:_?.homepage}},this.concurrency),z=F.join(this.projectPath,"composer.json");if(q.existsSync(z))try{let G=await this.getComposerOutdatedPackages();Q.push(...G)}catch(G){this.logger.warn("Failed to check Composer packages:",G)}return this.logger.success(`Found ${Q.length} package updates`),Q}catch(Z){throw this.logger.error("Failed to check for outdated packages:",Z),new B(`Failed to check for outdated packages: ${Z instanceof Error?Z.message:"Unknown error"}`)}}async getUpdatesForPackages(X){let Z=X.join(" ");return this.getOutdatedPackages(Z)}async getUpdatesWithPattern(X){return this.getOutdatedPackages(X)}async getPackageMetadata(X){try{C(X,"package name");let Z=await this.fetchPackument(X);if(!Z)return;let $=Object.keys(Z.versions??{}),K=Z["dist-tags"]?.latest??$[$.length-1]??"",Y=Z.versions?.[K]??{},H=Y.repository??Z.repository,Q=Y.license??Z.license,z=Y.author??Z.author;return{name:Y.name??Z.name??X,description:Y.description??Z.description,repository:typeof H==="string"?H:H?.url,homepage:Y.homepage??Z.homepage,license:typeof Q==="string"?Q:Q?.type,author:typeof z==="string"?z:z?.name,keywords:Y.keywords??Z.keywords,latestVersion:K,versions:$,weeklyDownloads:void 0,dependencies:Y.dependencies,devDependencies:Y.devDependencies,peerDependencies:Y.peerDependencies}}catch(Z){this.logger.warn(`Failed to get metadata for ${X}:`,Z);return}}async packageExists(X){try{return C(X,"package name"),await this.fetchPackument(X)!==null}catch{return!1}}async getLatestVersion(X){try{return await this.getLatestVersionFromNpm(X)}catch{return null}}async getReleaseVersions(X){let Z=await this.getLatestVersion(X);if(!Z)return[];let $=await this.fetchPackument(X),K=this.config?.packages?.includePrerelease??!1;return Object.keys($?.versions??{}).filter((Y)=>(K||!this.isPrerelease(Y))&&Bun.semver.order(Y,Z)<=0)}async getLatestVersionFromNpm(X){let Z=await this.fetchPackument(X);if(!Z)return null;let $=Object.keys(Z.versions??{});if($.length===0)return null;let K=this.config?.packages?.includePrerelease??!1,Y=Z["dist-tags"]?.latest;if(Y&&(K||!this.isPrerelease(Y)))return Y;let H=K?$:$.filter((z)=>!this.isPrerelease(z));if(H.length===0)return null;return[...H].sort((z,G)=>{try{return Bun.semver.order(G,z)}catch{return 0}})[0]||null}isPrerelease(X){return/-(?:alpha|beta|rc|dev|canary|next|experimental|snapshot|nightly)/i.test(X)}async runBunOutdated(X){let Z=[];if(X)for(let $ of X.split(/\s+/).filter(Boolean))C($,"package filter"),Z.push($);try{let $=await this.runCommand("bun",["outdated","--json",...Z]),K=this.parseBunOutdatedJson($);if(K)return K;this.logger.debug("bun outdated --json produced unrecognized output, falling back to table parsing")}catch($){this.logger.debug("bun outdated --json unavailable, falling back to table parsing:",$)}try{let $=await this.runCommand("bun",["outdated",...Z]);return this.parseBunOutdatedOutput($)}catch($){this.logger.error("Failed to run bun outdated:",$);let K=$ instanceof Error?$.message:String($);throw new B(`bun outdated command failed: ${K}`)}}parseBunOutdatedJson(X){let Z=X.trim();if(!Z||!Z.startsWith("[")&&!Z.startsWith("{"))return null;let $;try{$=JSON.parse(Z)}catch{return null}let K=Array.isArray($)?$:Object.entries($).map(([H,Q])=>({name:H,...Q&&typeof Q==="object"?Q:{}})),Y=[];for(let H of K){let Q=typeof H.name==="string"?H.name:void 0,z=R(H.current),G=R(H.latest);if(!Q||!z||!G)continue;let _={name:Q,current:z,update:R(H.update)||G,latest:G},I=typeof H.workspace==="string"?H.workspace:void 0;if(I)_.workspace=I;Y.push(_)}return Y}parseBunOutdatedOutput(X){let Z=[],$=`${String.fromCharCode(27)}[`,Y=X.replace(new RegExp(`${$}[0-9;]*m`,"g"),"").split(`
|
|
3
3
|
`).filter((Q)=>Q.trim()),H=!1;for(let Q of Y){if(Q.includes("Package")&&Q.includes("Current")&&Q.includes("Update")){H=!0;continue}if(!H||!Q.trim())continue;if(Q.match(/^[\u2502\u251C\u2500\u253C\u2524\u2514\u2534\u2518\u250C\u252C\u2510|\-\s]+$/))continue;let z;if(Q.includes("\u2502"))z=Q.split("\u2502").map((G)=>G.trim());else z=Q.split("|").map((G)=>G.trim());if(z.length>=4){let G=z[1]?.trim()||"",_=z[2]?.trim()||"",I=z[3]?.trim()||"",W=z[4]?.trim()||"",L=z.length>=6?z[5]?.trim():void 0;if(G=G.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,""),G&&_&&W&&G!=="Package"){let O={name:G,current:_,update:I,latest:W};if(L&&L!=="Workspace")O.workspace=L;Z.push(O)}}}return Z}async getPackageJsonOutdated(X){try{let Z=F.join(this.projectPath,"package.json");if(!q.existsSync(Z))return[];let $;try{let I=q.readFileSync(Z,"utf-8"),W=JSON.parse(I);if(W===null||typeof W!=="object"||Array.isArray(W))throw new B(`package.json at ${Z} is not a JSON object`);$=W}catch(I){if(I instanceof B)throw I;let W=I instanceof Error?I.message:String(I);throw new B(`Failed to parse ${Z}: ${W}`)}let K=(I)=>{let W=$[I];return W&&typeof W==="object"&&!Array.isArray(W)?W:{}},Y={...K("dependencies"),...K("devDependencies"),...K("peerDependencies")},H=Object.keys(Y),Q=this.config?.packages?.ignore||[],z=this.config?.packages?.excludeMajor??!1,G=(X?H.filter((I)=>X.split(" ").some((W)=>I.includes(W))):H).flatMap((I)=>{if(!Y[I]||Q.includes(I))return[];let W=this.cleanVersionRange(Y[I]);return W?[{packageName:I,cleanVersion:W}]:[]});return(await M(G,async({packageName:I,cleanVersion:W})=>{let L=await this.getLatestVersion(I);if(!L)return null;if(Bun.semver.order(W,L)>=0)return null;if(z&&E(W,L)==="major")return null;return{name:I,current:W,update:L,latest:L}},this.concurrency)).filter((I)=>I!==null)}catch(Z){return this.logger.warn("Failed to check package.json versions:",Z),[]}}cleanVersionRange(X){if(X.startsWith("workspace:"))return null;return X.replace(/^[\^~>=<]/,"").trim()}async runCommand(X,Z){return new Promise(($,K)=>{let Y=N(X,Z,{cwd:this.projectPath,stdio:"pipe"}),H="",Q="";Y.stdout?.on("data",(z)=>{H+=z.toString()}),Y.stderr?.on("data",(z)=>{Q+=z.toString()}),Y.on("close",(z)=>{if(z===0)$(H);else K(Error(`Command failed with code ${z}: ${Q}`))}),Y.on("error",(z)=>{K(z)})})}getReleaseNotesUrl(X,Z){if(!Z?.repository)return;let $=Z.repository.match(/github\.com[/:]([^/]+\/[^/]+)/);if($)return`https://github.com/${$[1].replace(".git","")}/releases`;return}getChangelogUrl(X,Z){if(!Z?.repository)return;let $=Z.repository.match(/github\.com[/:]([^/]+\/[^/]+)/);if($)return`https://github.com/${$[1].replace(".git","")}/blob/main/CHANGELOG.md`;return}async getUpdatesForWorkspace(X){try{C(X,"workspace name");let Z=["outdated","--filter",X],$=await this.runCommand("bun",Z),K=this.parseBunOutdatedOutput($),Y=[];for(let H of K){let Q=E(H.current,H.latest),z=await this.getPackageMetadata(H.name);Y.push({name:H.name,currentVersion:H.current,newVersion:H.latest,updateType:Q,dependencyType:"dependencies",file:`${X}/package.json`,metadata:z,releaseNotesUrl:this.getReleaseNotesUrl(H.name,z),changelogUrl:this.getChangelogUrl(H.name,z),homepage:z?.homepage})}return Y}catch(Z){return this.logger.warn(`Failed to get updates for workspace ${X}:`,Z),[]}}async searchPackages(X,Z=10){try{let $=encodeURIComponent(X),Y=`${w(void 0,this.config,this.projectPath)}/-/v1/search?text=${$}&size=${Z}`,H=await A(Y,{headers:{"User-Agent":"buddy"}});if(!H.ok)throw Error(`HTTP ${H.status}: ${H.statusText}`);return(await H.json()).objects?.map((z)=>({name:z.package.name,version:z.package.version,description:z.package.description,keywords:z.package.keywords}))??[]}catch($){return this.logger.warn("Failed to search packages via registry API:",$),[]}}async getComposerOutdatedPackages(){this.logger.info("Checking for outdated Composer packages...");let X=[];try{this.logger.info("\uD83D\uDD0D Checking Composer availability...");try{let Q=await this.runCommand("composer",["--version"]);this.logger.info("\u2705 Composer version:",Q.split(`
|
|
4
4
|
`)[0])}catch(Q){return this.logger.info("\u274C Composer not available:",Q),this.logger.warn("Composer not found, skipping Composer package updates"),[]}let Z=F.join(this.projectPath,"composer.json");if(this.logger.info(`\uD83D\uDD0D Reading composer.json from: ${Z}`),!q.existsSync(Z))return this.logger.info("\u274C composer.json not found"),[];let $=q.readFileSync(Z,"utf8"),K=JSON.parse($);this.logger.info("\uD83D\uDCE6 composer.json require packages:",Object.keys(K.require||{})),this.logger.info("\uD83D\uDCE6 composer.json require-dev packages:",Object.keys(K["require-dev"]||{})),this.logger.info("\uD83D\uDD0D Running composer outdated (including dev dependencies)...");let Y=await this.runCommand("composer",["outdated","--format=json"]);this.logger.info("\uD83D\uDCCA Raw composer outdated output length:",Y.length);let H;try{H=JSON.parse(Y),this.logger.info(`\uD83D\uDCCB Composer outdated found ${H.installed?.length||0} packages`)}catch(Q){return this.logger.info("\u274C Failed to parse composer outdated JSON:",Q),this.logger.info("Raw output:",Y.substring(0,500)),[]}if(H.installed){this.logger.info("\uD83D\uDD04 Processing outdated packages...");for(let Q of H.installed)if(this.logger.info(`
|
|
5
5
|
\uD83D\uDCE6 Processing package: ${Q.name}`),this.logger.info(` Current version: ${Q.version}`),this.logger.info(` Latest version: ${Q.latest}`),Q.name&&Q.version&&Q.latest){let z=K.require?.[Q.name],G=K["require-dev"]?.[Q.name],_=z||G;if(this.logger.info(` Constraint: ${_||"NOT FOUND"}`),!_){this.logger.info(` \u26A0\uFE0F Skipping ${Q.name} - not found in composer.json`);continue}if((this.config?.packages?.ignore||[]).includes(Q.name)){this.logger.info(` \u26A0\uFE0F Skipping ${Q.name} - in ignore list`);continue}let W="require";if(K["require-dev"]&&K["require-dev"][Q.name])W="require-dev";this.logger.info(` Dependency type: ${W}`);let L=await this.getComposerPackageMetadata(Q.name),O=this.extractConstraintBaseVersion(_);if(this.logger.info(` Constraint base version: ${O}`),!O){this.logger.warn(`\u274C Could not extract base version from constraint "${_}" for ${Q.name}`);continue}let S=O,b=Q.latest;this.logger.info(` Using current version: ${S} (from constraint)`),this.logger.info(` Target latest version: ${b}`);let j=[];try{this.logger.info(` \uD83D\uDD0D Getting available versions for ${Q.name}...`);let x=await this.runCommand("composer",["show",Q.name,"--available","--format=json"]),U=JSON.parse(x);if(U.versions)j=U.versions,this.logger.info(` \uD83D\uDCCB Found ${j.length} available versions`)}catch(x){this.logger.warn(`\u274C Failed to get available versions for ${Q.name}, using latest only:`,x),j=[b]}this.logger.info(" \uD83C\uDFAF Finding best constraint updates...");let D=await this.findBestConstraintUpdates(_,j,S);this.logger.info(` \uD83D\uDCCA Found ${D.length} update candidates`);for(let x of D){let U=E(S,x.version);if(this.logger.info(` \uD83D\uDCC8 Update candidate: ${S} \u2192 ${x.version} (${U})`),(this.config?.packages?.excludeMajor??!1)&&U==="major"){this.logger.info(` \u26A0\uFE0F Skipping major update for ${Q.name} - excludeMajor is true`);continue}this.logger.info(` \u2705 Adding update: ${Q.name} ${S} \u2192 ${x.version}`),X.push({name:Q.name,currentVersion:S,newVersion:x.version,updateType:U,dependencyType:W,file:"composer.json",metadata:L,releaseNotesUrl:this.getComposerReleaseNotesUrl(Q.name,L),changelogUrl:this.getComposerChangelogUrl(Q.name,L),homepage:L?.homepage})}}}return this.logger.info(`\u2705 Final result: Found ${X.length} Composer package updates`),this.logger.success(`Found ${X.length} Composer package updates`),X}catch(Z){return this.logger.warn("Failed to check for outdated Composer packages:",Z),[]}}parseVersion(X){let $=X.replace(/^v/,"").split("-")[0].split("+")[0].split(".").map((K)=>Number.parseInt(K,10));if($.length<2||$.some((K)=>Number.isNaN(K)))return null;return{major:$[0]||0,minor:$[1]||0,patch:$[2]||0}}compareVersions(X,Z){let $=this.parseVersion(X),K=this.parseVersion(Z);if(!$||!K)return 0;if($.major!==K.major)return $.major-K.major;if($.minor!==K.minor)return $.minor-K.minor;return $.patch-K.patch}async getComposerPackageMetadata(X){try{let $=(await this.fetchComposerPackage(X))?.package;if(!$?.versions)return;let K=Object.keys($.versions),Y=K.find((Q)=>!Q.includes("dev")&&!Q.includes("alpha")&&!Q.includes("beta"))??K[0],H=(Y?$.versions[Y]:void 0)??{};return{name:$.name??X,description:H.description,repository:H.source?.url??H.homepage,homepage:H.homepage,license:Array.isArray(H.license)?H.license.join(", "):H.license,author:H.authors?.[0]?.name,keywords:H.keywords,latestVersion:Y,versions:K,weeklyDownloads:$.downloads?.monthly,dependencies:H.require,devDependencies:H["require-dev"]}}catch(Z){this.logger.warn(`Failed to get Composer metadata for ${X}:`,Z);return}}async composerPackageExists(X){try{return await this.fetchComposerPackage(X)!==null}catch{return!1}}async getComposerLatestVersion(X){try{let $=(await this.fetchComposerPackage(X))?.package;if(!$?.versions)return null;let K=Object.keys($.versions),Y=K.filter((Q)=>!Q.includes("dev")&&!Q.includes("alpha")&&!Q.includes("beta")&&!Q.includes("rc"));if(Y.length===0)return K[0]||null;let H=Y.sort((Q,z)=>{try{if(typeof Bun<"u"&&Bun.semver)return Bun.semver.order(Q,z);return Q.localeCompare(z,void 0,{numeric:!0})}catch{return Q.localeCompare(z)}});return H[H.length-1]||null}catch(Z){return this.logger.warn(`Failed to get latest Composer version for ${X}:`,Z),null}}getComposerReleaseNotesUrl(X,Z){if(!Z?.repository)return;let $=Z.repository.match(/github\.com[/:]([^/]+\/[^/]+)/);if($)return`https://github.com/${$[1].replace(".git","")}/releases`;return}getComposerChangelogUrl(X,Z){if(!Z?.repository)return;let $=Z.repository.match(/github\.com[/:]([^/]+\/[^/]+)/);if($)return`https://github.com/${$[1].replace(".git","")}/blob/main/CHANGELOG.md`;return}extractConstraintBaseVersion(X){let Z=X.match(/^[\^~>=<]*([\d.]+)/);if(Z)return Z[1];return null}async findBestConstraintUpdates(X,Z,$){let{getUpdateType:K}=await import("./chunk-51m5tgwp.js"),Y=[],H=this.parseVersion($);if(!H)return[];let Q=null,z=null,G=null;for(let _ of Z){if(_.includes("dev")||_.includes("alpha")||_.includes("beta")||_.includes("RC"))continue;let I=this.parseVersion(_);if(!I)continue;if(this.compareVersions(_,$)<=0)continue;let L=K($,_);if(L==="patch"&&I.major===H.major&&I.minor===H.minor){if(!Q||this.compareVersions(_,Q)>0)Q=_}else if(L==="minor"&&I.major===H.major){if(!z||this.compareVersions(_,z)>0)z=_}else if(L==="major"){if(!G||this.compareVersions(_,G)>0)G=_}}if(Q)Y.push({version:Q,type:"patch"});if(z)Y.push({version:z,type:"minor"});if(G)Y.push({version:G,type:"major"});return Y}async getWorkspaceOutdatedPackages(){try{let X=await this.getWorkspaceNames(),Z=await this.findPackageJsonFiles(),$=[];this.logger.info(`Found ${X.length} workspace packages to check`);for(let K of X)try{let Y=await this.runBunOutdatedForWorkspace(K);$.push(...Y)}catch(Y){this.logger.warn(`Failed to check workspace ${K}:`,Y)}this.logger.info(`Checking ${Z.length} package.json files directly`);for(let K of Z){if(K==="package.json")continue;try{let Y=F.join(this.projectPath,K),H=q.readFileSync(Y,"utf-8"),Q=JSON.parse(H),z={...Q.dependencies,...Q.devDependencies,...Q.peerDependencies,...Q.optionalDependencies};for(let[G,_]of Object.entries(z)){if(typeof _!=="string"||_.startsWith("workspace:"))continue;if($.some((I)=>I.name===G))continue;try{let I=await this.getLatestVersion(G);if(I){let W=this.cleanVersionRange(_);if(W&&Bun.semver.order(W,I)<0)$.push({name:G,current:W,update:I,latest:I,file:K})}}catch{continue}}}catch(Y){this.logger.warn(`Failed to check packages in ${K}:`,Y)}}return this.logger.info(`Found ${$.length} outdated packages across workspaces`),$}catch(X){return this.logger.warn("Failed to check workspace packages:",X),[]}}async getWorkspaceNames(){let X=[],Z=await this.findPackageJsonFiles();for(let $ of Z)try{let K=F.join(this.projectPath,$),Y=q.readFileSync(K,"utf-8"),H=JSON.parse(Y);if(H.name&&$!=="package.json")X.push(H.name)}catch(K){this.logger.warn(`Failed to parse package.json ${$}:`,K)}return X}async findPackageJsonFiles(){let X=[],Z=async($,K="")=>{try{let Y=await q.promises.readdir($);for(let H of Y){let Q=F.join($,H),z=K?F.join(K,H):H,G=await q.promises.lstat(Q);if(G.isDirectory()){if(!this.shouldSkipDirectory(H))await Z(Q,z)}else if(G.isFile()&&H==="package.json")X.push(z)}}catch{}};return await Z(this.projectPath),X}shouldSkipDirectory(X){return h(X)}async findPackageLocation(X){let Z=await this.findPackageJsonFiles();for(let $ of Z)try{let K=F.join(this.projectPath,$),Y=q.readFileSync(K,"utf-8"),H=JSON.parse(Y);if({...H.dependencies,...H.devDependencies,...H.peerDependencies,...H.optionalDependencies}[X])return $}catch{continue}return null}async getPackageVersionReleaseDate(X,Z){try{let K=(await this.fetchPackument(X))?.time?.[Z];if(!K)return null;let Y=new Date(K);return Number.isNaN(Y.getTime())?null:Y}catch($){return this.logger.debug(`Failed to get release date for ${X}@${Z}:`,$),null}}async getGitHubActionReleaseDate(X,Z){try{let[$,K]=X.split("/");if(!$||!K)return null;let Y=`${y(this.config)}/repos/${$}/${K}/releases/tags/${encodeURIComponent(Z)}`,H=await V(Y,{headers:g(this.config)});if(!H?.published_at)return null;let Q=new Date(H.published_at);return Number.isNaN(Q.getTime())?null:Q}catch($){return this.logger.debug(`Failed to get GitHub Action release date for ${X}@${Z}:`,$),null}}async getComposerPackageReleaseDate(X,Z){try{let K=(await this.fetchComposerPackage(X))?.package?.versions?.[Z]?.time;if(!K)return null;let Y=new Date(K);return Number.isNaN(Y.getTime())?null:Y}catch($){return this.logger.debug(`Failed to get Composer package release date for ${X}@${Z}:`,$),null}}async getDockerImageReleaseDate(X,Z){try{return this.logger.debug(`Docker image release date checking not fully implemented for ${X}:${Z}`),null}catch($){return this.logger.debug(`Failed to get Docker image release date for ${X}:${Z}:`,$),null}}async meetsMinimumReleaseAge(X,Z,$,K){let Y=K??this.config?.packages?.minimumReleaseAge??0,H=this.config?.packages?.minimumReleaseAgeExclude??[];if(Y===0)return!0;if(H.includes(X))return this.logger.debug(`Package ${X} is excluded from minimum release age requirement`),!0;let Q=null;switch($){case"github-actions":Q=await this.getGitHubActionReleaseDate(X,Z);break;case"require":case"require-dev":Q=await this.getComposerPackageReleaseDate(X,Z);break;case"docker-image":Q=await this.getDockerImageReleaseDate(X,Z);break;default:Q=await this.getPackageVersionReleaseDate(X,Z);break}if(!Q)return this.logger.warn(`Could not determine release date for ${X}@${Z} (${$||"unknown type"}), allowing update`),!0;let G=(new Date().getTime()-Q.getTime())/60000,_=G>=Y;if(!_)this.logger.info(`Package ${X}@${Z} (${$||"unknown type"}) is too new (${Math.round(G)} minutes old, minimum: ${Y} minutes)`);return _}async runBunOutdatedForWorkspace(X){try{C(X,"workspace name");let Z=await this.runCommand("bun",["outdated","--filter",X]);return this.parseBunOutdatedOutput(Z).map((K)=>({...K,workspace:X}))}catch(Z){return this.logger.warn(`Failed to run bun outdated for workspace ${X}:`,Z),[]}}}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_c as oX}from"./chunk-4r03rh93.js";import{dd as sX}from"./chunk-kpsvwjac.js";import{Rh as iX}from"./chunk-wzncz6j5.js";import{gl as n}from"./chunk-16aeend1.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return UQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
|
|
2
|
+
import{_c as oX}from"./chunk-4r03rh93.js";import{dd as sX}from"./chunk-z2gcfvze.js";import{Rh as iX}from"./chunk-wzncz6j5.js";import{gl as n}from"./chunk-16aeend1.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return UQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
|
|
3
3
|
`);for(let W of z)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:M.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let J=`${H} ${this.environment}.${Q.toUpperCase()}: ${U}
|
|
4
4
|
`;if(G)J+=`${G}
|
|
5
5
|
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!S()){let Y=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:M.blue("\u25D0"),tag:Y,message:`${M.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ed as a}from"./chunk-
|
|
2
|
+
import{ed as a}from"./chunk-z2gcfvze.js";import"./chunk-a8wcn3mh.js";import"./chunk-67bjaw56.js";import"./chunk-mthd2c8m.js";import"./chunk-bnp0r4eh.js";import"./chunk-0f1xye20.js";import"./chunk-hd74jxm2.js";import"./chunk-6gvx1g6h.js";import"./chunk-743mhx0e.js";import"./chunk-d09qj570.js";import"./chunk-wk175yyw.js";import"./chunk-4wv5s3vr.js";import"./chunk-gvpsbmeg.js";import"./chunk-j46f90n8.js";import"./chunk-7hm46cej.js";import"./chunk-wc2z7krw.js";import"./chunk-1pecmenc.js";import"./chunk-hk4d7rky.js";import"./chunk-24xvskkf.js";import"./chunk-z18bksyr.js";import"./chunk-cj4d5ad7.js";import"./chunk-c63e4ssc.js";import"./chunk-x9vpk4kk.js";import"./chunk-r1jvyhhd.js";import"./chunk-2z9mh5y4.js";import"./chunk-yh13j2af.js";import"./chunk-6w0n6c07.js";import"./chunk-s0ps33ft.js";import"./chunk-wzncz6j5.js";import"./chunk-m3rftash.js";import"./chunk-16aeend1.js";export{a as Buddy};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{kd as a}from"./chunk-
|
|
2
|
+
import{kd as a}from"./chunk-67bjaw56.js";import"./chunk-bnp0r4eh.js";import"./chunk-0f1xye20.js";import"./chunk-c63e4ssc.js";import"./chunk-x9vpk4kk.js";import"./chunk-r1jvyhhd.js";import"./chunk-2z9mh5y4.js";import"./chunk-yh13j2af.js";import"./chunk-s0ps33ft.js";import"./chunk-wzncz6j5.js";import"./chunk-m3rftash.js";import"./chunk-16aeend1.js";export{a as RegistryClient};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ib as w}from"./chunk-vckhctmr.js";import"./chunk-16aeend1.js";import{readdir as $}from"fs/promises";import{join as X}from"path";var G=["dependencies","peerDependencies","optionalDependencies"];async function x(V,W,Q,U){let M=await K(Q,U);if(M.length===0)return[];let J=new Map,D=(q,z,H)=>{let Y=J.get(q),Z={by:z,range:H};if(Y)Y.push(Z);else J.set(q,[Z])};for(let q of V)for(let z of q.dependencies)D(z.name,w,z.currentVersion);for(let q of M)for(let[z,H]of Object.entries(q.ranges))D(z,q.name,H);let E=[];for(let q of M){let z=J.get(q.name);if(!z||z.length===0)continue;try{let H=await W.getReleaseVersions(q.name);if(H.length===0)continue;E.push({name:q.name,installed:q.version,available:H,declared:z})}catch(H){U.debug(`Skipping drift analysis for ${q.name}: ${H}`)}}return E}async function K(V,W){let Q=X(V,"node_modules"),U=[],M;try{M=await $(Q)}catch{return W.debug("No node_modules directory, skipping resolution drift analysis"),[]}let J=[];for(let D of M){if(D.startsWith("."))continue;if(D.startsWith("@")){try{let E=await $(X(Q,D));J.push(...E.map((q)=>`${D}/${q}`))}catch{continue}continue}J.push(D)}return await Promise.all(J.map(async(D)=>{try{let E=await Bun.file(X(Q,D,"package.json")).json();if(!E.name||!E.version)return;let q={};for(let z of G)Object.assign(q,E[z]??{});U.push({name:E.name,version:E.version,ranges:q})}catch{}})),U}export{x as collectDriftInputs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{fd as nX}from"./chunk-a8wcn3mh.js";import{hd as TX,id as CX,jd as FX,kd as uX}from"./chunk-
|
|
2
|
+
import{fd as nX}from"./chunk-a8wcn3mh.js";import{hd as TX,id as CX,jd as FX,kd as uX}from"./chunk-67bjaw56.js";import{ld as oX}from"./chunk-mthd2c8m.js";import{rd as jX,sd as JX,td as fX}from"./chunk-hd74jxm2.js";import{wd as lX,zd as cX}from"./chunk-6gvx1g6h.js";import{qe as QX,re as i}from"./chunk-743mhx0e.js";import{rf as gX}from"./chunk-7hm46cej.js";import{uf as u,vf as yX,wf as zX,xf as mX,yf as n}from"./chunk-wc2z7krw.js";import{ig as OX,jg as hX,kg as f}from"./chunk-c63e4ssc.js";import{tg as c,xg as vX,yg as kX}from"./chunk-x9vpk4kk.js";import{Eg as PX}from"./chunk-r1jvyhhd.js";import{Ah as p}from"./chunk-yh13j2af.js";import{Gh as v}from"./chunk-6w0n6c07.js";import{Lh as HX}from"./chunk-s0ps33ft.js";import{Nh as RX,Oh as $X,Ph as UX,Qh as bX}from"./chunk-wzncz6j5.js";import{gl as G}from"./chunk-16aeend1.js";import xX from"fs";import{join as XX}from"path";import m from"process";var sX={critical:"\uD83D\uDD34 Critical",high:"\uD83D\uDFE0 High",moderate:"\uD83D\uDFE1 Moderate",low:"\u26AA Low"};class KX{generateDashboard(X,$={}){let{showOpenPRs:Q=!0,showDetectedDependencies:Y=!0,showDeprecatedDependencies:Z=!0,showVulnerableDependencies:K=!0,includePackageJson:W=!0,includeDependencyFiles:_=!0,includeGitHubActions:z=!0,bodyTemplate:L}=$,O="Dependency Dashboard";if(L)return{title:"Dependency Dashboard",body:this.applyTemplate(L,X)};let H=this.generateDefaultHeader(X);if(K&&X.vulnerableDependencies&&X.vulnerableDependencies.length>0)H+=this.generateVulnerableDependenciesSection(X.vulnerableDependencies);if(Z&&X.deprecatedDependencies&&X.deprecatedDependencies.length>0)H+=this.generateDeprecatedDependenciesSection(X.deprecatedDependencies);if(Q&&X.openPRs.length>0)H+=this.generateOpenPRsSection(X.openPRs);if(X.cappedDependencies&&X.cappedDependencies.length>0)H+=this.generateCappedDependenciesSection(X.cappedDependencies);if(Y)H+=this.generateDetectedDependenciesSection({packageJson:W?X.detectedDependencies.packageJson:[],dependencyFiles:_?X.detectedDependencies.dependencyFiles:[],githubActions:z?X.detectedDependencies.githubActions:[]});return H+=this.generateFooter(),{title:"Dependency Dashboard",body:H}}generateDefaultHeader(X){return`This issue lists Buddy updates and detected dependencies. Read the [Dependency Dashboard](https://buddy.sh/features/dependency-dashboard) docs to learn more.
|
|
3
3
|
|
|
4
4
|
`}sanitizeReferences(X){return X.replace(/(?<![`\w])#(\d+)(?!\d)/g,"`#$1`")}toRelativePrUrl(X,$){try{let Q=new URL(X);if(Q.hostname!=="github.com")return null;let Y=Q.pathname.match(/^\/[^/]+\/[^/]+\/pull\/(\d+)$/);if(!Y||Number(Y[1])!==$)return null;return`../pull/${$}`}catch{return null}}generateCappedDependenciesSection(X){let $=`## Capped dependencies
|
|
5
5
|
|
|
@@ -102,5 +102,5 @@ The following updates have all been created. To force a retry/rebase of any, cli
|
|
|
102
102
|
${Q.map((_)=>`- \`${_}\``).join(`
|
|
103
103
|
`)}
|
|
104
104
|
|
|
105
|
-
`;return W+="If this was closed in error, please reopen the PR and update the dependency files accordingly.",W}async createOrUpdateDashboard(){try{if(this.logger.info("Creating or updating dependency dashboard..."),!this.config.repository)throw Error("Repository configuration is required for dashboard");if(this.config.repository.provider!=="github")throw Error("Dashboard is currently only supported for GitHub repositories");if(!this.config.repository.owner||!this.config.repository.name)throw Error("Repository owner and name are required for dashboard. Set them in buddy.config.ts or ensure GITHUB_REPOSITORY env var is available.");let X=await QX({provider:this.config.repository.provider,owner:this.config.repository.owner,name:this.config.repository.name,...this.config.repository.token?{token:this.config.repository.token}:{},...this.config.repository.apiUrl?{apiUrl:this.config.repository.apiUrl}:{}},{logger:this.logger}),$=await this.collectDashboardData(X),Q=this.config.dashboard||{},{title:Y,body:Z}=this.dashboardGenerator.generateDashboard($,{showOpenPRs:Q.showOpenPRs??!0,showDetectedDependencies:Q.showDetectedDependencies??!0,showDeprecatedDependencies:Q.showDeprecatedDependencies??!0,includePackageJson:Q.includePackageJson??!0,includeDependencyFiles:Q.includeDependencyFiles??!0,includeGitHubActions:Q.includeGitHubActions??!0,bodyTemplate:Q.bodyTemplate}),K={title:Q.title||Y,body:Z,labels:Q.labels||["dependencies","dashboard"],assignees:Q.assignees},W=await this.findExistingDashboard(X,Q.issueNumber),_=null;if(W){if(this.logger.info(`Updating existing dashboard issue #${W.number}`),_=await this.updateDashboardIssue(X,W.number,K),_)this.logger.success(`\u2705 Successfully updated dashboard issue #${_.number}`)}if(!_){this.logger.info("Creating new dashboard issue"),this.logger.info("Performing final check for existing dashboards before creation...");let z=await this.findExistingDashboard(X,Q.issueNumber);if(z&&z.number!==W?.number){if(this.logger.info(`Race condition detected! Found existing dashboard #${z.number} during final check`),_=await this.updateDashboardIssue(X,z.number,K),_)this.logger.success(`\u2705 Updated existing dashboard issue #${_.number} (race condition avoided)`)}if(!_)_=await X.createIssue(K),this.logger.success(`\u2705 Successfully created new dashboard issue #${_.number}`)}if(Q.pin!==void 0)if(!Q.pin)await X.unpinIssue(_.number);else if(i(X,"pinIssues","pinIssue"))await X.pinIssue(_.number);else this.logger.debug("\uD83D\uDCCC Provider does not support pinning issues; leaving the dashboard unpinned");return this.logger.success(`\u2705 Dashboard updated: ${_.url}`),await this.events.emit("dashboard.updated",{number:_.number,url:_.url}),_}catch(X){throw this.logger.error("Failed to create or update dashboard:",X),X}}async collectDashboardData(X){let[$,Q]=await Promise.all([this.scanner.scanProject(),X.getPullRequests("open")]),Y=Q.filter((H)=>H.labels.includes("dependencies")||H.labels.includes("dependency")||H.labels.includes("deps")||H.title.toLowerCase().includes("update")||H.title.toLowerCase().includes("chore(deps)")||H.title.toLowerCase().includes("bump")||H.title.toLowerCase().includes("upgrade")||H.title.toLowerCase().includes("renovate")||H.head.includes("renovate/")||H.head.includes("dependabot/")||H.head.includes("buddy/")||v(H.head)||H.head.includes("update-")||H.head.includes("bump-")),Z=$.filter((H)=>H.type==="package.json"),K=$.filter((H)=>H.path.includes(".github/workflows/")&&(H.path.endsWith(".yml")||H.path.endsWith(".yaml"))),W=$.filter((H)=>!H.path.includes(".github/workflows/")&&H.type!=="package.json"),z=await new nX().checkDeprecatedDependencies($),L=await this.findVulnerableDependencies($),O=await this.findCappedDependencies($);return{openPRs:Y,detectedDependencies:{packageJson:Z,dependencyFiles:W,githubActions:K},deprecatedDependencies:z,vulnerableDependencies:L,cappedDependencies:O,repository:{owner:this.config.repository.owner,name:this.config.repository.name,provider:this.config.repository.provider},lastUpdated:new Date}}async findCappedDependencies(X){if(this.config.packages?.detectResolutionDrift===!1)return[];try{let{collectDriftInputs:$}=await import("./chunk-
|
|
105
|
+
`;return W+="If this was closed in error, please reopen the PR and update the dependency files accordingly.",W}async createOrUpdateDashboard(){try{if(this.logger.info("Creating or updating dependency dashboard..."),!this.config.repository)throw Error("Repository configuration is required for dashboard");if(this.config.repository.provider!=="github")throw Error("Dashboard is currently only supported for GitHub repositories");if(!this.config.repository.owner||!this.config.repository.name)throw Error("Repository owner and name are required for dashboard. Set them in buddy.config.ts or ensure GITHUB_REPOSITORY env var is available.");let X=await QX({provider:this.config.repository.provider,owner:this.config.repository.owner,name:this.config.repository.name,...this.config.repository.token?{token:this.config.repository.token}:{},...this.config.repository.apiUrl?{apiUrl:this.config.repository.apiUrl}:{}},{logger:this.logger}),$=await this.collectDashboardData(X),Q=this.config.dashboard||{},{title:Y,body:Z}=this.dashboardGenerator.generateDashboard($,{showOpenPRs:Q.showOpenPRs??!0,showDetectedDependencies:Q.showDetectedDependencies??!0,showDeprecatedDependencies:Q.showDeprecatedDependencies??!0,includePackageJson:Q.includePackageJson??!0,includeDependencyFiles:Q.includeDependencyFiles??!0,includeGitHubActions:Q.includeGitHubActions??!0,bodyTemplate:Q.bodyTemplate}),K={title:Q.title||Y,body:Z,labels:Q.labels||["dependencies","dashboard"],assignees:Q.assignees},W=await this.findExistingDashboard(X,Q.issueNumber),_=null;if(W){if(this.logger.info(`Updating existing dashboard issue #${W.number}`),_=await this.updateDashboardIssue(X,W.number,K),_)this.logger.success(`\u2705 Successfully updated dashboard issue #${_.number}`)}if(!_){this.logger.info("Creating new dashboard issue"),this.logger.info("Performing final check for existing dashboards before creation...");let z=await this.findExistingDashboard(X,Q.issueNumber);if(z&&z.number!==W?.number){if(this.logger.info(`Race condition detected! Found existing dashboard #${z.number} during final check`),_=await this.updateDashboardIssue(X,z.number,K),_)this.logger.success(`\u2705 Updated existing dashboard issue #${_.number} (race condition avoided)`)}if(!_)_=await X.createIssue(K),this.logger.success(`\u2705 Successfully created new dashboard issue #${_.number}`)}if(Q.pin!==void 0)if(!Q.pin)await X.unpinIssue(_.number);else if(i(X,"pinIssues","pinIssue"))await X.pinIssue(_.number);else this.logger.debug("\uD83D\uDCCC Provider does not support pinning issues; leaving the dashboard unpinned");return this.logger.success(`\u2705 Dashboard updated: ${_.url}`),await this.events.emit("dashboard.updated",{number:_.number,url:_.url}),_}catch(X){throw this.logger.error("Failed to create or update dashboard:",X),X}}async collectDashboardData(X){let[$,Q]=await Promise.all([this.scanner.scanProject(),X.getPullRequests("open")]),Y=Q.filter((H)=>H.labels.includes("dependencies")||H.labels.includes("dependency")||H.labels.includes("deps")||H.title.toLowerCase().includes("update")||H.title.toLowerCase().includes("chore(deps)")||H.title.toLowerCase().includes("bump")||H.title.toLowerCase().includes("upgrade")||H.title.toLowerCase().includes("renovate")||H.head.includes("renovate/")||H.head.includes("dependabot/")||H.head.includes("buddy/")||v(H.head)||H.head.includes("update-")||H.head.includes("bump-")),Z=$.filter((H)=>H.type==="package.json"),K=$.filter((H)=>H.path.includes(".github/workflows/")&&(H.path.endsWith(".yml")||H.path.endsWith(".yaml"))),W=$.filter((H)=>!H.path.includes(".github/workflows/")&&H.type!=="package.json"),z=await new nX().checkDeprecatedDependencies($),L=await this.findVulnerableDependencies($),O=await this.findCappedDependencies($);return{openPRs:Y,detectedDependencies:{packageJson:Z,dependencyFiles:W,githubActions:K},deprecatedDependencies:z,vulnerableDependencies:L,cappedDependencies:O,repository:{owner:this.config.repository.owner,name:this.config.repository.name,provider:this.config.repository.provider},lastUpdated:new Date}}async findCappedDependencies(X){if(this.config.packages?.detectResolutionDrift===!1)return[];try{let{collectDriftInputs:$}=await import("./chunk-k8sd78td.js"),{findDrift:Q}=await import("./chunk-tsd9jw07.js"),Y=await $(X,this.registryClient,this.projectPath,this.logger),Z=Q(Y).filter((K)=>K.kind==="capped");if(Z.length>0)this.logger.info(`\uD83D\uDD17 ${Z.length} package(s) capped by a dependant's range`);return Z}catch($){return this.logger.warn("Resolution drift analysis failed, continuing without it:",$),[]}}async findVulnerableDependencies(X){if(this.config.security?.enabled===!1)return[];let $=[],Q=new Map;for(let Y of X)for(let Z of Y.dependencies){let K=_X(Z.type);if(!K)continue;let W=Z.currentVersion.replace(/^[\^~>=<\s]*v?/,"").trim();if(!W)continue;let _={name:Z.name,version:W,ecosystem:K},z=a(_);if(Q.has(z))continue;Q.set(z,{name:Z.name,currentVersion:Z.currentVersion,ecosystem:K,file:Y.path}),$.push(_)}if($.length===0)return[];try{let Z=await new e(this.logger).findAdvisories($),K=this.config.security?.minimumSeverity??"low",W={low:0,moderate:1,high:2,critical:3},_=[];for(let[z,L]of Z){let O=Q.get(z);if(!O)continue;let H=L.filter((J)=>W[J.severity]>=W[K]);if(H.length>0)_.push({...O,advisories:H})}return _.sort((z,L)=>W[L.advisories[0].severity]-W[z.advisories[0].severity]),_}catch(Y){return this.logger.warn("Vulnerability check failed, dashboard will omit it:",Y),[]}}async updateDashboardIssue(X,$,Q){try{return await X.updateIssue($,Q)}catch(Y){if(Y instanceof RX&&Y.isNotFound)return this.logger.warn(`Dashboard issue #${$} no longer exists in ${Y.repository} (${Y.status}); creating a replacement dashboard instead.`),null;throw Y}}async findExistingDashboard(X,$){try{if(this.logger.info("Searching for existing dashboard issue..."),$){this.logger.info(`Looking for specific dashboard issue #${$}`);let _=(await X.getIssues("open")).find((z)=>z.number===$);if(_)return this.logger.info(`Found specified dashboard issue #${_.number}: ${_.title}`),_;else return this.logger.warn(`Specified dashboard issue #${$} not found`),null}let Q=await X.getIssues("open");this.logger.info(`Found ${Q.length} open issues to search through`);for(let W of Q){let _=W.labels.includes("dashboard")&&W.labels.includes("dependencies"),z=W.title.toLowerCase().includes("dependency dashboard"),L=W.body.includes("This issue lists Buddy updates and detected dependencies");if(L||_&&z)return this.logger.info(`Found existing dashboard issue #${W.number}: ${W.title}`),this.logger.info(` - Labels: ${W.labels.join(", ")}`),this.logger.info(` - Title matches: ${z}`),this.logger.info(` - Body has marker: ${L}`),W}let Y=Q.filter((W)=>W.labels.includes("dashboard")),Z=Q.filter((W)=>W.labels.includes("dependencies")),K=Q.filter((W)=>W.title.toLowerCase().includes("dependency dashboard"));if(this.logger.info("Dashboard search results:"),this.logger.info(` - Issues with 'dashboard' label: ${Y.length}`),this.logger.info(` - Issues with 'dependencies' label: ${Z.length}`),this.logger.info(` - Issues with 'dependency dashboard' in title: ${K.length}`),Y.length>0){this.logger.info("Issues with 'dashboard' label:");for(let W of Y)this.logger.info(` - #${W.number}: ${W.title} (labels: ${W.labels.join(", ")})`)}return this.logger.info("No existing dashboard issue found"),null}catch(Q){throw this.logger.error(`Failed to search for existing dashboard: ${Q}`),Q}}}
|
|
106
106
|
export{_X as $c,eX as ad,e as bd,a as cd,NX as dd,WX as ed};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Da as a}from"./chunk-
|
|
2
|
+
import{Da as a}from"./chunk-1jgh0ff1.js";import"./chunk-z2gcfvze.js";import"./chunk-a8wcn3mh.js";import"./chunk-67bjaw56.js";import"./chunk-mthd2c8m.js";import"./chunk-bnp0r4eh.js";import"./chunk-0f1xye20.js";import"./chunk-hd74jxm2.js";import"./chunk-6gvx1g6h.js";import"./chunk-743mhx0e.js";import"./chunk-d09qj570.js";import"./chunk-wk175yyw.js";import"./chunk-4wv5s3vr.js";import"./chunk-gvpsbmeg.js";import"./chunk-j46f90n8.js";import"./chunk-7hm46cej.js";import"./chunk-wc2z7krw.js";import"./chunk-1pecmenc.js";import"./chunk-hk4d7rky.js";import"./chunk-24xvskkf.js";import"./chunk-z18bksyr.js";import"./chunk-cj4d5ad7.js";import"./chunk-c63e4ssc.js";import"./chunk-x9vpk4kk.js";import"./chunk-r1jvyhhd.js";import"./chunk-2z9mh5y4.js";import"./chunk-yh13j2af.js";import"./chunk-6w0n6c07.js";import"./chunk-s0ps33ft.js";import"./chunk-wzncz6j5.js";import"./chunk-m3rftash.js";import"./chunk-16aeend1.js";export{a as Scheduler};
|
package/dist/src/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{I as wo,J as So,K as ho,L as uo,M as co,N as Vo,O as eo,P as go,Q as ro,R as vo,S as io,T as so,U as no}from"../chunk-ewhvahnb.js";import{W as ko,X as qo}from"../chunk-bafzw99p.js";import{$ as Wo,Y as Jo,Z as Ko,_ as Qo}from"../chunk-whtdmv3p.js";import{aa as PR,ba as aR,ca as lR,da as yR,ea as CR,fa as NR,ga as _R,ha as zR,ia as DR,ja as TR}from"../chunk-69qyr9ef.js";import{ka as pR,la as oR,ma as mR,na as xR,oa as fR,pa as dR,qa as RR,ra as MR,sa as UR,ta as AR,ua as GR,va as ER,wa as OR}from"../chunk-psjrcpgb.js";import{Aa as $o,Ba as bo,Ca as to,xa as Xo,ya as Yo,za as Zo}from"../chunk-1a14rx5n.js";import"../chunk-rb1fh9vd.js";import{Da as pm}from"../chunk-nzk13c4q.js";import{Ea as ed,Fa as gd,Ga as rd,Ha as vd,Ia as id,Ja as sd,Ka as nd}from"../chunk-9chq5m4p.js";import{La as Zd,Ma as $d,Na as bd,Oa as td,Pa as wd,Qa as Sd,Ra as hd,Sa as ud,Ta as cd,Ua as Vd}from"../chunk-fsghqtgf.js";import{Va as Yf,Wa as Zf}from"../chunk-her5azyp.js";import{$a as Sf,Xa as $f,Ya as bf,Za as tf,_a as wf,ab as hf,bb as uf,cb as cf,db as Vf,eb as ef,fb as gf,gb as rf}from"../chunk-jqh7vx2n.js";import{hb as vf,ib as sf,jb as nf,kb as pd,lb as od}from"../chunk-gg1ddvnf.js";import{mb as Id}from"../chunk-byqzhgzs.js";import{Ab as Td,Bb as jd,Cb as Ld,Db as Bd,nb as dd,ob as Rd,pb as Md,qb as Ud,rb as Ad,sb as Gd,tb as Ed,ub as Od,vb as Pd,wb as Nd,xb as _d,yb as zd,zb as Dd}from"../chunk-4dz5x4xw.js";import{Eb as md,Fb as xd,Gb as fd}from"../chunk-q2tjkhez.js";import{Hb as Co,Ib as No,Jb as _o,Kb as zo}from"../chunk-vckhctmr.js";import{Lb as ad,Mb as ld,Nb as yd,Pb as Cd}from"../chunk-5yfaptmp.js";import{Qb as Rf,Rb as Mf,Sb as Uf,Tb as Af,Ub as Gf,Vb as Ef,Wb as Of,Xb as Pf,Yb as af}from"../chunk-vs61069x.js";import{$b as nx,Zb as ix,_b as sx,ac as pf,bc as of,cc as mf,dc as xf,ec as ff,fc as df}from"../chunk-wfwrm4k3.js";import{gc as Vp,hc as ep,ic as gp,jc as rp,mc as vp,nc as ip}from"../chunk-1g43mpqn.js";import{Ac as Uo,Bc as Ao,Cc as Go,Dc as Eo,Ec as Oo,Fc as Po,Gc as ao,Hc as lo,Ic as yo,pc as sp,sc as np,tc as po,uc as oo,vc as mo,wc as xo,xc as fo,yc as Ro,zc as Mo}from"../chunk-mtn4angk.js";import{Mc as dp}from"../chunk-4chtv4nh.js";import{Nc as mp,Oc as xp,Pc as fp}from"../chunk-j57716xw.js";import{Uc as mm,Vc as xm,Wc as fm,Xc as dm}from"../chunk-20ex3fxc.js";import{Yc as Bo,Zc as Fo,_c as Ho}from"../chunk-4r03rh93.js";import{$c as Sp,ad as hp,bd as up,cd as cp,ed as Do}from"../chunk-kpsvwjac.js";import"../chunk-a8wcn3mh.js";import{gd as _p,hd as zp,id as Dp,jd as Tp,kd as jp}from"../chunk-knhvdm94.js";import{ld as wp}from"../chunk-mthd2c8m.js";import"../chunk-bnp0r4eh.js";import{nd as ex,od as gx,pd as rx,qd as vx}from"../chunk-0f1xye20.js";import{td as Np}from"../chunk-hd74jxm2.js";import{ud as Xf}from"../chunk-s3b3vrsj.js";import{Ad as hx,Bd as ux,Cd as cx,Dd as Vx,vd as $x,wd as bx,xd as tx,yd as wx,zd as Sx}from"../chunk-6gvx1g6h.js";import{Ed as Fd,Fd as Hd,Gd as kd,Hd as qd,Id as Jd,Jd as Kd,Kd as Qd,Ld as Wd,Md as Xd,Nd as Yd}from"../chunk-7m3pzkcj.js";import{$d as Hf,Od as lf,Pd as yf,Qd as Cf,Rd as Nf,Sd as _f,Td as zf,Ud as Df,Vd as Tf,Wd as jf,Xd as If,Yd as Lf,Zd as Bf,_d as Ff,ae as kf,be as qf,ce as Jf,de as Kf,ee as Qf,fe as Wf}from"../chunk-mr2d1zp0.js";import"../chunk-142zh7e5.js";import{ie as Rp,je as Mp,ke as Up,le as Ap,me as Gp,ne as Ep,oe as Op,pe as Pp,qe as ap,re as lp,se as yp}from"../chunk-743mhx0e.js";import"../chunk-d09qj570.js";import"../chunk-wk175yyw.js";import{Fe as Ip,Ge as Lp,He as Bp,Ie as Fp,Je as Hp,Ke as kp,Le as qp,Me as Jp,Ne as Kp,Oe as Qp,Pe as Wp}from"../chunk-4wv5s3vr.js";import{We as Cp}from"../chunk-gvpsbmeg.js";import{$e as bp,Xe as Xp,Ye as Yp,Ze as Zp,_e as $p,af as tp}from"../chunk-j46f90n8.js";import{df as a,ef as l,ff as y,gf as C,hf as N,if as _,jf as z,kf as D,lf as T,mf as j,nf as I,of as L,pf as B,qf as F,rf as H}from"../chunk-7hm46cej.js";import{sf as U,tf as A,uf as G,vf as E,wf as O,yf as P}from"../chunk-wc2z7krw.js";import{Af as ax,Bf as lx,Cf as yx,Df as Cx,Ef as Nx,zf as Px}from"../chunk-1pecmenc.js";import{Ff as Lx,Gf as Bx,Hf as Fx,If as Hx,Jf as kx,Kf as qx,Lf as Jx,Mf as Kx,Nf as Qx,Of as Wx,Pf as Xx,Qf as Yx,Rf as Zx}from"../chunk-hk4d7rky.js";import"../chunk-24xvskkf.js";import{Uf as _x,Vf as zx,Wf as Dx,Xf as Tx,Yf as jx,Zf as Ix}from"../chunk-z18bksyr.js";import"../chunk-cj4d5ad7.js";import{bg as e,cg as g,dg as r,eg as v,fg as i,gg as s,hg as n,ig as pp,jg as op,kg as d}from"../chunk-c63e4ssc.js";import"../chunk-x9vpk4kk.js";import"../chunk-r1jvyhhd.js";import"../chunk-2z9mh5y4.js";import{$g as Io,Zg as To,_g as jo,ah as Lo,ch as jR,dh as IR,eh as LR,fh as BR,gh as FR,hh as HR,ih as kR,jh as qR,kh as JR,lh as KR,mh as QR,nh as WR,oh as XR,ph as YR,qh as ZR,rh as $R,sh as bR,th as tR,uh as wR,vh as SR,wh as hR,xh as uR}from"../chunk-6kd81nf9.js";import{yh as om}from"../chunk-nznpzbq4.js";import{Ah as h,Bh as u,Ch as c,Dh as V,zh as S}from"../chunk-yh13j2af.js";import{Eh as t}from"../chunk-r7qa2ykf.js";import{Fh as w}from"../chunk-gq9gkyah.js";import"../chunk-6w0n6c07.js";import{Hh as J,Ih as K,Jh as Q,Kh as W,Lh as X,Mh as Y}from"../chunk-s0ps33ft.js";import{Nh as k,Oh as q,Ph as Z,Qh as $,Rh as b}from"../chunk-wzncz6j5.js";import"../chunk-m3rftash.js";import"../chunk-16aeend1.js";var{semver:m}=globalThis.Bun;class R{static compareVersions(p,o){return m.order(p,o)}static satisfiesRange(p,o){return m.satisfies(p,o)}static getLatestInRange(p,o){let f=p.filter((x)=>m.satisfies(x,o));if(f.length===0)return null;return f.sort((x,M)=>m.order(M,x))[0]}static createRange(p){return{raw:p,range:p.replace(/^[\^~>=<]+/,""),isExact:!/^[\^~>=<]/.test(p),satisfies:(o)=>this.satisfiesRange(o,p),getLatest:(o)=>this.getLatestInRange(o,p)}}static getUpdateType(p,o){return d(p,o)}static isSafeUpdate(p,o){return m.satisfies(o,p)}}export{Fx as writeFileTool,Yx as wrapUntrusted,gf as withTouchOffer,no as withNarrative,sf as verifyChanges,tR as validateWorkflowGeneration,wR as validateRepositoryAccess,Ud as validateFindings,Bo as validateConfig,Jo as validateAgainstSchema,HR as updateProgress,bf as unitTestsTouch,Sp as toOsvEcosystem,Hp as tagUpdateType,Kf as syntaxAnalyzer,lp as supports,z as summarizeUsage,fR as summarizeGates,lo as stripOperators,bd as stripNonCommandContext,nf as stackedBranchName,Mo as splitConstraint,op as sortUpdatesByPriority,wf as simplifyTouch,yR as similarity,Vx as sign,uR as showFinalInstructions,N as shouldOpenAsDraft,Yd as shouldFail,Jf as shellcheckAnalyzer,Kx as shellTool,hR as setupCustomWorkflow,$ as setDefaultLogger,ld as serializeReviewState,Af as serializeLearnings,Of as selectLearnings,Fp as selectLatestTag,qf as secretsAnalyzer,YR as schedulePlan,ao as scanEcosystems,vp as scanCatalogs,Bp as sameVariant,Go as rustAdapter,yf as runTool,pd as runStackedTouch,Bd as runReviewForPR,LR as runPreflightChecks,ER as runPostMerge,Zf as runPlan,Ko as runHeadless,xR as runGates,nd as runFixCi,Wf as runAnalyzers,UR as runAiGates,Zx as runAgent,A as ruleMatches,Ao as rubyAdapter,Ld as reviewPullRequest,Px as reviewMode,Ed as reviewDiff,Lx as resolveWorkspacePath,G as resolveRuleEffects,Op as resolveProviderToken,pf as resolveModelAlias,bp as resolveEngineVersion,Kp as resolveCredentials,ep as resolveCatalogReference,Id as resolveBuddyThreads,ff as resolveAiProvider,fm as resetConfigCache,Vf as renderTouchOffer,so as renderReport,TR as renderQuickLinks,aR as renderPackageContext,D as renderMigrationReport,Pf as renderLearnings,Td as renderFinding,qo as renderDoctorReport,xd as renderDiffForReview,_f as relativize,yo as regenerateLockfiles,xp as regenerateLockFile,Tx as redactError,Dx as redactDeep,zx as redact,Bx as readFileTool,Uo as pythonAdapter,Wo as publishOutput,Yo as productFor,jd as prepareReview,Sf as planTouch,yx as planMode,$p as pinBlocksUpdate,Ro as pep440UpdateType,Vp as parseWorkspaceCatalogs,md as parseUnifiedDiff,rf as parseTouchSelections,Nf as parseToolJson,Ip as parseTag,yd as parseReviewState,W as parseRetryDelay,qR as parseRemote,zR as parseQuickSelection,mo as parsePep440,g as parsePackageFile,Uf as parseLearnings,kp as parseImageRef,ho as parseHistory,td as parseCommand,Qp as parseAuthChallenge,If as offsetToLine,po as numericUpdateType,hp as normalizeSeverity,C as normalizePlan,Cd as needsReview,O as mergeGroupEffects,Sd as mentionsBot,B as matchesGlobs,Hf as markdownlintAnalyzer,zp as mapWithConcurrency,Cf as mapSeverity,af as loadLearnings,Vo as loadHistory,zd as loadGuidelines,Hx as listDirTool,Ff as linterAnalyzer,id as latestFailurePerWorkflow,wd as isReadOnlyCommand,fo as isPep440Prerelease,OR as isMergeEvent,gp as isCatalogReference,l as isAllowedCodemod,ax as implementMode,ef as hasTouchOffer,jf as hadolintAnalyzer,KR as guideTokenCreation,WR as guideRepositorySettings,P as groupsToRules,pp as groupUpdates,oo as goAdapter,Tf as githubActionsAnalyzer,bR as getWorkflowPreset,c as getNpmRegistryUrl,h as getGitHubServerUrl,S as getGitHubApiUrl,uf as getFinishingTouch,b as getDefaultLogger,xm as getConfig,V as getComposerRegistryUrl,mp as getAllLockFilePaths,Nx as getAgentMode,ZR as generateUnifiedWorkflow,jo as generateGitLabPipeline,$R as generateCoreWorkflows,XR as generateConfigFile,n as generateBranchName,Io as generateBitbucketPipeline,dR as gateIcon,kx as fsTools,e as formatSecurityAdvisorySection,Wd as formatReview,qd as formatPretty,i as formatPRTitle,s as formatPRBody,qp as formatImageRef,Qo as formatGithubOutput,Jd as formatGithub,q as formatError,Fo as formatConfigIssues,v as formatCommitMessage,Kd as formatAgent,lx as fixCiMode,Md as fingerprint,_ as findUsageSites,co as findPrevious,PR as findMentionedPackages,AR as findLinkedIssues,CR as findDuplicates,_o as findDrift,X as fetchWithTimeout,Y as fetchJsonOrNull,vd as failsOnBaseBranch,gd as extractErrorLines,Yp as extractEngines,Xf as emitEvent,U as ecosystemOf,Co as driftFor,$f as docstringsTouch,SR as displayValidationResults,kR as displayProgress,cd as dispatchCommand,Hd as diffArgsFor,ko as diagnose,fp as detectRequiredPackageManagers,JR as detectRepository,r as detectPackageManager,Bf as detectLinter,sp as detectFiles,od as detectChangedFiles,L as describeSpanGaps,rd as describeFailure,tx as describeEvent,to as describeEol,zo as describeDrift,Pd as defaultIncludePath,mm as defaultConfig,Ad as dedupeFindings,Zo as cycleFor,cx as createWebhookSink,hx as createSlackSink,Sx as createSinks,Yf as createReadIssueTool,ap as createProvider,FR as createProgressTracker,xf as createOpenAiProvider,Gf as createLearning,Vd as createHandlers,mf as createGoogleProvider,ux as createDiscordSink,of as createAnthropicProvider,df as createAiClient,Qd as countBySeverity,lR as constrainLabels,QR as confirmTokenSetup,dm as config,ro as computeMetrics,vo as computeDeltas,Dd as composeInstructions,Lp as compareVersions,xo as comparePep440,np as compareNumeric,zf as commandExists,I as collectSpanNotes,Zp as collectResolutionPins,kd as collectLocalDiff,fd as collectGitDiff,DR as clearQuickSelection,u as clearNpmrcCache,ed as classifyFailure,Lo as ciTemplateFor,Dp as chunk,pR as checkTitleFormat,ud as checkPermission,RR as checkLinkedIssue,$o as checkEol,oR as checkDescription,mR as checkDependencies,MR as checkCustomAssertions,tp as bumpEngineConstraint,Jx as buildShellEnv,y as buildAnalysisPrompt,tf as autofixTouch,T as attemptMajorUpgrade,sd as attemptFix,Ho as assertValidConfig,yp as assertSupports,Pp as assertProviderSupported,Xd as applySuggestion,E as applyRules,ip as applyCatalogUpdates,rp as applyCatalogUpdate,H as appendUpgradeReport,uo as appendHistory,GR as appendChangelogEntry,Jp as apiHostFor,Od as anchorMap,BR as analyzeProject,F as analyzeGroupMajors,cp as advisoryKey,Ef as addLearning,Po as adapterNamed,Oo as adapterFor,Df as actionlintAnalyzer,wx as WEBHOOK_PAYLOAD_VERSION,R as VersionResolver,Gp as UnsupportedProviderError,Xx as Toolbelt,Qx as ToolPermissionError,cf as TOUCH_OFFER_MARKER,lf as TOOL_TIMEOUT_MS,vf as TEST_COMMANDS,up as SecurityAdvisoryService,pm as Scheduler,qx as SHELL_ENV_ALLOWLIST,dd as SEVERITY_ORDER,kf as SECRET_RULES,Cp as ReleaseNotesFetcher,jp as RegistryClient,No as ROOT,ad as REVIEW_STATE_VERSION,Rd as REVIEW_SCHEMA,Fd as REVIEW_FORMATS,eo as REPORT_PERIODS,io as REPORT_MARKER,_x as REDACTED,$d as READ_ONLY_COMMANDS,NR as QUICK_LINKS_MARKER,_R as QUICK_ACTIONS,Np as PullRequestGenerator,IR as PluginManager,wp as PackageScanner,gx as PackageRegistryError,Up as PROVIDER_TRACKING_ISSUES,Ep as PROVIDER_TOKEN_ENV,nx as PROVIDER_PRIORITY,Rp as PROVIDER_NAMES,sx as PROVIDER_KEY_ENV,go as PERIOD_DAYS,Wp as OciClient,Ap as NO_CAPABILITIES,ix as MODEL_ALIASES,a as MIGRATION_PLAN_SCHEMA,_d as MAX_GUIDELINE_CHARS,Z as Logger,Lf as LINTER_SPECS,Xp as KNOWN_ENGINES,Mp as IMPLEMENTED_PROVIDERS,Q as HttpRequestError,wo as HISTORY_PATH,So as HISTORY_LIMIT,hd as HELP_TEXT,rx as GitProviderError,t as GitLabProvider,dp as GitHubProvider,k as GitHubApiError,om as GitHubActionsTemplate,hf as FINISHING_TOUCHES,bx as EventBus,$x as EVENT_NAMES,bo as EOL_WARNING_DAYS,Xo as EOL_PRODUCTS,J as DEFAULT_TIMEOUT_MS,j as DEFAULT_SPAN_BUDGET,To as DEFAULT_SCHEDULE,K as DEFAULT_RETRIES,Mf as DEFAULT_PROMPT_LIMIT,Rf as DEFAULT_LEARNINGS_FILE,Nd as DEFAULT_GUIDELINE_FILES,Gd as DEFAULT_EXCLUDED_PATHS,_p as DEFAULT_CONCURRENCY,jR as ConfigurationMigrator,vx as ConfigurationError,Zd as COMMAND_ALIASES,ex as BuddyError,Do as Buddy,w as BitbucketProvider,Wx as BUILTIN_TOOLS,Qf as BUILTIN_ANALYZERS,Eo as BUILTIN_ADAPTERS,Tp as AsyncMemo,Ix as AiProviderError,jx as AiBudgetExceededError,Cx as AGENT_MODES};
|
|
2
|
+
import{I as wo,J as So,K as ho,L as uo,M as co,N as Vo,O as eo,P as go,Q as ro,R as vo,S as io,T as so,U as no}from"../chunk-ewhvahnb.js";import{W as ko,X as qo}from"../chunk-bafzw99p.js";import{$ as Wo,Y as Jo,Z as Ko,_ as Qo}from"../chunk-whtdmv3p.js";import{aa as PR,ba as aR,ca as lR,da as yR,ea as CR,fa as NR,ga as _R,ha as zR,ia as DR,ja as TR}from"../chunk-69qyr9ef.js";import{ka as pR,la as oR,ma as mR,na as xR,oa as fR,pa as dR,qa as RR,ra as MR,sa as UR,ta as AR,ua as GR,va as ER,wa as OR}from"../chunk-psjrcpgb.js";import{Aa as $o,Ba as bo,Ca as to,xa as Xo,ya as Yo,za as Zo}from"../chunk-1a14rx5n.js";import"../chunk-rb1fh9vd.js";import{Da as pm}from"../chunk-1jgh0ff1.js";import{Ea as ed,Fa as gd,Ga as rd,Ha as vd,Ia as id,Ja as sd,Ka as nd}from"../chunk-9chq5m4p.js";import{La as Zd,Ma as $d,Na as bd,Oa as td,Pa as wd,Qa as Sd,Ra as hd,Sa as ud,Ta as cd,Ua as Vd}from"../chunk-fsghqtgf.js";import{Va as Yf,Wa as Zf}from"../chunk-her5azyp.js";import{$a as Sf,Xa as $f,Ya as bf,Za as tf,_a as wf,ab as hf,bb as uf,cb as cf,db as Vf,eb as ef,fb as gf,gb as rf}from"../chunk-jqh7vx2n.js";import{hb as vf,ib as sf,jb as nf,kb as pd,lb as od}from"../chunk-gg1ddvnf.js";import{mb as Id}from"../chunk-byqzhgzs.js";import{Ab as Td,Bb as jd,Cb as Ld,Db as Bd,nb as dd,ob as Rd,pb as Md,qb as Ud,rb as Ad,sb as Gd,tb as Ed,ub as Od,vb as Pd,wb as Nd,xb as _d,yb as zd,zb as Dd}from"../chunk-4dz5x4xw.js";import{Eb as md,Fb as xd,Gb as fd}from"../chunk-q2tjkhez.js";import{Hb as Co,Ib as No,Jb as _o,Kb as zo}from"../chunk-vckhctmr.js";import{Lb as ad,Mb as ld,Nb as yd,Pb as Cd}from"../chunk-5yfaptmp.js";import{Qb as Rf,Rb as Mf,Sb as Uf,Tb as Af,Ub as Gf,Vb as Ef,Wb as Of,Xb as Pf,Yb as af}from"../chunk-vs61069x.js";import{$b as nx,Zb as ix,_b as sx,ac as pf,bc as of,cc as mf,dc as xf,ec as ff,fc as df}from"../chunk-wfwrm4k3.js";import{gc as Vp,hc as ep,ic as gp,jc as rp,mc as vp,nc as ip}from"../chunk-1g43mpqn.js";import{Ac as Uo,Bc as Ao,Cc as Go,Dc as Eo,Ec as Oo,Fc as Po,Gc as ao,Hc as lo,Ic as yo,pc as sp,sc as np,tc as po,uc as oo,vc as mo,wc as xo,xc as fo,yc as Ro,zc as Mo}from"../chunk-mtn4angk.js";import{Mc as dp}from"../chunk-4chtv4nh.js";import{Nc as mp,Oc as xp,Pc as fp}from"../chunk-j57716xw.js";import{Uc as mm,Vc as xm,Wc as fm,Xc as dm}from"../chunk-6b0fmw0d.js";import{Yc as Bo,Zc as Fo,_c as Ho}from"../chunk-4r03rh93.js";import{$c as Sp,ad as hp,bd as up,cd as cp,ed as Do}from"../chunk-z2gcfvze.js";import"../chunk-a8wcn3mh.js";import{gd as _p,hd as zp,id as Dp,jd as Tp,kd as jp}from"../chunk-67bjaw56.js";import{ld as wp}from"../chunk-mthd2c8m.js";import"../chunk-bnp0r4eh.js";import{nd as ex,od as gx,pd as rx,qd as vx}from"../chunk-0f1xye20.js";import{td as Np}from"../chunk-hd74jxm2.js";import{ud as Xf}from"../chunk-s3b3vrsj.js";import{Ad as hx,Bd as ux,Cd as cx,Dd as Vx,vd as $x,wd as bx,xd as tx,yd as wx,zd as Sx}from"../chunk-6gvx1g6h.js";import{Ed as Fd,Fd as Hd,Gd as kd,Hd as qd,Id as Jd,Jd as Kd,Kd as Qd,Ld as Wd,Md as Xd,Nd as Yd}from"../chunk-7m3pzkcj.js";import{$d as Hf,Od as lf,Pd as yf,Qd as Cf,Rd as Nf,Sd as _f,Td as zf,Ud as Df,Vd as Tf,Wd as jf,Xd as If,Yd as Lf,Zd as Bf,_d as Ff,ae as kf,be as qf,ce as Jf,de as Kf,ee as Qf,fe as Wf}from"../chunk-mr2d1zp0.js";import"../chunk-142zh7e5.js";import{ie as Rp,je as Mp,ke as Up,le as Ap,me as Gp,ne as Ep,oe as Op,pe as Pp,qe as ap,re as lp,se as yp}from"../chunk-743mhx0e.js";import"../chunk-d09qj570.js";import"../chunk-wk175yyw.js";import{Fe as Ip,Ge as Lp,He as Bp,Ie as Fp,Je as Hp,Ke as kp,Le as qp,Me as Jp,Ne as Kp,Oe as Qp,Pe as Wp}from"../chunk-4wv5s3vr.js";import{We as Cp}from"../chunk-gvpsbmeg.js";import{$e as bp,Xe as Xp,Ye as Yp,Ze as Zp,_e as $p,af as tp}from"../chunk-j46f90n8.js";import{df as a,ef as l,ff as y,gf as C,hf as N,if as _,jf as z,kf as D,lf as T,mf as j,nf as I,of as L,pf as B,qf as F,rf as H}from"../chunk-7hm46cej.js";import{sf as U,tf as A,uf as G,vf as E,wf as O,yf as P}from"../chunk-wc2z7krw.js";import{Af as ax,Bf as lx,Cf as yx,Df as Cx,Ef as Nx,zf as Px}from"../chunk-1pecmenc.js";import{Ff as Lx,Gf as Bx,Hf as Fx,If as Hx,Jf as kx,Kf as qx,Lf as Jx,Mf as Kx,Nf as Qx,Of as Wx,Pf as Xx,Qf as Yx,Rf as Zx}from"../chunk-hk4d7rky.js";import"../chunk-24xvskkf.js";import{Uf as _x,Vf as zx,Wf as Dx,Xf as Tx,Yf as jx,Zf as Ix}from"../chunk-z18bksyr.js";import"../chunk-cj4d5ad7.js";import{bg as e,cg as g,dg as r,eg as v,fg as i,gg as s,hg as n,ig as pp,jg as op,kg as d}from"../chunk-c63e4ssc.js";import"../chunk-x9vpk4kk.js";import"../chunk-r1jvyhhd.js";import"../chunk-2z9mh5y4.js";import{$g as Io,Zg as To,_g as jo,ah as Lo,ch as jR,dh as IR,eh as LR,fh as BR,gh as FR,hh as HR,ih as kR,jh as qR,kh as JR,lh as KR,mh as QR,nh as WR,oh as XR,ph as YR,qh as ZR,rh as $R,sh as bR,th as tR,uh as wR,vh as SR,wh as hR,xh as uR}from"../chunk-6kd81nf9.js";import{yh as om}from"../chunk-nznpzbq4.js";import{Ah as h,Bh as u,Ch as c,Dh as V,zh as S}from"../chunk-yh13j2af.js";import{Eh as t}from"../chunk-r7qa2ykf.js";import{Fh as w}from"../chunk-gq9gkyah.js";import"../chunk-6w0n6c07.js";import{Hh as J,Ih as K,Jh as Q,Kh as W,Lh as X,Mh as Y}from"../chunk-s0ps33ft.js";import{Nh as k,Oh as q,Ph as Z,Qh as $,Rh as b}from"../chunk-wzncz6j5.js";import"../chunk-m3rftash.js";import"../chunk-16aeend1.js";var{semver:m}=globalThis.Bun;class R{static compareVersions(p,o){return m.order(p,o)}static satisfiesRange(p,o){return m.satisfies(p,o)}static getLatestInRange(p,o){let f=p.filter((x)=>m.satisfies(x,o));if(f.length===0)return null;return f.sort((x,M)=>m.order(M,x))[0]}static createRange(p){return{raw:p,range:p.replace(/^[\^~>=<]+/,""),isExact:!/^[\^~>=<]/.test(p),satisfies:(o)=>this.satisfiesRange(o,p),getLatest:(o)=>this.getLatestInRange(o,p)}}static getUpdateType(p,o){return d(p,o)}static isSafeUpdate(p,o){return m.satisfies(o,p)}}export{Fx as writeFileTool,Yx as wrapUntrusted,gf as withTouchOffer,no as withNarrative,sf as verifyChanges,tR as validateWorkflowGeneration,wR as validateRepositoryAccess,Ud as validateFindings,Bo as validateConfig,Jo as validateAgainstSchema,HR as updateProgress,bf as unitTestsTouch,Sp as toOsvEcosystem,Hp as tagUpdateType,Kf as syntaxAnalyzer,lp as supports,z as summarizeUsage,fR as summarizeGates,lo as stripOperators,bd as stripNonCommandContext,nf as stackedBranchName,Mo as splitConstraint,op as sortUpdatesByPriority,wf as simplifyTouch,yR as similarity,Vx as sign,uR as showFinalInstructions,N as shouldOpenAsDraft,Yd as shouldFail,Jf as shellcheckAnalyzer,Kx as shellTool,hR as setupCustomWorkflow,$ as setDefaultLogger,ld as serializeReviewState,Af as serializeLearnings,Of as selectLearnings,Fp as selectLatestTag,qf as secretsAnalyzer,YR as schedulePlan,ao as scanEcosystems,vp as scanCatalogs,Bp as sameVariant,Go as rustAdapter,yf as runTool,pd as runStackedTouch,Bd as runReviewForPR,LR as runPreflightChecks,ER as runPostMerge,Zf as runPlan,Ko as runHeadless,xR as runGates,nd as runFixCi,Wf as runAnalyzers,UR as runAiGates,Zx as runAgent,A as ruleMatches,Ao as rubyAdapter,Ld as reviewPullRequest,Px as reviewMode,Ed as reviewDiff,Lx as resolveWorkspacePath,G as resolveRuleEffects,Op as resolveProviderToken,pf as resolveModelAlias,bp as resolveEngineVersion,Kp as resolveCredentials,ep as resolveCatalogReference,Id as resolveBuddyThreads,ff as resolveAiProvider,fm as resetConfigCache,Vf as renderTouchOffer,so as renderReport,TR as renderQuickLinks,aR as renderPackageContext,D as renderMigrationReport,Pf as renderLearnings,Td as renderFinding,qo as renderDoctorReport,xd as renderDiffForReview,_f as relativize,yo as regenerateLockfiles,xp as regenerateLockFile,Tx as redactError,Dx as redactDeep,zx as redact,Bx as readFileTool,Uo as pythonAdapter,Wo as publishOutput,Yo as productFor,jd as prepareReview,Sf as planTouch,yx as planMode,$p as pinBlocksUpdate,Ro as pep440UpdateType,Vp as parseWorkspaceCatalogs,md as parseUnifiedDiff,rf as parseTouchSelections,Nf as parseToolJson,Ip as parseTag,yd as parseReviewState,W as parseRetryDelay,qR as parseRemote,zR as parseQuickSelection,mo as parsePep440,g as parsePackageFile,Uf as parseLearnings,kp as parseImageRef,ho as parseHistory,td as parseCommand,Qp as parseAuthChallenge,If as offsetToLine,po as numericUpdateType,hp as normalizeSeverity,C as normalizePlan,Cd as needsReview,O as mergeGroupEffects,Sd as mentionsBot,B as matchesGlobs,Hf as markdownlintAnalyzer,zp as mapWithConcurrency,Cf as mapSeverity,af as loadLearnings,Vo as loadHistory,zd as loadGuidelines,Hx as listDirTool,Ff as linterAnalyzer,id as latestFailurePerWorkflow,wd as isReadOnlyCommand,fo as isPep440Prerelease,OR as isMergeEvent,gp as isCatalogReference,l as isAllowedCodemod,ax as implementMode,ef as hasTouchOffer,jf as hadolintAnalyzer,KR as guideTokenCreation,WR as guideRepositorySettings,P as groupsToRules,pp as groupUpdates,oo as goAdapter,Tf as githubActionsAnalyzer,bR as getWorkflowPreset,c as getNpmRegistryUrl,h as getGitHubServerUrl,S as getGitHubApiUrl,uf as getFinishingTouch,b as getDefaultLogger,xm as getConfig,V as getComposerRegistryUrl,mp as getAllLockFilePaths,Nx as getAgentMode,ZR as generateUnifiedWorkflow,jo as generateGitLabPipeline,$R as generateCoreWorkflows,XR as generateConfigFile,n as generateBranchName,Io as generateBitbucketPipeline,dR as gateIcon,kx as fsTools,e as formatSecurityAdvisorySection,Wd as formatReview,qd as formatPretty,i as formatPRTitle,s as formatPRBody,qp as formatImageRef,Qo as formatGithubOutput,Jd as formatGithub,q as formatError,Fo as formatConfigIssues,v as formatCommitMessage,Kd as formatAgent,lx as fixCiMode,Md as fingerprint,_ as findUsageSites,co as findPrevious,PR as findMentionedPackages,AR as findLinkedIssues,CR as findDuplicates,_o as findDrift,X as fetchWithTimeout,Y as fetchJsonOrNull,vd as failsOnBaseBranch,gd as extractErrorLines,Yp as extractEngines,Xf as emitEvent,U as ecosystemOf,Co as driftFor,$f as docstringsTouch,SR as displayValidationResults,kR as displayProgress,cd as dispatchCommand,Hd as diffArgsFor,ko as diagnose,fp as detectRequiredPackageManagers,JR as detectRepository,r as detectPackageManager,Bf as detectLinter,sp as detectFiles,od as detectChangedFiles,L as describeSpanGaps,rd as describeFailure,tx as describeEvent,to as describeEol,zo as describeDrift,Pd as defaultIncludePath,mm as defaultConfig,Ad as dedupeFindings,Zo as cycleFor,cx as createWebhookSink,hx as createSlackSink,Sx as createSinks,Yf as createReadIssueTool,ap as createProvider,FR as createProgressTracker,xf as createOpenAiProvider,Gf as createLearning,Vd as createHandlers,mf as createGoogleProvider,ux as createDiscordSink,of as createAnthropicProvider,df as createAiClient,Qd as countBySeverity,lR as constrainLabels,QR as confirmTokenSetup,dm as config,ro as computeMetrics,vo as computeDeltas,Dd as composeInstructions,Lp as compareVersions,xo as comparePep440,np as compareNumeric,zf as commandExists,I as collectSpanNotes,Zp as collectResolutionPins,kd as collectLocalDiff,fd as collectGitDiff,DR as clearQuickSelection,u as clearNpmrcCache,ed as classifyFailure,Lo as ciTemplateFor,Dp as chunk,pR as checkTitleFormat,ud as checkPermission,RR as checkLinkedIssue,$o as checkEol,oR as checkDescription,mR as checkDependencies,MR as checkCustomAssertions,tp as bumpEngineConstraint,Jx as buildShellEnv,y as buildAnalysisPrompt,tf as autofixTouch,T as attemptMajorUpgrade,sd as attemptFix,Ho as assertValidConfig,yp as assertSupports,Pp as assertProviderSupported,Xd as applySuggestion,E as applyRules,ip as applyCatalogUpdates,rp as applyCatalogUpdate,H as appendUpgradeReport,uo as appendHistory,GR as appendChangelogEntry,Jp as apiHostFor,Od as anchorMap,BR as analyzeProject,F as analyzeGroupMajors,cp as advisoryKey,Ef as addLearning,Po as adapterNamed,Oo as adapterFor,Df as actionlintAnalyzer,wx as WEBHOOK_PAYLOAD_VERSION,R as VersionResolver,Gp as UnsupportedProviderError,Xx as Toolbelt,Qx as ToolPermissionError,cf as TOUCH_OFFER_MARKER,lf as TOOL_TIMEOUT_MS,vf as TEST_COMMANDS,up as SecurityAdvisoryService,pm as Scheduler,qx as SHELL_ENV_ALLOWLIST,dd as SEVERITY_ORDER,kf as SECRET_RULES,Cp as ReleaseNotesFetcher,jp as RegistryClient,No as ROOT,ad as REVIEW_STATE_VERSION,Rd as REVIEW_SCHEMA,Fd as REVIEW_FORMATS,eo as REPORT_PERIODS,io as REPORT_MARKER,_x as REDACTED,$d as READ_ONLY_COMMANDS,NR as QUICK_LINKS_MARKER,_R as QUICK_ACTIONS,Np as PullRequestGenerator,IR as PluginManager,wp as PackageScanner,gx as PackageRegistryError,Up as PROVIDER_TRACKING_ISSUES,Ep as PROVIDER_TOKEN_ENV,nx as PROVIDER_PRIORITY,Rp as PROVIDER_NAMES,sx as PROVIDER_KEY_ENV,go as PERIOD_DAYS,Wp as OciClient,Ap as NO_CAPABILITIES,ix as MODEL_ALIASES,a as MIGRATION_PLAN_SCHEMA,_d as MAX_GUIDELINE_CHARS,Z as Logger,Lf as LINTER_SPECS,Xp as KNOWN_ENGINES,Mp as IMPLEMENTED_PROVIDERS,Q as HttpRequestError,wo as HISTORY_PATH,So as HISTORY_LIMIT,hd as HELP_TEXT,rx as GitProviderError,t as GitLabProvider,dp as GitHubProvider,k as GitHubApiError,om as GitHubActionsTemplate,hf as FINISHING_TOUCHES,bx as EventBus,$x as EVENT_NAMES,bo as EOL_WARNING_DAYS,Xo as EOL_PRODUCTS,J as DEFAULT_TIMEOUT_MS,j as DEFAULT_SPAN_BUDGET,To as DEFAULT_SCHEDULE,K as DEFAULT_RETRIES,Mf as DEFAULT_PROMPT_LIMIT,Rf as DEFAULT_LEARNINGS_FILE,Nd as DEFAULT_GUIDELINE_FILES,Gd as DEFAULT_EXCLUDED_PATHS,_p as DEFAULT_CONCURRENCY,jR as ConfigurationMigrator,vx as ConfigurationError,Zd as COMMAND_ALIASES,ex as BuddyError,Do as Buddy,w as BitbucketProvider,Wx as BUILTIN_TOOLS,Qf as BUILTIN_ANALYZERS,Eo as BUILTIN_ADAPTERS,Tp as AsyncMemo,Ix as AiProviderError,jx as AiBudgetExceededError,Cx as AGENT_MODES};
|
|
@@ -20,6 +20,7 @@ export declare class RegistryClient {
|
|
|
20
20
|
getPackageMetadata(packageName: string): Promise<PackageMetadata | undefined>;
|
|
21
21
|
packageExists(packageName: string): Promise<boolean>;
|
|
22
22
|
getLatestVersion(packageName: string): Promise<string | null>;
|
|
23
|
+
getReleaseVersions(packageName: string): Promise<string[]>;
|
|
23
24
|
getUpdatesForWorkspace(workspaceName: string): Promise<PackageUpdate[]>;
|
|
24
25
|
searchPackages(query: string, limit?: number): Promise<Array<{
|
|
25
26
|
name: string
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@buddysh/buddy",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.11.
|
|
4
|
+
"version": "0.11.17",
|
|
5
5
|
"description": "AI code review and dependency updates in one bot. Reviews pull requests and local changes, answers @buddy comments, gates merges, repairs failing CI, and keeps dependencies current across npm, Composer, Docker, GitHub Actions and more.",
|
|
6
6
|
"author": "Chris Breuer <chris@stacksjs.org>",
|
|
7
7
|
"license": "MIT",
|
package/dist/chunk-pa7pav6h.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Ib as $}from"./chunk-vckhctmr.js";import"./chunk-16aeend1.js";import{readdir as Z}from"fs/promises";import{join as W}from"path";var w=["dependencies","peerDependencies","optionalDependencies"];async function x(U,V,M,Q){let J=await G(M,Q);if(J.length===0)return[];let H=new Map,z=(q,v,E)=>{let X=H.get(q),Y={by:v,range:E};if(X)X.push(Y);else H.set(q,[Y])};for(let q of U)for(let v of q.dependencies)z(v.name,$,v.currentVersion);for(let q of J)for(let[v,E]of Object.entries(q.ranges))z(v,q.name,E);let D=[];for(let q of J){let v=H.get(q.name);if(!v||v.length===0)continue;try{let E=await V.getPackageMetadata(q.name);if(!E?.versions?.length)continue;D.push({name:q.name,installed:q.version,available:E.versions,declared:v})}catch(E){Q.debug(`Skipping drift analysis for ${q.name}: ${E}`)}}return D}async function G(U,V){let M=W(U,"node_modules"),Q=[],J;try{J=await Z(M)}catch{return V.debug("No node_modules directory, skipping resolution drift analysis"),[]}let H=[];for(let z of J){if(z.startsWith("."))continue;if(z.startsWith("@")){try{let D=await Z(W(M,z));H.push(...D.map((q)=>`${z}/${q}`))}catch{continue}continue}H.push(z)}return await Promise.all(H.map(async(z)=>{try{let D=await Bun.file(W(M,z,"package.json")).json();if(!D.name||!D.version)return;let q={};for(let v of w)Object.assign(q,D[v]??{});Q.push({name:D.name,version:D.version,ranges:q})}catch{}})),Q}export{x as collectDriftInputs};
|