@buddysh/buddy 0.11.2 → 0.11.3

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.
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Uc as oX}from"./chunk-0eg3kxb5.js";import{Zc as sX}from"./chunk-dqbk3kcj.js";import{Fh as iX}from"./chunk-hfjywbbc.js";import{Wk as n}from"./chunk-q4t568hv.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return UQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
2
+ import{Uc as oX}from"./chunk-cs066zt9.js";import{Zc as sX}from"./chunk-e2t5jq26.js";import{Fh as iX}from"./chunk-hfjywbbc.js";import{Wk as n}from"./chunk-q4t568hv.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return UQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
3
3
  `);for(let W of z)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:M.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let J=`${H} ${this.environment}.${Q.toUpperCase()}: ${U}
4
4
  `;if(G)J+=`${G}
5
5
  `;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!S()){let Y=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:M.blue("\u25D0"),tag:Y,message:`${M.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
@@ -292,8 +292,9 @@ ${Yz(Z)}
292
292
  env:
293
293
  # Use the built-in GITHUB_TOKEN for commits and PRs \u2014 contributions are attributed
294
294
  # to github-actions[bot] instead of a personal account.
295
- # BUDDY_TOKEN (a PAT with 'repo' and 'workflow' scopes) is only used when
296
- # workflow file updates are needed. Create one at: https://github.com/settings/tokens
295
+ # BUDDY_TOKEN (a PAT with 'repo' and 'workflow' scopes) is used for
296
+ # workflow file updates, and to open the PR when the repository does not let
297
+ # GitHub Actions create pull requests. Create one at: https://github.com/settings/tokens
297
298
  GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
298
299
  BUDDY_TOKEN: \${{ secrets.BUDDY_TOKEN }}
299
300
 
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{od as A}from"./chunk-cwfkm7h9.js";import{le as G,me as q}from"./chunk-p8tmms5h.js";import{sf as T}from"./chunk-08x5b93v.js";import{If as S}from"./chunk-p6qbqsyp.js";import{Ch as K,Fh as O}from"./chunk-hfjywbbc.js";import{Wk as I}from"./chunk-q4t568hv.js";var w=[{kind:"lockfile-drift",mechanical:!0,patterns:[/lockfile had changes, but lockfile is frozen/i,/your lockfile does not satisfy your workspace/i,/the lockfile (?:is|was) out of date/i,/npm ci can only install packages when your package\.json and package-lock\.json .* are in sync/i,/composer\.lock is not up to date/i]},{kind:"flake",mechanical:!0,patterns:[/\bECONNRESET\b|\bETIMEDOUT\b|\bENOTFOUND\b|\bEAI_AGAIN\b/,/socket hang up/i,/502 Bad Gateway|503 Service Unavailable|504 Gateway Time-?out/i,/rate limit exceeded/i,/the runner has received a shutdown signal/i]},{kind:"install",mechanical:!1,patterns:[/could not resolve (?:dependency|host)/i,/no matching version found for/i,/unable to resolve dependency tree/i,/peer dep(?:endency)? .* conflict/i]},{kind:"type-error",mechanical:!1,patterns:[/error TS\d{4}:/,/\berror\[E\d+\]:/,/Type '.*' is not assignable to type/]},{kind:"test-failure",mechanical:!1,patterns:[/\d+ (?:tests? )?fail(?:ed|ing)\b/i,/\(fail\)/,/AssertionError|expect\(received\)/,/\u25CF .* \u203A /]},{kind:"lint",mechanical:!1,patterns:[/\b\d+ problems? \(\d+ errors?/i,/eslint|pickier|biome|oxlint/i]}];function N(x){if(!x.trim())return{kind:"unknown",mechanical:!1,evidence:[]};let H=x.split(`
2
+ import{od as A}from"./chunk-cwfkm7h9.js";import{le as G,me as q}from"./chunk-5av2vnvv.js";import{sf as T}from"./chunk-08x5b93v.js";import{If as S}from"./chunk-p6qbqsyp.js";import{Ch as K,Fh as O}from"./chunk-hfjywbbc.js";import{Wk as I}from"./chunk-q4t568hv.js";var w=[{kind:"lockfile-drift",mechanical:!0,patterns:[/lockfile had changes, but lockfile is frozen/i,/your lockfile does not satisfy your workspace/i,/the lockfile (?:is|was) out of date/i,/npm ci can only install packages when your package\.json and package-lock\.json .* are in sync/i,/composer\.lock is not up to date/i]},{kind:"flake",mechanical:!0,patterns:[/\bECONNRESET\b|\bETIMEDOUT\b|\bENOTFOUND\b|\bEAI_AGAIN\b/,/socket hang up/i,/502 Bad Gateway|503 Service Unavailable|504 Gateway Time-?out/i,/rate limit exceeded/i,/the runner has received a shutdown signal/i]},{kind:"install",mechanical:!1,patterns:[/could not resolve (?:dependency|host)/i,/no matching version found for/i,/unable to resolve dependency tree/i,/peer dep(?:endency)? .* conflict/i]},{kind:"type-error",mechanical:!1,patterns:[/error TS\d{4}:/,/\berror\[E\d+\]:/,/Type '.*' is not assignable to type/]},{kind:"test-failure",mechanical:!1,patterns:[/\d+ (?:tests? )?fail(?:ed|ing)\b/i,/\(fail\)/,/AssertionError|expect\(received\)/,/\u25CF .* \u203A /]},{kind:"lint",mechanical:!1,patterns:[/\b\d+ problems? \(\d+ errors?/i,/eslint|pickier|biome|oxlint/i]}];function N(x){if(!x.trim())return{kind:"unknown",mechanical:!1,evidence:[]};let H=x.split(`
3
3
  `);for(let z of w){let J=[];for(let V of H)if(z.patterns.some((Q)=>Q.test(V))){if(J.push(V.trim()),J.length>=5)break}if(J.length>0)return{kind:z.kind,mechanical:z.mechanical,evidence:J}}return{kind:"unknown",mechanical:!1,evidence:P(H)}}function P(x,H=40){let z=x.filter((J)=>/\b(?:error|failed|failure|exception|panic|fatal)\b/i.test(J)&&!/^\s*(?:at\s|\s*\.\.\.)/.test(J));return(z.length>0?z:x.slice(-H)).slice(-H).map((J)=>J.trim()).filter(Boolean)}function X(x){switch(x.kind){case"lockfile-drift":return"The lock file is out of step with its manifest.";case"flake":return"A network or runner problem, unrelated to the change.";case"install":return"Dependencies could not be resolved.";case"type-error":return"The change does not type-check.";case"test-failure":return"One or more tests failed.";case"lint":return"Lint or formatting checks failed.";default:return"The failure could not be classified automatically."}}var b=3;async function _(x,H,z,J){let V=J??O();try{let Q=await x.listWorkflowRuns(H,{status:"completed",limit:20});for(let Y of F(Q).slice(0,b)){let Z=await x.getWorkflowRunLogs(Y.id);if(!Z)continue;if(N(Z).kind===z)return V.info(`\uD83E\uDDED ${H} already fails the same way (run ${Y.id}) \u2014 not this pull request's to fix`),!0}return!1}catch(Q){return V.debug(`Could not check ${H} for a pre-existing failure: ${K(Q)}`),!1}}function F(x){let H=new Map;for(let z of x)if(!H.has(z.name))H.set(z.name,z);return[...H.values()].filter((z)=>z.conclusion==="failure")}function h(x,H){if(!x)return"Tried to regenerate the lock file, but the install did not succeed.";if(!H)return"Regenerated the lock file, but could not push it to the branch. The change is in the workspace only, so the run will still be red until someone commits it.";return"Regenerated the lock file and pushed the result. No model was needed."}function m(x){let H="Repairs run on the pull request's branch, and answering a comment runs on the default branch, so anything I changed here would land on the wrong tree. ";if(x.kind==="lockfile-drift")return`Regenerating the lock file would fix this, and no model would be needed. ${H}The \`fix-ci\` job will do it on the next failing run, or you can run \`buddy fix-ci --run-id <id> --pr <number>\` yourself.`;return`${H}The \`fix-ci\` job runs on the failing run itself and can repair this; this reply is the diagnosis it would start from.`}async function M(x){let H=x.logger??O(),z=N(x.log),J=x.maxAttempts??3;if(H.info(`\uD83E\uDE7A CI failure classified as ${z.kind}`),x.failsOnBase??(x.checkBase?await x.checkBase(z.kind):!1))return{failure:z,action:"skipped",fixed:!1,report:$(z,"This failure also occurs on the base branch, so it is not caused by this change. Fixing it here would only mask it.")};if((x.priorAttempts??0)>=J)return{failure:z,action:"skipped",fixed:!1,report:$(z,`Already attempted ${x.priorAttempts} time(s); stopping rather than looping.`)};if(x.analysisOnly&&z.kind!=="flake")return{failure:z,action:"reported",fixed:!1,report:$(z,m(z))};if(z.kind==="lockfile-drift"&&x.regenerateLockfile){if(x.dryRun)return{failure:z,action:"mechanical-fix",fixed:!1,report:$(z,"Regenerating the lock file would fix this. No model would be needed. Nothing was changed, because this was a dry run.")};H.info("\uD83D\uDD27 Regenerating the lock file");let{regenerated:Y,pushed:Z}=await x.regenerateLockfile();return{failure:z,action:"mechanical-fix",fixed:Z,report:$(z,h(Y,Z))}}if(z.kind==="flake"){if(x.dryRun)return{failure:z,action:"retry",fixed:!1,report:$(z,"This looks transient, and re-running the failed jobs would likely clear it. Nothing was changed, because this was a dry run.")};if(!x.rerun)return{failure:z,action:"retry",fixed:!1,report:$(z,"This looks transient. Re-running the failed job is likely to clear it.")};H.info("\uD83D\uDD01 Re-running the failed jobs");let Y=await x.rerun();return{failure:z,action:"retry",fixed:!1,report:$(z,Y?"This looks transient, so I re-ran the failed jobs. No model was needed.":"This looks transient, but I could not re-run the failed jobs \u2014 `actions: write` is the usual reason. "+"Re-running them from the Actions tab is likely to clear it.")}}if(!x.ai)return{failure:z,action:"reported",fixed:!1,report:$(z,"No AI provider is configured, so this needs a human. See https://buddy.sh/ai/providers to enable automatic repair.")};let Q=await S(x.ai,{mode:T,task:["A CI job on this branch is failing. Diagnose the root cause and fix it if the fix is clear.","",`Classification: ${z.kind} \u2014 ${X(z)}`,"","Relevant log lines:",z.evidence.join(`
4
4
  `),"","Verify your fix by running the project's tests or build before reporting it done.","If the fix is not clear, explain what you found rather than guessing."].join(`
5
5
  `),context:{workspace:x.workspace,baseBranch:x.baseBranch,...x.branch?{branch:x.branch}:{}},logger:H});return{failure:z,action:"agent-fix",fixed:Q.stopReason==="completed",report:$(z,Q.output||"The repair run ended without a conclusion.")}}function $(x,H){let z=`## \uD83E\uDE7A CI failure analysis
package/dist/src/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{I as wo,J as So,K as ho,L as uo,M as co,N as Vo,O as eo,P as go,Q as ro,R as vo,S as io,T as so,U as no}from"../chunk-0w695m54.js";import{W as ko,X as qo}from"../chunk-929h6hhp.js";import{$ as Wo,Y as Jo,Z as Ko,_ as Qo}from"../chunk-jnb80k2x.js";import{aa as PR,ba as aR,ca as lR,da as yR,ea as CR,fa as NR,ga as _R,ha as zR,ia as DR,ja as TR}from"../chunk-69qyr9ef.js";import{ka as pR,la as oR,ma as mR,na as xR,oa as fR,pa as dR,qa as RR,ra as MR,sa as UR,ta as AR,ua as GR,va as ER,wa as OR}from"../chunk-fjp3a7hp.js";import{Aa as $o,Ba as bo,Ca as to,xa as Xo,ya as Yo,za as Zo}from"../chunk-3cvng2nz.js";import"../chunk-rb1fh9vd.js";import{Da as pm}from"../chunk-657nbbp7.js";import{Ea as ed,Fa as gd,Ga as rd,Ha as vd,Ia as id,Ja as sd,Ka as nd}from"../chunk-6bd8ghkz.js";import{La as Zd,Ma as $d,Na as bd,Oa as td,Pa as wd,Qa as Sd,Ra as hd,Sa as ud,Ta as cd,Ua as Vd}from"../chunk-96ht6hwd.js";import{Va as Yf,Wa as Zf}from"../chunk-s6z3gm2s.js";import{$a as Sf,Xa as $f,Ya as bf,Za as tf,_a as wf,ab as hf,bb as uf,cb as cf,db as Vf,eb as ef,fb as gf,gb as rf}from"../chunk-s4zb0fcj.js";import{hb as vf,ib as sf,jb as nf,kb as pd,lb as od}from"../chunk-tw047td6.js";import{mb as Id}from"../chunk-cwqhxqv7.js";import{Ab as Td,Bb as jd,Cb as Ld,Db as Bd,nb as dd,ob as Rd,pb as Md,qb as Ud,rb as Ad,sb as Gd,tb as Ed,ub as Od,vb as Pd,wb as Nd,xb as _d,yb as zd,zb as Dd}from"../chunk-1c4690h9.js";import{Eb as md,Fb as xd,Gb as fd}from"../chunk-q2tjkhez.js";import{Hb as Co,Ib as No,Jb as _o,Kb as zo}from"../chunk-vckhctmr.js";import{Lb as ad,Mb as ld,Nb as yd,Pb as Cd}from"../chunk-5yfaptmp.js";import{Qb as Rf,Rb as Mf,Sb as Uf,Tb as Af,Ub as Gf,Vb as Ef,Wb as Of,Xb as Pf,Yb as af}from"../chunk-rc2mk5x6.js";import{$b as nx,Zb as ix,_b as sx,ac as pf,bc as of,cc as mf,dc as xf,ec as ff,fc as df}from"../chunk-tjc2vgwn.js";import{gc as Vp,hc as ep,ic as gp,jc as rp,mc as vp,nc as ip}from"../chunk-61xecp1z.js";import{Ac as Uo,Bc as Ao,Cc as Go,Dc as Eo,Ec as Oo,Fc as Po,Gc as ao,Hc as lo,Ic as yo,pc as sp,sc as np,tc as po,uc as oo,vc as mo,wc as xo,xc as fo,yc as Ro,zc as Mo}from"../chunk-6p4qz8qv.js";import{Jc as dp}from"../chunk-tws3npt7.js";import{Kc as mp,Lc as xp,Mc as fp}from"../chunk-8fw0v7bv.js";import{Oc as mm,Pc as xm,Qc as fm,Rc as dm}from"../chunk-15r904nz.js";import{Sc as Bo,Tc as Fo,Uc as Ho}from"../chunk-0eg3kxb5.js";import{Vc as Sp,Wc as hp,Xc as up,Yc as cp,_c as Do}from"../chunk-dqbk3kcj.js";import"../chunk-phfmnnne.js";import{ad as _p,bd as zp,cd as Dp,dd as Tp,ed as jp}from"../chunk-r763e19p.js";import{fd as wp}from"../chunk-be629jhq.js";import"../chunk-pkr6905p.js";import{hd as ex,id as gx,jd as rx,kd as vx}from"../chunk-eseshkd0.js";import{nd as Np}from"../chunk-11hdrnf6.js";import{od as Xf}from"../chunk-cwfkm7h9.js";import{pd as $x,qd as bx,rd as tx,sd as wx,td as Sx,ud as hx,vd as ux,wd as cx,xd as Vx}from"../chunk-mkzmjg3f.js";import{Ad as kd,Bd as qd,Cd as Jd,Dd as Kd,Ed as Qd,Fd as Wd,Gd as Xd,Hd as Yd,yd as Fd,zd as Hd}from"../chunk-vgtmrd4c.js";import{$d as Wf,Id as lf,Jd as yf,Kd as Cf,Ld as Nf,Md as _f,Nd as zf,Od as Df,Pd as Tf,Qd as jf,Rd as If,Sd as Lf,Td as Bf,Ud as Ff,Vd as Hf,Wd as kf,Xd as qf,Yd as Jf,Zd as Kf,_d as Qf}from"../chunk-nrr8z2z7.js";import"../chunk-xs12dtf1.js";import{ce as Rp,de as Mp,ee as Up,fe as Ap,ge as Gp,he as Ep,ie as Op,je as Pp,ke as ap,le as lp,me as yp}from"../chunk-p8tmms5h.js";import"../chunk-ytmxd5fk.js";import{Ae as Kp,Be as Qp,Ce as Wp,se as Ip,te as Lp,ue as Bp,ve as Fp,we as Hp,xe as kp,ye as qp,ze as Jp}from"../chunk-b9escac0.js";import{Je as Cp}from"../chunk-g30dr44w.js";import{Ke as Xp,Le as Yp,Me as Zp,Ne as $p,Oe as bp,Pe as tp}from"../chunk-2et8yavs.js";import"../chunk-txtrpypt.js";import{$e as _,We as a,Xe as l,Ye as y,Ze as C,_e as N,af as z,bf as D,cf as T,df as j,ef as I,ff as L,gf as B,hf as F,if as H}from"../chunk-8hjvthz4.js";import{jf as U,kf as A,lf as G,mf as E,nf as O,pf as P}from"../chunk-yngahb11.js";import{qf as Px,rf as ax,sf as lx,tf as yx,uf as Cx,vf as Nx}from"../chunk-08x5b93v.js";import{Af as kx,Bf as qx,Cf as Jx,Df as Kx,Ef as Qx,Ff as Wx,Gf as Xx,Hf as Yx,If as Zx,wf as Lx,xf as Bx,yf as Fx,zf as Hx}from"../chunk-p6qbqsyp.js";import"../chunk-1cpdz49v.js";import{Lf as _x,Mf as zx,Nf as Dx,Of as Tx,Pf as jx,Qf as Ix}from"../chunk-cgvt98pd.js";import"../chunk-c8rzx3a1.js";import{$f as pp,Uf as e,Vf as g,Wf as r,Xf as v,Yf as i,Zf as s,_f as n,ag as op,bg as d}from"../chunk-0hc97k0t.js";import"../chunk-3901s7h9.js";import"../chunk-jtxcr5yw.js";import"../chunk-qd2s51gc.js";import{$g as JR,Og as To,Pg as jo,Qg as Io,Rg as Lo,Tg as jR,Ug as IR,Vg as LR,Wg as BR,Xg as FR,Yg as HR,Zg as kR,_g as qR,ah as KR,bh as QR,ch as WR,dh as XR,eh as YR,fh as ZR,gh as $R,hh as bR,ih as tR,jh as wR,kh as SR,lh as hR,mh as uR}from"../chunk-bymwaezh.js";import{nh as om}from"../chunk-k26wnmzk.js";import{oh as S,ph as h,qh as u,rh as c,sh as V}from"../chunk-193abzy6.js";import{th as t}from"../chunk-5044y9en.js";import{uh as w}from"../chunk-f53y8ans.js";import{Ah as Y,vh as J,wh as K,xh as Q,yh as W,zh as X}from"../chunk-e68nf7cm.js";import{Bh as k,Ch as q,Dh as Z,Eh as $,Fh as b}from"../chunk-hfjywbbc.js";import"../chunk-g24hav8e.js";import"../chunk-q4t568hv.js";var{semver:m}=globalThis.Bun;class R{static compareVersions(p,o){return m.order(p,o)}static satisfiesRange(p,o){return m.satisfies(p,o)}static getLatestInRange(p,o){let f=p.filter((x)=>m.satisfies(x,o));if(f.length===0)return null;return f.sort((x,M)=>m.order(M,x))[0]}static createRange(p){return{raw:p,range:p.replace(/^[\^~>=<]+/,""),isExact:!/^[\^~>=<]/.test(p),satisfies:(o)=>this.satisfiesRange(o,p),getLatest:(o)=>this.getLatestInRange(o,p)}}static getUpdateType(p,o){return d(p,o)}static isSafeUpdate(p,o){return m.satisfies(o,p)}}export{Fx as writeFileTool,Yx as wrapUntrusted,gf as withTouchOffer,no as withNarrative,sf as verifyChanges,tR as validateWorkflowGeneration,wR as validateRepositoryAccess,Ud as validateFindings,Bo as validateConfig,Jo as validateAgainstSchema,HR as updateProgress,bf as unitTestsTouch,Sp as toOsvEcosystem,Hp as tagUpdateType,Kf as syntaxAnalyzer,lp as supports,z as summarizeUsage,fR as summarizeGates,lo as stripOperators,bd as stripNonCommandContext,nf as stackedBranchName,Mo as splitConstraint,op as sortUpdatesByPriority,wf as simplifyTouch,yR as similarity,Vx as sign,uR as showFinalInstructions,N as shouldOpenAsDraft,Yd as shouldFail,Jf as shellcheckAnalyzer,Kx as shellTool,hR as setupCustomWorkflow,$ as setDefaultLogger,ld as serializeReviewState,Af as serializeLearnings,Of as selectLearnings,Fp as selectLatestTag,qf as secretsAnalyzer,YR as schedulePlan,ao as scanEcosystems,vp as scanCatalogs,Bp as sameVariant,Go as rustAdapter,yf as runTool,pd as runStackedTouch,Bd as runReviewForPR,LR as runPreflightChecks,ER as runPostMerge,Zf as runPlan,Ko as runHeadless,xR as runGates,nd as runFixCi,Wf as runAnalyzers,UR as runAiGates,Zx as runAgent,A as ruleMatches,Ao as rubyAdapter,Ld as reviewPullRequest,Px as reviewMode,Ed as reviewDiff,Lx as resolveWorkspacePath,G as resolveRuleEffects,Op as resolveProviderToken,pf as resolveModelAlias,bp as resolveEngineVersion,Kp as resolveCredentials,ep as resolveCatalogReference,Id as resolveBuddyThreads,ff as resolveAiProvider,fm as resetConfigCache,Vf as renderTouchOffer,so as renderReport,TR as renderQuickLinks,aR as renderPackageContext,D as renderMigrationReport,Pf as renderLearnings,Td as renderFinding,qo as renderDoctorReport,xd as renderDiffForReview,_f as relativize,yo as regenerateLockfiles,xp as regenerateLockFile,Tx as redactError,Dx as redactDeep,zx as redact,Bx as readFileTool,Uo as pythonAdapter,Wo as publishOutput,Yo as productFor,jd as prepareReview,Sf as planTouch,yx as planMode,$p as pinBlocksUpdate,Ro as pep440UpdateType,Vp as parseWorkspaceCatalogs,md as parseUnifiedDiff,rf as parseTouchSelections,Nf as parseToolJson,Ip as parseTag,yd as parseReviewState,W as parseRetryDelay,qR as parseRemote,zR as parseQuickSelection,mo as parsePep440,g as parsePackageFile,Uf as parseLearnings,kp as parseImageRef,ho as parseHistory,td as parseCommand,Qp as parseAuthChallenge,If as offsetToLine,po as numericUpdateType,hp as normalizeSeverity,C as normalizePlan,Cd as needsReview,O as mergeGroupEffects,Sd as mentionsBot,B as matchesGlobs,Hf as markdownlintAnalyzer,zp as mapWithConcurrency,Cf as mapSeverity,af as loadLearnings,Vo as loadHistory,zd as loadGuidelines,Hx as listDirTool,Ff as linterAnalyzer,id as latestFailurePerWorkflow,wd as isReadOnlyCommand,fo as isPep440Prerelease,OR as isMergeEvent,gp as isCatalogReference,l as isAllowedCodemod,ax as implementMode,ef as hasTouchOffer,jf as hadolintAnalyzer,KR as guideTokenCreation,WR as guideRepositorySettings,P as groupsToRules,pp as groupUpdates,oo as goAdapter,Tf as githubActionsAnalyzer,bR as getWorkflowPreset,c as getNpmRegistryUrl,h as getGitHubServerUrl,S as getGitHubApiUrl,uf as getFinishingTouch,b as getDefaultLogger,xm as getConfig,V as getComposerRegistryUrl,mp as getAllLockFilePaths,Nx as getAgentMode,ZR as generateUnifiedWorkflow,jo as generateGitLabPipeline,$R as generateCoreWorkflows,XR as generateConfigFile,n as generateBranchName,Io as generateBitbucketPipeline,dR as gateIcon,kx as fsTools,e as formatSecurityAdvisorySection,Wd as formatReview,qd as formatPretty,i as formatPRTitle,s as formatPRBody,qp as formatImageRef,Qo as formatGithubOutput,Jd as formatGithub,q as formatError,Fo as formatConfigIssues,v as formatCommitMessage,Kd as formatAgent,lx as fixCiMode,Md as fingerprint,_ as findUsageSites,co as findPrevious,PR as findMentionedPackages,AR as findLinkedIssues,CR as findDuplicates,_o as findDrift,X as fetchWithTimeout,Y as fetchJsonOrNull,vd as failsOnBaseBranch,gd as extractErrorLines,Yp as extractEngines,Xf as emitEvent,U as ecosystemOf,Co as driftFor,$f as docstringsTouch,SR as displayValidationResults,kR as displayProgress,cd as dispatchCommand,Hd as diffArgsFor,ko as diagnose,fp as detectRequiredPackageManagers,JR as detectRepository,r as detectPackageManager,Bf as detectLinter,sp as detectFiles,od as detectChangedFiles,L as describeSpanGaps,rd as describeFailure,tx as describeEvent,to as describeEol,zo as describeDrift,Pd as defaultIncludePath,mm as defaultConfig,Ad as dedupeFindings,Zo as cycleFor,cx as createWebhookSink,hx as createSlackSink,Sx as createSinks,Yf as createReadIssueTool,ap as createProvider,FR as createProgressTracker,xf as createOpenAiProvider,Gf as createLearning,Vd as createHandlers,mf as createGoogleProvider,ux as createDiscordSink,of as createAnthropicProvider,df as createAiClient,Qd as countBySeverity,lR as constrainLabels,QR as confirmTokenSetup,dm as config,ro as computeMetrics,vo as computeDeltas,Dd as composeInstructions,Lp as compareVersions,xo as comparePep440,np as compareNumeric,zf as commandExists,I as collectSpanNotes,Zp as collectResolutionPins,kd as collectLocalDiff,fd as collectGitDiff,DR as clearQuickSelection,u as clearNpmrcCache,ed as classifyFailure,Lo as ciTemplateFor,Dp as chunk,pR as checkTitleFormat,ud as checkPermission,RR as checkLinkedIssue,$o as checkEol,oR as checkDescription,mR as checkDependencies,MR as checkCustomAssertions,tp as bumpEngineConstraint,Jx as buildShellEnv,y as buildAnalysisPrompt,tf as autofixTouch,T as attemptMajorUpgrade,sd as attemptFix,Ho as assertValidConfig,yp as assertSupports,Pp as assertProviderSupported,Xd as applySuggestion,E as applyRules,ip as applyCatalogUpdates,rp as applyCatalogUpdate,H as appendUpgradeReport,uo as appendHistory,GR as appendChangelogEntry,Jp as apiHostFor,Od as anchorMap,BR as analyzeProject,F as analyzeGroupMajors,cp as advisoryKey,Ef as addLearning,Po as adapterNamed,Oo as adapterFor,Df as actionlintAnalyzer,wx as WEBHOOK_PAYLOAD_VERSION,R as VersionResolver,Gp as UnsupportedProviderError,Xx as Toolbelt,Qx as ToolPermissionError,cf as TOUCH_OFFER_MARKER,lf as TOOL_TIMEOUT_MS,vf as TEST_COMMANDS,up as SecurityAdvisoryService,pm as Scheduler,qx as SHELL_ENV_ALLOWLIST,dd as SEVERITY_ORDER,kf as SECRET_RULES,Cp as ReleaseNotesFetcher,jp as RegistryClient,No as ROOT,ad as REVIEW_STATE_VERSION,Rd as REVIEW_SCHEMA,Fd as REVIEW_FORMATS,eo as REPORT_PERIODS,io as REPORT_MARKER,_x as REDACTED,$d as READ_ONLY_COMMANDS,NR as QUICK_LINKS_MARKER,_R as QUICK_ACTIONS,Np as PullRequestGenerator,IR as PluginManager,wp as PackageScanner,gx as PackageRegistryError,Up as PROVIDER_TRACKING_ISSUES,Ep as PROVIDER_TOKEN_ENV,nx as PROVIDER_PRIORITY,Rp as PROVIDER_NAMES,sx as PROVIDER_KEY_ENV,go as PERIOD_DAYS,Wp as OciClient,Ap as NO_CAPABILITIES,ix as MODEL_ALIASES,a as MIGRATION_PLAN_SCHEMA,_d as MAX_GUIDELINE_CHARS,Z as Logger,Lf as LINTER_SPECS,Xp as KNOWN_ENGINES,Mp as IMPLEMENTED_PROVIDERS,Q as HttpRequestError,wo as HISTORY_PATH,So as HISTORY_LIMIT,hd as HELP_TEXT,rx as GitProviderError,t as GitLabProvider,dp as GitHubProvider,k as GitHubApiError,om as GitHubActionsTemplate,hf as FINISHING_TOUCHES,bx as EventBus,$x as EVENT_NAMES,bo as EOL_WARNING_DAYS,Xo as EOL_PRODUCTS,J as DEFAULT_TIMEOUT_MS,j as DEFAULT_SPAN_BUDGET,To as DEFAULT_SCHEDULE,K as DEFAULT_RETRIES,Mf as DEFAULT_PROMPT_LIMIT,Rf as DEFAULT_LEARNINGS_FILE,Nd as DEFAULT_GUIDELINE_FILES,Gd as DEFAULT_EXCLUDED_PATHS,_p as DEFAULT_CONCURRENCY,jR as ConfigurationMigrator,vx as ConfigurationError,Zd as COMMAND_ALIASES,ex as BuddyError,Do as Buddy,w as BitbucketProvider,Wx as BUILTIN_TOOLS,Qf as BUILTIN_ANALYZERS,Eo as BUILTIN_ADAPTERS,Tp as AsyncMemo,Ix as AiProviderError,jx as AiBudgetExceededError,Cx as AGENT_MODES};
2
+ import{I as wo,J as So,K as ho,L as uo,M as co,N as Vo,O as eo,P as go,Q as ro,R as vo,S as io,T as so,U as no}from"../chunk-0w695m54.js";import{W as ko,X as qo}from"../chunk-rayxmbcx.js";import{$ as Wo,Y as Jo,Z as Ko,_ as Qo}from"../chunk-jnb80k2x.js";import{aa as PR,ba as aR,ca as lR,da as yR,ea as CR,fa as NR,ga as _R,ha as zR,ia as DR,ja as TR}from"../chunk-69qyr9ef.js";import{ka as pR,la as oR,ma as mR,na as xR,oa as fR,pa as dR,qa as RR,ra as MR,sa as UR,ta as AR,ua as GR,va as ER,wa as OR}from"../chunk-fjp3a7hp.js";import{Aa as $o,Ba as bo,Ca as to,xa as Xo,ya as Yo,za as Zo}from"../chunk-3cvng2nz.js";import"../chunk-rb1fh9vd.js";import{Da as pm}from"../chunk-jz5zs812.js";import{Ea as ed,Fa as gd,Ga as rd,Ha as vd,Ia as id,Ja as sd,Ka as nd}from"../chunk-yr8eta7p.js";import{La as Zd,Ma as $d,Na as bd,Oa as td,Pa as wd,Qa as Sd,Ra as hd,Sa as ud,Ta as cd,Ua as Vd}from"../chunk-96ht6hwd.js";import{Va as Yf,Wa as Zf}from"../chunk-s6z3gm2s.js";import{$a as Sf,Xa as $f,Ya as bf,Za as tf,_a as wf,ab as hf,bb as uf,cb as cf,db as Vf,eb as ef,fb as gf,gb as rf}from"../chunk-s4zb0fcj.js";import{hb as vf,ib as sf,jb as nf,kb as pd,lb as od}from"../chunk-tw047td6.js";import{mb as Id}from"../chunk-patms7t8.js";import{Ab as Td,Bb as jd,Cb as Ld,Db as Bd,nb as dd,ob as Rd,pb as Md,qb as Ud,rb as Ad,sb as Gd,tb as Ed,ub as Od,vb as Pd,wb as Nd,xb as _d,yb as zd,zb as Dd}from"../chunk-4jyw358y.js";import{Eb as md,Fb as xd,Gb as fd}from"../chunk-q2tjkhez.js";import{Hb as Co,Ib as No,Jb as _o,Kb as zo}from"../chunk-vckhctmr.js";import{Lb as ad,Mb as ld,Nb as yd,Pb as Cd}from"../chunk-5yfaptmp.js";import{Qb as Rf,Rb as Mf,Sb as Uf,Tb as Af,Ub as Gf,Vb as Ef,Wb as Of,Xb as Pf,Yb as af}from"../chunk-rc2mk5x6.js";import{$b as nx,Zb as ix,_b as sx,ac as pf,bc as of,cc as mf,dc as xf,ec as ff,fc as df}from"../chunk-tjc2vgwn.js";import{gc as Vp,hc as ep,ic as gp,jc as rp,mc as vp,nc as ip}from"../chunk-61xecp1z.js";import{Ac as Uo,Bc as Ao,Cc as Go,Dc as Eo,Ec as Oo,Fc as Po,Gc as ao,Hc as lo,Ic as yo,pc as sp,sc as np,tc as po,uc as oo,vc as mo,wc as xo,xc as fo,yc as Ro,zc as Mo}from"../chunk-6p4qz8qv.js";import{Jc as dp}from"../chunk-bmnx3s41.js";import{Kc as mp,Lc as xp,Mc as fp}from"../chunk-8fw0v7bv.js";import{Oc as mm,Pc as xm,Qc as fm,Rc as dm}from"../chunk-tsckfwch.js";import{Sc as Bo,Tc as Fo,Uc as Ho}from"../chunk-cs066zt9.js";import{Vc as Sp,Wc as hp,Xc as up,Yc as cp,_c as Do}from"../chunk-e2t5jq26.js";import"../chunk-phfmnnne.js";import{ad as _p,bd as zp,cd as Dp,dd as Tp,ed as jp}from"../chunk-r763e19p.js";import{fd as wp}from"../chunk-be629jhq.js";import"../chunk-pkr6905p.js";import{hd as ex,id as gx,jd as rx,kd as vx}from"../chunk-eseshkd0.js";import{nd as Np}from"../chunk-11hdrnf6.js";import{od as Xf}from"../chunk-cwfkm7h9.js";import{pd as $x,qd as bx,rd as tx,sd as wx,td as Sx,ud as hx,vd as ux,wd as cx,xd as Vx}from"../chunk-mkzmjg3f.js";import{Ad as kd,Bd as qd,Cd as Jd,Dd as Kd,Ed as Qd,Fd as Wd,Gd as Xd,Hd as Yd,yd as Fd,zd as Hd}from"../chunk-vgtmrd4c.js";import{$d as Wf,Id as lf,Jd as yf,Kd as Cf,Ld as Nf,Md as _f,Nd as zf,Od as Df,Pd as Tf,Qd as jf,Rd as If,Sd as Lf,Td as Bf,Ud as Ff,Vd as Hf,Wd as kf,Xd as qf,Yd as Jf,Zd as Kf,_d as Qf}from"../chunk-nrr8z2z7.js";import"../chunk-xs12dtf1.js";import{ce as Rp,de as Mp,ee as Up,fe as Ap,ge as Gp,he as Ep,ie as Op,je as Pp,ke as ap,le as lp,me as yp}from"../chunk-5av2vnvv.js";import"../chunk-ytmxd5fk.js";import{Ae as Kp,Be as Qp,Ce as Wp,se as Ip,te as Lp,ue as Bp,ve as Fp,we as Hp,xe as kp,ye as qp,ze as Jp}from"../chunk-b9escac0.js";import{Je as Cp}from"../chunk-g30dr44w.js";import{Ke as Xp,Le as Yp,Me as Zp,Ne as $p,Oe as bp,Pe as tp}from"../chunk-2et8yavs.js";import"../chunk-txtrpypt.js";import{$e as _,We as a,Xe as l,Ye as y,Ze as C,_e as N,af as z,bf as D,cf as T,df as j,ef as I,ff as L,gf as B,hf as F,if as H}from"../chunk-8hjvthz4.js";import{jf as U,kf as A,lf as G,mf as E,nf as O,pf as P}from"../chunk-yngahb11.js";import{qf as Px,rf as ax,sf as lx,tf as yx,uf as Cx,vf as Nx}from"../chunk-08x5b93v.js";import{Af as kx,Bf as qx,Cf as Jx,Df as Kx,Ef as Qx,Ff as Wx,Gf as Xx,Hf as Yx,If as Zx,wf as Lx,xf as Bx,yf as Fx,zf as Hx}from"../chunk-p6qbqsyp.js";import"../chunk-1cpdz49v.js";import{Lf as _x,Mf as zx,Nf as Dx,Of as Tx,Pf as jx,Qf as Ix}from"../chunk-cgvt98pd.js";import"../chunk-c8rzx3a1.js";import{$f as pp,Uf as e,Vf as g,Wf as r,Xf as v,Yf as i,Zf as s,_f as n,ag as op,bg as d}from"../chunk-0hc97k0t.js";import"../chunk-3901s7h9.js";import"../chunk-jtxcr5yw.js";import"../chunk-qd2s51gc.js";import{$g as JR,Og as To,Pg as jo,Qg as Io,Rg as Lo,Tg as jR,Ug as IR,Vg as LR,Wg as BR,Xg as FR,Yg as HR,Zg as kR,_g as qR,ah as KR,bh as QR,ch as WR,dh as XR,eh as YR,fh as ZR,gh as $R,hh as bR,ih as tR,jh as wR,kh as SR,lh as hR,mh as uR}from"../chunk-vbeeyhhe.js";import{nh as om}from"../chunk-k26wnmzk.js";import{oh as S,ph as h,qh as u,rh as c,sh as V}from"../chunk-193abzy6.js";import{th as t}from"../chunk-5044y9en.js";import{uh as w}from"../chunk-f53y8ans.js";import{Ah as Y,vh as J,wh as K,xh as Q,yh as W,zh as X}from"../chunk-e68nf7cm.js";import{Bh as k,Ch as q,Dh as Z,Eh as $,Fh as b}from"../chunk-hfjywbbc.js";import"../chunk-g24hav8e.js";import"../chunk-q4t568hv.js";var{semver:m}=globalThis.Bun;class R{static compareVersions(p,o){return m.order(p,o)}static satisfiesRange(p,o){return m.satisfies(p,o)}static getLatestInRange(p,o){let f=p.filter((x)=>m.satisfies(x,o));if(f.length===0)return null;return f.sort((x,M)=>m.order(M,x))[0]}static createRange(p){return{raw:p,range:p.replace(/^[\^~>=<]+/,""),isExact:!/^[\^~>=<]/.test(p),satisfies:(o)=>this.satisfiesRange(o,p),getLatest:(o)=>this.getLatestInRange(o,p)}}static getUpdateType(p,o){return d(p,o)}static isSafeUpdate(p,o){return m.satisfies(o,p)}}export{Fx as writeFileTool,Yx as wrapUntrusted,gf as withTouchOffer,no as withNarrative,sf as verifyChanges,tR as validateWorkflowGeneration,wR as validateRepositoryAccess,Ud as validateFindings,Bo as validateConfig,Jo as validateAgainstSchema,HR as updateProgress,bf as unitTestsTouch,Sp as toOsvEcosystem,Hp as tagUpdateType,Kf as syntaxAnalyzer,lp as supports,z as summarizeUsage,fR as summarizeGates,lo as stripOperators,bd as stripNonCommandContext,nf as stackedBranchName,Mo as splitConstraint,op as sortUpdatesByPriority,wf as simplifyTouch,yR as similarity,Vx as sign,uR as showFinalInstructions,N as shouldOpenAsDraft,Yd as shouldFail,Jf as shellcheckAnalyzer,Kx as shellTool,hR as setupCustomWorkflow,$ as setDefaultLogger,ld as serializeReviewState,Af as serializeLearnings,Of as selectLearnings,Fp as selectLatestTag,qf as secretsAnalyzer,YR as schedulePlan,ao as scanEcosystems,vp as scanCatalogs,Bp as sameVariant,Go as rustAdapter,yf as runTool,pd as runStackedTouch,Bd as runReviewForPR,LR as runPreflightChecks,ER as runPostMerge,Zf as runPlan,Ko as runHeadless,xR as runGates,nd as runFixCi,Wf as runAnalyzers,UR as runAiGates,Zx as runAgent,A as ruleMatches,Ao as rubyAdapter,Ld as reviewPullRequest,Px as reviewMode,Ed as reviewDiff,Lx as resolveWorkspacePath,G as resolveRuleEffects,Op as resolveProviderToken,pf as resolveModelAlias,bp as resolveEngineVersion,Kp as resolveCredentials,ep as resolveCatalogReference,Id as resolveBuddyThreads,ff as resolveAiProvider,fm as resetConfigCache,Vf as renderTouchOffer,so as renderReport,TR as renderQuickLinks,aR as renderPackageContext,D as renderMigrationReport,Pf as renderLearnings,Td as renderFinding,qo as renderDoctorReport,xd as renderDiffForReview,_f as relativize,yo as regenerateLockfiles,xp as regenerateLockFile,Tx as redactError,Dx as redactDeep,zx as redact,Bx as readFileTool,Uo as pythonAdapter,Wo as publishOutput,Yo as productFor,jd as prepareReview,Sf as planTouch,yx as planMode,$p as pinBlocksUpdate,Ro as pep440UpdateType,Vp as parseWorkspaceCatalogs,md as parseUnifiedDiff,rf as parseTouchSelections,Nf as parseToolJson,Ip as parseTag,yd as parseReviewState,W as parseRetryDelay,qR as parseRemote,zR as parseQuickSelection,mo as parsePep440,g as parsePackageFile,Uf as parseLearnings,kp as parseImageRef,ho as parseHistory,td as parseCommand,Qp as parseAuthChallenge,If as offsetToLine,po as numericUpdateType,hp as normalizeSeverity,C as normalizePlan,Cd as needsReview,O as mergeGroupEffects,Sd as mentionsBot,B as matchesGlobs,Hf as markdownlintAnalyzer,zp as mapWithConcurrency,Cf as mapSeverity,af as loadLearnings,Vo as loadHistory,zd as loadGuidelines,Hx as listDirTool,Ff as linterAnalyzer,id as latestFailurePerWorkflow,wd as isReadOnlyCommand,fo as isPep440Prerelease,OR as isMergeEvent,gp as isCatalogReference,l as isAllowedCodemod,ax as implementMode,ef as hasTouchOffer,jf as hadolintAnalyzer,KR as guideTokenCreation,WR as guideRepositorySettings,P as groupsToRules,pp as groupUpdates,oo as goAdapter,Tf as githubActionsAnalyzer,bR as getWorkflowPreset,c as getNpmRegistryUrl,h as getGitHubServerUrl,S as getGitHubApiUrl,uf as getFinishingTouch,b as getDefaultLogger,xm as getConfig,V as getComposerRegistryUrl,mp as getAllLockFilePaths,Nx as getAgentMode,ZR as generateUnifiedWorkflow,jo as generateGitLabPipeline,$R as generateCoreWorkflows,XR as generateConfigFile,n as generateBranchName,Io as generateBitbucketPipeline,dR as gateIcon,kx as fsTools,e as formatSecurityAdvisorySection,Wd as formatReview,qd as formatPretty,i as formatPRTitle,s as formatPRBody,qp as formatImageRef,Qo as formatGithubOutput,Jd as formatGithub,q as formatError,Fo as formatConfigIssues,v as formatCommitMessage,Kd as formatAgent,lx as fixCiMode,Md as fingerprint,_ as findUsageSites,co as findPrevious,PR as findMentionedPackages,AR as findLinkedIssues,CR as findDuplicates,_o as findDrift,X as fetchWithTimeout,Y as fetchJsonOrNull,vd as failsOnBaseBranch,gd as extractErrorLines,Yp as extractEngines,Xf as emitEvent,U as ecosystemOf,Co as driftFor,$f as docstringsTouch,SR as displayValidationResults,kR as displayProgress,cd as dispatchCommand,Hd as diffArgsFor,ko as diagnose,fp as detectRequiredPackageManagers,JR as detectRepository,r as detectPackageManager,Bf as detectLinter,sp as detectFiles,od as detectChangedFiles,L as describeSpanGaps,rd as describeFailure,tx as describeEvent,to as describeEol,zo as describeDrift,Pd as defaultIncludePath,mm as defaultConfig,Ad as dedupeFindings,Zo as cycleFor,cx as createWebhookSink,hx as createSlackSink,Sx as createSinks,Yf as createReadIssueTool,ap as createProvider,FR as createProgressTracker,xf as createOpenAiProvider,Gf as createLearning,Vd as createHandlers,mf as createGoogleProvider,ux as createDiscordSink,of as createAnthropicProvider,df as createAiClient,Qd as countBySeverity,lR as constrainLabels,QR as confirmTokenSetup,dm as config,ro as computeMetrics,vo as computeDeltas,Dd as composeInstructions,Lp as compareVersions,xo as comparePep440,np as compareNumeric,zf as commandExists,I as collectSpanNotes,Zp as collectResolutionPins,kd as collectLocalDiff,fd as collectGitDiff,DR as clearQuickSelection,u as clearNpmrcCache,ed as classifyFailure,Lo as ciTemplateFor,Dp as chunk,pR as checkTitleFormat,ud as checkPermission,RR as checkLinkedIssue,$o as checkEol,oR as checkDescription,mR as checkDependencies,MR as checkCustomAssertions,tp as bumpEngineConstraint,Jx as buildShellEnv,y as buildAnalysisPrompt,tf as autofixTouch,T as attemptMajorUpgrade,sd as attemptFix,Ho as assertValidConfig,yp as assertSupports,Pp as assertProviderSupported,Xd as applySuggestion,E as applyRules,ip as applyCatalogUpdates,rp as applyCatalogUpdate,H as appendUpgradeReport,uo as appendHistory,GR as appendChangelogEntry,Jp as apiHostFor,Od as anchorMap,BR as analyzeProject,F as analyzeGroupMajors,cp as advisoryKey,Ef as addLearning,Po as adapterNamed,Oo as adapterFor,Df as actionlintAnalyzer,wx as WEBHOOK_PAYLOAD_VERSION,R as VersionResolver,Gp as UnsupportedProviderError,Xx as Toolbelt,Qx as ToolPermissionError,cf as TOUCH_OFFER_MARKER,lf as TOOL_TIMEOUT_MS,vf as TEST_COMMANDS,up as SecurityAdvisoryService,pm as Scheduler,qx as SHELL_ENV_ALLOWLIST,dd as SEVERITY_ORDER,kf as SECRET_RULES,Cp as ReleaseNotesFetcher,jp as RegistryClient,No as ROOT,ad as REVIEW_STATE_VERSION,Rd as REVIEW_SCHEMA,Fd as REVIEW_FORMATS,eo as REPORT_PERIODS,io as REPORT_MARKER,_x as REDACTED,$d as READ_ONLY_COMMANDS,NR as QUICK_LINKS_MARKER,_R as QUICK_ACTIONS,Np as PullRequestGenerator,IR as PluginManager,wp as PackageScanner,gx as PackageRegistryError,Up as PROVIDER_TRACKING_ISSUES,Ep as PROVIDER_TOKEN_ENV,nx as PROVIDER_PRIORITY,Rp as PROVIDER_NAMES,sx as PROVIDER_KEY_ENV,go as PERIOD_DAYS,Wp as OciClient,Ap as NO_CAPABILITIES,ix as MODEL_ALIASES,a as MIGRATION_PLAN_SCHEMA,_d as MAX_GUIDELINE_CHARS,Z as Logger,Lf as LINTER_SPECS,Xp as KNOWN_ENGINES,Mp as IMPLEMENTED_PROVIDERS,Q as HttpRequestError,wo as HISTORY_PATH,So as HISTORY_LIMIT,hd as HELP_TEXT,rx as GitProviderError,t as GitLabProvider,dp as GitHubProvider,k as GitHubApiError,om as GitHubActionsTemplate,hf as FINISHING_TOUCHES,bx as EventBus,$x as EVENT_NAMES,bo as EOL_WARNING_DAYS,Xo as EOL_PRODUCTS,J as DEFAULT_TIMEOUT_MS,j as DEFAULT_SPAN_BUDGET,To as DEFAULT_SCHEDULE,K as DEFAULT_RETRIES,Mf as DEFAULT_PROMPT_LIMIT,Rf as DEFAULT_LEARNINGS_FILE,Nd as DEFAULT_GUIDELINE_FILES,Gd as DEFAULT_EXCLUDED_PATHS,_p as DEFAULT_CONCURRENCY,jR as ConfigurationMigrator,vx as ConfigurationError,Zd as COMMAND_ALIASES,ex as BuddyError,Do as Buddy,w as BitbucketProvider,Wx as BUILTIN_TOOLS,Qf as BUILTIN_ANALYZERS,Eo as BUILTIN_ADAPTERS,Tp as AsyncMemo,Ix as AiProviderError,jx as AiBudgetExceededError,Cx as AGENT_MODES};
package/dist/src/setup.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{$g as i,Tg as a,Ug as b,Vg as c,Wg as d,Xg as e,Yg as f,Zg as g,_g as h,ah as j,bh as k,ch as l,dh as m,eh as n,fh as o,gh as p,hh as q,ih as r,jh as s,kh as t,lh as u,mh as v}from"../chunk-bymwaezh.js";import"../chunk-k26wnmzk.js";import"../chunk-193abzy6.js";import"../chunk-e68nf7cm.js";import"../chunk-hfjywbbc.js";import"../chunk-q4t568hv.js";export{r as validateWorkflowGeneration,s as validateRepositoryAccess,f as updateProgress,v as showFinalInstructions,u as setupCustomWorkflow,n as schedulePlan,c as runPreflightChecks,h as parseRemote,j as guideTokenCreation,l as guideRepositorySettings,q as getWorkflowPreset,o as generateUnifiedWorkflow,p as generateCoreWorkflows,m as generateConfigFile,t as displayValidationResults,g as displayProgress,i as detectRepository,e as createProgressTracker,k as confirmTokenSetup,d as analyzeProject,b as PluginManager,a as ConfigurationMigrator};
2
+ import{$g as i,Tg as a,Ug as b,Vg as c,Wg as d,Xg as e,Yg as f,Zg as g,_g as h,ah as j,bh as k,ch as l,dh as m,eh as n,fh as o,gh as p,hh as q,ih as r,jh as s,kh as t,lh as u,mh as v}from"../chunk-vbeeyhhe.js";import"../chunk-k26wnmzk.js";import"../chunk-193abzy6.js";import"../chunk-e68nf7cm.js";import"../chunk-hfjywbbc.js";import"../chunk-q4t568hv.js";export{r as validateWorkflowGeneration,s as validateRepositoryAccess,f as updateProgress,v as showFinalInstructions,u as setupCustomWorkflow,n as schedulePlan,c as runPreflightChecks,h as parseRemote,j as guideTokenCreation,l as guideRepositorySettings,q as getWorkflowPreset,o as generateUnifiedWorkflow,p as generateCoreWorkflows,m as generateConfigFile,t as displayValidationResults,g as displayProgress,i as detectRepository,e as createProgressTracker,k as confirmTokenSetup,d as analyzeProject,b as PluginManager,a as ConfigurationMigrator};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@buddysh/buddy",
3
3
  "type": "module",
4
- "version": "0.11.2",
4
+ "version": "0.11.3",
5
5
  "description": "AI code review and dependency updates in one bot. Reviews pull requests and local changes, answers @buddy comments, gates merges, repairs failing CI, and keeps dependencies current across npm, Composer, Docker, GitHub Actions and more.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -64,17 +64,17 @@
64
64
  "lint:fix": "bunx --bun pickier . --fix",
65
65
  "format": "bunx --bun pickier . --format",
66
66
  "format:fix": "bunx --bun pickier . --format --write",
67
- "changelog": "bunx logsmith --verbose",
68
- "changelog:generate": "bunx logsmith --output CHANGELOG.md",
69
- "release": "bunx --bun bumpx -r",
67
+ "changelog": "bunx @stacksjs/logsmith --verbose",
68
+ "changelog:generate": "bunx @stacksjs/logsmith --output CHANGELOG.md",
69
+ "release": "bunx --bun @stacksjs/bumpx -r",
70
70
  "typecheck": "bunx tsc --noEmit",
71
71
  "check:docs": "bun scripts/check-docs-claims.ts",
72
72
  "dev:docs": "bun --bun bunpress dev",
73
73
  "build:docs": "bun --bun bunpress build",
74
74
  "preview:docs": "bun --bun bunpress preview --outdir docs/dist",
75
- "release:patch": "bunx --bun bumpx patch --recursive --commit --tag --push --yes",
76
- "release:minor": "bunx --bun bumpx minor --recursive --commit --tag --push --yes",
77
- "release:major": "bunx --bun bumpx major --recursive --commit --tag --push --yes",
75
+ "release:patch": "bunx --bun @stacksjs/bumpx patch --recursive --commit --tag --push --yes",
76
+ "release:minor": "bunx --bun @stacksjs/bumpx minor --recursive --commit --tag --push --yes",
77
+ "release:major": "bunx --bun @stacksjs/bumpx major --recursive --commit --tag --push --yes",
78
78
  "deploy:docs": "bun scripts/deploy-docs.ts"
79
79
  },
80
80
  "dependencies": {
@@ -1,104 +0,0 @@
1
- // @bun
2
- import{$c as c0}from"./chunk-phfmnnne.js";import{bd as S0,cd as B0,dd as w0,ed as g0}from"./chunk-r763e19p.js";import{fd as l0}from"./chunk-be629jhq.js";import{ld as _0,md as O0,nd as h0}from"./chunk-11hdrnf6.js";import{qd as m0,td as f0}from"./chunk-mkzmjg3f.js";import{ke as e,le as p}from"./chunk-p8tmms5h.js";import{if as y0}from"./chunk-8hjvthz4.js";import{lf as g,mf as k0,nf as H0,of as P0,pf as o}from"./chunk-yngahb11.js";import{$f as Z0,ag as v0,bg as l}from"./chunk-0hc97k0t.js";import{kg as f,og as R0,pg as b0}from"./chunk-3901s7h9.js";import{ph as Y0}from"./chunk-193abzy6.js";import{zh as W0}from"./chunk-e68nf7cm.js";import{Bh as C0,Ch as N0,Dh as x0,Eh as U0}from"./chunk-hfjywbbc.js";import{Wk as V}from"./chunk-q4t568hv.js";import F0 from"fs";import{join as a}from"path";import d from"process";var n0={critical:"\uD83D\uDD34 Critical",high:"\uD83D\uDFE0 High",moderate:"\uD83D\uDFE1 Moderate",low:"\u26AA Low"};class X0{generateDashboard($,X={}){let{showOpenPRs:Q=!0,showDetectedDependencies:K=!0,showDeprecatedDependencies:H=!0,showVulnerableDependencies:Y=!0,includePackageJson:W=!0,includeDependencyFiles:O=!0,includeGitHubActions:j=!0,bodyTemplate:J}=X,_="Dependency Dashboard";if(J)return{title:"Dependency Dashboard",body:this.applyTemplate(J,$)};let Z=this.generateDefaultHeader($);if(Y&&$.vulnerableDependencies&&$.vulnerableDependencies.length>0)Z+=this.generateVulnerableDependenciesSection($.vulnerableDependencies);if(H&&$.deprecatedDependencies&&$.deprecatedDependencies.length>0)Z+=this.generateDeprecatedDependenciesSection($.deprecatedDependencies);if(Q&&$.openPRs.length>0)Z+=this.generateOpenPRsSection($.openPRs);if($.cappedDependencies&&$.cappedDependencies.length>0)Z+=this.generateCappedDependenciesSection($.cappedDependencies);if(K)Z+=this.generateDetectedDependenciesSection({packageJson:W?$.detectedDependencies.packageJson:[],dependencyFiles:O?$.detectedDependencies.dependencyFiles:[],githubActions:j?$.detectedDependencies.githubActions:[]});return Z+=this.generateFooter(),{title:"Dependency Dashboard",body:Z}}generateDefaultHeader($){return`This issue lists Buddy updates and detected dependencies. Read the [Dependency Dashboard](https://buddy.sh/features/dependency-dashboard) docs to learn more.
3
-
4
- `}sanitizeReferences($){return $.replace(/(?<![`\w])#(\d+)(?!\d)/g,"`#$1`")}toRelativePrUrl($,X){try{let Q=new URL($);if(Q.hostname!=="github.com")return null;let K=Q.pathname.match(/^\/[^/]+\/[^/]+\/pull\/(\d+)$/);if(!K||Number(K[1])!==X)return null;return`../pull/${X}`}catch{return null}}generateCappedDependenciesSection($){let X=`## Capped dependencies
5
-
6
- The following packages are held below their latest version by a range declared elsewhere in the dependency tree. Updating this repository cannot move them \u2014 the constraint has to be widened where it is declared.
7
-
8
- | Package | Installed | Reachable | Latest | Capped by |
9
- |---|---|---|---|---|
10
- `;for(let Q of $){let K=Q.capping.map((H)=>`\`${this.sanitizeReferences(H.by)}\` (\`${H.range}\`)`).join(", ");X+=`| \`${this.sanitizeReferences(Q.name)}\` | \`${Q.installed}\` | \`${Q.reachable}\` | \`${Q.latest}\` | ${K} |
11
- `}return`${X}
12
- `}generateOpenPRsSection($){let X=`## Open
13
-
14
- The following updates have all been created. To force a retry/rebase of any, click on a checkbox below.
15
-
16
- `;for(let Q of $){let K=this.extractPackageInfo(Q),H=Q.head.replace(/[<>\s]|-->/g,""),Y=this.toRelativePrUrl(Q.url,Q.number)??Q.url,W=this.sanitizeReferences(Q.title);if(X+=` - [ ] <!-- rebase-branch=${H} -->[${W}](${Y})`,K.length>0)X+=` (\`${K.join("`, `")}\`)`;X+=`
17
- `}return X+=` - [ ] <!-- rebase-all-open-prs -->**Click on this checkbox to rebase all open PRs at once**
18
- `,X+=`
19
- `,X}generateDetectedDependenciesSection($){let X=`## Detected dependencies
20
-
21
- `;if($.packageJson.length>0)X+=this.generatePackageJsonSection($.packageJson);let Q=$.dependencyFiles.filter((W)=>W.path==="composer.json"||W.path.endsWith("/composer.json")),K=Q.filter((W)=>W.path==="composer.json"),H=Q.filter((W)=>W.path!=="composer.json");if(K.length>0)X+=this.generateComposerSection(K);if($.githubActions.length>0)X+=this.generateGitHubActionsSection($.githubActions);let Y=$.dependencyFiles.filter((W)=>!W.path.endsWith("/composer.json")&&W.path!=="composer.json");if(Y.length>0||H.length>0)X+=this.generateDependencyFilesSection([...Y,...H]);return X}generatePackageJsonSection($){let X=`<details><summary>npm</summary>
22
- <blockquote>
23
-
24
- `;for(let Q of $){let K=Q.path.split("/").pop()||Q.path;X+=`<details><summary>${K}</summary>
25
-
26
- `;let H={dependencies:Q.dependencies.filter((Y)=>Y.type==="dependencies"),devDependencies:Q.dependencies.filter((Y)=>Y.type==="devDependencies"),peerDependencies:Q.dependencies.filter((Y)=>Y.type==="peerDependencies"),optionalDependencies:Q.dependencies.filter((Y)=>Y.type==="optionalDependencies")};for(let[Y,W]of Object.entries(H))if(W.length>0)for(let O of W)X+=` - \`${O.name} ${O.currentVersion}\`
27
- `;X+=`
28
- </details>
29
-
30
- `}return X+=`</blockquote>
31
- </details>
32
-
33
- `,X}generateGitHubActionsSection($){let X=`<details><summary>github-actions</summary>
34
- <blockquote>
35
-
36
- `;for(let Q of $){X+=`<details><summary>${Q.path}</summary>
37
-
38
- `;let K=new Map;for(let H of Q.dependencies){let Y=`${H.name}@${H.currentVersion}`;if(!K.has(Y))K.set(Y,{name:H.name,currentVersion:H.currentVersion})}for(let H of K.values())X+=` - \`${H.name} ${H.currentVersion}\`
39
- `;X+=`
40
- </details>
41
-
42
- `}return X+=`</blockquote>
43
- </details>
44
-
45
- `,X}generateDependencyFilesSection($){let X=`<details><summary>dependency-files</summary>
46
- <blockquote>
47
-
48
- `;for(let Q of $){X+=`<details><summary>${Q.path}</summary>
49
-
50
- `;for(let K of Q.dependencies)X+=` - \`${K.name} ${K.currentVersion}\`
51
- `;X+=`
52
- </details>
53
-
54
- `}return X+=`</blockquote>
55
- </details>
56
-
57
- `,X}generateComposerSection($){let X=`<details><summary>composer</summary>
58
- <blockquote>
59
-
60
- `;for(let Q of $){let K=Q.path.split("/").pop()||Q.path;X+=`<details><summary>${K}</summary>
61
-
62
- `;let H={require:Q.dependencies.filter((Y)=>Y.type==="require"),"require-dev":Q.dependencies.filter((Y)=>Y.type==="require-dev")};for(let[Y,W]of Object.entries(H))if(W.length>0)for(let O of W)X+=` - \`${O.name} ${O.currentVersion}\`
63
- `;X+=`
64
- </details>
65
-
66
- `}return X+=`</blockquote>
67
- </details>
68
-
69
- `,X}generateVulnerableDependenciesSection($){let X=$.reduce((K,H)=>K+H.advisories.length,0),Q=`> [!CAUTION]
70
- > ${X} known ${X===1?"vulnerability affects":"vulnerabilities affect"} ${$.length} ${$.length===1?"dependency":"dependencies"} in this repository.
71
-
72
- | Severity | Package | Current | Advisory | Fixed in |
73
- |----------|---------|---------|----------|----------|
74
- `;for(let K of $)for(let H of K.advisories){let Y=n0[H.severity]??H.severity,W=H.url?`[${H.id}](${H.url})`:H.id;Q+=`| ${Y} | \`${K.name}\` | \`${K.currentVersion}\` | ${W} | \`${H.fixedVersion??"n/a"}\` |
75
- `}return Q+=`
76
- `,Q}generateDeprecatedDependenciesSection($){let X=`> [!WARNING]
77
- > These dependencies are deprecated and should be updated to avoid potential security risks and compatibility issues.
78
-
79
- | Datasource | Name | Replacement PR? |
80
- |------------|------|-----------------|
81
- `;for(let Q of $){let K=`\`${Q.name}\``,Y=(Q.replacementAvailable?"available":"unavailable")==="available"?"![available](https://img.shields.io/badge/available-green)":"![unavailable](https://img.shields.io/badge/unavailable-orange)";X+=`| ${Q.datasource} | ${K} | ${Y} |
82
- `}return X+=`
83
- `,X}generateFooter(){return`---
84
-
85
- - [ ] <!-- manual job -->Check this box to trigger a request for Buddy to run again on this repository
86
- `}extractPackageInfo($){let X=[],Q=[/update.*?dependency\s+(\S+)/i,/update\s+require(?:-dev)?\s+(\S+)\s+to\s+v?\d+/i,/update\s+(\S+)\s+to\s+v?\d+/i,/bump\s+(\S+)\s+from/i,/chore\(deps\):\s*update\s+dependency\s+(\S+)/i];for(let H of Q){let Y=$.title.match(H);if(Y&&Y[1]&&!X.includes(Y[1]))X.push(Y[1])}let K=[{name:"npm",pattern:/### npm Dependencies[\s\S]*?(?=###|\n\n---|z)/i},{name:"pkgx",pattern:/### Launchpad\/pkgx Dependencies[\s\S]*?(?=###|\n\n---|z)/i},{name:"actions",pattern:/### GitHub Actions[\s\S]*?(?=###|\n\n---|z)/i}];for(let H of K){let Y=$.body.match(H.pattern);if(Y){let O=Y[0].match(/\|\s*\[([^\]]+)\]\([^)]+\)\s*\|/g);if(O)for(let j of O){let J=j.match(/\|\s*\[([^\]]+)\]/);if(J&&J[1]){let _=J[1].trim();if(_.includes("`")&&_.includes("->")){let Z=j.match(/\]\(([^)]+)\)/);if(Z&&Z[1]){let L=Z[1].match(/\/diffs\/npm\/([^/]+)\//);if(L&&L[1]){let S=decodeURIComponent(L[1]);if(S&&S.length>1&&!X.includes(S))X.push(S)}}continue}if(!_.includes("://")&&!_.includes("Compare Source")&&!_.includes("badge")&&!_.includes("!")&&!_.startsWith("[![")&&!_.includes("`")&&!_.includes("->")&&!_.includes(" -> ")&&!_.match(/^\d+\.\d+/)&&!_.includes(" ")&&_.length>0&&!X.includes(_))X.push(_)}}}}if(X.length<3){let H=$.body.match(/`([^`]+)`/g);if(H)for(let Y of H){let W=Y.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&&!X.includes(W)&&(W.startsWith("@")||W.includes("/")||W.match(/^[a-z][a-z0-9.-]*$/i)))X.push(W)}}return X}applyTemplate($,X){return $.replace(/\{\{repository\.owner\}\}/g,X.repository.owner).replace(/\{\{repository\.name\}\}/g,X.repository.name).replace(/\{\{openPRs\.count\}\}/g,X.openPRs.length.toString()).replace(/\{\{lastUpdated\}\}/g,X.lastUpdated.toISOString()).replace(/\{\{detectedDependencies\.packageJson\.count\}\}/g,X.detectedDependencies.packageJson.length.toString()).replace(/\{\{detectedDependencies\.githubActions\.count\}\}/g,X.detectedDependencies.githubActions.length.toString()).replace(/\{\{detectedDependencies\.dependencyFiles\.count\}\}/g,X.detectedDependencies.dependencyFiles.length.toString())}}var d0="buddy/",p0="no-auto-merge";function n($){let X=$.pullRequest?.autoMerge;return{enabled:X?.enabled??!1,strategy:X?.strategy??"squash",conditions:X?.conditions??[],requireGreenCI:X?.requireGreenCI??!0,optOutLabel:X?.optOutLabel??p0,securityLabel:$.security?.label??"security"}}function V0($,X,Q){let K=n(X);if(!K.enabled)return{eligible:!1,reason:"auto-merge is disabled by config"};if(K.conditions.length===0)return{eligible:!1,reason:"no auto-merge conditions configured (set conditions to at least one of patch-only, minor-only, security-only, all)"};if(!$.head.startsWith(d0))return{eligible:!1,reason:`PR #${$.number} is not a buddy PR (branch: ${$.head})`};if($.draft)return{eligible:!1,reason:`PR #${$.number} is a draft`};let H=$.labels??[];if(H.includes(K.optOutLabel))return{eligible:!1,reason:`PR #${$.number} carries the ${K.optOutLabel} label`};if(K.requireGreenCI&&Q===!1)return{eligible:!1,reason:`PR #${$.number} has failing or pending checks`};let Y=f($.body);if(!Y)return{eligible:!1,reason:`PR #${$.number} has no metadata manifest to verify update types against`};if(Y.truncated)return{eligible:!1,reason:`PR #${$.number} has a truncated manifest, so its full update set cannot be verified`};let W=D0(Y,X);if(W)return W;return E0(Y,H,K)}function D0($,X){let Q=[...o(X.packages?.groups),...X.packages?.rules??[]];if(Q.length===0||$.updates.length===0)return null;if(!$.updates.every((Y)=>Y.type&&Y.dependencyType))return null;let H=$.updates.map((Y)=>g(i0(Y),Q));if(H.some((Y)=>Y.autoMerge===!1))return{eligible:!1,reason:"a package rule holds one of these updates back from auto-merge"};if(H.every((Y)=>Y.autoMerge===!0))return{eligible:!0,reason:"every update is covered by a package rule that enables auto-merge"};return null}function i0($){return{name:$.name,currentVersion:$.current,newVersion:$.target,updateType:$.type,file:$.file,dependencyType:$.dependencyType}}function E0($,X,Q){for(let H of Q.conditions)switch(H){case"all":return{eligible:!0,reason:"all updates qualify (condition: all)"};case"patch-only":if($.updates.length>0&&$.updates.every((Y)=>Q0(Y)==="patch"))return{eligible:!0,reason:"every update is a patch"};break;case"minor-only":if($.updates.length>0&&$.updates.every((Y)=>Q0(Y)!=="major"))return{eligible:!0,reason:"every update is minor or patch"};break;case"security-only":if(X.includes(Q.securityLabel))return{eligible:!0,reason:"PR resolves a security advisory"};break}return{eligible:!1,reason:`update types (${[...new Set($.updates.map(Q0))].join(", ")||"none"}) do not satisfy conditions (${Q.conditions.join(", ")})`}}function Q0($){if($.type==="major"||$.type==="minor"||$.type==="patch")return $.type;let X=G0($.current),Q=G0($.target);if(!X||!Q)return"major";if(X[0]!==Q[0])return"major";if(X[1]!==Q[1])return"minor";return"patch"}function G0($){let X=$.trim().match(/(\d+)\.(\d+)\.(\d+)/);if(!X)return null;return[Number(X[1]),Number(X[2]),Number(X[3])]}function I0($,X,Q){let K=n(Q);if(!K.enabled)return{eligible:!1,reason:"auto-merge is disabled by config"};if(K.conditions.length===0)return{eligible:!1,reason:"no auto-merge conditions configured"};if(X.includes(K.optOutLabel))return{eligible:!1,reason:`PR carries the ${K.optOutLabel} label`};let H={schemaVersion:1,updates:$.map((W)=>({name:W.name,current:W.currentVersion,target:W.newVersion,type:W.updateType,file:W.file,dependencyType:W.dependencyType}))},Y=D0(H,Q);if(Y)return Y;return E0(H,X,K)}var A0="https://api.osv.dev",s0=1000,s={low:0,moderate:1,high:2,critical:3};function K0($){switch($){case"dependencies":case"devDependencies":case"peerDependencies":case"optionalDependencies":return"npm";case"require":case"require-dev":return"Packagist";case"python":return"PyPI";case"rust":return"crates.io";case"go":return"Go";case"ruby":return"RubyGems";case"github-actions":return"GitHub Actions";default:return null}}function r0($){let X=$.database_specific?.severity?.toLowerCase();if(X==="low"||X==="moderate"||X==="high"||X==="critical")return X;if(X==="medium")return"moderate";let Q=$.severity?.find((K)=>K.type?.startsWith("CVSS"))?.score;if(Q){let K=t0(Q);if(K!==null){if(K>=9)return"critical";if(K>=7)return"high";if(K>=4)return"moderate";return"low"}}return"moderate"}function t0($){let X=Number($);if(Number.isFinite(X))return X;let Q=$.match(/\/([0-9](?:\.[0-9])?)$/);if(Q){let K=Number(Q[1]);return Number.isFinite(K)?K:null}return null}function a0($,X){for(let Q of $.affected??[]){if(Q.package?.name!==X)continue;for(let K of Q.ranges??[])for(let H of K.events??[])if(H.fixed)return H.fixed}return}class t{logger;concurrency;detailCache=new w0;constructor($,X=8){this.logger=$;this.concurrency=X}async findAdvisories($){let X=new Map;if($.length===0)return X;let Q=await this.queryBatch($),K=[...new Set([...Q.values()].flat())];if(K.length===0)return X;this.logger.debug(`Fetching details for ${K.length} advisory record(s)`);let H=await S0(K,(W)=>this.fetchVulnerability(W),this.concurrency),Y=new Map;for(let W of H)if(W)Y.set(W.id,W);for(let[W,O]of Q){let j=W.slice(W.indexOf(":")+1,W.lastIndexOf("@")),J=[];for(let _ of O){let Z=Y.get(_);if(!Z)continue;J.push({id:Z.id,aliases:Z.aliases??[],summary:Z.summary??Z.details?.split(`
87
- `)[0]??"No summary provided",severity:r0(Z),url:`https://osv.dev/vulnerability/${Z.id}`,fixedVersion:a0(Z,j)})}if(J.length>0)J.sort((_,Z)=>s[Z.severity]-s[_.severity]),X.set(W,J)}return X}async annotateUpdates($,X="low"){let Q=[],K=[];if($.forEach((O,j)=>{let J=K0(O.dependencyType);if(!J)return;let _=M0(O.currentVersion);if(!_)return;let Z=J==="GitHub Actions"?_.replace(/^v/i,""):_;if(!Z)return;Q.push({name:O.name,version:Z,ecosystem:J}),K.push(j)}),Q.length===0)return $;let H=await this.findAdvisories(Q),Y=s[X],W=0;if(Q.forEach((O,j)=>{let J=H.get(r(O));if(!J?.length)return;let _=$[K[j]],Z=J.filter((z)=>{if(s[z.severity]<Y)return!1;if(!z.fixedVersion)return!1;return e0(M0(_.newVersion),z.fixedVersion)});if(Z.length>0)_.securityAdvisories=Z,W++}),W>0)this.logger.info(`\uD83D\uDD12 ${W} update(s) resolve known security advisories`);return $}async queryBatch($){let X=new Map,Q=B0($,s0);for(let K of Q)try{let H=await W0(`${A0}/v1/querybatch`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"buddy"},body:JSON.stringify({queries:K.map((W)=>({package:{name:W.name,ecosystem:W.ecosystem},version:W.version}))}),retryNonIdempotent:!0,onRetry:({delayMs:W,reason:O})=>this.logger.debug(`OSV batch retry in ${Math.round(W/1000)}s (${O})`)});if(!H.ok){this.logger.warn(`OSV advisory lookup failed: HTTP ${H.status}`);continue}(await H.json()).results?.forEach((W,O)=>{let j=W.vulns?.map((J)=>J.id)??[];if(j.length>0)X.set(r(K[O]),j)})}catch(H){this.logger.warn("OSV advisory lookup failed:",H)}return X}async fetchVulnerability($){return this.detailCache.get($,async()=>{try{let X=await W0(`${A0}/v1/vulns/${encodeURIComponent($)}`,{headers:{"User-Agent":"buddy"}});if(!X.ok)return null;return await X.json()}catch(X){return this.logger.debug(`Failed to fetch advisory ${$}:`,X),null}})}}function r($){return`${$.ecosystem}:${$.name}@${$.version}`}function M0($){return $.replace(/^[\^~>=<\s]*v?/,"").trim()}function e0($,X){if(!$||!X)return!1;try{return Bun.semver.order($,X)>=0}catch{return!1}}import $1 from"process";function X1($){if(!$)return null;let X=$.split("/").filter(Boolean);if(X.length<2)return null;return{owner:X.slice(0,-1).join("/"),name:X[X.length-1]}}var Q1=["GITHUB_REPOSITORY","CI_PROJECT_PATH","BITBUCKET_REPO_FULL_NAME"];function W1($){for(let X of Q1){let Q=X1($[X]);if(Q)return Q}return null}function T0($,X=$1.env){if(!$.repository)return{source:"unresolved",overrodeConfig:!1};let Q=$.repository,K=W1(X),H=Boolean(Q.owner&&Q.name);if(!K)return H?{owner:Q.owner,name:Q.name,source:"config",overrodeConfig:!1}:{source:"unresolved",overrodeConfig:!1};if(H&&(Q.owner!==K.owner||Q.name!==K.name)){let O=`Configured repository ${`${Q.owner}/${Q.name}`} does not match the checked-out repository ${K.owner}/${K.name}. Using ${K.owner}/${K.name} \u2014 buddy `+"operates on the checked-out repository. Update repository.owner/repository.name in your buddy config to silence this warning.";if(Q.owner=K.owner,Q.name=K.name,$.dashboard?.issueNumber!==void 0)$.dashboard.issueNumber=void 0;return{owner:K.owner,name:K.name,source:"environment",overrodeConfig:!0,warning:O}}if(!H)return Q.owner||=K.owner,Q.name||=K.name,{owner:K.owner,name:K.name,source:"environment",overrodeConfig:!1};return{owner:Q.owner,name:Q.name,source:"config",overrodeConfig:!1}}class $0{config;projectPath;logger;scanner;registryClient;eventBus=null;dashboardGenerator;constructor($,X=d.cwd()){this.config=$;this.projectPath=X;this.logger=new x0($.verbose??!1,$.logLevel),U0(this.logger),this.resolveRepositoryConfig(),this.scanner=new l0(this.projectPath,this.logger,this.config.packages?.ignorePaths),this.registryClient=new g0(this.projectPath,this.logger,this.config),this.dashboardGenerator=new X0}async analyzeMajors($,X){if(!this.config.ai?.majorUpgrades?.enabled)return{report:"",draft:!1};let{analyzeGroupMajors:Q}=await import("./chunk-vdd1cghr.js"),{createAiClient:K}=await import("./chunk-hsa07n7c.js"),{ReleaseNotesFetcher:H}=await import("./chunk-2wj5xtdn.js"),Y=new H(this.logger),W=await Q({updates:$,config:this.config,workspace:this.projectPath,baseBranch:this.config.repository?.baseBranch||"main",files:X,ai:K(this.config,this.logger),fetchReleases:(O,j,J)=>Y.fetchSpanReleases(O,j,J),logger:this.logger});return{report:W.report,draft:W.draft}}resolveRepositoryConfig(){let $=T0(this.config);if($.warning)this.logger.warn(`\u26A0\uFE0F ${$.warning}`);else if($.source==="environment")this.logger.info(`Auto-detected repository: ${$.owner}/${$.name} from GITHUB_REPOSITORY`)}async scanForUpdates(){let $=Date.now();this.logger.info("Starting dependency update scan...");try{let X=Date.now(),Q=await this.scanner.scanProject();this.logger.info(`\u23F1\uFE0F Package file scan took ${Date.now()-X}ms`);let K=Q.reduce((C,m)=>C+m.dependencies.length,0),H=[],Y=Date.now();if(this.config.packages?.ignore&&this.config.packages.ignore.length>0)H=(await this.registryClient.getOutdatedPackages()).filter((m)=>!this.config.packages.ignore.includes(m.name));else H=await this.registryClient.getOutdatedPackages();this.logger.info(`\u23F1\uFE0F bun outdated check took ${Date.now()-Y}ms (found ${H.length} updates)`);let W=Date.now(),O=await this.checkDependencyFilesForUpdates(Q);this.logger.info(`\u23F1\uFE0F Dependency file checks took ${Date.now()-W}ms (found ${O.length} updates)`);let j=Date.now(),J=await this.checkGitHubActionsForUpdates(Q);this.logger.info(`\u23F1\uFE0F GitHub Actions checks took ${Date.now()-j}ms (found ${J.length} updates)`);let _=Date.now(),Z=await this.checkDockerfilesForUpdates(Q);this.logger.info(`\u23F1\uFE0F Docker image checks took ${Date.now()-_}ms (found ${Z.length} updates)`);let z=Date.now(),L=await this.checkZigForUpdates(Q),S=this.config.packages?.engines===!0?await this.checkEnginesForUpdates(Q):[];this.logger.info(`\u23F1\uFE0F Zig dependency checks took ${Date.now()-z}ms (found ${L.length} updates)`);let{scanCatalogs:B}=await import("./chunk-0paakbpj.js"),E=await B(this.projectPath,(C)=>this.registryClient.getLatestVersion(C),{...this.config.packages?.ignore?{ignore:this.config.packages.ignore}:{},logger:this.logger});if(E.entries.length>0)this.logger.info(`\uD83D\uDCE6 pnpm catalogs: ${E.updates.length} update(s) across ${E.entries.length} entr(ies)`);let U=Date.now(),{scanEcosystems:A}=await import("./chunk-dgfb8k0h.js"),T=await A({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(T.manifests.length>0)this.logger.info(`\u23F1\uFE0F Ecosystem checks took ${Date.now()-U}ms (found ${T.updates.length} updates across ${T.manifests.map((C)=>C.ecosystem).join(", ")})`);let q=[...H,...O,...J,...Z,...L,...S,...T.updates,...E.updates];if(this.config.packages?.ignore&&this.config.packages.ignore.length>0)q=q.filter((C)=>!this.config.packages.ignore.includes(C.name));let N=Date.now();if(this.config.packages?.strategy)q=this.filterUpdatesByStrategy(q,this.config.packages.strategy);this.logger.info(`\u23F1\uFE0F Strategy filtering took ${Date.now()-N}ms`);let b=Date.now();q=await this.filterUpdatesByMinimumReleaseAge(q),this.logger.info(`\u23F1\uFE0F Minimum release age filtering took ${Date.now()-b}ms`),q=this.applyPins(q),q=await this.dropOverriddenUpdates(q,Q),q=this.applyPackageRules(q);let c=Date.now();q=await this.annotateSecurityAdvisories(q),this.logger.info(`\u23F1\uFE0F Security advisory lookup took ${Date.now()-c}ms`);let h=this.config.security?.prioritize??!0,I=Date.now();q=v0(q,{prioritizeSecurity:h}),this.logger.info(`\u23F1\uFE0F Sorting took ${Date.now()-I}ms`);let F=Date.now(),z0=this.config.packages?.groups?this.groupUpdatesByConfig(q):Z0(q,{prioritizeSecurity:h});this.logger.info(`\u23F1\uFE0F Grouping took ${Date.now()-F}ms`);let u=Date.now()-$,y={totalPackages:K,updates:q,groups:z0,scannedAt:new Date,duration:u};return this.logger.success(`Scan completed in ${u}ms. Found ${q.length} updates.`),await this.events.emit("scan.completed",{total:q.length,major:q.filter((C)=>C.updateType==="major").length,minor:q.filter((C)=>C.updateType==="minor").length,patch:q.filter((C)=>C.updateType==="patch").length}),y}catch(X){throw this.logger.error("Failed to scan for updates:",X),X}}prTitleFor($){let X=this.config.pullRequest?.titleFormat;if(!X)return $.title;return _0(X,O0($,{title:$.title},this.config.packages?.strategy))}commitMessageFor($,X){let Q=this.config.pullRequest?.commitMessageFormat,K=Q?_0(Q,O0($,{message:$.title,title:$.title},this.config.packages?.strategy)):$.title;return X?`${K} ${X}`:K}applyPackageRules($){let X=this.config.packages?.rules??[],K=[...o(this.config.packages?.groups),...X];if(K.length===0)return $;let H=k0($,K);if(H.length<$.length)this.logger.info(`\uD83D\uDCCB Package rules dropped ${$.length-H.length} update(s)`);return H.map((Y)=>Y.update)}static mergeUnique($,X){let Q=[...new Set([...$??[],...X])];return Q.length>0?Q:void 0}labelsFor($,X){let Q=$.updates.some((K)=>(K.securityAdvisories?.length??0)>0);return[...new Set([...X.generateLabels($),...Q?[this.config.security?.label??"security"]:[],...this.config.pullRequest?.labels??[],...this.groupEffectsFor($.updates).labels])]}activeRules(){return[...o(this.config.packages?.groups),...this.config.packages?.rules??[]]}groupEffectsFor($){let X=this.activeRules();if(X.length===0)return H0([]);return H0($.map((Q)=>g(Q,X)))}orderGroupsByPriority($){if(this.activeRules().length===0)return $;return $.map((Q,K)=>({group:Q,index:K,priority:this.groupEffectsFor(Q.updates).prPriority})).sort((Q,K)=>K.priority-Q.priority||Q.index-K.index).map((Q)=>Q.group)}async dropOverriddenUpdates($,X){let Q=X.filter((W)=>W.type==="package.json");if(Q.length===0)return $;let{collectResolutionPins:K,pinBlocksUpdate:H}=await import("./chunk-pskqrv5r.js"),Y=new Map;for(let W of Q)try{for(let O of K(JSON.parse(W.content)))Y.set(O.name,{version:O.version,field:O.field})}catch{continue}if(Y.size===0)return $;return $.filter((W)=>{let O=Y.get(W.name);if(!O)return!0;if(!H({name:W.name,version:O.version,field:O.field},W.newVersion))return!0;return this.logger.info(`\uD83D\uDD12 Skipping ${W.name} \u2192 ${W.newVersion}: ${O.field} pins it to ${O.version}, which would win at install time`),!1})}applyPins($){let X=this.config.packages?.pin;if(!X||Object.keys(X).length===0)return $;let Q=[];for(let K of $){let H=X[K.name];if(!H){Q.push(K);continue}if(K.currentVersion===H){this.logger.info(`\uD83D\uDCCC ${K.name} is pinned to ${H}, skipping update to ${K.newVersion}`);continue}this.logger.info(`\uD83D\uDCCC ${K.name} is pinned to ${H}, retargeting update from ${K.newVersion}`),Q.push({...K,newVersion:H,updateType:l(K.currentVersion,H)})}return Q}async annotateSecurityAdvisories($){if(this.config.security?.enabled===!1||$.length===0)return $;try{let Q=await new t(this.logger).annotateUpdates($,this.config.security?.minimumSeverity??"low"),K=Q.filter((H)=>H.securityAdvisories?.length);if(K.length>0)await this.events.emit("security.advisories",{packages:K.map((H)=>({name:H.name,severity:H.securityAdvisories?.[0]?.severity??"unknown"}))});return Q}catch(X){return this.logger.warn("Security advisory lookup failed, continuing without it:",X),$}}async createPullRequests($){let X=Date.now();this.logger.info("Creating pull requests for updates...");try{if(!this.config.repository){this.logger.error("\u274C Repository configuration required for PR creation"),this.logger.info("Configure repository.provider, repository.owner, repository.name in buddy.config.ts");return}if(!this.config.repository.owner||!this.config.repository.name){this.logger.error("\u274C Repository owner and name are required for PR creation"),this.logger.info("Set them in buddy.config.ts or ensure GITHUB_REPOSITORY env var is available");return}let Q=d.env.GITHUB_TOKEN,K=d.env.BUDDY_TOKEN;if(!Q&&!K){this.logger.error("\u274C GITHUB_TOKEN or BUDDY_TOKEN environment variable required for PR creation");return}let H=Q||K,Y=!!K;if(K)this.logger.info("\u2705 BUDDY_TOKEN detected - workflow file permissions enabled");else this.logger.info("\u2139\uFE0F No BUDDY_TOKEN \u2014 workflow file updates will be skipped");let W=await e({provider:this.config.repository.provider,owner:this.config.repository.owner,name:this.config.repository.name,token:H,...K?{workflowToken:K}:{},...this.config.repository.apiUrl?{apiUrl:this.config.repository.apiUrl}:{}},{logger:this.logger}),O=new h0(this.config),j=this.config.maxPRsPerRun??10,J=0,_=this.orderGroupsByPriority($.groups);for(let z of _)try{let L=Date.now();if(this.logger.info(`Creating PR for group: ${z.name} (${z.updates.length} updates)`),z.updates.length>0&&z.updates.every((G)=>G.file.includes(".github/workflows/"))&&!Y){this.logger.warn(`\u26A0\uFE0F Skipping group ${z.name} \u2014 workflow-file updates require BUDDY_TOKEN with the workflow scope`);continue}try{let{spawn:G}=await import("child_process"),w=(M,R)=>{return new Promise((x,v)=>{let P=G(M,R,{stdio:"pipe"});P.on("close",(i)=>i===0?x():v(Error(`Git command failed with code ${i}`))),P.on("error",v)})},D=this.config.repository.baseBranch||"main";await w("git",["checkout",D]),await w("git",["reset","--hard","HEAD"]),await w("git",["clean","-fd"])}catch(G){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state for early file-change check, continuing anyway:",G)}let B=await this.generateAllFileUpdates(z.updates);if(B.length===0){this.logger.info(`\u2139\uFE0F No file changes for group ${z.name}, skipping \u2014 leaving branches untouched`);continue}let E=this.prTitleFor(z),U=Date.now(),A=await O.generateBody(z),T=Date.now()-U;this.logger.info(`\u23F1\uFE0F PR body generation took ${T}ms`);let q=await this.analyzeMajors(z.updates,B.map((G)=>G.path)),N=y0(A,q.report),b=await W.getPullRequests("open"),c=this.generateBranchName(z),h=`buddy/update-${z.name.toLowerCase().replace(/\s+/g,"-")}-`,I=b.find((G)=>(G.head===c||G.title===E||G.head.startsWith(h)||this.isSimilarPRTitle(G.title,E))&&(G.author==="github-actions[bot]"||G.author.includes("buddy")||G.head.startsWith("buddy/"))&&!G.head.includes("renovate/")&&!G.head.includes("dependabot/")&&!G.author.toLowerCase().includes("renovate")&&!G.author.toLowerCase().includes("dependabot"));if(I){if(this.logger.info(`\uD83D\uDD04 Found existing PR #${I.number}: ${I.title}`),this.shouldAutoClosePR(I,z.updates)){this.logger.info(`\uD83D\uDD12 Auto-closing PR #${I.number} due to config change`);try{let D=this.generateCloseReason(I);try{await W.createComment(I.number,D)}catch(M){this.logger.warn(`\u26A0\uFE0F Could not add close reason comment to PR #${I.number}:`,M)}await W.closePullRequest(I.number),await this.events.emit("pr.closed",{number:I.number,title:I.title,reason:"no longer produced by the current configuration"});try{await W.deleteBranch(I.head),this.logger.success(`\u2705 Auto-closed PR #${I.number} and deleted branch ${I.head}`)}catch(M){this.logger.warn(`\u26A0\uFE0F Auto-closed PR #${I.number} but could not delete ${I.head}:`,M)}continue}catch(D){this.logger.error(`\u274C Failed to auto-close PR #${I.number}:`,D)}}if(this.checkIfUpdatesMatch(I.body,z.updates)){this.logger.info("\u2705 Existing PR has the same updates, skipping creation");continue}else{this.logger.info("\uD83D\uDD04 Updates differ, will update existing PR with new content");let D=I.head;try{let{spawn:x}=await import("child_process"),v=(P,i)=>{return new Promise((o0,J0)=>{let L0=x(P,i,{stdio:"pipe"});L0.on("close",(q0)=>{if(q0===0)o0();else J0(Error(`Git command failed with code ${q0}`))}),L0.on("error",J0)})};await v("git",["checkout","main"]),await v("git",["reset","--hard","HEAD"]),await v("git",["clean","-fd"]),this.logger.info(`\uD83E\uDDF9 Reset to clean main state before updating existing PR ${I.number}`)}catch(x){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state, continuing anyway:",x)}let M=await this.generateAllFileUpdates(z.updates);if(M.length===0)this.logger.warn(`\u2139\uFE0F No file changes generated for existing PR ${I.number}, updating metadata only`);else{this.logger.info(`\uD83D\uDCDD Regenerated ${M.length} file changes for existing PR ${I.number}`);try{let{hasBranchDifferences:x}=await import("./chunk-aa277p5r.js");if(!await x(M,D))this.logger.info(`\u2139\uFE0F No content differences for ${D}; recreating from ${this.config.repository.baseBranch||"main"} with same dependency changes to keep branch up-to-date`),await W.commitChanges(D,this.commitMessageFor(z,"(rebased)"),M,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated ${D} from ${this.config.repository.baseBranch||"main"} (dependency versions unchanged)`);else await W.commitChanges(D,this.commitMessageFor(z,"(updated)"),M,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated branch ${D} with latest dependency versions`)}catch(x){this.logger.warn("\u26A0\uFE0F Failed to compare branch content, proceeding with commit:",x),await W.commitChanges(D,this.commitMessageFor(z,"(updated)"),M,this.config.repository.baseBranch||"main"),this.logger.success(`\u2705 Recreated branch ${D} with latest dependency versions`)}}let R=this.labelsFor(z,O);await W.updatePullRequest(I.number,{title:E,body:N,labels:R,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:I.number,title:E,url:I.url}),this.logger.success(`\u2705 Updated existing PR #${I.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${I.url}`);continue}}if(J>=j){this.logger.warn(`\u26A0\uFE0F Rate limit reached: already created ${J} PRs this run (max: ${j}). Skipping remaining groups.`);break}let F=this.generateBranchName(z);if(await W.branchExists(F)){this.logger.info(`\uD83D\uDD04 Branch ${F} already exists, checking for associated PR...`);let G=b.find((D)=>D.head===F);if(G){this.logger.info(`\u2705 Found existing PR #${G.number} for branch ${F}, updating it...`);let D=await this.generateAllFileUpdates(z.updates);if(D.length>0)await W.commitChanges(F,this.commitMessageFor(z,"(updated)"),D,this.config.repository.baseBranch||"main");let M=this.labelsFor(z,O);await W.updatePullRequest(G.number,{title:E,body:N,labels:M,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:G.number,title:E,url:G.url}),this.logger.success(`\u2705 Updated existing PR #${G.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${G.url}`);continue}let w=!1;try{let M=(p(W,"reopenPullRequests","reopenPullRequest")?await W.getPullRequests("closed"):[]).find((R)=>{if(R.head!==F)return!1;if(R.mergedAt)return!1;return Date.now()-(R.updatedAt?.getTime()??0)<86400000});if(M){this.logger.info(`\uD83D\uDD04 Found recently-closed PR #${M.number} for branch ${F}, reopening...`);let R=await this.generateAllFileUpdates(z.updates);if(R.length>0)await W.commitChanges(F,this.commitMessageFor(z,"(reopened)"),R,this.config.repository.baseBranch||"main");await W.reopenPullRequest(M.number);let x=this.labelsFor(z,O);await W.updatePullRequest(M.number,{title:E,body:N,labels:x,reviewers:this.config.pullRequest?.reviewers,teamReviewers:this.config.pullRequest?.teamReviewers,assignees:this.config.pullRequest?.assignees}),await this.events.emit("pr.updated",{number:M.number,title:E,url:M.url}),this.logger.success(`\u2705 Reopened and updated PR #${M.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${M.url}`),w=!0}}catch(D){this.logger.warn("\u26A0\uFE0F Failed to check/reopen closed PRs:",D)}if(w)continue;this.logger.info(`\uD83E\uDDF9 Branch ${F} exists but has no open PR, cleaning up...`);try{await W.deleteBranch(F)}catch(D){this.logger.warn(`\u26A0\uFE0F Failed to delete orphaned branch ${F}:`,D)}}let u=!1;try{let w=(p(W,"reopenPullRequests","reopenPullRequest")?await W.getPullRequests("closed"):[]).find((D)=>{if(D.head!==F&&!this.isSimilarPRTitle(D.title,E))return!1;if(!D.head.startsWith("buddy/")&&D.author!=="github-actions[bot]")return!1;if(D.mergedAt)return!1;return Date.now()-(D.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(F,this.config.repository.baseBranch||"main");let D=await this.generateAllFileUpdates(z.updates);if(D.length>0)await W.commitChanges(F,this.commitMessageFor(z,"(reopened)"),D,this.config.repository.baseBranch||"main");await W.reopenPullRequest(w.number);let M=this.labelsFor(z,O);await W.updatePullRequest(w.number,{title:E,body:N,labels:M,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:E,url:w.url}),this.logger.success(`\u2705 Reopened and updated PR #${w.number}: ${E}`),this.logger.info(`\uD83D\uDD17 ${w.url}`),u=!0}}catch(G){this.logger.warn("\u26A0\uFE0F Failed to check/reopen closed PRs:",G)}if(u)continue;await W.createBranch(F,this.config.repository.baseBranch||"main");try{let{spawn:G}=await import("child_process"),w=(D,M)=>{return new Promise((R,x)=>{let v=G(D,M,{stdio:"pipe"});v.on("close",(P)=>{if(P===0)R();else x(Error(`Git command failed with code ${P}`))}),v.on("error",x)})};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 ${z.name}`)}catch(G){this.logger.warn("\u26A0\uFE0F Failed to reset to clean state, continuing anyway:",G)}let y=await this.generateAllFileUpdates(z.updates);if(y.length===0){this.logger.warn(`\u2139\uFE0F No file changes generated for group ${z.name}, skipping PR creation`);continue}let C=!1;for(let G of y)try{let w=await import("fs");if(w.existsSync(G.path)){if(w.readFileSync(G.path,"utf-8")!==G.content){C=!0;break}}else{C=!0;break}}catch{C=!0;break}if(!C){this.logger.warn(`\u2139\uFE0F No actual content changes for group ${z.name}, skipping PR creation`);continue}this.logger.info(`\uD83D\uDCDD Generated ${y.length} file changes for ${z.name}`),await W.commitChanges(F,this.commitMessageFor(z),y,this.config.repository.baseBranch||"main");let m=this.groupEffectsFor(z.updates),j0=this.labelsFor(z,O),k=await W.createPullRequest({title:E,body:N,head:F,base:this.config.repository.baseBranch||"main",draft:q.draft,reviewers:$0.mergeUnique(this.config.pullRequest?.reviewers,m.reviewers),teamReviewers:this.config.pullRequest?.teamReviewers,assignees:$0.mergeUnique(this.config.pullRequest?.assignees,m.assignees),labels:j0});J++,this.logger.success(`\u2705 Created PR #${k.number}: ${k.title} (${J}/${j} this run)`),this.logger.info(`\uD83D\uDD17 ${k.url}`),await this.events.emit("pr.created",{number:k.number,title:k.title,url:k.url,packages:z.updates.map((G)=>G.name)}),await this.queueAutoMerge(W,k,z.updates,j0);let u0=Date.now()-L;this.logger.info(`\u23F1\uFE0F Total group processing took ${u0}ms`)}catch(L){this.logger.error(`\u274C Failed to create PR for group ${z.name}:`,L)}let Z=Date.now()-X;this.logger.success(`\u2705 Completed PR creation for ${$.groups.length} group(s) in ${Z}ms`)}catch(Q){throw this.logger.error("Failed to create pull requests:",Q),Q}}shouldRespectVersion($){if(!(this.config.packages?.respectLatest??!0))return!1;let Q=["latest","*","main","master","develop","dev"],K=$.toLowerCase().trim();return Q.includes(K)}async checkDependencyFilesForUpdates($){let{isDependencyFile:X}=await import("./chunk-19zyq15p.js"),{resolveDependencyFile:Q}=await import("./chunk-05me15qw.js"),K=[],H=$.filter((O)=>X(O.path));this.logger.info(`\u26A1 Checking ${H.length} dependency files in parallel...`);let Y=H.map(async(O)=>{try{this.logger.info(`Checking dependency file: ${O.path}`);let j=await Q(O.path),J=[];for(let _ of j.allDependencies||[]){if(this.shouldRespectVersion(_.constraint)){this.logger.debug(`Skipping ${_.name} - version "${_.constraint}" should be respected`);continue}if(_.constraint!==_.version&&_.version){let Z=_.constraint.replace(/^[\^~>=<]+/,"");if(!this.isNewerVersion(Z,_.version)){this.logger.debug(`Skipping ${_.name} - latest (${_.version}) is not newer than constraint (${Z})`);continue}let z=l(Z,_.version),L=_.version;J.push({name:_.name,currentVersion:_.constraint,newVersion:L,updateType:z,dependencyType:"dependencies",file:O.path,metadata:void 0,releaseNotesUrl:void 0,changelogUrl:void 0,homepage:void 0})}}return J}catch(j){return this.logger.error(`Failed to check dependency file ${O.path}:`,j),[]}}),W=await Promise.all(Y);return K.push(...W.flat()),K}async checkZigForUpdates($){let{isZigManifest:X}=await import("./chunk-zxgkp71x.js"),{fetchLatestZigVersion:Q,fetchZigHash:K,isZigAvailable:H,parseZigSource:Y,zigUrlForVersion:W}=await import("./chunk-1qgr52wx.js"),O=$.filter((Z)=>X(Z.path));if(O.length===0)return[];if(!await H())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 j=d.env.GITHUB_TOKEN||d.env.BUDDY_TOKEN,J=O.flatMap((Z)=>Z.dependencies.filter((z)=>z.type==="zig-dependencies").map((z)=>({file:Z,dep:z})));return this.logger.info(`\u26A1 Checking ${J.length} Zig dependencies...`),(await Promise.all(J.map(async({file:Z,dep:z})=>{let L=z.metadata?.url;if(!L)return this.logger.debug(`Skipping ${z.name}: no URL recorded`),null;let S=Y(L);if(!S)return this.logger.debug(`Skipping ${z.name}: only GitHub-hosted Zig dependencies can be checked`),null;let B=await Q(S,j);if(!B||B===z.currentVersion)return null;let E=W(L,B),U=await K(E);if(!U)return this.logger.warn(`\u26A0\uFE0F Skipping ${z.name} ${z.currentVersion} \u2192 ${B}: could not compute its package hash`),null;return this.logger.info(`\uD83D\uDCE6 ${z.name}: ${z.currentVersion} \u2192 ${B}`),{name:z.name,currentVersion:z.currentVersion,newVersion:B,updateType:l(z.currentVersion,B),dependencyType:"zig-dependencies",file:Z.path,resolved:{url:E,hash:U}}}))).filter((Z)=>Z!==null)}async checkGitHubActionsForUpdates($){let{isGitHubActionsFile:X}=await import("./chunk-sc7emb71.js"),{fetchLatestActionVersion:Q}=await import("./chunk-sc7emb71.js"),K=[],H=$.filter((_)=>X(_.path));this.logger.info(`\uD83D\uDD0D Found ${H.length} GitHub Actions workflow files`);let Y=[];for(let _ of H){let Z=_.dependencies.filter((z)=>z.type==="github-actions");this.logger.info(`Found ${Z.length} GitHub Actions in ${_.path}`),Z.forEach((z)=>Y.push({file:_,dep:z}))}this.logger.info(`\u26A1 Checking ${Y.length} GitHub Actions in parallel...`);let W=Y.map(async({file:_,dep:Z})=>{try{this.logger.info(`Checking action: ${Z.name}@${Z.currentVersion}`);let z=await Q(Z.name);if(z)if(this.logger.info(`Latest version for ${Z.name}: ${z}`),z!==Z.currentVersion){let L=l(Z.currentVersion,z);return this.logger.info(`Update available: ${Z.name} ${Z.currentVersion} \u2192 ${z} (${L})`),{name:Z.name,currentVersion:Z.currentVersion,newVersion:z,updateType:L,dependencyType:"github-actions",file:_.path,metadata:void 0,releaseNotesUrl:`${Y0(this.config)}/${Z.name}/releases`,changelogUrl:void 0,homepage:`${Y0(this.config)}/${Z.name}`}}else this.logger.info(`No update needed for ${Z.name}: already at ${z}`);else this.logger.warn(`Could not fetch latest version for ${Z.name}`);return null}catch(z){return this.logger.warn(`Failed to check version for action ${Z.name}:`,z),null}}),j=(await Promise.all(W)).filter((_)=>_!==null);K.push(...j),this.logger.info(`Generated ${K.length} GitHub Actions updates`);let J=K.reduce((_,Z)=>{if(!_.find((L)=>L.name===Z.name&&L.currentVersion===Z.currentVersion&&L.newVersion===Z.newVersion&&L.file===Z.file))_.push(Z);return _},[]);return this.logger.info(`After deduplication: ${J.length} unique GitHub Actions updates`),J}async checkEnginesForUpdates($){let{bumpEngineConstraint:X,engineUpdateType:Q,resolveEngineVersion:K}=await import("./chunk-pskqrv5r.js"),{fetchLatestActionVersion:H}=await import("./chunk-sc7emb71.js"),Y=$.flatMap((j)=>j.dependencies.filter((J)=>J.type==="engines").map((J)=>({file:j,dep:J})));if(Y.length===0)return[];this.logger.info(`\u26A1 Checking ${Y.length} engine constraint(s)...`);let W={npm:(j)=>this.registryClient.getLatestVersion(j),github:(j)=>H(j)},O=Y.map(async({file:j,dep:J})=>{try{let _=await K(J.name,W);if(!_)return null;let Z=X(J.currentVersion,_);if(!Z)return this.logger.debug(`${J.name} ${J.currentVersion} already admits ${_}`),null;return this.logger.info(`Update available: ${J.name} ${J.currentVersion} \u2192 ${Z}`),{name:J.name,currentVersion:J.currentVersion,newVersion:Z,updateType:Q(J.currentVersion,Z),dependencyType:"engines",file:j.path}}catch(_){return this.logger.warn(`Could not check engine ${J.name}:`,_),null}});return(await Promise.all(O)).filter((j)=>j!==null)}async checkDockerfilesForUpdates($){let{isDockerfile:X}=await import("./chunk-ys1qqcpp.js"),{fetchLatestDockerImageVersion:Q}=await import("./chunk-ys1qqcpp.js"),K=[],H=$.filter((_)=>X(_.path));this.logger.info(`\uD83D\uDD0D Found ${H.length} Dockerfile(s)`);let Y=[];for(let _ of H){let Z=_.dependencies.filter((z)=>z.type==="docker-image");this.logger.info(`Found ${Z.length} Docker images in ${_.path}`),Z.forEach((z)=>Y.push({file:_,dep:z}))}this.logger.info(`\u26A1 Checking ${Y.length} Docker images in parallel...`);let W=Y.map(async({file:_,dep:Z})=>{try{if(this.logger.info(`Checking Docker image: ${Z.name}:${Z.currentVersion}`),this.shouldRespectVersion(Z.currentVersion))return this.logger.debug(`Skipping ${Z.name} - version "${Z.currentVersion}" should be respected`),null;let z=await Q(Z.name,Z.currentVersion,{...this.config.registries?.docker?{registries:this.config.registries.docker}:{},...this.config.packages?.includePrerelease!==void 0?{includePrerelease:this.config.packages.includePrerelease}:{}});if(z)if(this.logger.info(`Latest version for ${Z.name}: ${z}`),z!==Z.currentVersion){let L=l(Z.currentVersion,z);return this.logger.info(`Update available: ${Z.name} ${Z.currentVersion} \u2192 ${z} (${L})`),{name:Z.name,currentVersion:Z.currentVersion,newVersion:z,updateType:L,dependencyType:"docker-image",file:_.path,metadata:void 0,releaseNotesUrl:`https://hub.docker.com/r/${Z.name}/tags`,changelogUrl:void 0,homepage:`https://hub.docker.com/r/${Z.name}`}}else this.logger.info(`No update needed for ${Z.name}: already at ${z}`);else this.logger.warn(`Could not fetch latest version for Docker image ${Z.name}`);return null}catch(z){return this.logger.warn(`Failed to check version for Docker image ${Z.name}:`,z),null}}),j=(await Promise.all(W)).filter((_)=>_!==null);K.push(...j),this.logger.info(`Generated ${K.length} Docker image updates`);let J=K.reduce((_,Z)=>{if(!_.find((L)=>L.name===Z.name&&L.currentVersion===Z.currentVersion&&L.newVersion===Z.newVersion&&L.file===Z.file))_.push(Z);return _},[]);return this.logger.info(`After deduplication: ${J.length} unique Docker image updates`),J}isNewerVersion($,X){try{return Bun.semver.order(X.replace(/^[v^~>=<@]+/,""),$.replace(/^[v^~>=<@]+/,""))>0}catch{return!1}}readDeclaredNpmVersions(){let $=new Map;try{let X=V("fs"),K=V("path").join(this.projectPath,"package.json");if(!X.existsSync(K))return $;let H=JSON.parse(X.readFileSync(K,"utf8"));for(let Y of["dependencies","devDependencies","peerDependencies","optionalDependencies"])for(let[W,O]of Object.entries(H[Y]??{}))if(typeof O==="string"&&!$.has(W))$.set(W,O)}catch(X){this.logger.debug("Could not read declared versions from package.json:",X)}return $}compareVersionsSafe($,X){try{let Q=X.replace(/^[v^~>=<@]+/,""),K=$.replace(/^[v^~>=<@]+/,"");if(!/^\d+\.\d+/.test(Q)||!/^\d+\.\d+/.test(K))return"failed";return Bun.semver.order(Q,K)>0?"behind":"at-or-beyond"}catch{return"failed"}}async generateAllFileUpdates($){let X=[],Q=$.filter((Z)=>Z.file.endsWith("package.json")&&Z.dependencyType!=="engines"&&!Z.file.includes(".yaml")&&!Z.file.includes(".yml")&&!Z.file.includes(".github/workflows/")),K=$.filter((Z)=>Z.dependencyType==="engines");if(K.length>0){let{applyEngineUpdates:Z}=await import("./chunk-pskqrv5r.js"),z=new Map;for(let L of K)z.set(L.file,[...z.get(L.file)??[],L]);for(let[L,S]of z)try{let B=F0.readFileSync(L,"utf-8"),E=Z(B,S);if(E===B){this.logger.warn(`\u26A0\uFE0F No engine changes written to ${L}`);continue}X.push({path:L,content:E,type:"update"})}catch(B){this.logger.warn(`Failed to update engines in ${L}:`,B)}}let H=new Map;for(let Z of Q){if(!H.has(Z.file))H.set(Z.file,[]);H.get(Z.file).push(Z)}for(let[Z,z]of H)try{let L=F0.readFileSync(Z,"utf-8"),S=JSON.parse(L);for(let B of z){let E=!1,U=B.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,""),A=["dependencies","devDependencies","peerDependencies","optionalDependencies"];for(let T of A)if(S[T]&&S[T][U]){let N=S[T][U].match(/^(\D*)/),b=N?N[1]:"",c=U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=T.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),I=new RegExp(`("${h}"\\s*:\\s*\\{[^}]*?)("${c}"\\s*:\\s*")([^"]+)(")([^}]*?\\})`,"gs"),F=`${b}${B.newVersion}`;L=L.replace(I,`$1$2${F}$4$5`),E=!0;break}if(!E)this.logger.warn(`Package ${U} not found in ${Z}`)}X.push({path:Z,content:L,type:"update"})}catch(L){this.logger.warn(`Failed to update ${Z}:`,L)}let Y=$.filter((Z)=>{let z=Z.file.toLowerCase();return(z.endsWith("deps.yaml")||z.endsWith("deps.yml")||z.endsWith("dependencies.yaml")||z.endsWith("dependencies.yml"))&&!Z.file.includes(".github/workflows/")});if(Y.length>0)try{let{generateDependencyFileUpdates:Z}=await import("./chunk-19zyq15p.js"),z=await Z(Y);X.push(...z)}catch(Z){this.logger.error("Failed to generate dependency file updates:",Z)}let W=$.filter((Z)=>Z.file.endsWith("composer.json")||Z.file.endsWith("composer.lock"));if(W.length>0)try{let{generateComposerUpdates:Z}=await import("./chunk-vqa6vte3.js"),z=await Z(W);X.push(...z)}catch(Z){this.logger.error("Failed to generate Composer updates:",Z)}let O=$.filter((Z)=>Z.file.includes(".github/workflows/"));if(O.length>0)try{let{generateGitHubActionsUpdates:Z}=await import("./chunk-sc7emb71.js"),z=await Z(O);X.push(...z)}catch(Z){this.logger.error("Failed to generate GitHub Actions updates:",Z)}let j=$.filter((Z)=>Z.dependencyType==="docker-image");if(j.length>0)try{let{generateDockerfileUpdates:Z}=await import("./chunk-ys1qqcpp.js"),z=await Z(j,this.config.registries?.docker);X.push(...z)}catch(Z){this.logger.error("Failed to generate Dockerfile updates:",Z)}let J=$.filter((Z)=>Z.dependencyType==="zig-dependencies");if(J.length>0)try{let{generateZigManifestUpdates:Z}=await import("./chunk-zxgkp71x.js"),z=await Z(J);X.push(...z)}catch(Z){this.logger.error("Failed to generate Zig manifest updates:",Z)}let _=$.filter((Z)=>Z.dependencyType==="catalog");if(_.length>0)try{let{applyCatalogUpdates:Z}=await import("./chunk-0paakbpj.js"),z=_[0].file,L=await Bun.file(a(this.projectPath,z)).text(),S=Z(L,_);if(S===L)this.logger.warn(`\u26A0\uFE0F No catalog changes written to ${z}`);else X.push({path:z,content:S,type:"update"})}catch(Z){this.logger.error("Failed to generate pnpm catalog updates:",Z)}return X.push(...await this.generateAdapterFileUpdates($)),X}async generateAdapterFileUpdates($){let{adapterNamed:X}=await import("./chunk-wn6pbyzn.js"),Q=new Map;for(let Y of $){if(!X(Y.dependencyType))continue;let W=Q.get(Y.file);if(W)W.push(Y);else Q.set(Y.file,[Y])}let K=[],H=new Set;for(let[Y,W]of Q){let O=X(W[0].dependencyType);if(!O)continue;H.add(O.name);try{let j=a(this.projectPath,Y),J=await Bun.file(j).text(),_=J;for(let Z of W)_=O.applyUpdate(_,{name:Z.name,currentVersion:Z.currentVersion,newVersion:Z.newVersion,section:Z.dependencyType});if(_===J){this.logger.warn(`\u26A0\uFE0F ${O.name}: no changes written to ${Y}`);continue}K.push({path:Y,content:_,type:"update"})}catch(j){this.logger.error(`Failed to write ${O.name} updates to ${Y}:`,j)}}return[...K,...await this.regenerateAdapterLockfiles(K,[...H])]}async regenerateAdapterLockfiles($,X){if($.length===0||X.length===0)return[];let{regenerateLockfiles:Q}=await import("./chunk-wn6pbyzn.js");try{for(let W of $)await Bun.write(a(this.projectPath,W.path),W.content)}catch(W){return this.logger.warn(`\u26A0\uFE0F Could not stage manifests for lockfile regeneration: ${W}`),[]}let{regenerated:K,notes:H}=await Q(this.projectPath,X);for(let W of H)this.logger.info(`\u2139\uFE0F ${W}`);let Y=[];for(let W of K)try{Y.push({path:W,content:await Bun.file(a(this.projectPath,W)).text(),type:"update"}),this.logger.info(`\uD83D\uDD12 Regenerated ${W}`)}catch(O){this.logger.warn(`\u26A0\uFE0F Could not read the regenerated ${W}: ${O}`)}return Y}async run(){let $=await this.scanForUpdates();if($.updates.length===0)return this.logger.info("No updates available!"),$;if(this.config.pullRequest)await this.createPullRequests($);return $}async checkPackages($){return this.logger.info(`Checking specific packages: ${$.join(", ")}`),this.applyStrategy(await this.registryClient.getUpdatesForPackages($))}async checkPackagesWithPattern($){return this.logger.info(`Checking packages with pattern: ${$}`),this.applyStrategy(await this.registryClient.getUpdatesWithPattern($))}applyStrategy($){let X=this.config.packages?.strategy;return X?this.filterUpdatesByStrategy($,X):$}filterUpdatesByStrategy($,X){if(X==="all")return $;return $.filter((Q)=>P0(X,Q.updateType))}async filterUpdatesByMinimumReleaseAge($){let X=this.config.packages?.minimumReleaseAge??0,Q=this.activeRules(),K=Q.some((j)=>j.minimumReleaseAge!==void 0);if(X===0&&!K)return $;this.logger.info(`Applying minimum release age filter (global ${X} minutes${K?", with per-rule overrides":""}) in parallel...`);let H=$.map(async(j)=>{try{let J=(Q.length>0?g(j,Q).minimumReleaseAge:void 0)??X;if(J===0)return j;if(await this.registryClient.meetsMinimumReleaseAge(j.name,j.newVersion,j.dependencyType,J))return j;else return this.logger.debug(`Filtered out ${j.name}@${j.newVersion} (${j.dependencyType}) \u2014 held for ${J} minutes after publication`),null}catch(J){return this.logger.warn(`Error checking release age for ${j.name}@${j.newVersion} (${j.dependencyType}), including update:`,J),j}}),W=(await Promise.all(H)).filter((j)=>j!==null),O=$.length-W.length;if(O>0)this.logger.info(`Filtered out ${O} updates due to minimum release age requirement`);return W}groupUpdatesByConfig($){let X=[],{grouped:Q,remaining:K}=this.groupByRuleNames($);X.push(...Q);let H=[...K];if(this.config.packages?.groups)for(let Y of this.config.packages.groups){let W=[],{Glob:O}=globalThis.Bun,j=new Set;for(let _ of Y.patterns){let Z;try{Z=new O(_)}catch(z){this.logger.warn(`Invalid group pattern '${_}':`,z);continue}H.forEach((z,L)=>{if(!j.has(L)&&Z.match(z.name))W.push(z),j.add(L)})}if(j.size>0){for(let _=H.length-1;_>=0;_--)if(j.has(_))H.splice(_,1)}let J=W;if(Y.strategy)J=this.filterUpdatesByStrategy(W,Y.strategy);if(J.length>0)X.push({name:Y.name,updates:J,updateType:this.getHighestUpdateType(J),title:`chore(deps): update ${Y.name}`,body:`Update ${J.length} packages in ${Y.name} group`})}if(H.length>0){let Y=Z0(H);X.push(...Y)}return X}groupByRuleNames($){let X=this.config.packages?.rules??[];if(X.length===0)return{grouped:[],remaining:$};let Q=new Map,K=[];for(let Y of $){let W=g(Y,X).groupName;if(!W){K.push(Y);continue}let O=Q.get(W);if(O)O.push(Y);else Q.set(W,[Y])}return{grouped:[...Q.entries()].map(([Y,W])=>({name:Y,updates:W,updateType:this.getHighestUpdateType(W),title:`chore(deps): update ${Y}`,body:`Update ${W.length} packages in ${Y} group`})),remaining:K}}getHighestUpdateType($){if($.some((X)=>X.updateType==="major"))return"major";if($.some((X)=>X.updateType==="minor"))return"minor";return"patch"}generateBranchName($){return`buddy/update-${$.name.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}`}isSimilarPRTitle($,X){if($.toLowerCase()===X.toLowerCase())return!0;let Q=$.toLowerCase(),K=X.toLowerCase(),H=Q.includes("github actions"),Y=K.includes("github actions");if(H&&Y)return!0;if(H!==Y)return!1;let W=Q.includes("docker image"),O=K.includes("docker image");if(W&&O)return!0;if(W!==O)return!1;let j=[/update all non-major/i,/update \d+ dependenc(y|ies)/i,/update.*\(minor\)/i,/update.*\(patch\)/i,/update.*\(major\)/i],J=j.some((Z)=>Z.test($)),_=j.some((Z)=>Z.test(X));if(J&&_){let Z=Q.includes("(major)")||Q.includes("major update"),z=K.includes("(major)")||K.includes("major update");return Z===z}if(K.includes("update dependency ")){let Z=X.match(/update dependency (\S+)/i),z=$.match(/update dependency (\S+)/i);if(Z&&z)return Z[1]===z[1]}if(J!==_)return!1;if(Q.includes("dependency ")&&K.includes("dependency "))return!1;return!1}checkIfUpdatesMatch($,X){if(!$)return!1;let Q=this.extractPackageUpdatesFromPRBody($),K=new Map;for(let H of Q)K.set(H.name,{from:H.currentVersion,to:H.newVersion});for(let H of X){let Y=K.get(H.name);if(!Y)return!1;let W=Y.to.replace(/^[v^~>=<]+/,""),O=H.newVersion.replace(/^[v^~>=<]+/,"");if(W!==O)return!1}return K.size===X.length}shouldAutoClosePR($,X){if(this.shouldAutoCloseForRespectLatest($))return!0;if(this.shouldAutoCloseForIgnorePaths($))return!0;if(this.shouldAutoCloseForRemovedFiles($))return!0;return!1}shouldAutoCloseForRespectLatest($){if(!(this.config.packages?.respectLatest??!0))return!1;let Q=["latest","*","main","master","develop","dev"],K=this.extractPackageUpdatesFromPRBody($.body);if(K.length===0)return!1;return K.filter((Y)=>{let W=Y.currentVersion.toLowerCase().trim();return Q.includes(W)}).length>0}shouldAutoCloseForIgnorePaths($){let X=this.config.packages?.ignorePaths;if(!X||X.length===0)return!1;let Q=this.extractFilePathsFromPRBody($.body);if(Q.length===0)return!1;let{Glob:K}=globalThis.Bun,H=Q.filter((Y)=>{let W=Y.replace(/^\.\//,"");return X.some((O)=>{try{return new K(O).match(W)}catch(j){return this.logger.debug(`Failed to match path ${W} against pattern ${O}: ${j}`),!1}})});if(H.length>0)return this.logger.debug(`PR #${$.number} contains files now in ignorePaths: ${H.join(", ")}`),!0;return!1}shouldAutoCloseForRemovedFiles($){try{let X=this.extractFilePathsFromPRBody($.body);if(X.length===0)return!1;let Q=V("fs"),K=V("path"),H=X.filter((Y)=>{let W=K.join(this.projectPath,Y);return!Q.existsSync(W)});if(H.length>0){if(this.logger.info(`PR #${$.number} references removed files: ${H.join(", ")}`),this.config.packages?.ignorePaths&&this.config.packages.ignorePaths.length>0){let{Glob:_}=globalThis.Bun;if(H.filter((z)=>{return!this.config.packages.ignorePaths.some((L)=>{try{return new _(L).match(z)}catch(S){return this.logger.warn(`Invalid glob pattern '${L}':`,S),!1}})}).length>0)return this.logger.info(`Some removed files are outside ignored paths - not auto-closing PR #${$.number}`),!1}if(H.some((_)=>_.endsWith("composer.json")))return this.logger.info(`composer.json was removed - PR #${$.number} should be auto-closed`),!0;let W=$.body.toLowerCase(),O=W.includes("composer")||H.some((_)=>_.includes("composer")),j=W.includes("package.json")||H.some((_)=>_.includes("package.json")),J=H.some((_)=>_.endsWith("deps.yaml")||_.endsWith("deps.yml")||_.endsWith("dependencies.yaml")||_.endsWith("dependencies.yml"));if(O||j||J)return this.logger.info(`PR #${$.number} is about removed dependency system - should be auto-closed`),!0}return!1}catch(X){return this.logger.debug(`Failed to check for removed files in PR #${$.number}: ${X}`),!1}}get events(){if(!this.eventBus){this.eventBus=new m0(this.logger);for(let $ of f0(this.config.notifications))this.eventBus.register($)}return this.eventBus}async createGitProvider(){let $=this.config.repository;if(!$?.owner||!$.name)return this.logger.warn("\u26A0\uFE0F Repository owner and name are required for pull request operations"),null;try{return await e({provider:$.provider,owner:$.owner,name:$.name,...$.apiUrl?{apiUrl:$.apiUrl}:{}},{logger:this.logger})}catch(X){return this.logger.warn(`\u26A0\uFE0F ${N0(X)}`),null}}async queueAutoMerge($,X,Q,K){let H=I0(Q,K,this.config);if(!H.eligible){this.logger.debug(`\uD83D\uDD00 PR #${X.number} not auto-merged: ${H.reason}`);return}let{strategy:Y}=n(this.config);if(!p($,"nativeAutoMerge","enableAutoMerge")){this.logger.info(`\uD83D\uDD00 PR #${X.number} qualifies for auto-merge but this provider has no merge queue; update-check will merge it once checks pass`);return}try{if(await $.enableAutoMerge(X.number,Y))this.logger.success(`\uD83D\uDD00 PR #${X.number} queued for auto-merge (${H.reason})`);else this.logger.info(`\uD83D\uDD00 PR #${X.number} qualifies for auto-merge but the repository cannot queue it; update-check will merge it once checks pass`)}catch(W){this.logger.warn(`\u26A0\uFE0F Failed to queue auto-merge for PR #${X.number}: ${W}`)}}async mergeEligiblePullRequests($=!1){let X=n(this.config);if(!X.enabled)return[];let Q=await this.createGitProvider();if(!Q)return[];let K=[],H=await Q.getPullRequests("open");for(let Y of H.filter((W)=>W.head.startsWith("buddy/"))){let W=X.requireGreenCI&&Q.getPullRequestChecksState?await Q.getPullRequestChecksState(Y.number):"none",O=W==="success"||W==="none",j=V0({number:Y.number,title:Y.title,body:Y.body,head:Y.head,labels:Y.labels,draft:Y.draft},this.config,O);if(!j.eligible){this.logger.debug(`\uD83D\uDD00 PR #${Y.number} not merged: ${j.reason}`);continue}if($){this.logger.info(`\uD83D\uDD00 [DRY RUN] Would merge PR #${Y.number} (${j.reason})`),K.push(Y.number);continue}try{await Q.mergePullRequest(Y.number,X.strategy),this.logger.success(`\uD83D\uDD00 Merged PR #${Y.number}: ${j.reason}`),await this.events.emit("pr.merged",{number:Y.number,title:Y.title,strategy:X.strategy}),K.push(Y.number)}catch(J){this.logger.warn(`\u26A0\uFE0F Failed to merge PR #${Y.number}: ${J}`)}}return K}isPlausibleRepoPath($){if(!$||/[\s()[\]!`]|:\/\//.test($))return!1;return/^[\w@.-]+(?:\/[\w@.-]+)*$/.test($)}extractFilePathsFromPRBody($){let X=f($);if(X)return b0(X);let Q=[],K=/\|\s*\[[^\]]+\]\([^)]*\)\s*\|[^|]*\|\s*\*\*([^*]+)\*\*\s*\|/g,H;while((H=K.exec($))!==null){let j=H[1].trim();if(this.isPlausibleRepoPath(j)&&!Q.includes(j))Q.push(j)}let Y=/\*\*([^*]+\.(?:json|yaml|yml|lock))\*\*/g;while((H=Y.exec($))!==null){let j=H[1].trim();if(this.isPlausibleRepoPath(j)&&!Q.includes(j))Q.push(j)}let W=/\|[^|]+\|[^|]+\|([^|]+)\|[^|]*\|/g;while((H=W.exec($))!==null){let j=H[1].trim();if(this.isPlausibleRepoPath(j)&&(j.includes("/")||/\.(?:json|yaml|yml|lock)$/.test(j))&&!Q.includes(j))Q.push(j)}let O=/(?:^|\s)([\w-]+(?:\/[\w.-]+)*\/[\w.-]+\.(?:json|yaml|yml|lock))(?:\s|$)/gm;while((H=O.exec($))!==null){let j=H[1].trim();if(this.isPlausibleRepoPath(j)&&!Q.includes(j))Q.push(j)}return Q}extractPackagesFromPRBody($){let X=f($);if(X)return[...new Set(X.updates.map((Y)=>Y.name))];let Q=[],K=$.match(/\|[^|]*\|[^|]*\|[^|]*\|[^|]*\|/g);if(K)for(let Y of K){let W=Y.match(/\[([^\]]+)\]\([^)]*\)/);if(W)Q.push(W[1])}let H=$.match(/<summary>([^<]+)<\/summary>/g);if(H)for(let Y of H){let W=Y.replace(/<summary>/,"").replace(/<\/summary>/,"").trim();if(W&&!Q.includes(W))Q.push(W)}return Q}extractPackageUpdatesFromPRBody($){let X=f($);if(X)return R0(X);let Q=[],K=new Set,H=/\|\s*\[([^\]]+)\][^|]*\|\s*\[?`?[v^~>=]*([^`|\s]+)`?\s*(?:->|\u2192)\s*`?[v^~>=]*([^`|\s]+)`?\]?/g,Y;while((Y=H.exec($))!==null){let[,W,O,j]=Y;if(!K.has(W))K.add(W),Q.push({name:W,currentVersion:O,newVersion:j})}return Q}getConfig(){return this.config}getProjectPath(){return this.projectPath}async checkAndCloseObsoletePRs($,X=!1){try{this.logger.info("\uD83D\uDD0D Scanning for obsolete PRs due to removed dependency files...");let K=(await $.getPullRequests("open")).filter((Y)=>Y.head.startsWith("buddy/")||Y.author==="github-actions[bot]"&&Y.labels.includes("dependencies"));this.logger.info(`Found ${K.length} dependency-related PRs to check`);let H=0;for(let Y of K)try{if(this.shouldAutoCloseForRemovedFiles(Y))if(this.logger.info(`\uD83D\uDD12 PR #${Y.number} should be auto-closed: ${Y.title}`),X)this.logger.info(`\uD83D\uDD0D [DRY RUN] Would auto-close PR #${Y.number}`),H++;else try{let O=this.generateCloseReason(Y);try{await $.createComment(Y.number,O)}catch(j){this.logger.warn(`\u26A0\uFE0F Could not add close reason comment to PR #${Y.number}:`,j)}if(await $.closePullRequest(Y.number),await this.events.emit("pr.closed",{number:Y.number,title:Y.title,reason:"obsolete \u2014 its dependency files no longer exist"}),Y.head.startsWith("buddy/"))try{await $.deleteBranch(Y.head),this.logger.success(`\u2705 Auto-closed PR #${Y.number} and deleted branch ${Y.head}`)}catch(j){this.logger.warn(`\u26A0\uFE0F Auto-closed PR #${Y.number} but failed to delete branch: ${j}`)}else this.logger.success(`\u2705 Auto-closed PR #${Y.number}`);H++}catch(O){this.logger.error(`\u274C Failed to auto-close PR #${Y.number}:`,O)}}catch(W){this.logger.warn(`\u26A0\uFE0F Error checking PR #${Y.number}:`,W)}if(H>0)this.logger.success(`\u2705 ${X?"Would auto-close":"Auto-closed"} ${H} obsolete PR(s)`);else this.logger.info("\uD83D\uDCCB No obsolete PRs found")}catch(Q){throw this.logger.error("Failed to check for obsolete PRs:",Q),Q}}async checkAndCloseSatisfiedPRs($,X=!1){try{this.logger.info("\uD83D\uDD0D Checking for PRs where dependencies are already at target version...");let K=(await $.getPullRequests("open")).filter((_)=>_.head.startsWith("buddy/")||_.author==="github-actions[bot]"&&_.labels.includes("dependencies"));if(this.logger.info(`Found ${K.length} buddy dependency PRs to validate`),K.length===0){this.logger.info("\uD83D\uDCCB No buddy PRs to check");return}let H=0,Y={...this.config,packages:{...this.config.packages,strategy:"all"}},O=await new $0(Y,this.projectPath).scanForUpdates(),j=new Map;for(let _ of O.updates)j.set(_.name,_);let J=this.readDeclaredNpmVersions();if(O.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 _ of K)try{let Z=this.extractPackageUpdatesFromPRBody(_.body);if(Z.length===0){this.logger.debug(`PR #${_.number}: Could not extract package updates, skipping`);continue}let z=_.body.match(/\*\*Total\*\*\s*\|\s*\*\*(\d+)\*\*/),L=z?Number.parseInt(z[1],10):0;if(L>0&&Z.length<L){this.logger.debug(`PR #${_.number}: Extracted ${Z.length}/${L} updates \u2014 incomplete extraction, skipping satisfied check`);continue}let S=0,B=0,E=0;for(let A of Z){let T=j.get(A.name);if(!T){let N=J.get(A.name);if(N){let b=this.compareVersionsSafe(N,A.newVersion);if(b==="at-or-beyond"){this.logger.debug(`PR #${_.number}: ${A.name} declared at ${N}, at or beyond ${A.newVersion}`),S++;continue}if(b==="behind"){this.logger.debug(`PR #${_.number}: ${A.name} declared at ${N}, still behind ${A.newVersion} \u2014 the scan missed it`),B++;continue}}this.logger.debug(`PR #${_.number}: ${A.name} not in current scan and not declared (unverifiable)`),E++;continue}if(T.newVersion===A.newVersion){this.logger.debug(`PR #${_.number}: ${A.name} still needs update to ${A.newVersion}`),B++;continue}let q=this.compareVersionsSafe(T.currentVersion,A.newVersion);if(q==="at-or-beyond")this.logger.debug(`PR #${_.number}: ${A.name} already at or beyond ${A.newVersion}`),S++;else if(q==="behind")this.logger.debug(`PR #${_.number}: ${A.name} still behind ${A.newVersion}`),B++;else this.logger.debug(`PR #${_.number}: ${A.name} version comparison inconclusive`),E++}let U=B===0&&E===0&&S>0;if(this.logger.debug(`PR #${_.number}: verified-satisfied=${S}, still-needed=${B}, unverifiable=${E} \u2192 ${U?"CLOSE":"KEEP"}`),U)if(this.logger.info(`\u2705 PR #${_.number} is satisfied (dependencies at target version): ${_.title}`),X)this.logger.info(`\uD83D\uDD0D [DRY RUN] Would close PR #${_.number}`),H++;else try{let A=Z.filter((q)=>{let b=j.get(q.name)?.currentVersion??J.get(q.name);if(!b)return!1;return this.compareVersionsSafe(b,q.newVersion)==="at-or-beyond"}),T=`\uD83E\uDD16 **Auto-closing satisfied PR**
88
-
89
- `;if(A.length>0)T+=`The following packages are already at the target version or newer:
90
-
91
- `,A.forEach((q)=>{T+=`- **${q.name}**: ${q.currentVersion} \u2192 ${q.newVersion}
92
- `}),T+=`
93
- `;T+="If this was closed in error, please reopen and add a comment explaining why.";try{await $.createComment(_.number,T)}catch(q){this.logger.warn(`\u26A0\uFE0F Could not add comment to PR #${_.number}:`,q)}if(await $.closePullRequest(_.number),await this.events.emit("pr.closed",{number:_.number,title:_.title,reason:"satisfied \u2014 every package already at or beyond target"}),_.head.startsWith("buddy/"))try{await $.deleteBranch(_.head),this.logger.success(`\u2705 Closed PR #${_.number} and deleted branch ${_.head}`)}catch(q){this.logger.warn(`\u26A0\uFE0F Closed PR #${_.number} but failed to delete branch: ${q}`)}else this.logger.success(`\u2705 Closed PR #${_.number}`);H++}catch(A){this.logger.error(`\u274C Failed to close PR #${_.number}:`,A)}}catch(Z){this.logger.warn(`\u26A0\uFE0F Error validating PR #${_.number}:`,Z)}if(H>0)this.logger.success(`\u2705 ${X?"Would close":"Closed"} ${H} satisfied PR(s)`);else this.logger.info("\uD83D\uDCCB No satisfied PRs found")}catch(Q){throw this.logger.error("Failed to check for satisfied PRs:",Q),Q}}generateCloseReason($){let Q=this.extractFilePathsFromPRBody($.body).filter((O)=>{let j=V("fs"),_=V("path").join(this.projectPath,O);return!j.existsSync(_)}),K=Q.some((O)=>O.includes("composer")),H=Q.some((O)=>O.includes("package.json")),Y=Q.some((O)=>O.endsWith("deps.yaml")||O.endsWith("deps.yml")||O.endsWith("dependencies.yaml")||O.endsWith("dependencies.yml")),W=`\uD83E\uDD16 **Auto-closing obsolete PR**
94
-
95
- `;if(K)W+="This PR was automatically closed because `composer.json` has been removed from the project, indicating that Composer is no longer used for dependency management.\n\n";else if(H)W+="This PR was automatically closed because `package.json` has been removed from the project, indicating that npm/yarn/pnpm is no longer used for dependency management.\n\n";else if(Y)W+=`This PR was automatically closed because the dependency files it references have been removed from the project.
96
-
97
- `;else W+=`This PR was automatically closed because the dependency files it references are no longer present in the project.
98
-
99
- `;if(Q.length>0)W+=`**Removed files:**
100
- ${Q.map((O)=>`- \`${O}\``).join(`
101
- `)}
102
-
103
- `;return W+="If this was closed in error, please reopen the PR and update the dependency files accordingly.",W}async createOrUpdateDashboard(){try{if(this.logger.info("Creating or updating dependency dashboard..."),!this.config.repository)throw Error("Repository configuration is required for dashboard");if(this.config.repository.provider!=="github")throw Error("Dashboard is currently only supported for GitHub repositories");if(!this.config.repository.owner||!this.config.repository.name)throw Error("Repository owner and name are required for dashboard. Set them in buddy.config.ts or ensure GITHUB_REPOSITORY env var is available.");let $=await e({provider:this.config.repository.provider,owner:this.config.repository.owner,name:this.config.repository.name,...this.config.repository.token?{token:this.config.repository.token}:{},...this.config.repository.apiUrl?{apiUrl:this.config.repository.apiUrl}:{}},{logger:this.logger}),X=await this.collectDashboardData($),Q=this.config.dashboard||{},{title:K,body:H}=this.dashboardGenerator.generateDashboard(X,{showOpenPRs:Q.showOpenPRs??!0,showDetectedDependencies:Q.showDetectedDependencies??!0,showDeprecatedDependencies:Q.showDeprecatedDependencies??!0,includePackageJson:Q.includePackageJson??!0,includeDependencyFiles:Q.includeDependencyFiles??!0,includeGitHubActions:Q.includeGitHubActions??!0,bodyTemplate:Q.bodyTemplate}),Y={title:Q.title||K,body:H,labels:Q.labels||["dependencies","dashboard"],assignees:Q.assignees},W=await this.findExistingDashboard($,Q.issueNumber),O=null;if(W){if(this.logger.info(`Updating existing dashboard issue #${W.number}`),O=await this.updateDashboardIssue($,W.number,Y),O)this.logger.success(`\u2705 Successfully updated dashboard issue #${O.number}`)}if(!O){this.logger.info("Creating new dashboard issue"),this.logger.info("Performing final check for existing dashboards before creation...");let j=await this.findExistingDashboard($,Q.issueNumber);if(j&&j.number!==W?.number){if(this.logger.info(`Race condition detected! Found existing dashboard #${j.number} during final check`),O=await this.updateDashboardIssue($,j.number,Y),O)this.logger.success(`\u2705 Updated existing dashboard issue #${O.number} (race condition avoided)`)}if(!O)O=await $.createIssue(Y),this.logger.success(`\u2705 Successfully created new dashboard issue #${O.number}`)}if(Q.pin!==void 0)if(!Q.pin)await $.unpinIssue(O.number);else if(p($,"pinIssues","pinIssue"))await $.pinIssue(O.number);else this.logger.debug("\uD83D\uDCCC Provider does not support pinning issues; leaving the dashboard unpinned");return this.logger.success(`\u2705 Dashboard updated: ${O.url}`),await this.events.emit("dashboard.updated",{number:O.number,url:O.url}),O}catch($){throw this.logger.error("Failed to create or update dashboard:",$),$}}async collectDashboardData($){let[X,Q]=await Promise.all([this.scanner.scanProject(),$.getPullRequests("open")]),K=Q.filter((Z)=>Z.labels.includes("dependencies")||Z.labels.includes("dependency")||Z.labels.includes("deps")||Z.title.toLowerCase().includes("update")||Z.title.toLowerCase().includes("chore(deps)")||Z.title.toLowerCase().includes("bump")||Z.title.toLowerCase().includes("upgrade")||Z.title.toLowerCase().includes("renovate")||Z.head.includes("renovate/")||Z.head.includes("dependabot/")||Z.head.includes("buddy/")||Z.head.includes("update-")||Z.head.includes("bump-")),H=X.filter((Z)=>Z.type==="package.json"),Y=X.filter((Z)=>Z.path.includes(".github/workflows/")&&(Z.path.endsWith(".yml")||Z.path.endsWith(".yaml"))),W=X.filter((Z)=>!Z.path.includes(".github/workflows/")&&Z.type!=="package.json"),j=await new c0().checkDeprecatedDependencies(X),J=await this.findVulnerableDependencies(X),_=await this.findCappedDependencies(X);return{openPRs:K,detectedDependencies:{packageJson:H,dependencyFiles:W,githubActions:Y},deprecatedDependencies:j,vulnerableDependencies:J,cappedDependencies:_,repository:{owner:this.config.repository.owner,name:this.config.repository.name,provider:this.config.repository.provider},lastUpdated:new Date}}async findCappedDependencies($){if(this.config.packages?.detectResolutionDrift===!1)return[];try{let{collectDriftInputs:X}=await import("./chunk-yp1tgdh3.js"),{findDrift:Q}=await import("./chunk-3fzbvs2p.js"),K=await X($,this.registryClient,this.projectPath,this.logger),H=Q(K).filter((Y)=>Y.kind==="capped");if(H.length>0)this.logger.info(`\uD83D\uDD17 ${H.length} package(s) capped by a dependant's range`);return H}catch(X){return this.logger.warn("Resolution drift analysis failed, continuing without it:",X),[]}}async findVulnerableDependencies($){if(this.config.security?.enabled===!1)return[];let X=[],Q=new Map;for(let K of $)for(let H of K.dependencies){let Y=K0(H.type);if(!Y)continue;let W=H.currentVersion.replace(/^[\^~>=<\s]*v?/,"").trim();if(!W)continue;let O={name:H.name,version:W,ecosystem:Y},j=r(O);if(Q.has(j))continue;Q.set(j,{name:H.name,currentVersion:H.currentVersion,ecosystem:Y,file:K.path}),X.push(O)}if(X.length===0)return[];try{let H=await new t(this.logger).findAdvisories(X),Y=this.config.security?.minimumSeverity??"low",W={low:0,moderate:1,high:2,critical:3},O=[];for(let[j,J]of H){let _=Q.get(j);if(!_)continue;let Z=J.filter((z)=>W[z.severity]>=W[Y]);if(Z.length>0)O.push({..._,advisories:Z})}return O.sort((j,J)=>W[J.advisories[0].severity]-W[j.advisories[0].severity]),O}catch(K){return this.logger.warn("Vulnerability check failed, dashboard will omit it:",K),[]}}async updateDashboardIssue($,X,Q){try{return await $.updateIssue(X,Q)}catch(K){if(K instanceof C0&&K.isNotFound)return this.logger.warn(`Dashboard issue #${X} no longer exists in ${K.repository} (${K.status}); creating a replacement dashboard instead.`),null;throw K}}async findExistingDashboard($,X){try{if(this.logger.info("Searching for existing dashboard issue..."),X){this.logger.info(`Looking for specific dashboard issue #${X}`);let O=(await $.getIssues("open")).find((j)=>j.number===X);if(O)return this.logger.info(`Found specified dashboard issue #${O.number}: ${O.title}`),O;else return this.logger.warn(`Specified dashboard issue #${X} not found`),null}let Q=await $.getIssues("open");this.logger.info(`Found ${Q.length} open issues to search through`);for(let W of Q){let O=W.labels.includes("dashboard")&&W.labels.includes("dependencies"),j=W.title.toLowerCase().includes("dependency dashboard"),J=W.body.includes("This issue lists Buddy updates and detected dependencies");if(J||O&&j)return this.logger.info(`Found existing dashboard issue #${W.number}: ${W.title}`),this.logger.info(` - Labels: ${W.labels.join(", ")}`),this.logger.info(` - Title matches: ${j}`),this.logger.info(` - Body has marker: ${J}`),W}let K=Q.filter((W)=>W.labels.includes("dashboard")),H=Q.filter((W)=>W.labels.includes("dependencies")),Y=Q.filter((W)=>W.title.toLowerCase().includes("dependency dashboard"));if(this.logger.info("Dashboard search results:"),this.logger.info(` - Issues with 'dashboard' label: ${K.length}`),this.logger.info(` - Issues with 'dependencies' label: ${H.length}`),this.logger.info(` - Issues with 'dependency dashboard' in title: ${Y.length}`),K.length>0){this.logger.info("Issues with 'dashboard' label:");for(let W of K)this.logger.info(` - #${W.number}: ${W.title} (labels: ${W.labels.join(", ")})`)}return this.logger.info("No existing dashboard issue found"),null}catch(Q){throw this.logger.error(`Failed to search for existing dashboard: ${Q}`),Q}}}
104
- export{K0 as Vc,r0 as Wc,t as Xc,r as Yc,T0 as Zc,$0 as _c};