@buddysh/buddy 0.11.17 → 0.11.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +12 -0
- package/bin/cli.ts +92 -72
- package/dist/bin/cli.js +73 -107
- package/dist/bin/entry.d.ts +1 -0
- package/dist/bin/entry.js +3 -0
- package/dist/bin/stacks.d.ts +1 -0
- package/dist/bin/stacks.js +3 -0
- package/dist/chunk-05nyhkdp.js +2 -0
- package/dist/{chunk-hd74jxm2.js → chunk-065sjjzg.js} +2 -2
- package/dist/chunk-0796xk82.js +2 -0
- package/dist/{chunk-bnp0r4eh.js → chunk-0pf9vk80.js} +1 -1
- package/dist/chunk-11599831.js +2 -0
- package/dist/chunk-1et7ppg7.js +2 -0
- package/dist/chunk-20sxtyt7.js +3 -0
- package/dist/chunk-23cjwxjk.js +2 -0
- package/dist/{chunk-cj4d5ad7.js → chunk-2g8r8khw.js} +1 -1
- package/dist/{chunk-cb25v2mp.js → chunk-2v4b940m.js} +1 -1
- package/dist/{chunk-nk8wxxy7.js → chunk-33ymc651.js} +2 -2
- package/dist/{chunk-0kce7e60.js → chunk-3pg9420w.js} +1 -1
- package/dist/{chunk-1a14rx5n.js → chunk-47k0qdd5.js} +2 -2
- package/dist/chunk-4gf3a9pm.js +2 -0
- package/dist/chunk-4we8d2ys.js +2 -0
- package/dist/{chunk-1g43mpqn.js → chunk-539wp217.js} +1 -1
- package/dist/{chunk-j57716xw.js → chunk-58et72hc.js} +1 -1
- package/dist/{chunk-743mhx0e.js → chunk-5feeegzy.js} +2 -2
- package/dist/{chunk-1pecmenc.js → chunk-5nn5mms4.js} +1 -1
- package/dist/{chunk-j46f90n8.js → chunk-5q5tm30a.js} +1 -1
- package/dist/{chunk-t1r2ycn7.js → chunk-5qxs04gf.js} +1 -1
- package/dist/{chunk-9chq5m4p.js → chunk-5ytyahtm.js} +4 -4
- package/dist/chunk-6477cdgj.js +2 -0
- package/dist/{chunk-s3b3vrsj.js → chunk-6bdrm4ab.js} +2 -2
- package/dist/{chunk-psjrcpgb.js → chunk-6kmaj5br.js} +2 -2
- package/dist/chunk-6m03hqbw.js +3 -0
- package/dist/{chunk-whtdmv3p.js → chunk-73a090ce.js} +2 -2
- package/dist/chunk-78pxywjv.js +2 -0
- package/dist/{chunk-nznpzbq4.js → chunk-7bqy4enq.js} +1 -1
- package/dist/chunk-843907bh.js +2 -0
- package/dist/{chunk-dxd0eg4r.js → chunk-88jx1n4t.js} +1 -1
- package/dist/{chunk-gq9gkyah.js → chunk-89spjk6r.js} +2 -2
- package/dist/chunk-8fm0z13m.js +2 -0
- package/dist/{chunk-sj7n6xa1.js → chunk-8hstj0s3.js} +1 -1
- package/dist/{chunk-6w0n6c07.js → chunk-8y4szfd2.js} +1 -1
- package/dist/{chunk-2f7j0dmw.js → chunk-91q9x0df.js} +1 -1
- package/dist/chunk-9pt7kwmm.js +2 -0
- package/dist/{chunk-mthd2c8m.js → chunk-a5hevn6e.js} +2 -2
- package/dist/{chunk-sddaassq.js → chunk-agdvymzh.js} +1 -1
- package/dist/{chunk-8r2819xn.js → chunk-ar8skamr.js} +1 -1
- package/dist/chunk-b8n7zh62.js +2 -0
- package/dist/chunk-by2hfewp.js +2 -0
- package/dist/{chunk-4chtv4nh.js → chunk-c7ja1xmh.js} +1 -1
- package/dist/chunk-cfj98vmf.js +2 -0
- package/dist/{chunk-wk175yyw.js → chunk-cp3g2srn.js} +2 -2
- package/dist/chunk-cxbrnbcp.js +2 -0
- package/dist/{chunk-wfwrm4k3.js → chunk-dev3g0n3.js} +1 -1
- package/dist/{chunk-mr2d1zp0.js → chunk-dgcct70c.js} +2 -2
- package/dist/{chunk-16aeend1.js → chunk-dh8yykbg.js} +1 -1
- package/dist/{chunk-m3rftash.js → chunk-dkgz8hsd.js} +7 -7
- package/dist/{chunk-byqzhgzs.js → chunk-dmaxdw65.js} +1 -1
- package/dist/chunk-e0d1n3yn.js +2 -0
- package/dist/{chunk-1pdvjg0x.js → chunk-ebb90mp9.js} +1 -1
- package/dist/chunk-ece98jde.js +2 -0
- package/dist/{chunk-gg1ddvnf.js → chunk-ednwgr1b.js} +2 -2
- package/dist/{chunk-69qyr9ef.js → chunk-ejfyc7r8.js} +1 -1
- package/dist/{chunk-wfg3bp85.js → chunk-en525sf9.js} +1 -1
- package/dist/{chunk-d09qj570.js → chunk-eq5xb8k1.js} +2 -2
- package/dist/{chunk-h2f92qwd.js → chunk-ewnhhpak.js} +1 -1
- package/dist/{chunk-1jgh0ff1.js → chunk-f3fmewqb.js} +2 -2
- package/dist/chunk-f694pp35.js +2 -0
- package/dist/{chunk-r1jvyhhd.js → chunk-fcax5a60.js} +2 -2
- package/dist/{chunk-pxfrq43h.js → chunk-ffjp134d.js} +1 -1
- package/dist/{chunk-vs61069x.js → chunk-g763t4rr.js} +1 -1
- package/dist/chunk-h65g7hd0.js +2 -0
- package/dist/{chunk-c63e4ssc.js → chunk-h9deve0y.js} +3 -3
- package/dist/chunk-hfq56cgn.js +2 -0
- package/dist/chunk-hwpv7jhw.js +1043 -0
- package/dist/chunk-j9pe2np4.js +5 -0
- package/dist/chunk-jq846den.js +2 -0
- package/dist/{chunk-26yejy1v.js → chunk-jxmpwday.js} +1 -1
- package/dist/{chunk-wc2z7krw.js → chunk-jy1kbr1k.js} +2 -2
- package/dist/{chunk-6gvx1g6h.js → chunk-m6qym0ya.js} +2 -2
- package/dist/chunk-nezqdnp3.js +2 -0
- package/dist/{chunk-7m3pzkcj.js → chunk-ng9zksy3.js} +1 -1
- package/dist/{chunk-7p1b809h.js → chunk-nmrf0ydg.js} +1 -1
- package/dist/{chunk-0f1xye20.js → chunk-pxv58dh1.js} +1 -1
- package/dist/{chunk-2z9mh5y4.js → chunk-q3dg57xx.js} +1 -1
- package/dist/chunk-q9x936wq.js +2 -0
- package/dist/{chunk-jqh7vx2n.js → chunk-qbqk1jax.js} +2 -2
- package/dist/{chunk-ewhvahnb.js → chunk-qfm0eh6y.js} +2 -2
- package/dist/{chunk-g09atq0m.js → chunk-qn1g860m.js} +1 -1
- package/dist/{chunk-yh13j2af.js → chunk-r0jmwzr3.js} +1 -1
- package/dist/chunk-rmv4ajb2.js +2 -0
- package/dist/{chunk-wzncz6j5.js → chunk-rrm4x81p.js} +1 -1
- package/dist/chunk-rsvtnsmt.js +2 -0
- package/dist/{chunk-24xvskkf.js → chunk-rwzt9xvk.js} +1 -1
- package/dist/{chunk-qngnmrpw.js → chunk-ry21xmre.js} +1 -1
- package/dist/{chunk-67bjaw56.js → chunk-s6w47z4a.js} +3 -3
- package/dist/chunk-sek2e857.js +2 -0
- package/dist/{chunk-s0ps33ft.js → chunk-sg7bhtb7.js} +1 -1
- package/dist/{chunk-r7qa2ykf.js → chunk-snya72ah.js} +2 -2
- package/dist/{chunk-a8wcn3mh.js → chunk-t7grk0az.js} +2 -2
- package/dist/chunk-tes3e84x.js +2 -0
- package/dist/chunk-tgm4vbaq.js +2 -0
- package/dist/{chunk-142zh7e5.js → chunk-tqwek43e.js} +1 -1
- package/dist/{chunk-mtn4angk.js → chunk-tztc0r76.js} +1 -1
- package/dist/chunk-v0895nt9.js +2 -0
- package/dist/chunk-v6rrvfh4.js +2 -0
- package/dist/{chunk-k8sd78td.js → chunk-vn4c8fxq.js} +1 -1
- package/dist/{chunk-4r03rh93.js → chunk-vpz26asn.js} +2 -2
- package/dist/{chunk-x9vpk4kk.js → chunk-vxt1h0c4.js} +1 -1
- package/dist/chunk-vyckmje5.js +2 -0
- package/dist/{chunk-4dz5x4xw.js → chunk-wca85ahg.js} +1 -1
- package/dist/chunk-we1n57ze.js +2 -0
- package/dist/{chunk-5yfaptmp.js → chunk-wm6g7y1r.js} +1 -1
- package/dist/chunk-wnqqprmy.js +2 -0
- package/dist/chunk-wt8b3ywq.js +2 -0
- package/dist/{chunk-bw43q8k7.js → chunk-wx4qd9e9.js} +1 -1
- package/dist/chunk-x0mq8nn2.js +2 -0
- package/dist/{chunk-her5azyp.js → chunk-x9spxa46.js} +2 -2
- package/dist/chunk-xfk9a8az.js +2 -0
- package/dist/{chunk-gvpsbmeg.js → chunk-xmk24pz9.js} +2 -2
- package/dist/{chunk-6b0fmw0d.js → chunk-xn2xv07k.js} +2 -2
- package/dist/chunk-xntpzagn.js +3 -0
- package/dist/{chunk-bafzw99p.js → chunk-xqcmw7d0.js} +2 -2
- package/dist/chunk-xvq8w2jm.js +2 -0
- package/dist/{chunk-4wv5s3vr.js → chunk-xyry3bma.js} +2 -2
- package/dist/{chunk-hk4d7rky.js → chunk-y6292gbf.js} +2 -2
- package/dist/chunk-ye3aym4p.js +2 -0
- package/dist/{chunk-7hm46cej.js → chunk-yx9v94q5.js} +2 -2
- package/dist/chunk-yxt8294f.js +2 -0
- package/dist/{chunk-vckhctmr.js → chunk-yy8vb4yk.js} +1 -1
- package/dist/{chunk-fsghqtgf.js → chunk-z0avay86.js} +2 -2
- package/dist/{chunk-z2gcfvze.js → chunk-z906zp4k.js} +5 -5
- package/dist/chunk-zy6azdxt.js +2 -0
- package/dist/src/index.js +1 -1
- package/dist/src/setup.js +1 -1
- package/dist/src/stacks-cli.d.ts +7 -0
- package/package.json +5 -5
- package/dist/chunk-0n03s02h.js +0 -2
- package/dist/chunk-1k4p8wyx.js +0 -2
- package/dist/chunk-1mkwhnsf.js +0 -2
- package/dist/chunk-2309x9r7.js +0 -2
- package/dist/chunk-3jm67wxm.js +0 -2
- package/dist/chunk-3mnpvfg3.js +0 -2
- package/dist/chunk-485kgdtb.js +0 -2
- package/dist/chunk-51m5tgwp.js +0 -2
- package/dist/chunk-5t07s3dv.js +0 -2
- package/dist/chunk-6bqs7rtc.js +0 -2
- package/dist/chunk-6kd81nf9.js +0 -1070
- package/dist/chunk-8b7cwedf.js +0 -2
- package/dist/chunk-8wrbxhs3.js +0 -2
- package/dist/chunk-9fagkyrp.js +0 -2
- package/dist/chunk-9gabxm8n.js +0 -2
- package/dist/chunk-bgb44971.js +0 -2
- package/dist/chunk-bz5yx7g6.js +0 -2
- package/dist/chunk-dttp44vs.js +0 -2
- package/dist/chunk-fzs7vpps.js +0 -2
- package/dist/chunk-gkb0gja4.js +0 -2
- package/dist/chunk-hxkxset4.js +0 -2
- package/dist/chunk-jgq5d6s2.js +0 -2
- package/dist/chunk-km4aszfp.js +0 -2
- package/dist/chunk-kthwzc4p.js +0 -2
- package/dist/chunk-m9qtb4xj.js +0 -2
- package/dist/chunk-p9xksx9p.js +0 -2
- package/dist/chunk-pag93kz1.js +0 -2
- package/dist/chunk-q4j2f72t.js +0 -2
- package/dist/chunk-qbep9dk4.js +0 -2
- package/dist/chunk-rqj1vrfs.js +0 -2
- package/dist/chunk-s4fccg73.js +0 -2
- package/dist/chunk-tjj6ttj1.js +0 -2
- package/dist/chunk-tsd9jw07.js +0 -2
- package/dist/chunk-ttkjzy0m.js +0 -2
- package/dist/chunk-txe5z472.js +0 -2
- package/dist/chunk-vffz69jj.js +0 -2
- package/dist/chunk-wn9vr9ct.js +0 -2
- package/dist/chunk-y2ntnpdb.js +0 -2
- package/dist/chunk-y5fdq7cd.js +0 -2
- package/dist/chunk-yr6qyeab.js +0 -2
- package/dist/chunk-z18bksyr.js +0 -3
- package/dist/chunk-zj2pt1bx.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{qd as N}from"./chunk-0f1xye20.js";import{vd as M}from"./chunk-6gvx1g6h.js";import{ee as T}from"./chunk-mr2d1zp0.js";import{je as L,ke as _}from"./chunk-743mhx0e.js";var D=["major","minor","patch","all"],m=["merge","squash","rebase"],P=["patch-only","minor-only","security-only","all"],R=["anthropic","openai","google","openrouter","openai-compatible"],A=["low","medium","high"],S=["chill","assertive"],d=["never","critical"],q=["low","moderate","high","critical"],E=["silent","error","warn","info","debug"],w=["npm","composer","github-actions","docker","pkgx","zig","python","rust","go","ruby"],b=["major","minor","patch"],U=T.map((J)=>J.name);function K(J){return JSON.stringify(J)}function Z(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}function Y(J,B,X,$){if(X===void 0)return;if(typeof X!=="string"||!$.includes(X))J.push({path:B,message:`expected one of ${$.map(K).join(", ")}, got ${K(X)}`})}function C(J,B,X,$={}){let Q=$.min??0,W=$.integer??!1;if(X===void 0)return;if(typeof X!=="number"||!Number.isFinite(X)||X<Q){J.push({path:B,message:`expected a number >= ${Q}, got ${K(X)}`});return}if(W&&!Number.isInteger(X))J.push({path:B,message:`expected a whole number, got ${K(X)}`})}function j(J,B,X,$){if(X===void 0)return;if(!Array.isArray(X)){J.push({path:B,message:`expected an array, got ${K(X)}`});return}X.forEach((Q,W)=>Y(J,`${B}[${W}]`,Q,$))}function F(J,B,X){if(X===void 0)return;if(!Array.isArray(X)){J.push({path:B,message:`expected an array of strings, got ${K(X)}`});return}X.forEach(($,Q)=>{if(typeof $!=="string"||!$.trim())J.push({path:`${B}[${Q}]`,message:`expected a non-empty string, got ${K($)}`})})}function G(J,B,X){if(X===void 0)return;if(typeof X!=="string"){J.push({path:B,message:`expected a URL string, got ${K(X)}`});return}try{let $=new URL(X);if($.protocol!=="http:"&&$.protocol!=="https:")J.push({path:B,message:`expected an http(s) URL, got ${K(X)}`})}catch{J.push({path:B,message:`expected a valid absolute URL, got ${K(X)}`})}}function x(J,B,X){if(X===void 0)return;if(typeof X!=="string"||!X.trim()){J.push({path:B,message:`expected a cron expression string, got ${K(X)}`});return}let $=X.trim().split(/\s+/);if($.length!==5&&$.length!==6)J.push({path:B,message:`expected 5 or 6 whitespace-separated fields, got ${$.length} (${K(X)})`})}function p(J){let B=[];if(J.verbose!==void 0&&typeof J.verbose!=="boolean")B.push({path:"verbose",message:`expected a boolean, got ${K(J.verbose)}`});return Y(B,"logLevel",J.logLevel,E),C(B,"maxPRsPerRun",J.maxPRsPerRun,{min:1,integer:!0}),h(B,J),v(B,J),n(B,J),l(B,J),t(B,J),r(B,J),o(B,J),a(B,J),i(B,J),c(B,J),y(B,J),B}function f(J,B){if(B===void 0)return;if(!Z(B)){J.push({path:"registries.docker",message:`expected an object keyed by registry host, got ${K(B)}`});return}for(let[X,$]of Object.entries(B)){let Q=`registries.docker.${X}`;if(!Z($)){J.push({path:Q,message:`expected an object, got ${K($)}`});continue}for(let W of["username","passwordEnv","tokenEnv"]){let H=$[W];if(H!==void 0&&(typeof H!=="string"||!H.trim()))J.push({path:`${Q}.${W}`,message:`expected a non-empty string, got ${K(H)}`})}if($.username&&!$.passwordEnv&&!$.tokenEnv)J.push({path:`${Q}.passwordEnv`,message:"is required when a username is given"});if($.passwordEnv&&!$.username)J.push({path:`${Q}.username`,message:"is required when passwordEnv is given"})}}function y(J,B){let X=B.analysis;if(X===void 0)return;if(!Z(X)){J.push({path:"analysis",message:`expected an object, got ${K(X)}`});return}if(X.enabled!==void 0&&typeof X.enabled!=="boolean")J.push({path:"analysis.enabled",message:`expected a boolean, got ${K(X.enabled)}`});if(X.tools===void 0)return;if(!Z(X.tools)){J.push({path:"analysis.tools",message:`expected an object mapping analyzer names to booleans, got ${K(X.tools)}`});return}for(let[$,Q]of Object.entries(X.tools))if(typeof Q!=="boolean")J.push({path:`analysis.tools.${$}`,message:`expected a boolean, got ${K(Q)}`});else if(!U.includes($))J.push({path:`analysis.tools.${$}`,message:`unknown analyzer; expected one of ${U.map(K).join(", ")}`})}function h(J,B){let X=B.repository;if(X===void 0)return;if(!Z(X)){J.push({path:"repository",message:`expected an object, got ${K(X)}`});return}if(X.provider!==void 0&&!L.includes(X.provider)){let $=_[String(X.provider)];J.push({path:"repository.provider",message:$?`${K(X.provider)} support is not implemented yet \u2014 follow ${$}`:`only ${L.map(K).join(", ")} is supported, got ${K(X.provider)}`})}for(let $ of["owner","name","baseBranch","token"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="string")J.push({path:`repository.${$}`,message:`expected a string, got ${K(Q)}`})}G(J,"repository.apiUrl",X.apiUrl),G(J,"repository.serverUrl",X.serverUrl)}function v(J,B){let X=B.packages;if(X===void 0)return;if(!Z(X)){J.push({path:"packages",message:`expected an object, got ${K(X)}`});return}Y(J,"packages.strategy",X.strategy,D),F(J,"packages.ignore",X.ignore),F(J,"packages.ignorePaths",X.ignorePaths),F(J,"packages.minimumReleaseAgeExclude",X.minimumReleaseAgeExclude),C(J,"packages.minimumReleaseAge",X.minimumReleaseAge,{min:0});for(let $ of["includePrerelease","excludeMajor","respectLatest","engines"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`packages.${$}`,message:`expected a boolean, got ${K(Q)}`})}if(X.pin!==void 0){if(!Z(X.pin))J.push({path:"packages.pin",message:`expected an object mapping package names to versions, got ${K(X.pin)}`});else for(let[$,Q]of Object.entries(X.pin))if(typeof Q!=="string"||!Q.trim())J.push({path:`packages.pin.${$}`,message:`expected a version string, got ${K(Q)}`})}if(X.groups!==void 0){if(!Array.isArray(X.groups)){J.push({path:"packages.groups",message:`expected an array of groups, got ${K(X.groups)}`});return}X.groups.forEach(($,Q)=>{let W=`packages.groups[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}if(typeof $.name!=="string"||!$.name.trim())J.push({path:`${W}.name`,message:`expected a non-empty string, got ${K($.name)}`});if(!Array.isArray($.patterns)||$.patterns.length===0)J.push({path:`${W}.patterns`,message:`expected a non-empty array of patterns, got ${K($.patterns)}`});else F(J,`${W}.patterns`,$.patterns);Y(J,`${W}.strategy`,$.strategy,D)})}g(J,X.rules)}var I=["matchPackages","matchEcosystems","matchDepTypes","matchUpdateTypes","matchFiles","matchCurrentVersion","schedule"],k=["enabled","strategy","groupName","labels","reviewers","assignees","autoMerge","autoMigrate","minimumReleaseAge","prPriority","scheduleTimezone"];function g(J,B){if(B===void 0)return;if(!Array.isArray(B)){J.push({path:"packages.rules",message:`expected an array of rules, got ${K(B)}`});return}let X=new Set([...I,...k]);B.forEach(($,Q)=>{let W=`packages.rules[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}for(let z of Object.keys($))if(!X.has(z))J.push({path:`${W}.${z}`,message:`unknown key; expected one of ${[...X].map(K).join(", ")}`});if(!I.some((z)=>$[z]!==void 0))J.push({path:W,message:'has no matchers, so it applies to every update \u2014 add `matchPackages: ["*"]` if that is intended'});if(F(J,`${W}.matchPackages`,$.matchPackages),F(J,`${W}.matchDepTypes`,$.matchDepTypes),F(J,`${W}.matchFiles`,$.matchFiles),F(J,`${W}.labels`,$.labels),F(J,`${W}.reviewers`,$.reviewers),F(J,`${W}.assignees`,$.assignees),j(J,`${W}.matchEcosystems`,$.matchEcosystems,w),j(J,`${W}.matchUpdateTypes`,$.matchUpdateTypes,b),Y(J,`${W}.strategy`,$.strategy,D),C(J,`${W}.minimumReleaseAge`,$.minimumReleaseAge,{min:0}),$.prPriority!==void 0&&typeof $.prPriority!=="number")J.push({path:`${W}.prPriority`,message:`expected a number, got ${K($.prPriority)}`});for(let z of["enabled","autoMerge","autoMigrate"])if($[z]!==void 0&&typeof $[z]!=="boolean")J.push({path:`${W}.${z}`,message:`expected a boolean, got ${K($[z])}`});for(let z of["groupName","matchCurrentVersion","scheduleTimezone"])if($[z]!==void 0&&(typeof $[z]!=="string"||!String($[z]).trim()))J.push({path:`${W}.${z}`,message:`expected a non-empty string, got ${K($[z])}`});x(J,`${W}.schedule`,$.schedule)})}function n(J,B){let X=B.pullRequest;if(X===void 0)return;if(!Z(X)){J.push({path:"pullRequest",message:`expected an object, got ${K(X)}`});return}F(J,"pullRequest.reviewers",X.reviewers),F(J,"pullRequest.assignees",X.assignees),F(J,"pullRequest.labels",X.labels);let $=X.autoMerge;if($!==void 0){if(!Z($)){J.push({path:"pullRequest.autoMerge",message:`expected an object, got ${K($)}`});return}if($.enabled!==void 0&&typeof $.enabled!=="boolean")J.push({path:"pullRequest.autoMerge.enabled",message:`expected a boolean, got ${K($.enabled)}`});if(Y(J,"pullRequest.autoMerge.strategy",$.strategy,m),F(J,"pullRequest.autoMerge.conditions",$.conditions),Array.isArray($.conditions))for(let[Q,W]of $.conditions.entries())Y(J,`pullRequest.autoMerge.conditions[${Q}]`,W,P);if($.requireGreenCI!==void 0&&typeof $.requireGreenCI!=="boolean")J.push({path:"pullRequest.autoMerge.requireGreenCI",message:`expected a boolean, got ${K($.requireGreenCI)}`});if($.optOutLabel!==void 0&&typeof $.optOutLabel!=="string")J.push({path:"pullRequest.autoMerge.optOutLabel",message:`expected a string, got ${K($.optOutLabel)}`})}}function c(J,B){let X=B.ai;if(X===void 0)return;if(!Z(X)){J.push({path:"ai",message:`expected an object, got ${K(X)}`});return}if(X.enabled!==void 0&&typeof X.enabled!=="boolean")J.push({path:"ai.enabled",message:`expected a boolean, got ${K(X.enabled)}`});Y(J,"ai.provider",X.provider,R),Y(J,"ai.effort",X.effort,A);for(let Q of["model","apiKeyEnv","baseUrl"])if(X[Q]!==void 0&&typeof X[Q]!=="string")J.push({path:`ai.${Q}`,message:`expected a string, got ${K(X[Q])}`});if(typeof X.apiKeyEnv==="string"&&/^sk-|^AIza/.test(X.apiKeyEnv))J.push({path:"ai.apiKeyEnv",message:"expected the NAME of an environment variable, not an API key"});let $=X.review;if($!==void 0)if(!Z($))J.push({path:"ai.review",message:`expected an object, got ${K($)}`});else{for(let Q of["enabled","drafts","autoReview","summaryOnly"])if($[Q]!==void 0&&typeof $[Q]!=="boolean")J.push({path:`ai.review.${Q}`,message:`expected a boolean, got ${K($[Q])}`});if(Y(J,"ai.review.profile",$.profile,S),Y(J,"ai.review.requestChangesOn",$.requestChangesOn,d),F(J,"ai.review.ignoreTitleKeywords",$.ignoreTitleKeywords),F(J,"ai.review.ignoreUsernames",$.ignoreUsernames),F(J,"ai.review.pathFilters",$.pathFilters),$.instructions!==void 0&&typeof $.instructions!=="string")J.push({path:"ai.review.instructions",message:`expected a string, got ${K($.instructions)}`});if($.guidelineFiles!==void 0&&$.guidelineFiles!==!1)F(J,"ai.review.guidelineFiles",$.guidelineFiles);if($.pathInstructions!==void 0)if(!Array.isArray($.pathInstructions))J.push({path:"ai.review.pathInstructions",message:`expected an array, got ${K($.pathInstructions)}`});else $.pathInstructions.forEach((Q,W)=>{let H=`ai.review.pathInstructions[${W}]`;if(!Z(Q)){J.push({path:H,message:`expected an object, got ${K(Q)}`});return}for(let z of["path","instructions"])if(typeof Q[z]!=="string"||!Q[z].trim())J.push({path:`${H}.${z}`,message:`expected a non-empty string, got ${K(Q[z])}`})})}if(X.maxTokensPerRun!==void 0){if(typeof X.maxTokensPerRun!=="number"||!Number.isFinite(X.maxTokensPerRun)||X.maxTokensPerRun<=0)J.push({path:"ai.maxTokensPerRun",message:`expected a positive number, got ${K(X.maxTokensPerRun)}`})}}function l(J,B){let X=B.registries;if(X===void 0)return;if(!Z(X)){J.push({path:"registries",message:`expected an object, got ${K(X)}`});return}if(f(J,X.docker),G(J,"registries.npm",X.npm),G(J,"registries.composer",X.composer),X.npmScopes!==void 0){if(!Z(X.npmScopes)){J.push({path:"registries.npmScopes",message:`expected an object keyed by scope, got ${K(X.npmScopes)}`});return}for(let[$,Q]of Object.entries(X.npmScopes)){if(!$.startsWith("@"))J.push({path:`registries.npmScopes.${$}`,message:`scope keys must start with "@", got ${K($)}`});G(J,`registries.npmScopes.${$}`,Q)}}}function t(J,B){let X=B.security;if(X===void 0)return;if(!Z(X)){J.push({path:"security",message:`expected an object, got ${K(X)}`});return}for(let $ of["enabled","prioritize"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`security.${$}`,message:`expected a boolean, got ${K(Q)}`})}if(X.label!==void 0&&(typeof X.label!=="string"||!X.label.trim()))J.push({path:"security.label",message:`expected a non-empty string, got ${K(X.label)}`});Y(J,"security.minimumSeverity",X.minimumSeverity,q)}function r(J,B){if(B.schedule!==void 0){if(!Z(B.schedule))J.push({path:"schedule",message:`expected an object, got ${K(B.schedule)}`});else if(x(J,"schedule.cron",B.schedule.cron),B.schedule.timezone!==void 0&&typeof B.schedule.timezone!=="string")J.push({path:"schedule.timezone",message:`expected a string, got ${K(B.schedule.timezone)}`})}let X=B.workflows?.custom;if(X===void 0)return;if(!Array.isArray(X)){J.push({path:"workflows.custom",message:`expected an array, got ${K(X)}`});return}X.forEach(($,Q)=>{let W=`workflows.custom[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}if(typeof $.name!=="string"||!$.name.trim())J.push({path:`${W}.name`,message:`expected a non-empty string, got ${K($.name)}`});x(J,`${W}.schedule`,$.schedule),Y(J,`${W}.strategy`,$.strategy,D),F(J,`${W}.reviewers`,$.reviewers),F(J,`${W}.assignees`,$.assignees),F(J,`${W}.labels`,$.labels)})}function o(J,B){let X=B.releaseNotes;if(X===void 0)return;if(!Z(X)){J.push({path:"releaseNotes",message:`expected an object, got ${K(X)}`});return}for(let $ of["enabled","sanitizeReferences","includeCompareLinks"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`releaseNotes.${$}`,message:`expected a boolean, got ${K(Q)}`})}C(J,"releaseNotes.maxReleases",X.maxReleases,{min:1,integer:!0}),C(J,"releaseNotes.maxBodyLength",X.maxBodyLength,{min:1,integer:!0})}function a(J,B){let X=B.dashboard;if(X===void 0)return;if(!Z(X)){J.push({path:"dashboard",message:`expected an object, got ${K(X)}`});return}if(F(J,"dashboard.labels",X.labels),F(J,"dashboard.assignees",X.assignees),C(J,"dashboard.issueNumber",X.issueNumber,{min:1,integer:!0}),X.title!==void 0&&(typeof X.title!=="string"||!X.title.trim()))J.push({path:"dashboard.title",message:`expected a non-empty string, got ${K(X.title)}`})}function i(J,B){let X=B.notifications;if(X===void 0)return;if(!Z(X)){J.push({path:"notifications",message:`expected an object, got ${K(X)}`});return}let $=(H,z)=>{if(z===void 0)return;if(!Array.isArray(z)){J.push({path:H,message:`expected an array of event names, got ${K(z)}`});return}z.forEach((V,O)=>{Y(J,`${H}[${O}]`,V,M)})},Q=(H,z)=>{if(z!==void 0&&(typeof z!=="string"||!z.trim()))J.push({path:H,message:`expected an environment variable name, got ${K(z)}`})};for(let H of["slack","discord"]){let z=X[H];if(z===void 0)continue;if(!Z(z)){J.push({path:`notifications.${H}`,message:`expected an object, got ${K(z)}`});continue}Q(`notifications.${H}.webhookEnv`,z.webhookEnv),$(`notifications.${H}.events`,z.events)}let W=X.webhooks;if(W===void 0)return;if(!Array.isArray(W)){J.push({path:"notifications.webhooks",message:`expected an array, got ${K(W)}`});return}W.forEach((H,z)=>{let V=`notifications.webhooks[${z}]`;if(!Z(H)){J.push({path:V,message:`expected an object, got ${K(H)}`});return}if(H.url===void 0)J.push({path:`${V}.url`,message:"a webhook needs a url"});else G(J,`${V}.url`,H.url);Q(`${V}.secretEnv`,H.secretEnv),$(`${V}.events`,H.events)})}function u(J){return J.map((B)=>` \u2022 ${B.path}: ${B.message}`).join(`
|
|
2
|
+
import{Bd as N}from"./chunk-pxv58dh1.js";import{Gd as M}from"./chunk-m6qym0ya.js";import{fe as T}from"./chunk-dgcct70c.js";import{ke as L,le as _}from"./chunk-5feeegzy.js";var D=["major","minor","patch","all"],m=["merge","squash","rebase"],P=["patch-only","minor-only","security-only","all"],R=["anthropic","openai","google","openrouter","openai-compatible"],A=["low","medium","high"],S=["chill","assertive"],d=["never","critical"],q=["low","moderate","high","critical"],E=["silent","error","warn","info","debug"],w=["npm","composer","github-actions","docker","pkgx","zig","python","rust","go","ruby"],b=["major","minor","patch"],U=T.map((J)=>J.name);function K(J){return JSON.stringify(J)}function Z(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}function Y(J,B,X,$){if(X===void 0)return;if(typeof X!=="string"||!$.includes(X))J.push({path:B,message:`expected one of ${$.map(K).join(", ")}, got ${K(X)}`})}function C(J,B,X,$={}){let Q=$.min??0,W=$.integer??!1;if(X===void 0)return;if(typeof X!=="number"||!Number.isFinite(X)||X<Q){J.push({path:B,message:`expected a number >= ${Q}, got ${K(X)}`});return}if(W&&!Number.isInteger(X))J.push({path:B,message:`expected a whole number, got ${K(X)}`})}function j(J,B,X,$){if(X===void 0)return;if(!Array.isArray(X)){J.push({path:B,message:`expected an array, got ${K(X)}`});return}X.forEach((Q,W)=>Y(J,`${B}[${W}]`,Q,$))}function F(J,B,X){if(X===void 0)return;if(!Array.isArray(X)){J.push({path:B,message:`expected an array of strings, got ${K(X)}`});return}X.forEach(($,Q)=>{if(typeof $!=="string"||!$.trim())J.push({path:`${B}[${Q}]`,message:`expected a non-empty string, got ${K($)}`})})}function G(J,B,X){if(X===void 0)return;if(typeof X!=="string"){J.push({path:B,message:`expected a URL string, got ${K(X)}`});return}try{let $=new URL(X);if($.protocol!=="http:"&&$.protocol!=="https:")J.push({path:B,message:`expected an http(s) URL, got ${K(X)}`})}catch{J.push({path:B,message:`expected a valid absolute URL, got ${K(X)}`})}}function x(J,B,X){if(X===void 0)return;if(typeof X!=="string"||!X.trim()){J.push({path:B,message:`expected a cron expression string, got ${K(X)}`});return}let $=X.trim().split(/\s+/);if($.length!==5&&$.length!==6)J.push({path:B,message:`expected 5 or 6 whitespace-separated fields, got ${$.length} (${K(X)})`})}function p(J){let B=[];if(J.verbose!==void 0&&typeof J.verbose!=="boolean")B.push({path:"verbose",message:`expected a boolean, got ${K(J.verbose)}`});return Y(B,"logLevel",J.logLevel,E),C(B,"maxPRsPerRun",J.maxPRsPerRun,{min:1,integer:!0}),h(B,J),v(B,J),n(B,J),l(B,J),t(B,J),r(B,J),o(B,J),a(B,J),i(B,J),c(B,J),y(B,J),B}function f(J,B){if(B===void 0)return;if(!Z(B)){J.push({path:"registries.docker",message:`expected an object keyed by registry host, got ${K(B)}`});return}for(let[X,$]of Object.entries(B)){let Q=`registries.docker.${X}`;if(!Z($)){J.push({path:Q,message:`expected an object, got ${K($)}`});continue}for(let W of["username","passwordEnv","tokenEnv"]){let H=$[W];if(H!==void 0&&(typeof H!=="string"||!H.trim()))J.push({path:`${Q}.${W}`,message:`expected a non-empty string, got ${K(H)}`})}if($.username&&!$.passwordEnv&&!$.tokenEnv)J.push({path:`${Q}.passwordEnv`,message:"is required when a username is given"});if($.passwordEnv&&!$.username)J.push({path:`${Q}.username`,message:"is required when passwordEnv is given"})}}function y(J,B){let X=B.analysis;if(X===void 0)return;if(!Z(X)){J.push({path:"analysis",message:`expected an object, got ${K(X)}`});return}if(X.enabled!==void 0&&typeof X.enabled!=="boolean")J.push({path:"analysis.enabled",message:`expected a boolean, got ${K(X.enabled)}`});if(X.tools===void 0)return;if(!Z(X.tools)){J.push({path:"analysis.tools",message:`expected an object mapping analyzer names to booleans, got ${K(X.tools)}`});return}for(let[$,Q]of Object.entries(X.tools))if(typeof Q!=="boolean")J.push({path:`analysis.tools.${$}`,message:`expected a boolean, got ${K(Q)}`});else if(!U.includes($))J.push({path:`analysis.tools.${$}`,message:`unknown analyzer; expected one of ${U.map(K).join(", ")}`})}function h(J,B){let X=B.repository;if(X===void 0)return;if(!Z(X)){J.push({path:"repository",message:`expected an object, got ${K(X)}`});return}if(X.provider!==void 0&&!L.includes(X.provider)){let $=_[String(X.provider)];J.push({path:"repository.provider",message:$?`${K(X.provider)} support is not implemented yet \u2014 follow ${$}`:`only ${L.map(K).join(", ")} is supported, got ${K(X.provider)}`})}for(let $ of["owner","name","baseBranch","token"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="string")J.push({path:`repository.${$}`,message:`expected a string, got ${K(Q)}`})}G(J,"repository.apiUrl",X.apiUrl),G(J,"repository.serverUrl",X.serverUrl)}function v(J,B){let X=B.packages;if(X===void 0)return;if(!Z(X)){J.push({path:"packages",message:`expected an object, got ${K(X)}`});return}Y(J,"packages.strategy",X.strategy,D),F(J,"packages.ignore",X.ignore),F(J,"packages.ignorePaths",X.ignorePaths),F(J,"packages.minimumReleaseAgeExclude",X.minimumReleaseAgeExclude),C(J,"packages.minimumReleaseAge",X.minimumReleaseAge,{min:0});for(let $ of["includePrerelease","excludeMajor","respectLatest","engines"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`packages.${$}`,message:`expected a boolean, got ${K(Q)}`})}if(X.pin!==void 0){if(!Z(X.pin))J.push({path:"packages.pin",message:`expected an object mapping package names to versions, got ${K(X.pin)}`});else for(let[$,Q]of Object.entries(X.pin))if(typeof Q!=="string"||!Q.trim())J.push({path:`packages.pin.${$}`,message:`expected a version string, got ${K(Q)}`})}if(X.groups!==void 0){if(!Array.isArray(X.groups)){J.push({path:"packages.groups",message:`expected an array of groups, got ${K(X.groups)}`});return}X.groups.forEach(($,Q)=>{let W=`packages.groups[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}if(typeof $.name!=="string"||!$.name.trim())J.push({path:`${W}.name`,message:`expected a non-empty string, got ${K($.name)}`});if(!Array.isArray($.patterns)||$.patterns.length===0)J.push({path:`${W}.patterns`,message:`expected a non-empty array of patterns, got ${K($.patterns)}`});else F(J,`${W}.patterns`,$.patterns);Y(J,`${W}.strategy`,$.strategy,D)})}g(J,X.rules)}var I=["matchPackages","matchEcosystems","matchDepTypes","matchUpdateTypes","matchFiles","matchCurrentVersion","schedule"],k=["enabled","strategy","groupName","labels","reviewers","assignees","autoMerge","autoMigrate","minimumReleaseAge","prPriority","scheduleTimezone"];function g(J,B){if(B===void 0)return;if(!Array.isArray(B)){J.push({path:"packages.rules",message:`expected an array of rules, got ${K(B)}`});return}let X=new Set([...I,...k]);B.forEach(($,Q)=>{let W=`packages.rules[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}for(let z of Object.keys($))if(!X.has(z))J.push({path:`${W}.${z}`,message:`unknown key; expected one of ${[...X].map(K).join(", ")}`});if(!I.some((z)=>$[z]!==void 0))J.push({path:W,message:'has no matchers, so it applies to every update \u2014 add `matchPackages: ["*"]` if that is intended'});if(F(J,`${W}.matchPackages`,$.matchPackages),F(J,`${W}.matchDepTypes`,$.matchDepTypes),F(J,`${W}.matchFiles`,$.matchFiles),F(J,`${W}.labels`,$.labels),F(J,`${W}.reviewers`,$.reviewers),F(J,`${W}.assignees`,$.assignees),j(J,`${W}.matchEcosystems`,$.matchEcosystems,w),j(J,`${W}.matchUpdateTypes`,$.matchUpdateTypes,b),Y(J,`${W}.strategy`,$.strategy,D),C(J,`${W}.minimumReleaseAge`,$.minimumReleaseAge,{min:0}),$.prPriority!==void 0&&typeof $.prPriority!=="number")J.push({path:`${W}.prPriority`,message:`expected a number, got ${K($.prPriority)}`});for(let z of["enabled","autoMerge","autoMigrate"])if($[z]!==void 0&&typeof $[z]!=="boolean")J.push({path:`${W}.${z}`,message:`expected a boolean, got ${K($[z])}`});for(let z of["groupName","matchCurrentVersion","scheduleTimezone"])if($[z]!==void 0&&(typeof $[z]!=="string"||!String($[z]).trim()))J.push({path:`${W}.${z}`,message:`expected a non-empty string, got ${K($[z])}`});x(J,`${W}.schedule`,$.schedule)})}function n(J,B){let X=B.pullRequest;if(X===void 0)return;if(!Z(X)){J.push({path:"pullRequest",message:`expected an object, got ${K(X)}`});return}F(J,"pullRequest.reviewers",X.reviewers),F(J,"pullRequest.assignees",X.assignees),F(J,"pullRequest.labels",X.labels);let $=X.autoMerge;if($!==void 0){if(!Z($)){J.push({path:"pullRequest.autoMerge",message:`expected an object, got ${K($)}`});return}if($.enabled!==void 0&&typeof $.enabled!=="boolean")J.push({path:"pullRequest.autoMerge.enabled",message:`expected a boolean, got ${K($.enabled)}`});if(Y(J,"pullRequest.autoMerge.strategy",$.strategy,m),F(J,"pullRequest.autoMerge.conditions",$.conditions),Array.isArray($.conditions))for(let[Q,W]of $.conditions.entries())Y(J,`pullRequest.autoMerge.conditions[${Q}]`,W,P);if($.requireGreenCI!==void 0&&typeof $.requireGreenCI!=="boolean")J.push({path:"pullRequest.autoMerge.requireGreenCI",message:`expected a boolean, got ${K($.requireGreenCI)}`});if($.optOutLabel!==void 0&&typeof $.optOutLabel!=="string")J.push({path:"pullRequest.autoMerge.optOutLabel",message:`expected a string, got ${K($.optOutLabel)}`})}}function c(J,B){let X=B.ai;if(X===void 0)return;if(!Z(X)){J.push({path:"ai",message:`expected an object, got ${K(X)}`});return}if(X.enabled!==void 0&&typeof X.enabled!=="boolean")J.push({path:"ai.enabled",message:`expected a boolean, got ${K(X.enabled)}`});Y(J,"ai.provider",X.provider,R),Y(J,"ai.effort",X.effort,A);for(let Q of["model","apiKeyEnv","baseUrl"])if(X[Q]!==void 0&&typeof X[Q]!=="string")J.push({path:`ai.${Q}`,message:`expected a string, got ${K(X[Q])}`});if(typeof X.apiKeyEnv==="string"&&/^sk-|^AIza/.test(X.apiKeyEnv))J.push({path:"ai.apiKeyEnv",message:"expected the NAME of an environment variable, not an API key"});let $=X.review;if($!==void 0)if(!Z($))J.push({path:"ai.review",message:`expected an object, got ${K($)}`});else{for(let Q of["enabled","drafts","autoReview","summaryOnly"])if($[Q]!==void 0&&typeof $[Q]!=="boolean")J.push({path:`ai.review.${Q}`,message:`expected a boolean, got ${K($[Q])}`});if(Y(J,"ai.review.profile",$.profile,S),Y(J,"ai.review.requestChangesOn",$.requestChangesOn,d),F(J,"ai.review.ignoreTitleKeywords",$.ignoreTitleKeywords),F(J,"ai.review.ignoreUsernames",$.ignoreUsernames),F(J,"ai.review.pathFilters",$.pathFilters),$.instructions!==void 0&&typeof $.instructions!=="string")J.push({path:"ai.review.instructions",message:`expected a string, got ${K($.instructions)}`});if($.guidelineFiles!==void 0&&$.guidelineFiles!==!1)F(J,"ai.review.guidelineFiles",$.guidelineFiles);if($.pathInstructions!==void 0)if(!Array.isArray($.pathInstructions))J.push({path:"ai.review.pathInstructions",message:`expected an array, got ${K($.pathInstructions)}`});else $.pathInstructions.forEach((Q,W)=>{let H=`ai.review.pathInstructions[${W}]`;if(!Z(Q)){J.push({path:H,message:`expected an object, got ${K(Q)}`});return}for(let z of["path","instructions"])if(typeof Q[z]!=="string"||!Q[z].trim())J.push({path:`${H}.${z}`,message:`expected a non-empty string, got ${K(Q[z])}`})})}if(X.maxTokensPerRun!==void 0){if(typeof X.maxTokensPerRun!=="number"||!Number.isFinite(X.maxTokensPerRun)||X.maxTokensPerRun<=0)J.push({path:"ai.maxTokensPerRun",message:`expected a positive number, got ${K(X.maxTokensPerRun)}`})}}function l(J,B){let X=B.registries;if(X===void 0)return;if(!Z(X)){J.push({path:"registries",message:`expected an object, got ${K(X)}`});return}if(f(J,X.docker),G(J,"registries.npm",X.npm),G(J,"registries.composer",X.composer),X.npmScopes!==void 0){if(!Z(X.npmScopes)){J.push({path:"registries.npmScopes",message:`expected an object keyed by scope, got ${K(X.npmScopes)}`});return}for(let[$,Q]of Object.entries(X.npmScopes)){if(!$.startsWith("@"))J.push({path:`registries.npmScopes.${$}`,message:`scope keys must start with "@", got ${K($)}`});G(J,`registries.npmScopes.${$}`,Q)}}}function t(J,B){let X=B.security;if(X===void 0)return;if(!Z(X)){J.push({path:"security",message:`expected an object, got ${K(X)}`});return}for(let $ of["enabled","prioritize"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`security.${$}`,message:`expected a boolean, got ${K(Q)}`})}if(X.label!==void 0&&(typeof X.label!=="string"||!X.label.trim()))J.push({path:"security.label",message:`expected a non-empty string, got ${K(X.label)}`});Y(J,"security.minimumSeverity",X.minimumSeverity,q)}function r(J,B){if(B.schedule!==void 0){if(!Z(B.schedule))J.push({path:"schedule",message:`expected an object, got ${K(B.schedule)}`});else if(x(J,"schedule.cron",B.schedule.cron),B.schedule.timezone!==void 0&&typeof B.schedule.timezone!=="string")J.push({path:"schedule.timezone",message:`expected a string, got ${K(B.schedule.timezone)}`})}let X=B.workflows?.custom;if(X===void 0)return;if(!Array.isArray(X)){J.push({path:"workflows.custom",message:`expected an array, got ${K(X)}`});return}X.forEach(($,Q)=>{let W=`workflows.custom[${Q}]`;if(!Z($)){J.push({path:W,message:`expected an object, got ${K($)}`});return}if(typeof $.name!=="string"||!$.name.trim())J.push({path:`${W}.name`,message:`expected a non-empty string, got ${K($.name)}`});x(J,`${W}.schedule`,$.schedule),Y(J,`${W}.strategy`,$.strategy,D),F(J,`${W}.reviewers`,$.reviewers),F(J,`${W}.assignees`,$.assignees),F(J,`${W}.labels`,$.labels)})}function o(J,B){let X=B.releaseNotes;if(X===void 0)return;if(!Z(X)){J.push({path:"releaseNotes",message:`expected an object, got ${K(X)}`});return}for(let $ of["enabled","sanitizeReferences","includeCompareLinks"]){let Q=X[$];if(Q!==void 0&&typeof Q!=="boolean")J.push({path:`releaseNotes.${$}`,message:`expected a boolean, got ${K(Q)}`})}C(J,"releaseNotes.maxReleases",X.maxReleases,{min:1,integer:!0}),C(J,"releaseNotes.maxBodyLength",X.maxBodyLength,{min:1,integer:!0})}function a(J,B){let X=B.dashboard;if(X===void 0)return;if(!Z(X)){J.push({path:"dashboard",message:`expected an object, got ${K(X)}`});return}if(F(J,"dashboard.labels",X.labels),F(J,"dashboard.assignees",X.assignees),C(J,"dashboard.issueNumber",X.issueNumber,{min:1,integer:!0}),X.title!==void 0&&(typeof X.title!=="string"||!X.title.trim()))J.push({path:"dashboard.title",message:`expected a non-empty string, got ${K(X.title)}`})}function i(J,B){let X=B.notifications;if(X===void 0)return;if(!Z(X)){J.push({path:"notifications",message:`expected an object, got ${K(X)}`});return}let $=(H,z)=>{if(z===void 0)return;if(!Array.isArray(z)){J.push({path:H,message:`expected an array of event names, got ${K(z)}`});return}z.forEach((V,O)=>{Y(J,`${H}[${O}]`,V,M)})},Q=(H,z)=>{if(z!==void 0&&(typeof z!=="string"||!z.trim()))J.push({path:H,message:`expected an environment variable name, got ${K(z)}`})};for(let H of["slack","discord"]){let z=X[H];if(z===void 0)continue;if(!Z(z)){J.push({path:`notifications.${H}`,message:`expected an object, got ${K(z)}`});continue}Q(`notifications.${H}.webhookEnv`,z.webhookEnv),$(`notifications.${H}.events`,z.events)}let W=X.webhooks;if(W===void 0)return;if(!Array.isArray(W)){J.push({path:"notifications.webhooks",message:`expected an array, got ${K(W)}`});return}W.forEach((H,z)=>{let V=`notifications.webhooks[${z}]`;if(!Z(H)){J.push({path:V,message:`expected an object, got ${K(H)}`});return}if(H.url===void 0)J.push({path:`${V}.url`,message:"a webhook needs a url"});else G(J,`${V}.url`,H.url);Q(`${V}.secretEnv`,H.secretEnv),$(`${V}.events`,H.events)})}function u(J){return J.map((B)=>` \u2022 ${B.path}: ${B.message}`).join(`
|
|
3
3
|
`)}function $J(J){let B=p(J);if(B.length===0)return;throw new N(`Invalid buddy configuration (${B.length} issue${B.length===1?"":"s"}):
|
|
4
4
|
${u(B)}`,B[0].path)}
|
|
5
|
-
export{p as
|
|
5
|
+
export{p as Zc,u as _c,$J as $c};
|
|
@@ -4,4 +4,4 @@ var F=1,G=30000,V=/<!--\s*buddy:manifest\s+v(\d+)\s*([\s\S]*?)-->/;function W(B)
|
|
|
4
4
|
<!-- buddy:manifest v1
|
|
5
5
|
${JSON.stringify(B)}
|
|
6
6
|
-->`}function I(B,C={}){return Y(B.updates,{group:B.name,...C})}function Z(B){if(!B)return null;let C=B.match(V);if(!C)return null;try{let D=JSON.parse(C[2].trim());if(!z(D))return null;return{...D,schemaVersion:Number(D.schemaVersion)||Number(C[1])||1,updates:D.updates.filter(A)}}catch{return null}}function P(B){return Z(B)!==null}function q(B){return B.replace(V,"").trimEnd()}function U(B,C,D={}){return q(B)+Y(C,D)}function X(B){return B.updates.map((C)=>({name:C.name,currentVersion:C.current,newVersion:C.target}))}function _(B){return[...new Set(B.updates.map((C)=>C.file).filter(Boolean))]}function z(B){if(typeof B!=="object"||B===null)return!1;return Array.isArray(B.updates)}function A(B){if(typeof B!=="object"||B===null)return!1;let C=B;return typeof C.name==="string"&&typeof C.current==="string"&&typeof C.target==="string"}function S(B,C,D){let L=Z(C)?.group;if(L){let K=B.find((J)=>J.name===L);if(K)return K}let H=new Set(D);return B.find((K)=>{let J=new Set(K.updates.map((O)=>O.name));return J.size===H.size&&[...H].every((O)=>J.has(O))})}
|
|
7
|
-
export{F as
|
|
7
|
+
export{F as qg,G as rg,Y as sg,I as tg,Z as ug,P as vg,q as wg,U as xg,X as yg,_ as zg,S as Ag};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{wd as a}from"./chunk-a5hevn6e.js";import"./chunk-0pf9vk80.js";import"./chunk-pxv58dh1.js";import"./chunk-eq5xb8k1.js";import"./chunk-cp3g2srn.js";import"./chunk-xyry3bma.js";import"./chunk-5q5tm30a.js";import"./chunk-fcax5a60.js";import"./chunk-q3dg57xx.js";import"./chunk-r0jmwzr3.js";import"./chunk-sg7bhtb7.js";import"./chunk-rrm4x81p.js";import"./chunk-dkgz8hsd.js";import"./chunk-dh8yykbg.js";export{a as PackageScanner};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Eb as _,Fb as y}from"./chunk-q2tjkhez.js";import{
|
|
2
|
+
import{Eb as _,Fb as y}from"./chunk-q2tjkhez.js";import{Ib as g,Jb as r,Kb as e,Lb as jj}from"./chunk-wm6g7y1r.js";import{Wb as n,Xb as o,Yb as t}from"./chunk-g763t4rr.js";import{fc as s}from"./chunk-dev3g0n3.js";import{ge as i}from"./chunk-dgcct70c.js";import{te as S}from"./chunk-5feeegzy.js";import{Tf as b,Uf as m}from"./chunk-rwzt9xvk.js";import{Wh as Y}from"./chunk-rrm4x81p.js";var C=["critical","major","minor","nit"],w={type:"object",properties:{summary:{type:"string",description:"One paragraph on what this change does"},effort:{type:"integer",description:"Reviewer effort, 1 (trivial) to 5 (demanding)"},walkthrough:{type:"array",items:{type:"object",properties:{path:{type:"string"},description:{type:"string"}},required:["path","description"],additionalProperties:!1}},findings:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"Repository-relative path"},line:{type:"integer",description:"Line number on the new side of the diff"},severity:{type:"string",enum:C},category:{type:"string",description:"Short slug, e.g. correctness or security"},message:{type:"string",description:"What is wrong and why it matters"},suggestion:{type:"string",description:"Replacement code, only when the fix is mechanical"}},required:["path","line","severity","category","message"],additionalProperties:!1}}},required:["summary","effort","walkthrough","findings"],additionalProperties:!1};function I(J){let j=J.message.toLowerCase().replace(/\s+/g," ").trim().slice(0,120);return`${J.path}:${J.category}:${j}`}function N(J,j){let Q=[],Z=[];for(let $ of J)if(j.get($.path)?.has($.line))Q.push($);else Z.push($);return Q.sort(($,X)=>C.indexOf($.severity)-C.indexOf(X.severity)),{valid:Q,dropped:Z}}function v(J,j){let Q=[],Z=new Set;for(let $ of J){let X=I($);if(j.has(X)||Z.has(X))continue;Z.add(X),Q.push($)}return Q}var Jj=[/(?:^|\/)(?:bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.lock|pantry\.lock)$/,/(?:^|\/)(?:dist|build|out|coverage|node_modules|vendor)\//,/\.min\.(?:js|css)$/,/(?:^|\/)(?:.*\.snap)$/],Qj=`You are reviewing a pull request diff.
|
|
3
3
|
|
|
4
4
|
Report only defects you can point at in the diff. A review that invents
|
|
5
5
|
findings to look thorough is worse than one that reports nothing, so say
|
|
@@ -4,4 +4,4 @@ ${JSON.stringify(x)}
|
|
|
4
4
|
-->`}function I(j){if(!j)return null;let x=j.match(B);if(!x)return null;try{let k=JSON.parse(x[2].trim());if(typeof k.reviewedSha!=="string")return null;return{schemaVersion:Number(k.schemaVersion)||1,reviewedSha:k.reviewedSha,fingerprints:Array.isArray(k.fingerprints)?k.fingerprints.filter((D)=>typeof D==="string"):[],reviewedAt:typeof k.reviewedAt==="string"?k.reviewedAt:new Date(0).toISOString(),...k.paused?{paused:!0}:{}}}catch{return null}}function J(j,x){return`${(j??"").replace(B,"").trimEnd()}
|
|
5
5
|
|
|
6
6
|
${F(x)}`}function L(j,x){if(j?.paused)return!1;return j?.reviewedSha!==x}
|
|
7
|
-
export{H as
|
|
7
|
+
export{H as Hb,F as Ib,I as Jb,J as Kb,L as Lb};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Xa as a}from"./chunk-f3fmewqb.js";import"./chunk-z906zp4k.js";import"./chunk-t7grk0az.js";import"./chunk-s6w47z4a.js";import"./chunk-a5hevn6e.js";import"./chunk-0pf9vk80.js";import"./chunk-pxv58dh1.js";import"./chunk-065sjjzg.js";import"./chunk-m6qym0ya.js";import"./chunk-5feeegzy.js";import"./chunk-eq5xb8k1.js";import"./chunk-cp3g2srn.js";import"./chunk-xyry3bma.js";import"./chunk-xmk24pz9.js";import"./chunk-5q5tm30a.js";import"./chunk-yx9v94q5.js";import"./chunk-jy1kbr1k.js";import"./chunk-5nn5mms4.js";import"./chunk-y6292gbf.js";import"./chunk-rwzt9xvk.js";import"./chunk-xntpzagn.js";import"./chunk-20sxtyt7.js";import"./chunk-2g8r8khw.js";import"./chunk-h9deve0y.js";import"./chunk-vxt1h0c4.js";import"./chunk-fcax5a60.js";import"./chunk-q3dg57xx.js";import"./chunk-r0jmwzr3.js";import"./chunk-8y4szfd2.js";import"./chunk-sg7bhtb7.js";import"./chunk-rrm4x81p.js";import"./chunk-dkgz8hsd.js";import"./chunk-dh8yykbg.js";export{a as Scheduler};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{A as V0,B as z0,C as EQ,a as N,b as X,c as R,r as dQ,s as $0,t as HQ,x as F,y as U,z as AQ}from"./chunk-
|
|
2
|
+
import{A as V0,B as z0,C as EQ,a as N,b as X,c as R,r as dQ,s as $0,t as HQ,x as F,y as U,z as AQ}from"./chunk-33ymc651.js";import"./chunk-dh8yykbg.js";import*as O from"fs/promises";import*as XQ from"fs";import*as T from"path";import*as FQ from"child_process";import*as M0 from"crypto";import*as A0 from"readline";function S(V){if(V.inputSchema.type!=="object")throw Error(`JSON schema for tool "${V.name}" must be an object, but got ${V.inputSchema.type}`);return{type:"custom",name:V.name,input_schema:V.inputSchema,description:V.description,run:V.run,parse:(Q)=>Q,...V.close?{close:V.close}:{}}}import*as b from"fs/promises";import*as C from"path";import{randomUUID as L0}from"crypto";var e=493,T0=420;function YQ(V,Q){let $=C.relative(V,Q);return $===""||!$.startsWith(".."+C.sep)&&$!==".."&&!C.isAbsolute($)}async function OQ(V,Q){for(let $ of V)if(YQ(await r(C.resolve($)),Q))return $;return}var y0=40;function QQ(V){let Q=V?.code;return typeof Q==="string"?Q:void 0}async function r(V){let Q=[],$=V,z=0;for(;;){let K;try{K=await b.realpath($)}catch(Z){let q;try{q=(await b.lstat($)).isSymbolicLink()}catch(Y){let W=QQ(Y);if(W!=="ENOENT"&&W!=="ENOTDIR")throw Y;let J=C.dirname($);if(J===$)throw Y;Q.push(C.basename($)),$=J;continue}if(!q)throw Z;if(++z>y0)throw Object.assign(Error("too many levels of symbolic links"),{code:"ELOOP"});$=C.resolve(C.dirname($),await b.readlink($));continue}return Q.length?C.join(K,...Q.reverse()):K}}async function fQ(V,Q,$){let z=$?.allowedRoots??[],K=await r(C.resolve(V)),Z;try{Z=await r(C.resolve(K,Q))}catch(Y){throw new U(n(Y,`path ${JSON.stringify(Q)}`))}if(YQ(K,Z)||await OQ(z,Z)!==void 0)return Z;let q=z.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new U(`path ${JSON.stringify(Q)} is outside ${q}`)}async function RQ(V,Q){let $=C.dirname(V),z=C.join($,`.tmp-${process.pid}-${L0()}`),K;try{K=await b.open(z,"wx",T0),await K.writeFile(Q,"utf-8"),await K.sync(),await K.close(),K=void 0,await b.rename(z,V)}catch(Z){if(K)await K.close().catch(()=>{});throw await b.unlink(z).catch(()=>{}),Z}}function n(V,Q){let $=QQ(V);switch($){case"ENOENT":return`${Q}: no such file or directory`;case"EACCES":case"EPERM":return`${Q}: permission denied`;case"ENOTDIR":return`${Q}: not a directory`;case"EISDIR":return`${Q}: is a directory`;case"ELOOP":return`${Q}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${Q}: file name too long`;case"ENOSPC":return`${Q}: no space left on device`;case"EMFILE":case"ENFILE":return`${Q}: too many open files`;default:return`${Q}: ${$!==void 0?`i/o error (${$})`:"i/o error"}`}}import*as G from"fs/promises";import*as uQ from"fs";import*as w from"path";import{execFile as b0}from"child_process";import{promisify as x0}from"util";import{Readable as v0}from"stream";import{pipeline as P0}from"stream/promises";var E0=x0(b0);async function F0(V){let{client:Q,sessionId:$}=V;if(!Q)return async()=>{};let z=HQ(Q),K=V.session;if(!K){if($===void 0)return async()=>{};z.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),K=await Q.beta.sessions.retrieve($)}let Z=w.resolve(V.workdir,"skills"),q=[];for(let Y of K.agent.skills)try{let W=await Q.beta.skills.versions.retrieve(Y.version,{skill_id:Y.skill_id}),J=w.basename(W.name.trim());if(J===""||J==="."||J==="..")J=Y.skill_id;let H=w.resolve(Z,J);if(H!==Z&&!H.startsWith(Z+w.sep)){z.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:W.name});continue}let M=await Q.beta.skills.versions.download(W.id,{skill_id:Y.skill_id});await G.rm(H,{recursive:!0,force:!0}),await G.mkdir(H,{recursive:!0,mode:e}),q.push(H),await mQ(M,H),z.info("downloaded skill",{component:"agent-tool-context",skill_id:Y.skill_id,version:W.id,dest:H})}catch(W){z.warn("failed to download skill",{component:"agent-tool-context",skill_id:Y.skill_id,error:String(W)})}return async()=>{for(let Y of q)await G.rm(Y,{recursive:!0,force:!0}).catch((W)=>{z.warn("failed to clean up skill",{component:"agent-tool-context",dest:Y,error:String(W)})})}}function f0(V){for(let Q of V){let $=Q.trim();if(!$)continue;if(w.isAbsolute($)||$.split(/[\\/]/).includes(".."))throw new R(`refusing to extract unsafe archive member: ${$}`)}}var LQ="skill archive listing is inconsistent; refusing to extract",g0={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function gQ(V){let Q=V.split(`
|
|
3
3
|
`);if(Q[Q.length-1]==="")Q.pop();return Q}function u0(V,Q){return/^[\x20-\x7E]+$/.test(Q)&&!/[\\^#]/.test(Q)&&!(V==="unzip"&&Q.startsWith("-"))}function S0(V,Q,$){let z=gQ(Q),K=gQ($);if(z.length!==K.length)throw new R(LQ);let Z=[],q=[];return z.forEach((Y,W)=>{if(g0[V].has(K[W].charAt(0))){Z.push(Y);return}if(!u0(V,Y))throw new R(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(Y)}`);q.push(Y)}),{plain:Z,special:q}}async function SQ(V){for(let Q of await G.readdir(V,{withFileTypes:!0}))if(Q.isDirectory())await SQ(w.join(V,Q.name));else if(!Q.isFile())throw new R(LQ)}async function jQ(V,Q){try{let{stdout:$}=await E0(V,Q);return $}catch($){if(QQ($)==="ENOENT")throw new R(`skill extraction requires the \`${V}\` command, but it was not found on PATH`);throw $}}function m0(V){let Q,$=!1;for(let z of V){let K=z.trim().split("/").filter((q)=>q!==""&&q!==".");if(K.length===0)continue;let Z=K[0];if(Q===void 0)Q=Z;else if(Z!==Q)return"";if(K.length>1)$=!0}return Q!==void 0&&$?Q:""}async function mQ(V,Q){let $=w.join(Q,`.skill-archive-${process.pid}-${Date.now()}`);if(!V.body)throw new R("skill download response had no body");await P0(v0.fromWeb(V.body),uQ.createWriteStream($));let z=w.join(w.dirname(Q),`.skill-stage-${process.pid}-${Date.now()}`),K=w.join(w.dirname(Q),`.skill-exclude-${process.pid}-${Date.now()}`);try{let Z=await _0($,4),q=Z.length>=4&&Z[0]===80&&Z[1]===75&&Z[2]===3&&Z[3]===4,Y=q?"unzip":"tar",W=await jQ(Y,q?["-Z1",$]:["-tf",$]),J=await jQ(Y,q?["-Z","--h","--t",$]:["-tvf",$]),{plain:H,special:M}=S0(Y,W,J);f0([...H,...M]);let j=m0(H);if(await G.mkdir(z,{recursive:!0,mode:e}),H.length>0)await jQ(Y,await p0(Y,$,z,M,K));await SQ(z);let v=j?w.join(z,j):z,P=await G.readdir(v).catch((E)=>{throw QQ(E)==="ENOENT"?new R(LQ):E});for(let E of P)await G.rename(w.join(v,E),w.join(Q,E))}finally{await G.rm($,{force:!0}),await G.rm(K,{force:!0}),await G.rm(z,{recursive:!0,force:!0})}}async function p0(V,Q,$,z,K){let Z=z.map((q)=>q.replace(/[*?[\\]/g,"\\$&"));if(V==="unzip")return["-oq",Q,"-d",$,...Z.length>0?["-x",...Z]:[]];if(Z.length===0)return["-xf",Q,"-C",$];return await G.writeFile(K,Z.join(`
|
|
4
4
|
`)+`
|
|
5
5
|
`,{flag:"wx",mode:384}),["-xf",Q,"-C",$,"-X",K]}async function _0(V,Q){let $=await G.open(V,"r");try{let z=Buffer.alloc(Q),{bytesRead:K}=await $.read(z,0,Q,0);return z.subarray(0,K)}finally{await $.close()}}import*as q0 from"path";import{createHash as V1}from"crypto";import*as A from"fs/promises";import*as k from"path";import{constants as i}from"fs";import{createHash as h0,randomBytes as d0}from"crypto";var cQ=448,c0=384,n0=448,TQ=i.O_NOFOLLOW??0,i0=i.O_NONBLOCK??0;class D extends Error{constructor(V,Q){super(`path ${JSON.stringify(Q)} ${V}`);this.name="FileStoreError",this.reason=V,this.relPath=Q}}D.ESCAPES_ROOT="escapes the store root";D.IS_A_SYMLINK="is a symlink";D.NOT_A_FILE="is not a regular file";D.NOT_A_DIRECTORY="is not a directory";D.NOT_UTF8="is not valid utf-8";D.MOVE_DESTINATION_EXISTS="already exists";function yQ(V){return V.startsWith("/")&&!V.split("/").includes("..")}class l{constructor(V,Q,$=!1){this.hashes=new Map,this.rootPath=V,this.removedOnDispose=Q,this.decoder=$?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(V,Q){if(!l0())throw Error("FileStore requires O_NOFOLLOW support on this platform");let $=!1;try{await A.lstat(V)}catch(z){if(z.code!=="ENOENT")throw z;$=!0}return new l(k.resolve(V),$,Q?.utf8??!1)}async createRoot(){await a0(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){if(!this.removedOnDispose)return;await A.rm(this.rootPath,{recursive:!0,force:!0})}async put(V,Q,$){let z=V.replace(/\\/g,"/");if(z.endsWith("/")||z.endsWith("/.")||z===""||z===".")throw new D(D.NOT_A_FILE,V);let K=this.resolveUnderRoot(V),Z=typeof Q==="string"?dQ(Q):Q;this.requireUtf8(V,Z),await pQ(this.rootPath,k.dirname(K)),await o0(K,Z,$?.executable??!1)}async get(V){let Q=this.resolveUnderRoot(V),$;try{$=await nQ(V,Q)}catch(K){if(K.code==="ENOENT")return null;throw K}let z;try{let K=await $.readFile();z=new Uint8Array(K.buffer,K.byteOffset,K.byteLength)}finally{await $.close()}return this.requireUtf8(V,z),z}async ls(V="/"){let Q=this.resolveUnderRoot(V);return new Set((await _Q(this.rootPath,V,Q)).map(([$])=>$))}async findSymlinks(V="/"){let Q=this.resolveUnderRoot(V);return t0(this.rootPath,V,Q)}async hashtree(V="/"){let Q=this.resolveUnderRoot(V),$=JQ.nowNs(),z=Object.create(null);for(let[K,Z]of await _Q(this.rootPath,V,Q)){let q=await this.hashViaCache(K,Z,$);if(q!==null)z[K]=q}return z}async hashFile(V){let Q=this.resolveUnderRoot(V),$;try{$=await A.lstat(Q,{bigint:!0})}catch(K){if(K.code==="ENOENT")return null;throw K}if($.isSymbolicLink())throw new D(D.IS_A_SYMLINK,V);if(!$.isFile())throw new D(D.NOT_A_FILE,V);let z=k.relative(this.rootPath,Q).split(k.sep).join("/");return this.hashViaCache(z,Q,JQ.nowNs())}async move(V,Q){let $=this.resolveUnderRoot(V),z=this.resolveUnderRoot(Q);if($===this.rootPath||z===this.rootPath)return;if(await A.stat(z).then(()=>!0,()=>!1))throw new D(D.MOVE_DESTINATION_EXISTS,Q);await pQ(this.rootPath,k.dirname(z)),await A.rename($,z)}async remove(V){let Q=this.resolveUnderRoot(V);if(Q===this.rootPath)return;let $;try{$=await A.lstat(Q,{bigint:!0})}catch(z){if(z.code==="ENOENT")return;throw z}if($.isDirectory())await A.rm(Q,{recursive:!0,force:!0});else try{await A.unlink(Q)}catch(z){if(z.code!=="ENOENT")throw z}}resolveUnderRoot(V){let Q=V.replace(/\\/g,"/").replace(/^\/+/,""),$=Q.split("/").filter((z)=>z!==""&&z!==".");if(k.posix.isAbsolute(Q)||$.includes(".."))throw new D(D.ESCAPES_ROOT,V);return $.length===0?this.rootPath:k.join(this.rootPath,...$)}requireUtf8(V,Q){if(!this.decoder)return;try{this.decoder.decode(Q)}catch{throw new D(D.NOT_UTF8,V)}}async hashViaCache(V,Q,$){let z;try{z=await A.lstat(Q,{bigint:!0})}catch(q){if(q.code==="ENOENT")return null;throw q}if(!z.isFile())return null;let K=this.hashes.get(V),Z;if(K!==void 0&&e0(K,z))Z=K.sha;else try{Z=await JQ.hashFile(Q)}catch(q){let Y=q.code;if(Y==="ENOENT"||q instanceof D)return null;if(Y==="ELOOP"||Y==="EMLINK")return null;throw q}if(Q1(z,$))this.hashes.set(V,{mtimeNs:z.mtimeNs,ctimeNs:z.ctimeNs,size:z.size,sha:Z});return Z}}l.isPathLegal=yQ;function l0(){return TQ!==0}async function a0(V){let Q=[],$=V;for(;;){try{await A.stat($);break}catch(K){let Z=K.code;if(Z!=="ENOENT"&&Z!=="ENOTDIR"&&Z!=="ELOOP")throw K}Q.push($);let z=k.dirname($);if(z===$)break;$=z}for(let z of Q.reverse())try{await A.mkdir(z,{mode:cQ})}catch(K){if(K.code!=="EEXIST")throw K}}async function pQ(V,Q){let $=k.relative(V,Q);if($==="")return;let z=V;for(let K of $.split(k.sep)){z=k.join(z,K);try{await A.mkdir(z,{mode:cQ})}catch(Z){if(Z.code!=="EEXIST")throw Z}}}async function o0(V,Q,$){let z=$?n0:c0,K=k.join(k.dirname(V),`.fs-${d0(8).toString("hex")}.tmp`),Z;try{Z=await A.open(K,i.O_WRONLY|i.O_CREAT|i.O_EXCL|TQ,z),await Z.writeFile(Q),await Z.close(),Z=void 0,await A.rename(K,V)}catch(q){if(Z)await Z.close().catch(()=>{});throw await A.unlink(K).catch(()=>{}),q}}async function nQ(V,Q){let $;try{$=await A.open(Q,i.O_RDONLY|TQ|i0)}catch(z){let K=z.code;if(K==="ELOOP"||K==="EMLINK")throw new D(D.IS_A_SYMLINK,V);throw z}try{if(!(await $.stat()).isFile())throw new D(D.NOT_A_FILE,V)}catch(z){throw await $.close().catch(()=>{}),z}return $}async function s0(V){let Q=h0("sha256"),$=await nQ(k.basename(V),V),z=new Uint8Array(1048576);try{for(;;){let{bytesRead:K}=await $.read(z,0,z.length);if(K===0)break;Q.update(z.subarray(0,K))}}finally{await $.close()}return Q.digest("hex")}async function _Q(V,Q,$){if(!await r0(Q,$))return[];let z=[];return await iQ($,(K,Z)=>{if(Z.isFile())z.push([k.relative(V,K).split(k.sep).join("/"),K])}),z.sort(),z}async function t0(V,Q,$){let z=(q)=>k.relative(V,q).split(k.sep).join("/"),K;try{K=await A.lstat($,{bigint:!0})}catch(q){let Y=q.code;if(Y==="ENOENT"||Y==="ENOTDIR")return new Set;throw q}if(K.isSymbolicLink())return new Set([z($)]);if(!K.isDirectory())throw new D(D.NOT_A_DIRECTORY,Q);let Z=new Set;return await iQ($,(q,Y)=>{if(Y.isSymbolicLink())Z.add(z(q))}),Z}async function r0(V,Q){let $;try{$=await A.lstat(Q,{bigint:!0})}catch(z){let K=z.code;if(K==="ENOENT"||K==="ENOTDIR")return!1;throw z}if(!$.isDirectory())throw new D(D.NOT_A_DIRECTORY,V);return!0}async function iQ(V,Q){let $=[V];while($.length){let z=$.pop(),K;try{K=await A.readdir(z,{withFileTypes:!0})}catch(Z){if(Z.code==="ENOENT")continue;throw Z}for(let Z of K){let q=k.join(z,Z.name);if(Q(q,Z),Z.isDirectory()&&!Z.isSymbolicLink())$.push(q)}}}function e0(V,Q){return Q.mtimeNs===V.mtimeNs&&Q.ctimeNs===V.ctimeNs&&Q.size===V.size}function Q1(V,Q){return(V.mtimeNs>V.ctimeNs?V.mtimeNs:V.ctimeNs)<Q-JQ.timestampTrustMarginNs}var $1=2000000000n,JQ={hashFile:s0,timestampTrustMarginNs:$1,nowNs:()=>BigInt(Date.now())*1000000n},lQ=l,hQ=Symbol.asyncDispose;if(hQ)Object.defineProperty(l.prototype,hQ,{value:l.prototype.dispose,configurable:!0,writable:!0});var I,g,BQ,$Q,MQ,B,a,DQ,f,K0,NQ,Z0,X0,bQ,vQ,aQ,oQ,xQ,sQ,tQ,WQ,UQ,rQ,eQ,z1=30000,o=".anthropic-memory-store",Y0=1;function Q0(V){return V1("sha256").update(`version ${Y0}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Wa as w}from"./chunk-dmaxdw65.js";import{Ab as u,Bb as v,Cb as x,Db as y,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,vb as l,wb as q,xb as r,yb as s,zb as t}from"./chunk-wca85ahg.js";import{Eb as a,Fb as b,Gb as c}from"./chunk-q2tjkhez.js";import{Hb as m,Ib as n,Jb as o,Lb as p}from"./chunk-wm6g7y1r.js";import"./chunk-g763t4rr.js";import"./chunk-dev3g0n3.js";import{ad as z,bd as A,cd as B,dd as C,ed as D,fd as E,gd as F,hd as G,id as H,jd as I}from"./chunk-ng9zksy3.js";import"./chunk-dgcct70c.js";import"./chunk-tqwek43e.js";import"./chunk-5feeegzy.js";import"./chunk-rwzt9xvk.js";import"./chunk-xntpzagn.js";import"./chunk-20sxtyt7.js";import"./chunk-sg7bhtb7.js";import"./chunk-rrm4x81p.js";import"./chunk-dh8yykbg.js";export{g as validateFindings,I as shouldFail,n as serializeReviewState,y as runReviewForPR,x as reviewPullRequest,j as reviewDiff,w as resolveBuddyThreads,u as renderFinding,b as renderDiffForReview,v as prepareReview,a as parseUnifiedDiff,o as parseReviewState,p as needsReview,s as loadGuidelines,G as formatReview,C as formatPretty,D as formatGithub,E as formatAgent,f as fingerprint,A as diffArgsFor,l as defaultIncludePath,h as dedupeFindings,F as countBySeverity,t as composeInstructions,B as collectLocalDiff,c as collectGitDiff,H as applySuggestion,k as anchorMap,d as SEVERITY_ORDER,m as REVIEW_STATE_VERSION,e as REVIEW_SCHEMA,z as REVIEW_FORMATS,r as MAX_GUIDELINE_CHARS,q as DEFAULT_GUIDELINE_FILES,i as DEFAULT_EXCLUDED_PATHS};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{fc as F}from"./chunk-
|
|
2
|
+
import{fc as F}from"./chunk-dev3g0n3.js";import{Df as c}from"./chunk-5nn5mms4.js";import{Pf as E,Sf as A}from"./chunk-y6292gbf.js";import{Wh as m}from"./chunk-rrm4x81p.js";function S(T,f,r){let O=r?"pull request":"issue";return{name:"read_issue",tier:"read",description:`Read the ${O} this task is about: its title and description.`,parameters:{type:"object",properties:{}},async run(M,x){try{let e=r?(await T.getPullRequests("all")).find((h)=>h.number===f):(await T.getIssues("all")).find((h)=>h.number===f);if(!e)return{content:`Could not find ${O} #${f}.`,isError:!0};let k=(e.body??"").slice(0,20000);return x.log(`read ${O} #${f}`),{content:`# ${e.title}
|
|
3
3
|
|
|
4
4
|
${k||"(no description)"}`,untrusted:!0}}catch(e){return{content:`Could not read ${O} #${f}: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}}}async function C(T){let f=T.logger??m(),r=F(T.config,f);if(!r)return"I need an AI provider configured to write a plan. See https://buddy.sh/ai/providers";let M=[`Write an implementation plan for ${T.isPullRequest?"pull request":"issue"} #${T.number} in this repository.`,"","Call `read_issue` first to see what is being asked for, then read enough of","the repository to be concrete about it.",...T.request?["","The person asking added this direction, which comes from them rather than","from the repository:",` ${T.request.replace(/\n/g," ")}`]:[],"","Produce: the files that would change and why, the order of the work, the","risks, and how the result would be verified. Prefer naming real paths you","have read over describing the change in the abstract.","","If the request is too vague to plan, say what you would need to know","instead of inventing a plan around the gap."].join(`
|
|
5
|
-
`),x=await A(r,{mode:c,task:M,tools:[...E,S(T.provider,T.number,T.isPullRequest)],context:{workspace:T.workspace??process.cwd(),baseBranch:T.config.repository?.baseBranch??"main"},logger:f});if(!x.output)return x.stopReason==="completed"?"I finished researching but produced no plan. That is a bug \u2014 please open an issue.":`I could not finish the plan (${x.stopReason}). The issue may need narrowing.`;return x.output}export{S as
|
|
5
|
+
`),x=await A(r,{mode:c,task:M,tools:[...E,S(T.provider,T.number,T.isPullRequest)],context:{workspace:T.workspace??process.cwd(),baseBranch:T.config.repository?.baseBranch??"main"},logger:f});if(!x.output)return x.stopReason==="completed"?"I finished researching but produced no plan. That is a bug \u2014 please open an issue.":`I could not finish the plan (${x.stopReason}). The issue may need narrowing.`;return x.output}export{S as Da,C as Ea};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ga as a,ha as b,ia as c,ja as d,ka as e,la as f,ma as g,na as h,oa as i,pa as j}from"./chunk-ejfyc7r8.js";import"./chunk-dh8yykbg.js";export{d as similarity,j as renderQuickLinks,b as renderPackageContext,h as parseQuickSelection,a as findMentionedPackages,e as findDuplicates,c as constrainLabels,i as clearQuickSelection,f as QUICK_LINKS_MARKER,g as QUICK_ACTIONS};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ch as
|
|
2
|
+
import{Ch as G,Fh as R,Gh as S}from"./chunk-r0jmwzr3.js";import{Qh as x}from"./chunk-sg7bhtb7.js";import{Wh as K}from"./chunk-rrm4x81p.js";var{semver:H}=globalThis.Bun;import F from"process";class P{userAgent="Buddy/1.0.0 (https://github.com/stacksjs/buddy)";logger;constructor(B){this.logger=B??K()}githubHeaders(){let B={"User-Agent":this.userAgent,Accept:"application/vnd.github.v3+json"},J=F.env.BUDDY_TOKEN||F.env.GITHUB_TOKEN||F.env.GH_TOKEN;if(J)B.Authorization=`Bearer ${J}`;return B}async fetchPackageInfo(B,J,Y){if(F.env.APP_ENV==="test"){let X={stripe:{owner:"stripe",repo:"stripe-node"},typescript:{owner:"microsoft",repo:"TypeScript"},react:{owner:"facebook",repo:"react"}}[B]||{owner:"example",repo:B};return{packageInfo:{name:B,description:`Package ${B} description`,repository:{type:"git",url:`https://github.com/${X.owner}/${X.repo}`}},releaseNotes:[],changelog:[],compareUrl:this.generateCompareUrl(X.owner,X.repo,J,Y)}}try{let q=await this.fetchNpmPackageInfo(B),X=[],Z=[],Q;if(q.repository?.url){let O=this.parseGitHubUrl(q.repository.url);if(O)X=await this.fetchGitHubReleases(O.owner,O.repo,J,Y),Q=this.generateCompareUrl(O.owner,O.repo,J,Y),Z=await this.fetchChangelog(O.owner,O.repo)}return{packageInfo:q,releaseNotes:X,changelog:Z,compareUrl:Q}}catch(q){return this.logger.error(`\u274C Failed to fetch package info for ${B}:`,q),{packageInfo:{name:B,description:`Package ${B} - see npm for details`,repository:{type:"git",url:`https://github.com/search?q=${encodeURIComponent(B)}&type=repositories`}},releaseNotes:[],changelog:[]}}}async fetchNpmPackageInfo(B){try{let J=R(B),Y=await x(`${J}/${encodeURIComponent(B).replace("%40","@")}`,{headers:{"User-Agent":this.userAgent}});if(!Y.ok)throw Error(`NPM registry responded with ${Y.status}`);let q=await Y.json(),X=q["dist-tags"]?.latest,Z;try{let L=await x(`https://api.npmjs.org/downloads/point/last-week/${encodeURIComponent(B)}`,{headers:{"User-Agent":this.userAgent}});if(L.ok)Z=(await L.json()).downloads}catch{}let Q=typeof q.repository==="string"?{type:"git",url:q.repository}:q.repository?.url?{type:q.repository.type??"git",url:q.repository.url}:void 0,O=q.author,_=typeof O==="string"?O:O&&typeof O==="object"&&("name"in O)&&typeof O.name==="string"?O:void 0,$=Array.isArray(q.maintainers)?q.maintainers.filter((L)=>!!L&&typeof L==="object"&&("name"in L)&&typeof L.name==="string"):void 0;return{name:B,description:q.description,homepage:q.homepage,repository:Q,license:q.license,author:_,keywords:q.keywords,weeklyDownloads:Z,lastPublish:X?q.time?.[X]:void 0,maintainers:$}}catch(J){return this.logger.warn(`\u26A0\uFE0F Failed to fetch npm info for ${B}:`,J),{name:B,description:`NPM package ${B}`,homepage:`https://www.npmjs.com/package/${encodeURIComponent(B)}`}}}async fetchSpanReleases(B,J,Y,q=5){let X=await this.fetchNpmPackageInfo(B).catch(()=>null),Z=X?.repository?.url?this.parseGitHubUrl(X.repository.url):null;if(!Z)return this.logger.debug(`No GitHub repository for ${B}; no span notes available`),[];let Q=[];for(let O=1;O<=q;O++){let _=await x(`${G()}/repos/${Z.owner}/${Z.repo}/releases?per_page=100&page=${O}`,{headers:this.githubHeaders()}).catch(()=>null);if(!_?.ok)break;let $=await _.json().catch(()=>null);if(!Array.isArray($)||$.length===0)break;for(let j of $)Q.push({version:j.tag_name,date:j.published_at,title:j.name??j.tag_name,body:j.body??"",htmlUrl:j.html_url,isPrerelease:j.prerelease});if($.some((j)=>this.isVersionBetween(j.tag_name.replace(/^v/,""),"0.0.0",J))||$.length<100)break}return Q.filter((O)=>this.isVersionBetween(O.version.replace(/^v/,""),J,Y))}parseGitHubUrl(B){try{let J=B.replace(/^git\+/,"").replace(/\.git$/,"").replace(/^git:\/\//,"https://").replace(/^ssh:\/\/git@/,"https://").replace(/^git@github\.com:/,"https://github.com/"),Y=new URL(J);if(Y.hostname!=="github.com")return null;let q=Y.pathname.split("/").filter(Boolean);if(q.length>=2)return{owner:q[0],repo:q[1]};return null}catch{return null}}async fetchGitHubReleases(B,J,Y,q){try{let X=await x(`${G()}/repos/${B}/${J}/releases?per_page=50`,{headers:this.githubHeaders()});if(!X.ok)return[];return(await X.json()).filter((Q)=>{let O=Q.tag_name.replace(/^v/,"");return this.isVersionBetween(O,Y,q)}).map((Q)=>({version:Q.tag_name,date:Q.published_at,title:Q.name??Q.tag_name,body:Q.body??"",htmlUrl:Q.html_url,compareUrl:this.generateCompareUrl(B,J,Y,Q.tag_name),author:Q.author?.login,isPrerelease:Q.prerelease,assets:Q.assets?.map((O)=>({name:O.name,downloadUrl:O.browser_download_url,size:O.size,contentType:O.content_type}))??[]}))}catch(X){return this.logger.warn(`Failed to fetch GitHub releases for ${B}/${J}:`,X),[]}}async fetchChangelog(B,J){let Y=["CHANGELOG.md","CHANGELOG.rst","HISTORY.md","RELEASES.md"];for(let q of Y)try{let X=await x(`${G()}/repos/${B}/${J}/contents/${q}`,{headers:this.githubHeaders()});if(X.ok){let Z=await X.json();if(Z.content){let Q=atob(Z.content);return this.parseChangelog(Q)}}}catch{}return[]}parseChangelog(B){let J=[],Y=B.split(`
|
|
3
3
|
`),q=null,X=null;for(let Z of Y){let Q=Z.match(/^##\s*\[?([^\]]+)\]?\s*-?\s*(.*)/);if(Q){if(q)J.push(q);q={version:Q[1],date:Q[2].trim(),changes:{}},X=null;continue}let O=Z.match(/^###\s*(.+)/);if(O&&q){X=O[1].toLowerCase();continue}let _=Z.match(/^[-*]\s*(.+)/);if(_&&q&&X){if(!q.changes)q.changes={};let $=X;if(!q.changes[$])q.changes[$]=[];q.changes[$].push(_[1])}}if(q)J.push(q);return J.slice(0,10)}generateCompareUrl(B,J,Y,q){let X=this.getComparableVersion(Y),Z=this.getComparableVersion(q);if(!X||!Z)return;return`https://github.com/${B}/${J}/compare/${encodeURIComponent(`v${X}`)}...${encodeURIComponent(`v${Z}`)}`}isVersionBetween(B,J,Y){let q=this.getComparableVersion(B),X=this.getComparableVersion(J),Z=this.getComparableVersion(Y);if(!q||!X||!Z)return!1;try{return H.order(q,X)>0&&H.order(q,Z)<=0}catch{return q>X&&q<=Z}}getComparableVersion(B){let J=B.split("||").flatMap((Y)=>{let q=Y.trim();if(q.startsWith("<"))return[];let X=q.match(/^(?:[~^]|>=?|=)?\s*v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Z.-]+)?)/i);if(!X)return[];let[Z,Q]=X[1].split("-",2),O=Z.split(".");while(O.length<3)O.push("0");return[`${O.join(".")}${Q?`-${Q}`:""}`]});if(J.length===0)return null;return J.reduce((Y,q)=>{try{return H.order(q,Y)>0?q:Y}catch{return q>Y?q:Y}})}generatePackageBadges(B,J,Y){let q=encodeURIComponent(B.name),X=this.normalizeVersionForBadges(J),Z=this.normalizeVersionForBadges(Y),Q=encodeURIComponent(X),O=encodeURIComponent(Z);return{age:`[](https://docs.renovatebot.com/merge-confidence/)`,adoption:`[](https://docs.renovatebot.com/merge-confidence/)`,passing:`[](https://docs.renovatebot.com/merge-confidence/)`,confidence:`[](https://docs.renovatebot.com/merge-confidence/)`}}async fetchComposerPackageInfo(B){if(F.env.APP_ENV==="test")return{name:B,description:`PHP package ${B} description`,homepage:`https://packagist.org/packages/${B}`,repository:{type:"git",url:`https://github.com/example/${B}`},license:"MIT"};try{let J=await x(`${S()}/packages/${encodeURIComponent(B)}.json`,{headers:{"User-Agent":this.userAgent}});if(!J.ok)throw Error(`Packagist responded with ${J.status}`);let q=(await J.json()).package;if(!q?.versions)return{name:B};let X=Object.keys(q.versions),Z=X.find((L)=>!L.includes("dev")&&!L.includes("alpha")&&!L.includes("beta"))??X[0],Q=(Z?q.versions[Z]:void 0)??{},O=Array.isArray(Q.license)?Q.license[0]:Q.license,_=Q.authors?.[0],$=_&&typeof _==="object"&&"name"in _&&typeof _.name==="string"?_:void 0;return{name:q.name??B,description:Q.description,homepage:Q.homepage,repository:Q.source?.url?{type:"git",url:Q.source.url}:void 0,license:O,author:$,keywords:Q.keywords,lastPublish:Q.time}}catch(J){return this.logger.warn(`Failed to fetch Packagist info for ${B}:`,J),{name:B}}}generateComposerBadges(B,J,Y){let q=encodeURIComponent(B.name),X=this.normalizeVersionForBadges(J),Z=this.normalizeVersionForBadges(Y),Q=encodeURIComponent(X),O=encodeURIComponent(Z);return{age:`[](https://docs.renovatebot.com/merge-confidence/)`,adoption:`[](https://docs.renovatebot.com/merge-confidence/)`,passing:`[](https://docs.renovatebot.com/merge-confidence/)`,confidence:`[](https://docs.renovatebot.com/merge-confidence/)`}}normalizeVersionForBadges(B){let J=B.replace(/^v/,"");if(J.split(".").length===2)J=`${J}.0`;return J}}
|
|
4
|
-
export{P as
|
|
4
|
+
export{P as Xe};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_c as oX}from"./chunk-4r03rh93.js";import{dd as sX}from"./chunk-z2gcfvze.js";import{Rh as iX}from"./chunk-wzncz6j5.js";import{gl as n}from"./chunk-16aeend1.js";import{resolve as b8}from"path";import y8 from"process";import{existsSync as aX,statSync as eX}from"fs";import{resolve as wQ}from"path";import SZ from"process";import{existsSync as TZ,mkdirSync as m8,readdirSync as u8,readFileSync as OZ,writeFileSync as g8}from"fs";import{homedir as ZQ}from"os";import{dirname as n8,resolve as l}from"path";import QX from"process";import{existsSync as QY,statSync as XY}from"fs";import{existsSync as SX,mkdirSync as NZ,readdirSync as CZ,writeFileSync as xZ}from"fs";import{homedir as $Q}from"os";import{dirname as YY,resolve as y}from"path";import YQ from"process";import{join as kZ,relative as PZ,resolve as ZY}from"path";import mQ from"process";import{existsSync as gY,mkdirSync as Y9,readdirSync as Z9,writeFileSync as $9}from"fs";import{homedir as HX}from"os";import{dirname as J9,resolve as b}from"path";import KQ from"process";import{join as bZ,relative as yZ,resolve as $Y}from"path";import uQ from"process";import{existsSync as cY,mkdirSync as W9,readdirSync as z9,writeFileSync as B9}from"fs";import{dirname as w9,resolve as gQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as vZ,createDecipheriv as hZ,randomBytes as UX}from"crypto";import{closeSync as JX,createReadStream as HY,createWriteStream as dZ,existsSync as GX,fsyncSync as UY,openSync as JY,writeFileSync as fZ}from"fs";import{access as pZ,constants as GY,mkdir as mZ,readdir as MQ,rename as _Y,stat as HQ,unlink as DQ,writeFile as _X}from"fs/promises";import{join as UQ}from"path";import x from"process";import{pipeline as uZ}from"stream/promises";import{createGzip as qY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as gZ,createDecipheriv as cZ,randomBytes as qX}from"crypto";import{closeSync as AX,createReadStream as AY,createWriteStream as lZ,existsSync as SQ,fsyncSync as WY,openSync as zY,writeFileSync as nZ}from"fs";import{access as iZ,constants as BY,mkdir as sZ,readdir as VQ,rename as RY,stat as GQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as oZ,join as _Q,resolve as rZ}from"path";import w from"process";import{pipeline as tZ}from"stream/promises";import{createGzip as wY}from"zlib";import qQ from"process";import r from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as aZ}from"fs";import{existsSync as eZ,readdirSync as Q0}from"fs";import{extname as BX,resolve as LY}from"path";import X0 from"process";import{join as Y0,relative as Z0,resolve as KY}from"path";import cQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as $0,createDecipheriv as H0,randomBytes as RX}from"crypto";import{closeSync as wX,createReadStream as jY,createWriteStream as U0,existsSync as NQ,fsyncSync as IY,openSync as FY,writeFileSync as J0}from"fs";import{access as G0,constants as MY,mkdir as _0,readdir as CQ,rename as DY,stat as AQ,unlink as xQ,writeFile as LX}from"fs/promises";import{isAbsolute as q0,join as WQ,resolve as A0}from"path";import L from"process";import{pipeline as W0}from"stream/promises";import{createGzip as SY}from"zlib";import zQ from"process";import t from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as dY}from"path";import{existsSync as x8}from"fs";class fY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!aX(Q))return!0;return eX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=aX(Y)?eX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class pY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new fY,vX=new pY;var mY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function uY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function VZ(Q){return uY(Q).flatMap((Y)=>mY.map((Z)=>wQ(Q.directory,`${Y}${Z}`)))}function EZ(Q={}){let X=wQ(Q.cwd||SZ.cwd());return Array.from(new Set([X,wQ(X,"config"),wQ(X,".config"),Q.configDir?wQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var z0=Object.defineProperty,B0=(Q)=>Q;function R0(Q,X){this[Q]=B0.bind(null,X)}var w0=(Q,X)=>{for(var Y in X)z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:R0.bind(X,Y)})},L0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),lY={};w0(lY,{withErrorRecovery:()=>sY,tryLoadConfig:()=>p0,loadConfigWithResult:()=>d0,loadConfig:()=>eY,isRetryableError:()=>k0,isConfigNotFoundError:()=>x0,isBunfigError:()=>oY,globalPerformanceMonitor:()=>FQ,globalCache:()=>BQ,getEnvOrDefault:()=>P0,generateConfigTypes:()=>m0,defaultGeneratedDir:()=>JZ,defaultConfigDir:()=>UZ,deepMergeWithArrayStrategy:()=>mX,deepMerge:()=>rY,createLibraryConfig:()=>u0,config:()=>f0,bunfigPlugin:()=>g0,applyEnvVarsToConfig:()=>LQ,TypeGenerationError:()=>kX,SchemaValidationError:()=>IQ,PluginError:()=>bX,PerformanceMonitor:()=>dX,FileSystemError:()=>xX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>XX,ConfigValidator:()=>uX,ConfigValidationError:()=>NX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>CX,ConfigLoader:()=>gX,ConfigLoadError:()=>jQ,ConfigFileLoader:()=>YX,ConfigCache:()=>hX,CacheUtils:()=>XZ,BunfigError:()=>h,BrowserConfigError:()=>PX,ArrayMergeStrategies:()=>$Z});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!QY(Q))return!0;return XY(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=QY(Y)?XY(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function K0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function j0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function I0(Q){return Q.getStats().size*2}function fX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=fX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function F0(Q,X){if(!cY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return fX(X,Z)}catch{return null}}catch{return null}}async function M0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await F0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(cY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return fX(Y,J)}catch{}}}catch{}return Y}function D0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=$Y(Y,"..");let Z=$Y(Y,Q||"");if(X?.relative)return yZ(uQ.cwd(),Z);return Z}async function S0(){try{let Q=await M0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function V0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class nY{async format(Q){let X=await V0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new nY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await pZ(this.config.logDirectory,GY.F_OK|GY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await mZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if($=JY(this.currentLogFile,"a",420),fZ($,J,{flag:"a"}),UY($),$!==void 0)JX($),$=void 0;if((await HQ(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await HQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{JX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return UQ(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return UQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return UQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return UX(16).toString("hex")}generateKey(){return UX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=UX(16),Z=vZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=qY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await HQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await HQ(Y).catch(()=>null))try{if(await _Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await DQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await HQ(Y).catch(()=>null))await _Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await DQ(UQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=HY(Q),Z=dZ(X),$=qY();await uZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=JY(this.currentLogFile,"r+");UY(Q),JX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(UQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=x.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=YZ[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
|
|
2
|
+
import{$c as oX}from"./chunk-vpz26asn.js";import{od as sX}from"./chunk-z906zp4k.js";import{Wh as iX}from"./chunk-rrm4x81p.js";import{ll as n}from"./chunk-dh8yykbg.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(_+=`
|
|
@@ -59,4 +59,4 @@ export type ConfigOf = Config
|
|
|
59
59
|
`,Y+=`|----------|------|-------------|----------|
|
|
60
60
|
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
61
61
|
`;return Y}}function nX(Q,X,Y={}){return LZ(Q,X,Y,new WeakMap)}function LZ(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:U}=Y;if(X===null||X===void 0)return H?Q:X;if(U){let G=U(Q,X);if(G!==void 0)return G}if(Array.isArray(X)||Array.isArray(Q))return KZ(Q,X,$,Z);if(!f(X)||!f(Q))return X;return C8(Q,X,Y,Z)}function KZ(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return T8(Q,X);case"smart":return O8(Q,X,Z);default:return X}return X}function T8(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>yX($,Z)))Y.push(Z);return Y}function O8(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(f(X[0])&&f(Q[0]))return N8(Q,X,Y);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}function N8(Q,X,Y){let Z=[...X];for(let $ of Q){if(!f($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let G of H)if(G in $){if(Z.find((_)=>f(_)&&(G in _)&&_[G]===$[G])){U=!0;break}}if(!U)Z.push($)}return Z}function C8(Q,X,Y,Z){let $=X;if(f($)&&Z.has($))return Z.get($);let H={...Q};if(f($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let G=$[U],J=H[U];if(Y.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){H[U]=G;continue}if(f(G)&&f(J))H[U]=LZ(J,G,Y,Z);else if(Array.isArray(G)||Array.isArray(J))H[U]=KZ(J,G,Y.arrayMergeMode||"smart",Z);else H[U]=G}return H}function jZ(Q,X,Y="replace"){return nX(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function yX(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(!yX(Q[Y],X[Y]))return!1;return!0}if(f(Q)&&f(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(!yX(Q[$],X[$]))return!1}return!0}return!1}function f(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class IZ{extensions=mY;async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:U=!0,verbose:G=!1}=Y;if($){let _=pQ.getWithFileCheck("file",Q);if(_){if(G)console.log(`Configuration loaded from cache: ${Q}`);return _}}let J=async()=>{if(!bQ(Q))return null;try{let _=`?t=${Date.now()}`,q=await import(Q+_),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new aQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new aQ(Q,Error("Configuration must export a valid object"),"unknown");let R={config:jZ(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)pQ.setWithFileCheck("file",R,Q,H);return R}catch(_){throw _ instanceof Error?XQ.configLoad(Q,_):XQ.configLoad(Q,Error(String(_)))}};if(U)return vX.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){return VZ({name:Q,directory:X,alias:Y})}generateNamePatterns(Q,X){return uY({name:Q,alias:X})}checkFileAccess(Q){return E8(async()=>{return bQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!bQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let G=dY(Q,`${H}${U}`);if(await this.checkFileAccess(G))Z.push(G)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let G=dY(Q,U);if(await this.checkFileAccess(G))Z.push(G)}}catch{return[]}return Z}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!bQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),H=$(Q,"utf8");JSON.parse(H)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}var k8=/^https?:\/\//;class FZ{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:G=!0,verbose:J=!1}=Y,_=async()=>{let q=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:G,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...U],z);else return this.validateWithJSONSchema(Q,X,z)}catch(W){return q.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:q,warnings:A}}};if(G)return await vX.track("validateConfiguration",_);return _()}async validateWithSchemaFile(Q,X,Y){try{if(!x8(X))throw new eQ(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new eQ(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,H){if(H.validateTypes&&X.type){let U=Array.isArray(Q)?"array":typeof Q,G=Array.isArray(X.type)?X.type:[X.type];if(!G.includes(U)){if(Z.push({path:Y,message:`Expected type ${G.join(" or ")}, got ${U}`,expected:G.join(" or "),actual:U,rule:"type"}),H.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),H.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let U=0;U<Q.length;U++){let G=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let U=Q;if(H.validateRequired&&X.required){for(let G of X.required)if(!(G in U)){if(Z.push({path:Y?`${Y}.${G}`:G,message:`Missing required property '${G}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[G,J]of Object.entries(X.properties))if(G in U){let _=Y?`${Y}.${G}`:G;if(this.validateObjectAgainstSchema(U[G],J,_,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let G=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!G.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let U=this.getValueByPath(Q,H.path),G=this.validateWithRule(U,H,H.path);if(Z.push(...G),Y.stopOnFirstError&&Z.length>0)break}catch(U){Z.push({path:H.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,H,U]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(U)})}return X}mapTypeScriptType(Q){switch(Q.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:k8},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var u=new ZX("bunfig",{showTags:!0});function P8(Q){if(!Q)return"";let X=Array.isArray(Q)?Q.filter(Boolean):[Q];if(X.length===0)return"";if(X.length===1)return` or alias "${X[0]}"`;return` or aliases ${X.map((Y)=>`"${Y}"`).join(", ")}`}class MZ{fileLoader=new IZ;envProcessor=new lX;validator=new FZ;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...U}=Q;try{if(Y?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let G;try{G=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){if(U.configFile)throw J;let _=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(_)throw J;G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let q=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!q&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),z=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(_&&(z||q))throw J;if(A&&(!_||!z))G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!_)G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||H)await this.validateConfiguration(G.config,$,H,U.name);if(Y?.enabled&&G)this.cacheResult(U.name||"",G,Y,U);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:U.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)u.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);G.metrics=J}return G}catch(G){if(G instanceof Error&&G.name==="ConfigNotFoundError")throw G;let J=Date.now()-X;throw u.error(`Configuration loading failed after ${J}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,configFile:H,cwd:U,configDir:G,defaultConfig:J,checkEnv:_=!0,arrayStrategy:q="replace",verbose:A=!1}=Q,z=U||QX.cwd(),W=[];if(H){let V=l(z,H);W.push(V);let p=_?RQ(Z,J,A):J,v=await this.fileLoader.tryLoadFromPaths([V],p,{arrayStrategy:q,verbose:A,cacheTtl:Y?.ttl,useCache:!Y?.ttl||Y.ttl>100});if(!v)throw XQ.configNotFound(Z||H,W,$);if(A)u.success(`Configuration loaded from explicit path: ${V}`);return this.finalizeResult(v,W,_,Z,A)}let I=await this.loadLocalConfiguration(Z,$,z,G,J,q,A,_,Y);if(I)return W.push(...this.getLocalSearchPaths(Z,$,z,G)),this.finalizeResult(I,W,_,Z,A);let B=await this.loadHomeConfiguration(Z,$,J,q,A,_);if(B)return W.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(B,W,_,Z,A);let R=await this.loadPackageJsonConfiguration(Z,$,z,J,q,A,_);if(R)return W.push(l(z,"package.json")),this.finalizeResult(R,W,_,Z,A);if(W.push(...this.getAllSearchPaths(Z,$,z,G)),X)throw XQ.configNotFound(Z,W,$);return{...await this.applyEnvironmentVariables(Z,J,_,A),warnings:[`No configuration file found for "${Z}"${P8($)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,G,J){let _=G?RQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let A of q){if(U)u.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,_,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(W){if(U)u.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let U=H?RQ(Q,Y,$):Y,G=[l(ZQ(),".config",Q),l(ZQ(),".config"),ZQ()];for(let J of G){if($)u.info(`Checking home directory: ${J}`);let _=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(_,U,{arrayStrategy:Z,verbose:$});if(q){if($)u.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let G=U?RQ(Q,Z,H):Z;try{let J=l(Y,"package.json");if(!TZ(J))return null;let _={};try{_=JSON.parse(OZ(J,"utf8"))}catch(z){if(H)u.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let q=_[Q],A=Q;if(!q&&X){let z=Array.isArray(X)?X:[X];for(let W of z){if(!W)continue;if(_[W]){q=_[W],A=W;break}}}if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)u.success(`Configuration loaded from package.json: ${A}`);return{config:jZ(G,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)u.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:RQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let H=Y(Q);if(H)$.push(...H)}if(X){let H=await this.validator.validateConfiguration(Q,X);if(!H.isValid)$.push(...H.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if($.length>0)throw XQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return pQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);pQ.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias){let Z=Array.isArray(X.alias)?X.alias.join(","):X.alias;Y.push(`alias:${Z}`)}if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configFile)Y.push(`configFile:${X.configFile}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return EZ({cwd:Q,configDir:X})}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(l(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),H=[];for(let U of $)H.push(...this.fileLoader.generateConfigPaths(Q,U,X));return H}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[l(ZQ(),".config",Q),l(ZQ(),".config"),ZQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var DX=new MZ;async function DZ(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await DX.loadConfig(Q);else Z=await DX.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){if(Q.configFile)throw Z;let $=Z instanceof Error?Z.name:"UnknownError",H=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||H.includes("config"))&&Q.verbose)u.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let G=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await DX.applyEnvironmentVariables(G.name||"",X,!0,G.verbose||!1))?.config??X;return X}}function RQ(Q,X,Y=!1){let Z=new lX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let A=[...G,_],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,I;for(let B of z)if(W=QX.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof q==="boolean")J[_]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))J[_]=B}else if(Array.isArray(q))try{J[_]=JSON.parse(W)}catch{J[_]=W.split(",").map((B)=>B.trim())}else J[_]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))J[_]=H(q,A)}return J}return H(X)}var I$=l(QX.cwd(),"config"),F$=l(QX.cwd(),"src/generated");var rX={verbose:!0,repository:{owner:"",name:"",provider:"github"},security:{enabled:!0,prioritize:!0,label:"security",minimumSeverity:"low"},dashboard:{enabled:!1,title:"Dependency Dashboard"},workflows:{enabled:!1,outputDir:".github/workflows",templates:{daily:!1,weekly:!1,monthly:!1},custom:[]},packages:{strategy:"all",ignore:[],ignorePaths:[],pin:{},groups:[],includePrerelease:!1,excludeMajor:!1,respectLatest:!0,minimumReleaseAge:0,minimumReleaseAgeExclude:[]}},$X=null;async function v8(Q){let X=b8(Q),Y=Bun.file(X);if(!await Y.exists())throw Error(`Config file not found: ${X}`);let Z;if(X.endsWith(".json"))Z=await Y.json();else{let $=await import(X);Z=$.default??$.config}if(typeof Z!=="object"||Z===null)throw Error(`Config file ${X} does not export a configuration object`);return nX(rX,Z)}async function N$(Q){if(Q){let X=await v8(Q),Y=sX(X);if(Y.warning)iX().warn(`\u26A0\uFE0F ${Y.warning}`);return oX(X),X}if(!$X){let X=await DZ({name:"buddy",alias:"buddy-bot",cwd:y8.cwd(),defaultConfig:rX}),Y=sX(X);if(Y.warning)iX().warn(`\u26A0\uFE0F ${Y.warning}`);oX(X),$X=X}return $X}function C$(){$X=null}var x$=rX;
|
|
62
|
-
export{rX as
|
|
62
|
+
export{rX as Vc,N$ as Wc,C$ as Xc,x$ as Yc};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
class x extends Error{spent;budget;constructor(f,k){super(`AI token budget exceeded: ${f} of ${k} output tokens used`);this.spent=f;this.budget=k;this.name="AiBudgetExceededError"}}class y extends Error{provider;status;constructor(f,k,z){super(f);this.provider=k;this.status=z;this.name="AiProviderError"}}
|
|
3
|
+
export{x as Vf,y as Wf};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ec as X}from"./chunk-
|
|
2
|
+
import{ec as X}from"./chunk-dev3g0n3.js";import{Zc as I}from"./chunk-vpz26asn.js";import{Ud as C,fe as P}from"./chunk-dgcct70c.js";import{oe as x,pe as V}from"./chunk-5feeegzy.js";import Y from"process";var Z=[["actionlint","actionlint"],["shellcheck","shellcheck"],["hadolint","hadolint"],["markdownlint","markdownlint"]];async function R(q,J={}){let W=J.env??Y.env,Q=J.cwd??Y.cwd(),F=J.hasCommand??C,G=[];G.push({name:"bun",status:"ok",detail:`Bun ${Bun.version}`});let H=!1,$;try{let j=Bun.spawn(["git","rev-parse","--is-inside-work-tree"],{cwd:Q,stdout:"pipe",stderr:"ignore",timeout:5000}),[M,D]=await Promise.all([j.exited,new Response(j.stdout).text()]);H=M===0&&D.trim()==="true"}catch(j){$=j instanceof Error?j.message:String(j)}G.push(H?{name:"git repository",status:"ok",detail:Q}:{name:"git repository",status:"fail",detail:$?`Git could not inspect ${Q}: ${$}`:`${Q} is not a git repository`,remediation:$?"Check that Git is installed and the working directory exists.":"Run buddy from inside a repository, or run `git init`."});let b=I(q);G.push(b.length===0?{name:"configuration",status:"ok",detail:"valid"}:{name:"configuration",status:"fail",detail:`${b.length} problem(s): ${b.slice(0,3).map((j)=>`${j.path} ${j.message}`).join("; ")}`,remediation:"Fix the paths reported above in buddy.config.ts."});let S=Boolean(q.repository?.owner&&q.repository.name);G.push(S?{name:"repository config",status:"ok",detail:`${q.repository.owner}/${q.repository.name}`}:{name:"repository config",status:"warn",detail:"owner and name are not set",remediation:"Set repository.owner and repository.name, or run in Actions where GITHUB_REPOSITORY is available. Local review works without them."});let K=q.repository?.provider??"github",U=q.repository?.token?{token:q.repository.token,source:"repository.token"}:V(K,W);G.push(U?{name:"git token",status:"ok",detail:`found in ${U.source}`}:{name:"git token",status:"warn",detail:"no token found",remediation:`Set one of ${(x[K]??[]).join(", ")}. Local review does not need one.`});let B=X(q,W);G.push(B?{name:"ai provider",status:"ok",detail:`${B.provider} via ${B.apiKeyEnv}`}:{name:"ai provider",status:"warn",detail:"no API key found",remediation:"Set ANTHROPIC_API_KEY (or OPENAI_API_KEY / GOOGLE_API_KEY). Dependency updates and static analysis work without one."});for(let[j,M]of Z){let D=await F(M);G.push(D?{name:`analyzer: ${j}`,status:"ok",detail:`${M} found`}:{name:`analyzer: ${j}`,status:"warn",detail:`${M} not installed`,remediation:`Install ${M} to enable the ${j} analyzer. Reviews run without it and report it as skipped.`})}let w=P.filter((j)=>!Z.some(([M])=>M===j.name)).map((j)=>j.name);return G.push({name:"native analyzers",status:"ok",detail:`${w.join(", ")} \u2014 always available`}),{checks:G,healthy:!G.some((j)=>j.status==="fail")}}var A={ok:"\u2705",warn:"\u26A0\uFE0F ",fail:"\u274C"};function E(q){let J=["","Buddy environment",""];for(let F of q.checks)if(J.push(`${A[F.status]} ${F.name}: ${F.detail}`),F.remediation)J.push(` \u2192 ${F.remediation}`);let W=q.checks.filter((F)=>F.status==="fail").length,Q=q.checks.filter((F)=>F.status==="warn").length;return J.push(""),J.push(q.healthy?`Ready. ${Q} optional capability/capabilities unavailable.`:`${W} problem(s) must be fixed before buddy can run.`),`${J.join(`
|
|
3
3
|
`)}
|
|
4
4
|
`}
|
|
5
|
-
export{R as
|
|
5
|
+
export{R as aa,E as ba};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Da as t,Ea as u}from"./chunk-x9spxa46.js";import{Fa as v,Ga as w,Ha as x,Ia as y,Ja as z,Ka as A,La as B,Ma as C,Na as D,Oa as E,Pa as F,Qa as G}from"./chunk-qbqk1jax.js";import{Ra as H,Sa as I,Ta as J,Ua as K,Va as L}from"./chunk-ednwgr1b.js";import"./chunk-g763t4rr.js";import"./chunk-dev3g0n3.js";import{Af as a,Bf as b,Cf as c,Df as d,Ef as e,Ff as f}from"./chunk-5nn5mms4.js";import{Gf as g,Hf as h,If as i,Jf as j,Kf as k,Lf as l,Mf as m,Nf as n,Of as o,Pf as p,Qf as q,Rf as r,Sf as s}from"./chunk-y6292gbf.js";import"./chunk-rwzt9xvk.js";import"./chunk-xntpzagn.js";import"./chunk-20sxtyt7.js";import"./chunk-2g8r8khw.js";import"./chunk-sg7bhtb7.js";import"./chunk-rrm4x81p.js";import"./chunk-dh8yykbg.js";export{i as writeFileTool,r as wrapUntrusted,F as withTouchOffer,I as verifyChanges,w as unitTestsTouch,J as stackedBranchName,y as simplifyTouch,n as shellTool,K as runStackedTouch,u as runPlan,s as runAgent,a as reviewMode,g as resolveWorkspacePath,D as renderTouchOffer,h as readFileTool,z as planTouch,d as planMode,G as parseTouchSelections,j as listDirTool,b as implementMode,E as hasTouchOffer,B as getFinishingTouch,f as getAgentMode,k as fsTools,c as fixCiMode,v as docstringsTouch,L as detectChangedFiles,t as createReadIssueTool,m as buildShellEnv,x as autofixTouch,q as Toolbelt,o as ToolPermissionError,C as TOUCH_OFFER_MARKER,H as TEST_COMMANDS,l as SHELL_ENV_ALLOWLIST,A as FINISHING_TOUCHES,p as BUILTIN_TOOLS,e as AGENT_MODES};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Qh as O}from"./chunk-sg7bhtb7.js";import{Wh as q}from"./chunk-rrm4x81p.js";import{ll as p}from"./chunk-dh8yykbg.js";var T=/(?:^|[-_.])(?:rc|alpha|beta|pre|dev|nightly|canary|snapshot|edge|next)\d*(?:$|[-_.])/i;function B(j){let z=/^v?(\d+(?:\.\d+)*)(.*)$/.exec(j.trim());if(!z)return null;let[,G,Q]=z,J=T.test(Q),Y=Q.replace(T,(Z)=>{return Z.endsWith("-")||Z.endsWith("_")||Z.endsWith(".")?"-":""}).replace(/^[-_.]/,"").toLowerCase();return{raw:j,version:G.split(".").map(Number),suffix:Y,prerelease:J}}function x(j,z){for(let G=0;G<Math.max(j.length,z.length);G++){let Q=(j[G]??0)-(z[G]??0);if(Q!==0)return Q}return j.length-z.length}function k(j,z){let G=(Q)=>/^[a-z]+/.exec(Q)?.[0]??Q;return G(j)===G(z)}function b(j,z,G={}){let Q=B(j);if(!Q)return null;let J=z.map(B).filter((Y)=>Y!==null).filter((Y)=>G.includePrerelease?!0:!Y.prerelease).filter((Y)=>k(Y.suffix,Q.suffix)).filter((Y)=>Y.version.length===Q.version.length).filter((Y)=>x(Y.version,Q.version)>0);if(J.length===0)return null;return J.sort((Y,Z)=>x(Z.version,Y.version)),J[0].raw}function l(j,z){let G=B(j),Q=B(z);if(!G||!Q)return"patch";if((Q.version[0]??0)!==(G.version[0]??0))return"major";if((Q.version[1]??0)!==(G.version[1]??0))return"minor";return"patch"}import P from"process";var v="registry-1.docker.io";function U(j){let z=j.trim(),G,Q=z.indexOf("@");if(Q!==-1)G=z.slice(Q+1),z=z.slice(0,Q);let J=z.indexOf("/"),Y=J===-1?"":z.slice(0,J),Z=Y==="localhost"||Y.includes(".")||Y.includes(":"),X=Z?Y:"docker.io",$=Z?z.slice(J+1):z,K="latest",S=$.lastIndexOf("/"),W=$.indexOf(":",S+1);if(W!==-1)K=$.slice(W+1),$=$.slice(0,W);let M=X==="docker.io"&&!$.includes("/")?`library/${$}`:$;return{registry:X,repository:M,tag:K,...G?{digest:G}:{}}}function i(j){let z=j.registry==="docker.io"?j.repository.replace(/^library\//,""):`${j.registry}/${j.repository}`;return j.digest?`${z}:${j.tag}@${j.digest}`:`${z}:${j.tag}`}function C(j){return j==="docker.io"?v:j}function y(j,z,G=P.env){let Q=z?.[j];if(Q?.tokenEnv){let J=G[Q.tokenEnv]?.trim();if(J)return{token:J}}if(Q?.username&&Q.passwordEnv){let J=G[Q.passwordEnv]?.trim();if(J)return{username:Q.username,password:J}}if(j==="ghcr.io"){let J=G.GITHUB_TOKEN?.trim()||G.BUDDY_TOKEN?.trim();if(J)return{username:"buddy",password:J}}if(j==="docker.io"){let J=G.DOCKERHUB_TOKEN?.trim()||G.DOCKER_TOKEN?.trim();if(J)return{username:G.DOCKERHUB_USERNAME?.trim()||"buddy",password:J}}return null}function R(j){if(!j?.toLowerCase().startsWith("bearer "))return null;let z={};for(let G of j.slice(7).matchAll(/(\w+)="([^"]*)"/g))z[G[1]]=G[2];return z.realm?{realm:z.realm,...z.service?{service:z.service}:{},...z.scope?{scope:z.scope}:{}}:null}function u(j,z){let G=new URL(j.realm);if(j.service)G.searchParams.set("service",j.service);return G.searchParams.set("scope",j.scope??`repository:${z}:pull`),G.toString()}class H{options;logger;tokens=new Map;constructor(j={}){this.options=j;this.logger=j.logger??q()}async listTags(j){let z=C(j.registry),G=this.options.maxPages??10,Q=[],J=`https://${z}/v2/${j.repository}/tags/list?n=100`;for(let Y=0;Y<G&&J;Y++){let Z=await this.authorizedFetch(J,j);if(!Z?.ok){if(Y===0)this.logger.debug(`Could not list tags for ${j.repository} on ${j.registry}: ${Z?.status??"no response"}`);break}let X=await Z.json().catch(()=>null);if(Array.isArray(X?.tags))Q.push(...X.tags);J=h(Z.headers.get("link"),z)}return Q}async resolveDigest(j){let G=`https://${C(j.registry)}/v2/${j.repository}/manifests/${j.tag}`,Q=await this.authorizedFetch(G,j,{method:"HEAD",headers:{Accept:["application/vnd.oci.image.index.v1+json","application/vnd.oci.image.manifest.v1+json","application/vnd.docker.distribution.manifest.list.v2+json","application/vnd.docker.distribution.manifest.v2+json"].join(", ")}});return Q?.ok?Q.headers.get("docker-content-digest"):null}async authorizedFetch(j,z,G={}){let Q={"User-Agent":"buddy",...G.headers},J=this.tokens.get(I(z));if(J)Q.Authorization=`Bearer ${J}`;let Y=()=>O(j,{...G,headers:Q}).catch(()=>null),Z=await Y();if(Z?.status!==401||J!==void 0)return Z;let X=R(Z.headers.get("www-authenticate"));if(!X)return Z;let $=await this.fetchToken(X,z);if(!$)return Z;return this.tokens.set(I(z),$),Q.Authorization=`Bearer ${$}`,Z=await Y(),Z}async fetchToken(j,z){let G=y(z.registry,this.options.registries,this.options.env);if(G&&"token"in G)return G.token;let Q={"User-Agent":"buddy"};if(G){let Z=Buffer.from(`${G.username}:${G.password}`).toString("base64");Q.Authorization=`Basic ${Z}`}let J=await O(u(j,z.repository),{headers:Q}).catch(()=>null);if(!J?.ok)return this.logger.debug(`Token exchange failed for ${z.registry}/${z.repository}: ${J?.status??"no response"}`),null;let Y=await J.json().catch(()=>null);return Y?.token??Y?.access_token??null}}function I(j){return`${j.registry}/${j.repository}`}function h(j,z){if(!j)return null;let G=/<([^>]+)>\s*;\s*rel="?next"?/i.exec(j);if(!G)return null;let Q=G[1];return Q.startsWith("http")?Q:`https://${z}${Q}`}var m=[".md",".txt",".log",".bak",".orig",".example",".sample",".tmpl",".template"];function F(j){let z=(j.split("/").pop()||"").toLowerCase();if(!z)return!1;if(m.some((G)=>z.endsWith(G)))return!1;if(z==="containerfile"||z.startsWith("containerfile."))return!0;if(z==="dockerfile"||z.startsWith("dockerfile."))return!0;return z.endsWith(".dockerfile")||z.endsWith(".containerfile")}async function jj(j,z){try{if(!F(j))return null;let G=[],Q=z.split(`
|
|
3
3
|
`);for(let J=0;J<Q.length;J++){let Y=Q[J].trim();if(!Y||Y.startsWith("#"))continue;let Z=Y.match(/^FROM\s+(\S+)(?:\s+as\s+\w+)?$/i);if(Z){let X=Z[1];if(X==="scratch"||X.startsWith("$"))continue;let $=c(X);if($)G.push({name:$.name,currentVersion:$.version,type:"docker-image",file:j})}}return{path:j,type:"Dockerfile",content:z,dependencies:G}}catch(G){return q().warn(`Failed to parse Dockerfile ${j}:`,G),null}}function c(j){try{let z,G,Q=j.indexOf("@"),J=Q===-1?void 0:j.slice(Q+1);if(Q!==-1)j=j.slice(0,Q);if(J&&!j.includes(":"))return null;if(j.includes(":")){let Y=j.lastIndexOf(":"),Z=j.substring(0,Y),X=j.substring(Y+1);if(/^\d+\//.test(X))z=j,G="latest";else z=Z,G=X}else z=j,G="latest";if(G.includes("$")||G.startsWith("sha256:"))return null;return{name:z,version:G,...J?{digest:J}:{}}}catch(z){return q().warn(`Failed to parse image reference ${j}:`,z),null}}async function zj(j,z,G={}){try{let Q=j.replace(/\s*\(.*\)$/,""),J=U(z?`${Q}:${z}`:Q),Z=await new H({...G.registries?{registries:G.registries}:{},logger:q()}).listTags(J);if(Z.length===0)return null;return b(J.tag,Z,{includePrerelease:G.includePrerelease??!1})}catch(Q){return q().warn(`Failed to fetch latest version for Docker image ${j}:`,Q),null}}async function d(j,z,G){let Q=U(`${j.replace(/\s*\(.*\)$/,"")}:${z}`);return new H({...G?{registries:G}:{},logger:q()}).resolveDigest(Q)}async function f(j,z,G,Q){try{if(!F(j))return q().info(`\u26A0\uFE0F updateDockerfile: ${j} is not a Dockerfile, returning original content`),z;let J=z;for(let Y of G){if(Y.dependencyType!=="docker-image")continue;let Z=Y.name.replace(/\s*\(.*\)$/,""),X=Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$=new RegExp(`(FROM\\s+${X})(:)([^\\s@]+)(@sha256:[a-f0-9]+)?([ \\t].*)?$`,"gim"),K=(W)=>{let M=["latest","main","master","develop","dev","stable"],w=W.toLowerCase().trim();return M.includes(w)},S=J.matchAll($);for(let W of S){let M=W[0],w=W[1],L=W[2],_=W[3],V=W[4]||"",D=W[5]||"";if(K(_)){q().info(`\u26A0\uFE0F Skipping update for ${Z} - version "${_}" should be respected`);continue}let A=V;if(V){let E=await d(Z,Y.newVersion,Q);if(!E){q().warn(`\u26A0\uFE0F Leaving ${Z} pinned at ${_}: could not resolve the digest for ${Y.newVersion}`);continue}A=`@${E}`}let N=`${w}${L}${Y.newVersion}${A}${D}`;J=J.replace(M,N),q().info(`\uD83D\uDCDD Updated ${Z}: ${_} \u2192 ${Y.newVersion}${A?" (digest re-resolved)":""}`)}}return J}catch(J){return q().warn(`Failed to update Dockerfile ${j}:`,J),z}}async function Gj(j,z){let G=[],Q=new Map;for(let J of j)if(J.dependencyType==="docker-image"&&F(J.file)){if(!Q.has(J.file))Q.set(J.file,[]);Q.get(J.file).push(J)}for(let[J,Y]of Q)try{let Z=await import("fs");if(Z.existsSync(J)){let X=Z.readFileSync(J,"utf-8"),$=await f(J,X,Y,z);if($!==X)G.push({path:J,content:$,type:"update"}),q().info(`\u2705 Generated update for ${J} with ${Y.length} image changes`);else q().info(`\u2139\uFE0F No changes needed for ${J} - versions already up to date`)}else q().warn(`\u26A0\uFE0F Dockerfile ${J} does not exist`)}catch(Z){q().warn(`Failed to generate updates for Dockerfile ${J}:`,Z)}return G}
|
|
4
|
-
export{B as
|
|
4
|
+
export{B as Ge,x as He,k as Ie,b as Je,l as Ke,U as Le,i as Me,C as Ne,y as Oe,R as Pe,H as Qe,F as Re,jj as Se,zj as Te,d as Ue,f as Ve,Gj as We};
|