@r5n/hydra 0.5.4 → 0.5.5
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/dist/cli.js +73 -93
- package/package.json +6 -5
- package/schema.json +5 -23
- package/dist/bundle-report.json +0 -21
package/dist/cli.js
CHANGED
|
@@ -1,104 +1,84 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
var
|
|
2
|
+
var Ki=Object.create;var{getPrototypeOf:Wi,defineProperty:ir,getOwnPropertyNames:Ti}=Object;var Ji=Object.prototype.hasOwnProperty;var Cn=(n,r,o)=>{o=n!=null?Ki(Wi(n)):{};let i=r||!n||!n.__esModule?ir(o,"default",{value:n,enumerable:!0}):o;for(let s of Ti(n))if(!Ji.call(i,s))ir(i,s,{get:()=>n[s],enumerable:!0});return i};var ao=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports);var to=(n,r)=>{for(var o in r)ir(n,o,{get:r[o],enumerable:!0,configurable:!0,set:(i)=>r[o]=()=>i})};var O=(n,r)=>()=>(n&&(r=n(n=0)),r);var Yi=import.meta.require;var Un="0.5.5";var sr=()=>{};var ar=ao((xa,cr)=>{var Ln=process||{},uo=Ln.argv||[],Mn=Ln.env||{},Qi=!(!!Mn.NO_COLOR||uo.includes("--no-color"))&&(!!Mn.FORCE_COLOR||uo.includes("--color")||Ln.platform==="win32"||(Ln.stdout||{}).isTTY&&Mn.TERM!=="dumb"||!!Mn.CI),Zi=(n,r,o=n)=>(i)=>{let s=""+i,c=s.indexOf(r,n.length);return~c?n+Fi(s,r,o,c)+r:n+s+r},Fi=(n,r,o,i)=>{let s="",c=0;do s+=n.substring(c,i)+o,c=i+r.length,i=n.indexOf(r,c);while(~i);return s+n.substring(c)},fo=(n=Qi)=>{let r=n?Zi:()=>String;return{isColorSupported:n,reset:r("\x1B[0m","\x1B[0m"),bold:r("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:r("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:r("\x1B[3m","\x1B[23m"),underline:r("\x1B[4m","\x1B[24m"),inverse:r("\x1B[7m","\x1B[27m"),hidden:r("\x1B[8m","\x1B[28m"),strikethrough:r("\x1B[9m","\x1B[29m"),black:r("\x1B[30m","\x1B[39m"),red:r("\x1B[31m","\x1B[39m"),green:r("\x1B[32m","\x1B[39m"),yellow:r("\x1B[33m","\x1B[39m"),blue:r("\x1B[34m","\x1B[39m"),magenta:r("\x1B[35m","\x1B[39m"),cyan:r("\x1B[36m","\x1B[39m"),white:r("\x1B[37m","\x1B[39m"),gray:r("\x1B[90m","\x1B[39m"),bgBlack:r("\x1B[40m","\x1B[49m"),bgRed:r("\x1B[41m","\x1B[49m"),bgGreen:r("\x1B[42m","\x1B[49m"),bgYellow:r("\x1B[43m","\x1B[49m"),bgBlue:r("\x1B[44m","\x1B[49m"),bgMagenta:r("\x1B[45m","\x1B[49m"),bgCyan:r("\x1B[46m","\x1B[49m"),bgWhite:r("\x1B[47m","\x1B[49m"),blackBright:r("\x1B[90m","\x1B[39m"),redBright:r("\x1B[91m","\x1B[39m"),greenBright:r("\x1B[92m","\x1B[39m"),yellowBright:r("\x1B[93m","\x1B[39m"),blueBright:r("\x1B[94m","\x1B[39m"),magentaBright:r("\x1B[95m","\x1B[39m"),cyanBright:r("\x1B[96m","\x1B[39m"),whiteBright:r("\x1B[97m","\x1B[39m"),bgBlackBright:r("\x1B[100m","\x1B[49m"),bgRedBright:r("\x1B[101m","\x1B[49m"),bgGreenBright:r("\x1B[102m","\x1B[49m"),bgYellowBright:r("\x1B[103m","\x1B[49m"),bgBlueBright:r("\x1B[104m","\x1B[49m"),bgMagentaBright:r("\x1B[105m","\x1B[49m"),bgCyanBright:r("\x1B[106m","\x1B[49m"),bgWhiteBright:r("\x1B[107m","\x1B[49m")}};cr.exports=fo();cr.exports.createColors=fo});var ur=ao((Ra,po)=>{var tr={to(n,r){if(!r)return`\x1B[${n+1}G`;return`\x1B[${r+1};${n+1}H`},move(n,r){let o="";if(n<0)o+=`\x1B[${-n}D`;else if(n>0)o+=`\x1B[${n}C`;if(r<0)o+=`\x1B[${-r}A`;else if(r>0)o+=`\x1B[${r}B`;return o},up:(n=1)=>`\x1B[${n}A`,down:(n=1)=>`\x1B[${n}B`,forward:(n=1)=>`\x1B[${n}C`,backward:(n=1)=>`\x1B[${n}D`,nextLine:(n=1)=>"\x1B[E".repeat(n),prevLine:(n=1)=>"\x1B[F".repeat(n),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},vi={up:(n=1)=>"\x1B[S".repeat(n),down:(n=1)=>"\x1B[T".repeat(n)},ns={screen:"\x1B[2J",up:(n=1)=>"\x1B[1J".repeat(n),down:(n=1)=>"\x1B[J".repeat(n),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(n){let r="";for(let o=0;o<n;o++)r+=this.line+(o<n-1?tr.up():"");if(n)r+=tr.left;return r}};po.exports={cursor:tr,scroll:vi,erase:ns,beep:"\x07"}});import{stdout as lo,stdin as ho}from"process";import*as an from"readline";import rs from"readline";import{ReadStream as mo}from"tty";function go(n,r,o){return String(n).normalize().replaceAll(`\r
|
|
3
|
+
`,`
|
|
3
4
|
`).split(`
|
|
4
|
-
`).map((
|
|
5
|
-
`)}function
|
|
6
|
-
`),
|
|
7
|
-
`),
|
|
8
|
-
`),
|
|
9
|
-
`).length-1;this.output.write(
|
|
10
|
-
`);this.output.write(o
|
|
11
|
-
`).slice(
|
|
12
|
-
`)),this._prevFrame=r;return}this.output.write(A.erase.down())}this.output.write(r),this.state==="initial"&&(this.state="active"),this._prevFrame=r}}}var A,Xn,Si,Dn,Ci,Wi,Gi=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},Mi,nn=10,qn=(r=0)=>(n)=>`\x1B[${n+r}m`,Bn=(r=0)=>(n)=>`\x1B[${38+r};5;${n}m`,jn=(r=0)=>(n,t,o)=>`\x1B[${38+r};2;${n};${t};${o}m`,$,Ui,Pi,qi,Ar,Bi=39,en="\x07",rt="[",ji="]",nt="m",sn,Vn=(r)=>`${Ar.values().next().value}${rt}${r}${nt}`,Kn=(r)=>`${Ar.values().next().value}${sn}${r}${en}`,Vi=(r)=>r.split(" ").map((n)=>wr(n)),tn=(r,n,t)=>{let o=[...n],e=!1,s=!1,i=wr(Qn(r[r.length-1]));for(let[a,f]of o.entries()){let d=wr(f);if(i+d<=t?r[r.length-1]+=f:(r.push(f),i=0),Ar.has(f)&&(e=!0,s=o.slice(a+1).join("").startsWith(sn)),e){s?f===en&&(e=!1,s=!1):f===nt&&(e=!1);continue}i+=d,i===t&&a<o.length-1&&(r.push(""),i=0)}!i&&r[r.length-1].length>0&&r.length>1&&(r[r.length-2]+=r.pop())},Ki=(r)=>{let n=r.split(" "),t=n.length;for(;t>0&&!(wr(n[t-1])>0);)t--;return t===n.length?r:n.slice(0,t).join(" ")+n.slice(t).join("")},Zi=(r,n,t={})=>{if(t.trim!==!1&&r.trim()==="")return"";let o="",e,s,i=Vi(r),a=[""];for(let[d,c]of r.split(" ").entries()){t.trim!==!1&&(a[a.length-1]=a[a.length-1].trimStart());let u=wr(a[a.length-1]);if(d!==0&&(u>=n&&(t.wordWrap===!1||t.trim===!1)&&(a.push(""),u=0),(u>0||t.trim===!1)&&(a[a.length-1]+=" ",u++)),t.hard&&i[d]>n){let l=n-u,R=1+Math.floor((i[d]-l-1)/n);Math.floor((i[d]-1)/n)<R&&a.push(""),tn(a,c,n);continue}if(u+i[d]>n&&u>0&&i[d]>0){if(t.wordWrap===!1&&u<n){tn(a,c,n);continue}a.push("")}if(u+i[d]>n&&t.wordWrap===!1){tn(a,c,n);continue}a[a.length-1]+=c}t.trim!==!1&&(a=a.map((d)=>Ki(d)));let f=[...a.join(`
|
|
13
|
-
`)]
|
|
14
|
-
`?(
|
|
15
|
-
`&&(
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
`}}}).
|
|
24
|
-
${
|
|
25
|
-
`,
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
`}}}).prompt()},
|
|
29
|
-
${hn(this.state)} ${r.message}
|
|
30
|
-
`;switch(this.state){case"submit":return`${t}${p.default.gray(_)} ${n(this.options[this.cursor],"selected")}`;case"cancel":return`${t}${p.default.gray(_)} ${n(this.options[this.cursor],"cancelled")}
|
|
31
|
-
${p.default.gray(_)}`;default:return`${t}${p.default.cyan(_)} ${fo({cursor:this.cursor,options:this.options,maxItems:r.maxItems,style:(o,e)=>n(o,e?"active":"inactive")}).join(`
|
|
32
|
-
${p.default.cyan(_)} `)}
|
|
33
|
-
${p.default.cyan(cr)}
|
|
34
|
-
`}}}).prompt()},Rn=(r="")=>{process.stdout.write(`${p.default.gray(cr)} ${p.default.red(r)}
|
|
5
|
+
`).map((i)=>ys(i,r,o)).join(`
|
|
6
|
+
`)}function br(n,r){if(typeof n=="string")return cn.aliases.get(n)===r;for(let o of n)if(o!==void 0&&br(o,r))return!0;return!1}function bs(n,r){if(n===r)return;let o=n.split(`
|
|
7
|
+
`),i=r.split(`
|
|
8
|
+
`),s=[];for(let c=0;c<Math.max(o.length,i.length);c++)o[c]!==i[c]&&s.push(c);return s}function B(n){return n===mr}function Vn(n,r){let o=n;o.isTTY&&o.setRawMode(r)}function eo({input:n=ho,output:r=lo,overwrite:o=!0,hideCursor:i=!0}={}){let s=an.createInterface({input:n,output:r,prompt:"",tabSize:1});an.emitKeypressEvents(n,s),n instanceof mo&&n.isTTY&&n.setRawMode(!0);let c=(a,{name:u,sequence:t})=>{let f=String(a);if(br([f,u,t],"cancel")){i&&r.write(q.cursor.show),process.exit(0);return}if(!o)return;an.moveCursor(r,u==="return"?0:-1,u==="return"?-1:0,()=>{an.clearLine(r,1,()=>{n.once("keypress",c)})})};return i&&r.write(q.cursor.hide),n.once("keypress",c),()=>{n.off("keypress",c),i&&r.write(q.cursor.show),n instanceof mo&&n.isTTY&&!gs&&n.setRawMode(!1),s.terminal=!1,s.close()}}class ln{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(n,r=!0){let{input:o=ho,output:i=lo,render:s,signal:c,...a}=n;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=r,this._abortSignal=c,this.input=o,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(n,r){let o=this._subscribers.get(n)??[];o.push(r),this._subscribers.set(n,o)}on(n,r){this.setSubscriber(n,{cb:r})}once(n,r){this.setSubscriber(n,{cb:r,once:!0})}emit(n,...r){let o=this._subscribers.get(n)??[],i=[];for(let s of o)s.cb(...r),s.once&&i.push(()=>o.splice(o.indexOf(s),1));for(let s of i)s()}prompt(){return new Promise((n)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),n(mr);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=rs.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Vn(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(q.cursor.show),this.output.off("resize",this.render),Vn(this.input,!1),n(this.value)}),this.once("cancel",()=>{this.output.write(q.cursor.show),this.output.off("resize",this.render),Vn(this.input,!1),n(mr)})})}_isActionKey(n,r){return n==="\t"}_setValue(n){this.value=n,this.emit("value",this.value)}_setUserInput(n,r){this.userInput=n??"",this.emit("userInput",this.userInput),r&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(n,r){if(this._track&&r.name!=="return"&&(r.name&&this._isActionKey(n,r)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),r?.name&&(!this._track&&cn.aliases.has(r.name)&&this.emit("cursor",cn.aliases.get(r.name)),cn.actions.has(r.name)&&this.emit("cursor",r.name)),n&&(n.toLowerCase()==="y"||n.toLowerCase()==="n")&&this.emit("confirm",n.toLowerCase()==="y"),this.emit("key",n?.toLowerCase(),r),r?.name==="return"){if(this.opts.validate){let o=this.opts.validate(this.value);o&&(this.error=o instanceof Error?o.message:o,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}br([n,r?.name,r?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
9
|
+
`),Vn(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let n=go(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
10
|
+
`).length-1;this.output.write(q.cursor.move(-999,n*-1))}render(){let n=go(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(n!==this._prevFrame){if(this.state==="initial")this.output.write(q.cursor.hide);else{let r=bs(this._prevFrame,n);if(this.restoreCursor(),r&&r?.length===1){let o=r[0];this.output.write(q.cursor.move(0,o)),this.output.write(q.erase.lines(1));let i=n.split(`
|
|
11
|
+
`);this.output.write(i[o]),this._prevFrame=n,this.output.write(q.cursor.move(0,i.length-o-1));return}if(r&&r?.length>1){let o=r[0];this.output.write(q.cursor.move(0,o)),this.output.write(q.erase.down());let i=n.split(`
|
|
12
|
+
`).slice(o);this.output.write(i.join(`
|
|
13
|
+
`)),this._prevFrame=n;return}this.output.write(q.erase.down())}this.output.write(n),this.state==="initial"&&(this.state="active"),this._prevFrame=n}}}function ls(n,r){if(n===void 0||r.length===0)return 0;let o=r.findIndex((i)=>i.value===n);return o!==-1?o:0}function hs(n,r){return(r.label??String(r.value)).toLowerCase().includes(n.toLowerCase())}function xs(n,r){if(r)return n?r:r[0]}function zn(n,r,o){let i=n+r,s=Math.max(o.length-1,0),c=i<0?s:i>s?0:i;return o[c].disabled?zn(c,r<0?-1:1,o):c}var On,q,os=(n)=>n===161||n===164||n===167||n===168||n===170||n===173||n===174||n>=176&&n<=180||n>=182&&n<=186||n>=188&&n<=191||n===198||n===208||n===215||n===216||n>=222&&n<=225||n===230||n>=232&&n<=234||n===236||n===237||n===240||n===242||n===243||n>=247&&n<=250||n===252||n===254||n===257||n===273||n===275||n===283||n===294||n===295||n===299||n>=305&&n<=307||n===312||n>=319&&n<=322||n===324||n>=328&&n<=331||n===333||n===338||n===339||n===358||n===359||n===363||n===462||n===464||n===466||n===468||n===470||n===472||n===474||n===476||n===593||n===609||n===708||n===711||n>=713&&n<=715||n===717||n===720||n>=728&&n<=731||n===733||n===735||n>=768&&n<=879||n>=913&&n<=929||n>=931&&n<=937||n>=945&&n<=961||n>=963&&n<=969||n===1025||n>=1040&&n<=1103||n===1105||n===8208||n>=8211&&n<=8214||n===8216||n===8217||n===8220||n===8221||n>=8224&&n<=8226||n>=8228&&n<=8231||n===8240||n===8242||n===8243||n===8245||n===8251||n===8254||n===8308||n===8319||n>=8321&&n<=8324||n===8364||n===8451||n===8453||n===8457||n===8467||n===8470||n===8481||n===8482||n===8486||n===8491||n===8531||n===8532||n>=8539&&n<=8542||n>=8544&&n<=8555||n>=8560&&n<=8569||n===8585||n>=8592&&n<=8601||n===8632||n===8633||n===8658||n===8660||n===8679||n===8704||n===8706||n===8707||n===8711||n===8712||n===8715||n===8719||n===8721||n===8725||n===8730||n>=8733&&n<=8736||n===8739||n===8741||n>=8743&&n<=8748||n===8750||n>=8756&&n<=8759||n===8764||n===8765||n===8776||n===8780||n===8786||n===8800||n===8801||n>=8804&&n<=8807||n===8810||n===8811||n===8814||n===8815||n===8834||n===8835||n===8838||n===8839||n===8853||n===8857||n===8869||n===8895||n===8978||n>=9312&&n<=9449||n>=9451&&n<=9547||n>=9552&&n<=9587||n>=9600&&n<=9615||n>=9618&&n<=9621||n===9632||n===9633||n>=9635&&n<=9641||n===9650||n===9651||n===9654||n===9655||n===9660||n===9661||n===9664||n===9665||n>=9670&&n<=9672||n===9675||n>=9678&&n<=9681||n>=9698&&n<=9701||n===9711||n===9733||n===9734||n===9737||n===9742||n===9743||n===9756||n===9758||n===9792||n===9794||n===9824||n===9825||n>=9827&&n<=9829||n>=9831&&n<=9834||n===9836||n===9837||n===9839||n===9886||n===9887||n===9919||n>=9926&&n<=9933||n>=9935&&n<=9939||n>=9941&&n<=9953||n===9955||n===9960||n===9961||n>=9963&&n<=9969||n===9972||n>=9974&&n<=9977||n===9979||n===9980||n===9982||n===9983||n===10045||n>=10102&&n<=10111||n>=11094&&n<=11097||n>=12872&&n<=12879||n>=57344&&n<=63743||n>=65024&&n<=65039||n===65533||n>=127232&&n<=127242||n>=127248&&n<=127277||n>=127280&&n<=127337||n>=127344&&n<=127373||n===127375||n===127376||n>=127387&&n<=127404||n>=917760&&n<=917999||n>=983040&&n<=1048573||n>=1048576&&n<=1114109,is=(n)=>n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510,ss=(n)=>n>=4352&&n<=4447||n===8986||n===8987||n===9001||n===9002||n>=9193&&n<=9196||n===9200||n===9203||n===9725||n===9726||n===9748||n===9749||n>=9800&&n<=9811||n===9855||n===9875||n===9889||n===9898||n===9899||n===9917||n===9918||n===9924||n===9925||n===9934||n===9940||n===9962||n===9970||n===9971||n===9973||n===9978||n===9981||n===9989||n===9994||n===9995||n===10024||n===10060||n===10062||n>=10067&&n<=10069||n===10071||n>=10133&&n<=10135||n===10160||n===10175||n===11035||n===11036||n===11088||n===11093||n>=11904&&n<=11929||n>=11931&&n<=12019||n>=12032&&n<=12245||n>=12272&&n<=12287||n>=12289&&n<=12350||n>=12353&&n<=12438||n>=12441&&n<=12543||n>=12549&&n<=12591||n>=12593&&n<=12686||n>=12688&&n<=12771||n>=12783&&n<=12830||n>=12832&&n<=12871||n>=12880&&n<=19903||n>=19968&&n<=42124||n>=42128&&n<=42182||n>=43360&&n<=43388||n>=44032&&n<=55203||n>=63744&&n<=64255||n>=65040&&n<=65049||n>=65072&&n<=65106||n>=65108&&n<=65126||n>=65128&&n<=65131||n>=94176&&n<=94180||n===94192||n===94193||n>=94208&&n<=100343||n>=100352&&n<=101589||n>=101632&&n<=101640||n>=110576&&n<=110579||n>=110581&&n<=110587||n===110589||n===110590||n>=110592&&n<=110882||n===110898||n>=110928&&n<=110930||n===110933||n>=110948&&n<=110951||n>=110960&&n<=111355||n===126980||n===127183||n===127374||n>=127377&&n<=127386||n>=127488&&n<=127490||n>=127504&&n<=127547||n>=127552&&n<=127560||n===127568||n===127569||n>=127584&&n<=127589||n>=127744&&n<=127776||n>=127789&&n<=127797||n>=127799&&n<=127868||n>=127870&&n<=127891||n>=127904&&n<=127946||n>=127951&&n<=127955||n>=127968&&n<=127984||n===127988||n>=127992&&n<=128062||n===128064||n>=128066&&n<=128252||n>=128255&&n<=128317||n>=128331&&n<=128334||n>=128336&&n<=128359||n===128378||n===128405||n===128406||n===128420||n>=128507&&n<=128591||n>=128640&&n<=128709||n===128716||n>=128720&&n<=128722||n>=128725&&n<=128727||n>=128732&&n<=128735||n===128747||n===128748||n>=128756&&n<=128764||n>=128992&&n<=129003||n===129008||n>=129292&&n<=129338||n>=129340&&n<=129349||n>=129351&&n<=129535||n>=129648&&n<=129660||n>=129664&&n<=129672||n>=129680&&n<=129725||n>=129727&&n<=129733||n>=129742&&n<=129755||n>=129760&&n<=129768||n>=129776&&n<=129784||n>=131072&&n<=196605||n>=196608&&n<=262141,fr,jn,qn,pr,Bn,cs,as,xo=(n,r={},o={})=>{let i=r.limit??1/0,s=r.ellipsis??"",c=r?.ellipsisWidth??(s?xo(s,as,o).width:0),a=o.ansiWidth??0,u=o.controlWidth??0,t=o.tabWidth??8,f=o.ambiguousWidth??1,m=o.emojiWidth??2,b=o.fullWidthWidth??2,y=o.regularWidth??1,e=o.wideWidth??2,p=0,d=0,x=n.length,$=0,E=!1,C=x,S=Math.max(0,i-c),_=0,N=0,h=0,R=0;n:for(;;){if(N>_||d>=x&&d>p){let z=n.slice(_,N)||n.slice(p,d);$=0;for(let D of z.replaceAll(cs,"")){let A=D.codePointAt(0)||0;if(is(A)?R=b:ss(A)?R=e:f!==y&&os(A)?R=f:R=y,h+R>S&&(C=Math.min(C,Math.max(_,p)+$)),h+R>i){E=!0;break n}$+=D.length,h+=R}_=N=0}if(d>=x)break;if(Bn.lastIndex=d,Bn.test(n)){if($=Bn.lastIndex-d,R=$*y,h+R>S&&(C=Math.min(C,d+Math.floor((S-h)/y))),h+R>i){E=!0;break}h+=R,_=p,N=d,d=p=Bn.lastIndex;continue}if(fr.lastIndex=d,fr.test(n)){if(h+a>S&&(C=Math.min(C,d)),h+a>i){E=!0;break}h+=a,_=p,N=d,d=p=fr.lastIndex;continue}if(jn.lastIndex=d,jn.test(n)){if($=jn.lastIndex-d,R=$*u,h+R>S&&(C=Math.min(C,d+Math.floor((S-h)/u))),h+R>i){E=!0;break}h+=R,_=p,N=d,d=p=jn.lastIndex;continue}if(qn.lastIndex=d,qn.test(n)){if($=qn.lastIndex-d,R=$*t,h+R>S&&(C=Math.min(C,d+Math.floor((S-h)/t))),h+R>i){E=!0;break}h+=R,_=p,N=d,d=p=qn.lastIndex;continue}if(pr.lastIndex=d,pr.test(n)){if(h+m>S&&(C=Math.min(C,d)),h+m>i){E=!0;break}h+=m,_=p,N=d,d=p=pr.lastIndex;continue}d+=1}return{width:E?S:h,index:E?C:x,truncated:E,ellipsed:E&&i>=c}},ts,Sn=(n,r={})=>xo(n,ts,r).width,An="\x1B",Ro="\x9B",us=39,yr="\x07",$o="[",fs="]",Eo="m",wr,yo,ps=(n)=>{if(n>=30&&n<=37||n>=90&&n<=97)return 39;if(n>=40&&n<=47||n>=100&&n<=107)return 49;if(n===1||n===2)return 22;if(n===3)return 23;if(n===4)return 24;if(n===7)return 27;if(n===8)return 28;if(n===9)return 29;if(n===0)return 0},wo=(n)=>`${An}${$o}${n}${Eo}`,bo=(n)=>`${An}${wr}${n}${yr}`,ds=(n)=>n.map((r)=>Sn(r)),dr=(n,r,o)=>{let i=r[Symbol.iterator](),s=!1,c=!1,a=n.at(-1),u=a===void 0?0:Sn(a),t=i.next(),f=i.next(),m=0;for(;!t.done;){let b=t.value,y=Sn(b);u+y<=o?n[n.length-1]+=b:(n.push(b),u=0),(b===An||b===Ro)&&(s=!0,c=r.startsWith(wr,m+1)),s?c?b===yr&&(s=!1,c=!1):b===Eo&&(s=!1):(u+=y,u===o&&!f.done&&(n.push(""),u=0)),t=f,f=i.next(),m+=b.length}a=n.at(-1),!u&&a!==void 0&&a.length>0&&n.length>1&&(n[n.length-2]+=n.pop())},ms=(n)=>{let r=n.split(" "),o=r.length;for(;o>0&&!(Sn(r[o-1])>0);)o--;return o===r.length?n:r.slice(0,o).join(" ")+r.slice(o).join("")},ys=(n,r,o={})=>{if(o.trim!==!1&&n.trim()==="")return"";let i="",s,c,a=n.split(" "),u=ds(a),t=[""];for(let[p,d]of a.entries()){o.trim!==!1&&(t[t.length-1]=(t.at(-1)??"").trimStart());let x=Sn(t.at(-1)??"");if(p!==0&&(x>=r&&(o.wordWrap===!1||o.trim===!1)&&(t.push(""),x=0),(x>0||o.trim===!1)&&(t[t.length-1]+=" ",x++)),o.hard&&u[p]>r){let $=r-x,E=1+Math.floor((u[p]-$-1)/r);Math.floor((u[p]-1)/r)<E&&t.push(""),dr(t,d,r);continue}if(x+u[p]>r&&x>0&&u[p]>0){if(o.wordWrap===!1&&x<r){dr(t,d,r);continue}t.push("")}if(x+u[p]>r&&o.wordWrap===!1){dr(t,d,r);continue}t[t.length-1]+=d}o.trim!==!1&&(t=t.map((p)=>ms(p)));let f=t.join(`
|
|
14
|
+
`),m=f[Symbol.iterator](),b=m.next(),y=m.next(),e=0;for(;!b.done;){let p=b.value,d=y.value;if(i+=p,p===An||p===Ro){yo.lastIndex=e+1;let $=yo.exec(f)?.groups;if($?.code!==void 0){let E=Number.parseFloat($.code);s=E===us?void 0:E}else $?.uri!==void 0&&(c=$.uri.length===0?void 0:$.uri)}let x=s?ps(s):void 0;d===`
|
|
15
|
+
`?(c&&(i+=bo("")),s&&x&&(i+=wo(x))):p===`
|
|
16
|
+
`&&(s&&x&&(i+=wo(s)),c&&(i+=bo(c))),e+=p.length,b=y,y=m.next()}return i},ws,cn,gs,mr,gr=(n)=>("columns"in n)&&typeof n.columns=="number"?n.columns:80,Co=(n)=>("rows"in n)&&typeof n.rows=="number"?n.rows:20,Oo,So,ko,lr,hr;var xr=O(()=>{On=Cn(ar(),1),q=Cn(ur(),1),fr=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,jn=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,qn=/\t{1,1000}/y,pr=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Bn=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,cs=/\p{M}+/gu,as={limit:1/0,ellipsis:""},ts={limit:1/0,ellipsis:"",ellipsisWidth:0},wr=`${fs}8;;`,yo=new RegExp(`(?:\\${$o}(?<code>\\d+)m|\\${wr}(?<uri>.*)${yr})`,"y");ws=["up","down","left","right","space","enter","cancel"],cn={actions:new Set(ws),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};gs=globalThis.process.platform.startsWith("win"),mr=Symbol("clack:cancel");Oo=class Oo extends ln{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#o="";#i;#r;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return On.default.inverse(On.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let n=this.userInput.slice(0,this._cursor),[r,...o]=this.userInput.slice(this._cursor);return`${n}${On.default.inverse(r)}${o.join("")}`}get options(){return typeof this.#r=="function"?this.#r():this.#r}constructor(n){super(n),this.#r=n.options;let r=this.options;this.filteredOptions=[...r],this.multiple=n.multiple===!0,this.#i=n.filter??hs;let o;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?o=n.initialValue:o=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(o=[this.options[0].value]),o)for(let i of o){let s=r.findIndex((c)=>c.value===i);s!==-1&&(this.toggleSelected(i),this.#n=s)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(i,s)=>this.#s(i,s)),this.on("userInput",(i)=>this.#c(i))}_isActionKey(n,r){return n==="\t"||this.multiple&&this.isNavigating&&r.name==="space"&&n!==void 0&&n!==""}#s(n,r){let o=r.name==="up",i=r.name==="down",s=r.name==="return";o||i?(this.#n=Math.max(0,Math.min(this.#n+(o?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=xs(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(r.name==="tab"||this.isNavigating&&r.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((r)=>r!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#c(n){if(n!==this.#o){this.#o=n;let r=this.options;n?this.filteredOptions=r.filter((o)=>this.#i(n,o)):this.filteredOptions=[...r],this.#n=ls(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};So=class extends ln{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(n){super(n,!1),this.value=!!n.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(r)=>{this.output.write(q.cursor.move(0,-1)),this.value=r,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};ko=class ko extends ln{options;cursor=0;#n;getGroupItems(n){return this.options.filter((r)=>r.group===n)}isGroupSelected(n){let r=this.getGroupItems(n),o=this.value;return o===void 0?!1:r.every((i)=>o.includes(i.value))}toggleValue(){let n=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),n.group===!0){let r=n.value,o=this.getGroupItems(r);this.isGroupSelected(r)?this.value=this.value.filter((i)=>o.findIndex((s)=>s.value===i)===-1):this.value=[...this.value,...o.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let r=this.value.includes(n.value);this.value=r?this.value.filter((o)=>o!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:r}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(r).flatMap(([o,i])=>[{value:o,group:!0,label:o},...i.map((s)=>({...s,group:o}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:o})=>o===n.cursorAt),this.#n?0:1),this.on("cursor",(o)=>{switch(o){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}};lr=class lr extends ln{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(n){super(n,!1),this.options=n.options;let r=this.options.findIndex(({value:i})=>i===n.initialValue),o=r===-1?0:r;this.cursor=this.options[o].disabled?zn(o,1,this.options):o,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=zn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=zn(this.cursor,1,this.options);break}this.changeValue()})}};hr=class hr extends ln{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let n=this.userInput;if(this.cursor>=n.length)return`${this.userInput}\u2588`;let r=n.slice(0,this.cursor),[o,...i]=n.slice(this.cursor);return`${r}${On.default.inverse(o)}${i.join("")}`}get cursor(){return this._cursor}constructor(n){super({...n,initialUserInput:n.initialUserInput??n.initialValue}),this.on("userInput",(r)=>{this._setValue(r)}),this.on("finalize",()=>{this.value||(this.value=n.defaultValue),this.value===void 0&&(this.value="")})}}});import Y from"process";function Rs(){return Y.platform!=="win32"?Y.env.TERM!=="linux":!!Y.env.CI||!!Y.env.WT_SESSION||!!Y.env.TERMINUS_SUBLIME||Y.env.ConEmuTask==="{cmd::Cmder}"||Y.env.TERM_PROGRAM==="Terminus-Sublime"||Y.env.TERM_PROGRAM==="vscode"||Y.env.TERM==="xterm-256color"||Y.env.TERM==="alacritty"||Y.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function Or(n,r,o){return String(n).normalize().replaceAll(`\r
|
|
17
|
+
`,`
|
|
18
|
+
`).split(`
|
|
19
|
+
`).map((i)=>Vs(i,r,o)).join(`
|
|
20
|
+
`)}var g,kn,er,$s=()=>process.env.CI==="true",H=(n,r)=>er?n:r,Es,No,Po,Sr,es,M,hn,Pa,Ua,Cr,Wn,Ma,La,ja,qa,Ba,Va,za,Aa,Da,Ia,Cs,Os,Ss,ks,kr=(n)=>{switch(n){case"initial":case"active":return g.default.cyan(Es);case"cancel":return g.default.red(No);case"error":return g.default.yellow(Po);case"submit":return g.default.green(Sr)}},_s=(n)=>n===161||n===164||n===167||n===168||n===170||n===173||n===174||n>=176&&n<=180||n>=182&&n<=186||n>=188&&n<=191||n===198||n===208||n===215||n===216||n>=222&&n<=225||n===230||n>=232&&n<=234||n===236||n===237||n===240||n===242||n===243||n>=247&&n<=250||n===252||n===254||n===257||n===273||n===275||n===283||n===294||n===295||n===299||n>=305&&n<=307||n===312||n>=319&&n<=322||n===324||n>=328&&n<=331||n===333||n===338||n===339||n===358||n===359||n===363||n===462||n===464||n===466||n===468||n===470||n===472||n===474||n===476||n===593||n===609||n===708||n===711||n>=713&&n<=715||n===717||n===720||n>=728&&n<=731||n===733||n===735||n>=768&&n<=879||n>=913&&n<=929||n>=931&&n<=937||n>=945&&n<=961||n>=963&&n<=969||n===1025||n>=1040&&n<=1103||n===1105||n===8208||n>=8211&&n<=8214||n===8216||n===8217||n===8220||n===8221||n>=8224&&n<=8226||n>=8228&&n<=8231||n===8240||n===8242||n===8243||n===8245||n===8251||n===8254||n===8308||n===8319||n>=8321&&n<=8324||n===8364||n===8451||n===8453||n===8457||n===8467||n===8470||n===8481||n===8482||n===8486||n===8491||n===8531||n===8532||n>=8539&&n<=8542||n>=8544&&n<=8555||n>=8560&&n<=8569||n===8585||n>=8592&&n<=8601||n===8632||n===8633||n===8658||n===8660||n===8679||n===8704||n===8706||n===8707||n===8711||n===8712||n===8715||n===8719||n===8721||n===8725||n===8730||n>=8733&&n<=8736||n===8739||n===8741||n>=8743&&n<=8748||n===8750||n>=8756&&n<=8759||n===8764||n===8765||n===8776||n===8780||n===8786||n===8800||n===8801||n>=8804&&n<=8807||n===8810||n===8811||n===8814||n===8815||n===8834||n===8835||n===8838||n===8839||n===8853||n===8857||n===8869||n===8895||n===8978||n>=9312&&n<=9449||n>=9451&&n<=9547||n>=9552&&n<=9587||n>=9600&&n<=9615||n>=9618&&n<=9621||n===9632||n===9633||n>=9635&&n<=9641||n===9650||n===9651||n===9654||n===9655||n===9660||n===9661||n===9664||n===9665||n>=9670&&n<=9672||n===9675||n>=9678&&n<=9681||n>=9698&&n<=9701||n===9711||n===9733||n===9734||n===9737||n===9742||n===9743||n===9756||n===9758||n===9792||n===9794||n===9824||n===9825||n>=9827&&n<=9829||n>=9831&&n<=9834||n===9836||n===9837||n===9839||n===9886||n===9887||n===9919||n>=9926&&n<=9933||n>=9935&&n<=9939||n>=9941&&n<=9953||n===9955||n===9960||n===9961||n>=9963&&n<=9969||n===9972||n>=9974&&n<=9977||n===9979||n===9980||n===9982||n===9983||n===10045||n>=10102&&n<=10111||n>=11094&&n<=11097||n>=12872&&n<=12879||n>=57344&&n<=63743||n>=65024&&n<=65039||n===65533||n>=127232&&n<=127242||n>=127248&&n<=127277||n>=127280&&n<=127337||n>=127344&&n<=127373||n===127375||n===127376||n>=127387&&n<=127404||n>=917760&&n<=917999||n>=983040&&n<=1048573||n>=1048576&&n<=1114109,Hs=(n)=>n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510,Gs=(n)=>n>=4352&&n<=4447||n===8986||n===8987||n===9001||n===9002||n>=9193&&n<=9196||n===9200||n===9203||n===9725||n===9726||n===9748||n===9749||n>=9800&&n<=9811||n===9855||n===9875||n===9889||n===9898||n===9899||n===9917||n===9918||n===9924||n===9925||n===9934||n===9940||n===9962||n===9970||n===9971||n===9973||n===9978||n===9981||n===9989||n===9994||n===9995||n===10024||n===10060||n===10062||n>=10067&&n<=10069||n===10071||n>=10133&&n<=10135||n===10160||n===10175||n===11035||n===11036||n===11088||n===11093||n>=11904&&n<=11929||n>=11931&&n<=12019||n>=12032&&n<=12245||n>=12272&&n<=12287||n>=12289&&n<=12350||n>=12353&&n<=12438||n>=12441&&n<=12543||n>=12549&&n<=12591||n>=12593&&n<=12686||n>=12688&&n<=12771||n>=12783&&n<=12830||n>=12832&&n<=12871||n>=12880&&n<=19903||n>=19968&&n<=42124||n>=42128&&n<=42182||n>=43360&&n<=43388||n>=44032&&n<=55203||n>=63744&&n<=64255||n>=65040&&n<=65049||n>=65072&&n<=65106||n>=65108&&n<=65126||n>=65128&&n<=65131||n>=94176&&n<=94180||n===94192||n===94193||n>=94208&&n<=100343||n>=100352&&n<=101589||n>=101632&&n<=101640||n>=110576&&n<=110579||n>=110581&&n<=110587||n===110589||n===110590||n>=110592&&n<=110882||n===110898||n>=110928&&n<=110930||n===110933||n>=110948&&n<=110951||n>=110960&&n<=111355||n===126980||n===127183||n===127374||n>=127377&&n<=127386||n>=127488&&n<=127490||n>=127504&&n<=127547||n>=127552&&n<=127560||n===127568||n===127569||n>=127584&&n<=127589||n>=127744&&n<=127776||n>=127789&&n<=127797||n>=127799&&n<=127868||n>=127870&&n<=127891||n>=127904&&n<=127946||n>=127951&&n<=127955||n>=127968&&n<=127984||n===127988||n>=127992&&n<=128062||n===128064||n>=128066&&n<=128252||n>=128255&&n<=128317||n>=128331&&n<=128334||n>=128336&&n<=128359||n===128378||n===128405||n===128406||n===128420||n>=128507&&n<=128591||n>=128640&&n<=128709||n===128716||n>=128720&&n<=128722||n>=128725&&n<=128727||n>=128732&&n<=128735||n===128747||n===128748||n>=128756&&n<=128764||n>=128992&&n<=129003||n===129008||n>=129292&&n<=129338||n>=129340&&n<=129349||n>=129351&&n<=129535||n>=129648&&n<=129660||n>=129664&&n<=129672||n>=129680&&n<=129725||n>=129727&&n<=129733||n>=129742&&n<=129755||n>=129760&&n<=129768||n>=129776&&n<=129784||n>=131072&&n<=196605||n>=196608&&n<=262141,Rr,Dn,In,$r,Kn,Ns,Ps,Uo=(n,r={},o={})=>{let i=r.limit??1/0,s=r.ellipsis??"",c=r?.ellipsisWidth??(s?Uo(s,Ps,o).width:0),a=o.ansiWidth??0,u=o.controlWidth??0,t=o.tabWidth??8,f=o.ambiguousWidth??1,m=o.emojiWidth??2,b=o.fullWidthWidth??2,y=o.regularWidth??1,e=o.wideWidth??2,p=0,d=0,x=n.length,$=0,E=!1,C=x,S=Math.max(0,i-c),_=0,N=0,h=0,R=0;n:for(;;){if(N>_||d>=x&&d>p){let z=n.slice(_,N)||n.slice(p,d);$=0;for(let D of z.replaceAll(Ns,"")){let A=D.codePointAt(0)||0;if(Hs(A)?R=b:Gs(A)?R=e:f!==y&&_s(A)?R=f:R=y,h+R>S&&(C=Math.min(C,Math.max(_,p)+$)),h+R>i){E=!0;break n}$+=D.length,h+=R}_=N=0}if(d>=x)break;if(Kn.lastIndex=d,Kn.test(n)){if($=Kn.lastIndex-d,R=$*y,h+R>S&&(C=Math.min(C,d+Math.floor((S-h)/y))),h+R>i){E=!0;break}h+=R,_=p,N=d,d=p=Kn.lastIndex;continue}if(Rr.lastIndex=d,Rr.test(n)){if(h+a>S&&(C=Math.min(C,d)),h+a>i){E=!0;break}h+=a,_=p,N=d,d=p=Rr.lastIndex;continue}if(Dn.lastIndex=d,Dn.test(n)){if($=Dn.lastIndex-d,R=$*u,h+R>S&&(C=Math.min(C,d+Math.floor((S-h)/u))),h+R>i){E=!0;break}h+=R,_=p,N=d,d=p=Dn.lastIndex;continue}if(In.lastIndex=d,In.test(n)){if($=In.lastIndex-d,R=$*t,h+R>S&&(C=Math.min(C,d+Math.floor((S-h)/t))),h+R>i){E=!0;break}h+=R,_=p,N=d,d=p=In.lastIndex;continue}if($r.lastIndex=d,$r.test(n)){if(h+m>S&&(C=Math.min(C,d)),h+m>i){E=!0;break}h+=m,_=p,N=d,d=p=$r.lastIndex;continue}d+=1}return{width:E?S:h,index:E?C:x,truncated:E,ellipsed:E&&i>=c}},Us,_n=(n,r={})=>Uo(n,Us,r).width,Tn="\x1B",Mo="\x9B",Ms=39,_r="\x07",Lo="[",Ls="]",jo="m",Hr,_o,js=(n)=>{if(n>=30&&n<=37||n>=90&&n<=97)return 39;if(n>=40&&n<=47||n>=100&&n<=107)return 49;if(n===1||n===2)return 22;if(n===3)return 23;if(n===4)return 24;if(n===7)return 27;if(n===8)return 28;if(n===9)return 29;if(n===0)return 0},Ho=(n)=>`${Tn}${Lo}${n}${jo}`,Go=(n)=>`${Tn}${Hr}${n}${_r}`,qs=(n)=>n.map((r)=>_n(r)),Er=(n,r,o)=>{let i=r[Symbol.iterator](),s=!1,c=!1,a=n.at(-1),u=a===void 0?0:_n(a),t=i.next(),f=i.next(),m=0;for(;!t.done;){let b=t.value,y=_n(b);u+y<=o?n[n.length-1]+=b:(n.push(b),u=0),(b===Tn||b===Mo)&&(s=!0,c=r.startsWith(Hr,m+1)),s?c?b===_r&&(s=!1,c=!1):b===jo&&(s=!1):(u+=y,u===o&&!f.done&&(n.push(""),u=0)),t=f,f=i.next(),m+=b.length}a=n.at(-1),!u&&a!==void 0&&a.length>0&&n.length>1&&(n[n.length-2]+=n.pop())},Bs=(n)=>{let r=n.split(" "),o=r.length;for(;o>0&&!(_n(r[o-1])>0);)o--;return o===r.length?n:r.slice(0,o).join(" ")+r.slice(o).join("")},Vs=(n,r,o={})=>{if(o.trim!==!1&&n.trim()==="")return"";let i="",s,c,a=n.split(" "),u=qs(a),t=[""];for(let[p,d]of a.entries()){o.trim!==!1&&(t[t.length-1]=(t.at(-1)??"").trimStart());let x=_n(t.at(-1)??"");if(p!==0&&(x>=r&&(o.wordWrap===!1||o.trim===!1)&&(t.push(""),x=0),(x>0||o.trim===!1)&&(t[t.length-1]+=" ",x++)),o.hard&&u[p]>r){let $=r-x,E=1+Math.floor((u[p]-$-1)/r);Math.floor((u[p]-1)/r)<E&&t.push(""),Er(t,d,r);continue}if(x+u[p]>r&&x>0&&u[p]>0){if(o.wordWrap===!1&&x<r){Er(t,d,r);continue}t.push("")}if(x+u[p]>r&&o.wordWrap===!1){Er(t,d,r);continue}t[t.length-1]+=d}o.trim!==!1&&(t=t.map((p)=>Bs(p)));let f=t.join(`
|
|
21
|
+
`),m=f[Symbol.iterator](),b=m.next(),y=m.next(),e=0;for(;!b.done;){let p=b.value,d=y.value;if(i+=p,p===Tn||p===Mo){_o.lastIndex=e+1;let $=_o.exec(f)?.groups;if($?.code!==void 0){let E=Number.parseFloat($.code);s=E===Ms?void 0:E}else $?.uri!==void 0&&(c=$.uri.length===0?void 0:$.uri)}let x=s?js(s):void 0;d===`
|
|
22
|
+
`?(c&&(i+=Go("")),s&&x&&(i+=Ho(x))):p===`
|
|
23
|
+
`&&(s&&x&&(i+=Ho(s)),c&&(i+=Go(c))),e+=p.length,b=y,y=m.next()}return i},zs=(n,r,o,i,s)=>{let c=r,a=0;for(let u=o;u<i;u++){let t=n[u];if(c=c-t.length,a++,c<=s)break}return{lineCount:c,removals:a}},As=(n)=>{let{cursor:r,options:o,style:i}=n,s=n.output??process.stdout,c=gr(s),a=n.columnPadding??0,u=n.rowPadding??4,t=c-a,f=Co(s),m=g.default.dim("..."),b=n.maxItems??Number.POSITIVE_INFINITY,y=Math.max(f-u,0),e=Math.max(Math.min(b,y),5),p=0;r>=e-3&&(p=Math.max(Math.min(r-e+3,o.length-e),0));let d=e<o.length&&p>0,x=e<o.length&&p+e<o.length,$=Math.min(p+e,o.length),E=[],C=0;d&&C++,x&&C++;let S=p+(d?1:0),_=$-(x?1:0);for(let h=S;h<_;h++){let R=Or(i(o[h],h===r),t,{hard:!0,trim:!1}).split(`
|
|
24
|
+
`);E.push(R),C+=R.length}if(C>y){let h=0,R=0,z=C,D=r-S,A=(Nn,j)=>zs(E,z,Nn,j,y);d?({lineCount:z,removals:h}=A(0,D),z>y&&({lineCount:z,removals:R}=A(D+1,E.length))):({lineCount:z,removals:R}=A(D+1,E.length),z>y&&({lineCount:z,removals:h}=A(0,D))),h>0&&(d=!0,E.splice(0,h)),R>0&&(x=!0,E.splice(E.length-R,R))}let N=[];d&&N.push(m);for(let h of E)for(let R of h)N.push(R);return x&&N.push(m),N},V=(n)=>{let r=n.active??"Yes",o=n.inactive??"No";return new So({active:r,inactive:o,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue??!0,render(){let i=`${g.default.gray(M)}
|
|
25
|
+
${kr(this.state)} ${n.message}
|
|
26
|
+
`,s=this.value?r:o;switch(this.state){case"submit":return`${i}${g.default.gray(M)} ${g.default.dim(s)}`;case"cancel":return`${i}${g.default.gray(M)} ${g.default.strikethrough(g.default.dim(s))}
|
|
27
|
+
${g.default.gray(M)}`;default:return`${i}${g.default.cyan(M)} ${this.value?`${g.default.green(Cr)} ${r}`:`${g.default.dim(Wn)} ${g.default.dim(r)}`} ${g.default.dim("/")} ${this.value?`${g.default.dim(Wn)} ${g.default.dim(o)}`:`${g.default.green(Cr)} ${o}`}
|
|
28
|
+
${g.default.cyan(hn)}
|
|
29
|
+
`}}}).prompt()},qo=async(n,r)=>{let o={},i=Object.keys(n);for(let s of i){let c=n[s],a=await c({results:o})?.catch((u)=>{throw u});if(typeof r?.onCancel=="function"&&B(a)){o[s]="canceled",r.onCancel({results:o});continue}o[s]=a}return o},w,Gr=(n="",r)=>{(r?.output??process.stdout).write(`${g.default.gray(hn)} ${g.default.red(n)}
|
|
35
30
|
|
|
36
|
-
`)},
|
|
37
|
-
`)},
|
|
38
|
-
${
|
|
31
|
+
`)},Nr=(n="",r)=>{(r?.output??process.stdout).write(`${g.default.gray(es)} ${n}
|
|
32
|
+
`)},Pr=(n="",r)=>{(r?.output??process.stdout).write(`${g.default.gray(M)}
|
|
33
|
+
${g.default.gray(hn)} ${n}
|
|
39
34
|
|
|
40
|
-
`)},
|
|
41
|
-
`);let
|
|
42
|
-
`);
|
|
43
|
-
`);let
|
|
44
|
-
`):
|
|
45
|
-
`),h(),
|
|
46
|
-
|
|
35
|
+
`)},Ds,rn=({indicator:n="dots",onCancel:r,output:o=process.stdout,cancelMessage:i,errorMessage:s,frames:c=er?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:a=er?80:120,signal:u,...t}={})=>{let f=$s(),m,b,y=!1,e=!1,p="",d,x=performance.now(),$=gr(o),E=t?.styleFrame??Ds,C=(j)=>{let K=j>1?s??cn.messages.error:i??cn.messages.cancel;e=j===1,y&&(Nn(K,j),e&&typeof r=="function"&&r())},S=()=>C(2),_=()=>C(1),N=()=>{process.on("uncaughtExceptionMonitor",S),process.on("unhandledRejection",S),process.on("SIGINT",_),process.on("SIGTERM",_),process.on("exit",C),u&&u.addEventListener("abort",_)},h=()=>{process.removeListener("uncaughtExceptionMonitor",S),process.removeListener("unhandledRejection",S),process.removeListener("SIGINT",_),process.removeListener("SIGTERM",_),process.removeListener("exit",C),u&&u.removeEventListener("abort",_)},R=()=>{if(d===void 0)return;f&&o.write(`
|
|
36
|
+
`);let j=Or(d,$,{hard:!0,trim:!1}).split(`
|
|
37
|
+
`);j.length>1&&o.write(kn.cursor.up(j.length-1)),o.write(kn.cursor.to(0)),o.write(kn.erase.down())},z=(j)=>j.replace(/\.+$/,""),D=(j)=>{let K=(performance.now()-j)/1000,v=Math.floor(K/60),gn=Math.floor(K%60);return v>0?`[${v}m ${gn}s]`:`[${gn}s]`},A=(j="")=>{y=!0,m=eo({output:o}),p=z(j),x=performance.now(),o.write(`${g.default.gray(M)}
|
|
38
|
+
`);let K=0,v=0;N(),b=setInterval(()=>{if(f&&p===d)return;R(),d=p;let gn=E(c[K]),Pn;if(f)Pn=`${gn} ${p}...`;else if(n==="timer")Pn=`${gn} ${p} ${D(x)}`;else{let Ii=".".repeat(Math.floor(v)).slice(0,3);Pn=`${gn} ${p}${Ii}`}let Di=Or(Pn,$,{hard:!0,trim:!1});o.write(Di),K=K+1<c.length?K+1:0,v=v<4?v+0.125:0},a)},Nn=(j="",K=0)=>{if(!y)return;y=!1,clearInterval(b),R();let v=K===0?g.default.green(Sr):K===1?g.default.red(No):g.default.red(Po);p=j??p,n==="timer"?o.write(`${v} ${p} ${D(x)}
|
|
39
|
+
`):o.write(`${v} ${p}
|
|
40
|
+
`),h(),m()};return{start:A,stop:Nn,message:(j="")=>{p=z(j??p)},get isCancelled(){return e}}},Ka,tn=(n)=>{let r=(o,i)=>{let s=o.label??String(o.value);switch(i){case"disabled":return`${g.default.gray(Wn)} ${g.default.gray(s)}${o.hint?` ${g.default.dim(`(${o.hint??"disabled"})`)}`:""}`;case"selected":return`${g.default.dim(s)}`;case"active":return`${g.default.green(Cr)} ${s}${o.hint?` ${g.default.dim(`(${o.hint})`)}`:""}`;case"cancelled":return`${g.default.strikethrough(g.default.dim(s))}`;default:return`${g.default.dim(Wn)} ${g.default.dim(s)}`}};return new lr({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue,render(){let o=`${g.default.gray(M)}
|
|
41
|
+
${kr(this.state)} ${n.message}
|
|
42
|
+
`;switch(this.state){case"submit":return`${o}${g.default.gray(M)} ${r(this.options[this.cursor],"selected")}`;case"cancel":return`${o}${g.default.gray(M)} ${r(this.options[this.cursor],"cancelled")}
|
|
43
|
+
${g.default.gray(M)}`;default:{let i=`${g.default.cyan(M)} `;return`${o}${i}${As({output:n.output,cursor:this.cursor,options:this.options,maxItems:n.maxItems,columnPadding:i.length,style:(s,c)=>r(s,s.disabled?"disabled":c?"active":"inactive")}).join(`
|
|
44
|
+
${i}`)}
|
|
45
|
+
${g.default.cyan(hn)}
|
|
46
|
+
`}}}}).prompt()},Wa,P=(n)=>new hr({validate:n.validate,placeholder:n.placeholder,defaultValue:n.defaultValue,initialValue:n.initialValue,output:n.output,signal:n.signal,input:n.input,render(){let r=`${g.default.gray(M)}
|
|
47
|
+
${kr(this.state)} ${n.message}
|
|
48
|
+
`,o=n.placeholder?g.default.inverse(n.placeholder[0])+g.default.dim(n.placeholder.slice(1)):g.default.inverse(g.default.hidden("_")),i=this.userInput?this.userInputWithCursor:o,s=this.value??"";switch(this.state){case"error":{let c=this.error?` ${g.default.yellow(this.error)}`:"";return`${r.trim()}
|
|
49
|
+
${g.default.yellow(M)} ${i}
|
|
50
|
+
${g.default.yellow(hn)}${c}
|
|
51
|
+
`}case"submit":{let c=s?` ${g.default.dim(s)}`:"";return`${r}${g.default.gray(M)}${c}`}case"cancel":{let c=s?` ${g.default.strikethrough(g.default.dim(s))}`:"";return`${r}${g.default.gray(M)}${c}${s.trim()?`
|
|
52
|
+
${g.default.gray(M)}`:""}`}default:return`${r}${g.default.cyan(M)} ${i}
|
|
53
|
+
${g.default.cyan(hn)}
|
|
54
|
+
`}}}).prompt();var I=O(()=>{xr();xr();g=Cn(ar(),1),kn=Cn(ur(),1);er=Rs(),Es=H("\u25C6","*"),No=H("\u25A0","x"),Po=H("\u25B2","x"),Sr=H("\u25C7","o"),es=H("\u250C","T"),M=H("\u2502","|"),hn=H("\u2514","\u2014"),Pa=H("\u2510","T"),Ua=H("\u2518","\u2014"),Cr=H("\u25CF",">"),Wn=H("\u25CB"," "),Ma=H("\u25FB","[\u2022]"),La=H("\u25FC","[+]"),ja=H("\u25FB","[ ]"),qa=H("\u25AA","\u2022"),Ba=H("\u2500","-"),Va=H("\u256E","+"),za=H("\u251C","+"),Aa=H("\u256F","+"),Da=H("\u2570","+"),Ia=H("\u256D","+"),Cs=H("\u25CF","\u2022"),Os=H("\u25C6","*"),Ss=H("\u25B2","!"),ks=H("\u25A0","x"),Rr=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Dn=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,In=/\t{1,1000}/y,$r=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Kn=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ns=/\p{M}+/gu,Ps={limit:1/0,ellipsis:""},Us={limit:1/0,ellipsis:"",ellipsisWidth:0},Hr=`${Ls}8;;`,_o=new RegExp(`(?:\\${Lo}(?<code>\\d+)m|\\${Hr}(?<uri>.*)${_r})`,"y");w={message:(n=[],{symbol:r=g.default.gray(M),secondarySymbol:o=g.default.gray(M),output:i=process.stdout,spacing:s=1}={})=>{let c=[];for(let u=0;u<s;u++)c.push(`${o}`);let a=Array.isArray(n)?n:n.split(`
|
|
55
|
+
`);if(a.length>0){let[u,...t]=a;u.length>0?c.push(`${r} ${u}`):c.push(r);for(let f of t)f.length>0?c.push(`${o} ${f}`):c.push(o)}i.write(`${c.join(`
|
|
47
56
|
`)}
|
|
48
|
-
`)},info:(r)=>{
|
|
49
|
-
`)}function
|
|
50
|
-
`)}var yt=I(()=>{Xr()});var ht=I(()=>{P()});async function Cr(r,n={}){let t={...co,...n},o=new Error("Operation failed");for(let e=1;e<=t.maxAttempts;e++)try{return await r()}catch(s){if(o=s instanceof Error?s:new Error(String(s)),!t.retryableErrors.some((f)=>o.message.toLowerCase().includes(f.toLowerCase()))||e===t.maxAttempts)throw o;t.onRetry(e,o);let a=Math.min(t.initialDelay*t.backoffMultiplier**(e-1),t.maxDelay);await new Promise((f)=>setTimeout(f,a))}throw o}var co;var Rt=I(()=>{P();co={backoffMultiplier:2,initialDelay:1000,maxAttempts:3,maxDelay:30000,onRetry:(r,n)=>{Yr.warn(`Retry attempt ${r}: ${n.message}`)},retryableErrors:["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","rate limit","429","503","502","504","npm ERR!","EPUBLISHCONFLICT"]}});import{homedir as mo}from"os";import{join as gt}from"path";var uo,Qs;var wt=I(()=>{uo=gt(mo(),".r5n","cache"),Qs=gt(uo,"update-check.json")});var Y=(r)=>{return r.map=(n)=>Y((t)=>n(r(t))),r.or=(n)=>Y((t)=>{try{return r(t)}catch(o){return n(t)}}),r},Wr=()=>"bad banditype"(),bt=(r)=>Y((n)=>r.includes(n)?n:Wr()),Gr=(r)=>Y((n)=>typeof n===typeof r?n:Wr()),br=()=>Gr(""),Et=()=>Gr(0),xt=()=>Gr(!0),$t=()=>Gr(),_t=(r)=>Y((n)=>n instanceof r?n:Wr()),wn=(r)=>_t(Object).map((n)=>{let t={};for(let o in n){let e=r(n[o]);e!==void 0&&(t[o]=e)}return t}),ur=(r)=>_t(Object).map((n)=>{let t={};for(let o in r){let e=r[o](n[o]);e!==void 0&&(t[o]=e)}return t});function po(r,n){return Y((t)=>{try{return r(t)}catch{try{return n(t)}catch{throw new Error("No matching schema in union")}}})}function ir(r,n){return(t)=>{if(t===void 0)return n;return r(t)}}function Ot(){return Y((r)=>{let n=Et()(r);if(!Number.isInteger(n)||n<=0)throw new Error("Must be a positive integer");return n})}function kt(){return Y((r)=>{let n=br()(r);try{return new URL(n),n}catch{throw new Error("Must be a valid URL")}})}function vt(r,n){return Y((t)=>{let o=br()(t);if(!r.test(o))throw new Error(n||`Must match pattern ${r}`);return o})}function Er(r){return{parse(n){try{return r(n)}catch(t){throw new Error(t instanceof Error?t.message:"Validation failed")}},safeParse(n){try{return{data:r(n),success:!0}}catch(t){return{error:t instanceof Error?t:new Error("Validation failed"),success:!1}}},validator:r}}function F(){return po($t(),br())}function or(r){return ir(br(),r)}function pr(r){return ir(xt(),r)}function Mr(r,n){return ir(bt(r),n)}var Tt=()=>{};var Nt=()=>{};var G=I(()=>{Xr();ft();gn();ct();ut();yt();ht();Rt();wt();Tt();Nt()});var Z={};hi(Z,{help:()=>Br});function Br(r){if(r&&Vt[r]){console.info(pt(Vt[r]));return}let n=[{description:"Initialize a new Hydra configuration file",name:"init"},{description:"Create and register new GitHub runner machines",name:"create"},{description:"Check runner health and diagnose issues",name:"health"},{description:"Remove GitHub runner machines",name:"remove"},{description:"Start existing GitHub runner machines",name:"run"},{description:"Check the status of GitHub runner machines",name:"status"},{description:"Generate runner configuration templates",name:"template"},{description:"Validate configuration file",name:"validate"},{description:"Watch and auto-restart runners on failure",name:"watch"},{description:"Migrate configuration to latest format",name:"migrate"},{description:"Run performance benchmarks to test CLI performance",name:"benchmark"},{description:"Show this help message",name:"help"}];console.info(lt(`Hydra@${kr} - GitHub self-hosted runner manager`,"hydra <command> [options]",n,"Use hydra <command> --help for more information about a command."))}var Vt;var j=I(()=>{G();Zr();Vt={benchmark:{description:"Run performance benchmarks to test CLI performance",examples:[{command:"hydra benchmark",description:"Run full benchmark suite"},{command:"hydra benchmark --quick",description:"Run quick benchmark (1 iteration)"},{command:"hydra benchmark --startup-only",description:"Test only CLI startup time"},{command:"hydra benchmark --memory-only",description:"Test only memory usage"},{command:"hydra benchmark --worker-only",description:"Test only worker spawn performance"},{command:"hydra benchmark --iterations=10",description:"Run with 10 iterations"}],name:"hydra benchmark",notes:["Tests startup time, worker spawn time, memory usage, and command execution","Targets: startup <100ms, worker spawn <50ms, memory <100MB","Exit code 0 if score \u226570%, 1 if performance is below threshold"],options:[{description:"Number of benchmark iterations",flags:"--iterations",type:"number"},{description:"Number of workers to test",flags:"--workers",type:"number"},{description:"Test only CLI startup time",flags:"--startup-only",type:"boolean"},{description:"Test only memory usage",flags:"--memory-only",type:"boolean"},{description:"Test only worker spawn performance",flags:"--worker-only",type:"boolean"},{description:"Run quick benchmark (1 iteration)",flags:"--quick",type:"boolean"}],usage:"hydra benchmark [options]"},create:{description:"Create and register new GitHub runner machines",examples:[{command:"hydra create -t TOKEN -u https://github.com/org/repo",description:"Create a single runner"},{command:"hydra create -t TOKEN -u URL -m 3",description:"Create 3 runners"},{command:"hydra create -t TOKEN -u URL -l docker,gpu",description:"Create runner with labels"},{command:"hydra create -p production",description:"Create using production profile"}],name:"hydra create",notes:["Requires a GitHub personal access token with repo scope","Creates runners in ./gh-runners by default","Use --run to immediately start runners after creation"],options:[{description:"GitHub personal access token",flags:"-t, --token",type:"string"},{description:"Repository or organization URL",flags:"-u, --url",type:"string"},{description:"Runner name prefix",flags:"-n, --name",type:"string"},{description:"Number of machines to create",flags:"-m, --numberOfMachines",type:"number"},{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Runner labels (comma-separated)",flags:"-l, --labels",type:"string"},{description:"Runner group",flags:"-g, --runnerGroup",type:"string"},{description:"Operating system",flags:"-s, --os",type:"string"},{description:"Overwrite existing runners",flags:"-f, --overwrite",type:"boolean"},{description:"Start runners after creation",flags:"-r, --run",type:"boolean"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra create [options]"},health:{description:"Check runner health and diagnose issues",examples:[{command:"hydra health",description:"Check health of all runners"},{command:"hydra health --fix",description:"Auto-fix common issues"},{command:"hydra health -p production",description:"Check health using profile"}],name:"hydra health",notes:["Checks runner registration, connectivity, and configuration","Use --fix to automatically resolve common issues","Exit code 0 if healthy, 1 if issues found"],options:[{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Auto-fix common issues",flags:"--fix",type:"boolean"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra health [options]"},init:{description:"Initialize a new Hydra configuration file",examples:[{command:"hydra init",description:"Create hydra.json interactively"},{command:"hydra init --toml",description:"Create hydra.toml instead"}],name:"hydra init",options:[{description:"Use TOML format instead of JSON",flags:"--toml",type:"boolean"}],usage:"hydra init [options]"},migrate:{description:"Migrate configuration to latest format",examples:[{command:"hydra migrate",description:"Migrate configuration"},{command:"hydra migrate --dry-run",description:"Preview changes without applying"}],name:"hydra migrate",options:[{description:"Preview changes without applying",flags:"--dry-run",type:"boolean"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra migrate [options]"},remove:{description:"Remove GitHub runner machines",examples:[{command:"hydra remove -t TOKEN -u https://github.com/org/repo",description:"Remove all runners"},{command:"hydra remove -t TOKEN -u URL -m 2",description:"Remove 2 runners"},{command:"hydra remove -t TOKEN -u URL --force",description:"Force remove without confirmation"},{command:"hydra remove -p production",description:"Remove using production profile"}],name:"hydra remove",notes:["Requires a GitHub personal access token with repo scope","Removes runners from GitHub and deletes local files","Use --force to skip confirmation prompt"],options:[{description:"GitHub personal access token",flags:"-t, --token",type:"string"},{description:"Repository or organization URL",flags:"-u, --url",type:"string"},{description:"Number of machines to remove",flags:"-m, --numberOfMachines",type:"number"},{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Force removal without confirmation",flags:"-f, --force",type:"boolean"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra remove [options]"},run:{description:"Start existing GitHub runner machines",examples:[{command:"hydra run -t TOKEN -u https://github.com/org/repo",description:"Start all runners"},{command:"hydra run -t TOKEN -u URL -m 2",description:"Start 2 runners"},{command:"hydra run -p production",description:"Start using production profile"}],name:"hydra run",notes:["Requires a GitHub personal access token with repo scope","Runners must be created first using 'hydra create'","Runs in foreground, use Ctrl+C to stop"],options:[{description:"GitHub personal access token",flags:"-t, --token",type:"string"},{description:"Repository or organization URL",flags:"-u, --url",type:"string"},{description:"Runner name prefix",flags:"-n, --name",type:"string"},{description:"Number of machines to run",flags:"-m, --numberOfMachines",type:"number"},{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Runner labels (comma-separated)",flags:"-l, --labels",type:"string"},{description:"Runner group",flags:"-g, --runnerGroup",type:"string"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra run [options]"},status:{description:"Check the status of GitHub runner machines",examples:[{command:"hydra status",description:"Show status of all runners"},{command:"hydra status --json",description:"Output status as JSON"},{command:"hydra status -p production",description:"Check status using profile"}],name:"hydra status",notes:["Shows runner registration status and current state","Use --json for machine-readable output"],options:[{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Output as JSON",flags:"--json",type:"boolean"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra status [options]"},template:{description:"Generate runner configuration templates",examples:[{command:"hydra template",description:"Generate default template"},{command:"hydra template --type docker",description:"Generate Docker runner template"}],name:"hydra template",options:[{description:"Template type",flags:"--type",type:"string"},{description:"Output file path",flags:"-o, --output",type:"string"}],usage:"hydra template [options]"},validate:{description:"Validate configuration file",examples:[{command:"hydra validate",description:"Validate hydra.json"},{command:"hydra validate -c custom.toml",description:"Validate custom config file"}],name:"hydra validate",options:[{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra validate [options]"},watch:{description:"Watch and auto-restart runners on failure",examples:[{command:"hydra watch",description:"Watch all runners"},{command:"hydra watch -p production",description:"Watch using profile"}],name:"hydra watch",notes:["Monitors runners and restarts them if they fail","Runs in foreground, use Ctrl+C to stop"],options:[{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra watch [options]"}}});Zr();class Rr extends Error{code;severity;context;originalError;timestamp;recoveryStrategy;constructor(r,n,t="medium",o={},e){super(r);if(this.name="HydraError",this.code=n,this.severity=t,this.context=o,this.originalError=e,this.timestamp=new Date,this.recoveryStrategy=w.getRecoveryStrategy(n),e?.stack)this.stack=`${this.stack}
|
|
51
|
-
Caused by: ${e.stack}`}toJSON(){return{code:this.code,context:this.context,message:this.message,name:this.name,originalError:this.originalError?.message,recoveryStrategy:this.recoveryStrategy,severity:this.severity,timestamp:this.timestamp.toISOString()}}}class w{static instance=null;errorHistory=[];maxHistorySize=100;constructor(){}static getInstance(){if(!w.instance)w.instance=new w;return w.instance}static getRecoveryStrategy(r){switch(r){case"NETWORK_ERROR":return{canRecover:!0,maxRetries:3,recoveryAction:"retry_with_backoff",retryable:!0,retryDelay:2000,userAction:"Check your network connection and try again"};case"CONFIG_ERROR":return{canRecover:!0,retryable:!1,userAction:"Fix the configuration file and try again. Use 'hydra validate' to check your config"};case"VALIDATION_ERROR":return{canRecover:!0,retryable:!1,userAction:"Correct the validation errors and try again"};case"FILE_SYSTEM_ERROR":return{canRecover:!0,retryable:!1,userAction:"Check file permissions and disk space, then try again"};case"AUTHENTICATION_ERROR":return{canRecover:!0,retryable:!1,userAction:"Check your GitHub token and repository permissions"};case"WORKER_ERROR":return{canRecover:!0,maxRetries:2,recoveryAction:"restart_worker",retryable:!0,retryDelay:1000,userAction:"Worker will be restarted automatically"};case"GITHUB_API_ERROR":return{canRecover:!0,maxRetries:3,recoveryAction:"retry_with_exponential_backoff",retryable:!0,retryDelay:5000,userAction:"GitHub API rate limit may be exceeded. Please wait and try again"};case"TEMPLATE_ERROR":return{canRecover:!0,retryable:!1,userAction:"Check template syntax and dependencies, then try again"};case"MIGRATION_ERROR":return{canRecover:!1,retryable:!1,userAction:"Manual intervention required. Check migration logs and contact support"};case"RUNNER_ERROR":return{canRecover:!0,maxRetries:2,recoveryAction:"recreate_runner",retryable:!0,retryDelay:3000,userAction:"Runner will be recreated automatically"};case"PERMISSION_ERROR":return{canRecover:!0,retryable:!1,userAction:"Check file/directory permissions and run with appropriate privileges"};case"DEPENDENCY_ERROR":return{canRecover:!0,retryable:!1,userAction:"Install missing dependencies and try again"};case"COMMAND_ERROR":return{canRecover:!0,retryable:!1,userAction:"Check command syntax and arguments, then try again"};default:return{canRecover:!1,retryable:!1,userAction:"An unexpected error occurred. Please report this issue"}}}static createError(r,n,t="medium",o={},e){return new Rr(r,n,t,o,e)}static handleError(r,n={}){let t=w.getInstance();if(r instanceof Rr)return t.recordError(r),r;let o;if(r instanceof Error){let e=w.classifyError(r),s=w.getSeverityFromCode(e);o=new Rr(r.message,e,s,n,r)}else o=new Rr(String(r),"UNKNOWN_ERROR","medium",n);return t.recordError(o),o}static classifyError(r){let n=r.message.toLowerCase(),t=r.stack?.toLowerCase()||"";if(n.includes("network")||n.includes("connection")||n.includes("timeout"))return"NETWORK_ERROR";if(n.includes("config")||n.includes("configuration"))return"CONFIG_ERROR";if(n.includes("validation")||n.includes("invalid")||n.includes("schema"))return"VALIDATION_ERROR";if(n.includes("enoent")||n.includes("permission")||n.includes("access denied"))return"FILE_SYSTEM_ERROR";if(n.includes("auth")||n.includes("token")||n.includes("unauthorized"))return"AUTHENTICATION_ERROR";if(n.includes("worker")||t.includes("worker"))return"WORKER_ERROR";if(n.includes("github")||n.includes("api")||n.includes("rate limit"))return"GITHUB_API_ERROR";if(n.includes("template"))return"TEMPLATE_ERROR";if(n.includes("migration")||n.includes("migrate"))return"MIGRATION_ERROR";if(n.includes("runner"))return"RUNNER_ERROR";if(n.includes("permission")||n.includes("eperm"))return"PERMISSION_ERROR";if(n.includes("dependency")||n.includes("missing")||n.includes("not found"))return"DEPENDENCY_ERROR";if(n.includes("command")||n.includes("unknown"))return"COMMAND_ERROR";return"UNKNOWN_ERROR"}static getSeverityFromCode(r){switch(r){case"MIGRATION_ERROR":case"PERMISSION_ERROR":return"critical";case"AUTHENTICATION_ERROR":case"CONFIG_ERROR":case"DEPENDENCY_ERROR":return"high";case"NETWORK_ERROR":case"GITHUB_API_ERROR":case"WORKER_ERROR":case"RUNNER_ERROR":return"medium";default:return"low"}}static formatError(r){let{code:n,message:t,severity:o,context:e,recoveryStrategy:s}=r,i=`\u274C ${t}`;if(e.command)i+=`
|
|
52
|
-
Command: ${e.command}`;if(e.operation)i+=`
|
|
53
|
-
Operation: ${e.operation}`;if(e.profile)i+=`
|
|
54
|
-
Profile: ${e.profile}`;if(e.directory)i+=`
|
|
55
|
-
Directory: ${e.directory}`;if(e.machineIndex!==void 0)i+=`
|
|
56
|
-
Machine: ${e.machineIndex}`;if(i+=`
|
|
57
|
-
Code: ${n}`,i+=`
|
|
58
|
-
Severity: ${o.toUpperCase()}`,s.userAction)i+=`
|
|
59
|
-
|
|
60
|
-
\uD83D\uDCA1 ${s.userAction}`;return i}static formatDebugError(r){return JSON.stringify(r.toJSON(),null,2)}recordError(r){if(this.errorHistory.unshift(r),this.errorHistory.length>this.maxHistorySize)this.errorHistory=this.errorHistory.slice(0,this.maxHistorySize)}getErrorHistory(){return[...this.errorHistory]}getErrorStats(){return this.errorHistory.reduce((r,n)=>{return r[n.code]=(r[n.code]||0)+1,r},{})}clearHistory(){this.errorHistory=[]}}import{dirname as go,join as wo}from"path";import{fileURLToPath as bo}from"url";import{parseArgs as Eo}from"util";import{performance as lr}from"perf_hooks";P();G();function Ur(){let r=import.meta.path,n=r.substring(0,r.lastIndexOf("/"));return n.substring(0,n.lastIndexOf("/"))}var lo=ur({directory:or(`${process.cwd()}/gh-runners`),labels:F(),name:or("runner"),numberOfMachines:ir(vt(/^\d+$/,"Number of machines must be a positive integer"),"1"),os:Mr(["osx","linux","windows"],"osx"),overwrite:pr(!1),run:pr(!1),token:or(process.env.GITHUB_PERSONAL_ACCESS_TOKEN??""),url:kt()}),wa=Er(lo);function U(r){return r.replace(/[^a-zA-Z0-9\-_./\s]/g,"")}function It(r,n){let t=r;for(let o of n)if(o&&o.length>0){let e=o.length>8?`${o.slice(0,2)}${"*".repeat(o.length-4)}${o.slice(-2)}`:"*".repeat(o.length),s=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replace(new RegExp(s,"g"),e)}return t=t.replace(/ghp_[a-zA-Z0-9]{36}/g,"ghp_************************************"),t=t.replace(/github_pat_[a-zA-Z0-9_]{82}/g,"github_pat_**********************************"),t=t.replace(/\b[A-Z]{20,}\b/g,(o)=>{return`${o.slice(0,2)}${"*".repeat(o.length-4)}${o.slice(-2)}`}),t}function x({prefix:r,secrets:n=[]}){let t=k({prefix:r}),o=[...n];if(process.env.GITHUB_TOKEN)o.push(process.env.GITHUB_TOKEN);if(process.env.RUNNER_TOKEN)o.push(process.env.RUNNER_TOKEN);if(process.env.RUNNER_CFG_PAT)o.push(process.env.RUNNER_CFG_PAT);let e=(s)=>{if(typeof s==="string")return It(s,o);if(typeof s==="object"&&s!==null){let i=Array.isArray(s)?[]:{};for(let a in s)i[a]=e(s[a]);return i}return s};return{...t,addSecret:(s)=>{if(s&&!o.includes(s))o.push(s)},child:(s)=>x({prefix:`${r}:${s}`,secrets:o}),debug:(...s)=>t.debug(...s.map(e)),error:(...s)=>t.error(...s.map(e)),info:(...s)=>t.info(...s.map(e)),warn:(...s)=>t.warn(...s.map(e))}}class Pr{metrics={};startTimes=new Map;logger=x({prefix:"Performance"});thresholds;defaultThresholds={commandExecutionTime:5000,memoryUsage:104857600,startupTime:100,workerSpawnTime:50};constructor(r={}){this.thresholds={...this.defaultThresholds,...r}}startTimer(r){this.startTimes.set(r,lr.now())}endTimer(r){let n=this.startTimes.get(r);if(!n)throw new Error(`Timer ${r} was not started`);let t=lr.now()-n;return this.startTimes.delete(r),t}measureStartupTime(){let r=lr.now()-process.uptime()*1000;return this.metrics.startupTime=r,this.logger.debug(`Startup time: ${r.toFixed(2)}ms`),r}measureWorkerSpawn(r){return new Promise((n)=>{let t=lr.now();setTimeout(()=>{let e=lr.now()-t;if(!this.metrics.workerSpawnTimes)this.metrics.workerSpawnTimes=[];this.metrics.workerSpawnTimes.push(e),this.logger.debug(`Worker ${r} spawn time: ${e.toFixed(2)}ms`),n(e)},0)})}measureMemoryUsage(){let r=process.memoryUsage();this.metrics.memoryUsage=r;let n=(r.heapUsed/1024/1024).toFixed(2),t=(r.rss/1024/1024).toFixed(2);return this.logger.debug(`Memory usage - Heap: ${n}MB, RSS: ${t}MB`),r}async measureCommandExecution(r,n){this.startTimer(`command_${r}`);try{let t=await n(),o=this.endTimer(`command_${r}`);return this.metrics.commandExecutionTime=o,this.logger.debug(`Command ${r} execution time: ${o.toFixed(2)}ms`),{executionTime:o,result:t}}catch(t){throw this.endTimer(`command_${r}`),t}}getMetrics(){return{commandExecutionTime:this.metrics.commandExecutionTime||0,memoryUsage:this.metrics.memoryUsage||process.memoryUsage(),startupTime:this.metrics.startupTime||0,timestamp:Date.now(),workerSpawnTimes:this.metrics.workerSpawnTimes||[]}}generateReport(){let r=this.getMetrics(),n=[];if(n.push({name:"Startup Time",passed:r.startupTime<=this.thresholds.startupTime,threshold:this.thresholds.startupTime,unit:"ms",value:r.startupTime}),r.workerSpawnTimes.length>0){let s=r.workerSpawnTimes.reduce((a,f)=>a+f,0)/r.workerSpawnTimes.length,i=Math.max(...r.workerSpawnTimes);n.push({name:"Average Worker Spawn Time",passed:s<=this.thresholds.workerSpawnTime,threshold:this.thresholds.workerSpawnTime,unit:"ms",value:s}),n.push({name:"Max Worker Spawn Time",passed:i<=this.thresholds.workerSpawnTime*2,threshold:this.thresholds.workerSpawnTime*2,unit:"ms",value:i})}if(n.push({name:"Memory Usage (Heap Used)",passed:r.memoryUsage.heapUsed<=this.thresholds.memoryUsage,threshold:this.thresholds.memoryUsage,unit:"bytes",value:r.memoryUsage.heapUsed}),n.push({name:"Memory Usage (RSS)",passed:r.memoryUsage.rss<=this.thresholds.memoryUsage*1.5,threshold:this.thresholds.memoryUsage*1.5,unit:"bytes",value:r.memoryUsage.rss}),r.commandExecutionTime>0)n.push({name:"Command Execution Time",passed:r.commandExecutionTime<=this.thresholds.commandExecutionTime,threshold:this.thresholds.commandExecutionTime,unit:"ms",value:r.commandExecutionTime});let t=n.filter((s)=>s.passed).length,o=n.length,e=Math.round(t/o*100);return{duration:lr.now(),results:n,summary:{failed:o-t,passed:t,score:e,total:o},timestamp:r.timestamp}}logReport(r){this.logger.info("=== Performance Report ==="),this.logger.info(`Timestamp: ${new Date(r.timestamp).toISOString()}`),this.logger.info(`Duration: ${r.duration.toFixed(2)}ms`),this.logger.info(`Score: ${r.summary.score}% (${r.summary.passed}/${r.summary.total} passed)`),this.logger.info(`
|
|
61
|
-
Results:`);for(let n of r.results){let t=n.passed?"\u2705 PASS":"\u274C FAIL",o=n.unit==="bytes"?`${(n.value/1024/1024).toFixed(2)}MB`:`${n.value.toFixed(2)}${n.unit}`,e=n.unit==="bytes"?`${(n.threshold/1024/1024).toFixed(2)}MB`:`${n.threshold.toFixed(2)}${n.unit}`;this.logger.info(` ${t} ${n.name}: ${o} (threshold: ${e})`)}}reset(){this.metrics={},this.startTimes.clear()}}function bn(r){if(r===0)return"0 B";let n=["B","KB","MB","GB"],t=Math.floor(Math.log(r)/Math.log(1024));return`${(r/1024**t).toFixed(2)} ${n[t]}`}function Lr(r){if(r<1000)return`${r.toFixed(2)}ms`;let n=r/1000;if(n<60)return`${n.toFixed(2)}s`;return`${(n/60).toFixed(2)}m`}var ka=new Pr;import{EventEmitter as Ro}from"events";import{performance as St}from"perf_hooks";G();var yo=ur({directory:or("./gh-runners"),labels:F(),name:or("runner"),numberOfMachines:ir(Ot(),1),os:Mr(["osx","linux","windows"],"osx"),overwrite:pr(!1),run:pr(!1),runnerGroup:F(),token:F(),url:F()}),ho=Er(yo),At=Er(ur({defaultProfile:F(),profiles:wn(ho.validator)})),xr;((c)=>{c.INIT="init";c.START="start";c.STOP="stop";c.SHUTDOWN="shutdown";c.SUCCESS="success";c.ERROR="error";c.PROGRESS="progress";c.STATUS="status";c.HEARTBEAT="heartbeat";c.LOG="log"})(xr||={});function qr(r){if(!r||typeof r!=="object"||r===null)return!1;let n=r;return typeof n.type==="string"&&Object.values(xr).includes(n.type)}function Ht(r){if(!r||typeof r!=="object"||r===null)return!1;let n=r;return typeof n.machineCwd==="string"&&typeof n.token==="string"&&typeof n.url==="string"&&typeof n.index==="number"&&(n.name===void 0||typeof n.name==="string")&&(n.labels===void 0||typeof n.labels==="string")&&(n.runnerGroup===void 0||typeof n.runnerGroup==="string")}class er extends Ro{options;workers=new Map;workerInfo=new Map;shutdownInProgress=!1;logger=x({prefix:"WorkerManager"});cleanupRegistered=!1;constructor(r={}){super();this.options=r;this.options={gracefulShutdownTimeout:30000,maxRestarts:3,restartDelay:1000,restartOnError:!0,...r},this.registerCleanup()}registerCleanup(){if(this.cleanupRegistered)return;this.cleanupRegistered=!0;let r=async()=>{if(!this.shutdownInProgress)await this.shutdown()};process.on("exit",()=>{if(!this.shutdownInProgress&&this.workers.size>0)this.logger.warn("Forced exit with active workers")}),process.on("SIGINT",async()=>{this.logger.info("Received SIGINT, initiating graceful shutdown..."),await r(),process.exit(0)}),process.on("SIGTERM",async()=>{this.logger.info("Received SIGTERM, initiating graceful shutdown..."),await r(),process.exit(0)}),process.on("uncaughtException",async(n)=>{this.logger.error("Uncaught exception:",n),await r(),process.exit(1)})}async createWorker(r){if(this.shutdownInProgress)throw new Error("Cannot create worker during shutdown");if(this.workers.size>=(this.options.maxWorkers||100))throw new Error(`Maximum worker limit reached: ${this.options.maxWorkers}`);if(this.workers.has(r.id))throw new Error(`Worker with id ${r.id} already exists`);let n=St.now(),t={id:r.id,name:r.name,restartCount:0,startTime:new Date,status:"starting"};this.workerInfo.set(r.id,t);try{let o=new Worker(r.scriptPath,{name:r.name,ref:!0});this.workers.set(r.id,o);let e=St.now()-n;if(t.spawnTime=e,this.setupWorkerHandlers(o,r,t),r.data){let s={data:r.data,timestamp:Date.now(),type:"init"};o.postMessage(s)}t.status="running",this.emit("workerStarted",t),this.emit("workerSpawned",{spawnTime:e,workerId:r.id}),this.logger.info(`Worker ${r.name} (${r.id}) started in ${e.toFixed(2)}ms`)}catch(o){throw t.status="error",t.error=o,t.endTime=new Date,this.emit("workerError",t,o),o}}setupWorkerHandlers(r,n,t){r.addEventListener("message",({data:o})=>{if(qr(o))this.emit("workerMessage",t,o),n.onMessage?.(o);else this.logger.warn(`Received invalid message from worker ${n.name}:`,o)}),r.addEventListener("error",(o)=>{if(this.logger.error(`Worker ${n.name} error:`,o),t.status="error",t.error=o.error||o,this.emit("workerError",t,o),n.onError?.(o.error||o),this.options.restartOnError&&t.restartCount<(this.options.maxRestarts||3))this.scheduleRestart(n,t)}),r.addEventListener("messageerror",(o)=>{this.logger.error(`Worker ${n.name} message error:`,o),t.status="error",t.error=new Error("Worker message error"),this.emit("workerError",t,o),n.onError?.(new Error("Worker message error"))})}scheduleRestart(r,n){let t=this.options.restartDelay||1000;n.restartCount++,this.logger.info(`Scheduling restart for worker ${r.name} (attempt ${n.restartCount}/${this.options.maxRestarts}) in ${t}ms`),setTimeout(async()=>{if(!this.shutdownInProgress)try{await this.createWorker(r)}catch(o){this.logger.error(`Failed to restart worker ${r.name}:`,o)}},t)}async stopWorker(r,n=!1){let t=this.workers.get(r),o=this.workerInfo.get(r);if(!t||!o)throw new Error(`Worker ${r} not found`);if(o.status="stopping",this.emit("workerStopping",o),n)t.terminate(),this.workers.delete(r),o.status="stopped",o.endTime=new Date,this.emit("workerStopped",o);else{let e={data:{graceful:!0},timestamp:Date.now(),type:"shutdown"};t.postMessage(e),await new Promise((s)=>{let i=setTimeout(()=>{this.logger.warn(`Worker ${o.name} did not stop gracefully, terminating...`),t.terminate(),s()},this.options.gracefulShutdownTimeout||30000);t.addEventListener("exit",()=>{clearTimeout(i),s()})})}}async shutdown(){if(this.shutdownInProgress)return;this.shutdownInProgress=!0,this.logger.info(`Shutting down ${this.workers.size} workers...`);let r=Array.from(this.workers.keys()).map((n)=>this.stopWorker(n).catch((t)=>{this.logger.error(`Error stopping worker ${n}:`,t)}));await Promise.all(r),this.workers.clear(),this.workerInfo.clear(),this.logger.info("All workers shut down")}getWorkerInfo(r){return this.workerInfo.get(r)}getAllWorkerInfo(){return Array.from(this.workerInfo.values())}getWorkerCount(){return this.workers.size}isShuttingDown(){return this.shutdownInProgress}}var xo=bo(import.meta.url),$o=go(xo),C=x({prefix:"Benchmark"});async function Ct(){let{values:r}=Eo({allowPositionals:!0,args:process.argv.slice(2),options:{help:{short:"h",type:"boolean"},iterations:{default:"3",type:"string"},"memory-only":{type:"boolean"},quick:{type:"boolean"},"startup-only":{type:"boolean"},"worker-only":{type:"boolean"},workers:{default:"3",type:"string"}}});if(r.help){console.log(`
|
|
62
|
-
Usage: hydra benchmark [options]
|
|
63
|
-
|
|
64
|
-
Options:
|
|
65
|
-
--iterations=N Number of benchmark iterations (default: 3)
|
|
66
|
-
--workers=N Number of workers to test (default: 3)
|
|
67
|
-
--startup-only Test only CLI startup time
|
|
68
|
-
--memory-only Test only memory usage
|
|
69
|
-
--worker-only Test only worker spawn performance
|
|
70
|
-
--quick Run a quick benchmark (1 iteration)
|
|
71
|
-
--help, -h Show this help message
|
|
72
|
-
|
|
73
|
-
Examples:
|
|
74
|
-
hydra benchmark
|
|
75
|
-
hydra benchmark --iterations=5 --workers=10
|
|
76
|
-
hydra benchmark --quick
|
|
77
|
-
hydra benchmark --startup-only
|
|
78
|
-
`);return}let n=r.quick?1:Number.parseInt(r.iterations),t=Number.parseInt(r.workers),o=new Pr({commandExecutionTime:1000,memoryUsage:104857600,startupTime:100,workerSpawnTime:50});C.info("Starting Hydra CLI Performance Benchmark...");try{if(r["startup-only"])await Wt(o,n);else if(r["memory-only"])await Gt(o);else if(r["worker-only"])await Mt(o,t);else await _o(o,n,t);let e=o.generateReport();if(o.logReport(e),e.summary.score<70)C.warn("Performance score is below acceptable threshold (70%)"),process.exit(1);else if(e.summary.score>=95)C.info("Excellent performance! \uD83D\uDE80");else if(e.summary.score>=85)C.info("Good performance! \uD83D\uDC4D")}catch(e){C.error("Benchmark failed:",e),process.exit(1)}}async function Wt(r,n){C.info(`Running startup benchmark (${n} iterations)...`);let t=0;for(let e=0;e<n;e++)if(r.startTimer("startup"),await new Promise((s)=>{setTimeout(()=>{let i=r.endTimer("startup");t+=i,s(i)},10)}),e<n-1)await new Promise((s)=>setTimeout(s,50));let o=t/n;r.getMetrics().startupTime=o,C.info(`Average startup time: ${Lr(o)}`)}async function Gt(r){C.info("Running memory usage benchmark..."),global.gc?.(),await new Promise((t)=>setTimeout(t,100));let n=r.measureMemoryUsage();C.info(`Heap used: ${bn(n.heapUsed)}`),C.info(`RSS memory: ${bn(n.rss)}`)}async function Mt(r,n){C.info(`Running worker spawn benchmark (${n} workers)...`);let t=new er,o=[];t.on("workerSpawned",({spawnTime:e})=>{o.push(e)});try{let e=[];for(let a=0;a<n;a++){let f=t.createWorker({data:{index:a,machineCwd:process.cwd(),token:"benchmark-token",url:"https://github.com/test/repo"},id:`benchmark-worker-${a}`,name:`BenchmarkWorker${a}`,scriptPath:wo($o,"../runner-worker.ts")});e.push(f),await new Promise((d)=>setTimeout(d,10))}await Promise.all(e),r.getMetrics().workerSpawnTimes=o;let s=o.reduce((a,f)=>a+f,0)/o.length,i=Math.max(...o);C.info(`Average worker spawn time: ${Lr(s)}`),C.info(`Max worker spawn time: ${Lr(i)}`)}finally{await t.shutdown()}}async function _o(r,n,t){C.info(`Running full benchmark suite (${n} iterations, ${t} workers)...`),await Wt(r,Math.min(n,3)),await new Promise((o)=>setTimeout(o,100)),await Gt(r),await new Promise((o)=>setTimeout(o,100)),await Mt(r,Math.min(t,3)),C.info("Full benchmark suite completed")}L();import{homedir as Ho}from"os";import{join as So}from"path";import{parseArgs as Co}from"util";var{$:Zt}=globalThis.Bun;import{join as Oo}from"path";var{$:K}=globalThis.Bun;class Ut{async exists(r){try{return(await K`test -e ${r}`.quiet().nothrow()).exitCode===0}catch{return!1}}async readFile(r){let n=Bun.file(r);if(!await n.exists())throw new Error(`File not found: ${r}`);return n.text()}async writeFile(r,n){await Bun.write(r,n)}async deleteFile(r){let n=U(r);await K`rm -f ${n}`.quiet()}async createDirectory(r,n){let t=U(r);if(n?.recursive)await K`mkdir -p ${t}`.quiet();else await K`mkdir ${t}`.quiet()}async deleteDirectory(r,n){let t=U(r);if(n?.recursive)await K`rm -rf ${t}`.quiet();else await K`rmdir ${t}`.quiet()}async listDirectory(r){let n=U(r),o=(await K`ls -la ${n}`.quiet()).stdout.toString().trim().split(`
|
|
79
|
-
`),e=[];for(let s of o.slice(1)){let i=s.split(/\s+/);if(i.length<9)continue;let a=i[0],f=Number.parseInt(i[4]||"0",10),d=i.slice(8).join(" ");if(d==="."||d==="..")continue;e.push({isDirectory:a?.startsWith("d")||!1,modifiedTime:new Date,name:d,size:f})}return e}async copyFile(r,n){let t=U(r),o=U(n);await K`cp ${t} ${o}`.quiet()}async moveFile(r,n){let t=U(r),o=U(n);await K`mv ${t} ${o}`.quiet()}async getFileInfo(r){if(!await Bun.file(r).exists())return null;let t=U(r),e=(await K`stat -f "%z %m %Y" ${t} 2>/dev/null || stat -c "%s %Y %F" ${t}`.quiet()).stdout.toString().trim().split(" "),s=e[0]||"0",i=e[1]||"0";return{isDirectory:!1,modifiedTime:new Date(Number.parseInt(i,10)*1000),name:r.split("/").pop()||r,size:Number.parseInt(s,10)}}async chmod(r,n){let t=U(r);await K`chmod ${n} ${t}`.quiet()}async readDir(r){return(await this.listDirectory(r)).map((t)=>({isDirectory:t.isDirectory,isFile:!t.isDirectory,name:t.name}))}async ensureDir(r){if(!await this.exists(r))await this.createDirectory(r,{recursive:!0})}}var b=new Ut;async function En(r){if(!await b.exists(r))await b.createDirectory(r,{recursive:!0})}var ko=["hydra.json",".hydra.json","hydra.toml",".hydra.toml"];async function xn(r=process.cwd()){for(let n of ko){let t=Oo(r,n);if(await b.exists(t))return t}return null}async function q(r){let n=r?.configPath||await xn();if(!n)return null;if(!await b.exists(n))return null;try{let t=await b.readFile(n),o=n.endsWith(".toml")?vo(t):JSON.parse(t);return At.parse(o)}catch(t){if(t instanceof Error)throw new Error(`Invalid config file: ${t.message}`);throw t}}async function B(r,n){if(!r)return null;let t=n||r.defaultProfile;if(!t)return null;return r.profiles[t]||null}function Pt(r,n){if(!r)return n;let t={...n};for(let[o,e]of Object.entries(r)){let s=o;if(t[s]===void 0&&e!==void 0)t[s]=e}return t}function vo(r){try{return Bun.TOML.parse(r)}catch(n){throw new Error(`Failed to parse TOML configuration: ${n}`)}}G();var Lt=k({prefix:"runner-templates"}),$n={postHook:`git reset --hard && git clean --force -df
|
|
57
|
+
`)},info:(n,r)=>{w.message(n,{...r,symbol:g.default.blue(Cs)})},success:(n,r)=>{w.message(n,{...r,symbol:g.default.green(Os)})},step:(n,r)=>{w.message(n,{...r,symbol:g.default.green(Sr)})},warn:(n,r)=>{w.message(n,{...r,symbol:g.default.yellow(Ss)})},warning:(n,r)=>{w.warn(n,r)},error:(n,r)=>{w.message(n,{...r,symbol:g.default.red(ks)})}},Ds=g.default.magenta,Ka={light:H("\u2500","-"),heavy:H("\u2501","="),block:H("\u2588","#")},Wa=`${g.default.gray(M)} `});function Ur(n){return(r)=>Is?`${n}${r}${zo.reset}`:r}function Vo({bright:n=!1,color:r}){let o=Bun.color(r,"ansi");if(!o||typeof o!=="string")return"";return n&&o in Bo?Bo[o]:o}var Is,Ks,Ws,zo,Bo,Ts,Js,k;var Mr=O(()=>{Is=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Ks=["blue","cyan","gray","green","magenta","red","white","yellow"],Ws=["bold","dim","italic","underline","reset"],zo={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Bo={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};Ts=Ks.reduce((n,r)=>{let o=Vo({color:r});if(o)n[r]=Ur(o);let i=Vo({bright:!0,color:r});if(i)n[`${r}Bright`]=Ur(i);return n},{}),Js=Ws.reduce((n,r)=>{return n[r]=Ur(zo[r]),n},{}),k={...Ts,...Js}});function Xs({prefix:n,level:r,message:o}){let i="";try{let a=new Date().toISOString().split("T")[1];if(a)i=a.split(".")[0]||""}catch{i="00:00:00"}let s=n?`[${n}] `:"";return`${k.dim(i)} ${r} ${s}${o}`}var Ys,L=({prefix:n="",level:r=process.env.DEBUG?0:1}={})=>{let o={};for(let i of Ys)o[i.method]=r<=i.level?(...s)=>{let c=s.map((a)=>String(a??"")).join(" ");i.console(Xs({level:i.color(i.label),message:c,prefix:n}))}:()=>{};return o.child=(i)=>L({level:r,prefix:`${n}:${i}`}),o},Lr;var Ao=O(()=>{Mr();Ys=[{color:k.dim,console:console.log,label:"DEBUG",level:0,method:"debug"},{color:k.cyan,console:console.info,label:"INFO ",level:1,method:"info"},{color:k.yellow,console:console.warn,label:"WARN ",level:2,method:"warn"},{color:k.red,console:console.error,label:"ERROR",level:3,method:"error"}],Lr=L()});var X=O(()=>{Mr();Ao()});var l;var jr=O(()=>{X();l={arrow:k.yellow,bold:k.bold,boolean:k.cyan,bullet:k.yellow,busy:k.yellow,command:k.green,dim:k.dim,error:k.red,flag:k.yellow,info:k.cyan,number:k.magenta,offline:k.red,online:k.green,separator:k.dim,string:k.green,success:k.green,value:k.cyan,warning:k.yellow}});var qr=()=>{};var tt;var Do=O(()=>{I();X();qr();tt=L({prefix:"cli-core"}).child("error")});var ft;var Io=O(()=>{ft=new Uint32Array(65536)});var Ko=O(()=>{Io()});async function xn(n,r={}){let{fallback:o,logLevel:i="warn",message:s="Operation failed gracefully"}=r;try{return await n()}catch(c){let a=c instanceof Error?c.message:String(c);if(Wo[i](`${s}: ${a}`),o)try{await o()}catch(u){Wo.error(`Fallback also failed: ${u instanceof Error?u.message:String(u)}`)}return}}var Wo;var To=O(()=>{X();Wo=L({prefix:"cli-core"}).child("graceful")});function Jo(n){let r=[];if(r.push(l.bold(`${n.name} - ${n.description}`)),r.push(""),r.push(l.bold("USAGE")),r.push(` ${n.usage}`),r.push(""),n.options?.length){r.push(l.bold("OPTIONS"));for(let o of n.options){let i=[o.description];if(o.default!==void 0)i.push(l.dim(`(default: ${o.default})`));if(o.required)i.push(l.error("(required)"));r.push(` ${l.flag(o.flags.padEnd(26))} ${i.join(" ")}`)}r.push("")}if(n.examples?.length){r.push(l.bold("EXAMPLES"));for(let o of n.examples)r.push(l.dim(` # ${o.description}`)),r.push(` ${l.value(o.command)}`),r.push("")}if(n.notes?.length){r.push(l.bold("NOTES"));for(let o of n.notes)r.push(` - ${o}`);r.push("")}if(n.sections?.length)for(let o of n.sections){r.push(l.bold(o.title));for(let i of o.content)r.push(` ${i}`);r.push("")}if(r[r.length-1]==="")r.pop();return r.join(`
|
|
58
|
+
`)}function Yo(n,r,o,i){let s=[];s.push(l.bold(n)),s.push(""),s.push(l.bold("USAGE")),s.push(` ${r}`),s.push(""),s.push(l.bold("COMMANDS"));let c=Math.max(...o.map((a)=>a.name.length));for(let a of o)s.push(` ${l.command(a.name.padEnd(c+2))} ${a.description}`);if(i)s.push(""),s.push(i);return s.join(`
|
|
59
|
+
`)}var Xo=O(()=>{jr()});var Qo=O(()=>{X()});var Zo=O(()=>{I()});async function Jn(n,r={}){let o={...Qs,...r},i=Error("Operation failed");for(let s=1;s<=o.maxAttempts;s++)try{return await n()}catch(c){if(i=c instanceof Error?c:Error(String(c)),!o.retryableErrors.some((t)=>i.message.toLowerCase().includes(t.toLowerCase()))||s===o.maxAttempts)throw i;o.onRetry(s,i);let u=Math.min(o.initialDelay*o.backoffMultiplier**(s-1),o.maxDelay);await new Promise((t)=>setTimeout(t,u))}throw i}var Qs;var Fo=O(()=>{X();Qs={backoffMultiplier:2,initialDelay:1000,maxAttempts:3,maxDelay:30000,onRetry:(n,r)=>{Lr.warn(`Retry attempt ${n}: ${r.message}`)},retryableErrors:["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","rate limit","429","503","502","504","npm ERR!","EPUBLISHCONFLICT"]}});var vo=()=>{};import{homedir as Zs}from"os";import{join as ni}from"path";var Fs,Pt;var ri=O(()=>{Fs=ni(Zs(),".r5n","cache"),Pt=ni(Fs,"update-check.json")});var un=(n)=>{return n.map=(r)=>un((o)=>r(n(o))),n.or=(r)=>un((o)=>{try{return n(o)}catch(i){return r(o)}}),n},Yn=()=>"bad banditype"(),oi=(n)=>un((r)=>n.includes(r)?r:Yn()),Xn=(n)=>un((r)=>typeof r===typeof n?r:Yn()),Br=()=>Xn(""),ii=()=>Xn(0),si=()=>Xn(!0),ci=()=>Xn(),ai=(n)=>un((r)=>r instanceof n?r:Yn()),Vr=(n)=>ai(Object).map((r)=>{let o={};for(let i in r){let s=n(r[i]);s!==void 0&&(o[i]=s)}return o}),Qn=(n)=>ai(Object).map((r)=>{let o={};for(let i in n){let s=n[i](r[i]);s!==void 0&&(o[i]=s)}return o});var ti=()=>{};function vs(n,r){return un((o)=>{try{return n(o)}catch{try{return r(o)}catch{throw Error("No matching schema in union")}}})}function Hn(n,r){return(o)=>{if(o===void 0)return r;return n(o)}}function ui(){return un((n)=>{let r=ii()(n);if(!Number.isInteger(r)||r<=0)throw Error("Must be a positive integer");return r})}function zr(n){return{parse(r){try{return n(r)}catch(o){throw Error(o instanceof Error?o.message:"Validation failed")}},safeParse(r){try{return{data:n(r),success:!0}}catch(o){return{error:o instanceof Error?o:Error("Validation failed"),success:!1}}},validator:n}}function Rn(){return vs(ci(),Br())}function Ar(n){return Hn(Br(),n)}function Dr(n){return Hn(si(),n)}function fi(n,r){return Hn(oi(n),r)}var pi=O(()=>{ti()});var Q=O(()=>{jr();Do();qr();Ko();To();Xo();Qo();Zo();Fo();vo();ri();pi()});var nc,rc,Zn;var Fn=O(()=>{Q();nc=Qn({directory:Ar("./gh-runners"),labels:Rn(),name:Ar("runner"),numberOfMachines:Hn(ui(),1),os:fi(["osx","linux","windows"],"osx"),overwrite:Dr(!1),run:Dr(!1),runnerGroup:Rn(),token:Rn(),url:Rn()}),rc=zr(nc),Zn=zr(Qn({defaultProfile:Rn(),profiles:Vr(rc.validator)}))});import{existsSync as Ir}from"fs";import{mkdir as oc,readdir as ic,readFile as sc,rm as cc,writeFile as ac}from"fs/promises";import{dirname as tc}from"path";async function $n(n){if(!Ir(n))await oc(n,{recursive:!0})}var G;var nn=O(()=>{G={exists:(n)=>Ir(n),readdir:async(n)=>{try{return await ic(n)}catch{return[]}},readFile:async(n)=>sc(n,"utf-8"),remove:async(n,r)=>{if(!Ir(n))return;await cc(n,{force:r?.force??!1,recursive:r?.recursive??!1})},writeFile:async(n,r)=>{await $n(tc(n)),await ac(n,r,"utf-8")}}});import{join as uc}from"path";async function Kr(n=process.cwd()){for(let r of fc){let o=uc(n,r);if(await G.exists(o))return o}return null}async function W(n){let r=n?.configPath||await Kr();if(!r)return null;if(!await G.exists(r))return null;try{let o=await G.readFile(r),i=r.endsWith(".toml")?pc(o):JSON.parse(o);return Zn.parse(i)}catch(o){if(o instanceof Error)throw Error(`Invalid config file: ${o.message}`);throw o}}async function T(n,r){if(!n)return null;let o=r||n.defaultProfile;if(!o)return null;return n.profiles[o]||null}function di(n,r){if(!n)return r;let o={...r};for(let[i,s]of Object.entries(n)){let c=i;if(o[c]===void 0&&s!==void 0)o[c]=s}return o}function pc(n){try{return Bun.TOML.parse(n)}catch(r){throw Error(`Failed to parse TOML configuration: ${r}`)}}var fc;var fn=O(()=>{Fn();nn();fc=["hydra.json",".hydra.json","hydra.toml",".hydra.toml"]});function En(n){try{let r=new URL(n),o=r.pathname.split("/").filter(Boolean);if(r.hostname==="github.com"||r.hostname==="www.github.com"){if(o[0]==="orgs"&&o[1])return`https://github.com/organizations/${o[1]}/settings/actions/runners/new`;if(o.length>=2)return`https://github.com/${o[0]}/${o[1]}/settings/actions/runners/new`}else{if(o[0]==="orgs"&&o[1])return`${r.origin}/organizations/${o[1]}/settings/actions/runners/new`;if(o.length>=2)return`${r.origin}/${o[0]}/${o[1]}/settings/actions/runners/new`}return n}catch{return n}}async function Tr(n,r={}){let{maxAttempts:o=5,baseDelay:i=1000,onRetry:s}=r;for(let c=1;c<=o;c++)try{return await n()}catch(a){if(c===o)throw a;let u=Math.min(i*2**(c-1),16000),t=Math.random()*0.1*u,f=u+t;if(s)s(c,a instanceof Error?a:Error(String(a)));await new Promise((m)=>setTimeout(m,f))}throw Error("Retry logic should not reach here")}function mi(n){return n.replace(/[^a-zA-Z0-9\-_./\s]/g,"")}function yi(n,r){let o=n;for(let i of r)if(i&&i.length>0){let s=i.length>8?`${i.slice(0,2)}${"*".repeat(i.length-4)}${i.slice(-2)}`:"*".repeat(i.length),c=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=o.replace(new RegExp(c,"g"),s)}return o=o.replace(/ghp_[a-zA-Z0-9]{36}/g,"ghp_************************************"),o=o.replace(/github_pat_[a-zA-Z0-9_]{82}/g,"github_pat_**********************************"),o=o.replace(/\b[A-Z]{20,}\b/g,(i)=>{return`${i.slice(0,2)}${"*".repeat(i.length-4)}${i.slice(-2)}`}),o}function Jr(n,r){if(typeof n==="string")return yi(n,r);if(Array.isArray(n))return n.map((o)=>Jr(o,r));if(typeof n==="object"&&n!==null){let o={};for(let i in n)o[i]=Jr(n[i],r);return o}return n}function U({prefix:n,secrets:r=[]}){let o=L({prefix:n}),i=[...r];if(process.env.GITHUB_TOKEN)i.push(process.env.GITHUB_TOKEN);if(process.env.RUNNER_TOKEN)i.push(process.env.RUNNER_TOKEN);if(process.env.RUNNER_CFG_PAT)i.push(process.env.RUNNER_CFG_PAT);let s=(c)=>Jr(c,i);return{...o,addSecret:(c)=>{if(c&&!i.includes(c))i.push(c)},child:(c)=>U({prefix:`${n}:${c}`,secrets:i}),debug:(...c)=>o.debug(...c.map(s)),error:(...c)=>o.error(...c.map(s)),info:(...c)=>o.info(...c.map(s)),warn:(...c)=>o.warn(...c.map(s))}}var pn=O(()=>{X()});async function dc(n){let r=U({prefix:"github-release-validator",secrets:[]});try{let o=await fetch(n);if(!o.ok)throw Error(`GitHub API request failed: ${o.status} ${o.statusText}`);let i=await o.json();if(!i||typeof i!=="object")throw Error("Invalid GitHub release response format");r.debug("GitHub release validation passed")}catch(o){if(o instanceof Error)throw o;throw Error(`GitHub release validation error: ${String(o)}`)}}async function wi({directory:n,os:r}){let o=U({prefix:"createMachines:download",secrets:[]});o.info(`Fetching latest runner version for ${r}...`);let i=await Tr(async()=>{let t=await fetch("https://github.com/actions/runner/releases/latest",{method:"GET",redirect:"manual"});if(t.status>=300&&t.status<400){let f=t.headers.get("location");if(f)return f}throw Error(`Failed to get redirect URL: ${t.status}`)},{onRetry:(t,f)=>{o.warn(`Retrying GitHub API call (attempt ${t}): ${f.message}`)}});if(!i||typeof i!=="string")throw Error("Invalid release info received from GitHub");if(!i.includes("github.com/actions/runner/releases/tag/"))throw Error(`Invalid GitHub release URL format: ${i}`);let s=i.split("/").pop()||"";if(!s)throw Error("Could not extract release tag from GitHub URL");let c=s.trim().replace("v","");if(!c||c.length===0)throw Error("Invalid version extracted from release tag");if(process.env.HYDRA_VALIDATE_GITHUB_RELEASES==="true"){o.debug("Performing additional GitHub release validation...");let t=`https://api.github.com/repos/actions/runner/releases/tags/${s}`;try{await dc(t)}catch(f){o.warn(`GitHub release validation failed (non-critical): ${f instanceof Error?f.message:String(f)}`)}}let a=`actions-runner-${r}-x64-${c}.tar.gz`,u=`https://github.com/actions/runner/releases/download/v${c}/${a}`;if(o.debug(`Runner version: ${c}`),o.debug(`Download URL: ${u}`),await $n(n),await $n(`${n}/machines`),!await G.exists(`${n}/${a}`))o.info("Downloading runner image..."),await Tr(async()=>{let t=await fetch(u);if(!t.ok)throw Error(`Download failed: ${t.status} ${t.statusText}`);if(!t.body)throw Error("No response body");let f=t.body.getReader(),m=[];try{while(!0){let{done:p,value:d}=await f.read();if(p)break;m.push(d)}}finally{f.releaseLock()}let b=m.reduce((p,d)=>p+d.length,0),y=new Uint8Array(b),e=0;for(let p of m)y.set(p,e),e+=p.length;await Bun.write(`${n}/${a}`,y)},{maxAttempts:5,onRetry:(t,f)=>{o.warn(`Retrying runner download (attempt ${t}): ${f.message}`)}}),o.info("Download complete");else o.info("Runner image already exists, skipping download");return a}var bi=O(()=>{nn();pn()});async function li(n){try{let r=`${n}/hooks`;await Bun.$`mkdir -p ${r}`.quiet(),await Bun.write(`${r}/pre.sh`,Yr.preHook),await Bun.$`chmod +x ${r}/pre.sh`.quiet(),await Bun.write(`${r}/post.sh`,Yr.postHook),await Bun.$`chmod +x ${r}/post.sh`.quiet(),await Bun.write(`${n}/.runner-env`,Yr.runnerEnv),gi.debug(`Created runner hooks and environment for ${n}`)}catch(r){throw gi.error("Failed to create runner files:",r),r}}var gi,Yr;var hi=O(()=>{Q();gi=L({prefix:"runner-templates"}),Yr={postHook:`git reset --hard && git clean --force -df
|
|
80
60
|
`,preHook:`export BUN_INSTALL_CACHE_DIR=./.bun/cache
|
|
81
61
|
`,runnerEnv:`ACTIONS_RUNNER_HOOK_JOB_STARTED=./hooks/pre.sh
|
|
82
62
|
ACTIONS_RUNNER_HOOK_JOB_COMPLETED=./hooks/post.sh
|
|
83
|
-
`};async function qt(r){try{let n=`${r}/hooks`;await Bun.$`mkdir -p ${n}`.quiet(),await Bun.write(`${n}/pre.sh`,$n.preHook),await Bun.$`chmod +x ${n}/pre.sh`.quiet(),await Bun.write(`${n}/post.sh`,$n.postHook),await Bun.$`chmod +x ${n}/post.sh`.quiet(),await Bun.write(`${r}/.runner-env`,$n.runnerEnv),Lt.debug(`Created runner hooks and environment for ${r}`)}catch(n){throw Lt.error("Failed to create runner files:",n),n}}function To(r){if(!r||typeof r!=="object")return!1;let n=r;if(typeof n.name!=="string"||n.name.trim().length===0)return!1;if(n.description!==void 0&&typeof n.description!=="string")return!1;if(n.extends!==void 0&&typeof n.extends!=="string")return!1;if(n.metadata!==void 0){if(typeof n.metadata!=="object"||n.metadata===null)return!1;let t=n.metadata;if(t.author!==void 0&&typeof t.author!=="string"||t.created!==void 0&&typeof t.created!=="string"||t.updated!==void 0&&typeof t.updated!=="string"||t.tags!==void 0&&(!Array.isArray(t.tags)||!t.tags.every((o)=>typeof o==="string")))return!1}return!0}function No(r){if(!r||typeof r!=="object")return!1;let n=r;if(!n.templates||typeof n.templates!=="object"||n.templates===null)return!1;let t=n.templates;for(let[o,e]of Object.entries(t))if(typeof o!=="string"||!To(e))return!1;if(n.version!==void 0&&typeof n.version!=="string")return!1;return!0}function _n(r){if(!No(r))throw new Error("Invalid template store: must contain a valid templates object")}G();P();var nf=k({prefix:"worker-validator"});class Bt{validateWorkerData(r){let n={errors:[],valid:!0,warnings:[]};if(!Ht(r))return n.valid=!1,n.errors.push({code:"INVALID_WORKER_DATA",field:"data",message:"Invalid worker data format"}),n;let t=r;if(this.validateUrl(t.url,n),this.validateToken(t.token,n),t.index<0)n.valid=!1,n.errors.push({code:"INVALID_INDEX",field:"index",message:"Worker index must be non-negative"});return n}validateWorkerMessage(r){let n={errors:[],valid:!0,warnings:[]};if(!qr(r))return n.valid=!1,n.errors.push({code:"INVALID_WORKER_MESSAGE",field:"message",message:"Invalid worker message format"}),n;if(!Object.values(xr).includes(r.type))n.valid=!1,n.errors.push({code:"INVALID_MESSAGE_TYPE",field:"type",message:`Invalid message type: ${r.type}`});return n}validateGitHubRelease(r){let n={errors:[],valid:!0,warnings:[]};if(!r||typeof r!=="object")return n.valid=!1,n.errors.push({code:"INVALID_GITHUB_RELEASE",field:"release",message:"GitHub release must be an object"}),n;let t=r;if(this.validateRequiredString(t.tag_name,"tag_name",n),this.validateRequiredString(t.html_url,"html_url",n),this.validateRequiredNumber(t.id,"id",n),t.draft!==void 0&&typeof t.draft!=="boolean")n.valid=!1,n.errors.push({code:"INVALID_TYPE",field:"draft",message:"Draft field must be a boolean"});if(t.prerelease!==void 0&&typeof t.prerelease!=="boolean")n.valid=!1,n.errors.push({code:"INVALID_TYPE",field:"prerelease",message:"Prerelease field must be a boolean"});if(t.prerelease===!0)n.warnings.push({code:"PRERELEASE_VERSION",field:"prerelease",message:"This is a prerelease version which may be unstable"});if(t.assets&&Array.isArray(t.assets))for(let[o,e]of t.assets.entries())this.validateGitHubReleaseAsset(e,`assets[${o}]`,n);return n}validateRequiredString(r,n,t){if(!r||typeof r!=="string")t.valid=!1,t.errors.push({code:"MISSING_REQUIRED_FIELD",field:n,message:`${n} is required and must be a string`});else if(r.trim().length===0)t.valid=!1,t.errors.push({code:"EMPTY_REQUIRED_FIELD",field:n,message:`${n} cannot be empty`})}validateRequiredNumber(r,n,t){if(typeof r!=="number")t.valid=!1,t.errors.push({code:"MISSING_REQUIRED_FIELD",field:n,message:`${n} is required and must be a number`});else if(!Number.isInteger(r))t.valid=!1,t.errors.push({code:"INVALID_NUMBER",field:n,message:`${n} must be an integer`});else if(r<0)t.valid=!1,t.errors.push({code:"NEGATIVE_NUMBER",field:n,message:`${n} must be a non-negative number`})}validateGitHubReleaseAsset(r,n,t){if(!r||typeof r!=="object"){t.valid=!1,t.errors.push({code:"INVALID_RELEASE_ASSET",field:n,message:"Release asset must be an object"});return}let o=r;if(!o.name||typeof o.name!=="string")t.valid=!1,t.errors.push({code:"MISSING_ASSET_NAME",field:`${n}.name`,message:"Asset name is required"});if(!o.browser_download_url||typeof o.browser_download_url!=="string")t.valid=!1,t.errors.push({code:"MISSING_DOWNLOAD_URL",field:`${n}.browser_download_url`,message:"Asset download URL is required"})}validateUrl(r,n){try{let t=new URL(r);if(!t.hostname.includes("github.com")&&!t.hostname.includes("github"))n.warnings.push({code:"NON_GITHUB_URL",field:"url",message:"URL does not appear to be a GitHub URL"})}catch{n.valid=!1,n.errors.push({code:"INVALID_URL",field:"url",message:"Invalid URL format"})}}validateToken(r,n){if(r.length<10)n.warnings.push({code:"SHORT_TOKEN",field:"token",message:"Token appears to be too short"});if(r.includes(" "))n.valid=!1,n.errors.push({code:"INVALID_TOKEN_FORMAT",field:"token",message:"Token cannot contain spaces"})}}function Ao(){return new Bt}function jt(r){return Ao().validateGitHubRelease(r)}async function Kt(r,n={}){let{maxAttempts:t=5,baseDelay:o=1000,onRetry:e}=n;for(let s=1;s<=t;s++)try{return await r()}catch(i){if(s===t)throw i;let a=Math.min(o*2**(s-1),16000),f=Math.random()*0.1*a,d=a+f;if(e)e(s,i instanceof Error?i:new Error(String(i)));await new Promise((c)=>setTimeout(c,d))}throw new Error("Retry logic should not reach here")}async function zt(){let r=x({prefix:"createMachines"}),n=await Go(),{overwrite:t,directory:o,numberOfMachines:e,os:s,run:i,name:a,labels:f,runnerGroup:d}=n,{token:c,url:u}=n;if(!u)throw w.createError("URL (-u) parameter is required","VALIDATION_ERROR",void 0,{operation:"create_machines",parameter:"url"});if(!c){let R=Wo(u),h=await S({message:`No token provided. Would you like to open GitHub to get a runner token?
|
|
84
|
-
${R}`});if(H(h)||!h)throw w.createError("Token is required to create runners","AUTHENTICATION_ERROR",void 0,{operation:"create_machines",parameter:"token"});r.info("Opening GitHub runner settings..."),await Zt`open ${R}`.quiet();let g=await T({message:"Enter the runner registration token:",placeholder:"AXXXXXXXXXXXXXXXXXXXXXXXXX",validate:(N)=>{if(!N||N.trim().length===0)return"Token is required";return}});if(H(g))throw w.createError("Token is required to create runners","AUTHENTICATION_ERROR",void 0,{operation:"create_machines",parameter:"token"});c=g.trim()}if(r=x({prefix:"createMachines",secrets:[c]}),r.info(`Creating ${e} runners in ${o}`),r.debug(`OS: ${s}, Name: ${a}, Labels: ${f||"none"}`),await b.exists(o))if(t)r.warn(`Directory ${o} exists, removing...`),await b.deleteDirectory(o,{recursive:!0});else throw w.createError(`Directory ${o} already exists`,"FILE_SYSTEM_ERROR",void 0,{directory:o,operation:"create_machines"});let l=await Uo({directory:o,os:s});if(await Po({directory:o,numberOfMachines:e,overwrite:t,runnerBase:l}),!i){r.info("Runners created but not started");return}await Lo({directory:o,labels:f,name:a,numberOfMachines:e,runnerGroup:d,token:c,url:u})}function Wo(r){try{let n=new URL(r),t=n.pathname.split("/").filter(Boolean);if(n.hostname==="github.com"||n.hostname==="www.github.com"){if(t[0]==="orgs"&&t[1])return`https://github.com/organizations/${t[1]}/settings/actions/runners/new`;if(t.length>=2)return`https://github.com/${t[0]}/${t[1]}/settings/actions/runners/new`}else{if(t[0]==="orgs"&&t[1])return`${n.origin}/organizations/${t[1]}/settings/actions/runners/new`;if(t.length>=2)return`${n.origin}/${t[0]}/${t[1]}/settings/actions/runners/new`}return r}catch{return r}}async function Go(){let r=process.argv.slice(3);if(r.includes("--help")||r.includes("-h")){let{help:a}=await Promise.resolve().then(() => (j(),Z));a("create"),process.exit(0)}let{values:n}=Co({args:r,options:{config:{short:"c",type:"string"},directory:{default:`${process.cwd()}/gh-runners`,short:"d",type:"string"},labels:{short:"l",type:"string"},name:{default:"runner",short:"n",type:"string"},numberOfMachines:{default:"1",short:"m",type:"string"},os:{default:"osx",short:"s",type:"string"},overwrite:{default:!1,short:"f",type:"boolean"},profile:{short:"p",type:"string"},run:{default:!1,short:"r",type:"boolean"},runnerGroup:{short:"g",type:"string"},template:{short:"T",type:"string"},token:{short:"t",type:"string"},url:{short:"u",type:"string"}},strict:!0}),t=await q({configPath:n.config}),o=await B(t,n.profile),e;if(n.template)e=await qo(n.template);let s={directory:n.directory,labels:n.labels,name:n.name,numberOfMachines:n.numberOfMachines,os:n.os,overwrite:n.overwrite,run:n.run,runnerGroup:n.runnerGroup,token:n.token||process.env.GITHUB_TOKEN||process.env.RUNNER_TOKEN,url:n.url},i=o||e?{directory:s.directory??o?.directory??e?.directory??`${process.cwd()}/gh-runners`,labels:s.labels??o?.labels??e?.labels,name:s.name??o?.name??e?.name??"runner",numberOfMachines:s.numberOfMachines??String(o?.numberOfMachines??e?.numberOfMachines)??"1",os:s.os??o?.os??e?.os??"osx",overwrite:s.overwrite??o?.overwrite??e?.overwrite??!1,run:s.run??o?.run??e?.run??!1,runnerGroup:s.runnerGroup??o?.runnerGroup??e?.runnerGroup,token:s.token||o?.token,url:s.url??o?.url??e?.url}:null;if(i)return i;return{directory:s.directory,labels:s.labels,name:s.name,numberOfMachines:s.numberOfMachines,os:s.os,overwrite:s.overwrite,run:s.run,runnerGroup:s.runnerGroup,token:s.token,url:s.url}}async function Mo(r){let n=x({prefix:"github-release-validator",secrets:[]});try{let t=await fetch(r);if(!t.ok)throw w.createError(`GitHub API request failed: ${t.status} ${t.statusText}`,"GITHUB_API_ERROR",void 0,{operation:"validate_github_release",status:t.status});let o=await t.json(),e=jt(o);if(!e.valid){n.error("GitHub release validation failed:");for(let s of e.errors)n.error(` ${s.field}: ${s.message}`);throw w.createError("Invalid GitHub release response format","GITHUB_API_ERROR",void 0,{operation:"validate_github_release"})}if(e.warnings.length>0){n.warn("GitHub release validation warnings:");for(let s of e.warnings)n.warn(` ${s.field}: ${s.message}`)}n.debug("GitHub release validation passed")}catch(t){if(t instanceof Error)throw t;throw new Error(`GitHub release validation error: ${String(t)}`)}}async function Uo({directory:r,os:n}){let t=x({prefix:"createMachines:download",secrets:[]});t.info(`Fetching latest runner version for ${n}...`);let o=await Kt(async()=>{let f=await fetch("https://github.com/actions/runner/releases/latest",{method:"GET",redirect:"manual"});if(f.status>=300&&f.status<400){let d=f.headers.get("location");if(d)return d}throw new Error(`Failed to get redirect URL: ${f.status}`)},{onRetry:(f,d)=>{t.warn(`Retrying GitHub API call (attempt ${f}): ${d.message}`)}});if(!o||typeof o!=="string")throw w.createError("Invalid release info received from GitHub","GITHUB_API_ERROR",void 0,{operation:"get_latest_github_runner_release"});if(!o.includes("github.com/actions/runner/releases/tag/"))throw new Error(`Invalid GitHub release URL format: ${o}`);let e=o.split("/").pop()||"";if(!e)throw new Error("Could not extract release tag from GitHub URL");let s=e.trim().replace("v","");if(!s||s.length===0)throw new Error("Invalid version extracted from release tag");if(process.env.HYDRA_VALIDATE_GITHUB_RELEASES==="true"){t.debug("Performing additional GitHub release validation...");let f=`https://api.github.com/repos/actions/runner/releases/tags/${e}`;try{await Mo(f)}catch(d){t.warn(`GitHub release validation failed (non-critical): ${d instanceof Error?d.message:String(d)}`)}}let i=`actions-runner-${n}-x64-${s}.tar.gz`,a=`https://github.com/actions/runner/releases/download/v${s}/${i}`;if(t.debug(`Runner version: ${s}`),t.debug(`Download URL: ${a}`),await En(r),await En(`${r}/machines`),!await b.exists(`${r}/${i}`))t.info("Downloading runner image..."),await Kt(async()=>{let f=await fetch(a);if(!f.ok)throw new Error(`Download failed: ${f.status} ${f.statusText}`);if(!f.body)throw new Error("No response body");let d=f.body.getReader(),c=[];try{while(!0){let{done:h,value:g}=await d.read();if(h)break;c.push(g)}}finally{d.releaseLock()}let u=c.reduce((h,g)=>h+g.length,0),l=new Uint8Array(u),R=0;for(let h of c)l.set(h,R),R+=h.length;await Bun.write(`${r}/${i}`,l)},{maxAttempts:5,onRetry:(f,d)=>{t.warn(`Retrying runner download (attempt ${f}): ${d.message}`)}}),t.info("Download complete");else t.info("Runner image already exists, skipping download");return i}async function Po({overwrite:r,numberOfMachines:n,directory:t,runnerBase:o}){let e=x({prefix:"createMachines:extract",secrets:[]}),s=Number(n),i=(()=>{try{let c=Bun.spawnSync(["nproc"]);return Number.parseInt(c.stdout.toString().trim(),10)||4}catch{try{let c=Bun.spawnSync(["sysctl","-n","hw.ncpu"]);return Number.parseInt(c.stdout.toString().trim(),10)||4}catch{return 4}}})(),a=Math.min(Math.max(2,Math.floor(i/2)),s,8);e.info(`Extracting ${s} runners with concurrency of ${a}`);let f=Array.from({length:s},(c,u)=>u+1).map((c)=>({execute:async()=>{let u=`${t}/machines/${c}`;if(await b.exists(u))if(r)e.debug(`Machine ${c} already exists, removing...`),await b.deleteDirectory(u,{recursive:!0});else{e.debug(`Machine ${c} already exists, skipping...`);return}await b.createDirectory(u),await Zt`tar xzf ${o} -C ${u.replace(`${t}/`,"")}`.cwd(t),await qt(u),e.debug(`Machine ${c} extracted successfully`)},runnerIndex:c})),d=[];for(let c=0;c<f.length;c+=a){let u=f.slice(c,c+a),l=Math.floor(c/a)+1,R=Math.ceil(f.length/a);e.info(`Processing batch ${l}/${R} (${u.length} runners)`);let h=await Promise.allSettled(u.map((g)=>g.execute()));for(let g=0;g<h.length;g++){let N=h[g];if(N&&N.status==="rejected")throw e.error(`Failed to extract runner ${u[g]?.runnerIndex}: ${N.reason}`),N.reason}d.push(...h),e.info(`Batch ${l}/${R} completed successfully`)}e.info(`Successfully extracted ${s} runners`)}async function Lo({directory:r,numberOfMachines:n,token:t,url:o,name:e,labels:s,runnerGroup:i}){let a=x({prefix:"createMachines:start",secrets:[t]});a.info(`Starting ${n} runners concurrently...`);let f=new er({maxRestarts:3,maxWorkers:Number(n),restartDelay:5000,restartOnError:!0}),d=Array.from({length:Number(n)},(h,g)=>{let N=g+1,ar=`${Ur()}/src/runner-worker.ts`,fr=`${e}-${N}`,Or=`runner-${N}`;return{data:{index:N,labels:s,machineCwd:`${r}/machines/${N}`,name:e,runnerGroup:i,token:t,url:o},id:Or,name:fr,onError:(O)=>{a.error(`Worker ${fr} error:`,O)},onExit:(O)=>{a.info(`Worker ${fr} exited with code ${O}`)},onMessage:(O)=>{let W=O.type==="error"?"error":"info";a[W](`${fr}: ${O.message}`)},scriptPath:ar}}),c=d.map(async(h)=>{try{return await f.createWorker(h),{success:!0,workerId:h.id,workerName:h.name}}catch(g){return a.error(`Failed to start worker ${h.name}:`,g),{error:g,success:!1,workerId:h.id,workerName:h.name}}}),u=await Promise.allSettled(c),l=0,R=0;if(u.forEach((h,g)=>{if(h.status==="fulfilled")if(h.value.success)l++,a.debug(`Worker ${h.value.workerName} started successfully`);else R++,a.error(`Worker ${h.value.workerName} failed to start: ${h.value.error}`);else{R++;let N=d[g];a.error(`Unexpected error starting worker ${N?.name}:`,h.reason)}}),R>0)a.warn(`${l} workers started successfully, ${R} failed`),a.info("Failed workers will be reported but won't stop other workers");else a.info(`All ${l} workers started successfully`);a.info("Press Ctrl+C to stop all machines")}async function qo(r){let n=x({prefix:"loadTemplate"}),t="./hydra-templates.json",o=Bun.file("./hydra-templates.json");if(await o.exists())try{let i=await o.json();if(_n(i),i.templates?.[r])return n.info(`Using local template: ${r}`),On(i.templates[r],i.templates)}catch(i){n.warn(`Failed to load local templates: ${i}`)}let e=So(Ho(),".hydra","templates.json"),s=Bun.file(e);if(await s.exists())try{let i=await s.json();if(_n(i),i.templates?.[r])return n.info(`Using global template: ${r}`),On(i.templates[r],i.templates)}catch(i){n.warn(`Failed to load global templates: ${i}`)}n.warn(`Template '${r}' not found`);return}function On(r,n,t=new Set){if(r.name&&t.has(r.name))throw w.createError(`Circular template dependency detected: ${r.name}`,"TEMPLATE_ERROR",void 0,{operation:"resolve_template_inheritance",templateName:r.name});if(r.name)t.add(r.name);let o={};if(r.extends&&n[r.extends]){let d=n[r.extends];if(d)o=On(d,n,t)}let{name:e,description:s,extends:i,metadata:a,...f}=r;return{...o,...f}}L();G();P();import{existsSync as $r}from"fs";import{readdir as Jt}from"fs/promises";import{join as D,resolve as Bo}from"path";import{parseArgs as jo}from"util";var{$:vn}=globalThis.Bun;var Vo=k({prefix:"hydra"}).child("health");async function Ko(){let r=process.argv.slice(3);if(r.includes("--help")||r.includes("-h")){let{help:e}=await Promise.resolve().then(() => (j(),Z));e("health"),process.exit(0)}let{values:n}=jo({args:r,options:{config:{short:"c",type:"string"},directory:{default:`${process.cwd()}/gh-runners`,short:"d",type:"string"},fix:{default:!1,short:"f",type:"boolean"},json:{default:!1,short:"j",type:"boolean"},profile:{short:"p",type:"string"},runner:{short:"r",type:"string"},token:{short:"t",type:"string"},url:{short:"u",type:"string"}},strict:!0}),t=await q({configPath:n.config}),o=await B(t,n.profile);return{directory:n.directory||o?.directory||`${process.cwd()}/gh-runners`,fix:n.fix,json:n.json,runner:n.runner,token:n.token,url:n.url||o?.url}}async function Yt(){try{let r=await Ko(),n=Bo(r.directory),t=D(n,"machines");if(!$r(t)){m.error(`No runners found in ${r.directory}`);return}let o=Q();o.start("Performing health checks...");let e=await Jt(t),s=[];for(let i of e){if(r.runner&&i!==r.runner)continue;let a=D(t,i),f=await Zo(i,a,r);s.push(f)}if(o.stop("Health checks completed"),r.json){console.log(JSON.stringify(s,null,2));return}if(Xo(s),r.fix)await Qo(s,r)}catch(r){Vo.error("Failed to perform health checks:",r),process.exit(1)}}async function Zo(r,n,t){let o=[],e={configuration:!1,connectivity:!1,disk:{percentage:0,total:0,used:0},lastActivity:null,process:!1};try{let i=D(n,".runner");if($r(i)){let a=await Bun.file(i).text(),f=await zo(a.trim());if(e.process=f,!f)o.push("Runner process is not running")}else o.push("No PID file found")}catch{o.push("Could not check process status")}try{let i=await Jo(n);if(e.disk=i,i.percentage>90)o.push(`Low disk space: ${i.percentage.toFixed(1)}% used`)}catch{o.push("Could not check disk space")}try{let i=D(n,"_diag");if($r(i)){let a=await Jt(i),f=null;for(let d of a)if(d.endsWith(".log")){let c=await Bun.file(D(i,d)).stat();if(!f||c.mtime>f)f=new Date(c.mtime)}if(e.lastActivity=f,f){let d=(Date.now()-f.getTime())/3600000;if(d>24)o.push(`No activity for ${Math.floor(d)} hours`)}}}catch{o.push("Could not check last activity")}try{let i=D(n,".runner"),a=D(n,".credentials");if(e.configuration=$r(i)&&$r(a),!e.configuration)o.push("Missing configuration files")}catch{o.push("Could not check configuration")}if(t.token&&t.url)try{let i=await Yo(t.url,t.token);if(e.connectivity=i,!i)o.push("Cannot connect to GitHub API")}catch{o.push("Failed to check GitHub connectivity")}let s="healthy";if(o.length===0)s="healthy";else if(o.some((i)=>i.includes("not running")||i.includes("Missing configuration")||i.includes("Cannot connect")))s="critical";else if(o.length>0)s="warning";return{checks:e,issues:o,runner:r,status:s}}async function zo(r){try{return await vn`kill -0 ${r}`.quiet(),!0}catch{return!1}}async function Jo(r){let t=(await vn`df -k ${r} | tail -1`.text()).trim().split(/\s+/),o=Number.parseInt(t[1]||"0",10)*1024,e=Number.parseInt(t[2]||"0",10)*1024;return{percentage:Number.parseInt(t[4]?.replace("%","")||"0",10),total:o,used:e}}async function Yo(r,n){return Cr(async()=>{let t=r.match(/github\.com[:/]([^/]+)(?:\/([^/.]+))?/);if(!t)return!1;let[,o,e]=t,s=e?`https://api.github.com/repos/${o}/${e}`:`https://api.github.com/orgs/${o}`;return(await fetch(s,{headers:{Accept:"application/vnd.github.v3+json",Authorization:`Bearer ${n}`}})).ok},{maxAttempts:3})}function Xo(r){console.log(),console.log(y.bold("\uD83C\uDFE5 Runner Health Status")),console.log("\u2500".repeat(80));let n={critical:"\u274C",healthy:"\u2705",unknown:"\u2753",warning:"\u26A0\uFE0F"},t={critical:y.error,healthy:y.success,unknown:y.dim,warning:y.warning};for(let e of r){let s=n[e.status],i=t[e.status];if(console.log(`${s} ${y.bold(`Runner ${e.runner}`)}: ${i(e.status.toUpperCase())}`),console.log(` Process: ${e.checks.process?"\u2705 Running":"\u274C Not running"}`),console.log(` Config: ${e.checks.configuration?"\u2705 Valid":"\u274C Missing"}`),e.checks.disk.total>0){let a=e.checks.disk.percentage>90?y.error:y.success;console.log(` Disk: ${a(`${e.checks.disk.percentage.toFixed(1)}% used`)}`)}if(e.checks.lastActivity){let f=(Date.now()-e.checks.lastActivity.getTime())/3600000>24?y.warning:y.success;console.log(` Last Activity: ${f(Fo(e.checks.lastActivity))}`)}if(e.checks.connectivity!==null)console.log(` GitHub API: ${e.checks.connectivity?"\u2705 Connected":"\u274C Disconnected"}`);if(e.issues.length>0){console.log(" Issues:");for(let a of e.issues)console.log(` - ${y.dim(a)}`)}console.log()}let o={critical:r.filter((e)=>e.status==="critical").length,healthy:r.filter((e)=>e.status==="healthy").length,total:r.length,warning:r.filter((e)=>e.status==="warning").length};console.log("\u2500".repeat(80)),console.log(`Summary: Total: ${o.total} | ${y.success(`Healthy: ${o.healthy}`)} | ${y.warning(`Warning: ${o.warning}`)} | ${y.error(`Critical: ${o.critical}`)}`)}async function Qo(r,n){let t=r.filter((e)=>e.status==="critical");if(t.length===0){m.info("No critical issues found that require fixing");return}if(console.log(),!await S({initialValue:!1,message:`Found ${t.length} runners with critical issues. Attempt to fix?`}))return;for(let e of t){if(console.log(),m.info(`Attempting to fix runner ${e.runner}...`),!e.checks.process&&e.checks.configuration){m.info("Attempting to restart runner...");try{let s=D(n.directory,"machines",e.runner);await vn`cd ${s} && ./run.sh`.quiet(),m.success(`Runner ${e.runner} restarted successfully`)}catch(s){m.error(`Failed to restart runner ${e.runner}`)}}if(!e.checks.configuration)m.warning(`Runner ${e.runner} needs to be reconfigured. Run 'hydra create' to set up again.`)}}function Fo(r){let t=new Date().getTime()-r.getTime(),o=Math.floor(t/3600000);if(o<1)return`${Math.floor(t/60000)}m ago`;if(o<24)return`${o}h ago`;return`${Math.floor(o/24)}d ago`}j();L();G();P();import{resolve as Do}from"path";import{parseArgs as re}from"util";var{$:Tn}=globalThis.Bun;var sr=k({prefix:"hydra"}).child("init");async function Xt(){let{toml:r}=await te(),n=r?"hydra.toml":"hydra.json",t=Do(process.cwd(),n);if(await Bun.file(t).exists()){let u=await S({initialValue:!1,message:`Configuration file ${n} already exists. Overwrite?`});if(H(u)||!u)Rn("Configuration cancelled"),process.exit(0)}et(E.cyan("\uD83D\uDE80 Hydra Configuration Setup")),sr.info("This will create a configuration file with your runner settings."),sr.info("You can always edit the file later or create additional profiles.");let e=await at({profileName:()=>T({message:"Profile name?",placeholder:"default"}),directory:()=>T({defaultValue:"./gh-runners",message:"Directory to store runners?",placeholder:"./gh-runners"}),name:()=>T({defaultValue:"runner",message:"Runner name prefix?",placeholder:"runner"}),labels:({results:u})=>{let l=u.name||"runner";return T({defaultValue:l,message:"Runner labels (comma-separated)?",placeholder:l})},numberOfMachines:()=>T({defaultValue:"1",message:"Number of runner machines?",placeholder:"1",validate:(u)=>{let l=Number.parseInt(u,10);if(Number.isNaN(l)||l<1)return"Please enter a valid number greater than 0";return}}),url:()=>T({message:"GitHub repository or organization URL? (optional)",placeholder:"https://github.com/org/repo"})},{onCancel:()=>{Rn("Configuration cancelled"),process.exit(0)}}),{profileName:s,labels:i,numberOfMachines:a,...f}=e,d={defaultProfile:s,profiles:{[s]:{...f,labels:i,numberOfMachines:Number.parseInt(a,10),os:"osx",overwrite:!1,run:!1}}},c=JSON.stringify(d,null,2);if(await Bun.write(t,c),await mr(async()=>{await Tn`chmod 600 ${t}`.quiet()},{logLevel:"warn",message:"Could not set secure file permissions"}),st(E.green(`\u2713 Configuration saved to ${n}`)),sr.info("Example usage:"),sr.info(` hydra create -p ${s} --token YOUR_TOKEN${e.url?"":" --url REPO_URL"}`),sr.info("You can add more profiles by editing the configuration file."),e.url)await ne(e.url)}async function ne(r){let n=/github\.com[:/]([^/]+)(?:\/([^/.]+))?/,t=r.match(n);if(!t)return;let[,o,e]=t,i=`https://github.com/${e?`${o}/${e}`:`organizations/${o}`}/settings/actions/runners`;sr.info(`Opening GitHub settings: ${i}`),await mr(async()=>{await Tn`open ${i}`.quiet()},{fallback:async()=>{await mr(async()=>{await Tn`xdg-open ${i}`.quiet()},{fallback:()=>{sr.info("Please open the URL manually to add a new runner token.")},logLevel:"info",message:"Alternative browser open method also failed"})},logLevel:"info",message:"Could not open browser automatically"})}async function te(){let r=process.argv.slice(3);if(r.includes("--help")||r.includes("-h")){let{help:t}=await Promise.resolve().then(() => (j(),Z));t("init"),process.exit(0)}let{values:n}=re({args:r,options:{toml:{default:!1,short:"t",type:"boolean"}},strict:!0});return n}L();G();import{parseArgs as ie}from"util";var{$:Qt,Glob:oe}=globalThis.Bun;async function ee(){let r=process.argv.slice(3);if(r.includes("--help")||r.includes("-h")){let{help:t}=await Promise.resolve().then(() => (j(),Z));t("migrate"),process.exit(0)}let{values:n}=ie({args:r,options:{all:{default:!1,short:"a",type:"boolean"},backup:{default:!0,short:"b",type:"boolean"},dryRun:{default:!1,short:"d",type:"boolean"},format:{short:"f",type:"string"},path:{short:"p",type:"string"}},strict:!0});return{all:n.all,backup:n.backup,dryRun:n.dryRun,format:n.format,path:n.path}}async function Ft(){let r=await ee();if(!r.path&&!r.all)r.path=await T({message:"Path to configuration file:",placeholder:"./hydra.json",validate:(o)=>{if(!o)return"Path is required";return}});let n=await se(r);if(n.length===0){m.error("No configuration files found");return}m.info(`Found ${n.length} configuration file(s) to migrate`);let t=[];for(let o of n){let e=await ae(o,r);t.push(e)}ce(t,r)}async function se(r){if(r.path){if(!await Bun.file(r.path).exists())throw new Error(`Configuration file not found: ${r.path}`);return[r.path]}if(r.all){let n=new oe("**/hydra.{json,toml}"),t=[];for await(let o of n.scan("."))if(!o.includes("node_modules")&&!o.includes(".git"))t.push(o);return t}return[]}async function ae(r,n){let t=Q();t.start(`Migrating ${r}...`);try{let o=await Bun.file(r).text(),e=r.endsWith(".toml")?"toml":"json",s=n.format||e,i,a=[];if(e==="toml"){let d=`.temp-${Date.now()}.toml`;await Bun.write(d,o),i=(await import(d)).default,await Qt`rm ${d}`.quiet()}else i=JSON.parse(o);let f=await fe(i,a);if(n.backup&&!n.dryRun){let d=`${r}.backup-${new Date().toISOString().replace(/:/g,"-")}`;await Bun.write(d,o),a.push(`Created backup at ${d}`)}if(!n.dryRun){let d=s!==e?r.replace(/\.(json|toml)$/,`.${s}`):r;if(s==="toml")await de(d,f);else await Bun.write(d,JSON.stringify(f,null,2));if(d!==r){if(await S({initialValue:!0,message:`Remove original file ${r}?`}))await Qt`rm ${r}`.quiet(),a.push(`Removed original file ${r}`)}a.push(`Migrated to ${d}`)}return t.stop(`Migrated ${r}`),{changes:a,path:r,success:!0}}catch(o){return t.stop(`Failed to migrate ${r}`),{error:o.message,path:r,success:!1}}}async function fe(r,n){let t={profiles:{}};if(r.defaultProfile)t.defaultProfile=r.defaultProfile;if(r.url||r.numberOfMachines||r.directory||r.labels){let o={};if(r.directory)o.directory=r.directory;if(r.labels)o.labels=r.labels;if(r.name)o.name=r.name;if(r.numberOfMachines)o.numberOfMachines=r.numberOfMachines;if(r.os)o.os=r.os;if(r.runnerGroup)o.runnerGroup=r.runnerGroup;if(r.url)o.url=r.url;if(r.overwrite!==void 0)o.overwrite=r.overwrite;if(r.run!==void 0)o.run=r.run;t.profiles.default=o,n.push("Migrated root-level settings to default profile"),delete r.url,delete r.numberOfMachines,delete r.directory,delete r.labels,delete r.name,delete r.os,delete r.runnerGroup,delete r.overwrite,delete r.run}if(r.profiles)for(let[o,e]of Object.entries(r.profiles)){let s=typeof e==="object"&&e!==null?{...e}:{};if(typeof e==="object"&&e!==null){if("runnerCount"in e&&!("numberOfMachines"in e))s.numberOfMachines=e.runnerCount,delete s.runnerCount,n.push(`Renamed 'runnerCount' to 'numberOfMachines' in profile '${o}'`);if("workDir"in e&&!("directory"in e))s.directory=e.workDir,delete s.workDir,n.push(`Renamed 'workDir' to 'directory' in profile '${o}'`);if(typeof e.labels==="string")s.labels=e.labels.split(",").map((i)=>i.trim()),n.push(`Converted labels to array format in profile '${o}'`)}t.profiles[o]=s}for(let[o,e]of Object.entries(r))if(!["profiles","defaultProfile"].includes(o))t[o]=e,n.push(`Preserved unknown property '${o}'`);return t}async function de(r,n){let t="";if(n.defaultProfile)t+=`defaultProfile = "${n.defaultProfile}"
|
|
63
|
+
`}});var{$:xi}=globalThis.Bun;async function Ri({overwrite:n,numberOfMachines:r,directory:o,runnerBase:i}){let s=U({prefix:"createMachines:extract",secrets:[]}),c=Number(r),a=(()=>{try{let m=Bun.spawnSync(["nproc"]);return Number.parseInt(m.stdout.toString().trim(),10)||4}catch{try{let m=Bun.spawnSync(["sysctl","-n","hw.ncpu"]);return Number.parseInt(m.stdout.toString().trim(),10)||4}catch{return 4}}})(),u=Math.min(Math.max(2,Math.floor(a/2)),c,8);s.info(`Extracting ${c} runners with concurrency of ${u}`);let t=Array.from({length:c},(m,b)=>b+1).map((m)=>({execute:async()=>{let b=`${o}/machines/${m}`;if(await G.exists(b))if(n)s.debug(`Machine ${m} already exists, removing...`),await xi`rm -rf ${b}`;else{s.debug(`Machine ${m} already exists, skipping...`);return}await $n(b),await xi`tar xzf ${i} -C ${b.replace(`${o}/`,"")}`.cwd(o),await li(b),s.debug(`Machine ${m} extracted successfully`)},runnerIndex:m})),f=[];for(let m=0;m<t.length;m+=u){let b=t.slice(m,m+u),y=Math.floor(m/u)+1,e=Math.ceil(t.length/u);s.info(`Processing batch ${y}/${e} (${b.length} runners)`);let p=await Promise.allSettled(b.map((d)=>d.execute()));for(let d=0;d<p.length;d++){let x=p[d];if(x&&x.status==="rejected")throw s.error(`Failed to extract runner ${b[d]?.runnerIndex}: ${x.reason}`),x.reason}f.push(...p),s.info(`Batch ${y}/${e} completed successfully`)}s.info(`Successfully extracted ${c} runners`)}var $i=O(()=>{nn();pn();hi()});function yc(){if(Ei)return;Ei=!0;let n=()=>{if(sn.size>0)on.info("Cleaning up workers...");Xr()};process.on("exit",n),process.on("SIGINT",n),process.on("SIGTERM",n)}async function ei(n){yc();let r=new Worker(mc);return r.addEventListener("message",(o)=>{let{type:i,message:s}=o.data;if(i==="success")on.info(`[Worker ${n.index}] ${s}`);else if(i==="error")on.error(`[Worker ${n.index}] ${s}`);else if(i==="progress")on.debug(`[Worker ${n.index}] Progress: ${s}`)}),r.addEventListener("error",(o)=>{on.error(`[Worker ${n.index}] Error:`,o.message)}),r.addEventListener("exit",()=>{sn.delete(n.index),on.debug(`[Worker ${n.index}] Exited. Remaining: ${sn.size}`)}),sn.set(n.index,r),r.postMessage({data:n,timestamp:Date.now(),type:"init"}),on.debug(`Worker ${n.index} spawned. Total: ${sn.size}`),`worker-${n.index}`}function Xr(){if(sn.size>0){on.info(`Terminating ${sn.size} workers...`);for(let n of sn.values())try{n.terminate()}catch(r){on.error("Failed to terminate worker:",r)}sn.clear()}}var on,mc,sn,Ei=!1;var Ci=O(()=>{X();Fn();on=L({prefix:"WorkerManager"}),mc=new URL("../workers/runner-worker.ts",import.meta.url).href,sn=new Map});async function vn({directory:n,numberOfMachines:r,token:o,url:i,name:s,labels:c,runnerGroup:a}){let u=U({prefix:"runMachines:start",secrets:[o]});u.info(`Starting ${r} workers...`);let t=0;for(let f=1;f<=Number(r);f++){let m=`${n}/machines/${f}`;if(!await G.exists(m))throw u.error(`Machine ${f} doesn't exist at ${m}`),Error(`Machine ${f} not found. Please run 'hydra create' first or check your directory.`);try{await ei({index:f,labels:c,machineCwd:m,name:s,runnerGroup:a,token:o,url:i}),u.info(`Worker ${s}-${f} started successfully`),t++}catch(b){let y=b instanceof Error?b.message:String(b);u.error(`Failed to start worker ${s}-${f}:`,y)}}if(t===0)throw Error("No workers could be started");u.info(`${t} workers started. Press Ctrl+C to stop all machines`),process.on("SIGINT",async()=>{u.info("Gracefully shutting down workers..."),Xr(),process.exit(0)})}var Qr=O(()=>{nn();pn();Ci()});var Z={};to(Z,{help:()=>nr});function nr(n){if(n&&Oi[n]){console.info(Jo(Oi[n]));return}let r=[{description:"Initialize a new Hydra configuration file",name:"init"},{description:"Create and register new GitHub runner machines",name:"create"},{description:"Check runner health and diagnose issues",name:"health"},{description:"Remove GitHub runner machines",name:"remove"},{description:"Start existing GitHub runner machines",name:"run"},{description:"Check the status of GitHub runner machines",name:"status"},{description:"Generate runner configuration templates",name:"template"},{description:"Validate configuration file",name:"validate"},{description:"Watch and auto-restart runners on failure",name:"watch"},{description:"Migrate configuration to latest format",name:"migrate"},{description:"Show this help message",name:"help"}];console.info(Yo(`Hydra@${Un} - GitHub self-hosted runner manager`,"hydra <command> [options]",r,"Use hydra <command> --help for more information about a command."))}var Oi;var J=O(()=>{Q();sr();Oi={create:{description:"Create and register new GitHub runner machines",examples:[{command:"hydra create -t TOKEN -u https://github.com/org/repo",description:"Create a single runner"},{command:"hydra create -t TOKEN -u URL -m 3",description:"Create 3 runners"},{command:"hydra create -t TOKEN -u URL -l docker,gpu",description:"Create runner with labels"},{command:"hydra create -p production",description:"Create using production profile"}],name:"hydra create",notes:["Requires a GitHub personal access token with repo scope","Creates runners in ./gh-runners by default","Use --run to immediately start runners after creation"],options:[{description:"GitHub personal access token",flags:"-t, --token",type:"string"},{description:"Repository or organization URL",flags:"-u, --url",type:"string"},{description:"Runner name prefix",flags:"-n, --name",type:"string"},{description:"Number of machines to create",flags:"-m, --numberOfMachines",type:"number"},{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Runner labels (comma-separated)",flags:"-l, --labels",type:"string"},{description:"Runner group",flags:"-g, --runnerGroup",type:"string"},{description:"Operating system",flags:"-s, --os",type:"string"},{description:"Overwrite existing runners",flags:"-f, --overwrite",type:"boolean"},{description:"Start runners after creation",flags:"-r, --run",type:"boolean"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra create [options]"},health:{description:"Check runner health and diagnose issues",examples:[{command:"hydra health",description:"Check health of all runners"},{command:"hydra health --fix",description:"Auto-fix common issues"},{command:"hydra health -p production",description:"Check health using profile"}],name:"hydra health",notes:["Checks runner registration, connectivity, and configuration","Use --fix to automatically resolve common issues","Exit code 0 if healthy, 1 if issues found"],options:[{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Auto-fix common issues",flags:"--fix",type:"boolean"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra health [options]"},init:{description:"Initialize a new Hydra configuration file",examples:[{command:"hydra init",description:"Create hydra.json interactively"},{command:"hydra init --toml",description:"Create hydra.toml instead"}],name:"hydra init",options:[{description:"Use TOML format instead of JSON",flags:"--toml",type:"boolean"}],usage:"hydra init [options]"},migrate:{description:"Migrate configuration to latest format",examples:[{command:"hydra migrate",description:"Migrate configuration"},{command:"hydra migrate --dry-run",description:"Preview changes without applying"}],name:"hydra migrate",options:[{description:"Preview changes without applying",flags:"--dry-run",type:"boolean"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra migrate [options]"},remove:{description:"Remove GitHub runner machines",examples:[{command:"hydra remove -t TOKEN -u https://github.com/org/repo",description:"Remove all runners"},{command:"hydra remove -t TOKEN -u URL -m 2",description:"Remove 2 runners"},{command:"hydra remove -t TOKEN -u URL --force",description:"Force remove without confirmation"},{command:"hydra remove -p production",description:"Remove using production profile"}],name:"hydra remove",notes:["Requires a GitHub personal access token with repo scope","Removes runners from GitHub and deletes local files","Use --force to skip confirmation prompt"],options:[{description:"GitHub personal access token",flags:"-t, --token",type:"string"},{description:"Repository or organization URL",flags:"-u, --url",type:"string"},{description:"Number of machines to remove",flags:"-m, --numberOfMachines",type:"number"},{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Force removal without confirmation",flags:"-f, --force",type:"boolean"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra remove [options]"},run:{description:"Start existing GitHub runner machines",examples:[{command:"hydra run -t TOKEN -u https://github.com/org/repo",description:"Start all runners"},{command:"hydra run -t TOKEN -u URL -m 2",description:"Start 2 runners"},{command:"hydra run -p production",description:"Start using production profile"}],name:"hydra run",notes:["Requires a GitHub personal access token with repo scope","Runners must be created first using 'hydra create'","Runs in foreground, use Ctrl+C to stop"],options:[{description:"GitHub personal access token",flags:"-t, --token",type:"string"},{description:"Repository or organization URL",flags:"-u, --url",type:"string"},{description:"Runner name prefix",flags:"-n, --name",type:"string"},{description:"Number of machines to run",flags:"-m, --numberOfMachines",type:"number"},{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Runner labels (comma-separated)",flags:"-l, --labels",type:"string"},{description:"Runner group",flags:"-g, --runnerGroup",type:"string"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra run [options]"},status:{description:"Check the status of GitHub runner machines",examples:[{command:"hydra status",description:"Show status of all runners"},{command:"hydra status --json",description:"Output status as JSON"},{command:"hydra status -p production",description:"Check status using profile"}],name:"hydra status",notes:["Shows runner registration status and current state","Use --json for machine-readable output"],options:[{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Output as JSON",flags:"--json",type:"boolean"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra status [options]"},template:{description:"Generate runner configuration templates",examples:[{command:"hydra template",description:"Generate default template"},{command:"hydra template --type docker",description:"Generate Docker runner template"}],name:"hydra template",options:[{description:"Template type",flags:"--type",type:"string"},{description:"Output file path",flags:"-o, --output",type:"string"}],usage:"hydra template [options]"},validate:{description:"Validate configuration file",examples:[{command:"hydra validate",description:"Validate hydra.json"},{command:"hydra validate -c custom.toml",description:"Validate custom config file"}],name:"hydra validate",options:[{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra validate [options]"},watch:{description:"Watch and auto-restart runners on failure",examples:[{command:"hydra watch",description:"Watch all runners"},{command:"hydra watch -p production",description:"Watch using profile"}],name:"hydra watch",notes:["Monitors runners and restarts them if they fail","Runs in foreground, use Ctrl+C to stop"],options:[{description:"Runners directory",flags:"-d, --directory",type:"string"},{description:"Configuration profile",flags:"-p, --profile",type:"string"},{description:"Configuration file path",flags:"-c, --config",type:"string"}],usage:"hydra watch [options]"}}});var ki={};to(ki,{createMachines:()=>Fr});import{homedir as wc}from"os";import{join as bc}from"path";import{parseArgs as gc}from"util";var{$:Si}=globalThis.Bun;async function Fr(n){let r=U({prefix:"createMachines"}),o=n||await lc(),{overwrite:i,directory:s,numberOfMachines:c,os:a,run:u,name:t,labels:f,runnerGroup:m}=o,{token:b,url:y}=o;if(u){if(!y)throw Error("URL (-u) parameter is required when running machines");if(!b){let p=En(y),d=await V({message:`No token provided. Would you like to open GitHub to get a runner token?
|
|
64
|
+
${p}`});if(B(d)||!d)throw Error("Token is required to run machines");r.info("Opening GitHub runner settings..."),await Si`open ${p}`.quiet();let x=await P({message:"Enter the runner registration token:",placeholder:"AXXXXXXXXXXXXXXXXXXXXXXXXX",validate:($)=>{if(!$||$.trim().length===0)return"Token is required";return}});if(B(x))throw Error("Token is required to run machines");b=x.trim()}r=U({prefix:"createMachines",secrets:[b]})}if(r.info(`Creating ${c} machine directories in ${s}`),r.debug(`OS: ${a}, Name: ${t}, Labels: ${f||"none"}, Run: ${u}`),await G.exists(s))if(i)r.warn(`Directory ${s} exists, removing...`),await Si`rm -rf ${s}`;else throw Error(`Directory ${s} already exists. Use -f to overwrite.`);let e=await wi({directory:s,os:a});if(await Ri({directory:s,numberOfMachines:c,overwrite:i,runnerBase:e}),!u){r.info("Machine directories created. Use 'hydra run' to start them.");return}if(!y||!b){r.warn("Cannot start machines without URL and token"),r.info("Machine directories created. Use 'hydra run' with -u and -t to start them.");return}await vn({directory:s,labels:f,name:t,numberOfMachines:c,runnerGroup:m,token:b,url:y})}async function lc(){let n=process.argv.slice(3);if(n.includes("--help")||n.includes("-h")){let{help:u}=await Promise.resolve().then(() => (J(),Z));u("create"),process.exit(0)}let{values:r}=gc({args:n,options:{config:{short:"c",type:"string"},directory:{default:`${process.cwd()}/gh-runners`,short:"d",type:"string"},labels:{short:"l",type:"string"},name:{default:"runner",short:"n",type:"string"},numberOfMachines:{default:"1",short:"m",type:"string"},os:{default:"osx",short:"s",type:"string"},overwrite:{default:!1,short:"f",type:"boolean"},profile:{short:"p",type:"string"},run:{default:!1,short:"r",type:"boolean"},runnerGroup:{short:"g",type:"string"},template:{short:"T",type:"string"},token:{short:"t",type:"string"},url:{short:"u",type:"string"}},strict:!0}),o=await W({configPath:r.config}),i=await T(o,r.profile),s;if(r.template)s=await hc(r.template);let c={directory:r.directory,labels:r.labels,name:r.name,numberOfMachines:r.numberOfMachines,os:r.os,overwrite:r.overwrite,run:r.run,runnerGroup:r.runnerGroup,token:r.token||process.env.GITHUB_TOKEN||process.env.RUNNER_TOKEN,url:r.url},a=i||s?{directory:c.directory??i?.directory??s?.directory??`${process.cwd()}/gh-runners`,labels:c.labels??i?.labels??s?.labels,name:c.name??i?.name??s?.name??"runner",numberOfMachines:c.numberOfMachines??String(i?.numberOfMachines??s?.numberOfMachines)??"1",os:c.os??i?.os??s?.os??"osx",overwrite:c.overwrite??i?.overwrite??s?.overwrite??!1,run:c.run??i?.run??s?.run??!1,runnerGroup:c.runnerGroup??i?.runnerGroup??s?.runnerGroup,token:c.token||i?.token,url:c.url??i?.url??s?.url}:null;if(a)return a;return{directory:c.directory,labels:c.labels,name:c.name,numberOfMachines:c.numberOfMachines,os:c.os,overwrite:c.overwrite,run:c.run,runnerGroup:c.runnerGroup,token:c.token,url:c.url}}async function hc(n){let r=U({prefix:"loadTemplate"}),o="./hydra-templates.json",i=Bun.file("./hydra-templates.json");if(await i.exists())try{let a=await i.json();if(a&&typeof a==="object"&&"templates"in a&&a.templates&&typeof a.templates==="object"&&n in a.templates)return r.info(`Using local template: ${n}`),Zr(a.templates[n],a.templates)}catch(a){r.warn(`Failed to load local templates: ${a}`)}let s=bc(wc(),".hydra","templates.json"),c=Bun.file(s);if(await c.exists())try{let a=await c.json();if(a&&typeof a==="object"&&"templates"in a&&a.templates&&typeof a.templates==="object"&&n in a.templates)return r.info(`Using global template: ${n}`),Zr(a.templates[n],a.templates)}catch(a){r.warn(`Failed to load global templates: ${a}`)}r.warn(`Template '${n}' not found`);return}function Zr(n,r,o=new Set){if(n.name&&o.has(n.name))throw Error(`Circular template dependency detected: ${n.name}`);if(n.name)o.add(n.name);let i={};if(n.extends&&r[n.extends]){let f=r[n.extends];if(f)i=Zr(f,r,o)}let{name:s,description:c,extends:a,metadata:u,...t}=n;return{...i,...t}}var vr=O(()=>{I();fn();bi();$i();Qr();nn();pn()});sr();vr();I();Q();X();fn();import{existsSync as Gn}from"fs";import{readdir as _i}from"fs/promises";import{join as dn,resolve as xc}from"path";import{parseArgs as Rc}from"util";var{$:no}=globalThis.Bun;var $c=L({prefix:"hydra"}).child("health");async function Ec(){let n=process.argv.slice(3);if(n.includes("--help")||n.includes("-h")){let{help:s}=await Promise.resolve().then(() => (J(),Z));s("health"),process.exit(0)}let{values:r}=Rc({args:n,options:{config:{short:"c",type:"string"},directory:{default:`${process.cwd()}/gh-runners`,short:"d",type:"string"},fix:{default:!1,short:"f",type:"boolean"},json:{default:!1,short:"j",type:"boolean"},profile:{short:"p",type:"string"},runner:{short:"r",type:"string"},token:{short:"t",type:"string"},url:{short:"u",type:"string"}},strict:!0}),o=await W({configPath:r.config}),i=await T(o,r.profile);return{directory:r.directory||i?.directory||`${process.cwd()}/gh-runners`,fix:r.fix,json:r.json,runner:r.runner,token:r.token,url:r.url||i?.url}}async function Hi(){try{let n=await Ec(),r=xc(n.directory),o=dn(r,"machines");if(!Gn(o)){w.error(`No runners found in ${n.directory}`);return}let i=rn();i.start("Performing health checks...");let s=await _i(o),c=[];for(let a of s){if(n.runner&&a!==n.runner)continue;let u=dn(o,a),t=await ec(a,u,n);c.push(t)}if(i.stop("Health checks completed"),n.json){console.log(JSON.stringify(c,null,2));return}if(kc(c),n.fix)await _c(c,n)}catch(n){$c.error("Failed to perform health checks:",n),process.exit(1)}}async function ec(n,r,o){let i=[],s={configuration:!1,connectivity:!1,disk:{percentage:0,total:0,used:0},lastActivity:null,process:!1};try{let a=dn(r,".runner");if(Gn(a)){let u=await Bun.file(a).text(),t=await Cc(u.trim());if(s.process=t,!t)i.push("Runner process is not running")}else i.push("No PID file found")}catch{i.push("Could not check process status")}try{let a=await Oc(r);if(s.disk=a,a.percentage>90)i.push(`Low disk space: ${a.percentage.toFixed(1)}% used`)}catch{i.push("Could not check disk space")}try{let a=dn(r,"_diag");if(Gn(a)){let u=await _i(a),t=null;for(let f of u)if(f.endsWith(".log")){let m=await Bun.file(dn(a,f)).stat();if(!t||m.mtime>t)t=new Date(m.mtime)}if(s.lastActivity=t,t){let f=(Date.now()-t.getTime())/3600000;if(f>24)i.push(`No activity for ${Math.floor(f)} hours`)}}}catch{i.push("Could not check last activity")}try{let a=dn(r,".runner"),u=dn(r,".credentials");if(s.configuration=Gn(a)&&Gn(u),!s.configuration)i.push("Missing configuration files")}catch{i.push("Could not check configuration")}if(o.token&&o.url)try{let a=await Sc(o.url,o.token);if(s.connectivity=a,!a)i.push("Cannot connect to GitHub API")}catch{i.push("Failed to check GitHub connectivity")}let c="healthy";if(i.length===0)c="healthy";else if(i.some((a)=>a.includes("not running")||a.includes("Missing configuration")||a.includes("Cannot connect")))c="critical";else if(i.length>0)c="warning";return{checks:s,issues:i,runner:n,status:c}}async function Cc(n){try{return await no`kill -0 ${n}`.quiet(),!0}catch{return!1}}async function Oc(n){let o=(await no`df -k ${n} | tail -1`.text()).trim().split(/\s+/),i=Number.parseInt(o[1]||"0",10)*1024,s=Number.parseInt(o[2]||"0",10)*1024;return{percentage:Number.parseInt(o[4]?.replace("%","")||"0",10),total:i,used:s}}async function Sc(n,r){return Jn(async()=>{let o=n.match(/github\.com[:/]([^/]+)(?:\/([^/.]+))?/);if(!o)return!1;let[,i,s]=o,c=s?`https://api.github.com/repos/${i}/${s}`:`https://api.github.com/orgs/${i}`;return(await fetch(c,{headers:{Accept:"application/vnd.github.v3+json",Authorization:`Bearer ${r}`}})).ok},{maxAttempts:3})}function kc(n){console.log(),console.log(l.bold("\uD83C\uDFE5 Runner Health Status")),console.log("\u2500".repeat(80));let r={critical:"\u274C",healthy:"\u2705",unknown:"\u2753",warning:"\u26A0\uFE0F"},o={critical:l.error,healthy:l.success,unknown:l.dim,warning:l.warning};for(let s of n){let c=r[s.status],a=o[s.status];if(console.log(`${c} ${l.bold(`Runner ${s.runner}`)}: ${a(s.status.toUpperCase())}`),console.log(` Process: ${s.checks.process?"\u2705 Running":"\u274C Not running"}`),console.log(` Config: ${s.checks.configuration?"\u2705 Valid":"\u274C Missing"}`),s.checks.disk.total>0){let u=s.checks.disk.percentage>90?l.error:l.success;console.log(` Disk: ${u(`${s.checks.disk.percentage.toFixed(1)}% used`)}`)}if(s.checks.lastActivity){let t=(Date.now()-s.checks.lastActivity.getTime())/3600000>24?l.warning:l.success;console.log(` Last Activity: ${t(Hc(s.checks.lastActivity))}`)}if(s.checks.connectivity!==null)console.log(` GitHub API: ${s.checks.connectivity?"\u2705 Connected":"\u274C Disconnected"}`);if(s.issues.length>0){console.log(" Issues:");for(let u of s.issues)console.log(` - ${l.dim(u)}`)}console.log()}let i={critical:n.filter((s)=>s.status==="critical").length,healthy:n.filter((s)=>s.status==="healthy").length,total:n.length,warning:n.filter((s)=>s.status==="warning").length};console.log("\u2500".repeat(80)),console.log(`Summary: Total: ${i.total} | ${l.success(`Healthy: ${i.healthy}`)} | ${l.warning(`Warning: ${i.warning}`)} | ${l.error(`Critical: ${i.critical}`)}`)}async function _c(n,r){let o=n.filter((s)=>s.status==="critical");if(o.length===0){w.info("No critical issues found that require fixing");return}if(console.log(),!await V({initialValue:!1,message:`Found ${o.length} runners with critical issues. Attempt to fix?`}))return;for(let s of o){if(console.log(),w.info(`Attempting to fix runner ${s.runner}...`),!s.checks.process&&s.checks.configuration){w.info("Attempting to restart runner...");try{let c=dn(r.directory,"machines",s.runner);await no`cd ${c} && ./run.sh`.quiet(),w.success(`Runner ${s.runner} restarted successfully`)}catch(c){w.error(`Failed to restart runner ${s.runner}`)}}if(!s.checks.configuration)w.warning(`Runner ${s.runner} needs to be reconfigured. Run 'hydra create' to set up again.`)}}function Hc(n){let o=new Date().getTime()-n.getTime(),i=Math.floor(o/3600000);if(i<1)return`${Math.floor(o/60000)}m ago`;if(i<24)return`${i}h ago`;return`${Math.floor(i/24)}d ago`}J();I();Q();X();import{resolve as Gc}from"path";import{parseArgs as Nc}from"util";var{$:ro}=globalThis.Bun;var wn=L({prefix:"hydra"}).child("init");async function Gi(){let{toml:n}=await Uc(),r=n?"hydra.toml":"hydra.json",o=Gc(process.cwd(),r);if(await Bun.file(o).exists()){let b=await V({initialValue:!1,message:`Configuration file ${r} already exists. Overwrite?`});if(B(b)||!b)Gr("Configuration cancelled"),process.exit(0)}Nr(k.cyan("\uD83D\uDE80 Hydra Configuration Setup")),wn.info("This will create a configuration file with your runner settings."),wn.info("You can always edit the file later or create additional profiles.");let s=await qo({profileName:()=>P({message:"Profile name?",placeholder:"default"}),directory:()=>P({defaultValue:"./gh-runners",message:"Directory to store runners?",placeholder:"./gh-runners"}),name:()=>P({defaultValue:"runner",message:"Runner name prefix?",placeholder:"runner"}),labels:({results:b})=>{let y=b.name||"runner";return P({defaultValue:y,message:"Runner labels (comma-separated)?",placeholder:y})},numberOfMachines:()=>P({defaultValue:"1",message:"Number of runner machines?",placeholder:"1",validate:(b)=>{let y=Number.parseInt(b||"0",10);if(Number.isNaN(y)||y<1)return"Please enter a valid number greater than 0";return}}),url:()=>P({message:"GitHub repository or organization URL? (optional)",placeholder:"https://github.com/org/repo"})},{onCancel:()=>{Gr("Configuration cancelled"),process.exit(0)}}),{profileName:c,labels:a,numberOfMachines:u,...t}=s,f={defaultProfile:c,profiles:{[c]:{...t,labels:a,numberOfMachines:Number.parseInt(u,10),os:"osx",overwrite:!1,run:!1}}},m=JSON.stringify(f,null,2);if(await Bun.write(o,m),await xn(async()=>{await ro`chmod 600 ${o}`.quiet()},{logLevel:"warn",message:"Could not set secure file permissions"}),Pr(k.green(`\u2713 Configuration saved to ${r}`)),wn.info("Example usage:"),wn.info(` hydra create -p ${c} --token YOUR_TOKEN${s.url?"":" --url REPO_URL"}`),wn.info("You can add more profiles by editing the configuration file."),s.url)await Pc(s.url)}async function Pc(n){let r=/github\.com[:/]([^/]+)(?:\/([^/.]+))?/,o=n.match(r);if(!o)return;let[,i,s]=o,a=`https://github.com/${s?`${i}/${s}`:`organizations/${i}`}/settings/actions/runners`;wn.info(`Opening GitHub settings: ${a}`),await xn(async()=>{await ro`open ${a}`.quiet()},{fallback:async()=>{await xn(async()=>{await ro`xdg-open ${a}`.quiet()},{fallback:()=>{wn.info("Please open the URL manually to add a new runner token.")},logLevel:"info",message:"Alternative browser open method also failed"})},logLevel:"info",message:"Could not open browser automatically"})}async function Uc(){let n=process.argv.slice(3);if(n.includes("--help")||n.includes("-h")){let{help:o}=await Promise.resolve().then(() => (J(),Z));o("init"),process.exit(0)}let{values:r}=Nc({args:n,options:{toml:{default:!1,short:"t",type:"boolean"}},strict:!0});return r}I();Q();import{parseArgs as Mc}from"util";var{$:Ni,Glob:Lc}=globalThis.Bun;async function jc(){let n=process.argv.slice(3);if(n.includes("--help")||n.includes("-h")){let{help:o}=await Promise.resolve().then(() => (J(),Z));o("migrate"),process.exit(0)}let{values:r}=Mc({args:n,options:{all:{default:!1,short:"a",type:"boolean"},backup:{default:!0,short:"b",type:"boolean"},dryRun:{default:!1,short:"d",type:"boolean"},format:{short:"f",type:"string"},path:{short:"p",type:"string"}},strict:!0});return{all:r.all,backup:r.backup,dryRun:r.dryRun,format:r.format,path:r.path}}async function Pi(){let n=await jc();if(!n.path&&!n.all)n.path=await P({message:"Path to configuration file:",placeholder:"./hydra.json",validate:(i)=>{if(!i)return"Path is required";return}});let r=await qc(n);if(r.length===0){w.error("No configuration files found");return}w.info(`Found ${r.length} configuration file(s) to migrate`);let o=[];for(let i of r){let s=await Bc(i,n);o.push(s)}Dc(o,n)}async function qc(n){if(n.path){if(!await Bun.file(n.path).exists())throw Error(`Configuration file not found: ${n.path}`);return[n.path]}if(n.all){let r=new Lc("**/hydra.{json,toml}"),o=[];for await(let i of r.scan("."))if(!i.includes("node_modules")&&!i.includes(".git"))o.push(i);return o}return[]}async function Bc(n,r){let o=rn();o.start(`Migrating ${n}...`);try{let i=await Bun.file(n).text(),s=n.endsWith(".toml")?"toml":"json",c=r.format||s,a,u=[];if(s==="toml"){let f=`.temp-${Date.now()}.toml`;await Bun.write(f,i),a=(await import(f)).default,await Ni`rm ${f}`.quiet()}else a=JSON.parse(i);let t=await Vc(a,u);if(r.backup&&!r.dryRun){let f=`${n}.backup-${new Date().toISOString().replace(/:/g,"-")}`;await Bun.write(f,i),u.push(`Created backup at ${f}`)}if(!r.dryRun){let f=c!==s?n.replace(/\.(json|toml)$/,`.${c}`):n;if(c==="toml")await Ac(f,t);else await Bun.write(f,JSON.stringify(t,null,2));if(f!==n){if(await V({initialValue:!0,message:`Remove original file ${n}?`}))await Ni`rm ${n}`.quiet(),u.push(`Removed original file ${n}`)}u.push(`Migrated to ${f}`)}return o.stop(`Migrated ${n}`),{changes:u,path:n,success:!0}}catch(i){return o.stop(`Failed to migrate ${n}`),{error:i.message,path:n,success:!1}}}function rr(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}async function Vc(n,r){let o={profiles:{}};if(rr(n)&&"profiles"in n){let i=n.profiles;if(rr(i))for(let[s,c]of Object.entries(i))o.profiles[s]=await zc(c,r)}else if(rr(n)){let i={};if("directory"in n)i.directory=n.directory;if("name"in n)i.name=n.name;if("numberOfMachines"in n)i.numberOfMachines=n.numberOfMachines;if("os"in n)i.os=n.os;if("overwrite"in n)i.overwrite=n.overwrite;if("run"in n)i.run=n.run;if("token"in n)i.token=n.token;if("url"in n)i.url=n.url;if("labels"in n)i.labels=n.labels;if("runnerGroup"in n)i.runnerGroup=n.runnerGroup;o.profiles.default=i,r.push("Converted flat config to profile-based config")}if(!o.defaultProfile&&Object.keys(o.profiles).length===1)o.defaultProfile=Object.keys(o.profiles)[0],r.push("Set default profile to the only profile");return o}async function zc(n,r){if(!rr(n))return{directory:"./gh-runners",name:"runner",numberOfMachines:1,os:"osx",overwrite:!1,run:!1};let o={...n};if(!("directory"in o))o.directory="./gh-runners",r.push("Added default directory");if(!("name"in o))o.name="runner",r.push("Added default name");if(!("numberOfMachines"in o))o.numberOfMachines=1,r.push("Added default numberOfMachines");if(!("os"in o))o.os="osx",r.push("Added default os");if(!("overwrite"in o))o.overwrite=!1,r.push("Added default overwrite");if(!("run"in o))o.run=!1,r.push("Added default run");return o}async function Ac(n,r){let o="";if(r.defaultProfile)o+=`defaultProfile = "${r.defaultProfile}"
|
|
85
65
|
|
|
86
|
-
`;for(let[
|
|
87
|
-
`;for(let[
|
|
88
|
-
`;else if(typeof
|
|
89
|
-
`;else if(
|
|
90
|
-
`;else
|
|
91
|
-
|
|
92
|
-
`}
|
|
93
|
-
|
|
94
|
-
${
|
|
95
|
-
`)
|
|
66
|
+
`;for(let[i,s]of Object.entries(r.profiles)){o+=`[profiles.${i}]
|
|
67
|
+
`;let c=Object.entries(s);for(let[a,u]of c){if(u===void 0||u===null)continue;if(typeof u==="string")o+=`${a} = "${u}"
|
|
68
|
+
`;else if(typeof u==="number")o+=`${a} = ${u}
|
|
69
|
+
`;else if(typeof u==="boolean")o+=`${a} = ${u}
|
|
70
|
+
`;else if(Array.isArray(u))o+=`${a} = [${u.map((t)=>`"${t}"`).join(", ")}]
|
|
71
|
+
`;else o+=`${a} = ${JSON.stringify(u)}
|
|
72
|
+
`}o+=`
|
|
73
|
+
`}await Bun.write(n,o.trim())}function Dc(n,r){if(w.info(""),r.dryRun)w.warn("DRY RUN MODE - No files were actually modified"),w.info("");let o=n.filter((s)=>s.success),i=n.filter((s)=>!s.success);if(o.length>0){w.success(`Successfully migrated ${o.length} file(s):`);for(let s of o)if(w.info(` ${l.value(s.path)}`),s.changes&&s.changes.length>0)for(let c of s.changes)w.info(` ${l.dim("\u2192")} ${c}`)}if(i.length>0){w.error(`Failed to migrate ${i.length} file(s):`);for(let s of i)w.error(` ${l.value(s.path)}: ${s.error}`)}w.info(""),w.info("Migration complete!")}I();fn();nn();pn();import{rm as oo}from"fs/promises";import{parseArgs as Ic}from"util";var{$:Ui}=globalThis.Bun;var F=U({prefix:"hydra:remove"});async function Mi(){let n=await Kc(),{directory:r,numberOfMachines:o,force:i}=n,{token:s,url:c}=n,a=`${r}/machines`;if(!await G.exists(a))throw Error(`Machines directory not found at ${a}. Nothing to remove.`);if(s)F=U({prefix:"hydra:remove",secrets:[s]});if(!s&&!i){if(!c)throw F.warn("No token or URL provided. Runners will not be unregistered from GitHub."),F.warn("Use --force to remove runners without unregistering them."),Error("Token (-t) and URL (-u) parameters are required or use --force");let u=En(c),t=await V({message:`No token provided. Would you like to open GitHub to get a runner token for unregistration?
|
|
74
|
+
${u}`});if(B(t)||!t)throw F.warn("Use --force to remove runners without unregistering them."),Error("Token is required to unregister runners (or use --force)");F.info("Opening GitHub runner settings..."),await Ui`open ${u}`.quiet();let f=await P({message:"Enter the runner removal token:",placeholder:"AXXXXXXXXXXXXXXXXXXXXXXXXX",validate:(m)=>{if(!m||m.trim().length===0)return"Token is required";return}});if(B(f))throw F.warn("Use --force to remove runners without unregistering them."),Error("Token is required to unregister runners (or use --force)");s=f.trim()}if(s&&c)F.info("Unregistering runners from GitHub..."),await Wc({directory:r,numberOfMachines:o,token:s});else if(!i)throw F.warn("No token or URL provided. Runners will not be unregistered from GitHub."),F.warn("Use --force to remove runners without unregistering them."),Error("Token (-t) and URL (-u) parameters are required or use --force");await Tc({directory:r,numberOfMachines:o}),F.info("Runners successfully removed")}async function Kc(){let n=process.argv.slice(3);if(n.includes("--help")||n.includes("-h")){let{help:c}=await Promise.resolve().then(() => (J(),Z));c("remove"),process.exit(0)}let{values:r}=Ic({args:n,options:{config:{short:"c",type:"string"},directory:{default:`${process.cwd()}/gh-runners`,short:"d",type:"string"},force:{default:!1,short:"f",type:"boolean"},numberOfMachines:{default:"1",short:"m",type:"string"},profile:{short:"p",type:"string"},token:{short:"t",type:"string"},url:{short:"u",type:"string"}},strict:!0}),o=await W({configPath:r.config}),i=await T(o,r.profile),s={directory:r.directory,force:r.force,numberOfMachines:r.numberOfMachines,token:r.token||process.env.GITHUB_TOKEN||process.env.RUNNER_TOKEN,url:r.url};if(i)return{directory:s.directory??i.directory??`${process.cwd()}/gh-runners`,force:s.force,numberOfMachines:s.numberOfMachines??String(i.numberOfMachines)??"1",token:s.token||i?.token,url:s.url??i.url};return s}async function Wc({directory:n,numberOfMachines:r,token:o}){let i=U({prefix:"hydra:remove:unregister",secrets:[o]}),s=Number(r),c=(()=>{try{let y=Bun.spawnSync(["nproc"]);return Number.parseInt(y.stdout.toString().trim(),10)||4}catch{try{let y=Bun.spawnSync(["sysctl","-n","hw.ncpu"]);return Number.parseInt(y.stdout.toString().trim(),10)||4}catch{return 4}}})(),a=Math.min(Math.max(2,Math.floor(c/2)),s,8);i.info(`Unregistering ${s} runners with concurrency of ${a}`);let u=Array.from({length:s},(y,e)=>e+1).map((y)=>({execute:async()=>{let e=`${n}/machines/${y}`;if(!await G.exists(e))return i.debug(`Machine ${y} doesn't exist, skipping...`),{runnerIndex:y,status:"skipped"};try{return i.debug(`Unregistering machine ${y}...`),await Ui`${mi(e)}/config.sh remove`.quiet().env({...process.env,RUNNER_CFG_PAT:o}),i.info(`Successfully unregistered machine ${y} from GitHub`),{runnerIndex:y,status:"success"}}catch(p){return i.warn(`Unable to unregister machine ${y}: ${p}`),{error:p,runnerIndex:y,status:"failed"}}},runnerIndex:y})),t=[];for(let y=0;y<u.length;y+=a){let e=u.slice(y,y+a),p=await Promise.allSettled(e.map((d)=>d.execute()));t.push(...p)}let f=t.filter((y)=>y.status==="fulfilled"&&y.value?.status==="success").length,m=t.filter((y)=>y.status==="fulfilled"&&y.value?.status==="failed").length,b=t.filter((y)=>y.status==="fulfilled"&&y.value?.status==="skipped").length;i.info(`Unregistration complete: ${f} successful, ${m} failed, ${b} skipped`)}async function Tc({directory:n,numberOfMachines:r}){let o=U({prefix:"hydra:remove:removeDirectories",secrets:[]}),i=Number(r),s=Array.from({length:i},(t,f)=>f+1).map((t)=>({execute:async()=>{let f=`${n}/machines/${t}`;if(!await G.exists(f))return{runnerIndex:t,status:"skipped"};try{return await oo(f,{force:!0,recursive:!0}),o.debug(`Removed machine ${t} directory`),{runnerIndex:t,status:"success"}}catch(m){return o.error(`Error removing machine ${t} directory: ${m}`),{error:m,runnerIndex:t,status:"failed"}}},runnerIndex:t})),c=await Promise.allSettled(s.map((t)=>t.execute())),a=c.filter((t)=>t.status==="fulfilled"&&t.value?.status==="success").length,u=c.filter((t)=>t.status==="fulfilled"&&t.value?.status==="failed").length;if(o.info(`Directory removal complete: ${a} removed, ${u} failed`),u>0)throw Error(`Failed to remove ${u} runner directories`);try{let t=`${n}/machines`;if((await G.readdir(t)).length===0){if(await oo(t,{force:!0,recursive:!0}),(await G.readdir(n)).length===0)await oo(n,{force:!0,recursive:!0});F.info("Removed empty directories")}}catch(t){}}I();fn();Qr();nn();pn();import{parseArgs as Jc}from"util";var{$:Yc}=globalThis.Bun;var bn=U({prefix:"runMachines"});async function Li(n){let r=n||await Xc(),{directory:o,numberOfMachines:i,name:s,labels:c,runnerGroup:a}=r,{token:u,url:t}=r;if(!t)throw Error("URL (-u) parameter is required");if(!u){let b=En(t),y=await V({message:`No token provided. Would you like to open GitHub to get a runner token?
|
|
75
|
+
${b}`});if(B(y)||!y)throw Error("Token is required to run machines");bn.info("Opening GitHub runner settings..."),await Yc`open ${b}`.quiet();let e=await P({message:"Enter the runner registration token:",placeholder:"AXXXXXXXXXXXXXXXXXXXXXXXXX",validate:(p)=>{if(!p||p.trim().length===0)return"Token is required";return}});if(B(e))throw Error("Token is required to run machines");u=e.trim()}bn=U({prefix:"runMachines",secrets:[u]}),bn.info(`Starting ${i} runners from ${o}`),bn.debug(`Name: ${s}, Labels: ${c||"none"}`);let f=`${o}/machines`,m=!1;if(!await G.exists(f))bn.warn(`Machines directory not found at ${f}`),m=!0;else for(let b=1;b<=Number(i);b++)if(!await G.exists(`${f}/${b}`)){bn.warn(`Machine directory ${b} is missing`),m=!0;break}if(m){bn.info("Creating machine directories before running...");let{createMachines:b}=await Promise.resolve().then(() => (vr(),ki));await b({directory:o,labels:c,name:s,numberOfMachines:i,os:"osx",overwrite:!1,run:!1,runnerGroup:a,token:void 0,url:void 0})}await vn({directory:o,labels:c,name:s,numberOfMachines:i,runnerGroup:a,token:u,url:t})}async function Xc(){let n=process.argv.slice(3);if(n.includes("--help")||n.includes("-h")){let{help:c}=await Promise.resolve().then(() => (J(),Z));c("run"),process.exit(0)}let{values:r}=Jc({args:n,options:{config:{short:"c",type:"string"},directory:{default:`${process.cwd()}/gh-runners`,short:"d",type:"string"},labels:{short:"l",type:"string"},name:{default:"runner",short:"n",type:"string"},numberOfMachines:{default:"1",short:"m",type:"string"},profile:{short:"p",type:"string"},runnerGroup:{short:"g",type:"string"},token:{short:"t",type:"string"},url:{short:"u",type:"string"}},strict:!0}),o=await W({configPath:r.config}),i=await T(o,r.profile),s={directory:r.directory,labels:r.labels,name:r.name,numberOfMachines:r.numberOfMachines,runnerGroup:r.runnerGroup,token:r.token||process.env.GITHUB_TOKEN||process.env.RUNNER_TOKEN,url:r.url};if(i)return{directory:s.directory??i.directory??`${process.cwd()}/gh-runners`,labels:s.labels??i.labels,name:s.name??i.name??"runner",numberOfMachines:s.numberOfMachines??String(i.numberOfMachines)??"1",runnerGroup:s.runnerGroup??i.runnerGroup,token:s.token||i?.token,url:s.url??i.url};return s}I();Q();X();fn();import{parseArgs as Qc}from"util";var{$:Zc}=globalThis.Bun;var en=L({prefix:"hydra"}).child("status");async function ji(){let n=await Fc(),{directory:r,token:o,url:i,json:s}=n;if(!o||!i)throw Error("Token (-t) and URL (-u) parameters are required");let c=rn();c.start("Fetching runner status...");try{let a=await vc(r),u=await na(i,o),t=ra(a,u);if(c.stop("Runner status fetched"),s)en.info(JSON.stringify(t,null,2));else oa(t)}catch(a){throw c.stop("Failed to fetch runner status"),a}}async function Fc(){let n=process.argv.slice(3);if(n.includes("--help")||n.includes("-h")){let{help:s}=await Promise.resolve().then(() => (J(),Z));s("status"),process.exit(0)}let{values:r}=Qc({args:n,options:{config:{short:"c",type:"string"},directory:{default:`${process.cwd()}/gh-runners`,short:"d",type:"string"},json:{default:!1,short:"j",type:"boolean"},profile:{short:"p",type:"string"},token:{short:"t",type:"string"},url:{short:"u",type:"string"}},strict:!0}),o=await W({configPath:r.config}),i=await T(o,r.profile);return{directory:r.directory||i?.directory||`${process.cwd()}/gh-runners`,json:r.json,token:r.token||i?.token||process.env.GITHUB_TOKEN||process.env.RUNNER_TOKEN,url:r.url||i?.url}}async function vc(n){let r=`${n}/machines`;return await xn(async()=>{return(await Zc`ls ${r} 2>/dev/null || true`.quiet()).stdout.toString().trim().split(`
|
|
76
|
+
`).filter(Boolean)},{fallback:()=>{},logLevel:"debug",message:"No local runners found"})||[]}async function na(n,r){let o=n.match(/github\.com[:/]([^/]+)(?:\/([^/.]+))?/);if(!o)throw Error("Invalid GitHub URL");let[,i,s]=o,c=s?`https://api.github.com/repos/${i}/${s}/actions/runners`:`https://api.github.com/orgs/${i}/actions/runners`;return Jn(async()=>{let a={Accept:"application/vnd.github.v3+json",Authorization:`Bearer ${r}`},u=await fetch(c,{headers:a});if(!u.ok)throw Error(`GitHub API error: ${u.status} ${u.statusText}`);return await u.json()},{onRetry:(a,u)=>{w.warn(`Retrying GitHub API call (attempt ${a}): ${u.message}`)}})}function ra(n,r){let o=[],i=new Map(r.runners.map((s)=>[s.name,s]));for(let s of n){let c=`runner-${s}`,a=i.get(c);if(a)o.push({busy:a.busy,labels:a.labels.map((u)=>u.name),name:c,os:a.os,status:a.busy?"busy":a.status==="online"?"online":"offline"});else o.push({busy:!1,labels:[],name:c,os:"unknown",status:"offline"})}return o}function oa(n){if(n.length===0){w.info("No runners found");return}en.info("Runner Status:"),en.info("\u2500".repeat(80));let r={busy:l.busy,offline:l.offline,online:l.online};for(let i of n){let s=r[i.status],c=i.status.toUpperCase().padEnd(7);en.info(`${s("\u25CF")} ${s(c)} ${l.value(i.name.padEnd(20))} ${l.dim(`OS: ${i.os.padEnd(10)}`)} ${i.labels.length>0?l.dim(`Labels: ${i.labels.join(", ")}`):""}`)}en.info("\u2500".repeat(80));let o={busy:n.filter((i)=>i.status==="busy").length,offline:n.filter((i)=>i.status==="offline").length,online:n.filter((i)=>i.status==="online").length,total:n.length};en.info(`Summary: Total: ${o.total} | ${l.online(`Online: ${o.online}`)} | ${l.busy(`Busy: ${o.busy}`)} | ${l.offline(`Offline: ${o.offline}`)}`)}I();Q();import{homedir as qi}from"os";import{join as io}from"path";import{parseArgs as ia}from"util";var or={global:io(qi(),".hydra","templates.json"),local:"./hydra-templates.json"};async function sa(){let n=process.argv.slice(3);if(n.includes("--help")||n.includes("-h")){let{help:i}=await Promise.resolve().then(() => (J(),Z));i("template"),process.exit(0)}let{values:r}=ia({args:n,options:{action:{default:"list",short:"a",type:"string"},force:{default:!1,short:"f",type:"boolean"},from:{short:"F",type:"string"},global:{default:!1,short:"g",type:"boolean"},name:{short:"n",type:"string"}},strict:!0}),o=r.action;if(o&&!["list","create","use","delete","show"].includes(o))throw Error(`Unknown action: ${o}`);return{action:o,force:r.force,from:r.from,global:r.global,name:r.name}}async function Bi(){let n=await sa();if(!n.action)n.action=await tn({message:"What would you like to do?",options:[{label:"List templates",value:"list"},{label:"Create a new template",value:"create"},{label:"Use a template",value:"use"},{label:"Show template details",value:"show"},{label:"Delete a template",value:"delete"}]});switch(n.action){case"list":await ca();break;case"create":await aa(n);break;case"use":await ta(n);break;case"show":await ua(n);break;case"delete":await fa(n);break;default:w.error(`Unknown action: ${n.action}`),w.info("Available actions: list, create, use, show, delete")}}async function mn(n){let r=n?or.global:or.local,o=Bun.file(r);if(!await o.exists())return{templates:{},version:"1.0"};try{return await o.json()}catch{return{templates:{},version:"1.0"}}}async function Vi(n,r){let o=r?or.global:or.local;if(r){let i=io(qi(),".hydra");await Bun.write(io(i,".gitkeep"),"")}await Bun.write(o,JSON.stringify(n,null,2))}async function ca(){let n=await mn(!0),r=await mn(!1),o={...n.templates,...r.templates};if(Object.keys(o).length===0){w.info("No templates found"),w.info(""),w.info("Create a template with: hydra template create");return}w.info(l.value("Available Templates:")),w.info("");for(let[i,s]of Object.entries(o)){let a=i in n.templates?l.dim(" (global)"):"";if(w.info(` ${l.value(i)}${a}`),s.description)w.info(` ${l.dim(s.description)}`);if(s.extends)w.info(` ${l.dim(`Extends: ${s.extends}`)}`);let u=[];if(s.numberOfMachines)u.push(`machines: ${s.numberOfMachines}`);if(s.os)u.push(`os: ${s.os}`);if(s.labels)u.push(`labels: ${s.labels}`);if(u.length>0)w.info(` ${l.dim(u.join(", "))}`);w.info("")}}async function aa(n){let r=n.name||await P({message:"Template name:",placeholder:"my-template",validate:(m)=>{if(!m)return"Template name is required";if(!/^[a-zA-Z0-9-_]+$/.test(m))return"Template name can only contain letters, numbers, hyphens, and underscores";return}}),o=await mn(n.global??!1);if(!n.force&&r in o.templates){if(!await V({initialValue:!1,message:`Template '${r}' already exists. Overwrite?`})){w.info("Template creation cancelled");return}}let i=await P({message:"Description (optional):",placeholder:"Template for production runners"}),s={};if(n.from){let m=o.templates[n.from];if(m)s={...m},delete s.name,delete s.description,delete s.metadata,delete s.extends}let c=await P({initialValue:s.numberOfMachines?.toString()||"1",message:"Number of machines:",placeholder:s.numberOfMachines?.toString()||"1"}),a=await tn({initialValue:s.os||"osx",message:"Operating system:",options:[{label:"macOS",value:"osx"},{label:"Linux",value:"linux"},{label:"Windows",value:"windows"}]}),u=await P({initialValue:s.labels,message:"Labels (comma-separated, optional):",placeholder:s.labels||"self-hosted,x64"}),t=await P({initialValue:s.directory||"./gh-runners",message:"Runner directory:",placeholder:s.directory||"./gh-runners"}),f={description:i||void 0,directory:t,extends:n.from||void 0,labels:u||void 0,metadata:{author:process.env.USER||void 0,created:new Date().toISOString(),updated:new Date().toISOString()},name:r,numberOfMachines:Number.parseInt(c,10),os:a};o.templates[r]=f,await Vi(o,n.global??!1),w.success(`Template '${r}' created successfully`),w.info(""),w.info(`Use it with: hydra create --template ${r}`)}async function ta(n){let r=await mn(!0),o=await mn(!1),i={...r.templates,...o.templates};if(Object.keys(i).length===0){w.error("No templates found"),w.info("Create a template with: hydra template create");return}let s=n.name||await tn({message:"Select a template:",options:Object.entries(i).map(([t,f])=>({label:`${t}${f.description?` - ${f.description}`:""}`,value:t}))}),c=i[s];if(!c){w.error(`Template '${s}' not found`);return}let a=await so(c,i);if(w.info(""),w.info(l.value(`Using template: ${s}`)),w.info(""),w.info("This will create runners with the following configuration:"),w.info(` Number of machines: ${a.numberOfMachines||1}`),w.info(` OS: ${a.os||"osx"}`),w.info(` Directory: ${a.directory||"./gh-runners"}`),a.labels)w.info(` Labels: ${a.labels}`);w.info("");let u=await tn({message:"Where should this configuration be saved?",options:[{label:"Create hydra.json in current directory",value:"json"},{label:"Create hydra.toml in current directory",value:"toml"},{label:"Just show the command",value:"command"}]});if(u==="command"){let t=[];if(a.numberOfMachines)t.push(`-m ${a.numberOfMachines}`);if(a.os)t.push(`-s ${a.os}`);if(a.directory)t.push(`-d "${a.directory}"`);if(a.labels)t.push(`-l "${a.labels}"`);if(a.name)t.push(`-n "${a.name}"`);w.info("Run the following command:"),w.info(""),w.info(l.value(`hydra create ${t.join(" ")} -t <TOKEN> -u <URL>`)),w.info("")}else{let t={defaultProfile:"default",profiles:{default:a}},f=u==="json"?"hydra.json":"hydra.toml";if(u==="json")await Bun.write(f,JSON.stringify(t,null,2));else{let m=`defaultProfile = "default"
|
|
96
77
|
|
|
97
78
|
[profiles.default]
|
|
98
|
-
`;for(let[
|
|
99
|
-
`;else
|
|
100
|
-
`;await Bun.write(
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
Debug Information:`),console.error(w.formatDebugError(i));process.exit(1)}}await je();
|
|
79
|
+
`;for(let[b,y]of Object.entries(a))if(y!==void 0&&y!==null)if(typeof y==="string")m+=`${b} = "${y}"
|
|
80
|
+
`;else m+=`${b} = ${y}
|
|
81
|
+
`;await Bun.write(f,m)}w.success(`Created ${f}`),w.info(""),w.info("Now run:"),w.info(l.value("hydra create -t <TOKEN> -u <URL>"))}}async function ua(n){let r=await mn(!0),o=await mn(!1),i={...r.templates,...o.templates},s=n.name||await tn({message:"Select a template:",options:Object.entries(i).map(([u,t])=>({label:`${u}${t.description?` - ${t.description}`:""}`,value:u}))}),c=i[s];if(!c){w.error(`Template '${s}' not found`);return}let a=await so(c,i);if(w.info(""),w.info(l.value(`Template: ${s}`)),w.info("\u2500".repeat(40)),c.description)w.info(`Description: ${c.description}`);if(c.extends)w.info(`Extends: ${c.extends}`);if(c.metadata){if(c.metadata.author)w.info(`Author: ${c.metadata.author}`);if(c.metadata.created)w.info(`Created: ${new Date(c.metadata.created).toLocaleDateString()}`);if(c.metadata.updated)w.info(`Updated: ${new Date(c.metadata.updated).toLocaleDateString()}`);if(c.metadata.tags?.length)w.info(`Tags: ${c.metadata.tags.join(", ")}`)}w.info(""),w.info("Configuration:"),w.info(JSON.stringify(a,null,2))}async function fa(n){let r=await mn(n.global??!1);if(Object.keys(r.templates).length===0){w.error("No templates found");return}let o=n.name||await tn({message:"Select a template to delete:",options:Object.entries(r.templates).map(([i,s])=>({label:`${i}${s.description?` - ${s.description}`:""}`,value:i}))});if(!(o in r.templates)){w.error(`Template '${o}' not found`);return}if(!n.force){if(!await V({initialValue:!1,message:`Are you sure you want to delete template '${o}'?`})){w.info("Deletion cancelled");return}}delete r.templates[o],await Vi(r,n.global??!1),w.success(`Template '${o}' deleted`)}async function so(n,r,o=new Set){if(o.has(n.name))throw Error(`Circular template dependency detected: ${n.name}`);o.add(n.name);let i={};if(n.extends){let f=r[n.extends];if(f)i=await so(f,r,o)}let{name:s,description:c,extends:a,metadata:u,...t}=n;return{...i,...t}}I();Q();fn();Fn();nn();import{parseArgs as pa}from"util";async function da(){let n=process.argv.slice(3);if(n.includes("--help")||n.includes("-h")){let{help:o}=await Promise.resolve().then(() => (J(),Z));o("validate"),process.exit(0)}let{values:r}=pa({args:n,options:{config:{short:"c",type:"string"}},strict:!0});return{configPath:r.config}}async function zi(){let r=(await da()).configPath||await Kr();if(!r)w.error("No configuration file found. Create one with: hydra init"),process.exit(1);if(!await G.exists(r))w.error(`Configuration file not found: ${r}`),process.exit(1);w.info(`Validating configuration: ${l.dim(r)}`);try{let o=await G.readFile(r),i=r.endsWith(".toml")?Bun.TOML.parse(o):JSON.parse(o);Zn.parse(i),w.success("Configuration is valid"),process.exit(0)}catch(o){w.error(`Validation failed: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}}I();Q();fn();nn();pn();import{watch as ma}from"fs";import{parseArgs as ya}from"util";var yn=U({prefix:"watch"});async function wa(){let n=process.argv.slice(3);if(n.includes("--help")||n.includes("-h")){let{help:c}=await Promise.resolve().then(() => (J(),Z));c("watch"),process.exit(0)}let{values:r}=ya({args:n,options:{command:{default:"status",short:"C",type:"string"},config:{short:"c",type:"string"},debounce:{default:"1000",type:"string"},directory:{default:"./gh-runners",short:"d",type:"string"},exclude:{default:[],multiple:!0,type:"string"},profile:{short:"p",type:"string"}},strict:!0}),o=await W({configPath:r.config}),i=await T(o,r.profile);return di(i,{command:r.command,debounce:Number.parseInt(r.debounce,10),directory:r.directory,exclude:r.exclude})}async function Ai(){let n=await wa();if(!await G.exists(n.directory))yn.error(`Directory not found: ${n.directory}`),process.exit(1);yn.info(`Watching ${n.directory} for changes...`),yn.info(`Will run: hydra ${n.command}`),yn.info(`Debounce: ${n.debounce}ms`);let r=rn(),o=null,i=!1,s=async()=>{if(i)return;i=!0,r.start(`Running: hydra ${n.command}`);try{let{$:u}=awaitPromise.resolve(globalThis.Bun),t=await u`hydra ${n.command} -d ${n.directory}`.quiet();if(t.exitCode===0)r.stop(l.success("\u2713 Command completed successfully"));else r.stop(l.error(`\u2717 Command failed with exit code ${t.exitCode}`)),yn.error(t.stderr.toString())}catch(u){r.stop(l.error("\u2717 Command failed")),yn.error("Error running command:",u)}finally{i=!1}},c=(u,t)=>{if(!t)return;if(n.exclude.some((m)=>{if(m.includes("*"))return new RegExp(m.replace(/\*/g,".*")).test(t);return t.includes(m)}))return;if(yn.info(`Detected ${u}: ${t}`),o)clearTimeout(o);o=setTimeout(()=>{s()},n.debounce)};await void s();let a=ma(n.directory,{recursive:!0},c);process.on("SIGINT",()=>{yn.info(`
|
|
82
|
+
Stopping watch mode...`),a.close(),process.exit(0)}),await new Promise(()=>{})}var co={create:Fr,health:Hi,help:async()=>nr(),init:Gi,migrate:Pi,remove:Mi,run:Li,status:ji,template:Bi,validate:zi,watch:Ai},ba={c:"create",h:"help",i:"init",r:"run",rm:"remove",s:"status",w:"watch"};async function ga(){let r=process.argv.slice(2)[0]?.toLowerCase();if(!r||r==="--help"||r==="-h")nr(),process.exit(0);if(r==="--version"||r==="-v"||r==="version")console.log(Un),process.exit(0);let o=ba[r]||r,i=co[o];if(!i)console.error(`Unknown command: ${r}`),console.error(`
|
|
83
|
+
Available commands: ${Object.keys(co).sort().join(", ")}`),process.exit(1);let s=["create","health","help","init","migrate","remove","run","status","template","validate","watch"];for(let c of s)if(!(c in co))throw Error(`Missing command implementation: ${c}`);try{await i()}catch(c){if(console.error(`Error in ${o}:`,c instanceof Error?c.message:c),process.env.DEBUG||process.env.HYDRA_DEBUG)console.error(`
|
|
84
|
+
Debug Information:`),console.error(c);process.exit(1)}}await ga();
|
package/package.json
CHANGED
|
@@ -4,9 +4,13 @@
|
|
|
4
4
|
"hydra": "./dist/cli.js"
|
|
5
5
|
},
|
|
6
6
|
"dependencies": {
|
|
7
|
-
"@clack/prompts": "0.
|
|
7
|
+
"@clack/prompts": "1.0.0-alpha.6",
|
|
8
|
+
"@r5n/cli-core": "workspace:*"
|
|
8
9
|
},
|
|
9
10
|
"description": "A tool for spawning multiple local GitHub self-hosted runners",
|
|
11
|
+
"devDependencies": {
|
|
12
|
+
"@r5n/tools": "workspace:*"
|
|
13
|
+
},
|
|
10
14
|
"files": [
|
|
11
15
|
"dist",
|
|
12
16
|
"schema.json",
|
|
@@ -28,7 +32,6 @@
|
|
|
28
32
|
"registry": "https://registry.npmjs.org/"
|
|
29
33
|
},
|
|
30
34
|
"scripts": {
|
|
31
|
-
"analyze": "bun src/lib/bundle-analyzer.ts",
|
|
32
35
|
"benchmark": "bun src/scripts/benchmark.ts",
|
|
33
36
|
"build": "rm -rf dist && bun build.ts",
|
|
34
37
|
"clean": "rm -rf dist node_modules",
|
|
@@ -36,12 +39,10 @@
|
|
|
36
39
|
"package:dryRun": "bun run package:prepare && bun publish --dry-run --no-git-checks --access public --force && bun install",
|
|
37
40
|
"package:prepare": "NODE_ENV=production bun run build && bun ../../tools/scripts/prepare-publish.ts .",
|
|
38
41
|
"package:publish": "bun run package:prepare && bun publish --access public --no-git-checks && bun install",
|
|
39
|
-
"test": "bun test",
|
|
40
|
-
"test:chaos": "bun test src/__tests__/chaos.test.ts",
|
|
41
42
|
"type-check": "bun --bun tsc --noEmit",
|
|
42
43
|
"type-check:go": "tsgo"
|
|
43
44
|
},
|
|
44
45
|
"type": "module",
|
|
45
46
|
"types": "src/cli.ts",
|
|
46
|
-
"version": "0.5.
|
|
47
|
+
"version": "0.5.5"
|
|
47
48
|
}
|
package/schema.json
CHANGED
|
@@ -11,15 +11,8 @@
|
|
|
11
11
|
"description": "Directory where runners will be created",
|
|
12
12
|
"type": "string"
|
|
13
13
|
},
|
|
14
|
-
"labels": {
|
|
15
|
-
|
|
16
|
-
"type": "string"
|
|
17
|
-
},
|
|
18
|
-
"name": {
|
|
19
|
-
"default": "runner",
|
|
20
|
-
"description": "Base name for the runners",
|
|
21
|
-
"type": "string"
|
|
22
|
-
},
|
|
14
|
+
"labels": { "description": "Comma-separated list of labels for the runners", "type": "string" },
|
|
15
|
+
"name": { "default": "runner", "description": "Base name for the runners", "type": "string" },
|
|
23
16
|
"numberOfMachines": {
|
|
24
17
|
"default": 1,
|
|
25
18
|
"description": "Number of runner machines to create",
|
|
@@ -32,22 +25,14 @@
|
|
|
32
25
|
"enum": ["osx", "linux", "windows"],
|
|
33
26
|
"type": "string"
|
|
34
27
|
},
|
|
35
|
-
"overwrite": {
|
|
36
|
-
"default": false,
|
|
37
|
-
"description": "Whether to overwrite existing runners",
|
|
38
|
-
"type": "boolean"
|
|
39
|
-
},
|
|
28
|
+
"overwrite": { "default": false, "description": "Whether to overwrite existing runners", "type": "boolean" },
|
|
40
29
|
"run": {
|
|
41
30
|
"default": false,
|
|
42
31
|
"description": "Whether to start runners immediately after creation",
|
|
43
32
|
"type": "boolean"
|
|
44
33
|
},
|
|
45
34
|
"runnerGroup": { "description": "Runner group to assign runners to", "type": "string" },
|
|
46
|
-
"url": {
|
|
47
|
-
"description": "GitHub repository or organization URL",
|
|
48
|
-
"format": "uri",
|
|
49
|
-
"type": "string"
|
|
50
|
-
}
|
|
35
|
+
"url": { "description": "GitHub repository or organization URL", "format": "uri", "type": "string" }
|
|
51
36
|
},
|
|
52
37
|
"type": "object"
|
|
53
38
|
}
|
|
@@ -55,10 +40,7 @@
|
|
|
55
40
|
"description": "Configuration for Hydra GitHub self-hosted runner manager",
|
|
56
41
|
"properties": {
|
|
57
42
|
"$schema": { "description": "JSON Schema reference for IDE support", "type": "string" },
|
|
58
|
-
"defaultProfile": {
|
|
59
|
-
"description": "The default profile to use when no profile is specified",
|
|
60
|
-
"type": "string"
|
|
61
|
-
},
|
|
43
|
+
"defaultProfile": { "description": "The default profile to use when no profile is specified", "type": "string" },
|
|
62
44
|
"profiles": {
|
|
63
45
|
"additionalProperties": { "$ref": "#/definitions/profile" },
|
|
64
46
|
"description": "Named profiles for different runner configurations",
|
package/dist/bundle-report.json
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"analysis": {
|
|
3
|
-
"files": [
|
|
4
|
-
{
|
|
5
|
-
"file": "dist/cli.js",
|
|
6
|
-
"size": 140858,
|
|
7
|
-
"sizeKB": 137.556640625,
|
|
8
|
-
"sizeMB": 0.13433265686035156
|
|
9
|
-
}
|
|
10
|
-
],
|
|
11
|
-
"totalSize": 140858,
|
|
12
|
-
"totalSizeKB": 137.556640625,
|
|
13
|
-
"totalSizeMB": 0.13433265686035156,
|
|
14
|
-
"warnings": []
|
|
15
|
-
},
|
|
16
|
-
"threshold": {
|
|
17
|
-
"exceeded": false,
|
|
18
|
-
"maxSizeMB": 1
|
|
19
|
-
},
|
|
20
|
-
"timestamp": "2025-08-08T09:09:45.779Z"
|
|
21
|
-
}
|