@buddysh/buddy 0.11.13 → 0.11.15
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 +30 -0
- package/dist/bin/cli.js +12 -12
- package/dist/{chunk-ksngk47a.js → chunk-18en5afz.js} +1 -1
- package/dist/{chunk-kkh3q0s2.js → chunk-2bp1j0w0.js} +1 -1
- package/dist/{chunk-6hyrj0b5.js → chunk-5qberaya.js} +1 -1
- package/dist/{chunk-54hdfa8r.js → chunk-9kscva05.js} +1 -1
- package/dist/{chunk-wjmrh1nv.js → chunk-dg1c0fyk.js} +1 -1
- package/dist/{chunk-ce26jarj.js → chunk-eccac8h7.js} +1 -1
- package/dist/{chunk-83srz04v.js → chunk-q9mxgp0n.js} +3 -3
- package/dist/chunk-sztjfky1.js +5 -0
- package/dist/{chunk-j6bejzk9.js → chunk-w2ccdet4.js} +1 -1
- package/dist/{chunk-ngzrrqy2.js → chunk-xjrb50hz.js} +1 -1
- package/dist/{chunk-pg32mf9k.js → chunk-xn2960z7.js} +1 -1
- package/dist/chunk-xyzcgskb.js +3 -0
- package/dist/{chunk-yrr9hqvw.js → chunk-y0rng1vc.js} +1 -1
- package/dist/{chunk-x9qhsyp6.js → chunk-ymh0kwm4.js} +1 -1
- package/dist/{chunk-0w6jmcsh.js → chunk-z0rsmhe4.js} +1 -1
- package/dist/chunk-zjp519wm.js +5 -0
- package/dist/src/index.js +1 -1
- package/package.json +3 -2
- package/dist/chunk-edm12hnb.js +0 -3
- package/dist/chunk-ekf183jk.js +0 -5
- package/dist/chunk-q7709hwk.js +0 -5
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ed as Z}from"./chunk-
|
|
2
|
+
import{ed as Z}from"./chunk-q9mxgp0n.js";import{Oh as _}from"./chunk-zwtx6vn3.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{fd as oX}from"./chunk-c9266b5x.js";import{hd as TX,id as FX,jd as CX,kd as cX}from"./chunk-
|
|
2
|
+
import{fd as oX}from"./chunk-c9266b5x.js";import{hd as TX,id as FX,jd as CX,kd as cX}from"./chunk-ymh0kwm4.js";import{ld as uX}from"./chunk-xyzcgskb.js";import{rd as jX,sd as JX,td as mX}from"./chunk-66nntsnf.js";import{wd as gX,zd as lX}from"./chunk-ebnc6980.js";import{qe as QX,re as i}from"./chunk-y1d6e0ye.js";import{rf as fX}from"./chunk-eh71jv8w.js";import{uf as u,vf as hX,wf as zX,xf as yX,yf as n}from"./chunk-3a5gcj3y.js";import{ig as OX,jg as PX,kg as f}from"./chunk-zy49dwqk.js";import{tg as c,xg as vX,yg as kX}from"./chunk-x9vpk4kk.js";import{zh as p}from"./chunk-7t8s2mcf.js";import{Fh as v}from"./chunk-j6geg3qt.js";import{Kh as HX}from"./chunk-34vracy4.js";import{Mh as RX,Nh as $X,Oh as UX,Ph as bX}from"./chunk-zwtx6vn3.js";import{fl as G}from"./chunk-s82adeq9.js";import xX from"fs";import{join as XX}from"path";import m from"process";var iX={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
|
|
|
@@ -84,9 +84,9 @@ The following updates have all been created. To force a retry/rebase of any, cli
|
|
|
84
84
|
|
|
85
85
|
- [ ] <!-- manual job -->Check this box to trigger a request for Buddy to run again on this repository
|
|
86
86
|
`}extractPackageInfo(X){let $=[],Q=[/update.*?dependency\s+(\S+)/i,/update\s+require(?:-dev)?\s+(\S+)\s+to\s+v?\d+/i,/update\s+(\S+)\s+to\s+v?\d+/i,/bump\s+(\S+)\s+from/i,/chore\(deps\):\s*update\s+dependency\s+(\S+)/i];for(let Z of Q){let K=X.title.match(Z);if(K&&K[1]&&!$.includes(K[1]))$.push(K[1])}let Y=[{name:"npm",pattern:/### npm Dependencies[\s\S]*?(?=###|\n\n---|z)/i},{name:"pkgx",pattern:/### Launchpad\/pkgx Dependencies[\s\S]*?(?=###|\n\n---|z)/i},{name:"actions",pattern:/### GitHub Actions[\s\S]*?(?=###|\n\n---|z)/i}];for(let Z of Y){let K=X.body.match(Z.pattern);if(K){let _=K[0].match(/\|\s*\[([^\]]+)\]\([^)]+\)\s*\|/g);if(_)for(let z of _){let L=z.match(/\|\s*\[([^\]]+)\]/);if(L&&L[1]){let O=L[1].trim();if(O.includes("`")&&O.includes("->")){let H=z.match(/\]\(([^)]+)\)/);if(H&&H[1]){let j=H[1].match(/\/diffs\/npm\/([^/]+)\//);if(j&&j[1]){let q=decodeURIComponent(j[1]);if(q&&q.length>1&&!$.includes(q))$.push(q)}}continue}if(!O.includes("://")&&!O.includes("Compare Source")&&!O.includes("badge")&&!O.includes("!")&&!O.startsWith("[![")&&!O.includes("`")&&!O.includes("->")&&!O.includes(" -> ")&&!O.match(/^\d+\.\d+/)&&!O.includes(" ")&&O.length>0&&!$.includes(O))$.push(O)}}}}if($.length<3){let Z=X.body.match(/`([^`]+)`/g);if(Z)for(let K of Z){let W=K.replace(/`/g,"").trim();if(W.includes("->")||W.includes(" -> ")||W.includes("` -> `")||W.match(/^\d+\.\d+/)||W.match(/^v\d+/)||W.match(/[\d.]+\s*->\s*[\d.]+/)||W.match(/^[\d.]+$/)||W.match(/^\d+\.\d+\.\d+/)||W.match(/^\d+\.\d+\.\d+\./)||W.match(/^\^?\d+\.\d+/)||W.match(/^~\d+\.\d+/)||W.includes("://")||W.includes("Compare Source")||W.includes("badge")||W.includes(" "))continue;if(W=W.split(",")[0].trim(),W&&W.length>1&&!$.includes(W)&&(W.startsWith("@")||W.includes("/")||W.match(/^[a-z][a-z0-9.-]*$/i)))$.push(W)}}return $}applyTemplate(X,$){return X.replace(/\{\{repository\.owner\}\}/g,$.repository.owner).replace(/\{\{repository\.name\}\}/g,$.repository.name).replace(/\{\{openPRs\.count\}\}/g,$.openPRs.length.toString()).replace(/\{\{lastUpdated\}\}/g,$.lastUpdated.toISOString()).replace(/\{\{detectedDependencies\.packageJson\.count\}\}/g,$.detectedDependencies.packageJson.length.toString()).replace(/\{\{detectedDependencies\.githubActions\.count\}\}/g,$.detectedDependencies.githubActions.length.toString()).replace(/\{\{detectedDependencies\.dependencyFiles\.count\}\}/g,$.detectedDependencies.dependencyFiles.length.toString())}}var sX="no-auto-merge";function d(X){let $=X.pullRequest?.autoMerge;return{enabled:$?.enabled??!1,strategy:$?.strategy??"squash",conditions:$?.conditions??[],requireGreenCI:$?.requireGreenCI??!0,optOutLabel:$?.optOutLabel??sX,securityLabel:X.security?.label??"security"}}function VX(X,$,Q){let Y=d($);if(!Y.enabled)return{eligible:!1,reason:"auto-merge is disabled by config"};if(Y.conditions.length===0)return{eligible:!1,reason:"no auto-merge conditions configured (set conditions to at least one of patch-only, minor-only, security-only, all)"};if(!v(X.head))return{eligible:!1,reason:`PR #${X.number} is not a buddy PR (branch: ${X.head})`};if(X.draft)return{eligible:!1,reason:`PR #${X.number} is a draft`};let Z=X.labels??[];if(Z.includes(Y.optOutLabel))return{eligible:!1,reason:`PR #${X.number} carries the ${Y.optOutLabel} label`};if(Y.requireGreenCI&&Q===!1)return{eligible:!1,reason:`PR #${X.number} has failing or pending checks`};let K=c(X.body);if(!K)return{eligible:!1,reason:`PR #${X.number} has no metadata manifest to verify update types against`};if(K.truncated)return{eligible:!1,reason:`PR #${X.number} has a truncated manifest, so its full update set cannot be verified`};let W=AX(K,$);if(W)return W;return MX(K,Z,Y)}function AX(X,$){let Q=[...n($.packages?.groups),...$.packages?.rules??[]];if(Q.length===0||X.updates.length===0)return null;if(!X.updates.every((K)=>K.type&&K.dependencyType))return null;let Z=X.updates.map((K)=>u(rX(K),Q));if(Z.some((K)=>K.autoMerge===!1))return{eligible:!1,reason:"a package rule holds one of these updates back from auto-merge"};if(Z.every((K)=>K.autoMerge===!0))return{eligible:!0,reason:"every update is covered by a package rule that enables auto-merge"};return null}function rX(X){return{name:X.name,currentVersion:X.current,newVersion:X.target,updateType:X.type,file:X.file,dependencyType:X.dependencyType}}function MX(X,$,Q){for(let Z of Q.conditions)switch(Z){case"all":return{eligible:!0,reason:"all updates qualify (condition: all)"};case"patch-only":if(X.updates.length>0&&X.updates.every((K)=>ZX(K)==="patch"))return{eligible:!0,reason:"every update is a patch"};break;case"minor-only":if(X.updates.length>0&&X.updates.every((K)=>ZX(K)!=="major"))return{eligible:!0,reason:"every update is minor or patch"};break;case"security-only":if($.includes(Q.securityLabel))return{eligible:!0,reason:"PR resolves a security advisory"};break}return{eligible:!1,reason:`update types (${[...new Set(X.updates.map(ZX))].join(", ")||"none"}) do not satisfy conditions (${Q.conditions.join(", ")})`}}function ZX(X){if(X.type==="major"||X.type==="minor"||X.type==="patch")return X.type;let $=IX(X.current),Q=IX(X.target);if(!$||!Q)return"major";if($[0]!==Q[0])return"major";if($[1]!==Q[1])return"minor";return"patch"}function IX(X){let $=X.trim().match(/(\d+)\.(\d+)\.(\d+)/);if(!$)return null;return[Number($[1]),Number($[2]),Number($[3])]}function SX(X,$,Q){let Y=d(Q);if(!Y.enabled)return{eligible:!1,reason:"auto-merge is disabled by config"};if(Y.conditions.length===0)return{eligible:!1,reason:"no auto-merge conditions configured"};if($.includes(Y.optOutLabel))return{eligible:!1,reason:`PR carries the ${Y.optOutLabel} label`};let Z={schemaVersion:1,updates:X.map((W)=>({name:W.name,current:W.currentVersion,target:W.newVersion,type:W.updateType,file:W.file,dependencyType:W.dependencyType}))},K=AX(Z,Q);if(K)return K;return MX(Z,$,Y)}var BX="https://api.osv.dev",tX=1000,t={low:0,moderate:1,high:2,critical:3};function _X(X){switch(X){case"dependencies":case"devDependencies":case"peerDependencies":case"optionalDependencies":return"npm";case"require":case"require-dev":return"Packagist";case"python":return"PyPI";case"rust":return"crates.io";case"go":return"Go";case"ruby":return"RubyGems";case"github-actions":return"GitHub Actions";default:return null}}function aX(X){let $=X.database_specific?.severity?.toLowerCase();if($==="low"||$==="moderate"||$==="high"||$==="critical")return $;if($==="medium")return"moderate";let Q=X.severity?.find((Y)=>Y.type?.startsWith("CVSS"))?.score;if(Q){let Y=eX(Q);if(Y!==null){if(Y>=9)return"critical";if(Y>=7)return"high";if(Y>=4)return"moderate";return"low"}}return"moderate"}function eX(X){let $=Number(X);if(Number.isFinite($))return $;let Q=X.match(/\/([0-9](?:\.[0-9])?)$/);if(Q){let Y=Number(Q[1]);return Number.isFinite(Y)?Y:null}return null}function X0(X,$){for(let Q of X.affected??[]){if(Q.package?.name!==$)continue;for(let Y of Q.ranges??[])for(let Z of Y.events??[])if(Z.fixed)return Z.fixed}return}class e{logger;concurrency;detailCache=new CX;constructor(X,$=8){this.logger=X;this.concurrency=$}async findAdvisories(X){let $=new Map;if(X.length===0)return $;let Q=await this.queryBatch(X),Y=[...new Set([...Q.values()].flat())];if(Y.length===0)return $;this.logger.debug(`Fetching details for ${Y.length} advisory record(s)`);let Z=await TX(Y,(W)=>this.fetchVulnerability(W),this.concurrency),K=new Map;for(let W of Z)if(W)K.set(W.id,W);for(let[W,_]of Q){let z=W.slice(W.indexOf(":")+1,W.lastIndexOf("@")),L=[];for(let O of _){let H=K.get(O);if(!H)continue;L.push({id:H.id,aliases:H.aliases??[],summary:H.summary??H.details?.split(`
|
|
87
|
-
`)[0]??"No summary provided",severity:aX(H),url:`https://osv.dev/vulnerability/${H.id}`,fixedVersion:X0(H,z)})}if(L.length>0)L.sort((O,H)=>t[H.severity]-t[O.severity]),$.set(W,L)}return $}async annotateUpdates(X,$="low"){let Q=[],Y=[];if(X.forEach((_,z)=>{let L=_X(_.dependencyType);if(!L)return;let O=wX(_.currentVersion);if(!O)return;let H=L==="GitHub Actions"?O.replace(/^v/i,""):O;if(!H)return;Q.push({name:_.name,version:H,ecosystem:L}),Y.push(z)}),Q.length===0)return X;let Z=await this.findAdvisories(Q),K=t[$],W=0;if(Q.forEach((_,z)=>{let L=Z.get(a(_));if(!L?.length)return;let O=X[Y[z]],H=L.filter((J)=>{if(t[J.severity]<K)return!1;if(!J.fixedVersion)return!1;return $0(wX(O.newVersion),J.fixedVersion)});if(H.length>0)O.securityAdvisories=H,W++}),W>0)this.logger.info(`\uD83D\uDD12 ${W} update(s) resolve known security advisories`);return X}async queryBatch(X){let $=new Map,Q=FX(X,tX);for(let Y of Q)try{let Z=await HX(`${BX}/v1/querybatch`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"buddy"},body:JSON.stringify({queries:Y.map((W)=>({package:{name:W.name,ecosystem:W.ecosystem},version:W.version}))}),retryNonIdempotent:!0,onRetry:({delayMs:W,reason:_})=>this.logger.debug(`OSV batch retry in ${Math.round(W/1000)}s (${_})`)});if(!Z.ok){this.logger.warn(`OSV advisory lookup failed: HTTP ${Z.status}`);continue}(await Z.json()).results?.forEach((W,_)=>{let z=W.vulns?.map((L)=>L.id)??[];if(z.length>0)$.set(a(Y[_]),z)})}catch(Z){this.logger.warn("OSV advisory lookup failed:",Z)}return $}async fetchVulnerability(X){return this.detailCache.get(X,async()=>{try{let $=await HX(`${BX}/v1/vulns/${encodeURIComponent(X)}`,{headers:{"User-Agent":"buddy"}});if(!$.ok)return null;return await $.json()}catch($){return this.logger.debug(`Failed to fetch advisory ${X}:`,$),null}})}}function a(X){return`${X.ecosystem}:${X.name}@${X.version}`}function wX(X){return X.replace(/^[\^~>=<\s]*v?/,"").trim()}function $0(X,$){if(!X||!$)return!1;try{return Bun.semver.order(X,$)>=0}catch{return!1}}import Q0 from"process";function W0(X){if(!X)return null;let $=X.split("/").filter(Boolean);if($.length<2)return null;return{owner:$.slice(0,-1).join("/"),name:$[$.length-1]}}var Y0=["GITHUB_REPOSITORY","CI_PROJECT_PATH","BITBUCKET_REPO_FULL_NAME"];function K0(X){for(let $ of Y0){let Q=W0(X[$]);if(Q)return Q}return null}function NX(X,$=Q0.env){if(!X.repository)return{source:"unresolved",overrodeConfig:!1};let Q=X.repository,Y=K0($),Z=Boolean(Q.owner&&Q.name);if(!Y)return Z?{owner:Q.owner,name:Q.name,source:"config",overrodeConfig:!1}:{source:"unresolved",overrodeConfig:!1};if(Z&&(Q.owner!==Y.owner||Q.name!==Y.name)){let _=`Configured repository ${`${Q.owner}/${Q.name}`} does not match the checked-out repository ${Y.owner}/${Y.name}. Using ${Y.owner}/${Y.name} \u2014 buddy `+"operates on the checked-out repository. Update repository.owner/repository.name in your buddy config to silence this warning.";if(Q.owner=Y.owner,Q.name=Y.name,X.dashboard?.issueNumber!==void 0)X.dashboard.issueNumber=void 0;return{owner:Y.owner,name:Y.name,source:"environment",overrodeConfig:!0,warning:_}}if(!Z)return Q.owner||=Y.owner,Q.name||=Y.name,{owner:Y.owner,name:Y.name,source:"environment",overrodeConfig:!1};return{owner:Q.owner,name:Q.name,source:"config",overrodeConfig:!1}}class WX{config;projectPath;logger;scanner;registryClient;eventBus=null;dashboardGenerator;constructor(X,$=m.cwd()){this.config=X;this.projectPath=$;this.logger=new UX(X.verbose??!1,X.logLevel),bX(this.logger),this.resolveRepositoryConfig(),this.scanner=new uX(this.projectPath,this.logger,this.config.packages?.ignorePaths),this.registryClient=new cX(this.projectPath,this.logger,this.config),this.dashboardGenerator=new KX}async analyzeMajors(X,$){if(!this.config.ai?.majorUpgrades?.enabled)return{report:"",draft:!1};let{analyzeGroupMajors:Q}=await import("./chunk-8jvmqdvc.js"),{createAiClient:Y}=await import("./chunk-4qv88x27.js"),{ReleaseNotesFetcher:Z}=await import("./chunk-zcsahxe6.js"),K=new Z(this.logger),W=await Q({updates:X,config:this.config,workspace:this.projectPath,baseBranch:this.config.repository?.baseBranch||"main",files:$,ai:Y(this.config,this.logger),fetchReleases:(_,z,L)=>K.fetchSpanReleases(_,z,L),logger:this.logger});return{report:W.report,draft:W.draft}}resolveRepositoryConfig(){let X=NX(this.config);if(X.warning)this.logger.warn(`\u26A0\uFE0F ${X.warning}`);else if(X.source==="environment")this.logger.info(`Auto-detected repository: ${X.owner}/${X.name} from GITHUB_REPOSITORY`)}async scanForUpdates(){let X=Date.now();this.logger.info("Starting dependency update scan...");try{let $=Date.now(),Q=await this.scanner.scanProject();this.logger.info(`\u23F1\uFE0F Package file scan took ${Date.now()-$}ms`);let Y=Q.reduce((x,h)=>x+h.dependencies.length,0),Z=[],K=Date.now();if(this.config.packages?.ignore&&this.config.packages.ignore.length>0)Z=(await this.registryClient.getOutdatedPackages()).filter((h)=>!this.config.packages.ignore.includes(h.name));else Z=await this.registryClient.getOutdatedPackages();this.logger.info(`\u23F1\uFE0F bun outdated check took ${Date.now()-K}ms (found ${Z.length} updates)`);let W=Date.now(),_=await this.checkDependencyFilesForUpdates(Q);this.logger.info(`\u23F1\uFE0F Dependency file checks took ${Date.now()-W}ms (found ${_.length} updates)`);let z=Date.now(),L=await this.checkGitHubActionsForUpdates(Q);this.logger.info(`\u23F1\uFE0F GitHub Actions checks took ${Date.now()-z}ms (found ${L.length} updates)`);let O=Date.now(),H=await this.checkDockerfilesForUpdates(Q);this.logger.info(`\u23F1\uFE0F Docker image checks took ${Date.now()-O}ms (found ${H.length} updates)`);let J=Date.now(),j=await this.checkZigForUpdates(Q),q=this.config.packages?.engines===!0?await this.checkEnginesForUpdates(Q):[];this.logger.info(`\u23F1\uFE0F Zig dependency checks took ${Date.now()-J}ms (found ${j.length} updates)`);let{scanCatalogs:I}=await import("./chunk-0w6jmcsh.js"),T=await I(this.projectPath,(x)=>this.registryClient.getLatestVersion(x),{...this.config.packages?.ignore?{ignore:this.config.packages.ignore}:{},logger:this.logger});if(T.entries.length>0)this.logger.info(`\uD83D\uDCE6 pnpm catalogs: ${T.updates.length} update(s) across ${T.entries.length} entr(ies)`);let M=Date.now(),{scanEcosystems:B}=await import("./chunk-wjmrh1nv.js"),C=await B({dir:this.projectPath,...this.config.packages?.includePrerelease!==void 0?{includePrerelease:this.config.packages.includePrerelease}:{},...this.config.packages?.ignore?{ignore:this.config.packages.ignore}:{},logger:this.logger});if(C.manifests.length>0)this.logger.info(`\u23F1\uFE0F Ecosystem checks took ${Date.now()-M}ms (found ${C.updates.length} updates across ${C.manifests.map((x)=>x.ecosystem).join(", ")})`);let D=[...Z,..._,...L,...H,...j,...q,...C.updates,...T.updates];if(this.config.packages?.ignore&&this.config.packages.ignore.length>0)D=D.filter((x)=>!this.config.packages.ignore.includes(x.name));let b=Date.now();if(this.config.packages?.strategy)D=this.filterUpdatesByStrategy(D,this.config.packages.strategy);this.logger.info(`\u23F1\uFE0F Strategy filtering took ${Date.now()-b}ms`);let R=Date.now();D=await this.filterUpdatesByMinimumReleaseAge(D),this.logger.info(`\u23F1\uFE0F Minimum release age filtering took ${Date.now()-R}ms`),D=this.applyPins(D),D=await this.dropOverriddenUpdates(D,Q),D=this.applyPackageRules(D);let g=Date.now();D=await this.annotateSecurityAdvisories(D),this.logger.info(`\u23F1\uFE0F Security advisory lookup took ${Date.now()-g}ms`);let l=this.config.security?.prioritize??!0,o=Date.now();D=PX(D,{prioritizeSecurity:l}),this.logger.info(`\u23F1\uFE0F Sorting took ${Date.now()-o}ms`);let V=Date.now(),N=this.config.packages?.groups?this.groupUpdatesByConfig(D):OX(D,{prioritizeSecurity:l});this.logger.info(`\u23F1\uFE0F Grouping took ${Date.now()-V}ms`);let YX=Date.now()-X,s={totalPackages:Y,updates:D,groups:N,scannedAt:new Date,duration:YX};return this.logger.success(`Scan completed in ${YX}ms. Found ${D.length} updates.`),await this.events.emit("scan.completed",{total:D.length,major:D.filter((x)=>x.updateType==="major").length,minor:D.filter((x)=>x.updateType==="minor").length,patch:D.filter((x)=>x.updateType==="patch").length}),s}catch($){throw this.logger.error("Failed to scan for updates:",$),$}}prTitleFor(X){let $=this.config.pullRequest?.titleFormat;if(!$)return X.title;return jX($,JX(X,{title:X.title},this.config.packages?.strategy))}commitMessageFor(X,$){let Q=this.config.pullRequest?.commitMessageFormat,Y=Q?jX(Q,JX(X,{message:X.title,title:X.title},this.config.packages?.strategy)):X.title;return $?`${Y} ${$}`:Y}applyPackageRules(X){let $=this.config.packages?.rules??[],Y=[...n(this.config.packages?.groups),...$];if(Y.length===0)return X;let Z=hX(X,Y);if(Z.length<X.length)this.logger.info(`\uD83D\uDCCB Package rules dropped ${X.length-Z.length} update(s)`);return Z.map((K)=>K.update)}static mergeUnique(X,$){let Q=[...new Set([...X??[],...$])];return Q.length>0?Q:void 0}labelsFor(X,$){let Q=X.updates.some((Y)=>(Y.securityAdvisories?.length??0)>0);return[...new Set([...$.generateLabels(X),...Q?[this.config.security?.label??"security"]:[],...this.config.pullRequest?.labels??[],...this.groupEffectsFor(X.updates).labels])]}activeRules(){return[...n(this.config.packages?.groups),...this.config.packages?.rules??[]]}groupEffectsFor(X){let $=this.activeRules();if($.length===0)return zX([]);return zX(X.map((Q)=>u(Q,$)))}orderGroupsByPriority(X){if(this.activeRules().length===0)return X;return X.map((Q,Y)=>({group:Q,index:Y,priority:this.groupEffectsFor(Q.updates).prPriority})).sort((Q,Y)=>Y.priority-Q.priority||Q.index-Y.index).map((Q)=>Q.group)}async dropOverriddenUpdates(X,$){let Q=$.filter((W)=>W.type==="package.json");if(Q.length===0)return X;let{collectResolutionPins:Y,pinBlocksUpdate:Z}=await import("./chunk-6qw89f68.js"),K=new Map;for(let W of Q)try{for(let _ of Y(JSON.parse(W.content)))K.set(_.name,{version:_.version,field:_.field})}catch{continue}if(K.size===0)return X;return X.filter((W)=>{let _=K.get(W.name);if(!_)return!0;if(!Z({name:W.name,version:_.version,field:_.field},W.newVersion))return!0;return this.logger.info(`\uD83D\uDD12 Skipping ${W.name} \u2192 ${W.newVersion}: ${_.field} pins it to ${_.version}, which would win at install time`),!1})}applyPins(X){let $=this.config.packages?.pin;if(!$||Object.keys($).length===0)return X;let Q=[];for(let Y of X){let Z=$[Y.name];if(!Z){Q.push(Y);continue}if(Y.currentVersion===Z){this.logger.info(`\uD83D\uDCCC ${Y.name} is pinned to ${Z}, skipping update to ${Y.newVersion}`);continue}this.logger.info(`\uD83D\uDCCC ${Y.name} is pinned to ${Z}, retargeting update from ${Y.newVersion}`),Q.push({...Y,newVersion:Z,updateType:f(Y.currentVersion,Z)})}return Q}async annotateSecurityAdvisories(X){if(this.config.security?.enabled===!1||X.length===0)return X;try{let Q=await new e(this.logger).annotateUpdates(X,this.config.security?.minimumSeverity??"low"),Y=Q.filter((Z)=>Z.securityAdvisories?.length);if(Y.length>0)await this.events.emit("security.advisories",{packages:Y.map((Z)=>({name:Z.name,severity:Z.securityAdvisories?.[0]?.severity??"unknown"}))});return Q}catch($){return this.logger.warn("Security advisory lookup failed, continuing without it:",$),X}}async createPullRequests(X){let $=Date.now();this.logger.info("Creating pull requests for updates...");try{if(!this.config.repository){this.logger.error("\u274C Repository configuration required for PR creation"),this.logger.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts");return}if(!this.config.repository.owner||!this.config.repository.name){this.logger.error("\u274C Repository owner and name are required for PR creation"),this.logger.info("Set them in buddy.config.ts or ensure GITHUB_REPOSITORY env var is available");return}let Q=m.env.GITHUB_TOKEN,Y=m.env.BUDDY_TOKEN||m.env.BUDDY_BOT_TOKEN;if(!Q&&!Y){this.logger.error("\u274C GITHUB_TOKEN or BUDDY_TOKEN environment variable required for PR creation");return}let Z=Q||Y,K=!!Y;if(Y)this.logger.info("\u2705 BUDDY_TOKEN detected - workflow file permissions enabled");else this.logger.info("\u2139\uFE0F No BUDDY_TOKEN \u2014 workflow file updates will be skipped");let W=await QX({provider:this.config.repository.provider,owner:this.config.repository.owner,name:this.config.repository.name,token:Z,...Y?{workflowToken:Y}:{},...this.config.repository.apiUrl?{apiUrl:this.config.repository.apiUrl}:{}},{logger:this.logger}),_=new mX(this.config),z=this.config.maxPRsPerRun??10,L=0,O=this.orderGroupsByPriority(X.groups),H=[];for(let j of O)try{let q=Date.now();if(this.logger.info(`Creating PR for group: ${j.name} (${j.updates.length} updates)`),j.updates.length>0&&j.updates.every((E)=>E.file.includes(".github/workflows/"))&&!K){this.logger.warn(`\u26A0\uFE0F Skipping group ${j.name} \u2014 workflow-file updates require BUDDY_TOKEN with the workflow scope`);continue}try{let{spawn:E}=await import("child_process"),w=(A,F)=>{return new Promise((P,U)=>{let k=E(A,F,{stdio:"pipe"});k.on("close",(r)=>r===0?P():U(Error(`Git command failed with code ${r}`))),k.on("error",U)})},S=this.config.repository.baseBranch||"main";await w("git",["checkout",S]),await w("git",["reset","--hard","HEAD"]),await w("git",["clean","-fd"])}catch(E){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state for early file-change check, continuing anyway:",E)}let T=await this.generateAllFileUpdates(j.updates);if(T.length===0){this.logger.info(`\u2139\uFE0F No file changes for group ${j.name}, skipping \u2014 leaving branches untouched`);continue}let M=this.prTitleFor(j),B=Date.now(),C=await _.generateBody(j),D=Date.now()-B;this.logger.info(`\u23F1\uFE0F PR body generation took ${D}ms`);let b=await this.analyzeMajors(j.updates,T.map((E)=>E.path)),R=fX(C,b.report),g=await W.getPullRequests("open"),l=this.generateBranchName(j),o=`buddy/update-${j.name.toLowerCase().replace(/\s+/g,"-")}-`,V=g.find((E)=>(E.head===l||E.title===M||E.head.startsWith(o)||this.isSimilarPRTitle(E.title,M))&&(E.author==="github-actions[bot]"||E.author.includes("buddy")||v(E.head))&&!E.head.includes("renovate/")&&!E.head.includes("dependabot/")&&!E.author.toLowerCase().includes("renovate")&&!E.author.toLowerCase().includes("dependabot"));if(V){if(this.logger.info(`\uD83D\uDD04 Found existing PR #${V.number}: ${V.title}`),this.shouldAutoClosePR(V,j.updates)){this.logger.info(`\uD83D\uDD12 Auto-closing PR #${V.number} due to config change`);try{let A=this.generateCloseReason(V);try{await W.createComment(V.number,A)}catch(F){this.logger.warn(`\u26A0\uFE0F Could not add close reason comment to PR #${V.number}:`,F)}await W.closePullRequest(V.number),await this.events.emit("pr.closed",{number:V.number,title:V.title,reason:"no longer produced by the current configuration"});try{await W.deleteBranch(V.head),this.logger.success(`\u2705 Auto-closed PR #${V.number} and deleted branch ${V.head}`)}catch(F){this.logger.warn(`\u26A0\uFE0F Auto-closed PR #${V.number} but could not delete ${V.head}:`,F)}continue}catch(A){this.logger.error(`\u274C Failed to auto-close PR #${V.number}:`,A)}}let w=this.checkIfUpdatesMatch(V.body,j.updates),S=[];if(w&&W.getPullRequestFiles)try{let{missingLockFiles:A}=await import("./chunk-3r0jb90q.js");S=A(await W.getPullRequestFiles(V.number))}catch(A){this.logger.warn(`\u26A0\uFE0F Could not list the files of PR #${V.number}; trusting it: ${$X(A)}`)}if(w&&S.length===0){this.logger.info("\u2705 Existing PR has the same updates, skipping creation");continue}else{if(S.length>0)this.logger.info(`\uD83D\uDD12 PR #${V.number} has the same updates but does not regenerate ${S.join(", ")}; refreshing it`);this.logger.info("\uD83D\uDD04 Updates differ, will update existing PR with new content");let A=V.head;try{let{spawn:U}=await import("child_process"),k=(r,dX)=>{return new Promise((pX,DX)=>{let EX=U(r,dX,{stdio:"pipe"});EX.on("close",(GX)=>{if(GX===0)pX();else DX(Error(`Git command failed with code ${GX}`))}),EX.on("error",DX)})};await k("git",["checkout","main"]),await k("git",["reset","--hard","HEAD"]),await k("git",["clean","-fd"]),this.logger.info(`\uD83E\uDDF9 Reset to clean main state before updating existing PR ${V.number}`)}catch(U){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state, continuing anyway:",U)}let F=await this.generateAllFileUpdates(j.updates);if(F.length===0)this.logger.warn(`\u2139\uFE0F No file changes generated for existing PR ${V.number}, updating metadata only`);else{this.logger.info(`\uD83D\uDCDD Regenerated ${F.length} file changes for existing PR ${V.number}`);try{let{hasBranchDifferences:U}=await import("./chunk-j7qktvpg.js");if(!await U(F,A))this.logger.info(`\u2139\uFE0F No content differences for ${A}; recreating from ${this.config.repository.baseBranch||"main"} with same dependency changes to keep branch up-to-date`),await W.commitChanges(A,this.commitMessageFor(j,"(rebased)"),F,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated ${A} from ${this.config.repository.baseBranch||"main"} (dependency versions unchanged)`);else await W.commitChanges(A,this.commitMessageFor(j,"(updated)"),F,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated branch ${A} with latest dependency versions`)}catch(U){this.logger.warn("\u26A0\uFE0F Failed to compare branch content, proceeding with commit:",U),await W.commitChanges(A,this.commitMessageFor(j,"(updated)"),F,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated branch ${A} with latest dependency versions`)}}let P=this.labelsFor(j,_);await W.updatePullRequest(V.number,{title:M,body:R,labels:P,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:V.number,title:M,url:V.url}),this.logger.success(`\u2705 Updated existing PR #${V.number}: ${M}`),this.logger.info(`\uD83D\uDD17 ${V.url}`);continue}}if(L>=z){this.logger.warn(`\u26A0\uFE0F Rate limit reached: already created ${L} PRs this run (max: ${z}). Skipping remaining groups.`);break}let N=this.generateBranchName(j);if(await W.branchExists(N)){this.logger.info(`\uD83D\uDD04 Branch ${N} already exists, checking for associated PR...`);let E=g.find((S)=>S.head===N);if(E){this.logger.info(`\u2705 Found existing PR #${E.number} for branch ${N}, updating it...`);let S=await this.generateAllFileUpdates(j.updates);if(S.length>0)await W.commitChanges(N,this.commitMessageFor(j,"(updated)"),S,this.config.repository.baseBranch||"main");let A=this.labelsFor(j,_);await W.updatePullRequest(E.number,{title:M,body:R,labels:A,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:E.number,title:M,url:E.url}),this.logger.success(`\u2705 Updated existing PR #${E.number}: ${M}`),this.logger.info(`\uD83D\uDD17 ${E.url}`);continue}let w=!1;try{let A=(i(W,"reopenPullRequests","reopenPullRequest")?await W.getPullRequests("closed"):[]).find((F)=>{if(F.head!==N)return!1;if(F.mergedAt)return!1;return Date.now()-(F.updatedAt?.getTime()??0)<86400000});if(A){this.logger.info(`\uD83D\uDD04 Found recently-closed PR #${A.number} for branch ${N}, reopening...`);let F=await this.generateAllFileUpdates(j.updates);if(F.length>0)await W.commitChanges(N,this.commitMessageFor(j,"(reopened)"),F,this.config.repository.baseBranch||"main");await W.reopenPullRequest(A.number);let P=this.labelsFor(j,_);await W.updatePullRequest(A.number,{title:M,body:R,labels:P,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:A.number,title:M,url:A.url}),this.logger.success(`\u2705 Reopened and updated PR #${A.number}: ${M}`),this.logger.info(`\uD83D\uDD17 ${A.url}`),w=!0}}catch(S){this.logger.warn("\u26A0\uFE0F Failed to check/reopen closed PRs:",S)}if(w)continue;this.logger.info(`\uD83E\uDDF9 Branch ${N} exists but has no open PR, cleaning up...`);try{await W.deleteBranch(N)}catch(S){this.logger.warn(`\u26A0\uFE0F Failed to delete orphaned branch ${N}:`,S)}}let s=!1;try{let w=(i(W,"reopenPullRequests","reopenPullRequest")?await W.getPullRequests("closed"):[]).find((S)=>{if(S.head!==N&&!this.isSimilarPRTitle(S.title,M))return!1;if(!v(S.head)&&S.author!=="github-actions[bot]")return!1;if(S.mergedAt)return!1;return Date.now()-(S.updatedAt?.getTime()??0)<604800000});if(w){this.logger.info(`\uD83D\uDD04 Found recently-closed PR #${w.number} (branch may have been deleted), recreating branch and reopening...`),await W.createBranch(N,this.config.repository.baseBranch||"main");let S=await this.generateAllFileUpdates(j.updates);if(S.length>0)await W.commitChanges(N,this.commitMessageFor(j,"(reopened)"),S,this.config.repository.baseBranch||"main");await W.reopenPullRequest(w.number);let A=this.labelsFor(j,_);await W.updatePullRequest(w.number,{title:M,body:R,labels:A,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:w.number,title:M,url:w.url}),this.logger.success(`\u2705 Reopened and updated PR #${w.number}: ${M}`),this.logger.info(`\uD83D\uDD17 ${w.url}`),s=!0}}catch(E){this.logger.warn("\u26A0\uFE0F Failed to check/reopen closed PRs:",E)}if(s)continue;await W.createBranch(N,this.config.repository.baseBranch||"main");try{let{spawn:E}=await import("child_process"),w=(S,A)=>{return new Promise((F,P)=>{let U=E(S,A,{stdio:"pipe"});U.on("close",(k)=>{if(k===0)F();else P(Error(`Git command failed with code ${k}`))}),U.on("error",P)})};await w("git",["checkout","main"]),await w("git",["reset","--hard","HEAD"]),await w("git",["clean","-fd"]),this.logger.info(`\uD83E\uDDF9 Reset to clean main state before generating updates for ${j.name}`)}catch(E){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state, continuing anyway:",E)}let x=await this.generateAllFileUpdates(j.updates);if(x.length===0){this.logger.warn(`\u2139\uFE0F No file changes generated for group ${j.name}, skipping PR creation`);continue}let h=!1;for(let E of x)try{let w=await import("fs");if(w.existsSync(E.path)){if(w.readFileSync(E.path,"utf-8")!==E.content){h=!0;break}}else{h=!0;break}}catch{h=!0;break}if(!h){this.logger.warn(`\u2139\uFE0F No actual content changes for group ${j.name}, skipping PR creation`);continue}this.logger.info(`\uD83D\uDCDD Generated ${x.length} file changes for ${j.name}`),await W.commitChanges(N,this.commitMessageFor(j),x,this.config.repository.baseBranch||"main");let LX=this.groupEffectsFor(j.updates),qX=this.labelsFor(j,_),y=await W.createPullRequest({title:M,body:R,head:N,base:this.config.repository.baseBranch||"main",draft:b.draft,reviewers:WX.mergeUnique(this.config.pullRequest?.reviewers,LX.reviewers),teamReviewers:this.config.pullRequest?.teamReviewers,assignees:WX.mergeUnique(this.config.pullRequest?.assignees,LX.assignees),labels:qX});L++,this.logger.success(`\u2705 Created PR #${y.number}: ${y.title} (${L}/${z} this run)`),this.logger.info(`\uD83D\uDD17 ${y.url}`),await this.events.emit("pr.created",{number:y.number,title:y.title,url:y.url,packages:j.updates.map((E)=>E.name)}),await this.queueAutoMerge(W,y,j.updates,qX);let nX=Date.now()-q;this.logger.info(`\u23F1\uFE0F Total group processing took ${nX}ms`)}catch(q){if(q instanceof Error&&q.name==="WorkflowPermissionError"){this.logger.warn(`\u26A0\uFE0F Skipping group ${j.name}: ${q.message}`);continue}this.logger.error(`\u274C Failed to create PR for group ${j.name}:`,q),H.push({name:j.name,error:q})}let J=Date.now()-$;if(H.length>0){let j=H.map((q)=>`${q.name}: ${$X(q.error)}`).join(`
|
|
87
|
+
`)[0]??"No summary provided",severity:aX(H),url:`https://osv.dev/vulnerability/${H.id}`,fixedVersion:X0(H,z)})}if(L.length>0)L.sort((O,H)=>t[H.severity]-t[O.severity]),$.set(W,L)}return $}async annotateUpdates(X,$="low"){let Q=[],Y=[];if(X.forEach((_,z)=>{let L=_X(_.dependencyType);if(!L)return;let O=wX(_.currentVersion);if(!O)return;let H=L==="GitHub Actions"?O.replace(/^v/i,""):O;if(!H)return;Q.push({name:_.name,version:H,ecosystem:L}),Y.push(z)}),Q.length===0)return X;let Z=await this.findAdvisories(Q),K=t[$],W=0;if(Q.forEach((_,z)=>{let L=Z.get(a(_));if(!L?.length)return;let O=X[Y[z]],H=L.filter((J)=>{if(t[J.severity]<K)return!1;if(!J.fixedVersion)return!1;return $0(wX(O.newVersion),J.fixedVersion)});if(H.length>0)O.securityAdvisories=H,W++}),W>0)this.logger.info(`\uD83D\uDD12 ${W} update(s) resolve known security advisories`);return X}async queryBatch(X){let $=new Map,Q=FX(X,tX);for(let Y of Q)try{let Z=await HX(`${BX}/v1/querybatch`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"buddy"},body:JSON.stringify({queries:Y.map((W)=>({package:{name:W.name,ecosystem:W.ecosystem},version:W.version}))}),retryNonIdempotent:!0,onRetry:({delayMs:W,reason:_})=>this.logger.debug(`OSV batch retry in ${Math.round(W/1000)}s (${_})`)});if(!Z.ok){this.logger.warn(`OSV advisory lookup failed: HTTP ${Z.status}`);continue}(await Z.json()).results?.forEach((W,_)=>{let z=W.vulns?.map((L)=>L.id)??[];if(z.length>0)$.set(a(Y[_]),z)})}catch(Z){this.logger.warn("OSV advisory lookup failed:",Z)}return $}async fetchVulnerability(X){return this.detailCache.get(X,async()=>{try{let $=await HX(`${BX}/v1/vulns/${encodeURIComponent(X)}`,{headers:{"User-Agent":"buddy"}});if(!$.ok)return null;return await $.json()}catch($){return this.logger.debug(`Failed to fetch advisory ${X}:`,$),null}})}}function a(X){return`${X.ecosystem}:${X.name}@${X.version}`}function wX(X){return X.replace(/^[\^~>=<\s]*v?/,"").trim()}function $0(X,$){if(!X||!$)return!1;try{return Bun.semver.order(X,$)>=0}catch{return!1}}import Q0 from"process";function W0(X){if(!X)return null;let $=X.split("/").filter(Boolean);if($.length<2)return null;return{owner:$.slice(0,-1).join("/"),name:$[$.length-1]}}var Y0=["GITHUB_REPOSITORY","CI_PROJECT_PATH","BITBUCKET_REPO_FULL_NAME"];function K0(X){for(let $ of Y0){let Q=W0(X[$]);if(Q)return Q}return null}function NX(X,$=Q0.env){if(!X.repository)return{source:"unresolved",overrodeConfig:!1};let Q=X.repository,Y=K0($),Z=Boolean(Q.owner&&Q.name);if(!Y)return Z?{owner:Q.owner,name:Q.name,source:"config",overrodeConfig:!1}:{source:"unresolved",overrodeConfig:!1};if(Z&&(Q.owner!==Y.owner||Q.name!==Y.name)){let _=`Configured repository ${`${Q.owner}/${Q.name}`} does not match the checked-out repository ${Y.owner}/${Y.name}. Using ${Y.owner}/${Y.name} \u2014 buddy `+"operates on the checked-out repository. Update repository.owner/repository.name in your buddy config to silence this warning.";if(Q.owner=Y.owner,Q.name=Y.name,X.dashboard?.issueNumber!==void 0)X.dashboard.issueNumber=void 0;return{owner:Y.owner,name:Y.name,source:"environment",overrodeConfig:!0,warning:_}}if(!Z)return Q.owner||=Y.owner,Q.name||=Y.name,{owner:Y.owner,name:Y.name,source:"environment",overrodeConfig:!1};return{owner:Q.owner,name:Q.name,source:"config",overrodeConfig:!1}}class WX{config;projectPath;logger;scanner;registryClient;eventBus=null;dashboardGenerator;constructor(X,$=m.cwd()){this.config=X;this.projectPath=$;this.logger=new UX(X.verbose??!1,X.logLevel),bX(this.logger),this.resolveRepositoryConfig(),this.scanner=new uX(this.projectPath,this.logger,this.config.packages?.ignorePaths),this.registryClient=new cX(this.projectPath,this.logger,this.config),this.dashboardGenerator=new KX}async analyzeMajors(X,$){if(!this.config.ai?.majorUpgrades?.enabled)return{report:"",draft:!1};let{analyzeGroupMajors:Q}=await import("./chunk-8jvmqdvc.js"),{createAiClient:Y}=await import("./chunk-4qv88x27.js"),{ReleaseNotesFetcher:Z}=await import("./chunk-zcsahxe6.js"),K=new Z(this.logger),W=await Q({updates:X,config:this.config,workspace:this.projectPath,baseBranch:this.config.repository?.baseBranch||"main",files:$,ai:Y(this.config,this.logger),fetchReleases:(_,z,L)=>K.fetchSpanReleases(_,z,L),logger:this.logger});return{report:W.report,draft:W.draft}}resolveRepositoryConfig(){let X=NX(this.config);if(X.warning)this.logger.warn(`\u26A0\uFE0F ${X.warning}`);else if(X.source==="environment")this.logger.info(`Auto-detected repository: ${X.owner}/${X.name} from GITHUB_REPOSITORY`)}async scanForUpdates(){let X=Date.now();this.logger.info("Starting dependency update scan...");try{let $=Date.now(),Q=await this.scanner.scanProject();this.logger.info(`\u23F1\uFE0F Package file scan took ${Date.now()-$}ms`);let Y=Q.reduce((x,h)=>x+h.dependencies.length,0),Z=[],K=Date.now();if(this.config.packages?.ignore&&this.config.packages.ignore.length>0)Z=(await this.registryClient.getOutdatedPackages()).filter((h)=>!this.config.packages.ignore.includes(h.name));else Z=await this.registryClient.getOutdatedPackages();this.logger.info(`\u23F1\uFE0F bun outdated check took ${Date.now()-K}ms (found ${Z.length} updates)`);let W=Date.now(),_=await this.checkDependencyFilesForUpdates(Q);this.logger.info(`\u23F1\uFE0F Dependency file checks took ${Date.now()-W}ms (found ${_.length} updates)`);let z=Date.now(),L=await this.checkGitHubActionsForUpdates(Q);this.logger.info(`\u23F1\uFE0F GitHub Actions checks took ${Date.now()-z}ms (found ${L.length} updates)`);let O=Date.now(),H=await this.checkDockerfilesForUpdates(Q);this.logger.info(`\u23F1\uFE0F Docker image checks took ${Date.now()-O}ms (found ${H.length} updates)`);let J=Date.now(),j=await this.checkZigForUpdates(Q),q=this.config.packages?.engines===!0?await this.checkEnginesForUpdates(Q):[];this.logger.info(`\u23F1\uFE0F Zig dependency checks took ${Date.now()-J}ms (found ${j.length} updates)`);let{scanCatalogs:I}=await import("./chunk-z0rsmhe4.js"),T=await I(this.projectPath,(x)=>this.registryClient.getLatestVersion(x),{...this.config.packages?.ignore?{ignore:this.config.packages.ignore}:{},logger:this.logger});if(T.entries.length>0)this.logger.info(`\uD83D\uDCE6 pnpm catalogs: ${T.updates.length} update(s) across ${T.entries.length} entr(ies)`);let M=Date.now(),{scanEcosystems:B}=await import("./chunk-dg1c0fyk.js"),C=await B({dir:this.projectPath,...this.config.packages?.includePrerelease!==void 0?{includePrerelease:this.config.packages.includePrerelease}:{},...this.config.packages?.ignore?{ignore:this.config.packages.ignore}:{},logger:this.logger});if(C.manifests.length>0)this.logger.info(`\u23F1\uFE0F Ecosystem checks took ${Date.now()-M}ms (found ${C.updates.length} updates across ${C.manifests.map((x)=>x.ecosystem).join(", ")})`);let D=[...Z,..._,...L,...H,...j,...q,...C.updates,...T.updates];if(this.config.packages?.ignore&&this.config.packages.ignore.length>0)D=D.filter((x)=>!this.config.packages.ignore.includes(x.name));let b=Date.now();if(this.config.packages?.strategy)D=this.filterUpdatesByStrategy(D,this.config.packages.strategy);this.logger.info(`\u23F1\uFE0F Strategy filtering took ${Date.now()-b}ms`);let R=Date.now();D=await this.filterUpdatesByMinimumReleaseAge(D),this.logger.info(`\u23F1\uFE0F Minimum release age filtering took ${Date.now()-R}ms`),D=this.applyPins(D),D=await this.dropOverriddenUpdates(D,Q),D=this.applyPackageRules(D);let g=Date.now();D=await this.annotateSecurityAdvisories(D),this.logger.info(`\u23F1\uFE0F Security advisory lookup took ${Date.now()-g}ms`);let l=this.config.security?.prioritize??!0,o=Date.now();D=PX(D,{prioritizeSecurity:l}),this.logger.info(`\u23F1\uFE0F Sorting took ${Date.now()-o}ms`);let V=Date.now(),N=this.config.packages?.groups?this.groupUpdatesByConfig(D):OX(D,{prioritizeSecurity:l});this.logger.info(`\u23F1\uFE0F Grouping took ${Date.now()-V}ms`);let YX=Date.now()-X,s={totalPackages:Y,updates:D,groups:N,scannedAt:new Date,duration:YX};return this.logger.success(`Scan completed in ${YX}ms. Found ${D.length} updates.`),await this.events.emit("scan.completed",{total:D.length,major:D.filter((x)=>x.updateType==="major").length,minor:D.filter((x)=>x.updateType==="minor").length,patch:D.filter((x)=>x.updateType==="patch").length}),s}catch($){throw this.logger.error("Failed to scan for updates:",$),$}}prTitleFor(X){let $=this.config.pullRequest?.titleFormat;if(!$)return X.title;return jX($,JX(X,{title:X.title},this.config.packages?.strategy))}commitMessageFor(X,$){let Q=this.config.pullRequest?.commitMessageFormat,Y=Q?jX(Q,JX(X,{message:X.title,title:X.title},this.config.packages?.strategy)):X.title;return $?`${Y} ${$}`:Y}applyPackageRules(X){let $=this.config.packages?.rules??[],Y=[...n(this.config.packages?.groups),...$];if(Y.length===0)return X;let Z=hX(X,Y);if(Z.length<X.length)this.logger.info(`\uD83D\uDCCB Package rules dropped ${X.length-Z.length} update(s)`);return Z.map((K)=>K.update)}static mergeUnique(X,$){let Q=[...new Set([...X??[],...$])];return Q.length>0?Q:void 0}labelsFor(X,$){let Q=X.updates.some((Y)=>(Y.securityAdvisories?.length??0)>0);return[...new Set([...$.generateLabels(X),...Q?[this.config.security?.label??"security"]:[],...this.config.pullRequest?.labels??[],...this.groupEffectsFor(X.updates).labels])]}activeRules(){return[...n(this.config.packages?.groups),...this.config.packages?.rules??[]]}groupEffectsFor(X){let $=this.activeRules();if($.length===0)return zX([]);return zX(X.map((Q)=>u(Q,$)))}orderGroupsByPriority(X){if(this.activeRules().length===0)return X;return X.map((Q,Y)=>({group:Q,index:Y,priority:this.groupEffectsFor(Q.updates).prPriority})).sort((Q,Y)=>Y.priority-Q.priority||Q.index-Y.index).map((Q)=>Q.group)}async dropOverriddenUpdates(X,$){let Q=$.filter((W)=>W.type==="package.json");if(Q.length===0)return X;let{collectResolutionPins:Y,pinBlocksUpdate:Z}=await import("./chunk-6qw89f68.js"),K=new Map;for(let W of Q)try{for(let _ of Y(JSON.parse(W.content)))K.set(_.name,{version:_.version,field:_.field})}catch{continue}if(K.size===0)return X;return X.filter((W)=>{let _=K.get(W.name);if(!_)return!0;if(!Z({name:W.name,version:_.version,field:_.field},W.newVersion))return!0;return this.logger.info(`\uD83D\uDD12 Skipping ${W.name} \u2192 ${W.newVersion}: ${_.field} pins it to ${_.version}, which would win at install time`),!1})}applyPins(X){let $=this.config.packages?.pin;if(!$||Object.keys($).length===0)return X;let Q=[];for(let Y of X){let Z=$[Y.name];if(!Z){Q.push(Y);continue}if(Y.currentVersion===Z){this.logger.info(`\uD83D\uDCCC ${Y.name} is pinned to ${Z}, skipping update to ${Y.newVersion}`);continue}this.logger.info(`\uD83D\uDCCC ${Y.name} is pinned to ${Z}, retargeting update from ${Y.newVersion}`),Q.push({...Y,newVersion:Z,updateType:f(Y.currentVersion,Z)})}return Q}async annotateSecurityAdvisories(X){if(this.config.security?.enabled===!1||X.length===0)return X;try{let Q=await new e(this.logger).annotateUpdates(X,this.config.security?.minimumSeverity??"low"),Y=Q.filter((Z)=>Z.securityAdvisories?.length);if(Y.length>0)await this.events.emit("security.advisories",{packages:Y.map((Z)=>({name:Z.name,severity:Z.securityAdvisories?.[0]?.severity??"unknown"}))});return Q}catch($){return this.logger.warn("Security advisory lookup failed, continuing without it:",$),X}}async createPullRequests(X){let $=Date.now();this.logger.info("Creating pull requests for updates...");try{if(!this.config.repository){this.logger.error("\u274C Repository configuration required for PR creation"),this.logger.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts");return}if(!this.config.repository.owner||!this.config.repository.name){this.logger.error("\u274C Repository owner and name are required for PR creation"),this.logger.info("Set them in buddy.config.ts or ensure GITHUB_REPOSITORY env var is available");return}let Q=m.env.GITHUB_TOKEN,Y=m.env.BUDDY_TOKEN||m.env.BUDDY_BOT_TOKEN;if(!Q&&!Y){this.logger.error("\u274C GITHUB_TOKEN or BUDDY_TOKEN environment variable required for PR creation");return}let Z=Q||Y,K=!!Y;if(Y)this.logger.info("\u2705 BUDDY_TOKEN detected - workflow file permissions enabled");else this.logger.info("\u2139\uFE0F No BUDDY_TOKEN \u2014 workflow file updates will be skipped");let W=await QX({provider:this.config.repository.provider,owner:this.config.repository.owner,name:this.config.repository.name,token:Z,...Y?{workflowToken:Y}:{},...this.config.repository.apiUrl?{apiUrl:this.config.repository.apiUrl}:{}},{logger:this.logger}),_=new mX(this.config),z=this.config.maxPRsPerRun??10,L=0,O=this.orderGroupsByPriority(X.groups),H=[];for(let j of O)try{let q=Date.now();if(this.logger.info(`Creating PR for group: ${j.name} (${j.updates.length} updates)`),j.updates.length>0&&j.updates.every((E)=>E.file.includes(".github/workflows/"))&&!K){this.logger.warn(`\u26A0\uFE0F Skipping group ${j.name} \u2014 workflow-file updates require BUDDY_TOKEN with the workflow scope`);continue}try{let{spawn:E}=await import("child_process"),w=(A,F)=>{return new Promise((P,U)=>{let k=E(A,F,{stdio:"pipe"});k.on("close",(r)=>r===0?P():U(Error(`Git command failed with code ${r}`))),k.on("error",U)})},S=this.config.repository.baseBranch||"main";await w("git",["checkout",S]),await w("git",["reset","--hard","HEAD"]),await w("git",["clean","-fd"])}catch(E){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state for early file-change check, continuing anyway:",E)}let T=await this.generateAllFileUpdates(j.updates);if(T.length===0){this.logger.info(`\u2139\uFE0F No file changes for group ${j.name}, skipping \u2014 leaving branches untouched`);continue}let M=this.prTitleFor(j),B=Date.now(),C=await _.generateBody(j),D=Date.now()-B;this.logger.info(`\u23F1\uFE0F PR body generation took ${D}ms`);let b=await this.analyzeMajors(j.updates,T.map((E)=>E.path)),R=fX(C,b.report),g=await W.getPullRequests("open"),l=this.generateBranchName(j),o=`buddy/update-${j.name.toLowerCase().replace(/\s+/g,"-")}-`,V=g.find((E)=>(E.head===l||E.title===M||E.head.startsWith(o)||this.isSimilarPRTitle(E.title,M))&&(E.author==="github-actions[bot]"||E.author.includes("buddy")||v(E.head))&&!E.head.includes("renovate/")&&!E.head.includes("dependabot/")&&!E.author.toLowerCase().includes("renovate")&&!E.author.toLowerCase().includes("dependabot"));if(V){if(this.logger.info(`\uD83D\uDD04 Found existing PR #${V.number}: ${V.title}`),this.shouldAutoClosePR(V,j.updates)){this.logger.info(`\uD83D\uDD12 Auto-closing PR #${V.number} due to config change`);try{let A=this.generateCloseReason(V);try{await W.createComment(V.number,A)}catch(F){this.logger.warn(`\u26A0\uFE0F Could not add close reason comment to PR #${V.number}:`,F)}await W.closePullRequest(V.number),await this.events.emit("pr.closed",{number:V.number,title:V.title,reason:"no longer produced by the current configuration"});try{await W.deleteBranch(V.head),this.logger.success(`\u2705 Auto-closed PR #${V.number} and deleted branch ${V.head}`)}catch(F){this.logger.warn(`\u26A0\uFE0F Auto-closed PR #${V.number} but could not delete ${V.head}:`,F)}continue}catch(A){this.logger.error(`\u274C Failed to auto-close PR #${V.number}:`,A)}}let w=this.checkIfUpdatesMatch(V.body,j.updates),S=[];if(w&&W.getPullRequestFiles)try{let{missingLockFiles:A}=await import("./chunk-3r0jb90q.js");S=A(await W.getPullRequestFiles(V.number))}catch(A){this.logger.warn(`\u26A0\uFE0F Could not list the files of PR #${V.number}; trusting it: ${$X(A)}`)}if(w&&S.length===0){this.logger.info("\u2705 Existing PR has the same updates, skipping creation");continue}else{if(S.length>0)this.logger.info(`\uD83D\uDD12 PR #${V.number} has the same updates but does not regenerate ${S.join(", ")}; refreshing it`);this.logger.info("\uD83D\uDD04 Updates differ, will update existing PR with new content");let A=V.head;try{let{spawn:U}=await import("child_process"),k=(r,dX)=>{return new Promise((pX,DX)=>{let EX=U(r,dX,{stdio:"pipe"});EX.on("close",(GX)=>{if(GX===0)pX();else DX(Error(`Git command failed with code ${GX}`))}),EX.on("error",DX)})};await k("git",["checkout","main"]),await k("git",["reset","--hard","HEAD"]),await k("git",["clean","-fd"]),this.logger.info(`\uD83E\uDDF9 Reset to clean main state before updating existing PR ${V.number}`)}catch(U){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state, continuing anyway:",U)}let F=await this.generateAllFileUpdates(j.updates);if(F.length===0)this.logger.warn(`\u2139\uFE0F No file changes generated for existing PR ${V.number}, updating metadata only`);else{this.logger.info(`\uD83D\uDCDD Regenerated ${F.length} file changes for existing PR ${V.number}`);try{let{hasBranchDifferences:U}=await import("./chunk-j7qktvpg.js");if(!await U(F,A))this.logger.info(`\u2139\uFE0F No content differences for ${A}; recreating from ${this.config.repository.baseBranch||"main"} with same dependency changes to keep branch up-to-date`),await W.commitChanges(A,this.commitMessageFor(j,"(rebased)"),F,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated ${A} from ${this.config.repository.baseBranch||"main"} (dependency versions unchanged)`);else await W.commitChanges(A,this.commitMessageFor(j,"(updated)"),F,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated branch ${A} with latest dependency versions`)}catch(U){this.logger.warn("\u26A0\uFE0F Failed to compare branch content, proceeding with commit:",U),await W.commitChanges(A,this.commitMessageFor(j,"(updated)"),F,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated branch ${A} with latest dependency versions`)}}let P=this.labelsFor(j,_);await W.updatePullRequest(V.number,{title:M,body:R,labels:P,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:V.number,title:M,url:V.url}),this.logger.success(`\u2705 Updated existing PR #${V.number}: ${M}`),this.logger.info(`\uD83D\uDD17 ${V.url}`);continue}}if(L>=z){this.logger.warn(`\u26A0\uFE0F Rate limit reached: already created ${L} PRs this run (max: ${z}). Skipping remaining groups.`);break}let N=this.generateBranchName(j);if(await W.branchExists(N)){this.logger.info(`\uD83D\uDD04 Branch ${N} already exists, checking for associated PR...`);let E=g.find((S)=>S.head===N);if(E){this.logger.info(`\u2705 Found existing PR #${E.number} for branch ${N}, updating it...`);let S=await this.generateAllFileUpdates(j.updates);if(S.length>0)await W.commitChanges(N,this.commitMessageFor(j,"(updated)"),S,this.config.repository.baseBranch||"main");let A=this.labelsFor(j,_);await W.updatePullRequest(E.number,{title:M,body:R,labels:A,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:E.number,title:M,url:E.url}),this.logger.success(`\u2705 Updated existing PR #${E.number}: ${M}`),this.logger.info(`\uD83D\uDD17 ${E.url}`);continue}let w=!1;try{let A=(i(W,"reopenPullRequests","reopenPullRequest")?await W.getPullRequests("closed"):[]).find((F)=>{if(F.head!==N)return!1;if(F.mergedAt)return!1;return Date.now()-(F.updatedAt?.getTime()??0)<86400000});if(A){this.logger.info(`\uD83D\uDD04 Found recently-closed PR #${A.number} for branch ${N}, reopening...`);let F=await this.generateAllFileUpdates(j.updates);if(F.length>0)await W.commitChanges(N,this.commitMessageFor(j,"(reopened)"),F,this.config.repository.baseBranch||"main");await W.reopenPullRequest(A.number);let P=this.labelsFor(j,_);await W.updatePullRequest(A.number,{title:M,body:R,labels:P,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:A.number,title:M,url:A.url}),this.logger.success(`\u2705 Reopened and updated PR #${A.number}: ${M}`),this.logger.info(`\uD83D\uDD17 ${A.url}`),w=!0}}catch(S){this.logger.warn("\u26A0\uFE0F Failed to check/reopen closed PRs:",S)}if(w)continue;this.logger.info(`\uD83E\uDDF9 Branch ${N} exists but has no open PR, cleaning up...`);try{await W.deleteBranch(N)}catch(S){this.logger.warn(`\u26A0\uFE0F Failed to delete orphaned branch ${N}:`,S)}}let s=!1;try{let w=(i(W,"reopenPullRequests","reopenPullRequest")?await W.getPullRequests("closed"):[]).find((S)=>{if(S.head!==N&&!this.isSimilarPRTitle(S.title,M))return!1;if(!v(S.head)&&S.author!=="github-actions[bot]")return!1;if(S.mergedAt)return!1;return Date.now()-(S.updatedAt?.getTime()??0)<604800000});if(w){this.logger.info(`\uD83D\uDD04 Found recently-closed PR #${w.number} (branch may have been deleted), recreating branch and reopening...`),await W.createBranch(N,this.config.repository.baseBranch||"main");let S=await this.generateAllFileUpdates(j.updates);if(S.length>0)await W.commitChanges(N,this.commitMessageFor(j,"(reopened)"),S,this.config.repository.baseBranch||"main");await W.reopenPullRequest(w.number);let A=this.labelsFor(j,_);await W.updatePullRequest(w.number,{title:M,body:R,labels:A,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:w.number,title:M,url:w.url}),this.logger.success(`\u2705 Reopened and updated PR #${w.number}: ${M}`),this.logger.info(`\uD83D\uDD17 ${w.url}`),s=!0}}catch(E){this.logger.warn("\u26A0\uFE0F Failed to check/reopen closed PRs:",E)}if(s)continue;await W.createBranch(N,this.config.repository.baseBranch||"main");try{let{spawn:E}=await import("child_process"),w=(S,A)=>{return new Promise((F,P)=>{let U=E(S,A,{stdio:"pipe"});U.on("close",(k)=>{if(k===0)F();else P(Error(`Git command failed with code ${k}`))}),U.on("error",P)})};await w("git",["checkout","main"]),await w("git",["reset","--hard","HEAD"]),await w("git",["clean","-fd"]),this.logger.info(`\uD83E\uDDF9 Reset to clean main state before generating updates for ${j.name}`)}catch(E){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state, continuing anyway:",E)}let x=await this.generateAllFileUpdates(j.updates);if(x.length===0){this.logger.warn(`\u2139\uFE0F No file changes generated for group ${j.name}, skipping PR creation`);continue}let h=!1;for(let E of x)try{let w=await import("fs");if(w.existsSync(E.path)){if(w.readFileSync(E.path,"utf-8")!==E.content){h=!0;break}}else{h=!0;break}}catch{h=!0;break}if(!h){this.logger.warn(`\u2139\uFE0F No actual content changes for group ${j.name}, skipping PR creation`);continue}this.logger.info(`\uD83D\uDCDD Generated ${x.length} file changes for ${j.name}`),await W.commitChanges(N,this.commitMessageFor(j),x,this.config.repository.baseBranch||"main");let LX=this.groupEffectsFor(j.updates),qX=this.labelsFor(j,_),y=await W.createPullRequest({title:M,body:R,head:N,base:this.config.repository.baseBranch||"main",draft:b.draft,reviewers:WX.mergeUnique(this.config.pullRequest?.reviewers,LX.reviewers),teamReviewers:this.config.pullRequest?.teamReviewers,assignees:WX.mergeUnique(this.config.pullRequest?.assignees,LX.assignees),labels:qX});L++,this.logger.success(`\u2705 Created PR #${y.number}: ${y.title} (${L}/${z} this run)`),this.logger.info(`\uD83D\uDD17 ${y.url}`),await this.events.emit("pr.created",{number:y.number,title:y.title,url:y.url,packages:j.updates.map((E)=>E.name)}),await this.queueAutoMerge(W,y,j.updates,qX);let nX=Date.now()-q;this.logger.info(`\u23F1\uFE0F Total group processing took ${nX}ms`)}catch(q){if(q instanceof Error&&q.name==="WorkflowPermissionError"){this.logger.warn(`\u26A0\uFE0F Skipping group ${j.name}: ${q.message}`);continue}this.logger.error(`\u274C Failed to create PR for group ${j.name}:`,q),H.push({name:j.name,error:q})}let J=Date.now()-$;if(H.length>0){let j=H.map((q)=>`${q.name}: ${$X(q.error)}`).join(`
|
|
88
88
|
`);throw Error(`Could not create pull requests for ${H.length} of ${O.length} group(s):
|
|
89
|
-
${j}`)}this.logger.success(`\u2705 Completed PR creation for ${X.groups.length} group(s) in ${J}ms`)}catch(Q){throw this.logger.error("Failed to create pull requests:",Q),Q}}shouldRespectVersion(X){if(!(this.config.packages?.respectLatest??!0))return!1;let Q=["latest","*","main","master","develop","dev"],Y=X.toLowerCase().trim();return Q.includes(Y)}async checkDependencyFilesForUpdates(X){let{isDependencyFile:$}=await import("./chunk-j21m6rf6.js"),{resolveDependencyFile:Q}=await import("./chunk-1znpbjrv.js"),Y=[],Z=X.filter((_)=>$(_.path));this.logger.info(`\u26A1 Checking ${Z.length} dependency files in parallel...`);let K=Z.map(async(_)=>{try{this.logger.info(`Checking dependency file: ${_.path}`);let z=await Q(_.path),L=[];for(let O of z.allDependencies||[]){if(this.shouldRespectVersion(O.constraint)){this.logger.debug(`Skipping ${O.name} - version "${O.constraint}" should be respected`);continue}if(O.constraint!==O.version&&O.version){let H=O.constraint.replace(/^[\^~>=<]+/,"");if(!this.isNewerVersion(H,O.version)){this.logger.debug(`Skipping ${O.name} - latest (${O.version}) is not newer than constraint (${H})`);continue}let J=f(H,O.version),j=O.version;L.push({name:O.name,currentVersion:O.constraint,newVersion:j,updateType:J,dependencyType:"dependencies",file:_.path,metadata:void 0,releaseNotesUrl:void 0,changelogUrl:void 0,homepage:void 0})}}return L}catch(z){return this.logger.error(`Failed to check dependency file ${_.path}:`,z),[]}}),W=await Promise.all(K);return Y.push(...W.flat()),Y}async checkZigForUpdates(X){let{isZigManifest:$}=await import("./chunk-nd780ymh.js"),{fetchLatestZigVersion:Q,fetchZigHash:Y,isZigAvailable:Z,parseZigSource:K,zigUrlForVersion:W}=await import("./chunk-jkn2sdm0.js"),_=X.filter((H)=>$(H.path));if(_.length===0)return[];if(!await Z())return this.logger.warn("\u26A0\uFE0F Found Zig manifests but the zig toolchain is not available. "+"Skipping Zig updates: their content-addressed hashes cannot be recomputed without `zig fetch`."),[];let z=m.env.GITHUB_TOKEN||m.env.BUDDY_TOKEN||m.env.BUDDY_BOT_TOKEN,L=_.flatMap((H)=>H.dependencies.filter((J)=>J.type==="zig-dependencies").map((J)=>({file:H,dep:J})));return this.logger.info(`\u26A1 Checking ${L.length} Zig dependencies...`),(await Promise.all(L.map(async({file:H,dep:J})=>{let j=J.metadata?.url;if(!j)return this.logger.debug(`Skipping ${J.name}: no URL recorded`),null;let q=K(j);if(!q)return this.logger.debug(`Skipping ${J.name}: only GitHub-hosted Zig dependencies can be checked`),null;let I=await Q(q,z);if(!I||I===J.currentVersion)return null;let T=W(j,I),M=await Y(T);if(!M)return this.logger.warn(`\u26A0\uFE0F Skipping ${J.name} ${J.currentVersion} \u2192 ${I}: could not compute its package hash`),null;return this.logger.info(`\uD83D\uDCE6 ${J.name}: ${J.currentVersion} \u2192 ${I}`),{name:J.name,currentVersion:J.currentVersion,newVersion:I,updateType:f(J.currentVersion,I),dependencyType:"zig-dependencies",file:H.path,resolved:{url:T,hash:M}}}))).filter((H)=>H!==null)}async checkGitHubActionsForUpdates(X){let{fetchActionTagCommit:$,fetchLatestActionVersion:Q,isGitHubActionsFile:Y,sameActionVersion:Z}=await import("./chunk-fgec04jx.js"),K=[],W=X.filter((J)=>Y(J.path));this.logger.info(`\uD83D\uDD0D Found ${W.length} GitHub Actions workflow files`);let _=[];for(let J of W){let j=J.dependencies.filter((q)=>q.type==="github-actions");this.logger.info(`Found ${j.length} GitHub Actions in ${J.path}`),j.forEach((q)=>_.push({file:J,dep:q}))}this.logger.info(`\u26A1 Checking ${_.length} GitHub Actions in parallel...`);let z=_.map(async({file:J,dep:j})=>{try{this.logger.info(`Checking action: ${j.name}@${j.currentVersion}`);let q=await Q(j.name);if(q&&j.metadata?.pinnedSha){let I=j.metadata.pinnedVersion;if(!I)return this.logger.info(`Skipping ${j.name}@${j.currentVersion}: a SHA pin without a version comment cannot be compared`),null;if(Z(I,q))return this.logger.info(`No update needed for ${j.name}: already pinned to ${q}`),null;let T=await $(j.name,q);if(!T)return this.logger.warn(`Could not resolve ${j.name}@${q} to a commit; leaving the SHA pin alone`),null;let M=f(I,q);return this.logger.info(`Update available: ${j.name} ${I} \u2192 ${q} (${M}, pinned)`),{name:j.name,currentVersion:j.currentVersion,newVersion:q,updateType:M,dependencyType:"github-actions",file:J.path,metadata:void 0,resolved:{sha:T},releaseNotesUrl:`${p(this.config)}/${j.name}/releases`,changelogUrl:void 0,homepage:`${p(this.config)}/${j.name}`}}if(q)if(this.logger.info(`Latest version for ${j.name}: ${q}`),q!==j.currentVersion){let I=f(j.currentVersion,q);return this.logger.info(`Update available: ${j.name} ${j.currentVersion} \u2192 ${q} (${I})`),{name:j.name,currentVersion:j.currentVersion,newVersion:q,updateType:I,dependencyType:"github-actions",file:J.path,metadata:void 0,releaseNotesUrl:`${p(this.config)}/${j.name}/releases`,changelogUrl:void 0,homepage:`${p(this.config)}/${j.name}`}}else this.logger.info(`No update needed for ${j.name}: already at ${q}`);else this.logger.warn(`Could not fetch latest version for ${j.name}`);return null}catch(q){return this.logger.warn(`Failed to check version for action ${j.name}:`,q),null}}),O=(await Promise.all(z)).filter((J)=>J!==null);K.push(...O),this.logger.info(`Generated ${K.length} GitHub Actions updates`);let H=K.reduce((J,j)=>{if(!J.find((I)=>I.name===j.name&&I.currentVersion===j.currentVersion&&I.newVersion===j.newVersion&&I.file===j.file))J.push(j);return J},[]);return this.logger.info(`After deduplication: ${H.length} unique GitHub Actions updates`),H}async checkEnginesForUpdates(X){let{bumpEngineConstraint:$,engineUpdateType:Q,resolveEngineVersion:Y}=await import("./chunk-6qw89f68.js"),{fetchLatestActionVersion:Z}=await import("./chunk-fgec04jx.js"),K=X.flatMap((z)=>z.dependencies.filter((L)=>L.type==="engines").map((L)=>({file:z,dep:L})));if(K.length===0)return[];this.logger.info(`\u26A1 Checking ${K.length} engine constraint(s)...`);let W={npm:(z)=>this.registryClient.getLatestVersion(z),github:(z)=>Z(z)},_=K.map(async({file:z,dep:L})=>{try{let O=await Y(L.name,W);if(!O)return null;let H=$(L.currentVersion,O);if(!H)return this.logger.debug(`${L.name} ${L.currentVersion} already admits ${O}`),null;return this.logger.info(`Update available: ${L.name} ${L.currentVersion} \u2192 ${H}`),{name:L.name,currentVersion:L.currentVersion,newVersion:H,updateType:Q(L.currentVersion,H),dependencyType:"engines",file:z.path}}catch(O){return this.logger.warn(`Could not check engine ${L.name}:`,O),null}});return(await Promise.all(_)).filter((z)=>z!==null)}async checkDockerfilesForUpdates(X){let{isDockerfile:$}=await import("./chunk-awjm9n45.js"),{fetchLatestDockerImageVersion:Q}=await import("./chunk-awjm9n45.js"),Y=[],Z=X.filter((O)=>$(O.path));this.logger.info(`\uD83D\uDD0D Found ${Z.length} Dockerfile(s)`);let K=[];for(let O of Z){let H=O.dependencies.filter((J)=>J.type==="docker-image");this.logger.info(`Found ${H.length} Docker images in ${O.path}`),H.forEach((J)=>K.push({file:O,dep:J}))}this.logger.info(`\u26A1 Checking ${K.length} Docker images in parallel...`);let W=K.map(async({file:O,dep:H})=>{try{if(this.logger.info(`Checking Docker image: ${H.name}:${H.currentVersion}`),this.shouldRespectVersion(H.currentVersion))return this.logger.debug(`Skipping ${H.name} - version "${H.currentVersion}" should be respected`),null;let J=await Q(H.name,H.currentVersion,{...this.config.registries?.docker?{registries:this.config.registries.docker}:{},...this.config.packages?.includePrerelease!==void 0?{includePrerelease:this.config.packages.includePrerelease}:{}});if(J)if(this.logger.info(`Latest version for ${H.name}: ${J}`),J!==H.currentVersion){let j=f(H.currentVersion,J);return this.logger.info(`Update available: ${H.name} ${H.currentVersion} \u2192 ${J} (${j})`),{name:H.name,currentVersion:H.currentVersion,newVersion:J,updateType:j,dependencyType:"docker-image",file:O.path,metadata:void 0,releaseNotesUrl:`https://hub.docker.com/r/${H.name}/tags`,changelogUrl:void 0,homepage:`https://hub.docker.com/r/${H.name}`}}else this.logger.info(`No update needed for ${H.name}: already at ${J}`);else this.logger.warn(`Could not fetch latest version for Docker image ${H.name}`);return null}catch(J){return this.logger.warn(`Failed to check version for Docker image ${H.name}:`,J),null}}),z=(await Promise.all(W)).filter((O)=>O!==null);Y.push(...z),this.logger.info(`Generated ${Y.length} Docker image updates`);let L=Y.reduce((O,H)=>{if(!O.find((j)=>j.name===H.name&&j.currentVersion===H.currentVersion&&j.newVersion===H.newVersion&&j.file===H.file))O.push(H);return O},[]);return this.logger.info(`After deduplication: ${L.length} unique Docker image updates`),L}isNewerVersion(X,$){try{return Bun.semver.order($.replace(/^[v^~>=<@]+/,""),X.replace(/^[v^~>=<@]+/,""))>0}catch{return!1}}readDeclaredNpmVersions(){let X=new Map;try{let $=G("fs"),Y=G("path").join(this.projectPath,"package.json");if(!$.existsSync(Y))return X;let Z=JSON.parse($.readFileSync(Y,"utf8"));for(let K of["dependencies","devDependencies","peerDependencies","optionalDependencies"])for(let[W,_]of Object.entries(Z[K]??{}))if(typeof _==="string"&&!X.has(W))X.set(W,_)}catch($){this.logger.debug("Could not read declared versions from package.json:",$)}return X}compareVersionsSafe(X,$){try{let Q=$.replace(/^[v^~>=<@]+/,""),Y=X.replace(/^[v^~>=<@]+/,"");if(!/^\d+\.\d+/.test(Q)||!/^\d+\.\d+/.test(Y))return"failed";return Bun.semver.order(Q,Y)>0?"behind":"at-or-beyond"}catch{return"failed"}}async generateAllFileUpdates(X){let $=[],Q=X.filter((H)=>H.file.endsWith("package.json")&&H.dependencyType!=="engines"&&!H.file.includes(".yaml")&&!H.file.includes(".yml")&&!H.file.includes(".github/workflows/")),Y=X.filter((H)=>H.dependencyType==="engines");if(Y.length>0){let{applyEngineUpdates:H}=await import("./chunk-6qw89f68.js"),J=new Map;for(let j of Y)J.set(j.file,[...J.get(j.file)??[],j]);for(let[j,q]of J)try{let I=xX.readFileSync(j,"utf-8"),T=H(I,q);if(T===I){this.logger.warn(`\u26A0\uFE0F No engine changes written to ${j}`);continue}$.push({path:j,content:T,type:"update"})}catch(I){this.logger.warn(`Failed to update engines in ${j}:`,I)}}let Z=new Map;for(let H of Q){if(!Z.has(H.file))Z.set(H.file,[]);Z.get(H.file).push(H)}for(let[H,J]of Z)try{let j=xX.readFileSync(H,"utf-8"),q=JSON.parse(j);for(let I of J){let T=!1,M=I.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,""),B=["dependencies","devDependencies","peerDependencies","optionalDependencies"];for(let C of B)if(q[C]&&q[C][M]){let b=q[C][M].match(/^(\D*)/),R=b?b[1]:"",g=M.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`("${l}"\\s*:\\s*\\{[^}]*?)("${g}"\\s*:\\s*")([^"]+)(")([^}]*?\\})`,"gs"),V=`${R}${I.newVersion}`;j=j.replace(o,`$1$2${V}$4$5`),T=!0;break}if(!T)this.logger.warn(`Package ${M} not found in ${H}`)}$.push({path:H,content:j,type:"update"})}catch(j){this.logger.warn(`Failed to update ${H}:`,j)}let K=X.filter((H)=>{let J=H.file.toLowerCase();return(J.endsWith("deps.yaml")||J.endsWith("deps.yml")||J.endsWith("dependencies.yaml")||J.endsWith("dependencies.yml"))&&!H.file.includes(".github/workflows/")});if(K.length>0)try{let{generateDependencyFileUpdates:H}=await import("./chunk-j21m6rf6.js"),J=await H(K);$.push(...J)}catch(H){this.logger.error("Failed to generate dependency file updates:",H)}let W=X.filter((H)=>H.file.endsWith("composer.json")||H.file.endsWith("composer.lock"));if(W.length>0)try{let{generateComposerUpdates:H}=await import("./chunk-6prz7chv.js"),J=await H(W);$.push(...J)}catch(H){this.logger.error("Failed to generate Composer updates:",H)}let _=X.filter((H)=>H.file.includes(".github/workflows/"));if(_.length>0)try{let{generateGitHubActionsUpdates:H}=await import("./chunk-fgec04jx.js"),J=await H(_);$.push(...J)}catch(H){this.logger.error("Failed to generate GitHub Actions updates:",H)}let z=X.filter((H)=>H.dependencyType==="docker-image");if(z.length>0)try{let{generateDockerfileUpdates:H}=await import("./chunk-awjm9n45.js"),J=await H(z,this.config.registries?.docker);$.push(...J)}catch(H){this.logger.error("Failed to generate Dockerfile updates:",H)}let L=X.filter((H)=>H.dependencyType==="zig-dependencies");if(L.length>0)try{let{generateZigManifestUpdates:H}=await import("./chunk-nd780ymh.js"),J=await H(L);$.push(...J)}catch(H){this.logger.error("Failed to generate Zig manifest updates:",H)}let O=X.filter((H)=>H.dependencyType==="catalog");if(O.length>0)try{let{applyCatalogUpdates:H}=await import("./chunk-0w6jmcsh.js"),J=O[0].file,j=await Bun.file(XX(this.projectPath,J)).text(),q=H(j,O);if(q===j)this.logger.warn(`\u26A0\uFE0F No catalog changes written to ${J}`);else $.push({path:J,content:q,type:"update"})}catch(H){this.logger.error("Failed to generate pnpm catalog updates:",H)}return $.push(...await this.generateAdapterFileUpdates(X)),$}async generateAdapterFileUpdates(X){let{adapterNamed:$}=await import("./chunk-pg32mf9k.js"),Q=new Map;for(let K of X){if(!$(K.dependencyType))continue;let W=Q.get(K.file);if(W)W.push(K);else Q.set(K.file,[K])}let Y=[],Z=new Set;for(let[K,W]of Q){let _=$(W[0].dependencyType);if(!_)continue;Z.add(_.name);try{let z=XX(this.projectPath,K),L=await Bun.file(z).text(),O=L;for(let H of W)O=_.applyUpdate(O,{name:H.name,currentVersion:H.currentVersion,newVersion:H.newVersion,section:H.dependencyType});if(O===L){this.logger.warn(`\u26A0\uFE0F ${_.name}: no changes written to ${K}`);continue}Y.push({path:K,content:O,type:"update"})}catch(z){this.logger.error(`Failed to write ${_.name} updates to ${K}:`,z)}}return[...Y,...await this.regenerateAdapterLockfiles(Y,[...Z])]}async regenerateAdapterLockfiles(X,$){if(X.length===0||$.length===0)return[];let{regenerateLockfiles:Q}=await import("./chunk-pg32mf9k.js");try{for(let W of X)await Bun.write(XX(this.projectPath,W.path),W.content)}catch(W){return this.logger.warn(`\u26A0\uFE0F Could not stage manifests for lockfile regeneration: ${W}`),[]}let{regenerated:Y,notes:Z}=await Q(this.projectPath,$);for(let W of Z)this.logger.info(`\u2139\uFE0F ${W}`);let K=[];for(let W of Y)try{K.push({path:W,content:await Bun.file(XX(this.projectPath,W)).text(),type:"update"}),this.logger.info(`\uD83D\uDD12 Regenerated ${W}`)}catch(_){this.logger.warn(`\u26A0\uFE0F Could not read the regenerated ${W}: ${_}`)}return K}async run(){let X=await this.scanForUpdates();if(X.updates.length===0)return this.logger.info("No updates available!"),X;if(this.config.pullRequest)await this.createPullRequests(X);return X}async checkPackages(X){return this.logger.info(`Checking specific packages: ${X.join(", ")}`),this.applyStrategy(await this.registryClient.getUpdatesForPackages(X))}async checkPackagesWithPattern(X){return this.logger.info(`Checking packages with pattern: ${X}`),this.applyStrategy(await this.registryClient.getUpdatesWithPattern(X))}applyStrategy(X){let $=this.config.packages?.strategy;return $?this.filterUpdatesByStrategy(X,$):X}filterUpdatesByStrategy(X,$){if($==="all")return X;return X.filter((Q)=>yX($,Q.updateType))}async filterUpdatesByMinimumReleaseAge(X){let $=this.config.packages?.minimumReleaseAge??0,Q=this.activeRules(),Y=Q.some((z)=>z.minimumReleaseAge!==void 0);if($===0&&!Y)return X;this.logger.info(`Applying minimum release age filter (global ${$} minutes${Y?", with per-rule overrides":""}) in parallel...`);let Z=X.map(async(z)=>{try{let L=(Q.length>0?u(z,Q).minimumReleaseAge:void 0)??$;if(L===0)return z;if(await this.registryClient.meetsMinimumReleaseAge(z.name,z.newVersion,z.dependencyType,L))return z;else return this.logger.debug(`Filtered out ${z.name}@${z.newVersion} (${z.dependencyType}) \u2014 held for ${L} minutes after publication`),null}catch(L){return this.logger.warn(`Error checking release age for ${z.name}@${z.newVersion} (${z.dependencyType}), including update:`,L),z}}),W=(await Promise.all(Z)).filter((z)=>z!==null),_=X.length-W.length;if(_>0)this.logger.info(`Filtered out ${_} updates due to minimum release age requirement`);return W}groupUpdatesByConfig(X){let $=[],{grouped:Q,remaining:Y}=this.groupByRuleNames(X);$.push(...Q);let Z=[...Y];if(this.config.packages?.groups)for(let K of this.config.packages.groups){let W=[],{Glob:_}=globalThis.Bun,z=new Set;for(let O of K.patterns){let H;try{H=new _(O)}catch(J){this.logger.warn(`Invalid group pattern '${O}':`,J);continue}Z.forEach((J,j)=>{if(!z.has(j)&&H.match(J.name))W.push(J),z.add(j)})}if(z.size>0){for(let O=Z.length-1;O>=0;O--)if(z.has(O))Z.splice(O,1)}let L=W;if(K.strategy)L=this.filterUpdatesByStrategy(W,K.strategy);if(L.length>0)$.push({name:K.name,updates:L,updateType:this.getHighestUpdateType(L),title:`chore(deps): update ${K.name}`,body:`Update ${L.length} packages in ${K.name} group`})}if(Z.length>0){let K=OX(Z);$.push(...K)}return $}groupByRuleNames(X){let $=this.config.packages?.rules??[];if($.length===0)return{grouped:[],remaining:X};let Q=new Map,Y=[];for(let K of X){let W=u(K,$).groupName;if(!W){Y.push(K);continue}let _=Q.get(W);if(_)_.push(K);else Q.set(W,[K])}return{grouped:[...Q.entries()].map(([K,W])=>({name:K,updates:W,updateType:this.getHighestUpdateType(W),title:`chore(deps): update ${K}`,body:`Update ${W.length} packages in ${K} group`})),remaining:Y}}getHighestUpdateType(X){if(X.some(($)=>$.updateType==="major"))return"major";if(X.some(($)=>$.updateType==="minor"))return"minor";return"patch"}generateBranchName(X){return`buddy/update-${X.name.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}`}isSimilarPRTitle(X,$){if(X.toLowerCase()===$.toLowerCase())return!0;let Q=X.toLowerCase(),Y=$.toLowerCase(),Z=Q.includes("github actions"),K=Y.includes("github actions");if(Z&&K)return!0;if(Z!==K)return!1;let W=Q.includes("docker image"),_=Y.includes("docker image");if(W&&_)return!0;if(W!==_)return!1;let z=[/update all non-major/i,/update \d+ dependenc(y|ies)/i,/update.*\(minor\)/i,/update.*\(patch\)/i,/update.*\(major\)/i],L=z.some((H)=>H.test(X)),O=z.some((H)=>H.test($));if(L&&O){let H=Q.includes("(major)")||Q.includes("major update"),J=Y.includes("(major)")||Y.includes("major update");return H===J}if(Y.includes("update dependency ")){let H=$.match(/update dependency (\S+)/i),J=X.match(/update dependency (\S+)/i);if(H&&J)return H[1]===J[1]}if(L!==O)return!1;if(Q.includes("dependency ")&&Y.includes("dependency "))return!1;return!1}checkIfUpdatesMatch(X,$){if(!X)return!1;let Q=this.extractPackageUpdatesFromPRBody(X),Y=new Map;for(let Z of Q)Y.set(Z.name,{from:Z.currentVersion,to:Z.newVersion});for(let Z of $){let K=Y.get(Z.name);if(!K)return!1;let W=K.to.replace(/^[v^~>=<]+/,""),_=Z.newVersion.replace(/^[v^~>=<]+/,"");if(W!==_)return!1}return Y.size===$.length}shouldAutoClosePR(X,$){if(this.shouldAutoCloseForRespectLatest(X))return!0;if(this.shouldAutoCloseForIgnorePaths(X))return!0;if(this.shouldAutoCloseForRemovedFiles(X))return!0;return!1}shouldAutoCloseForRespectLatest(X){if(!(this.config.packages?.respectLatest??!0))return!1;let Q=["latest","*","main","master","develop","dev"],Y=this.extractPackageUpdatesFromPRBody(X.body);if(Y.length===0)return!1;return Y.filter((K)=>{let W=K.currentVersion.toLowerCase().trim();return Q.includes(W)}).length>0}shouldAutoCloseForIgnorePaths(X){let $=this.config.packages?.ignorePaths;if(!$||$.length===0)return!1;let Q=this.extractFilePathsFromPRBody(X.body);if(Q.length===0)return!1;let{Glob:Y}=globalThis.Bun,Z=Q.filter((K)=>{let W=K.replace(/^\.\//,"");return $.some((_)=>{try{return new Y(_).match(W)}catch(z){return this.logger.debug(`Failed to match path ${W} against pattern ${_}: ${z}`),!1}})});if(Z.length>0)return this.logger.debug(`PR #${X.number} contains files now in ignorePaths: ${Z.join(", ")}`),!0;return!1}shouldAutoCloseForRemovedFiles(X){try{let $=this.extractFilePathsFromPRBody(X.body);if($.length===0)return!1;let Q=G("fs"),Y=G("path"),Z=$.filter((K)=>{let W=Y.join(this.projectPath,K);return!Q.existsSync(W)});if(Z.length>0){if(this.logger.info(`PR #${X.number} references removed files: ${Z.join(", ")}`),this.config.packages?.ignorePaths&&this.config.packages.ignorePaths.length>0){let{Glob:O}=globalThis.Bun;if(Z.filter((J)=>{return!this.config.packages.ignorePaths.some((j)=>{try{return new O(j).match(J)}catch(q){return this.logger.warn(`Invalid glob pattern '${j}':`,q),!1}})}).length>0)return this.logger.info(`Some removed files are outside ignored paths - not auto-closing PR #${X.number}`),!1}if(Z.some((O)=>O.endsWith("composer.json")))return this.logger.info(`composer.json was removed - PR #${X.number} should be auto-closed`),!0;let W=X.body.toLowerCase(),_=W.includes("composer")||Z.some((O)=>O.includes("composer")),z=W.includes("package.json")||Z.some((O)=>O.includes("package.json")),L=Z.some((O)=>O.endsWith("deps.yaml")||O.endsWith("deps.yml")||O.endsWith("dependencies.yaml")||O.endsWith("dependencies.yml"));if(_||z||L)return this.logger.info(`PR #${X.number} is about removed dependency system - should be auto-closed`),!0}return!1}catch($){return this.logger.debug(`Failed to check for removed files in PR #${X.number}: ${$}`),!1}}get events(){if(!this.eventBus){this.eventBus=new gX(this.logger);for(let X of lX(this.config.notifications))this.eventBus.register(X)}return this.eventBus}async createGitProvider(){let X=this.config.repository;if(!X?.owner||!X.name)return this.logger.warn("\u26A0\uFE0F Repository owner and name are required for pull request operations"),null;try{return await QX({provider:X.provider,owner:X.owner,name:X.name,...X.apiUrl?{apiUrl:X.apiUrl}:{}},{logger:this.logger})}catch($){return this.logger.warn(`\u26A0\uFE0F ${$X($)}`),null}}async queueAutoMerge(X,$,Q,Y){let Z=SX(Q,Y,this.config);if(!Z.eligible){this.logger.debug(`\uD83D\uDD00 PR #${$.number} not auto-merged: ${Z.reason}`);return}let{strategy:K}=d(this.config);if(!i(X,"nativeAutoMerge","enableAutoMerge")){this.logger.info(`\uD83D\uDD00 PR #${$.number} qualifies for auto-merge but this provider has no merge queue; update-check will merge it once checks pass`);return}try{if(await X.enableAutoMerge($.number,K))this.logger.success(`\uD83D\uDD00 PR #${$.number} queued for auto-merge (${Z.reason})`);else this.logger.info(`\uD83D\uDD00 PR #${$.number} qualifies for auto-merge but the repository cannot queue it; update-check will merge it once checks pass`)}catch(W){this.logger.warn(`\u26A0\uFE0F Failed to queue auto-merge for PR #${$.number}: ${W}`)}}async mergeEligiblePullRequests(X=!1){let $=d(this.config);if(!$.enabled)return[];let Q=await this.createGitProvider();if(!Q)return[];let Y=[],Z=await Q.getPullRequests("open");for(let K of Z.filter((W)=>v(W.head))){let W=$.requireGreenCI&&Q.getPullRequestChecksState?await Q.getPullRequestChecksState(K.number):"none",_=W==="success"||W==="none",z=VX({number:K.number,title:K.title,body:K.body,head:K.head,labels:K.labels,draft:K.draft},this.config,_);if(!z.eligible){this.logger.debug(`\uD83D\uDD00 PR #${K.number} not merged: ${z.reason}`);continue}if(X){this.logger.info(`\uD83D\uDD00 [DRY RUN] Would merge PR #${K.number} (${z.reason})`),Y.push(K.number);continue}try{await Q.mergePullRequest(K.number,$.strategy),this.logger.success(`\uD83D\uDD00 Merged PR #${K.number}: ${z.reason}`),await this.events.emit("pr.merged",{number:K.number,title:K.title,strategy:$.strategy}),Y.push(K.number)}catch(L){this.logger.warn(`\u26A0\uFE0F Failed to merge PR #${K.number}: ${L}`)}}return Y}isPlausibleRepoPath(X){if(!X||/[\s()[\]!`]|:\/\//.test(X))return!1;return/^[\w@.-]+(?:\/[\w@.-]+)*$/.test(X)}extractFilePathsFromPRBody(X){let $=c(X);if($)return kX($);let Q=[],Y=/\|\s*\[[^\]]+\]\([^)]*\)\s*\|[^|]*\|\s*\*\*([^*]+)\*\*\s*\|/g,Z;while((Z=Y.exec(X))!==null){let z=Z[1].trim();if(this.isPlausibleRepoPath(z)&&!Q.includes(z))Q.push(z)}let K=/\*\*([^*]+\.(?:json|yaml|yml|lock))\*\*/g;while((Z=K.exec(X))!==null){let z=Z[1].trim();if(this.isPlausibleRepoPath(z)&&!Q.includes(z))Q.push(z)}let W=/\|[^|]+\|[^|]+\|([^|]+)\|[^|]*\|/g;while((Z=W.exec(X))!==null){let z=Z[1].trim();if(this.isPlausibleRepoPath(z)&&(z.includes("/")||/\.(?:json|yaml|yml|lock)$/.test(z))&&!Q.includes(z))Q.push(z)}let _=/(?:^|\s)([\w-]+(?:\/[\w.-]+)*\/[\w.-]+\.(?:json|yaml|yml|lock))(?:\s|$)/gm;while((Z=_.exec(X))!==null){let z=Z[1].trim();if(this.isPlausibleRepoPath(z)&&!Q.includes(z))Q.push(z)}return Q}extractPackagesFromPRBody(X){let $=c(X);if($)return[...new Set($.updates.map((K)=>K.name))];let Q=[],Y=X.match(/\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|/g);if(Y)for(let K of Y){let W=K.match(/\[([^\]]+)\]\([^)]*\)/);if(W)Q.push(W[1])}let Z=X.match(/<summary>([^<]+)<\/summary>/g);if(Z)for(let K of Z){let W=K.replace(/<summary>/,"").replace(/<\/summary>/,"").trim();if(W&&!Q.includes(W))Q.push(W)}return Q}extractPackageUpdatesFromPRBody(X){let $=c(X);if($)return vX($);let Q=[],Y=new Set,Z=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`?[v^~>=]*([^`|\s]+)`?\s*(?:->|\u2192)\s*`?[v^~>=]*([^`|\s]+)`?\]?/g,K;while((K=Z.exec(X))!==null){let[,W,_,z]=K;if(!Y.has(W))Y.add(W),Q.push({name:W,currentVersion:_,newVersion:z})}return Q}getConfig(){return this.config}getProjectPath(){return this.projectPath}async checkAndCloseObsoletePRs(X,$=!1){try{this.logger.info("\uD83D\uDD0D Scanning for obsolete PRs due to removed dependency files...");let Y=(await X.getPullRequests("open")).filter((K)=>v(K.head)||K.author==="github-actions[bot]"&&K.labels.includes("dependencies"));this.logger.info(`Found ${Y.length} dependency-related PRs to check`);let Z=0;for(let K of Y)try{if(this.shouldAutoCloseForRemovedFiles(K))if(this.logger.info(`\uD83D\uDD12 PR #${K.number} should be auto-closed: ${K.title}`),$)this.logger.info(`\uD83D\uDD0D [DRY RUN] Would auto-close PR #${K.number}`),Z++;else try{let _=this.generateCloseReason(K);try{await X.createComment(K.number,_)}catch(z){this.logger.warn(`\u26A0\uFE0F Could not add close reason comment to PR #${K.number}:`,z)}if(await X.closePullRequest(K.number),await this.events.emit("pr.closed",{number:K.number,title:K.title,reason:"obsolete \u2014 its dependency files no longer exist"}),v(K.head))try{await X.deleteBranch(K.head),this.logger.success(`\u2705 Auto-closed PR #${K.number} and deleted branch ${K.head}`)}catch(z){this.logger.warn(`\u26A0\uFE0F Auto-closed PR #${K.number} but failed to delete branch: ${z}`)}else this.logger.success(`\u2705 Auto-closed PR #${K.number}`);Z++}catch(_){this.logger.error(`\u274C Failed to auto-close PR #${K.number}:`,_)}}catch(W){this.logger.warn(`\u26A0\uFE0F Error checking PR #${K.number}:`,W)}if(Z>0)this.logger.success(`\u2705 ${$?"Would auto-close":"Auto-closed"} ${Z} obsolete PR(s)`);else this.logger.info("\uD83D\uDCCB No obsolete PRs found")}catch(Q){throw this.logger.error("Failed to check for obsolete PRs:",Q),Q}}async checkAndCloseSatisfiedPRs(X,$=!1){try{this.logger.info("\uD83D\uDD0D Checking for PRs where dependencies are already at target version...");let Y=(await X.getPullRequests("open")).filter((O)=>v(O.head)||O.author==="github-actions[bot]"&&O.labels.includes("dependencies"));if(this.logger.info(`Found ${Y.length} buddy dependency PRs to validate`),Y.length===0){this.logger.info("\uD83D\uDCCB No buddy PRs to check");return}let Z=0,K={...this.config,packages:{...this.config.packages,strategy:"all"}},_=await new WX(K,this.projectPath).scanForUpdates(),z=new Map;for(let O of _.updates)z.set(O.name,O);let L=this.readDeclaredNpmVersions();if(_.updates.length===0){this.logger.warn("\u26A0\uFE0F Scan returned 0 updates \u2014 skipping satisfied PR check to avoid false-positive closures");return}for(let O of Y)try{let H=this.extractPackageUpdatesFromPRBody(O.body);if(H.length===0){this.logger.debug(`PR #${O.number}: Could not extract package updates, skipping`);continue}let J=O.body.match(/\*\*Total\*\*\s*\|\s*\*\*(\d+)\*\*/),j=J?Number.parseInt(J[1],10):0;if(j>0&&H.length<j){this.logger.debug(`PR #${O.number}: Extracted ${H.length}/${j} updates \u2014 incomplete extraction, skipping satisfied check`);continue}let q=0,I=0,T=0;for(let B of H){let C=z.get(B.name);if(!C){let b=L.get(B.name);if(b){let R=this.compareVersionsSafe(b,B.newVersion);if(R==="at-or-beyond"){this.logger.debug(`PR #${O.number}: ${B.name} declared at ${b}, at or beyond ${B.newVersion}`),q++;continue}if(R==="behind"){this.logger.debug(`PR #${O.number}: ${B.name} declared at ${b}, still behind ${B.newVersion} \u2014 the scan missed it`),I++;continue}}this.logger.debug(`PR #${O.number}: ${B.name} not in current scan and not declared (unverifiable)`),T++;continue}if(C.newVersion===B.newVersion){this.logger.debug(`PR #${O.number}: ${B.name} still needs update to ${B.newVersion}`),I++;continue}let D=this.compareVersionsSafe(C.currentVersion,B.newVersion);if(D==="at-or-beyond")this.logger.debug(`PR #${O.number}: ${B.name} already at or beyond ${B.newVersion}`),q++;else if(D==="behind")this.logger.debug(`PR #${O.number}: ${B.name} still behind ${B.newVersion}`),I++;else this.logger.debug(`PR #${O.number}: ${B.name} version comparison inconclusive`),T++}let M=I===0&&T===0&&q>0;if(this.logger.debug(`PR #${O.number}: verified-satisfied=${q}, still-needed=${I}, unverifiable=${T} \u2192 ${M?"CLOSE":"KEEP"}`),M)if(this.logger.info(`\u2705 PR #${O.number} is satisfied (dependencies at target version): ${O.title}`),$)this.logger.info(`\uD83D\uDD0D [DRY RUN] Would close PR #${O.number}`),Z++;else try{let B=H.filter((D)=>{let R=z.get(D.name)?.currentVersion??L.get(D.name);if(!R)return!1;return this.compareVersionsSafe(R,D.newVersion)==="at-or-beyond"}),C=`\uD83E\uDD16 **Auto-closing satisfied PR**
|
|
89
|
+
${j}`)}this.logger.success(`\u2705 Completed PR creation for ${X.groups.length} group(s) in ${J}ms`)}catch(Q){throw this.logger.error("Failed to create pull requests:",Q),Q}}shouldRespectVersion(X){if(!(this.config.packages?.respectLatest??!0))return!1;let Q=["latest","*","main","master","develop","dev"],Y=X.toLowerCase().trim();return Q.includes(Y)}async checkDependencyFilesForUpdates(X){let{isDependencyFile:$}=await import("./chunk-j21m6rf6.js"),{resolveDependencyFile:Q}=await import("./chunk-1znpbjrv.js"),Y=[],Z=X.filter((_)=>$(_.path));this.logger.info(`\u26A1 Checking ${Z.length} dependency files in parallel...`);let K=Z.map(async(_)=>{try{this.logger.info(`Checking dependency file: ${_.path}`);let z=await Q(_.path),L=[];for(let O of z.allDependencies||[]){if(this.shouldRespectVersion(O.constraint)){this.logger.debug(`Skipping ${O.name} - version "${O.constraint}" should be respected`);continue}if(O.constraint!==O.version&&O.version){let H=O.constraint.replace(/^[\^~>=<]+/,"");if(!this.isNewerVersion(H,O.version)){this.logger.debug(`Skipping ${O.name} - latest (${O.version}) is not newer than constraint (${H})`);continue}let J=f(H,O.version),j=O.version;L.push({name:O.name,currentVersion:O.constraint,newVersion:j,updateType:J,dependencyType:"dependencies",file:_.path,metadata:void 0,releaseNotesUrl:void 0,changelogUrl:void 0,homepage:void 0})}}return L}catch(z){return this.logger.error(`Failed to check dependency file ${_.path}:`,z),[]}}),W=await Promise.all(K);return Y.push(...W.flat()),Y}async checkZigForUpdates(X){let{isZigManifest:$}=await import("./chunk-nd780ymh.js"),{fetchLatestZigVersion:Q,fetchZigHash:Y,isZigAvailable:Z,parseZigSource:K,zigUrlForVersion:W}=await import("./chunk-jkn2sdm0.js"),_=X.filter((H)=>$(H.path));if(_.length===0)return[];if(!await Z())return this.logger.warn("\u26A0\uFE0F Found Zig manifests but the zig toolchain is not available. "+"Skipping Zig updates: their content-addressed hashes cannot be recomputed without `zig fetch`."),[];let z=m.env.GITHUB_TOKEN||m.env.BUDDY_TOKEN||m.env.BUDDY_BOT_TOKEN,L=_.flatMap((H)=>H.dependencies.filter((J)=>J.type==="zig-dependencies").map((J)=>({file:H,dep:J})));return this.logger.info(`\u26A1 Checking ${L.length} Zig dependencies...`),(await Promise.all(L.map(async({file:H,dep:J})=>{let j=J.metadata?.url;if(!j)return this.logger.debug(`Skipping ${J.name}: no URL recorded`),null;let q=K(j);if(!q)return this.logger.debug(`Skipping ${J.name}: only GitHub-hosted Zig dependencies can be checked`),null;let I=await Q(q,z);if(!I||I===J.currentVersion)return null;let T=W(j,I),M=await Y(T);if(!M)return this.logger.warn(`\u26A0\uFE0F Skipping ${J.name} ${J.currentVersion} \u2192 ${I}: could not compute its package hash`),null;return this.logger.info(`\uD83D\uDCE6 ${J.name}: ${J.currentVersion} \u2192 ${I}`),{name:J.name,currentVersion:J.currentVersion,newVersion:I,updateType:f(J.currentVersion,I),dependencyType:"zig-dependencies",file:H.path,resolved:{url:T,hash:M}}}))).filter((H)=>H!==null)}async checkGitHubActionsForUpdates(X){let{fetchActionTagCommit:$,fetchLatestActionVersion:Q,isGitHubActionsFile:Y,sameActionVersion:Z}=await import("./chunk-fgec04jx.js"),K=[],W=X.filter((J)=>Y(J.path));this.logger.info(`\uD83D\uDD0D Found ${W.length} GitHub Actions workflow files`);let _=[];for(let J of W){let j=J.dependencies.filter((q)=>q.type==="github-actions");this.logger.info(`Found ${j.length} GitHub Actions in ${J.path}`),j.forEach((q)=>_.push({file:J,dep:q}))}this.logger.info(`\u26A1 Checking ${_.length} GitHub Actions in parallel...`);let z=_.map(async({file:J,dep:j})=>{try{this.logger.info(`Checking action: ${j.name}@${j.currentVersion}`);let q=await Q(j.name);if(q&&j.metadata?.pinnedSha){let I=j.metadata.pinnedVersion;if(!I)return this.logger.info(`Skipping ${j.name}@${j.currentVersion}: a SHA pin without a version comment cannot be compared`),null;if(Z(I,q))return this.logger.info(`No update needed for ${j.name}: already pinned to ${q}`),null;let T=await $(j.name,q);if(!T)return this.logger.warn(`Could not resolve ${j.name}@${q} to a commit; leaving the SHA pin alone`),null;let M=f(I,q);return this.logger.info(`Update available: ${j.name} ${I} \u2192 ${q} (${M}, pinned)`),{name:j.name,currentVersion:j.currentVersion,newVersion:q,updateType:M,dependencyType:"github-actions",file:J.path,metadata:void 0,resolved:{sha:T},releaseNotesUrl:`${p(this.config)}/${j.name}/releases`,changelogUrl:void 0,homepage:`${p(this.config)}/${j.name}`}}if(q)if(this.logger.info(`Latest version for ${j.name}: ${q}`),q!==j.currentVersion){let I=f(j.currentVersion,q);return this.logger.info(`Update available: ${j.name} ${j.currentVersion} \u2192 ${q} (${I})`),{name:j.name,currentVersion:j.currentVersion,newVersion:q,updateType:I,dependencyType:"github-actions",file:J.path,metadata:void 0,releaseNotesUrl:`${p(this.config)}/${j.name}/releases`,changelogUrl:void 0,homepage:`${p(this.config)}/${j.name}`}}else this.logger.info(`No update needed for ${j.name}: already at ${q}`);else this.logger.warn(`Could not fetch latest version for ${j.name}`);return null}catch(q){return this.logger.warn(`Failed to check version for action ${j.name}:`,q),null}}),O=(await Promise.all(z)).filter((J)=>J!==null);K.push(...O),this.logger.info(`Generated ${K.length} GitHub Actions updates`);let H=K.reduce((J,j)=>{if(!J.find((I)=>I.name===j.name&&I.currentVersion===j.currentVersion&&I.newVersion===j.newVersion&&I.file===j.file))J.push(j);return J},[]);return this.logger.info(`After deduplication: ${H.length} unique GitHub Actions updates`),H}async checkEnginesForUpdates(X){let{bumpEngineConstraint:$,engineUpdateType:Q,resolveEngineVersion:Y}=await import("./chunk-6qw89f68.js"),{fetchLatestActionVersion:Z}=await import("./chunk-fgec04jx.js"),K=X.flatMap((z)=>z.dependencies.filter((L)=>L.type==="engines").map((L)=>({file:z,dep:L})));if(K.length===0)return[];this.logger.info(`\u26A1 Checking ${K.length} engine constraint(s)...`);let W={npm:(z)=>this.registryClient.getLatestVersion(z),github:(z)=>Z(z)},_=K.map(async({file:z,dep:L})=>{try{let O=await Y(L.name,W);if(!O)return null;let H=$(L.currentVersion,O);if(!H)return this.logger.debug(`${L.name} ${L.currentVersion} already admits ${O}`),null;return this.logger.info(`Update available: ${L.name} ${L.currentVersion} \u2192 ${H}`),{name:L.name,currentVersion:L.currentVersion,newVersion:H,updateType:Q(L.currentVersion,H),dependencyType:"engines",file:z.path}}catch(O){return this.logger.warn(`Could not check engine ${L.name}:`,O),null}});return(await Promise.all(_)).filter((z)=>z!==null)}async checkDockerfilesForUpdates(X){let{isDockerfile:$}=await import("./chunk-awjm9n45.js"),{fetchLatestDockerImageVersion:Q}=await import("./chunk-awjm9n45.js"),Y=[],Z=X.filter((O)=>$(O.path));this.logger.info(`\uD83D\uDD0D Found ${Z.length} Dockerfile(s)`);let K=[];for(let O of Z){let H=O.dependencies.filter((J)=>J.type==="docker-image");this.logger.info(`Found ${H.length} Docker images in ${O.path}`),H.forEach((J)=>K.push({file:O,dep:J}))}this.logger.info(`\u26A1 Checking ${K.length} Docker images in parallel...`);let W=K.map(async({file:O,dep:H})=>{try{if(this.logger.info(`Checking Docker image: ${H.name}:${H.currentVersion}`),this.shouldRespectVersion(H.currentVersion))return this.logger.debug(`Skipping ${H.name} - version "${H.currentVersion}" should be respected`),null;let J=await Q(H.name,H.currentVersion,{...this.config.registries?.docker?{registries:this.config.registries.docker}:{},...this.config.packages?.includePrerelease!==void 0?{includePrerelease:this.config.packages.includePrerelease}:{}});if(J)if(this.logger.info(`Latest version for ${H.name}: ${J}`),J!==H.currentVersion){let j=f(H.currentVersion,J);return this.logger.info(`Update available: ${H.name} ${H.currentVersion} \u2192 ${J} (${j})`),{name:H.name,currentVersion:H.currentVersion,newVersion:J,updateType:j,dependencyType:"docker-image",file:O.path,metadata:void 0,releaseNotesUrl:`https://hub.docker.com/r/${H.name}/tags`,changelogUrl:void 0,homepage:`https://hub.docker.com/r/${H.name}`}}else this.logger.info(`No update needed for ${H.name}: already at ${J}`);else this.logger.warn(`Could not fetch latest version for Docker image ${H.name}`);return null}catch(J){return this.logger.warn(`Failed to check version for Docker image ${H.name}:`,J),null}}),z=(await Promise.all(W)).filter((O)=>O!==null);Y.push(...z),this.logger.info(`Generated ${Y.length} Docker image updates`);let L=Y.reduce((O,H)=>{if(!O.find((j)=>j.name===H.name&&j.currentVersion===H.currentVersion&&j.newVersion===H.newVersion&&j.file===H.file))O.push(H);return O},[]);return this.logger.info(`After deduplication: ${L.length} unique Docker image updates`),L}isNewerVersion(X,$){try{return Bun.semver.order($.replace(/^[v^~>=<@]+/,""),X.replace(/^[v^~>=<@]+/,""))>0}catch{return!1}}readDeclaredNpmVersions(){let X=new Map;try{let $=G("fs"),Y=G("path").join(this.projectPath,"package.json");if(!$.existsSync(Y))return X;let Z=JSON.parse($.readFileSync(Y,"utf8"));for(let K of["dependencies","devDependencies","peerDependencies","optionalDependencies"])for(let[W,_]of Object.entries(Z[K]??{}))if(typeof _==="string"&&!X.has(W))X.set(W,_)}catch($){this.logger.debug("Could not read declared versions from package.json:",$)}return X}compareVersionsSafe(X,$){try{let Q=$.replace(/^[v^~>=<@]+/,""),Y=X.replace(/^[v^~>=<@]+/,"");if(!/^\d+\.\d+/.test(Q)||!/^\d+\.\d+/.test(Y))return"failed";return Bun.semver.order(Q,Y)>0?"behind":"at-or-beyond"}catch{return"failed"}}async generateAllFileUpdates(X){let $=[],Q=X.filter((H)=>H.file.endsWith("package.json")&&H.dependencyType!=="engines"&&!H.file.includes(".yaml")&&!H.file.includes(".yml")&&!H.file.includes(".github/workflows/")),Y=X.filter((H)=>H.dependencyType==="engines");if(Y.length>0){let{applyEngineUpdates:H}=await import("./chunk-6qw89f68.js"),J=new Map;for(let j of Y)J.set(j.file,[...J.get(j.file)??[],j]);for(let[j,q]of J)try{let I=xX.readFileSync(j,"utf-8"),T=H(I,q);if(T===I){this.logger.warn(`\u26A0\uFE0F No engine changes written to ${j}`);continue}$.push({path:j,content:T,type:"update"})}catch(I){this.logger.warn(`Failed to update engines in ${j}:`,I)}}let Z=new Map;for(let H of Q){if(!Z.has(H.file))Z.set(H.file,[]);Z.get(H.file).push(H)}for(let[H,J]of Z)try{let j=xX.readFileSync(H,"utf-8"),q=JSON.parse(j);for(let I of J){let T=!1,M=I.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,""),B=["dependencies","devDependencies","peerDependencies","optionalDependencies"];for(let C of B)if(q[C]&&q[C][M]){let b=q[C][M].match(/^(\D*)/),R=b?b[1]:"",g=M.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`("${l}"\\s*:\\s*\\{[^}]*?)("${g}"\\s*:\\s*")([^"]+)(")([^}]*?\\})`,"gs"),V=`${R}${I.newVersion}`;j=j.replace(o,`$1$2${V}$4$5`),T=!0;break}if(!T)this.logger.warn(`Package ${M} not found in ${H}`)}$.push({path:H,content:j,type:"update"})}catch(j){this.logger.warn(`Failed to update ${H}:`,j)}let K=X.filter((H)=>{let J=H.file.toLowerCase();return(J.endsWith("deps.yaml")||J.endsWith("deps.yml")||J.endsWith("dependencies.yaml")||J.endsWith("dependencies.yml"))&&!H.file.includes(".github/workflows/")});if(K.length>0)try{let{generateDependencyFileUpdates:H}=await import("./chunk-j21m6rf6.js"),J=await H(K);$.push(...J)}catch(H){this.logger.error("Failed to generate dependency file updates:",H)}let W=X.filter((H)=>H.file.endsWith("composer.json")||H.file.endsWith("composer.lock"));if(W.length>0)try{let{generateComposerUpdates:H}=await import("./chunk-6prz7chv.js"),J=await H(W);$.push(...J)}catch(H){this.logger.error("Failed to generate Composer updates:",H)}let _=X.filter((H)=>H.file.includes(".github/workflows/"));if(_.length>0)try{let{generateGitHubActionsUpdates:H}=await import("./chunk-fgec04jx.js"),J=await H(_);$.push(...J)}catch(H){this.logger.error("Failed to generate GitHub Actions updates:",H)}let z=X.filter((H)=>H.dependencyType==="docker-image");if(z.length>0)try{let{generateDockerfileUpdates:H}=await import("./chunk-awjm9n45.js"),J=await H(z,this.config.registries?.docker);$.push(...J)}catch(H){this.logger.error("Failed to generate Dockerfile updates:",H)}let L=X.filter((H)=>H.dependencyType==="zig-dependencies");if(L.length>0)try{let{generateZigManifestUpdates:H}=await import("./chunk-nd780ymh.js"),J=await H(L);$.push(...J)}catch(H){this.logger.error("Failed to generate Zig manifest updates:",H)}let O=X.filter((H)=>H.dependencyType==="catalog");if(O.length>0)try{let{applyCatalogUpdates:H}=await import("./chunk-z0rsmhe4.js"),J=O[0].file,j=await Bun.file(XX(this.projectPath,J)).text(),q=H(j,O);if(q===j)this.logger.warn(`\u26A0\uFE0F No catalog changes written to ${J}`);else $.push({path:J,content:q,type:"update"})}catch(H){this.logger.error("Failed to generate pnpm catalog updates:",H)}return $.push(...await this.generateAdapterFileUpdates(X)),$}async generateAdapterFileUpdates(X){let{adapterNamed:$}=await import("./chunk-xn2960z7.js"),Q=new Map;for(let K of X){if(!$(K.dependencyType))continue;let W=Q.get(K.file);if(W)W.push(K);else Q.set(K.file,[K])}let Y=[],Z=new Set;for(let[K,W]of Q){let _=$(W[0].dependencyType);if(!_)continue;Z.add(_.name);try{let z=XX(this.projectPath,K),L=await Bun.file(z).text(),O=L;for(let H of W)O=_.applyUpdate(O,{name:H.name,currentVersion:H.currentVersion,newVersion:H.newVersion,section:H.dependencyType});if(O===L){this.logger.warn(`\u26A0\uFE0F ${_.name}: no changes written to ${K}`);continue}Y.push({path:K,content:O,type:"update"})}catch(z){this.logger.error(`Failed to write ${_.name} updates to ${K}:`,z)}}return[...Y,...await this.regenerateAdapterLockfiles(Y,[...Z])]}async regenerateAdapterLockfiles(X,$){if(X.length===0||$.length===0)return[];let{regenerateLockfiles:Q}=await import("./chunk-xn2960z7.js");try{for(let W of X)await Bun.write(XX(this.projectPath,W.path),W.content)}catch(W){return this.logger.warn(`\u26A0\uFE0F Could not stage manifests for lockfile regeneration: ${W}`),[]}let{regenerated:Y,notes:Z}=await Q(this.projectPath,$);for(let W of Z)this.logger.info(`\u2139\uFE0F ${W}`);let K=[];for(let W of Y)try{K.push({path:W,content:await Bun.file(XX(this.projectPath,W)).text(),type:"update"}),this.logger.info(`\uD83D\uDD12 Regenerated ${W}`)}catch(_){this.logger.warn(`\u26A0\uFE0F Could not read the regenerated ${W}: ${_}`)}return K}async run(){let X=await this.scanForUpdates();if(X.updates.length===0)return this.logger.info("No updates available!"),X;if(this.config.pullRequest)await this.createPullRequests(X);return X}async checkPackages(X){return this.logger.info(`Checking specific packages: ${X.join(", ")}`),this.applyStrategy(await this.registryClient.getUpdatesForPackages(X))}async checkPackagesWithPattern(X){return this.logger.info(`Checking packages with pattern: ${X}`),this.applyStrategy(await this.registryClient.getUpdatesWithPattern(X))}applyStrategy(X){let $=this.config.packages?.strategy;return $?this.filterUpdatesByStrategy(X,$):X}filterUpdatesByStrategy(X,$){if($==="all")return X;return X.filter((Q)=>yX($,Q.updateType))}async filterUpdatesByMinimumReleaseAge(X){let $=this.config.packages?.minimumReleaseAge??0,Q=this.activeRules(),Y=Q.some((z)=>z.minimumReleaseAge!==void 0);if($===0&&!Y)return X;this.logger.info(`Applying minimum release age filter (global ${$} minutes${Y?", with per-rule overrides":""}) in parallel...`);let Z=X.map(async(z)=>{try{let L=(Q.length>0?u(z,Q).minimumReleaseAge:void 0)??$;if(L===0)return z;if(await this.registryClient.meetsMinimumReleaseAge(z.name,z.newVersion,z.dependencyType,L))return z;else return this.logger.debug(`Filtered out ${z.name}@${z.newVersion} (${z.dependencyType}) \u2014 held for ${L} minutes after publication`),null}catch(L){return this.logger.warn(`Error checking release age for ${z.name}@${z.newVersion} (${z.dependencyType}), including update:`,L),z}}),W=(await Promise.all(Z)).filter((z)=>z!==null),_=X.length-W.length;if(_>0)this.logger.info(`Filtered out ${_} updates due to minimum release age requirement`);return W}groupUpdatesByConfig(X){let $=[],{grouped:Q,remaining:Y}=this.groupByRuleNames(X);$.push(...Q);let Z=[...Y];if(this.config.packages?.groups)for(let K of this.config.packages.groups){let W=[],{Glob:_}=globalThis.Bun,z=new Set;for(let O of K.patterns){let H;try{H=new _(O)}catch(J){this.logger.warn(`Invalid group pattern '${O}':`,J);continue}Z.forEach((J,j)=>{if(!z.has(j)&&H.match(J.name))W.push(J),z.add(j)})}if(z.size>0){for(let O=Z.length-1;O>=0;O--)if(z.has(O))Z.splice(O,1)}let L=W;if(K.strategy)L=this.filterUpdatesByStrategy(W,K.strategy);if(L.length>0)$.push({name:K.name,updates:L,updateType:this.getHighestUpdateType(L),title:`chore(deps): update ${K.name}`,body:`Update ${L.length} packages in ${K.name} group`})}if(Z.length>0){let K=OX(Z);$.push(...K)}return $}groupByRuleNames(X){let $=this.config.packages?.rules??[];if($.length===0)return{grouped:[],remaining:X};let Q=new Map,Y=[];for(let K of X){let W=u(K,$).groupName;if(!W){Y.push(K);continue}let _=Q.get(W);if(_)_.push(K);else Q.set(W,[K])}return{grouped:[...Q.entries()].map(([K,W])=>({name:K,updates:W,updateType:this.getHighestUpdateType(W),title:`chore(deps): update ${K}`,body:`Update ${W.length} packages in ${K} group`})),remaining:Y}}getHighestUpdateType(X){if(X.some(($)=>$.updateType==="major"))return"major";if(X.some(($)=>$.updateType==="minor"))return"minor";return"patch"}generateBranchName(X){return`buddy/update-${X.name.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}`}isSimilarPRTitle(X,$){if(X.toLowerCase()===$.toLowerCase())return!0;let Q=X.toLowerCase(),Y=$.toLowerCase(),Z=Q.includes("github actions"),K=Y.includes("github actions");if(Z&&K)return!0;if(Z!==K)return!1;let W=Q.includes("docker image"),_=Y.includes("docker image");if(W&&_)return!0;if(W!==_)return!1;let z=[/update all non-major/i,/update \d+ dependenc(y|ies)/i,/update.*\(minor\)/i,/update.*\(patch\)/i,/update.*\(major\)/i],L=z.some((H)=>H.test(X)),O=z.some((H)=>H.test($));if(L&&O){let H=Q.includes("(major)")||Q.includes("major update"),J=Y.includes("(major)")||Y.includes("major update");return H===J}if(Y.includes("update dependency ")){let H=$.match(/update dependency (\S+)/i),J=X.match(/update dependency (\S+)/i);if(H&&J)return H[1]===J[1]}if(L!==O)return!1;if(Q.includes("dependency ")&&Y.includes("dependency "))return!1;return!1}checkIfUpdatesMatch(X,$){if(!X)return!1;let Q=this.extractPackageUpdatesFromPRBody(X),Y=new Map;for(let Z of Q)Y.set(Z.name,{from:Z.currentVersion,to:Z.newVersion});for(let Z of $){let K=Y.get(Z.name);if(!K)return!1;let W=K.to.replace(/^[v^~>=<]+/,""),_=Z.newVersion.replace(/^[v^~>=<]+/,"");if(W!==_)return!1}return Y.size===$.length}shouldAutoClosePR(X,$){if(this.shouldAutoCloseForRespectLatest(X))return!0;if(this.shouldAutoCloseForIgnorePaths(X))return!0;if(this.shouldAutoCloseForRemovedFiles(X))return!0;return!1}shouldAutoCloseForRespectLatest(X){if(!(this.config.packages?.respectLatest??!0))return!1;let Q=["latest","*","main","master","develop","dev"],Y=this.extractPackageUpdatesFromPRBody(X.body);if(Y.length===0)return!1;return Y.filter((K)=>{let W=K.currentVersion.toLowerCase().trim();return Q.includes(W)}).length>0}shouldAutoCloseForIgnorePaths(X){let $=this.config.packages?.ignorePaths;if(!$||$.length===0)return!1;let Q=this.extractFilePathsFromPRBody(X.body);if(Q.length===0)return!1;let{Glob:Y}=globalThis.Bun,Z=Q.filter((K)=>{let W=K.replace(/^\.\//,"");return $.some((_)=>{try{return new Y(_).match(W)}catch(z){return this.logger.debug(`Failed to match path ${W} against pattern ${_}: ${z}`),!1}})});if(Z.length>0)return this.logger.debug(`PR #${X.number} contains files now in ignorePaths: ${Z.join(", ")}`),!0;return!1}shouldAutoCloseForRemovedFiles(X){try{let $=this.extractFilePathsFromPRBody(X.body);if($.length===0)return!1;let Q=G("fs"),Y=G("path"),Z=$.filter((K)=>{let W=Y.join(this.projectPath,K);return!Q.existsSync(W)});if(Z.length>0){if(this.logger.info(`PR #${X.number} references removed files: ${Z.join(", ")}`),this.config.packages?.ignorePaths&&this.config.packages.ignorePaths.length>0){let{Glob:O}=globalThis.Bun;if(Z.filter((J)=>{return!this.config.packages.ignorePaths.some((j)=>{try{return new O(j).match(J)}catch(q){return this.logger.warn(`Invalid glob pattern '${j}':`,q),!1}})}).length>0)return this.logger.info(`Some removed files are outside ignored paths - not auto-closing PR #${X.number}`),!1}if(Z.some((O)=>O.endsWith("composer.json")))return this.logger.info(`composer.json was removed - PR #${X.number} should be auto-closed`),!0;let W=X.body.toLowerCase(),_=W.includes("composer")||Z.some((O)=>O.includes("composer")),z=W.includes("package.json")||Z.some((O)=>O.includes("package.json")),L=Z.some((O)=>O.endsWith("deps.yaml")||O.endsWith("deps.yml")||O.endsWith("dependencies.yaml")||O.endsWith("dependencies.yml"));if(_||z||L)return this.logger.info(`PR #${X.number} is about removed dependency system - should be auto-closed`),!0}return!1}catch($){return this.logger.debug(`Failed to check for removed files in PR #${X.number}: ${$}`),!1}}get events(){if(!this.eventBus){this.eventBus=new gX(this.logger);for(let X of lX(this.config.notifications))this.eventBus.register(X)}return this.eventBus}async createGitProvider(){let X=this.config.repository;if(!X?.owner||!X.name)return this.logger.warn("\u26A0\uFE0F Repository owner and name are required for pull request operations"),null;try{return await QX({provider:X.provider,owner:X.owner,name:X.name,...X.apiUrl?{apiUrl:X.apiUrl}:{}},{logger:this.logger})}catch($){return this.logger.warn(`\u26A0\uFE0F ${$X($)}`),null}}async queueAutoMerge(X,$,Q,Y){let Z=SX(Q,Y,this.config);if(!Z.eligible){this.logger.debug(`\uD83D\uDD00 PR #${$.number} not auto-merged: ${Z.reason}`);return}let{strategy:K}=d(this.config);if(!i(X,"nativeAutoMerge","enableAutoMerge")){this.logger.info(`\uD83D\uDD00 PR #${$.number} qualifies for auto-merge but this provider has no merge queue; update-check will merge it once checks pass`);return}try{if(await X.enableAutoMerge($.number,K))this.logger.success(`\uD83D\uDD00 PR #${$.number} queued for auto-merge (${Z.reason})`);else this.logger.info(`\uD83D\uDD00 PR #${$.number} qualifies for auto-merge but the repository cannot queue it; update-check will merge it once checks pass`)}catch(W){this.logger.warn(`\u26A0\uFE0F Failed to queue auto-merge for PR #${$.number}: ${W}`)}}async mergeEligiblePullRequests(X=!1){let $=d(this.config);if(!$.enabled)return[];let Q=await this.createGitProvider();if(!Q)return[];let Y=[],Z=await Q.getPullRequests("open");for(let K of Z.filter((W)=>v(W.head))){let W=$.requireGreenCI&&Q.getPullRequestChecksState?await Q.getPullRequestChecksState(K.number):"none",_=W==="success"||W==="none",z=VX({number:K.number,title:K.title,body:K.body,head:K.head,labels:K.labels,draft:K.draft},this.config,_);if(!z.eligible){this.logger.debug(`\uD83D\uDD00 PR #${K.number} not merged: ${z.reason}`);continue}if(X){this.logger.info(`\uD83D\uDD00 [DRY RUN] Would merge PR #${K.number} (${z.reason})`),Y.push(K.number);continue}try{await Q.mergePullRequest(K.number,$.strategy),this.logger.success(`\uD83D\uDD00 Merged PR #${K.number}: ${z.reason}`),await this.events.emit("pr.merged",{number:K.number,title:K.title,strategy:$.strategy}),Y.push(K.number)}catch(L){this.logger.warn(`\u26A0\uFE0F Failed to merge PR #${K.number}: ${L}`)}}return Y}isPlausibleRepoPath(X){if(!X||/[\s()[\]!`]|:\/\//.test(X))return!1;return/^[\w@.-]+(?:\/[\w@.-]+)*$/.test(X)}extractFilePathsFromPRBody(X){let $=c(X);if($)return kX($);let Q=[],Y=/\|\s*\[[^\]]+\]\([^)]*\)\s*\|[^|]*\|\s*\*\*([^*]+)\*\*\s*\|/g,Z;while((Z=Y.exec(X))!==null){let z=Z[1].trim();if(this.isPlausibleRepoPath(z)&&!Q.includes(z))Q.push(z)}let K=/\*\*([^*]+\.(?:json|yaml|yml|lock))\*\*/g;while((Z=K.exec(X))!==null){let z=Z[1].trim();if(this.isPlausibleRepoPath(z)&&!Q.includes(z))Q.push(z)}let W=/\|[^|]+\|[^|]+\|([^|]+)\|[^|]*\|/g;while((Z=W.exec(X))!==null){let z=Z[1].trim();if(this.isPlausibleRepoPath(z)&&(z.includes("/")||/\.(?:json|yaml|yml|lock)$/.test(z))&&!Q.includes(z))Q.push(z)}let _=/(?:^|\s)([\w-]+(?:\/[\w.-]+)*\/[\w.-]+\.(?:json|yaml|yml|lock))(?:\s|$)/gm;while((Z=_.exec(X))!==null){let z=Z[1].trim();if(this.isPlausibleRepoPath(z)&&!Q.includes(z))Q.push(z)}return Q}extractPackagesFromPRBody(X){let $=c(X);if($)return[...new Set($.updates.map((K)=>K.name))];let Q=[],Y=X.match(/\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|/g);if(Y)for(let K of Y){let W=K.match(/\[([^\]]+)\]\([^)]*\)/);if(W)Q.push(W[1])}let Z=X.match(/<summary>([^<]+)<\/summary>/g);if(Z)for(let K of Z){let W=K.replace(/<summary>/,"").replace(/<\/summary>/,"").trim();if(W&&!Q.includes(W))Q.push(W)}return Q}extractPackageUpdatesFromPRBody(X){let $=c(X);if($)return vX($);let Q=[],Y=new Set,Z=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`?[v^~>=]*([^`|\s]+)`?\s*(?:->|\u2192)\s*`?[v^~>=]*([^`|\s]+)`?\]?/g,K;while((K=Z.exec(X))!==null){let[,W,_,z]=K;if(!Y.has(W))Y.add(W),Q.push({name:W,currentVersion:_,newVersion:z})}return Q}getConfig(){return this.config}getProjectPath(){return this.projectPath}async checkAndCloseObsoletePRs(X,$=!1){try{this.logger.info("\uD83D\uDD0D Scanning for obsolete PRs due to removed dependency files...");let Y=(await X.getPullRequests("open")).filter((K)=>v(K.head)||K.author==="github-actions[bot]"&&K.labels.includes("dependencies"));this.logger.info(`Found ${Y.length} dependency-related PRs to check`);let Z=0;for(let K of Y)try{if(this.shouldAutoCloseForRemovedFiles(K))if(this.logger.info(`\uD83D\uDD12 PR #${K.number} should be auto-closed: ${K.title}`),$)this.logger.info(`\uD83D\uDD0D [DRY RUN] Would auto-close PR #${K.number}`),Z++;else try{let _=this.generateCloseReason(K);try{await X.createComment(K.number,_)}catch(z){this.logger.warn(`\u26A0\uFE0F Could not add close reason comment to PR #${K.number}:`,z)}if(await X.closePullRequest(K.number),await this.events.emit("pr.closed",{number:K.number,title:K.title,reason:"obsolete \u2014 its dependency files no longer exist"}),v(K.head))try{await X.deleteBranch(K.head),this.logger.success(`\u2705 Auto-closed PR #${K.number} and deleted branch ${K.head}`)}catch(z){this.logger.warn(`\u26A0\uFE0F Auto-closed PR #${K.number} but failed to delete branch: ${z}`)}else this.logger.success(`\u2705 Auto-closed PR #${K.number}`);Z++}catch(_){this.logger.error(`\u274C Failed to auto-close PR #${K.number}:`,_)}}catch(W){this.logger.warn(`\u26A0\uFE0F Error checking PR #${K.number}:`,W)}if(Z>0)this.logger.success(`\u2705 ${$?"Would auto-close":"Auto-closed"} ${Z} obsolete PR(s)`);else this.logger.info("\uD83D\uDCCB No obsolete PRs found")}catch(Q){throw this.logger.error("Failed to check for obsolete PRs:",Q),Q}}async checkAndCloseSatisfiedPRs(X,$=!1){try{this.logger.info("\uD83D\uDD0D Checking for PRs where dependencies are already at target version...");let Y=(await X.getPullRequests("open")).filter((O)=>v(O.head)||O.author==="github-actions[bot]"&&O.labels.includes("dependencies"));if(this.logger.info(`Found ${Y.length} buddy dependency PRs to validate`),Y.length===0){this.logger.info("\uD83D\uDCCB No buddy PRs to check");return}let Z=0,K={...this.config,packages:{...this.config.packages,strategy:"all"}},_=await new WX(K,this.projectPath).scanForUpdates(),z=new Map;for(let O of _.updates)z.set(O.name,O);let L=this.readDeclaredNpmVersions();if(_.updates.length===0){this.logger.warn("\u26A0\uFE0F Scan returned 0 updates \u2014 skipping satisfied PR check to avoid false-positive closures");return}for(let O of Y)try{let H=this.extractPackageUpdatesFromPRBody(O.body);if(H.length===0){this.logger.debug(`PR #${O.number}: Could not extract package updates, skipping`);continue}let J=O.body.match(/\*\*Total\*\*\s*\|\s*\*\*(\d+)\*\*/),j=J?Number.parseInt(J[1],10):0;if(j>0&&H.length<j){this.logger.debug(`PR #${O.number}: Extracted ${H.length}/${j} updates \u2014 incomplete extraction, skipping satisfied check`);continue}let q=0,I=0,T=0;for(let B of H){let C=z.get(B.name);if(!C){let b=L.get(B.name);if(b){let R=this.compareVersionsSafe(b,B.newVersion);if(R==="at-or-beyond"){this.logger.debug(`PR #${O.number}: ${B.name} declared at ${b}, at or beyond ${B.newVersion}`),q++;continue}if(R==="behind"){this.logger.debug(`PR #${O.number}: ${B.name} declared at ${b}, still behind ${B.newVersion} \u2014 the scan missed it`),I++;continue}}this.logger.debug(`PR #${O.number}: ${B.name} not in current scan and not declared (unverifiable)`),T++;continue}if(C.newVersion===B.newVersion){this.logger.debug(`PR #${O.number}: ${B.name} still needs update to ${B.newVersion}`),I++;continue}let D=this.compareVersionsSafe(C.currentVersion,B.newVersion);if(D==="at-or-beyond")this.logger.debug(`PR #${O.number}: ${B.name} already at or beyond ${B.newVersion}`),q++;else if(D==="behind")this.logger.debug(`PR #${O.number}: ${B.name} still behind ${B.newVersion}`),I++;else this.logger.debug(`PR #${O.number}: ${B.name} version comparison inconclusive`),T++}let M=I===0&&T===0&&q>0;if(this.logger.debug(`PR #${O.number}: verified-satisfied=${q}, still-needed=${I}, unverifiable=${T} \u2192 ${M?"CLOSE":"KEEP"}`),M)if(this.logger.info(`\u2705 PR #${O.number} is satisfied (dependencies at target version): ${O.title}`),$)this.logger.info(`\uD83D\uDD0D [DRY RUN] Would close PR #${O.number}`),Z++;else try{let B=H.filter((D)=>{let R=z.get(D.name)?.currentVersion??L.get(D.name);if(!R)return!1;return this.compareVersionsSafe(R,D.newVersion)==="at-or-beyond"}),C=`\uD83E\uDD16 **Auto-closing satisfied PR**
|
|
90
90
|
|
|
91
91
|
`;if(B.length>0)C+=`The following packages are already at the target version or newer:
|
|
92
92
|
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Qh as x}from"./chunk-zwtx6vn3.js";import{lstat as R}from"fs/promises";import{join as W}from"path";var N=/^catalog:(.*)$/;function S(X){let J;try{J=Bun.YAML.parse(X)}catch{return{entries:[],hasCatalogs:!1}}if(typeof J!=="object"||J===null)return{entries:[],hasCatalogs:!1};let B=J,z=[],Z=!1,H=(M,U)=>{if(typeof M!=="object"||M===null||Array.isArray(M))return;Z=!0;for(let[j,q]of Object.entries(M))if(typeof q==="string"&&q.trim())z.push({name:j,version:q.trim(),catalog:U})};if(H(B.catalog,"default"),typeof B.catalogs==="object"&&B.catalogs!==null)for(let[M,U]of Object.entries(B.catalogs))H(U,M);return{entries:z,hasCatalogs:Z}}function w(X,J,B){let z=N.exec(X.trim());if(!z)return null;let Z=z[1].trim()||"default";return J.find((H)=>H.name===B&&H.catalog===Z)?.version??null}function f(X){return N.test(X.trim())}function V(X,J,B){let z=X.split(`
|
|
3
|
+
`),Z=/^(\s*)(["']?)([^"':]+)\2(\s*:\s*)(["']?)(.+?)\5(\s*(?:#.*)?)$/,H=null,M=!1,U=0;for(let j=0;j<z.length;j++){let q=z[j],F=q.length-q.trimStart().length,Y=q.trim();if(/^catalog\s*:\s*$/.test(Y)){H="default",M=!1;continue}if(/^catalogs\s*:\s*$/.test(Y)){M=!0,U=F,H=null;continue}if(M&&F>U&&/^[\w@./-]+\s*:\s*$/.test(Y)){H=Y.replace(/\s*:\s*$/,"");continue}if(M&&Y&&F<=U)M=!1,H=null;if(H!==J.catalog)continue;let $=Z.exec(q);if(!$||$[3].trim()!==J.name||$[6].trim()!==J.version)continue;let[,D,G,E,P,K,,Q]=$;return z[j]=`${D}${G}${E}${G}${P}${K}${B}${K}${Q}`,z.join(`
|
|
4
|
+
`)}return X}var I="pnpm-workspace.yaml",_="pnpm-workspace.yml";async function b(X,J,B={}){let z=B.logger??x(),Z=new Set(B.ignore??[]);for(let H of[I,_]){let M=W(X,H);if(!(await R(M).catch(()=>null))?.isFile())continue;let{entries:j,hasCatalogs:q}=S(await Bun.file(M).text());if(!q)return{updates:[],entries:[],file:H};return z.debug(`\uD83D\uDCE6 ${H}: ${j.length} catalog entr(ies)`),{updates:(await Promise.all(j.map(async(Y)=>{if(Z.has(Y.name))return null;try{let $=await J(Y.name);if(!$)return null;let D=Y.version.replace(/^[\^~>=<\s]+/,"").trim();if(!D||D===$)return null;return{name:Y.name,currentVersion:Y.version,newVersion:A(Y.version,$),updateType:k(D,$),dependencyType:"catalog",file:H,resolved:{catalog:Y.catalog}}}catch($){return z.debug(`Could not resolve catalog entry ${Y.name}: ${$}`),null}}))).filter((Y)=>Y!==null),entries:j,file:H}}return{updates:[],entries:[]}}function A(X,J){return`${/^([\^~]|>=|<=|>|<)?/.exec(X.trim())?.[1]??""}${J}`}function k(X,J){let B=(H)=>H.split(".").map((M)=>Number.parseInt(M,10)||0),z=B(X),Z=B(J);if((z[0]??0)!==(Z[0]??0))return"major";if((z[1]??0)!==(Z[1]??0))return"minor";return"patch"}function C(X,J){let B=X;for(let z of J){if(z.dependencyType!=="catalog")continue;B=V(B,{name:z.name,version:z.currentVersion,catalog:z.resolved?.catalog??"default"},z.newVersion)}return B}
|
|
5
|
+
export{S as gc,w as hc,f as ic,V as jc,I as kc,_ as lc,b as mc,C as nc};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Kh as U}from"./chunk-34vracy4.js";import{Qh as f}from"./chunk-zwtx6vn3.js";var{Glob:u}=globalThis.Bun;import{readdir as m}from"fs/promises";import{join as P,relative as l}from"path";import O from"process";var c=new Set(["node_modules","vendor","target",".git",".venv","venv","dist","build","__pycache__",".next",".cache"]);function W(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function L(z,H,$=4){let X=H.map((K)=>new u(K)),Z=[];async function J(K,G){if(G>$)return;let V=await m(K,{withFileTypes:!0}).catch(()=>[]);for(let Q of V){let j=P(K,Q.name);if(Q.isDirectory()){if(!c.has(Q.name)&&!Q.name.startsWith("."))await J(j,G+1);continue}let q=l(z,j);if(X.some((Y)=>Y.match(Q.name)||Y.match(q)))Z.push(q)}}return await J(z,0),Z.sort()}async function M(z,H){let $=[],X=[];for(let Z of H){if(!await Bun.file(P(z,Z.lockfile)).exists())continue;let[J]=Z.command;if(!await E(J)){X.push(`${Z.lockfile} (needs \`${Z.command.join(" ")}\`)`);continue}if(await Bun.spawn(Z.command,{cwd:z,stdout:"ignore",stderr:"ignore",env:{PATH:O.env.PATH??"",HOME:O.env.HOME??""}}).exited===0)$.push(Z.lockfile);else X.push(`${Z.lockfile} (\`${Z.command.join(" ")}\` failed)`)}return{regenerated:$,...X.length>0?{note:`These lockfiles were not regenerated and need updating locally: ${X.join(", ")}.`}:{}}}async function E(z){try{return await Bun.spawn(["which",z],{stdout:"ignore",stderr:"ignore",env:{PATH:O.env.PATH??""}}).exited===0}catch{return!1}}function B(z,H){let $=(J)=>J.replace(/^[^\d]*/,"").split(/[.-]/).map((K)=>Number.parseInt(K,10)||0),X=$(z),Z=$(H);for(let J=0;J<Math.max(X.length,Z.length);J++){let K=(X[J]??0)-(Z[J]??0);if(K!==0)return K}return 0}function C(z,H){let $=(J)=>J.replace(/^[^\d]*/,"").split(/[.-]/).map((K)=>Number.parseInt(K,10)||0),X=$(z),Z=$(H);if((X[0]??0)!==(Z[0]??0))return"major";if((X[1]??0)!==(Z[1]??0))return"minor";return"patch"}var p=/^\s*(?:require\s+)?([\w.~-]+(?:\.[\w.~-]+)*\/[^\s]+)\s+(v[\w.+-]+)\s*(\/\/.*)?$/,R=/^v\d+\.\d+\.\d+-\d{14}-[a-f0-9]{12}$/,I={name:"go",manifestPatterns:["go.mod"],async detect(z){return L(z,this.manifestPatterns)},async parse(z,H){let $=[],X=!1;for(let Z of H.split(`
|
|
2
|
+
import{Kh as U}from"./chunk-34vracy4.js";import{Qh as f}from"./chunk-zwtx6vn3.js";var{Glob:u}=globalThis.Bun;import{readdir as m}from"fs/promises";import{join as P,relative as l}from"path";import O from"process";var c=new Set(["node_modules","vendor","target",".git",".venv","venv","dist","build","__pycache__",".next",".cache"]);function W(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function L(z,H,$=4){let X=H.map((K)=>new u(K)),Z=[];async function J(K,G){if(G>$)return;let V=await m(K,{withFileTypes:!0}).catch(()=>[]);for(let Q of V){let j=P(K,Q.name);if(Q.isDirectory()){if(!c.has(Q.name)&&!Q.name.startsWith("."))await J(j,G+1);continue}if(!Q.isFile())continue;let q=l(z,j);if(X.some((Y)=>Y.match(Q.name)||Y.match(q)))Z.push(q)}}return await J(z,0),Z.sort()}async function M(z,H){let $=[],X=[];for(let Z of H){if(!await Bun.file(P(z,Z.lockfile)).exists())continue;let[J]=Z.command;if(!await E(J)){X.push(`${Z.lockfile} (needs \`${Z.command.join(" ")}\`)`);continue}if(await Bun.spawn(Z.command,{cwd:z,stdout:"ignore",stderr:"ignore",env:{PATH:O.env.PATH??"",HOME:O.env.HOME??""}}).exited===0)$.push(Z.lockfile);else X.push(`${Z.lockfile} (\`${Z.command.join(" ")}\` failed)`)}return{regenerated:$,...X.length>0?{note:`These lockfiles were not regenerated and need updating locally: ${X.join(", ")}.`}:{}}}async function E(z){try{return await Bun.spawn(["which",z],{stdout:"ignore",stderr:"ignore",env:{PATH:O.env.PATH??""}}).exited===0}catch{return!1}}function B(z,H){let $=(J)=>J.replace(/^[^\d]*/,"").split(/[.-]/).map((K)=>Number.parseInt(K,10)||0),X=$(z),Z=$(H);for(let J=0;J<Math.max(X.length,Z.length);J++){let K=(X[J]??0)-(Z[J]??0);if(K!==0)return K}return 0}function C(z,H){let $=(J)=>J.replace(/^[^\d]*/,"").split(/[.-]/).map((K)=>Number.parseInt(K,10)||0),X=$(z),Z=$(H);if((X[0]??0)!==(Z[0]??0))return"major";if((X[1]??0)!==(Z[1]??0))return"minor";return"patch"}var p=/^\s*(?:require\s+)?([\w.~-]+(?:\.[\w.~-]+)*\/[^\s]+)\s+(v[\w.+-]+)\s*(\/\/.*)?$/,R=/^v\d+\.\d+\.\d+-\d{14}-[a-f0-9]{12}$/,I={name:"go",manifestPatterns:["go.mod"],async detect(z){return L(z,this.manifestPatterns)},async parse(z,H){let $=[],X=!1;for(let Z of H.split(`
|
|
3
3
|
`)){let J=Z.trim();if(/^require\s*\($/.test(J)){X=!0;continue}if(X&&J===")"){X=!1;continue}if(!X&&!J.startsWith("require "))continue;let K=p.exec(Z);if(!K)continue;let[,G,V,Q]=K;if(Q?.includes("indirect"))continue;if(R.test(V))continue;$.push({name:G,currentVersion:V,section:"require",file:z})}return $},async latest(z,H={}){let $=H.registryUrl??"https://proxy.golang.org",X=z.name.replace(/[A-Z]/g,(K)=>`!${K.toLowerCase()}`),Z=await U(`${$}/${X}/@latest`,{headers:{"User-Agent":"buddy",Accept:"application/json"}}).catch(()=>null);if(!Z?.ok)return null;let J=await Z.json().catch(()=>null);if(!J?.Version)return null;if(R.test(J.Version))return null;return{latest:J.Version,...J.Time?{publishedAt:new Date(J.Time)}:{},releaseNotesUrl:`https://pkg.go.dev/${z.name}@${J.Version}`,homepage:`https://pkg.go.dev/${z.name}`}},applyUpdate(z,H){let $=W(H.name),X=W(H.currentVersion);return z.replace(new RegExp(`^(\\s*(?:require\\s+)?${$}\\s+)${X}(\\s|$)`,"gm"),`$1${H.newVersion}$2`)},async postWrite(z){return M(z,[{lockfile:"go.sum",command:["go","mod","tidy"]}])},osvEcosystem:"Go",compareVersions:B,updateType:C};var s=/^\s*v?(?:(\d+)!)?(\d+(?:\.\d+)*)((?:[-_.]?(?:a|b|c|rc|alpha|beta|pre|preview)[-_.]?\d*)?)((?:[-_.]?(?:post|rev|r)[-_.]?\d*|-\d+)?)((?:[-_.]?dev[-_.]?\d*)?)(?:\+([a-z0-9]+(?:[-_.][a-z0-9]+)*))?\s*$/i,i={a:"a",alpha:"a",b:"b",beta:"b",c:"rc",rc:"rc",pre:"rc",preview:"rc"},v={a:0,b:1,rc:2};function S(z){let H=s.exec(z);if(!H)return null;let[,$,X,Z,J,K,G]=H,V={epoch:$?Number($):0,release:X.split(".").map(Number)};if(Z){let Q=/([a-z]+)[-_.]?(\d*)/i.exec(Z);if(Q){let j=i[Q[1].toLowerCase()];if(j)V.pre=[j,Q[2]?Number(Q[2]):0]}}if(J){let Q=/(\d+)/.exec(J);V.post=Q?Number(Q[1]):0}if(K){let Q=/(\d+)/.exec(K);V.dev=Q?Number(Q[1]):0}if(G)V.local=G.toLowerCase();return V}function d(z,H){for(let $=0;$<Math.max(z.length,H.length);$++){let X=(z[$]??0)-(H[$]??0);if(X!==0)return X}return 0}function A(z,H){let $=S(z),X=S(H);if(!$||!X)return z===H?0:z<H?-1:1;if($.epoch!==X.epoch)return $.epoch-X.epoch;let Z=d($.release,X.release);if(Z!==0)return Z;let J=(Q)=>{if(Q.dev!==void 0&&Q.pre===void 0&&Q.post===void 0)return 0;if(Q.pre!==void 0)return 1;if(Q.post!==void 0)return 3;return 2},K=J($)-J(X);if(K!==0)return K;if($.pre&&X.pre){let Q=v[$.pre[0]]-v[X.pre[0]];if(Q!==0)return Q;if($.pre[1]!==X.pre[1])return $.pre[1]-X.pre[1]}if(($.post??0)!==(X.post??0))return($.post??0)-(X.post??0);let G=$.dev??Number.POSITIVE_INFINITY,V=X.dev??Number.POSITIVE_INFINITY;if(G!==V)return G<V?-1:1;return 0}function g(z){let H=S(z);return Boolean(H&&(H.pre!==void 0||H.dev!==void 0))}function D(z,H){let $=S(z),X=S(H);if(!$||!X)return"patch";if($.epoch!==X.epoch||($.release[0]??0)!==(X.release[0]??0))return"major";if(($.release[1]??0)!==(X.release[1]??0))return"minor";return"patch"}function N(z){let H=/^\s*(~=|===|==|!=|<=|>=|<|>|\^)?\s*(.*)$/.exec(z.trim());if(!H)return{operator:"",version:z.trim()};return{operator:H[1]??"",version:H[2].trim()}}var b=/^\s*([A-Z0-9][\w.-]*)\s*(\[[^\]]*\])?\s*([<>=!~^].*?)?\s*(?:;.*)?$/i,o=/^\s*(?:-|#|$)/;function r(z,H){let $=[];return H.split(`
|
|
4
4
|
`).forEach((X)=>{let Z=X.split("#")[0];if(o.test(Z))return;let J=b.exec(Z);if(!J?.[1]||!J[3])return;$.push({name:J[1],currentVersion:J[3].trim(),section:"dependencies",file:z,...J[2]?{metadata:{extras:J[2]}}:{}})}),$}var a=[[/^\s*dependencies\s*=\s*\[/m,"dependencies"],[/^\s*(?:dev-dependencies|dev)\s*=\s*\[/m,"devDependencies"]];function n(z,H){let $=[],X=new Set,Z=(K,G,V)=>{let Q=`${V}:${K}`;if(!G.trim()||G.trim()==="*"||X.has(Q))return;X.add(Q),$.push({name:K,currentVersion:G.trim(),section:V,file:z})};for(let[K,G]of a){let V=K.exec(H);if(!V)continue;let Q=V.index+V[0].length,j=H.indexOf("]",Q);if(j===-1)continue;for(let q of H.slice(Q,j).matchAll(/["']([^"']+)["']/g)){let Y=b.exec(q[1]);if(Y?.[1]&&Y[3])Z(Y[1],Y[3],G)}}let J=H.matchAll(/\[tool\.poetry\.(?:group\.[\w-]+\.)?(dependencies|dev-dependencies)\]([\s\S]*?)(?=\n\[|$)/g);for(let K of J){let G=K[1]==="dependencies"?"dependencies":"devDependencies";for(let V of K[2].matchAll(/^\s*([A-Z0-9][\w.-]*)\s*=\s*(.+)$/gim)){let Q=V[1];if(Q.toLowerCase()==="python")continue;let j=V[2].trim(),q=/version\s*=\s*["']([^"']+)["']/.exec(j),Y=/^["']([^"']+)["']/.exec(j),F=q?.[1]??Y?.[1];if(F)Z(Q,F,G)}}return $}var w={name:"python",manifestPatterns:["pyproject.toml","requirements.txt","requirements-*.txt","requirements/*.txt"],async detect(z){return L(z,this.manifestPatterns)},async parse(z,H){return z.endsWith(".toml")?n(z,H):r(z,H)},async latest(z,H={}){let $=H.registryUrl??"https://pypi.org",X=await U(`${$}/pypi/${encodeURIComponent(z.name)}/json`,{headers:{"User-Agent":"buddy",Accept:"application/json"}}).catch(()=>null);if(!X?.ok)return null;let Z=await X.json().catch(()=>null);if(!Z?.info?.version)return null;let J=Z.info.version;if(H.includePrerelease&&Z.releases){let V=Object.keys(Z.releases).filter((Q)=>!Z.releases[Q]?.every((j)=>j.yanked)).sort(A);J=V[V.length-1]??J}let G=Z.releases?.[J]?.find((V)=>V.upload_time_iso_8601)?.upload_time_iso_8601;return{latest:J,...G?{publishedAt:new Date(G)}:{},...Z.info.yanked?{deprecated:!0}:{},...Z.info.project_urls?.Changelog?{releaseNotesUrl:Z.info.project_urls.Changelog}:{},...Z.info.home_page?{homepage:Z.info.home_page}:{}}},applyUpdate(z,H){let{operator:$}=N(H.currentVersion),X=W(H.name),Z=W(H.currentVersion),J=N(H.newVersion).version,K=$?`${$}${J}`:J;return z.replace(new RegExp(`(^|["'\\s])(${X})(\\[[^\\]]*\\])?\\s*${Z}`,"gim"),(G,V,Q,j)=>`${V}${Q}${j??""}${K}`).replace(new RegExp(`^(\\s*${X}\\s*=\\s*["'])${Z}(["'])`,"gim"),`$1${K}$2`).replace(new RegExp(`^(\\s*${X}\\s*=\\s*\\{[^}]*version\\s*=\\s*["'])${Z}(["'])`,"gim"),`$1${K}$2`)},async postWrite(z){return M(z,[{lockfile:"uv.lock",command:["uv","lock"]},{lockfile:"poetry.lock",command:["poetry","lock","--no-update"]}])},osvEcosystem:"PyPI",compareVersions:A,updateType:D};var t=/^\s*gem\s+["']([\w-]+)["']\s*(?:,\s*["']([^"']+)["'])?/,e=/^\s*group\s+(.+?)\s+do\s*$/,zz=/^\s*end\s*$/,x={name:"ruby",manifestPatterns:["Gemfile","*.gemspec"],async detect(z){return L(z,this.manifestPatterns)},async parse(z,H){let $=[],X=[];for(let Z of H.split(`
|
|
5
5
|
`)){let J=Z.replace(/#.*$/,""),K=e.exec(J);if(K){X.push(K[1].replace(/[:'",\s]/g,"")||"default");continue}if(zz.test(J)){X.pop();continue}let G=t.exec(J);if(!G?.[1])continue;if(!G[2])continue;if(/\b(?:path|git|github|branch):/.test(J))continue;$.push({name:G[1],currentVersion:G[2],section:X.length>0?X[X.length-1]:"dependencies",file:z})}return $},async latest(z,H={}){let $=H.registryUrl??"https://rubygems.org",X=await U(`${$}/api/v1/versions/${encodeURIComponent(z.name)}.json`,{headers:{"User-Agent":"buddy",Accept:"application/json"}}).catch(()=>null);if(!X?.ok)return null;let Z=await X.json().catch(()=>null);if(!Array.isArray(Z)||Z.length===0)return null;let J=Z.filter((G)=>G.number&&!G.yanked).filter((G)=>H.includePrerelease?!0:!G.prerelease).sort((G,V)=>B(G.number,V.number)),K=J[J.length-1];if(!K?.number)return null;return{latest:K.number,...K.created_at?{publishedAt:new Date(K.created_at)}:{},homepage:`${$}/gems/${z.name}`}},applyUpdate(z,H){let $=W(H.name),X=W(H.currentVersion),Z=/^\s*(~>|>=|<=|>|<|=)?\s*/.exec(H.currentVersion)?.[1]??"",J=Z?`${Z} ${H.newVersion}`:H.newVersion;return z.replace(new RegExp(`^(\\s*gem\\s+["']${$}["']\\s*,\\s*["'])${X}(["'])`,"gm"),`$1${J}$2`)},async postWrite(z){return M(z,[{lockfile:"Gemfile.lock",command:["bundle","lock","--update"]}])},osvEcosystem:"RubyGems",compareVersions:B,updateType:C};var Hz=[[/^\[dependencies\]/m,"dependencies"],[/^\[dev-dependencies\]/m,"devDependencies"],[/^\[build-dependencies\]/m,"buildDependencies"],[/^\[workspace\.dependencies\]/m,"workspaceDependencies"]],T={name:"rust",manifestPatterns:["Cargo.toml"],async detect(z){return L(z,this.manifestPatterns)},async parse(z,H){let $=[];for(let[X,Z]of Hz){let J=X.exec(H);if(!J)continue;let K=J.index+J[0].length,G=H.slice(K).search(/\n\[/),V=G===-1?H.slice(K):H.slice(K,K+G);for(let Q of V.matchAll(/^\s*([\w-]+)\s*=\s*(.+)$/gm)){let j=Q[1],q=Q[2].trim(),Y=/version\s*=\s*["']([^"']+)["']/.exec(q),F=/^["']([^"']+)["']/.exec(q),_=Y?.[1]??F?.[1];if(!_||/\b(?:path|git)\s*=/.test(q))continue;$.push({name:j,currentVersion:_,section:Z,file:z})}}return $},async latest(z,H={}){let $=H.registryUrl??"https://crates.io",X=await U(`${$}/api/v1/crates/${encodeURIComponent(z.name)}`,{headers:{"User-Agent":"buddy (https://buddy.sh)",Accept:"application/json"}}).catch(()=>null);if(!X?.ok)return null;let Z=await X.json().catch(()=>null);if(!Z?.crate)return null;let J=H.includePrerelease?Z.crate.newest_version??Z.crate.max_stable_version:Z.crate.max_stable_version??Z.crate.newest_version;if(!J)return null;let K=Z.versions?.find((G)=>G.num===J);if(K?.yanked)return null;return{latest:J,...K?.created_at?{publishedAt:new Date(K.created_at)}:{},...Z.crate.repository?{releaseNotesUrl:`${Z.crate.repository}/releases`}:{},...Z.crate.homepage?{homepage:Z.crate.homepage}:{}}},applyUpdate(z,H){let $=W(H.name),X=W(H.currentVersion);return z.replace(new RegExp(`^(\\s*${$}\\s*=\\s*["'])${X}(["'])`,"gm"),`$1${H.newVersion}$2`).replace(new RegExp(`^(\\s*${$}\\s*=\\s*\\{[^}]*?version\\s*=\\s*["'])${X}(["'])`,"gm"),`$1${H.newVersion}$2`)},async postWrite(z){return M(z,[{lockfile:"Cargo.lock",command:["cargo","update","--workspace"]}])},osvEcosystem:"crates.io",compareVersions:B,updateType:C};import{join as Xz}from"path";async function Zz(z){let H=z.logger??f(),$=z.adapters??k,X=new Set(z.ignore??[]),Z=[],J={},K=[];return await Promise.all($.map(async(G)=>{let V;try{V=await G.detect(z.dir)}catch(Q){H.warn(`\u26A0\uFE0F ${G.name}: could not look for manifests: ${Q}`);return}if(V.length===0)return;K.push({ecosystem:G.name,files:V}),H.debug(`\uD83D\uDCE6 ${G.name}: ${V.length} manifest(s)`);for(let Q of V){let j;try{j=await G.parse(Q,await Bun.file(Xz(z.dir,Q)).text())}catch(Y){H.warn(`\u26A0\uFE0F ${G.name}: could not parse ${Q}: ${Y}`);continue}J[G.name]=(J[G.name]??0)+j.length;let q=await Promise.all(j.map(async(Y)=>{if(X.has(Y.name))return null;try{let F=await G.latest(Y,{...z.includePrerelease!==void 0?{includePrerelease:z.includePrerelease}:{},logger:H});if(!F)return null;let _=y(Y.currentVersion);if(G.compareVersions(F.latest,_)<=0)return null;return{name:Y.name,currentVersion:Y.currentVersion,newVersion:F.latest,updateType:G.updateType(_,F.latest),dependencyType:G.name,file:Q,...F.releaseNotesUrl?{releaseNotesUrl:F.releaseNotesUrl}:{},...F.homepage?{homepage:F.homepage}:{}}}catch(F){return H.debug(`${G.name}: could not resolve ${Y.name}: ${F}`),null}}));Z.push(...q.filter((Y)=>Y!==null))}})),{updates:Z,dependenciesByEcosystem:J,manifests:K}}function y(z){let H=/(\d[\w.!+-]*)/.exec(z);return H?H[1]:z.trim()}async function $z(z,H,$=k){let X=[],Z=[];for(let J of $){if(!H.includes(J.name)||!J.postWrite)continue;let K=await J.postWrite(z).catch(()=>({regenerated:[],note:void 0}));if(X.push(...K.regenerated),K.note)Z.push(K.note)}return{regenerated:X,notes:Z}}var k=[w,T,I,x];function Ez(z,H=k){let $=z.split("/").pop()??z;for(let X of H)if(X.manifestPatterns.some((Z)=>h($,Z)||h(z,Z)))return X;return null}function h(z,H){if(!H.includes("*"))return z===H;let $=H.split("*").map((X)=>X.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join("[^/]*");return new RegExp(`^${$}$`).test(z)}function Rz(z,H=k){return H.find(($)=>$.name===z)??null}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ed as a}from"./chunk-
|
|
2
|
+
import{ed as a}from"./chunk-q9mxgp0n.js";import"./chunk-c9266b5x.js";import"./chunk-ymh0kwm4.js";import"./chunk-xyzcgskb.js";import"./chunk-bnp0r4eh.js";import"./chunk-0f1xye20.js";import"./chunk-66nntsnf.js";import"./chunk-ebnc6980.js";import"./chunk-y1d6e0ye.js";import"./chunk-ma01xp3y.js";import"./chunk-gjhxc6ma.js";import"./chunk-3a63hke8.js";import"./chunk-92gh2n65.js";import"./chunk-j46f90n8.js";import"./chunk-eh71jv8w.js";import"./chunk-3a5gcj3y.js";import"./chunk-1pecmenc.js";import"./chunk-4kyxrwxn.js";import"./chunk-24xvskkf.js";import"./chunk-z18bksyr.js";import"./chunk-cj4d5ad7.js";import"./chunk-zy49dwqk.js";import"./chunk-x9vpk4kk.js";import"./chunk-94tnmc7j.js";import"./chunk-drmk6r1m.js";import"./chunk-7t8s2mcf.js";import"./chunk-j6geg3qt.js";import"./chunk-34vracy4.js";import"./chunk-zwtx6vn3.js";import"./chunk-028354j6.js";import"./chunk-s82adeq9.js";export{a as Buddy};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ac as m,Bc as n,Cc as o,Dc as p,Ec as q,Fc as r,Gc as s,Hc as t,Ic as u,oc as a,pc as b,qc as c,rc as d,sc as e,tc as f,uc as g,vc as h,wc as i,xc as j,yc as k,zc as l}from"./chunk-
|
|
2
|
+
import{Ac as m,Bc as n,Cc as o,Dc as p,Ec as q,Fc as r,Gc as s,Hc as t,Ic as u,oc as a,pc as b,qc as c,rc as d,sc as e,tc as f,uc as g,vc as h,wc as i,xc as j,yc as k,zc as l}from"./chunk-w2ccdet4.js";import"./chunk-34vracy4.js";import"./chunk-zwtx6vn3.js";import"./chunk-s82adeq9.js";export{t as stripOperators,l as splitConstraint,s as scanEcosystems,o as rustAdapter,n as rubyAdapter,c as regenerateWith,u as regenerateLockfiles,m as pythonAdapter,k as pep440UpdateType,h as parsePep440,f as numericUpdateType,j as isPep440Prerelease,g as goAdapter,a as escapeRegex,b as detectFiles,i as comparePep440,e as compareNumeric,d as commandAvailable,r as adapterNamed,q as adapterFor,p as BUILTIN_ADAPTERS};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{md as J}from"./chunk-bnp0r4eh.js";import{nd as Y}from"./chunk-0f1xye20.js";import{ue as _}from"./chunk-ma01xp3y.js";import{xe as x,ye as w}from"./chunk-gjhxc6ma.js";import{Qe as z,Re as M}from"./chunk-3a63hke8.js";import{Ye as N}from"./chunk-j46f90n8.js";import{Ag as L,Bg as S}from"./chunk-94tnmc7j.js";import{Qh as G}from"./chunk-zwtx6vn3.js";import{fl as j}from"./chunk-s82adeq9.js";var{Glob:D}=globalThis.Bun;import{lstat as Z,readdir as A,readFile as U}from"fs/promises";import{join as R,relative as E,sep as H}from"path";async function I(q,K){try{let O=JSON.parse(K),V=[];if(O.packages){for(let Q of Object.values(O.packages))if(Q.name&&Q.version)V.push({name:Q.name,currentVersion:Q.version,type:"dependencies",file:q})}return{path:q,type:"pantry.lock",content:K,dependencies:V}}catch(O){return G().warn(`Failed to parse pantry.lock file ${q}:`,O),null}}class m{projectPath;logger;ignoreGlobs=[];constructor(q,K,O){this.projectPath=q;this.logger=K;if(O&&O.length>0)this.ignoreGlobs=O.map((V)=>new D(V)),this.logger.info(`Initialized ${this.ignoreGlobs.length} ignore patterns: ${O.join(", ")}`)}async scanProject(){this.logger.info("Scanning project for package files...");let q=Date.now(),K=[];try{let O=await this.findFiles("package.json");for(let X of O){if(this.shouldIgnorePath(X))continue;let $=await this.parsePackageJsonFile(X);if($)K.push($)}let V=await this.findDependencyFiles();for(let X of V){if(this.shouldIgnorePath(X))continue;let $=await this.parseDependencyFile(X);if($)K.push($)}let Q=await this.findLockFiles();for(let X of Q){if(this.shouldIgnorePath(X))continue;let $=await this.parseLockFile(X);if($)K.push($)}let W=await this.findComposerFiles();for(let X of W){if(this.shouldIgnorePath(X))continue;let $=await this.parseComposerFile(X);if($)K.push($)}let B=await this.findGitHubActionsFiles();for(let X of B){if(this.shouldIgnorePath(X))continue;let $=await this.parseGitHubActionsFile(X);if($)K.push($)}let C=await this.findDockerfiles();this.logger.info(`\uD83D\uDD0D Found ${C.length} Dockerfile(s): ${C.join(", ")}`);for(let X of C){if(this.shouldIgnorePath(X))continue;let $=await this.parseDockerfile(X);if($)K.push($),this.logger.info(`\uD83D\uDCE6 Parsed Dockerfile: ${X} with ${$.dependencies.length} dependencies`)}let T=await this.findZigManifests();this.logger.info(`\uD83D\uDD0D Found ${T.length} Zig manifest(s): ${T.join(", ")}`);for(let X of T){if(this.shouldIgnorePath(X))continue;let $=await this.parseZigManifestFile(X);if($)K.push($),this.logger.info(`\uD83D\uDCE6 Parsed Zig manifest: ${X} with ${$.dependencies.length} dependencies`)}let b=await this.findFiles("pantry.lock");for(let X of b){if(this.shouldIgnorePath(X))continue;let $=await this.parsePantryLockFile(X);if($)K.push($),this.logger.info(`\uD83D\uDCE6 Parsed pantry.lock: ${X} with ${$.dependencies.length} dependencies`)}let v=Date.now()-q;return this.logger.success(`Found ${K.length} package files in ${v}ms`),K}catch(O){throw this.logger.error("Failed to scan project:",O),new Y(`Failed to scan project: ${O instanceof Error?O.message:"Unknown error"}`)}}async parsePackageJsonFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8"),V=JSON.parse(O),Q=[];return this.extractDependencies(V.dependencies,"dependencies",q,Q),this.extractDependencies(V.devDependencies,"devDependencies",q,Q),this.extractDependencies(V.peerDependencies,"peerDependencies",q,Q),this.extractDependencies(V.optionalDependencies,"optionalDependencies",q,Q),Q.push(...N(V.engines,q)),{path:q,type:"package.json",content:O,dependencies:Q}}catch(K){return this.logger.warn(`Failed to parse package.json file ${q}:`,K),null}}async parseLockFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8"),V=q.split("/").pop()||"",Q;if(V==="bun.lockb")Q="bun.lockb";else if(V==="package-lock.json")Q="package-lock.json";else if(V==="yarn.lock")Q="yarn.lock";else if(V==="pnpm-lock.yaml")Q="pnpm-lock.yaml";else return null;let W=await this.extractLockFileDependencies(O,Q,q);return{path:q,type:Q,content:O,dependencies:W}}catch(K){return this.logger.warn(`Failed to parse lock file ${q}:`,K),null}}async parseDependencyFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await S(q,O)}catch(K){return this.logger.warn(`Failed to parse dependency file ${q}:`,K),null}}async findDependencyFiles(){let q=[],K=["deps.yaml","deps.yml","dependencies.yaml","dependencies.yml","pkgx.yaml","pkgx.yml",".deps.yaml",".deps.yml"];for(let Q of K){let W=await this.findFiles(Q);q.push(...W)}let O=await this.findFilesByPattern("*.yaml"),V=await this.findFilesByPattern("*.yml");for(let Q of[...O,...V])if(L(Q)&&!q.includes(Q))q.push(Q);return q}async findGitHubActionsFiles(){let q=[];try{if(!(await Z(R(this.projectPath,".github")).catch(()=>null))?.isDirectory())return q;let V=R(this.projectPath,".github","workflows");if((await Z(V).catch(()=>null))?.isDirectory()){let W=await this.findFilesByPatternInDir("*.yaml",V),B=await this.findFilesByPatternInDir("*.yml",V);for(let C of[...W,...B])if(x(C))q.push(C)}}catch{}return q}async findDockerfiles(){return this.findFilesMatching(z)}async findFilesMatching(q,K=this.projectPath){let O=[];try{let V=await A(K);for(let Q of V){let W=R(K,Q);try{let B=await Z(W);if(B.isFile()){if(q(Q))O.push(E(this.projectPath,W).split(H).join("/"))}else if(B.isDirectory()&&!J(Q))O.push(...await this.findFilesMatching(q,W))}catch{continue}}}catch{}return O}async parseGitHubActionsFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await w(q,O)}catch(K){return this.logger.warn(`Failed to parse GitHub Actions file ${q}:`,K),null}}async parseDockerfile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await M(q,O)}catch(K){return this.logger.warn(`Failed to parse Dockerfile ${q}:`,K),null}}async findZigManifests(){let q=[];try{let K=await this.findFiles("build.zig.zon");q.push(...K)}catch{}return q}async parseZigManifestFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await _(q,O)}catch(K){return this.logger.warn(`Failed to parse Zig manifest ${q}:`,K),null}}async findComposerFiles(){let q=[];try{let K=await this.findFiles("composer.json");q.push(...K);let O=await this.findFiles("composer.lock");q.push(...O)}catch{}return q}async parseComposerFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8"),{parseComposerFile:V}=await import("./chunk-6prz7chv.js");return await V(q,O)}catch(K){return this.logger.warn(`Failed to parse Composer file ${q}:`,K),null}}async parsePantryLockFile(q){try{let K=R(this.projectPath,q),O=await U(K,"utf-8");return await I(q,O)}catch(K){return this.logger.warn(`Failed to parse pantry.lock file ${q}:`,K),null}}extractDependencies(q,K,O,V){if(!q)return;for(let[Q,W]of Object.entries(q))V.push({name:Q,currentVersion:W,type:K,file:this.getRelativePath(O)})}async extractLockFileDependencies(q,K,O){let V=[];if(K==="package-lock.json")try{let Q=JSON.parse(q);if(Q.packages){for(let[W,B]of Object.entries(Q.packages))if(W&&W!==""&&B&&typeof B==="object"){let C=B;if(C.version){let T=W.startsWith("node_modules/")?W.replace("node_modules/",""):W;V.push({name:T,currentVersion:C.version,type:C.dev?"devDependencies":"dependencies",file:this.getRelativePath(O)})}}}}catch(Q){this.logger.warn("Failed to parse package-lock.json:",Q)}return V}async findFiles(q,K=this.projectPath){let O=[];try{let V=await A(K);for(let Q of V){let W=R(K,Q);try{let B=await Z(W);if(B.isDirectory()){if(!J(Q)){let C=await this.findFiles(q,W);O.push(...C)}}else if(B.isFile()&&Q===q){let C=E(this.projectPath,W);O.push(C.split(H).join("/"))}}catch{continue}}}catch{}return O}async findLockFiles(){let q=["bun.lock","bun.lockb","package-lock.json","yarn.lock","pnpm-lock.yaml"],K=[];for(let O of q){let V=await this.findFiles(O);K.push(...V)}return K}async findFilesByPattern(q){let K=[],O=q.replace("*.","");try{let V=await A(this.projectPath);for(let Q of V){let W=R(this.projectPath,Q),B=await Z(W);if(B.isFile()&&Q.endsWith(`.${O}`)){let C=E(this.projectPath,W);K.push(C.split(H).join("/"))}else if(B.isDirectory()&&!J(Q)){let C=await this.findFilesByPatternInDir(q,W);K.push(...C)}}}catch{}return K}async findFilesByPatternInDir(q,K){let O=[],V=q.replace("*.","");try{let Q=await A(K);for(let W of Q){let B=R(K,W),C=await Z(B);if(C.isFile()&&W.endsWith(`.${V}`)){let T=E(this.projectPath,B);O.push(T.split(H).join("/"))}else if(C.isDirectory()&&!J(W)){let T=await this.findFilesByPatternInDir(q,B);O.push(...T)}}}catch{}return O}shouldIgnorePath(q){if(this.ignoreGlobs.length===0)return!1;let K=q;if(q.startsWith("/")||q.includes(":"))K=this.getRelativePath(q);for(let O of this.ignoreGlobs)if(O.match(K))return this.logger.debug(`Ignoring path: ${K} (matched pattern)`),!0;return!1}getRelativePath(q){return E(this.projectPath,q).split(H).join("/")}async getDependencyCount(){return(await this.scanProject()).reduce((K,O)=>K+O.dependencies.length,0)}async getUniqueDependencies(){return(await this.scanProject()).flatMap((V)=>V.dependencies).filter((V,Q,W)=>Q===W.findIndex((B)=>B.name===V.name))}}
|
|
3
|
+
export{m as ld};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ld as a}from"./chunk-
|
|
2
|
+
import{ld as a}from"./chunk-xyzcgskb.js";import"./chunk-bnp0r4eh.js";import"./chunk-0f1xye20.js";import"./chunk-ma01xp3y.js";import"./chunk-gjhxc6ma.js";import"./chunk-3a63hke8.js";import"./chunk-j46f90n8.js";import"./chunk-94tnmc7j.js";import"./chunk-drmk6r1m.js";import"./chunk-7t8s2mcf.js";import"./chunk-34vracy4.js";import"./chunk-zwtx6vn3.js";import"./chunk-028354j6.js";import"./chunk-s82adeq9.js";export{a as PackageScanner};
|
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
import{md as h}from"./chunk-bnp0r4eh.js";import{od as B}from"./chunk-0f1xye20.js";import{kg as E}from"./chunk-zy49dwqk.js";import{Bh as w,Ch as f,yh as y}from"./chunk-7t8s2mcf.js";import{Kh as A,Lh as V}from"./chunk-34vracy4.js";import{fl as v}from"./chunk-s82adeq9.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(`
|
|
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
|
-
\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-a6hv92fx.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.
|
|
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-a6hv92fx.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),[]}}}
|
|
6
6
|
export{P as gd,M as hd,m as id,J as jd,k as kd};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{kc as a,lc as b,mc as c,nc as d}from"./chunk-
|
|
2
|
+
import{kc as a,lc as b,mc as c,nc as d}from"./chunk-sztjfky1.js";import"./chunk-zwtx6vn3.js";import"./chunk-s82adeq9.js";export{c as scanCatalogs,d as applyCatalogUpdates,b as WORKSPACE_FILE_ALT,a as WORKSPACE_FILE};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ec as X}from"./chunk-5sh69bkj.js";import{Yc as I}from"./chunk-01d81hn0.js";import{Td as C,ee as P}from"./chunk-2b07w74s.js";import{ne as x,oe as V}from"./chunk-y1d6e0ye.js";import Y from"process";var Z=[["actionlint","actionlint"],["shellcheck","shellcheck"],["hadolint","hadolint"],["markdownlint","markdownlint"]];async function R(q,J={}){let W=J.env??Y.env,Q=J.cwd??Y.cwd(),F=J.hasCommand??C,G=[];G.push({name:"bun",status:"ok",detail:`Bun ${Bun.version}`});let H=!1,$;try{let j=Bun.spawn(["git","rev-parse","--is-inside-work-tree"],{cwd:Q,stdout:"pipe",stderr:"ignore",timeout:5000}),[M,D]=await Promise.all([j.exited,new Response(j.stdout).text()]);H=M===0&&D.trim()==="true"}catch(j){$=j instanceof Error?j.message:String(j)}G.push(H?{name:"git repository",status:"ok",detail:Q}:{name:"git repository",status:"fail",detail:$?`Git could not inspect ${Q}: ${$}`:`${Q} is not a git repository`,remediation:$?"Check that Git is installed and the working directory exists.":"Run buddy from inside a repository, or run `git init`."});let b=I(q);G.push(b.length===0?{name:"configuration",status:"ok",detail:"valid"}:{name:"configuration",status:"fail",detail:`${b.length} problem(s): ${b.slice(0,3).map((j)=>`${j.path} ${j.message}`).join("; ")}`,remediation:"Fix the paths reported above in buddy.config.ts."});let S=Boolean(q.repository?.owner&&q.repository.name);G.push(S?{name:"repository config",status:"ok",detail:`${q.repository.owner}/${q.repository.name}`}:{name:"repository config",status:"warn",detail:"owner and name are not set",remediation:"Set repository.owner and repository.name, or run in Actions where GITHUB_REPOSITORY is available. Local review works without them."});let K=q.repository?.provider??"github",U=q.repository?.token?{token:q.repository.token,source:"repository.token"}:V(K,W);G.push(U?{name:"git token",status:"ok",detail:`found in ${U.source}`}:{name:"git token",status:"warn",detail:"no token found",remediation:`Set one of ${(x[K]??[]).join(", ")}. Local review does not need one.`});let B=X(q,W);G.push(B?{name:"ai provider",status:"ok",detail:`${B.provider} via ${B.apiKeyEnv}`}:{name:"ai provider",status:"warn",detail:"no API key found",remediation:"Set ANTHROPIC_API_KEY (or OPENAI_API_KEY / GOOGLE_API_KEY). Dependency updates and static analysis work without one."});for(let[j,M]of Z){let D=await F(M);G.push(D?{name:`analyzer: ${j}`,status:"ok",detail:`${M} found`}:{name:`analyzer: ${j}`,status:"warn",detail:`${M} not installed`,remediation:`Install ${M} to enable the ${j} analyzer. Reviews run without it and report it as skipped.`})}let w=P.filter((j)=>!Z.some(([M])=>M===j.name)).map((j)=>j.name);return G.push({name:"native analyzers",status:"ok",detail:`${w.join(", ")} \u2014 always available`}),{checks:G,healthy:!G.some((j)=>j.status==="fail")}}var A={ok:"\u2705",warn:"\u26A0\uFE0F ",fail:"\u274C"};function E(q){let J=["","Buddy environment",""];for(let F of q.checks)if(J.push(`${A[F.status]} ${F.name}: ${F.detail}`),F.remediation)J.push(` \u2192 ${F.remediation}`);let W=q.checks.filter((F)=>F.status==="fail").length,Q=q.checks.filter((F)=>F.status==="warn").length;return J.push(""),J.push(q.healthy?`Ready. ${Q} optional capability/capabilities unavailable.`:`${W} problem(s) must be fixed before buddy can run.`),`${J.join(`
|
|
3
|
+
`)}
|
|
4
|
+
`}
|
|
5
|
+
export{R as W,E as X};
|