@r5n/hydra 0.12.0 → 0.13.0
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/README.md +8 -8
- package/dist/cli.js +113 -103
- package/package.json +1 -1
- package/schema.json +46 -8
package/dist/cli.js
CHANGED
|
@@ -1,106 +1,106 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`),
|
|
5
|
-
`){if(
|
|
6
|
-
`){if(
|
|
7
|
-
`)}var
|
|
8
|
-
`),
|
|
9
|
-
`),
|
|
10
|
-
`).map((
|
|
11
|
-
`)}function
|
|
12
|
-
`),
|
|
13
|
-
`).length-1;this.output.write(
|
|
14
|
-
`);this.output.write(
|
|
15
|
-
`).slice(
|
|
16
|
-
`)),this._prevFrame=e;return}}this.output.write(
|
|
17
|
-
`);
|
|
18
|
-
`:""}${o}
|
|
19
|
-
`,a=this.value?t:r;switch(this.state){case"submit":{let u=n?`${p("gray",E)} `:"";return`${l}${u}${p("dim",a)}`}case"cancel":{let u=n?`${p("gray",E)} `:"";return`${l}${u}${p(["strikethrough","dim"],a)}${n?`
|
|
20
|
-
${p("gray",E)}`:""}`}default:{let u=n?`${p("cyan",E)} `:"",f=n?p("cyan",ue):"";return`${l}${u}${this.value?`${p("green",Bt)} ${t}`:`${p("dim",Ve)} ${p("dim",t)}`}${e.vertical?n?`
|
|
21
|
-
${p("cyan",E)} `:`
|
|
22
|
-
`:` ${p("dim","/")} `}${this.value?`${p("dim",Ve)} ${p("dim",r)}`:`${p("green",Bt)} ${r}`}
|
|
23
|
-
${f}
|
|
24
|
-
`}}}}).prompt()};var Je=async(e,t)=>{let r={},n=Object.keys(e);for(let i of n){let s=e[i],o=await s({results:r})?.catch((l)=>{throw l});if(typeof t?.onCancel=="function"&&_e(o)){r[i]="canceled",t.onCancel({results:r});continue}r[i]=o}return r},is=[`${p("dim","\u2191/\u2193")} to navigate`,`${p("dim","Space:")} select`,`${p("dim","Enter:")} confirm`],Ie=(e,t)=>e.split(`
|
|
25
|
-
`).map((r)=>t(r)).join(`
|
|
26
|
-
`),ln=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${p("gray",Qr)} ${Ie(o,(l)=>p(["strikethrough","gray"],l))}${i.hint?` ${p("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${p("cyan",zi)} ${o}${i.hint?` ${p("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${p("green",Zr)} ${Ie(o,(l)=>p("dim",l))}${i.hint?` ${p("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${Ie(o,(l)=>p(["strikethrough","dim"],l))}`:s==="active-selected"?`${p("green",Zr)} ${o}${i.hint?` ${p("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${Ie(o,(l)=>p("dim",l))}`:`${p("dim",Qr)} ${Ie(o,(l)=>p("dim",l))}`},r=e.required??!0,n=e.showInstructions??!0;return new jt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:r,cursorAt:e.cursorAt,validate(i){if(r&&(i===void 0||i.length===0))return`Please select at least one option.
|
|
27
|
-
${p("reset",p("dim",`Press ${p(["gray","bgWhite","inverse"]," space ")} to select, ${p("gray",p("bgWhite",p("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??j.withGuide,s=le(e.output,e.message,i?`${sn(this.state)} `:"",`${Ge(this.state)} `),o=`${i?`${p("gray",E)}
|
|
3
|
+
var Sa=Object.create;var{getPrototypeOf:xa,defineProperty:co,getOwnPropertyNames:Ea}=Object;var lo=Object.prototype.hasOwnProperty;function ka(e){return this[e]}var _a,Ta,po=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var o=t?_a??=new WeakMap:Ta??=new WeakMap,i=o.get(e);if(i)return i}n=e!=null?Sa(xa(e)):{};let s=t||!e||!e.__esModule||!lo.call(e,"default")?co(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let c of Ea(e))if(!lo.call(s,c))co(s,c,{get:ka.bind(e,c),enumerable:!0})}if(r)o.set(e,s);return s};var Pa=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Jn=Pa(function(If,ko){var Vn={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Ka={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Va={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?Vn.up():"");if(e)t+=Vn.left;return t}};ko.exports={cursor:Vn,scroll:Ka,erase:Va,beep:"\x07"}});class de extends Error{constructor(e="Operation cancelled"){super(e)}}class y extends Error{hint;exitCode;constructor(e,t,n=1){super(e);this.hint=t;this.exitCode=n}}import{styleText as Ja}from"util";import{stdout as qn,stdin as To}from"process";import*as Ee from"readline";import Wa from"readline";var fo=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let n=0;e.lastIndex=0;while(e.test(t))n+=1;return t.length-n}})(),mo=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ho=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var Aa=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Ia=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,go=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Ha=/\t{1,1000}/y,yo=/[\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,Oa=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,La=/\p{M}+/gu,Na={limit:1/0,ellipsis:""},bo=(e,t={},n={})=>{let r=t.limit??1/0,o=t.ellipsis??"",i=t?.ellipsisWidth??(o?bo(o,Na,n).width:0),s=0,c=n.controlWidth??0,a=n.tabWidth??8,u=n.emojiWidth??2,d=2,p=n.regularWidth??1,m=n.wideWidth??2,h=[[Oa,p],[Aa,0],[Ia,c],[Ha,a],[yo,u],[go,m]],f=0,w=0,v=e.length,C=0,R=!1,P=v,H=Math.max(0,r-i),k=0,D=0,N=0,S=0;e:while(!0){if(D>k||w>=v&&w>f){let A=e.slice(k,D)||e.slice(f,w);C=0;for(let J of A.replaceAll(La,"")){let z=J.codePointAt(0)||0;if(mo(z))S=2;else if(ho(z))S=m;else S=p;if(N+S>H)P=Math.min(P,Math.max(k,f)+C);if(N+S>r){R=!0;break e}C+=J.length,N+=S}k=D=0}if(w>=v)break e;for(let A=0,J=h.length;A<J;A++){let[z,kt]=h[A];if(z.lastIndex=w,z.test(e)){if(C=z===go?fo(e.slice(w,z.lastIndex)):z===yo?1:z.lastIndex-w,S=C*kt,N+S>H)P=Math.min(P,w+Math.floor((H-N)/kt));if(N+S>r){R=!0;break e}N+=S,k=f,D=w,w=f=z.lastIndex;continue e}}w+=1}return{width:R?H:N,index:R?P:v,truncated:R,ellipsed:R&&r>=i}},wo=bo;var Da={limit:1/0,ellipsis:"",ellipsisWidth:0},Ga=(e,t={})=>wo(e,Da,t).width,Y=Ga;var Tt="\x1B",So="\x9B",Ma=39,Bn="\x07",xo="[",Fa="]",Eo="m",Kn=`${Fa}8;;`,$o=new RegExp(`(?:\\${xo}(?<code>\\d+)m|\\${Kn}(?<uri>.*)${Bn})`,"y"),vo=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},Ro=(e)=>`${Tt}${xo}${e}${Eo}`,Co=(e)=>`${Tt}${Kn}${e}${Bn}`,jn=(e,t,n)=>{let r=t[Symbol.iterator](),o=!1,i=!1,s=e.at(-1),c=s===void 0?0:Y(s),a=r.next(),u=r.next(),d=0;while(!a.done){let p=a.value,m=Y(p);if(c+m<=n)e[e.length-1]+=p;else e.push(p),c=0;if(p===Tt||p===So)o=!0,i=t.startsWith(Kn,d+1);if(o){if(i){if(p===Bn)o=!1,i=!1}else if(p===Eo)o=!1}else if(c+=m,c===n&&!u.done)e.push(""),c=0;a=u,u=r.next(),d+=p.length}if(s=e.at(-1),!c&&s!==void 0&&s.length&&e.length>1)e[e.length-2]+=e.pop()},Ua=(e)=>{let t=e.split(" "),n=t.length;while(n){if(Y(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},ja=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,i,s=e.split(" "),c=[""],a=0;for(let p=0;p<s.length;p++){let m=s[p];if(n.trim!==!1){let f=c.at(-1)??"",w=f.trimStart();if(f.length!==w.length)c[c.length-1]=w,a=Y(w)}if(p!==0){if(a>=t&&(n.wordWrap===!1||n.trim===!1))c.push(""),a=0;if(a||n.trim===!1)c[c.length-1]+=" ",a++}let h=Y(m);if(n.hard&&h>t){let f=t-a,w=1+Math.floor((h-f-1)/t);if(Math.floor((h-1)/t)<w)c.push("");jn(c,m,t),a=Y(c.at(-1)??"");continue}if(a+h>t&&a&&h){if(n.wordWrap===!1&&a<t){jn(c,m,t),a=Y(c.at(-1)??"");continue}c.push(""),a=0}if(a+h>t&&n.wordWrap===!1){jn(c,m,t),a=Y(c.at(-1)??"");continue}c[c.length-1]+=m,a+=h}if(n.trim!==!1)c=c.map((p)=>Ua(p));let u=c.join(`
|
|
4
|
+
`),d=!1;for(let p=0;p<u.length;p++){let m=u[p];if(r+=m,!d){if(d=m>="\uD800"&&m<="\uDBFF",d)continue}else d=!1;if(m===Tt||m===So){$o.lastIndex=p+1;let f=$o.exec(u)?.groups;if(f?.code!==void 0){let w=Number.parseFloat(f.code);o=w===Ma?void 0:w}else if(f?.uri!==void 0)i=f.uri.length===0?void 0:f.uri}if(u[p+1]===`
|
|
5
|
+
`){if(i)r+=Co("");let h=o?vo(o):void 0;if(o&&h)r+=Ro(h)}else if(m===`
|
|
6
|
+
`){if(o&&vo(o))r+=Ro(o);if(i)r+=Co(i)}}return r},Ba=/\r?\n/;function he(e,t,n){return String(e).normalize().split(Ba).map((r)=>ja(r,t,n)).join(`
|
|
7
|
+
`)}var W=po(Jn(),1);import{ReadStream as _o}from"tty";function Ne(e,t,n){if(!n.some((s)=>!s.disabled))return e;let r=e+t,o=Math.max(n.length-1,0),i=r<0?o:r>o?0:r;return n[i]?.disabled?Ne(i,t<0?-1:1,n):i}var qa=["up","down","left","right","space","enter","cancel"],za=["January","February","March","April","May","June","July","August","September","October","November","December"],K={actions:new Set(qa),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...za],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function zn(e,t){if(typeof e=="string")return K.aliases.get(e)===t;for(let n of e)if(n!==void 0&&zn(n,t))return!0;return!1}function Ya(e,t){if(e===t)return;let n=e.split(`
|
|
8
|
+
`),r=t.split(`
|
|
9
|
+
`),o=Math.max(n.length,r.length),i=[];for(let s=0;s<o;s++)n[s]!==r[s]&&i.push(s);return{lines:i,numLinesBefore:n.length,numLinesAfter:r.length,numLines:o}}var Xa=globalThis.process.platform.startsWith("win"),Wn=Symbol("clack:cancel");function lt(e){return e===Wn}function Pt(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Po({input:e=To,output:t=qn,overwrite:n=!0,hideCursor:r=!0}={}){let o=Ee.createInterface({input:e,output:t,prompt:"",tabSize:1});Ee.emitKeypressEvents(e,o),e instanceof _o&&e.isTTY&&e.setRawMode(!0);let i=(s,{name:c,sequence:a})=>{let u=String(s);if(zn([u,c,a],"cancel")){r&&t.write(W.cursor.show),process.exit(0);return}if(!n)return;Ee.moveCursor(t,c==="return"?0:-1,c==="return"?-1:0,()=>{Ee.clearLine(t,1,()=>{e.once("keypress",i)})})};return r&&t.write(W.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),r&&t.write(W.cursor.show),e instanceof _o&&e.isTTY&&!Xa&&e.setRawMode(!1),o.terminal=!1,o.close()}}var dt=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Yn=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function ke(e,t,n,r=n,o=n,i){let s=dt(e??qn);return he(t,s-n.length,{hard:!0,trim:!1}).split(`
|
|
10
|
+
`).map((c,a,u)=>{let d=i?i(c,a):c;return a===0?`${r}${d}`:a===u.length-1?`${o}${d}`:`${n}${d}`}).join(`
|
|
11
|
+
`)}function Ao(e,t){if("~standard"in e){let n=e["~standard"].validate(t);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return e(t)}class pt{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=To,output:r=qn,render:o,signal:i,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=o.bind(this),this._track=t,this._abortSignal=i,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let o of n)o.cb(...t),o.once&&r.push(()=>n.splice(n.indexOf(o),1));for(let o of r)o()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Wn);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Wa.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),Pt(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(W.cursor.show),this.output.off("resize",this.render),Pt(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(W.cursor.show),this.output.off("resize",this.render),Pt(this.input,!1),e(Wn)})})}_isActionKey(e,t){return e==="\t"}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&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(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&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"),t?.name&&(!this._track&&K.aliases.has(t.name)&&this.emit("cursor",K.aliases.get(t.name)),K.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let n=Ao(this.opts.validate,this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}zn([e,t?.name,t?.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(`
|
|
12
|
+
`),Pt(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=he(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
13
|
+
`).length-1;this.output.write(W.cursor.move(-999,e*-1))}render(){let e=he(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(W.cursor.hide);else{let t=Ya(this._prevFrame,e),n=Yn(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),o=Math.max(0,t.numLinesBefore-n),i=t.lines.find((s)=>s>=r);if(i===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(W.cursor.move(0,i-o)),this.output.write(W.erase.lines(1));let s=e.split(`
|
|
14
|
+
`);this.output.write(s[i]),this._prevFrame=e,this.output.write(W.cursor.move(0,s.length-i-1));return}else if(t.lines.length>1){if(r<o)i=r;else{let c=i-o;c>0&&this.output.write(W.cursor.move(0,c))}this.output.write(W.erase.down());let s=e.split(`
|
|
15
|
+
`).slice(i);this.output.write(s.join(`
|
|
16
|
+
`)),this._prevFrame=e;return}}this.output.write(W.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}class Xn extends pt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(W.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class Zn extends pt{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?Ne(t,1,this.options):t,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=Ne(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ne(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Io=class extends pt{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let t=this._selectedValue;this.value=t===void 0?void 0:t.value}constructor(t){super(t,!1),this.options=t.options;let n=this.options.findIndex(({value:o})=>o===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?Ne(r,1,this.options):r,this.changeValue(),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=Ne(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ne(this.cursor,1,this.options);break}this.changeValue()})}};class Qn extends pt{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${Ja("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as g,stripVTControlCharacters as qf}from"util";import ie from"process";var mt=po(Jn(),1);function Za(){if(ie.platform!=="win32")return ie.env.TERM!=="linux";return Boolean(ie.env.CI)||Boolean(ie.env.WT_SESSION)||Boolean(ie.env.TERMINUS_SUBLIME)||ie.env.ConEmuTask==="{cmd::Cmder}"||ie.env.TERM_PROGRAM==="Terminus-Sublime"||ie.env.TERM_PROGRAM==="vscode"||ie.env.TERM==="xterm-256color"||ie.env.TERM==="alacritty"||ie.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var er=Za(),Qa=()=>process.env.CI==="true";var O=(e,t)=>er?e:t,eu=O("\u25C6","*"),Do=O("\u25A0","x"),Go=O("\u25B2","x"),Ht=O("\u25C7","o"),tu=O("\u250C","T"),_=O("\u2502","|"),_e=O("\u2514","\u2014"),Zf=O("\u2510","T"),Qf=O("\u2518","\u2014"),tr=O("\u25CF",">"),It=O("\u25CB"," "),nu=O("\u25FB","[\u2022]"),Ho=O("\u25FC","[+]"),Oo=O("\u25FB","[ ]"),em=O("\u25AA","\u2022"),Lo=O("\u2500","-"),ru=O("\u256E","+"),ou=O("\u251C","+"),iu=O("\u256F","+"),su=O("\u2570","+"),tm=O("\u256D","+"),au=O("\u25CF","\u2022"),uu=O("\u25C6","*"),cu=O("\u25B2","!"),lu=O("\u25A0","x"),Ot=(e)=>{switch(e){case"initial":case"active":return g("cyan",eu);case"cancel":return g("red",Do);case"error":return g("yellow",Go);case"submit":return g("green",Ht)}},Mo=(e)=>{switch(e){case"initial":case"active":return g("cyan",_);case"cancel":return g("red",_);case"error":return g("yellow",_);case"submit":return g("green",_)}};function Fo(e,t){let n=[`${t?`${g("cyan",_)} `:""}${e.join(" \u2022 ")}`];return t&&n.push(g("cyan",_e)),n}var No=(e,t,n,r,o,i=!1)=>{let s=t,c=0;if(i)for(let a=r-1;a>=n;a--){let u=e[a];if(u&&(s-=u.length),c++,s<=o)break}else for(let a=n;a<r;a++){let u=e[a];if(u&&(s-=u.length),c++,s<=o)break}return{lineCount:s,removals:c}},nr=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:s=4})=>{let c=dt(r)-i,a=Yn(r),u=g("dim","..."),d=Math.max(a-s,0),p=Math.max(Math.min(o,d),5),m=0;e>=p-3&&(m=Math.max(Math.min(e-p+3,t.length-p),0));let h=p<t.length&&m>0,f=p<t.length&&m+p<t.length,w=Math.min(m+p,t.length),v=[],C=0;h&&C++,f&&C++;let R=m+(h?1:0),P=w-(f?1:0);for(let k=R;k<P;k++){let D=t[k],N=D?n(D,k===e):"",S=he(N,c,{hard:!0,trim:!1}).split(`
|
|
17
|
+
`);v.push(S),C+=S.length}if(C>d){let k=0,D=0,N=C,S=e-R,A=d,J=()=>No(v,N,0,S,A),z=()=>No(v,N,S+1,v.length,A,!0);h?({lineCount:N,removals:k}=J(),N>A&&(f||(A-=1),{lineCount:N,removals:D}=z())):(f||(A-=1),{lineCount:N,removals:D}=z(),N>A&&(A-=1,{lineCount:N,removals:k}=J())),k>0&&(h=!0,v.splice(0,k)),D>0&&(f=!0,v.splice(v.length-D,D))}let H=[];h&&H.push(u);for(let k of v)for(let D of k)H.push(D);return f&&H.push(u),H};var Uo=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new Xn({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??K.withGuide,o=`${Ot(this.state)} `,i=r?`${g("gray",_)} `:"",s=ke(e.output,e.message,i,o),c=`${r?`${g("gray",_)}
|
|
28
18
|
`:""}${s}
|
|
29
|
-
`,
|
|
30
|
-
${
|
|
31
|
-
|
|
32
|
-
`),
|
|
33
|
-
|
|
34
|
-
`).
|
|
35
|
-
|
|
36
|
-
${
|
|
37
|
-
`}
|
|
38
|
-
|
|
39
|
-
|
|
19
|
+
`,a=this.value?t:n;switch(this.state){case"submit":{let u=r?`${g("gray",_)} `:"";return`${c}${u}${g("dim",a)}`}case"cancel":{let u=r?`${g("gray",_)} `:"";return`${c}${u}${g(["strikethrough","dim"],a)}${r?`
|
|
20
|
+
${g("gray",_)}`:""}`}default:{let u=r?`${g("cyan",_)} `:"",d=r?g("cyan",_e):"";return`${c}${u}${this.value?`${g("green",tr)} ${t}`:`${g("dim",It)} ${g("dim",t)}`}${e.vertical?r?`
|
|
21
|
+
${g("cyan",_)} `:`
|
|
22
|
+
`:` ${g("dim","/")} `}${this.value?`${g("dim",It)} ${g("dim",n)}`:`${g("green",tr)} ${n}`}
|
|
23
|
+
${d}
|
|
24
|
+
`}}}}).prompt()};var Lt=async(e,t)=>{let n={},r=Object.keys(e);for(let o of r){let i=e[o],s=await i({results:n})?.catch((c)=>{throw c});if(typeof t?.onCancel=="function"&<(s)){n[o]="canceled",t.onCancel({results:n});continue}n[o]=s}return n},du=[`${g("dim","\u2191/\u2193")} to navigate`,`${g("dim","Space:")} select`,`${g("dim","Enter:")} confirm`],ft=(e,t)=>e.split(`
|
|
25
|
+
`).map((n)=>t(n)).join(`
|
|
26
|
+
`),jo=(e)=>{let t=(o,i)=>{let s=o.label??String(o.value);return i==="disabled"?`${g("gray",Oo)} ${ft(s,(c)=>g(["strikethrough","gray"],c))}${o.hint?` ${g("dim",`(${o.hint??"disabled"})`)}`:""}`:i==="active"?`${g("cyan",nu)} ${s}${o.hint?` ${g("dim",`(${o.hint})`)}`:""}`:i==="selected"?`${g("green",Ho)} ${ft(s,(c)=>g("dim",c))}${o.hint?` ${g("dim",`(${o.hint})`)}`:""}`:i==="cancelled"?`${ft(s,(c)=>g(["strikethrough","dim"],c))}`:i==="active-selected"?`${g("green",Ho)} ${s}${o.hint?` ${g("dim",`(${o.hint})`)}`:""}`:i==="submitted"?`${ft(s,(c)=>g("dim",c))}`:`${g("dim",Oo)} ${ft(s,(c)=>g("dim",c))}`},n=e.required??!0,r=e.showInstructions??!0;return new Zn({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(o){if(n&&(o===void 0||o.length===0))return`Please select at least one option.
|
|
27
|
+
${g("reset",g("dim",`Press ${g(["gray","bgWhite","inverse"]," space ")} to select, ${g("gray",g("bgWhite",g("inverse"," enter ")))} to submit`))}`},render(){let o=e.withGuide??K.withGuide,i=ke(e.output,e.message,o?`${Mo(this.state)} `:"",`${Ot(this.state)} `),s=`${o?`${g("gray",_)}
|
|
28
|
+
`:""}${i}
|
|
29
|
+
`,c=this.value??[],a=(u,d)=>{if(u.disabled)return t(u,"disabled");let p=c.includes(u.value);return d&&p?t(u,"active-selected"):p?t(u,"selected"):t(u,d?"active":"inactive")};switch(this.state){case"submit":{let u=this.options.filter(({value:p})=>c.includes(p)).map((p)=>t(p,"submitted")).join(g("dim",", "))||g("dim","none"),d=ke(e.output,u,o?`${g("gray",_)} `:"");return`${s}${d}`}case"cancel":{let u=this.options.filter(({value:p})=>c.includes(p)).map((p)=>t(p,"cancelled")).join(g("dim",", "));if(u.trim()==="")return`${s}${g("gray",_)}`;let d=ke(e.output,u,o?`${g("gray",_)} `:"");return`${s}${d}${o?`
|
|
30
|
+
${g("gray",_)}`:""}`}case"error":{let u=o?`${g("yellow",_)} `:"",d=this.error.split(`
|
|
31
|
+
`).map((h,f)=>f===0?`${o?`${g("yellow",_e)} `:""}${g("yellow",h)}`:` ${h}`).join(`
|
|
32
|
+
`),p=s.split(`
|
|
33
|
+
`).length,m=d.split(`
|
|
34
|
+
`).length+1;return`${s}${u}${nr({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:u.length,rowPadding:p+m,style:a}).join(`
|
|
40
35
|
${u}`)}
|
|
41
36
|
${d}
|
|
42
|
-
`}
|
|
43
|
-
`)
|
|
37
|
+
`}default:{let u=o?`${g("cyan",_)} `:"",d=s.split(`
|
|
38
|
+
`).length,p=r?Fo(du,o):o?[g("cyan",_e)]:[],m=p.join(`
|
|
39
|
+
`),h=p.length+1;return`${s}${u}${nr({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:u.length,rowPadding:d+h,style:a}).join(`
|
|
40
|
+
${u}`)}
|
|
41
|
+
${m}
|
|
42
|
+
`}}}}).prompt()};var b={message:(e=[],{symbol:t=g("gray",_),secondarySymbol:n=g("gray",_),output:r=process.stdout,spacing:o=1,withGuide:i}={})=>{let s=[],c=i??K.withGuide,a=c?n:"",u=c?`${t} `:"",d=c?`${n} `:"";for(let m=0;m<o;m++)s.push(a);let p=Array.isArray(e)?e:e.split(`
|
|
43
|
+
`);if(p.length>0){let[m,...h]=p;m.length>0?s.push(`${u}${m}`):s.push(c?t:"");for(let f of h)f.length>0?s.push(`${d}${f}`):s.push(c?n:"")}r.write(`${s.join(`
|
|
44
44
|
`)}
|
|
45
|
-
`)},info:(e,t)=>{b.message(e,{...t,symbol:
|
|
46
|
-
`)},
|
|
47
|
-
${
|
|
45
|
+
`)},info:(e,t)=>{b.message(e,{...t,symbol:g("blue",au)})},success:(e,t)=>{b.message(e,{...t,symbol:g("green",uu)})},step:(e,t)=>{b.message(e,{...t,symbol:g("green",Ht)})},warn:(e,t)=>{b.message(e,{...t,symbol:g("yellow",cu)})},warning:(e,t)=>{b.warn(e,t)},error:(e,t)=>{b.message(e,{...t,symbol:g("red",lu)})}};var Nt=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??K.withGuide?`${g("gray",tu)} `:"";n.write(`${r}${e}
|
|
46
|
+
`)},Dt=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??K.withGuide?`${g("gray",_)}
|
|
47
|
+
${g("gray",_e)} `:"";n.write(`${r}${e}
|
|
48
48
|
|
|
49
|
-
`)};var
|
|
50
|
-
`),
|
|
51
|
-
`).map(
|
|
52
|
-
`),
|
|
53
|
-
`:"",
|
|
49
|
+
`)};var pu=(e)=>e,fu=(e,t,n)=>{let r={hard:!0,trim:!1},o=he(e,t,r).split(`
|
|
50
|
+
`),i=o.reduce((a,u)=>Math.max(Y(u),a),0),s=o.map(n).reduce((a,u)=>Math.max(Y(u),a),0),c=t-(s-i);return he(e,c,r)},We=(e="",t="",n)=>{let r=n?.output??ie.stdout,o=n?.withGuide??K.withGuide,i=n?.format??pu,s=["",...fu(e,dt(r)-6,i).split(`
|
|
51
|
+
`).map(i),""],c=Y(t),a=Math.max(s.reduce((m,h)=>{let f=Y(h);return f>m?f:m},0),c)+2,u=s.map((m)=>`${g("gray",_)} ${m}${" ".repeat(a-Y(m))}${g("gray",_)}`).join(`
|
|
52
|
+
`),d=o?`${g("gray",_)}
|
|
53
|
+
`:"",p=o?ou:su;r.write(`${d}${g("green",Ht)} ${g("reset",t)} ${g("gray",Lo.repeat(Math.max(a-c-1,1))+ru)}
|
|
54
54
|
${u}
|
|
55
|
-
${
|
|
56
|
-
`)};var
|
|
57
|
-
`);let
|
|
58
|
-
`);
|
|
59
|
-
`);let
|
|
60
|
-
`):
|
|
61
|
-
`)),
|
|
55
|
+
${g("gray",p+Lo.repeat(a+2)+iu)}
|
|
56
|
+
`)};var mu=(e)=>g("magenta",e),Z=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:o,frames:i=er?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:s=er?80:120,signal:c,...a}={})=>{let u=Qa(),d,p,m=!1,h=!1,f="",w,v=performance.now(),C=dt(n),R=a?.styleFrame??mu,P=(G)=>{let oe=G>1?o??K.messages.error:r??K.messages.cancel;h=G===1,m&&(ct(oe,G),h&&typeof t=="function"&&t())},H=()=>P(2),k=()=>P(1),D=()=>{process.on("uncaughtExceptionMonitor",H),process.on("unhandledRejection",H),process.on("SIGINT",k),process.on("SIGTERM",k),process.on("exit",P),c&&c.addEventListener("abort",k)},N=()=>{process.removeListener("uncaughtExceptionMonitor",H),process.removeListener("unhandledRejection",H),process.removeListener("SIGINT",k),process.removeListener("SIGTERM",k),process.removeListener("exit",P),c&&c.removeEventListener("abort",k)},S=()=>{if(w===void 0)return;u&&n.write(`
|
|
57
|
+
`);let G=he(w,C,{hard:!0,trim:!1}).split(`
|
|
58
|
+
`);G.length>1&&n.write(mt.cursor.up(G.length-1)),n.write(mt.cursor.to(0)),n.write(mt.erase.down())},A=(G)=>G.replace(/\.+$/,""),J=(G)=>{let oe=(performance.now()-G)/1000,we=Math.floor(oe/60),$e=Math.floor(oe%60);return we>0?`[${we}m ${$e}s]`:`[${$e}s]`},z=a.withGuide??K.withGuide,kt=(G="")=>{m=!0,d=Po({output:n}),f=A(G),v=performance.now(),z&&n.write(`${g("gray",_)}
|
|
59
|
+
`);let oe=0,we=0;D(),p=setInterval(()=>{if(u&&f===w)return;S(),w=f;let $e=R(i[oe]),_t;if(u)_t=`${$e} ${f}...`;else if(e==="timer")_t=`${$e} ${f} ${J(v)}`;else{let Ca=".".repeat(Math.floor(we)).slice(0,3);_t=`${$e} ${f}${Ca}`}let Ra=he(_t,C,{hard:!0,trim:!1});n.write(Ra),oe=oe+1<i.length?oe+1:0,we=we<4?we+0.125:0},s)},ct=(G="",oe=0,we=!1)=>{if(!m)return;m=!1,clearInterval(p),S();let $e=oe===0?g("green",Ht):oe===1?g("red",Do):g("red",Go);f=G??f,we||(e==="timer"?n.write(`${$e} ${f} ${J(v)}
|
|
60
|
+
`):n.write(`${$e} ${f}
|
|
61
|
+
`)),N(),d()};return{start:kt,stop:(G="")=>ct(G,0),message:(G="")=>{f=A(G??f)},cancel:(G="")=>ct(G,1),error:(G="")=>ct(G,2),clear:()=>ct("",0,!0),get isCancelled(){return h}}},nm={light:O("\u2500","-"),heavy:O("\u2501","="),block:O("\u2588","#")};var hu=[`${g("dim","\u2191/\u2193")} to navigate`,`${g("dim","Enter:")} confirm`],At=(e,t)=>e.includes(`
|
|
62
62
|
`)?e.split(`
|
|
63
|
-
`).map((
|
|
64
|
-
`):t(e),
|
|
65
|
-
`:""}${
|
|
66
|
-
`;switch(this.state){case"submit":{let a=
|
|
67
|
-
${
|
|
68
|
-
`).length,
|
|
69
|
-
`),d
|
|
63
|
+
`).map((n)=>t(n)).join(`
|
|
64
|
+
`):t(e),Bo=(e)=>{let t=(r,o)=>{if(r===void 0)return"";let i=r.label??String(r.value);switch(o){case"disabled":return`${g("gray",It)} ${At(i,(s)=>g("gray",s))}${r.hint?` ${g("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${At(i,(s)=>g("dim",s))}`;case"active":return`${g("green",tr)} ${i}${r.hint?` ${g("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${At(i,(s)=>g(["strikethrough","dim"],s))}`;default:return`${g("dim",It)} ${At(i,(s)=>g("dim",s))}`}},n=e.showInstructions??!0;return new Io({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??K.withGuide,o=`${Ot(this.state)} `,i=`${Mo(this.state)} `,s=ke(e.output,e.message,i,o),c=`${r?`${g("gray",_)}
|
|
65
|
+
`:""}${s}
|
|
66
|
+
`;switch(this.state){case"submit":{let a=r?`${g("gray",_)} `:"",u=ke(e.output,t(this.options[this.cursor],"selected"),a);return`${c}${u}`}case"cancel":{let a=r?`${g("gray",_)} `:"",u=ke(e.output,t(this.options[this.cursor],"cancelled"),a);return`${c}${u}${r?`
|
|
67
|
+
${g("gray",_)}`:""}`}default:{let a=r?`${g("cyan",_)} `:"",u=c.split(`
|
|
68
|
+
`).length,d=n?Fo(hu,r):r?[g("cyan",_e)]:[],p=d.join(`
|
|
69
|
+
`),m=d.length+1;return`${c}${a}${nr({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:u+m,style:(h,f)=>t(h,h.disabled?"disabled":f?"active":"inactive")}).join(`
|
|
70
70
|
${a}`)}
|
|
71
|
-
${
|
|
72
|
-
`}}}}).prompt()};var
|
|
73
|
-
`:""}${
|
|
74
|
-
`,
|
|
75
|
-
${
|
|
76
|
-
${a}${
|
|
77
|
-
`}case"submit":{let
|
|
78
|
-
${
|
|
79
|
-
${
|
|
80
|
-
`}}}}).prompt();var
|
|
81
|
-
`).trimEnd()}command(e,t){let
|
|
82
|
-
`).trimEnd()}formatPositionalUsage(e){return Object.entries(e).map(([t,
|
|
83
|
-
Run "${
|
|
84
|
-
Run "${this.commandPath} --help" for usage.`),process.exit(1);let
|
|
71
|
+
${p}
|
|
72
|
+
`}}}}).prompt()};var rm=`${g("gray",_)} `;var Ko=(e)=>new Qn({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??K.withGuide,n=`${`${t?`${g("gray",_)}
|
|
73
|
+
`:""}${Ot(this.state)} `}${e.message}
|
|
74
|
+
`,r=e.placeholder&&e.placeholder.length>0?g("inverse",e.placeholder[0])+g("dim",e.placeholder.slice(1)):g(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:r,i=this.value??"";switch(this.state){case"error":{let s=this.error?` ${g("yellow",this.error)}`:"",c=t?`${g("yellow",_)} `:"",a=t?g("yellow",_e):"";return`${n.trim()}
|
|
75
|
+
${c}${o}
|
|
76
|
+
${a}${s}
|
|
77
|
+
`}case"submit":{let s=i?` ${g("dim",i)}`:"",c=t?g("gray",_):"";return`${n}${c}${s}`}case"cancel":{let s=i?` ${g(["strikethrough","dim"],i)}`:"",c=t?g("gray",_):"";return`${n}${c}${s}${i.trim()?`
|
|
78
|
+
${c}`:""}`}default:{let s=t?`${g("cyan",_)} `:"",c=t?g("cyan",_e):"";return`${n}${s}${o}
|
|
79
|
+
${c}
|
|
80
|
+
`}}}}).prompt();var yu=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Wo=["black","blue","cyan","gray","green","magenta","red","white","yellow"],bu=["bold","dim","italic","underline","reset"],qo={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},wu={black:"\x1B[30m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",green:"\x1B[32m",magenta:"\x1B[35m",red:"\x1B[31m",white:"\x1B[37m",yellow:"\x1B[33m"},$u={black:"\x1B[40m",blue:"\x1B[44m",cyan:"\x1B[46m",gray:"\x1B[100m",green:"\x1B[42m",magenta:"\x1B[45m",red:"\x1B[41m",white:"\x1B[47m",yellow:"\x1B[43m"},Vo={"\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"};function Gt(e){return(t)=>yu?`${e}${t}${qo.reset}`:t}function vu(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32&&n!==27)return!1}return!0}function Jo({bright:e=!1,color:t}){let n=Bun.color(t,"ansi"),r=typeof n==="string"&&n.length>0&&vu(n)?n:wu[t];if(!r)return"";return e&&r in Vo?Vo[r]:r}var Ru=Wo.reduce((e,t)=>{let n=Jo({color:t});if(n)e[t]=Gt(n);let r=Jo({bright:!0,color:t});if(r)e[`${t}Bright`]=Gt(r);return e},{}),Cu=bu.reduce((e,t)=>(e[t]=Gt(qo[t]),e),{}),Su=Wo.reduce((e,t)=>{let n=$u[t];if(n){let r=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[r]=Gt(n)}return e},{}),l={...Ru,...Cu,...Su};function Mt(e){if(lt(e))throw new de;return e}function Eu(e){return e.map((t)=>t.key?`${l.bold(t.key)} ${l.dim(t.text)}`:l.dim(t.text)).join(l.dim(" \xB7 "))}function Ft(e){b.info(Eu(e))}var Ut={confirm:[{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],multiselect:[{key:"\u2191\u2193",text:"navigate"},{key:"Space",text:"toggle"},{key:"a",text:"all"},{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],select:[{key:"\u2191\u2193",text:"navigate"},{key:"Enter",text:"select"},{key:"Esc",text:"cancel"}],text:[{key:"Enter",text:"submit"},{key:"Esc",text:"cancel"}]};async function pe(e){return Ft(Ut.confirm),Mt(await Uo(e))}async function ve(e){return Ft(Ut.text),Mt(await Ko(e))}async function De(e){return Ft(Ut.select),Mt(await Bo({showInstructions:!1,...e}))}async function Ge(e){return Ft(Ut.multiselect),Mt(await jo({showInstructions:!1,...e}))}var ku=4;function qe(e,t=0){if(t>=ku)return;let n=[...e instanceof AggregateError?e.errors:[],...e.cause!==void 0?[e.cause]:[]];for(let r of n){if(b.info(l.dim(`caused by: ${r instanceof Error?r.message:String(r)}`)),r instanceof y&&r.hint)b.info(l.dim(` ${r.hint}`));if(r instanceof Error)qe(r,t+1)}}function rr(e){return e==null?[]:Array.isArray(e)?e:[e]}function _u(e,t,n,r){var o,i=e[t],s=~r.string.indexOf(t)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~r.boolean.indexOf(t)?n==="false"?!1:n==="true"||(e._.push((o=+n,o*0===0)?o:n),!!n):(o=+n,o*0===0)?o:n;e[t]=i==null?s:Array.isArray(i)?i.concat(s):[i,s]}function ht(e,t){e=e||[],t=t||{};var n,r,o,i,s,c={_:[]},a=0,u=0,d=0,p=e.length;let m=t.alias!==void 0,h=t.unknown!==void 0,f=t.default!==void 0;if(t.alias=t.alias||{},t.string=rr(t.string),t.boolean=rr(t.boolean),m)for(n in t.alias){r=t.alias[n]=rr(t.alias[n]);for(a=0;a<r.length;a++)(t.alias[r[a]]=r.concat(n)).splice(a,1)}for(a=t.boolean.length;a-- >0;){r=t.alias[t.boolean[a]]||[];for(u=r.length;u-- >0;)t.boolean.push(r[u])}for(a=t.string.length;a-- >0;){r=t.alias[t.string[a]]||[];for(u=r.length;u-- >0;)t.string.push(r[u])}if(f){for(n in t.default)if(i=typeof t.default[n],r=t.alias[n]=t.alias[n]||[],t[i]!==void 0){t[i].push(n);for(a=0;a<r.length;a++)t[i].push(r[a])}}let w=h?Object.keys(t.alias):[];for(a=0;a<p;a++){if(o=e[a],o==="--"){c._=c._.concat(e.slice(++a));break}for(u=0;u<o.length;u++)if(o.charCodeAt(u)!==45)break;if(u===0)c._.push(o);else if(o.substring(u,u+3)==="no-"){if(i=o.substring(u+3),h&&!~w.indexOf(i))return t.unknown(o);c[i]=!1}else{for(d=u+1;d<o.length;d++)if(o.charCodeAt(d)===61)break;i=o.substring(u,d),s=o.substring(++d)||(a+1===p||(""+e[a+1]).charCodeAt(0)===45||e[++a]),r=u===2?[i]:i;for(d=0;d<r.length;d++){if(i=r[d],h&&!~w.indexOf(i))return t.unknown("-".repeat(u)+i);_u(c,i,d+1<r.length||s,t)}}}if(f){for(n in t.default)if(c[n]===void 0)c[n]=t.default[n]}if(m)for(n in c){r=t.alias[n]||[];while(r.length>0)c[r.shift()]=c[n]}return c}var zo=1,Tu=2;function ze(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function or(e){let t={alias:{},boolean:[],default:{},string:[]};for(let[n,r]of Object.entries(e)){if(r.type==="boolean")t.boolean.push(n);else t.string.push(n);if(r.alias)t.alias[r.alias]=n;let o=ze(n);if(o!==n)t.alias[o]=n;if(r.default!==void 0)t.default[n]=r.default}return t}function jt(e,t){if(e in t)return`--${ze(e)}`;let n=Object.entries(t).find(([,r])=>r.alias===e)?.[0];if(n)return`--${ze(n)}`;return e.length===zo?`-${e}`:`--${ze(e)}`}function T(e,t,n){let{alias:r}=or(t),o=Object.keys(e).find((i)=>!Object.hasOwn(t,i)&&!Object.hasOwn(r,i));if(o!==void 0)throw new y(`Unknown option: ${jt(o,t)}`,n)}function Yo(e,t){for(let[r,o]of Object.entries(e))if(Array.isArray(o))throw new y(`${jt(r,t)} can only be provided once`);let n={...e};for(let[r,o]of Object.entries(t)){if(o.type!=="number")continue;let i=e[r];if(i===void 0)continue;let s=Number(i);if(typeof i==="boolean"||typeof i==="string"&&i.trim().length===0||!Number.isFinite(s)){let c=jt(r,t);throw new y(`Invalid number for ${c}: "${i}"`,`Use ${c}=<number> with a finite numeric value`)}n[r]=s}return n}function gt(e,t){let n=or(t);Xo(e,n,t,!0);let r=ht(e,n),o=r._[0],i=o?e.indexOf(o):-1,s=ht(i>=0?e.slice(0,i):e,n),{_:c,...a}=s;T(a,t,"Place command options after the command name");let{_:u,...d}=r,p=Object.fromEntries(Object.entries(d).filter(([h])=>(h in t)||(h in n.alias))),m=Yo(p,t);return{command:o,flags:m,restArgs:i>=0?e.slice(i+1):[]}}function ir(e,t={}){let n=or(t),r=Pu(e,n);Xo(r,n,t);let o=ht(r,n),{_:i,...s}=o;return{args:Yo(s,t),rawPositionals:i}}function Xo(e,t,n,r=!1){let o=new Set;for(let i of e){if(i==="--")break;let s=i.match(/^-+/)?.[0];if(!s)continue;let c=i.slice(s.length),a=c.split("=",zo)[0]??"",u=c.startsWith("no-")?[c.slice(3)]:s.length===Tu?[a]:[...a];for(let d of u){let p=Object.hasOwn(t.alias,d)?t.alias[d]??d:d;if(r&&!Object.hasOwn(n,p))continue;if(o.has(p))throw new y(`${jt(p,n)} can only be provided once`);o.add(p)}}}function Pu(e,t){let n=!0;return e.map((r)=>{if(r==="--")n=!1;if(!n)return r;return r.replace(/^--(no-[^=]+)(=.*)?$/,(o,i,s)=>{let c=t.alias[i];return c&&t.boolean.includes(c)?`--${c}${s??""}`:o})})}function sr(e,t){let n={},r=Object.entries(t);for(let[o,[i,s]]of r.entries())n[i]=s.variadic?e.slice(o):e[o];return n}function Zo(e,t){for(let[n,r]of Object.entries(t)){if(!r.required)continue;let o=e[n];if(Array.isArray(o)?o.length===0:!o)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}var Au=(e)=>e,E={arg:l.magenta,cmd:l.cyan,default:l.bold,desc:Au,flag:l.green,header:(e)=>l.bold(l.yellow(e)),hint:l.dim,name:(e)=>l.bold(l.cyan(e)),placeholder:l.magenta};class ar{metadata;commands;globalArgs;constructor(e,t,n){this.metadata=e;this.commands=t;this.globalArgs=n}version(){return`${E.name(this.metadata.name)} ${E.hint(this.metadata.version??"0.0.0")}`}global(){let e=[],{name:t,bin:n,version:r,description:o}=this.metadata;if(e.push(`${E.name(t)}${r?` ${E.hint(`v${r}`)}`:""}`),o)e.push(E.desc(o));e.push(""),e.push(E.header("Usage:")),e.push(` ${E.cmd(n)} ${E.placeholder("[command]")} ${E.placeholder("[options]")}`),e.push(""),e.push(E.header("Commands:"));let i=Array.from(this.commands.values()).map((s)=>[` ${E.cmd(s.name)}`,E.desc(s.description)]);return e.push(...this.formatColumns(i)),e.push(""),e.push(E.header("Options:")),e.push(...this.formatArgDefs(this.globalArgs)),e.push(""),e.push(`${E.hint("Run")} ${E.cmd(`${n} <command> --help`)} ${E.hint("for command details.")}`),e.join(`
|
|
81
|
+
`).trimEnd()}command(e,t){let n=[],r=t??this.metadata.bin,o=`${r} ${e.name}`,i=`${E.cmd(r)} ${E.cmd(e.name)}`;n.push(E.name(o)),n.push(E.desc(e.description)),n.push(""),n.push(E.header("Usage:"));let s=this.formatPositionalUsage(e.positionals);if(e.hasSubcommands())n.push(` ${i} ${E.placeholder("<subcommand>")} ${E.placeholder("[options]")}`);else{let u=[i];if(s)u.push(s);u.push(E.placeholder("[options]")),n.push(` ${u.join(" ")}`)}if(e.prompts&&Object.keys(e.positionals).length>0)n.push(` ${E.hint("Omit positional arguments to run interactively.")}`);if(n.push(""),e.hasSubcommands()){n.push(E.header("Subcommands:"));let u=e.getSubcommands().map((d)=>[` ${E.cmd(d.name)}`,E.desc(d.description)]);n.push(...this.formatColumns(u)),n.push("")}if(Object.entries(e.positionals).length>0)n.push(E.header("Arguments:")),n.push(...this.formatPositionalDefs(e.positionals)),n.push("");if(Object.entries(e.args).length>0)n.push(E.header("Options:")),n.push(...this.formatArgDefs(e.args));return n.join(`
|
|
82
|
+
`).trimEnd()}formatPositionalUsage(e){return Object.entries(e).map(([t,n])=>{let r=n.variadic?`${t}...`:t;return n.required?E.arg(`<${r}>`):E.arg(`[${r}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([n,r])=>{let o=r.variadic?`${n}...`:n,i=E.desc(r.description??""),s=r.required?"":E.hint(" (optional)");return[` ${E.arg(o)}`,`${i}${s}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[n,r]of Object.entries(e)){let o=r.alias?`${E.flag(`-${r.alias}`)}, `:" ",i=r.type==="boolean"?"":` ${E.placeholder(`<${r.type==="number"?"number":"value"}>`)}`,s=`${o}${E.flag(`--${ze(n)}`)}${i}`,c=E.desc(r.description??""),a=this.formatDefault(r),u=a===void 0?"":` (default: ${E.default(a)})`;t.push([` ${s}`,`${c}${u}`])}return this.formatColumns(t)}formatDefault(e){if(typeof e.displayDefault==="string")return e.displayDefault;if(e.default===void 0)return;if(e.type==="boolean"&&e.default===!1)return;if(e.type==="string")return`"${e.default}"`;return String(e.default)}formatColumns(e){if(e.length===0)return[];let t=Math.max(...e.map(([r])=>this.stripAnsi(r).length)),n=2;return e.map(([r,o])=>{let i=t-this.stripAnsi(r).length+n;return`${r}${" ".repeat(i)}${o}`})}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}}var Re=new Uint32Array(65536),Iu=(e,t)=>{let n=e.length,r=t.length,o=1<<n-1,i=-1,s=0,c=n,a=n;while(a--)Re[e.charCodeAt(a)]|=1<<a;for(a=0;a<r;a++){let u=Re[t.charCodeAt(a)],d=u|s;if(u|=(u&i)+i^i,s|=~(u|i),i&=u,s&o)c++;if(i&o)c--;s=s<<1|1,i=i<<1|~(d|s),s&=d}a=n;while(a--)Re[e.charCodeAt(a)]=0;return c},Hu=(e,t)=>{let n=t.length,r=e.length,o=[],i=[],s=Math.ceil(n/32),c=Math.ceil(r/32);for(let f=0;f<s;f++)i[f]=-1,o[f]=0;let a=0;for(;a<c-1;a++){let f=0,w=-1,v=a*32,C=Math.min(32,r)+v;for(let R=v;R<C;R++)Re[e.charCodeAt(R)]|=1<<R;for(let R=0;R<n;R++){let P=Re[t.charCodeAt(R)],H=i[R/32|0]>>>R&1,k=o[R/32|0]>>>R&1,D=P|f,N=((P|k)&w)+w^w|P|k,S=f|~(N|w),A=w&N;if(S>>>31^H)i[R/32|0]^=1<<R;if(A>>>31^k)o[R/32|0]^=1<<R;S=S<<1|H,A=A<<1|k,w=A|~(D|S),f=S&D}for(let R=v;R<C;R++)Re[e.charCodeAt(R)]=0}let u=0,d=-1,p=a*32,m=Math.min(32,r-p)+p;for(let f=p;f<m;f++)Re[e.charCodeAt(f)]|=1<<f;let h=r;for(let f=0;f<n;f++){let w=Re[t.charCodeAt(f)],v=i[f/32|0]>>>f&1,C=o[f/32|0]>>>f&1,R=w|u,P=((w|C)&d)+d^d|w|C,H=u|~(P|d),k=d&P;if(h+=H>>>r-1&1,h-=k>>>r-1&1,H>>>31^v)i[f/32|0]^=1<<f;if(k>>>31^C)o[f/32|0]^=1<<f;H=H<<1|v,k=k<<1|C,d=k|~(R|H),u=H&R}for(let f=p;f<m;f++)Re[e.charCodeAt(f)]=0;return h},Ou=(e,t)=>{if(e.length<t.length){let n=t;t=e,e=n}if(t.length===0)return e.length;if(e.length<=32)return Iu(e,t);return Hu(e,t)},Qo=(e,t)=>{let n=1/0,r=0;for(let o=0;o<t.length;o++){let i=Ou(e,t[o]);if(i<n)n=i,r=o}return t[r]};function Bt(e,t,n,r){let o=Qo(t,n);if(console.error(l.red(`Unknown ${e}: ${t}`)),o)console.error(l.yellow(`Did you mean "${o}"?`));console.error(`
|
|
83
|
+
Run "${r} --help" for usage.`),process.exit(1)}function Kt(e,t){if(Array.isArray(t))return[...t];if(!ei(e)||!ei(t))return t;return Object.fromEntries([...Object.entries(e),...Object.entries(t).map(([n,r])=>[n,Kt(Object.hasOwn(e,n)?e[n]:void 0,r)])])}function ei(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var ur="__exit__";class Ye{command;env;prefix;options;selections;constructor(e,t,n,r={}){this.command=e;this.env=t;this.prefix=n;this.options=r;this.selections=r.selections??new Map}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(e,t){if(t&&process.stdout.isTTY!==!0)throw new y("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(t)await this.routeInteractive();else await this.routeDirect(e)}async routeDirect(e){let[t,...n]=e;if(t&&this.command.hasSubcommands()){let r=this.command.getSubcommand(t);if(r){await this.handleSubcommandRoute(r,n);return}if(!t.startsWith("-")){this.handleUnknownSubcommand(t);return}}await this.executeCommand(e)}handleUnknownSubcommand(e){let t=this.command.getSubcommands().map((n)=>n.name);Bt("subcommand",e,t,this.commandPath)}async handleSubcommandRoute(e,t){await new Ye(e,this.env,this.commandPath).route(t,!1)}async executeCommand(e){if(this.isHelpRequest(e)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:n,rawPositionals:r}=ir(e,this.command.args),o=sr(r,this.command.positionals),i=Zo(o,this.command.positionals);if(i)b.error(i),console.error(`
|
|
84
|
+
Run "${this.commandPath} --help" for usage.`),process.exit(1);let s=this.command.prompts&&r.length===0&&process.stdout.isTTY===!0,c=this.buildContext(o,n,s);await this.command.execute(c)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=ir([],this.command.args),t=sr([],this.command.positionals),n=this.buildContext(t,e,!0);await this.command.execute?.(n)}async runSubcommandMenu(){while(!0){let e=await this.promptSubcommandSelectionOrBack();if(e===null)return;if(e===ur){this.options.onExit?.();return}let t=this.command.getSubcommand(e);if(t)this.selections.set(this.commandPath,e),await this.executeSubcommand(t)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(e){if(e instanceof de){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new Ye(e,this.env,this.commandPath,{selections:this.selections}).route([],!0)}catch(t){if(t instanceof de)return;if(t instanceof y){if(b.warn(l.yellow(t.message)),t.hint)b.info(l.dim(t.hint));qe(t);return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:ur}:{hint:"Return to previous menu",label:"Back",value:ur};return De({message:e?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,initialValue:this.selections.get(this.commandPath),options:[...this.command.getSubcommands().map((n)=>({hint:n.description,label:n.name,value:n.name})),t]})}buildContext(e,t,n){return{...this.env,args:t,interactive:n,positionals:e}}isHelpRequest(e){let t=e.indexOf("--"),n=t<0?e:e.slice(0,t);return n.includes("--help")||n.includes("-h")}printHelp(e){let t=e===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(e,t))}}var Lu={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"},cr={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};class lr{commands=new Map;metadata;configManager;help;bin;globalArgs={...cr};constructor(e,t){this.configManager=e,this.metadata={...Lu,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new ar({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(e){for(let t of e)t.init?.(),this.commands.set(t.name,t)}async run(e=process.argv.slice(2)){try{let{command:t,flags:n,restArgs:r}=gt(e,this.globalArgs);if(n.version&&!t)return console.log(this.help.version());if(n.interactive&&!t)return await this.runInteractive();if(!t)return console.log(this.help.global());if(t==="help")return this.printHelpFor(r[0]);await this.runDirect(t,r,!!n.help)}catch(t){this.handleError(t)}}printHelpFor(e){if(!e)return console.log(this.help.global());let t=this.commands.get(e);if(!t)return this.handleUnknownCommand(e);console.log(this.help.command(t))}async runInteractive(){this.showIntro();let e=this.createVirtualRootCommand(),t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},n=new Ye(e,t,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await n.route([],!0)}catch(r){this.handleError(r)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(e)=>this.commands.get(e),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){Dt(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(e,t,n){let r=this.commands.get(e);if(!r)return this.handleUnknownCommand(e);let o=t.length>0&&!t[0]?.startsWith("-");if(n&&!o)return console.log(this.help.command(r));try{let i={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new Ye(r,i,this.bin).route(t,!1)}catch(i){this.handleError(i)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";Nt(`${l.bgCyan(l.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());Bt("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof de)process.exit(0);if(e instanceof y){if(b.warn(l.yellow(e.message)),e.hint)b.info(l.dim(e.hint));qe(e),process.exit(e.exitCode)}if(e instanceof Error)b.error(l.red(e.message)),qe(e),process.exit(1);console.error(l.red("Error:"),e),process.exit(1)}}class yt{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(e){for(let t of e)t.init?.(),this.subcommands.set(t.name,t)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(e){return this.subcommands.get(e)}getSubcommands(){return Array.from(this.subcommands.values())}}function L(e){return e}function B(e){return e}import se from"fs";import ni from"path";var bt=(e)=>(e.map=(t)=>bt((n)=>t(e(n))),e.or=(t)=>bt((n)=>{try{return e(n)}catch(r){return t(n)}}),e),F=()=>"bad banditype"();var wt=(e)=>bt((t)=>e.includes(t)?t:F()),Vt=(e)=>bt((t)=>typeof t===typeof e?t:F()),U=()=>Vt(""),Q=()=>Vt(0),te=()=>Vt(!0);var ti=()=>Vt();var Jt=(e)=>bt((t)=>t instanceof e?t:F());var ge=(e)=>Jt(Object).map((t)=>{let n={};for(let r in e){let o=e[r](t[r]);o!==void 0&&(n[r]=o)}return n});var Wt=(e)=>Jt(Array).map((t)=>t.map(e));function pr(e,t){JSON.parse(e);let n=JSON.parse(JSON.stringify(t)),r=Nu(e),o=e.match(/^[\t ]+(?=\S)/m)?.[0]??" ",i=e.includes(`\r
|
|
85
85
|
`)?`\r
|
|
86
86
|
`:`
|
|
87
|
-
`,
|
|
88
|
-
`));let
|
|
89
|
-
`));let
|
|
90
|
-
`)?
|
|
91
|
-
`))});return`${
|
|
92
|
-
`,
|
|
93
|
-
`,
|
|
94
|
-
`;if(z.writeFileSync(r,i,{flag:"wx",mode:n}),n!==void 0)z.chmodSync(r,n);z.renameSync(r,t)}catch(n){throw Error(`Failed to save config to ${this.configPath}`,{cause:n})}finally{z.rmSync(r,{force:!0})}}ensureDirectoryExists(){let e=Sn.dirname(this.configPath);if(!z.existsSync(e))try{z.mkdirSync(e,{recursive:!0})}catch(t){throw Error(`Failed to create config directory at ${e}`,{cause:t})}}loadConfig(){if(!z.existsSync(this.configPath))return structuredClone(this.defaultConfig);try{let e=z.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);if(Array.isArray(t))throw Error("Config must be an object");let r=Ps(t);return et(structuredClone(this.defaultConfig),r)}catch(e){return this.loadError=e,console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),structuredClone(this.defaultConfig)}}}var Rn="0.12.0";class I extends Oe{}var nt="hydra";var En=".hydra/config.json",te=".hydra/shared",De=".hydra/runners",Ne="default",_n={profiles:{}},kn=!1,An=24,it=7,In=["logs","shared"],Pn=!1,Tn=!0,On=!0,Dn=!0,Nn=120,Ln=["github.com","api.github.com","objects.githubusercontent.com","pipelines.actions.githubusercontent.com"];import{spawn as lo}from"child_process";import{once as uo}from"events";import{existsSync as ye}from"fs";import{cp as co,link as po,mkdir as mt,mkdtemp as mo,readdir as Yn,readFile as mr,readlink as fo,rename as ho,rm as $e,stat as Xn,symlink as go,unlink as Zn,writeFile as yo}from"fs/promises";import{join as k,resolve as fr}from"path";var Os=new Set(["github.com","www.github.com"]);var Fn=/\.git$/;function he(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid GitHub URL: ${e}`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error(`Invalid GitHub URL (expected http(s)): ${e}`);if(!Os.has(t.hostname))throw Error(`Invalid GitHub URL (host must be github.com): ${e}`);let r=t.pathname.split("/").filter(Boolean);if(r.length===1){let n=r[0]?.replace(Fn,"");if(!n)throw Error(`Invalid GitHub URL: ${e}`);return{kind:"org",org:n}}if(r.length===2){let n=r[0],i=r[1]?.replace(Fn,"");if(!n||!i)throw Error(`Invalid GitHub URL: ${e}`);return{kind:"repo",owner:n,repo:i}}throw Error(`Invalid GitHub URL (expected github.com/<owner>/<repo> or github.com/<org>): ${e}`)}function nr(e){return e.kind==="repo"?`${e.owner}/${e.repo}`:e.org}import{chmod as Ns,mkdir as Ls,readFile as Fs,rename as Hs,rm as Ms,stat as js,writeFile as Vn}from"fs/promises";import{dirname as Us,join as lr,resolve as ot}from"path";import{isAbsolute as Ds}from"path";var ir="# Generated by Hydra; hydra update rewrites this file.";function Hn(e){return`'${e.replaceAll("'","'\\''")}'`}function Mn(){return`#!/usr/bin/env bash
|
|
95
|
-
${
|
|
87
|
+
`,s=/\s/.test(e[r.start+1]??"")||r.entries.some((u)=>/:\s+$/.test(e.slice(u.start,u.node.start)))?" ":"";function c(u,d){let p=e.slice(u.start,u.end);if(JSON.stringify(u.value)===JSON.stringify(d))return p;let m=Array.isArray(d);if(d===null||typeof d!=="object"||u.value===null||typeof u.value!=="object"||Array.isArray(u.value)!==m)return a(d,u.start,p.includes(`
|
|
88
|
+
`));let h=m?d.map((S,A)=>String(A)):[...new Set([...u.entries.map((S)=>S.key).filter((S)=>Object.hasOwn(d,S)),...Object.keys(d)])];if(h.length===0)return m?"[]":"{}";let f=u.entries[0],w=u.entries.at(-1);if(!f||!w)return a(d,u.start,p.includes(`
|
|
89
|
+
`));let v=(S)=>m?d[Number(S)]:d[S];if(h.length===u.entries.length&&h.every((S,A)=>S===u.entries[A]?.key)){let S=u.start,A="";for(let J of u.entries)A+=e.slice(S,J.node.start)+c(J.node,v(J.key)),S=J.node.end;return A+e.slice(S,u.end)}let C=e.slice(u.start+1,f.start),R=e.slice(w.node.end,u.end-1),P=u.entries[1],H=P?e.slice(f.node.end,P.start):`,${C.includes(`
|
|
90
|
+
`)?C:s}`,k=m?"":e.slice(f.start,f.node.start).match(/:\s*$/)?.[0]??": ",D=new Map(u.entries.map((S)=>[S.key,S])),N=h.map((S)=>{let A=D.get(S);if(A)return e.slice(A.start,A.node.start)+c(A.node,v(S));return(m?"":JSON.stringify(S)+k)+a(v(S),f.start,C.includes(`
|
|
91
|
+
`))});return`${m?"[":"{"}${C}${N.join(H)}${R}${m?"]":"}"}`}function a(u,d,p){if(!p)return dr(u,s);let m=e.lastIndexOf(`
|
|
92
|
+
`,d-1)+1,h=e.slice(m,d).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(u,null,o).replaceAll(`
|
|
93
|
+
`,i+h)}return e.slice(0,r.start)+c(r,n)+e.slice(r.end)}function dr(e,t){if(Array.isArray(e))return`[${e.map((o)=>dr(o,t)).join(`,${t}`)}]`;if(e===null||typeof e!=="object")return JSON.stringify(e);let n=Object.entries(e);if(n.length===0)return"{}";let r=n.map(([o,i])=>`${JSON.stringify(o)}:${t}${dr(i,t)}`);return`{${t}${r.join(`,${t}`)}${t}}`}function Nu(e){let t=e.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),n=t.next().value;function r(){if(!n)throw Error("Unexpected end of JSON");let i=n;return n=t.next().value,i}function o(){let i=r(),s=[],c=i[0]==="{";if(!c&&i[0]!=="[")return{end:i.index+i[0].length,entries:s,start:i.index,value:JSON.parse(i[0])};let a=c?"}":"]";while(n&&n[0]!==a){let d=n.index,p=c?JSON.parse(r()[0]):String(s.length);if(c)r();if(s.push({key:p,node:o(),start:d}),n?.[0]===",")r()}let u=r().index+1;return{end:u,entries:s,start:i.index,value:JSON.parse(e.slice(i.index,u))}}return o()}var Du=2,Gu=Jt(Object);class fr{config;configPath;defaultConfig;loadError;loadFailure;constructor(e,t,n={}){this.configPath=ni.resolve(e),this.defaultConfig=t,this.config=this.loadConfig(n)}get path(){return this.configPath}get failure(){return this.loadFailure}get(e){return this.assertLoaded(),this.config[e]}set(e,t){this.assertLoaded(),this.config={...this.config,[e]:t},this.save()}delete(e){this.assertLoaded(),delete this.config[e],this.save()}exists(){return se.existsSync(this.configPath)}getAll(){return this.assertLoaded(),structuredClone(this.config)}save(e){if(this.assertLoaded(),this.loadError)throw Error(`Cannot overwrite unreadable config at ${this.configPath}; repair the file and try again`,{cause:this.loadError});if(e)this.config={...e};this.ensureDirectoryExists();let t=this.exists()?se.realpathSync(this.configPath):this.configPath,n=`${t}.${crypto.randomUUID()}.tmp`;try{let r=this.exists()?se.statSync(this.configPath).mode:void 0,o=this.exists()?pr(se.readFileSync(this.configPath,"utf-8"),this.config):`${JSON.stringify(this.config,null,Du)}
|
|
94
|
+
`;if(se.writeFileSync(n,o,{flag:"wx",mode:r}),r!==void 0)se.chmodSync(n,r);se.renameSync(n,t)}catch(r){throw Error(`Failed to save config to ${this.configPath}`,{cause:r})}finally{se.rmSync(n,{force:!0})}}assertLoaded(){if(this.loadFailure)throw this.loadFailure}ensureDirectoryExists(){let e=ni.dirname(this.configPath);if(!se.existsSync(e))try{se.mkdirSync(e,{recursive:!0})}catch(t){throw Error(`Failed to create config directory at ${e}`,{cause:t})}}loadConfig({parse:e,strict:t}){if(!t&&!se.existsSync(this.configPath))return structuredClone(this.defaultConfig);try{let n=this.readConfigFile();if(n===void 0)return structuredClone(this.defaultConfig);let r=JSON.parse(n);if(Array.isArray(r))throw Error("Config must be an object");let o=Kt(structuredClone(this.defaultConfig),Gu(r));return e?e(o):o}catch(n){if(t){let r=n instanceof Error?n.message:String(n);return this.loadFailure=Error(`Cannot read config at ${this.configPath}: ${r}`,{cause:n}),structuredClone(this.defaultConfig)}return this.loadError=n,console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),structuredClone(this.defaultConfig)}}readConfigFile(){try{return se.readFileSync(this.configPath,"utf-8")}catch(e){if(e.code==="ENOENT")return;throw e}}}var ri="0.13.0";class x extends yt{}var qt="hydra",$t="default",oi={profiles:{}},ii=!1,si=24,zt=7,ai=["logs","shared"],ui=!1,ci=!0,li=!0,di=!0,pi=120,fi=["github.com","api.github.com","objects.githubusercontent.com","pipelines.actions.githubusercontent.com"];import{readFileSync as Fu,statSync as mr}from"fs";import{homedir as Uu}from"os";import{basename as ju,dirname as gr,isAbsolute as hi,join as Te,resolve as Yt}from"path";var Xt=".hydra",ae="HYDRA_HOME",j="--home",Zt={description:"Use this state directory (absolute path)",displayDefault:`${ae} or ~/.hydra`,type:"string"},yr="config.json",Bu="runners",Ku="shared",Vu="--",Ju=`Pass ${j} <absolute path> or set ${ae}`;function gi(e){return Te(e.HOME||Uu(),Xt)}function yi(e,t){let{flag:n,rest:r}=Wu(e);if(n!==void 0)return{argv:r,home:mi(n,j),source:"flag"};let o=t[ae];if(o)return{argv:r,home:mi(o,ae),source:"environment"};return{argv:r,home:gi(t),source:"default"}}function Ce(e){return{config:Te(e,yr),home:e,runners:Te(e,Bu),shared:Te(e,Ku)}}function fe(e){return gr(e.path)}function br(e,t){if(hi(t))return t;return Yt(ju(e)===Xt?gr(e):e,t)}function bi(e,t){let n=Te(t,Xt);return $i(n)&&!hr(n,e)?n:void 0}function Qt(e,t,n){let r=[...wi(t).map((i)=>Te(i,Xt)),gi(n)],o=[];for(let i of r){if(!$i(i)||hr(i,e))continue;if(o.some((s)=>hr(s,i)))continue;o.push(i)}return o.map((i)=>({counts:qu(i),path:i}))}function Wu(e){let t=[],n;for(let r=0;r<e.length;r++){let o=e[r];if(o===Vu){t.push(...e.slice(r));break}let i=o.startsWith(`${j}=`);if(o!==j&&!i){t.push(o);continue}if(n!==void 0)throw new y(`${j} can only be provided once`);let s=i?o.slice(j.length+1):e[r+1];if(!s||!i&&s.startsWith("-"))throw new y(`${j} needs a directory`,`Use ${j} <absolute path>`);if(n=s,!i)r++}return{flag:n,rest:t}}function mi(e,t){if(!hi(e))throw new y(`${t} must be an absolute path: ${e}`,Ju);return Yt(e)}function wi(e){let t=gr(e);return t===e?[e]:[e,...wi(t)]}function $i(e){try{return mr(Te(e,yr)).isFile()}catch{return!1}}function hr(e,t){if(Yt(e)===Yt(t))return!0;try{let n=mr(e),r=mr(t);return n.dev===r.dev&&n.ino===r.ino}catch{return!1}}function vi(e){let t=Ri(e);if(!t)return;return(Array.isArray(t.runners)?t.runners:[]).flatMap((r)=>{if(typeof r!=="object"||r===null)return[];let{id:o,name:i}=r;return[o,i].filter((s)=>typeof s==="string")})}function qu(e){let t=Ri(e);if(!t)return;let{profiles:n,runners:r}=t;return{profiles:typeof n==="object"&&n!==null?Object.keys(n).length:0,runners:Array.isArray(r)?r.length:0}}function Ri(e){try{let t=JSON.parse(Fu(Te(e,yr),"utf-8"));return typeof t==="object"&&t!==null?t:void 0}catch{return}}var zu="https://api.github.com",Xe="HYDRA_GITHUB_API_URL",Yu="2022-11-28",Xu="r5n-hydra",Zu=3,Ti=500,Qu=60000,Pi=30000,en=1000,ec=100,Ci=100,tc=200,nc=403,Si=429,rc=204,oc=500,xi="[redacted]",ic=new Set(["DELETE","GET","PUT"]),sc=new Set(["127.0.0.1","[::1]"]),ac=[/\bgh[opsur]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_\w{20,}\b/g,/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g],uc=/[\p{Cc}\p{Cf}]+/gu,cc=/<([^>]+)>;\s*rel="next"/,lc=/\/+$/,dc=/^\/+/,pc=/\s+/g;class V extends Error{operation;method;path;status;_tag="GitHubApiError";constructor(e,t,n,r,o){let i=r===void 0?"got no response":`returned ${r}`;super(`${e} failed: ${t} ${n} ${i}${o?` (${o})`:""}`);this.operation=e;this.method=t;this.path=n;this.status=r;this.name="GitHubApiError"}}function tn(e){let t=e[Xe];if(!t)return zu;let n="Use an https URL, or http on 127.0.0.1 or [::1], with no credentials, query or fragment",r;try{r=new URL(t)}catch{throw new y(`${Xe} is not a URL`,n)}if(!(r.protocol==="https:"||r.protocol==="http:"&&sc.has(r.hostname))||r.username||r.password||r.search||r.hash)throw new y(`${Xe} is not an API root Hydra may send tokens to`,n);return r.href.replace(lc,"")}function wr({apiUrl:e,auth:t}){let n=new URL(`${e}/`);async function r(a,u,d,p,m){let h=i(u);for(let f=1;;f++){let w=await t.token(),v=f<Zu,C;try{C=await fetch(u,{body:p===void 0?void 0:JSON.stringify(p),headers:mc(w,p!==void 0),method:a,redirect:"manual",signal:AbortSignal.timeout(Pi)})}catch(H){if(m&&v){await Bun.sleep(Ei(f));continue}throw new V(d,a,h,void 0,_i(ki(H),w))}if(C.ok)return C;let R=hc(C);if(R!==void 0&&v&&R<=Qu){await C.body?.cancel(),await Bun.sleep(R);continue}if(R===void 0&&C.status>=oc&&m&&v){await C.body?.cancel(),await Bun.sleep(Ei(f));continue}let P=[R===void 0?"":gc(C),await yc(C)].filter(Boolean).join("; ");throw new V(d,a,h,C.status,_i(P,w))}}async function o(a,u,d,p,m){let h=i(m),f;try{f=a.status===rc?"":await a.text()}catch(v){throw new V(d,p,h,a.status,ki(v))}let w;try{w=f===""?void 0:JSON.parse(f)}catch{throw new V(d,p,h,a.status,"the response is not JSON")}try{return u(w)}catch{throw new V(d,p,h,a.status,"the response has an unexpected shape")}}function i(a){return a.pathname.slice(n.pathname.length-1)+a.search}function s(a){return new URL(a.replace(dc,""),n)}function c(a){return a.origin===n.origin&&a.pathname.startsWith(n.pathname)}return{async paginate({item:a,key:u,operation:d,path:p}){let m=[],h=s(p);if(!h.searchParams.has("per_page"))h.searchParams.set("per_page",String(ec));let f=h;for(let w=1;f;w++){if(w>Ci)throw new V(d,"GET",p,void 0,`stopped after ${Ci} pages`);let v=await r("GET",f,d,void 0,!0),C=v.headers.get("link"),R=await o(v,fc(a,u),d,"GET",f);m.push(...R);let P=C?.match(cc)?.[1];if(f=P?new URL(P):void 0,f&&!c(f))throw new V(d,"GET",p,v.status,"refused a next page outside the API root")}return m},async request({body:a,idempotent:u,method:d="GET",operation:p,path:m,schema:h}){let f=s(m),w=await r(d,f,p,a,u??ic.has(d));return o(w,h,p,d,f)}}}function Ai(e){let t,n=()=>(t??=e(),t);return{async paginate(r){return n().paginate(r)},async request(r){return n().request(r)}}}function fc(e,t){return(n)=>{let r=t===void 0?n:n?.[t];if(!Array.isArray(r))throw TypeError("not a list");return r.map((o)=>e(o))}}function mc(e,t){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"User-Agent":Xu,"X-GitHub-Api-Version":Yu,...t?{"Content-Type":"application/json"}:{}}}function Ei(e){return Ti*2**(e-1)}function hc(e){if(e.status!==nc&&e.status!==Si)return;let t=e.headers.get("retry-after");if(t!==null&&t.trim()!==""&&Number.isFinite(Number(t)))return Math.max(0,Number(t)*en);if(e.headers.get("x-ratelimit-remaining")==="0"){let n=e.headers.get("x-ratelimit-reset")?.trim(),r=n?Number(n):Number.NaN;return Number.isFinite(r)?Math.max(0,r*en-Date.now()):Number.POSITIVE_INFINITY}return e.status===Si?Ti:void 0}function gc(e){let t=Number(e.headers.get("x-ratelimit-reset")),n=Number(e.headers.get("retry-after"));if(Number.isFinite(n)&&n>0)return`rate limited; retry in ${n} s`;if(Number.isFinite(t)&&t>0)return`rate limited until ${new Date(t*en).toISOString()}`;return"rate limited"}async function yc(e){try{let n=JSON.parse(await e.text())?.message;return typeof n==="string"?n:""}catch{return""}}function ki(e){if(e instanceof Error&&e.name==="TimeoutError")return`timed out after ${Pi/en} s`;return e instanceof Error?e.message:String(e)}function _i(e,t){let n=t?e.replaceAll(t,xi):e;return ac.reduce((r,o)=>r.replace(o,xi),n).replace(uc," ").replace(pc," ").trim().slice(0,tc)}import{createPrivateKey as bc,sign as wc}from"crypto";import{constants as Ii}from"fs";import{open as $c,stat as vc}from"fs/promises";var Hi="github.com",Rc=60,Cc=540,Sc=300000,xc=1000,Ec=63,kc=511,_c=8,Tc=4,Pc=Ii.O_RDONLY|Ii.O_NONBLOCK,$r="Check the GitHub App's id, installation id and private key in credentials",vr=U().map((e)=>e.trim()===""?F():e),Ac=ge({expires_at:U(),token:vr}),Oi=new WeakMap;class Me extends y{_tag="GitHubCredentialsError"}function Ic(e,t){let n,r=()=>{if(n)return n;let o=tn(t),i=e?.mode==="app"?Oc(e,o):Hc();return n={client:wr({apiUrl:o,auth:i}),credentials:i},n};return{client:Ai(()=>r().client),credentials:{kind:e?.mode??"gh",async token(){return r().credentials.token()}}}}function nn(e){let t=Oi.get(e);if(t)return t;let n=Ic(e.get("credentials"),process.env);return Oi.set(e,n),n}function Ni(e){return e?.mode==="app"?`GitHub App ${e.appId}, installation ${e.installationId}, key ${e.privateKeyPath}`:"the gh login (gh auth token)"}async function Di(e){try{return Gi(await vc(e))}catch(t){return`cannot be read (${t.code??"unknown error"})`}}function Hc(){let e;return{kind:"gh",token(){return e??=Lc().catch((t)=>{throw e=void 0,t}),e}}}function Oc(e,t){let n=wr({apiUrl:t,auth:{token:async()=>Dc(e.appId,await Nc(e.privateKeyPath))}}),r,o;async function i(){try{let{expires_at:s,token:c}=await n.request({idempotent:!0,method:"POST",operation:`Mint an installation token for GitHub App ${e.appId}`,path:`/app/installations/${e.installationId}/access_tokens`,schema:Ac});return{expiresAt:Date.parse(s),token:c}}catch(s){throw s instanceof V?new Me(s.message,$r):s}}return{kind:"app",async token(){if(r&&r.expiresAt-Sc>Date.now())return r.token;o??=i().finally(()=>{o=void 0});let s=await o;return r=Number.isFinite(s.expiresAt)?s:void 0,s.token}}}async function Lc(){let e=await Bun.$`gh auth token --hostname ${Hi}`.quiet().nothrow(),t=e.stdout.toString().trim();if(e.exitCode===0&&t)return t;let n=e.stderr.toString().trim();throw new Me(`gh auth token failed for ${Hi}${n?`: ${n}`:""}`,"Run gh auth login, or configure a GitHub App in credentials")}async function Nc(e){let n;try{n=await $c(e,Pc)}catch(r){throw new Me(`Cannot open the GitHub App private key ${e} (${r.code??"unknown error"})`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600")}try{let r=Gi(await n.stat());if(r)throw new Me(`The GitHub App private key ${e} ${r}`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600");let o;try{o=bc(await n.readFile("utf8"))}catch{throw new Me(`The GitHub App private key ${e} is not a PEM private key`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600")}if(o.asymmetricKeyType!=="rsa")throw new Me(`The GitHub App private key ${e} is not an RSA key`,"credentials.privateKeyPath must name a PEM file owned by the user running Hydra, with mode 0600");return o}finally{await n.close()}}function Gi(e){let t=process.getuid?.();if(!e.isFile())return"is not a regular file";if(t===void 0)return"cannot be checked for its owner on this platform";if(e.uid!==t)return`is owned by uid ${e.uid}, not by the user running Hydra (uid ${t})`;if((e.mode&Ec)!==0)return`is open to its group or others (mode ${(e.mode&kc).toString(_c).padStart(Tc,"0")})`;return}function Dc(e,t){let n=Math.floor(Date.now()/xc)-Rc,r=Li(JSON.stringify({alg:"RS256",typ:"JWT"})),o=Li(JSON.stringify({exp:n+Cc,iat:n,iss:e})),i=wc("sha256",Buffer.from(`${r}.${o}`),t).toString("base64url");return`${r}.${o}.${i}`}function Li(e){return Buffer.from(e).toString("base64url")}var Gc=new Set(["github.com","www.github.com"]);var Mi=/\.git$/;function ue(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid GitHub URL: ${e}`)}if(t.protocol!=="https:"&&t.protocol!=="http:")throw Error(`Invalid GitHub URL (expected http(s)): ${e}`);if(!Gc.has(t.hostname))throw Error(`Invalid GitHub URL (host must be github.com): ${e}`);let n=t.pathname.split("/").filter(Boolean);if(n.length===1){let r=n[0]?.replace(Mi,"");if(!r)throw Error(`Invalid GitHub URL: ${e}`);return{kind:"org",org:r}}if(n.length===2){let r=n[0],o=n[1]?.replace(Mi,"");if(!r||!o)throw Error(`Invalid GitHub URL: ${e}`);return{kind:"repo",owner:r,repo:o}}throw Error(`Invalid GitHub URL (expected github.com/<owner>/<repo> or github.com/<org>): ${e}`)}function Pe(e){return e.kind==="repo"?`${e.owner}/${e.repo}`:e.org}var Fi=404,Mc=422,Fc="offline",Uc=Q().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),rn=ge({busy:te(),id:Uc,name:U(),status:U()}),jc=()=>{return};function Rr(e){return`/${e.kind==="repo"?`repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`:`orgs/${encodeURIComponent(e.org)}`}/actions/runners`}function on(e){return e.status===Fc}async function sn(e,t){return e.paginate({item:rn,key:"runners",operation:`List the runners of ${Pe(t)}`,path:Rr(t)})}async function Ze(e,t,n){try{return await e.request({operation:`Read runner ${n} of ${Pe(t)}`,path:`${Rr(t)}/${n}`,schema:rn})}catch(r){if(r instanceof V&&r.status===Fi)return;throw r}}async function Ui(e,t,n){try{return await e.request({method:"DELETE",operation:`Delete runner ${n} of ${Pe(t)}`,path:`${Rr(t)}/${n}`,schema:jc}),"deleted"}catch(r){if(!(r instanceof V))throw r;if(r.status===Fi)return"gone";if(r.status===Mc)return"busy";throw r}}function an(e,t){switch(e){case"app":return t.kind==="repo"?"The GitHub App needs the Administration repository permission (read and write) on the repository":"The GitHub App needs the Self-hosted runners organisation permission (read and write)";case"gh":return t.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope"}}var ji="selected",Bi=Q().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),Ki=ge({allows_public_repositories:te().or(ti()),default:te(),id:Bi,name:U(),visibility:U()}).map((e)=>({allowsPublicRepositories:e.allows_public_repositories,default:e.default,id:e.id,name:e.name,visibility:e.visibility})),Bc=ge({id:Bi}),Kc=()=>{return};function vt(e){return`/orgs/${encodeURIComponent(e)}/actions/runner-groups`}async function Vc(e,t){return e.paginate({item:Ki,key:"runner_groups",operation:`List the runner groups of ${t}`,path:vt(t)})}async function Vi(e,t,n){return(await Vc(e,t)).find((o)=>o.name.toLowerCase()===n.toLowerCase())}async function Ji(e,t,n){return e.request({body:{allows_public_repositories:!1,name:n,selected_repository_ids:[],visibility:ji},method:"POST",operation:`Create the runner group ${n} in ${t}`,path:vt(t),schema:Ki})}async function Wi(e,t,n){return(await e.paginate({item:Bc,key:"repositories",operation:`List the repositories that may use the runner group ${n.name} of ${t}`,path:`${vt(t)}/${n.id}/repositories`})).length}async function qi(e,t,n){return e.paginate({item:rn,key:"runners",operation:`List the runners in the runner group ${n.name} of ${t}`,path:`${vt(t)}/${n.id}/runners`})}async function zi(e,t,n,r){await e.request({method:"PUT",operation:`Move runner ${r} of ${t} into the runner group ${n.name}`,path:`${vt(t)}/${n.id}/runners/${r}`,schema:Kc})}function Yi(e,t){if(e.default)return"it is the default group, which every repository may use";if(e.visibility!==ji)return`its visibility is ${e.visibility}, not selected`;if(e.allowsPublicRepositories)return"it allows public repositories";if(t>0)return`${t} repository(ies) may use it`;return}import{spawn as Cl}from"child_process";import{once as Sl}from"events";import{existsSync as Ue}from"fs";import{cp as xl,link as El,mkdir as hn,mkdtemp as kl,readdir as cs,readFile as ls,readlink as _l,rename as Tl,rm as je,stat as ds,symlink as Pl,unlink as ps,writeFile as Al}from"fs/promises";import{join as I,resolve as Ir}from"path";import{chmod as Wc,mkdir as qc,readFile as zc,rename as Yc,rm as Xc,stat as Zc,writeFile as ts}from"fs/promises";import{dirname as Qc,join as kr,resolve as cn}from"path";import{isAbsolute as Jc}from"path";var Cr="# Generated by Hydra; hydra update rewrites this file.";function Xi(e){return`'${e.replaceAll("'","'\\''")}'`}function Zi(){return`#!/usr/bin/env bash
|
|
95
|
+
${Cr}
|
|
96
96
|
# Disabled in the Hydra profile; kept so runners started before the change still find it.
|
|
97
97
|
exit 0
|
|
98
|
-
`}function
|
|
99
|
-
${
|
|
98
|
+
`}function Qi(e){return`#!/usr/bin/env bash
|
|
99
|
+
${Cr}
|
|
100
100
|
# Waits until every host resolves, then lets the job start; fails the job on timeout.
|
|
101
101
|
set +e
|
|
102
102
|
|
|
103
|
-
hosts=(${e.hosts.map(
|
|
103
|
+
hosts=(${e.hosts.map(Xi).join(" ")})
|
|
104
104
|
timeout_seconds=${e.timeoutSeconds}
|
|
105
105
|
|
|
106
106
|
if command -v dscacheutil >/dev/null 2>&1; then
|
|
@@ -138,15 +138,15 @@ while :; do
|
|
|
138
138
|
pending=("\${unresolved[@]}")
|
|
139
139
|
sleep 1
|
|
140
140
|
done
|
|
141
|
-
`}function
|
|
142
|
-
${
|
|
141
|
+
`}function es(e,t){if(!Jc(e)||e==="/")throw Error(`Refusing to generate a workspace cleanup hook for runner directory "${e}"`);return`#!/usr/bin/env bash
|
|
142
|
+
${Cr}
|
|
143
143
|
# Removes this job's workspace and temporary files from this runner's _work directory.
|
|
144
144
|
# Always exits 0 so a cleanup problem never fails a finished job; problems become warnings.
|
|
145
145
|
set +e
|
|
146
146
|
trap 'exit 0' EXIT
|
|
147
147
|
shopt -s dotglob nullglob
|
|
148
148
|
|
|
149
|
-
runner_root=${
|
|
149
|
+
runner_root=${Xi(e)}
|
|
150
150
|
keep_tool_cache=${t.keepToolCache}
|
|
151
151
|
|
|
152
152
|
note() { echo "Hydra cleanup: $*"; }
|
|
@@ -234,19 +234,29 @@ cd -- "$work_root" || exit 0
|
|
|
234
234
|
clean_job_workspace "\${RUNNER_WORKSPACE:-\${GITHUB_WORKSPACE:-}}"
|
|
235
235
|
clear_dir "$work_root/_temp" _runner_file_commands _github_workflow
|
|
236
236
|
[ "$keep_tool_cache" = true ] || clear_dir "$work_root/_tool"
|
|
237
|
-
`}var
|
|
238
|
-
`);if(
|
|
237
|
+
`}var el="hydra-hooks",ns=".env",ln={started:{envKey:"ACTIONS_RUNNER_HOOK_JOB_STARTED",file:"job-started.sh"},completed:{envKey:"ACTIONS_RUNNER_HOOK_JOB_COMPLETED",file:"job-completed.sh"}},tl=Object.keys(ln),nl=493,rl=253,ol=/^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/,Er="Fix the profile's jobHooks in config.json in the Hydra home; see the Hydra reference for the allowed values",Sr={dns:["enabled","hosts","timeoutSeconds"],workspaceCleanup:["enabled","keepToolCache"]},il=U().map((e)=>e.length<=rl&&ol.test(e)?e:F()),sl=Wt(il).map((e)=>e.length>0?e:F()),al=Q().map((e)=>Number.isSafeInteger(e)&&e>0?e:F());function rs(){return{dns:{enabled:di,hosts:[...fi],timeoutSeconds:pi},workspaceCleanup:{enabled:ui,keepToolCache:li}}}function dn(){let e=rs();return{...e,workspaceCleanup:{...e.workspaceCleanup,enabled:ci}}}function Se(e){let t=rs(),n=xr(e,"jobHooks",Object.keys(Sr)),r=xr(n.dns,"jobHooks.dns",Sr.dns),o=xr(n.workspaceCleanup,"jobHooks.workspaceCleanup",Sr.workspaceCleanup);return{dns:{enabled:Rt(te(),r.enabled,t.dns.enabled,"jobHooks.dns.enabled","a boolean"),hosts:Rt(sl,r.hosts,t.dns.hosts,"jobHooks.dns.hosts","a non-empty list of hostnames"),timeoutSeconds:Rt(al,r.timeoutSeconds,t.dns.timeoutSeconds,"jobHooks.dns.timeoutSeconds","a positive whole number of seconds")},workspaceCleanup:{enabled:Rt(te(),o.enabled,t.workspaceCleanup.enabled,"jobHooks.workspaceCleanup.enabled","a boolean"),keepToolCache:Rt(te(),o.keepToolCache,t.workspaceCleanup.keepToolCache,"jobHooks.workspaceCleanup.keepToolCache","a boolean")}}}function os(e,t){return kr(cn(e),el,ln[t].file)}function is(e,t,n){switch(e){case"started":return n.dns.enabled?Qi(n.dns):null;case"completed":return n.workspaceCleanup.enabled?es(cn(t),n.workspaceCleanup):null}}function ul(e,t){let n=new Map(t.map((s)=>[s.key,s])),r=new Set,o=e.split(`
|
|
238
|
+
`);if(o.at(-1)==="")o.pop();let i=[];for(let s of o){let c=s.indexOf("="),a=c>0?n.get(s.slice(0,c)):void 0;if(!a){i.push(s);continue}if(a.value===null){if(s.slice(c+1)!==a.managedPath)i.push(s);continue}if(r.has(a.key))continue;r.add(a.key),i.push(`${a.key}=${a.value}`)}for(let s of t)if(s.value!==null&&!r.has(s.key))i.push(`${s.key}=${s.value}`);return i.length>0?`${i.join(`
|
|
239
239
|
`)}
|
|
240
|
-
`:""}async function
|
|
241
|
-
`).filter((
|
|
242
|
-
`)?e.slice(0,-1):e;if(
|
|
240
|
+
`:""}async function pn(e,t){let n=[],r=!1;for(let c of tl){let a=os(e,c),u=is(c,e,t),d=await un(a),p=u??(d===null?null:Zi());if(p!==null&&p!==d)await pl(a,p),r=!0;n.push({key:ln[c].envKey,managedPath:a,value:u===null?null:a})}let o=kr(cn(e),ns),i=await un(o)??"",s=ul(i,n);if(s===i)return{envChanged:!1,scriptsChanged:r};return await ts(o,s),{envChanged:!0,scriptsChanged:r}}async function _r(e,t){let n=kr(cn(e),ns),r=await un(n)??"",o=(i)=>cl(os(e,i),ll(r,ln[i].envKey),is(i,e,t));return{envModifiedAt:await dl(n),states:{completed:await o("completed"),started:await o("started")}}}async function cl(e,t,n){if(n===null){if(t===void 0)return"off";return t===e?"outdated":"foreign"}if(t===void 0)return"missing";if(t!==e)return"foreign";return await un(e)===n?"configured":"outdated"}function ll(e,t){let n=`${t}=`;return e.split(`
|
|
241
|
+
`).filter((r)=>r.startsWith(n)).map((r)=>r.slice(n.length)).at(-1)}async function dl(e){try{return(await Zc(e)).mtime}catch(t){if(t.code==="ENOENT")return null;throw t}}function xr(e,t,n){if(e===void 0)return{};if(typeof e!=="object"||e===null||Array.isArray(e))throw new y(`Invalid ${t}: expected an object`,Er);let r=Object.keys(e).find((o)=>!n.includes(o));if(r!==void 0)throw new y(`Unknown ${t} setting: ${r}`,Er);return e}function Rt(e,t,n,r,o){if(t===void 0)return n;try{return e(t)}catch{throw new y(`Invalid ${r}: expected ${o}`,Er)}}async function un(e){try{return await zc(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function pl(e,t){let n=`${e}.${process.pid}.tmp`;await qc(Qc(e),{recursive:!0});try{await ts(n,t),await Wc(n,nl),await Yc(n,e)}finally{await Xc(n,{force:!0})}}import{existsSync as fl}from"fs";import{readdir as ml,stat as hl}from"fs/promises";import{join as gl}from"path";var fn="_diag",ss={runner:/^Runner_.+\.log$/,worker:/^Worker_.+\.log$/},as=1024,us=["B","KB","MB","GB"],yl=1;function bl(e){if(ss.worker.test(e))return"worker";if(ss.runner.test(e))return"runner";return null}function Tr(e){return[...e].sort((t,n)=>n.mtime.getTime()-t.mtime.getTime())}async function mn(e){if(!fl(e))return[];let t=await ml(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile())continue;let o=bl(r.name);if(!o)continue;let i=gl(e,r.name),s=await hl(i);n.push({mtime:s.mtime,name:r.name,path:i,size:s.size,type:o})}return Tr(n)}function Pr(e,t){let n=e.find((o)=>o.type===t);if(n)return{fallback:!1,file:n};let r=e[0];return r?{fallback:!0,file:r}:null}function Ar(e,t){if(t<=0)return"";let n=e.endsWith(`
|
|
242
|
+
`)?e.slice(0,-1):e;if(n==="")return"";return n.split(`
|
|
243
243
|
`).slice(-t).join(`
|
|
244
|
-
`)}function ge(e){let t=e,r=0;while(t>=qn&&r<zn.length-1)t/=qn,r++;return`${r===0?String(t):t.toFixed(so)} ${zn[r]??"B"}`}var ao=/(?:^|\/)github\/([^/]+)\/externals$/;function dt(e){return e.match(ao)?.[1]??null}var Qn="actions/runner",$o={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},hr=["bin"],gr=["externals"],wo=1,bo=5000,vo=50,Co=5000,xo=50;class yr{profile;sharedPath=null;constructor(e){this.profile=e}async download(){let e=$o[this.profile.os],t=await this.getLatestVersion(),r=k(te,"github",t);if(await this.isCompleteDownload(r))return this.sharedPath=r,{path:r,version:t};let n=k(te,"github");await mt(n,{recursive:!0});let i=await mo(k(te,`.github-${t}-`)),s=`actions-runner-${e}-${t}.tar.gz`,o=k(i,s),l=`https://github.com/${Qn}/releases/download/v${t}/${s}`;try{if(await Bun.$`curl --fail --silent --show-error --location -o ${o} ${l}`,await Bun.$`tar xzf ${o} -C ${i}`,await Zn(o),!await this.isCompleteDownload(i))throw new w(`Runner v${t} archive is incomplete`);await this.publishDownload(i,r,t)}finally{await $e(i,{force:!0,recursive:!0})}return this.sharedPath=r,{path:r,version:t}}async create(e){let t=oe(this.profile.jobHooks),r=await this.ensureDownloaded(),n=[];for(let i of e){let s=k(this.profile.directory,i);if(ye(s))throw new w(`Runner directory already exists: ${s}`,"Remove or recover this runner before creating it again");try{await this.setupRunnerDir(r,s),await this.registerRunner(s,i,t)}catch(o){if(!ye(k(s,".runner")))await $e(s,{force:!0,recursive:!0});throw o}n.push({directory:s,id:i,name:i,status:"registered"})}return n}async remove(e){for(let t of e){let r=k(this.profile.directory,t);if(!ye(k(r,".runner")))continue;let n=await this.fetchRemovalToken(r),i=await Bun.$`bash ./config.sh remove --token ${n}`.cwd(r).quiet().nothrow();if(i.exitCode!==0)throw new w(`Failed to deregister runner ${t}`,i.stderr.toString().trim()||"Runner files have been preserved; retry removal")}}async start(e){for(let t of e){let r=k(this.profile.directory,t),n=await this.readPidFile(r);if(n&&this.isProcessRunning(n))continue;let i=lo("bash",["./run.sh"],{cwd:fr(r),detached:!0,stdio:"ignore"});if(await uo(i,"spawn"),i.pid===void 0)throw new w(`Failed to start runner ${t}`);i.unref(),await this.writePidFile(r,i.pid)}}async stop(e){for(let t of e){let r=k(this.profile.directory,t),n=await this.readPidFile(r);if(n&&this.isProcessRunning(n)){try{process.kill(-n,"SIGTERM")}catch(s){if(s.code!=="ESRCH")throw s;try{process.kill(n,"SIGTERM")}catch(o){if(o.code!=="ESRCH")throw o}}let i=Date.now()+bo;while(this.isProcessRunning(n)){if(Date.now()>=i)throw new w(`Runner ${t} did not stop`,"Wait for its current job to finish and retry");await Bun.sleep(vo)}}await this.removePidFile(r)}}async list(){let e=this.profile.directory;if(!ye(e))return[];let t=await Yn(e,{withFileTypes:!0}),r=[];for(let n of t){if(!n.isDirectory())continue;let i=k(e,n.name);r.push(await this.getRunnerStatus(i,n.name))}return r}async currentVersion(e){let t=k(this.profile.directory,e);return this.detectVersion(t)}async logFiles(e){return pt(k(this.profile.directory,e,ct))}async update(e){let t=oe(this.profile.jobHooks),r=await this.ensureDownloaded();for(let n of e){let i=k(this.profile.directory,n);await this.removeRunnerBinaries(i),await this.setupRunnerDir(r,i),await ut(i,t)}}async configureJobHooks(e){let t=oe(this.profile.jobHooks),r=k(this.profile.directory,e);if(!ye(k(r,".runner")))return{envChanged:!1,scriptsChanged:!1};return ut(r,t)}async getRunnerStatus(e,t){let r=await this.readRunnerName(e),n=await this.readPidFile(e),i=n!==null&&this.isProcessRunning(n),s="unknown";if(i)s="running";else if(ye(k(e,".runner")))s="registered";let o=i?await this.readStartTime(e):void 0;return{directory:e,id:t,name:r,pid:i?n:void 0,startedAt:o,status:s}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:e}=await this.download();return e}async isCompleteDownload(e){try{return(await Promise.all(["bin","externals","config.sh","run.sh"].map((r)=>Xn(k(e,r))))).every((r,n)=>n<hr.length+gr.length?r.isDirectory():r.isFile())}catch(t){if(t.code==="ENOENT")return!1;throw t}}async publishDownload(e,t,r){let n=k(te,`.github-${r}.lock`),i=Date.now()+Co;while(!0)try{await mt(n);break}catch(s){if(s.code!=="EEXIST")throw s;if(Date.now()>=i)throw new w(`Runner download is locked: ${n}`,"Retry after other Hydra downloads finish; remove a stale lock only when no download is running");await Bun.sleep(xo)}try{if(await this.isCompleteDownload(t))return;await $e(t,{force:!0,recursive:!0}),await ho(e,t)}finally{await $e(n,{force:!0,recursive:!0})}}async setupRunnerDir(e,t){await mt(t,{recursive:!0});for(let r of hr)await this.hardLinkDir(k(e,r),k(t,r));for(let r of gr){let n=fr(e,r),i=k(t,r);if(!ye(i))await go(n,i)}for(let r of["*.sh","*.sh.template"]){let n=await Array.fromAsync(new Bun.Glob(r).scan(e));for(let i of n)await co(k(e,i),k(t,i))}}async registerRunner(e,t,r){let n=await this.fetchRegistrationToken(),i=["--url",this.profile.url,"--token",n,"--name",t,"--unattended","--disableupdate"];if(this.profile.labels)i.push("--labels",this.profile.labels);if(this.profile.runnerGroup)i.push("--runnergroup",this.profile.runnerGroup);await Bun.$`bash ./config.sh ${i}`.cwd(e).quiet(),await ut(e,r)}async fetchRegistrationToken(){return this.fetchRunnerToken(he(this.profile.url),"registration-token")}async fetchRemovalToken(e){let t=await mr(k(e,".runner"),"utf-8"),n=JSON.parse(this.stripBom(t)).gitHubUrl;if(!n)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(he(n),"remove-token")}async fetchRunnerToken(e,t){let r=e.kind==="repo"?`repos/${e.owner}/${e.repo}/actions/runners/${t}`:`orgs/${e.org}/actions/runners/${t}`,n=e.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope",i=await Bun.$`gh api ${r} --method POST --jq .token`.quiet().nothrow();if(i.exitCode!==0){let o=i.stderr.toString().trim();throw Error(`gh api ${r} failed for ${nr(e)} (${n})${o?`: ${o}`:""}`)}let s=i.stdout.toString().trim();if(!s)throw Error(`Failed to fetch ${t} for ${nr(e)}`);return s}async getLatestVersion(){return(await Bun.$`gh api repos/${Qn}/releases/latest --jq .tag_name`.quiet()).stdout.toString().trim().replace(/^v/,"")}pidFilePath(e){return fr(e,".pid")}async writePidFile(e,t){await yo(this.pidFilePath(e),String(t))}async readPidFile(e){try{let t=await mr(this.pidFilePath(e),"utf-8"),r=Number(t.trim());return Number.isSafeInteger(r)&&r>wo?r:null}catch{return null}}async readStartTime(e){try{return(await Xn(this.pidFilePath(e))).mtime}catch{return}}async removePidFile(e){try{await Zn(this.pidFilePath(e))}catch{}}async readRunnerName(e){try{let t=await mr(k(e,".runner"),"utf-8");return JSON.parse(this.stripBom(t)).agentName??"unknown"}catch{return"unknown"}}async hardLinkDir(e,t){await mt(t,{recursive:!0});let r=await Yn(e,{withFileTypes:!0});for(let n of r){let i=k(e,n.name),s=k(t,n.name);if(n.isDirectory())await this.hardLinkDir(i,s);else await po(i,s)}}async detectVersion(e){try{let t=await fo(k(e,"externals"));return dt(t)}catch{return null}}async removeRunnerBinaries(e){for(let t of hr)await $e(k(e,t),{force:!0,recursive:!0});for(let t of gr)await $e(k(e,t),{force:!0});for(let t of["*.sh","*.sh.template"]){let r=await Array.fromAsync(new Bun.Glob(t).scan(e));for(let n of r)await $e(k(e,n),{force:!0})}}stripBom(e){return e.replace(/^\uFEFF/,"")}isProcessRunning(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}}import{existsSync as $r}from"fs";import{readdir as wr,readFile as So,readlink as Ro,rm as br,stat as Eo}from"fs/promises";import{join as ce}from"path";var _o="_work",ko="externals",Ao=".pid",Io="github",Po=["runner","worker"],To=24,ti=3600000,ei=10,Oo=1,Do=Se().map((e)=>Number.isSafeInteger(e)&&e>Oo?e:ee());function ft(e){return{auto:e?.auto??kn,intervalHours:e?.intervalHours??An,lastRun:e?.lastRun,olderThanDays:e?.olderThanDays??it,targets:e?.targets??In}}function No(e,t){return e-t*To*ti}function vr(e,t){if(!e.lastRun)return!0;let r=Date.parse(e.lastRun);if(Number.isNaN(r))return!0;return t-r>=e.intervalHours*ti}function Lo(e,t){let r=cr(e),n=new Set;for(let i of Po){let s=r.find((o)=>o.type===i);if(s)n.add(s.path)}return r.filter((i)=>!n.has(i.path)&&i.mtime.getTime()<t)}function Fo(e){return[...e].sort(Go)[0]??null}function Ho(e,t){let r=Fo(e),n=new Set(t);return e.filter((i)=>i!==r&&!n.has(i))}function ht(e){return Object.values(e).reduce((t,r)=>t+r.freedBytes,0)}async function Mo(e){let t;try{t=await So(ce(e,Ao),"utf-8")}catch(n){if(n.code==="ENOENT")return!1;throw n}let r;try{r=Do(Number(t.trim()))}catch{return!1}try{return process.kill(r,0),!0}catch(n){let i=n.code;if(i==="EPERM")return!0;if(i==="ESRCH")return!1;throw n}}async function Cr(e){if(!$r(e))return 0;let t=await wr(e,{withFileTypes:!0}),r=0;for(let n of t){if(n.isSymbolicLink())continue;let i=ce(e,n.name);if(n.isDirectory()){r+=await Cr(i);continue}if(n.isFile()){let s=await Eo(i);r+=s.size}}return r}async function gt(e){let t=No(e.now,e.olderThanDays),r={};for(let n of e.targets)switch(n){case"logs":r.logs=await jo(e.entries,t,e.dryRun);break;case"work":r.work=await Uo(e.entries,e.dryRun);break;case"shared":r.shared=await Vo(e.entries,e.dryRun,e.sharedDir);break}return r}async function jo(e,t,r){let n={freedBytes:0,removed:0,skipped:[]};for(let i of e){let s=await pt(ce(i.directory,ct));for(let o of Lo(s,t)){if(!r)await br(o.path,{force:!0});n.removed++,n.freedBytes+=o.size}}return n}async function Uo(e,t){let r={freedBytes:0,removed:0,skipped:[]};for(let n of e){if(await Mo(n.directory)){r.skipped.push(n.id);continue}let i=ce(n.directory,_o);if(!$r(i))continue;let s=await wr(i);if(s.length===0)continue;if(r.freedBytes+=await Cr(i),r.removed+=s.length,t)continue;for(let o of s)await br(ce(i,o),{force:!0,recursive:!0})}return r}async function Vo(e,t,r){let n={freedBytes:0,removed:0,skipped:[]},i=r??ce(te,Io);if(!$r(i))return n;let o=(await wr(i,{withFileTypes:!0})).filter((a)=>a.isDirectory()).map((a)=>a.name),l=await Bo(e);for(let a of Ho(o,l)){let u=ce(i,a);if(n.freedBytes+=await Cr(u),n.removed++,!t)await br(u,{force:!0,recursive:!0})}return n}async function Bo(e){let t=[];for(let r of e)try{let n=await Ro(ce(r.directory,ko)),i=dt(n);if(i)t.push(i)}catch{}return t}function Go(e,t){let r=e.split(".").map((s)=>Number.parseInt(s,ei)),n=t.split(".").map((s)=>Number.parseInt(s,ei)),i=Math.max(r.length,n.length);for(let s=0;s<i;s++){let o=r[s]??0,l=n[s]??0,a=Number.isNaN(o)?0:o,u=Number.isNaN(l)?0:l;if(a!==u)return u-a}return 0}import{readFile as Jo}from"fs/promises";var Ko=1e4,Wo="/etc/resolv.conf",qo=/^\s*nameserver\[\d+\]\s*:\s*(\S+)/gm,zo=/^\s*nameserver\s+(\S+)/gm,Yo=/^(?:ip|ipv6)_address:\s*(\S+)/gm,Xo=/^(\S+)\s/gm;async function xr(){let[e,t]=Bun.which("scutil")?[await ri(["scutil","--dns"]),qo]:[await Zo(),zo];return ii(ni(e,t))}function Sr(){return Bun.which("dscacheutil")!==null||Bun.which("getent")!==null}async function Rr(e){let[t,r]=Bun.which("dscacheutil")?[["dscacheutil","-q","host","-a","name",e],Yo]:[["getent","hosts",e],Xo],n=performance.now(),i=await ri(t);return{addresses:ii(ni(i,r)),durationMs:Math.round(performance.now()-n),host:e}}async function ri(e){let t=Bun.spawn(e,{stderr:"ignore",stdin:"ignore",stdout:"pipe",timeout:Ko}),[r]=await Promise.all([new Response(t.stdout).text(),t.exited]);return r}async function Zo(){try{return await Jo(Wo,"utf-8")}catch(e){if(e.code==="ENOENT")return"";throw e}}function ni(e,t){return[...e.matchAll(t)].flatMap((r)=>r[1]?[r[1]]:[])}function ii(e){return[...new Set(e)]}function H(e){switch(e.provider){case"github":return new yr(e);default:throw Error(`Runner provider "${e.provider}" is not yet implemented`)}}var oi=0,Qo={logs:"file(s)",shared:"version(s)",work:"item(s)"},si=Q({days:{alias:"d",default:oi,description:"Override log retention",displayDefault:`config or ${it} days`,type:"number"},dryRun:{alias:"n",default:!1,description:"Preview cleanup without deleting",type:"boolean"},logs:{alias:"l",default:!1,description:"Remove old diagnostic logs",type:"boolean"},shared:{alias:"s",default:!1,description:"Remove unused runner versions",type:"boolean"},work:{alias:"w",default:!1,description:"Clear stopped runners' workspaces",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip workspace confirmation",type:"boolean"}});class yt extends I{name="cleanup";description="Remove logs, workspaces, and old runner versions";args=si;async execute(e){F(e.args,si,"Run 'hydra cleanup --help' for supported options");let t=e.config.get("profiles");if(Object.keys(t).length===0)throw new w("No profiles configured","Run hydra init to set up a profile");let r=ft(e.config.get("cleanup")),n=this.explicitTargets(e),i=n.length>0?n:r.targets,s=e.args.days>oi?e.args.days:r.olderThanDays;if(i.includes("work")&&!e.args.dryRun&&!e.args.yes){if(!await de({message:"Delete _work contents (checkouts and caches) of stopped runners?"}))i=i.filter((a)=>a!=="work")}let o=await gt({dryRun:e.args.dryRun,entries:e.config.get("runners")??[],now:Date.now(),olderThanDays:s,targets:i});if(this.printReport(o,e.args.dryRun),e.args.dryRun)return;e.config.set("cleanup",{...e.config.get("cleanup"),lastRun:new Date().toISOString()})}explicitTargets(e){let t=[];if(e.args.logs)t.push("logs");if(e.args.work)t.push("work");if(e.args.shared)t.push("shared");return t}printReport(e,t){let r=[];for(let[s,o]of Object.entries(e)){if(!o)continue;let l=Qo[s],a=ge(o.freedBytes),u=t?`would remove ${o.removed} ${l}, ${a}`:`removed ${o.removed} ${l}, freed ${a}`;if(r.push(`${c.bold(s)}: ${o.removed>0?u:c.dim("nothing to do")}`),o.skipped.length>0)r.push(c.dim(` skipped running runner(s): ${o.skipped.join(", ")}`))}if(r.length===0){b.info(c.dim("Nothing to clean."));return}let n=ht(e),i=t?"Would free":"Freed";r.push(c.dim(`${i} ${ge(n)} total`)),b.info(r.join(`
|
|
245
|
-
`))}}async function $
|
|
246
|
-
`))
|
|
247
|
-
`),
|
|
248
|
-
`))}async printTail(e,t,r){let n=await oa(t.path,"utf-8"),i=[`${c.bold(e.name)} ${c.dim(la[t.type])}`,c.dim(t.path),c.dim(`Last modified: ${t.mtime.toISOString()}`)];b.info(i.join(`
|
|
249
|
-
`))
|
|
250
|
-
`),
|
|
251
|
-
`))
|
|
252
|
-
`))}}
|
|
244
|
+
`)}function Fe(e){let t=e,n=0;while(t>=as&&n<us.length-1)t/=as,n++;return`${n===0?String(t):t.toFixed(yl)} ${us[n]??"B"}`}import{readFile as wl}from"fs/promises";import{join as $l}from"path";var Qe="unknown";var xe=".runner",vl=/^\uFEFF/;async function Ct(e){try{let t=await wl($l(e,xe),"utf-8"),n=JSON.parse(t.replace(vl,""));return{agentId:Number.isSafeInteger(n.agentId)?n.agentId:void 0,name:typeof n.agentName==="string"?n.agentName:Qe}}catch{return{name:Qe}}}var Rl=/(?:^|\/)github\/([^/]+)\/externals$/;function et(e){return e.match(Rl)?.[1]??null}var fs="actions/runner",Il={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},Hr=["bin"],Or=["externals"],Hl=1,Ol=5000,Ll=50,Nl=5000,Dl=50,Gl="ACTIONS_RUNNER_INPUT_TOKEN",Ml=/^\d+\.\d+\.\d+$/,Fl=/^v/,Ul=ge({token:vr}),jl=ge({tag_name:U()}),Bl={app:$r,gh:"Check the gh login with gh auth status"},Kl={"registration-token":"Mint a runner registration token","remove-token":"Mint a runner removal token"};class Lr{profile;sharedDir;github;sharedPath=null;constructor(e,t,n){this.profile=e;this.sharedDir=t;this.github=n}async download(){let e=Il[this.profile.os],t=await this.getLatestVersion(),n=I(this.sharedDir,"github",t);if(await this.isCompleteDownload(n))return this.sharedPath=n,{path:n,version:t};let r=I(this.sharedDir,"github");await hn(r,{recursive:!0});let o=await kl(I(this.sharedDir,`.github-${t}-`)),i=`actions-runner-${e}-${t}.tar.gz`,s=I(o,i),c=`https://github.com/${fs}/releases/download/v${t}/${i}`;try{if(await Bun.$`curl --fail --silent --show-error --location -o ${s} ${c}`,await Bun.$`tar xzf ${s} -C ${o}`,await ps(s),!await this.isCompleteDownload(o))throw new y(`Runner v${t} archive is incomplete`);await this.publishDownload(o,n,t)}finally{await je(o,{force:!0,recursive:!0})}return this.sharedPath=n,{path:n,version:t}}async create(e){let t=Se(this.profile.jobHooks),n=await this.ensureDownloaded(),r=[];for(let o of e){let i=I(this.profile.directory,o);if(Ue(i))throw new y(`Runner directory already exists: ${i}`,"Remove or recover this runner before creating it again");try{await this.setupRunnerDir(n,i),await this.registerRunner(i,o,t)}catch(s){if(!Ue(I(i,".runner")))await je(i,{force:!0,recursive:!0});throw s}r.push({directory:i,id:o,name:o,status:"registered"})}return r}async remove(e){for(let t of e){let n=I(this.profile.directory,t);if(!Ue(I(n,".runner"))){await this.stop([t]);continue}let r=await this.fetchRemovalToken(n);await this.stop([t]);let o=await Bun.$`bash ./config.sh remove`.cwd(n).env(ms(r)).quiet().nothrow();if(o.exitCode!==0)throw new y(`Failed to deregister runner ${t}`,o.stderr.toString().trim()||"Runner files have been preserved; retry removal")}}async start(e){for(let t of e){let n=I(this.profile.directory,t),r=await this.readPidFile(n);if(r&&this.isProcessRunning(r))continue;let o=Cl("bash",["./run.sh"],{cwd:Ir(n),detached:!0,stdio:"ignore"});if(await Sl(o,"spawn"),o.pid===void 0)throw new y(`Failed to start runner ${t}`);o.unref(),await this.writePidFile(n,o.pid)}}async stop(e){for(let t of e){let n=I(this.profile.directory,t),r=await this.readPidFile(n);if(r&&this.isProcessRunning(r)){try{process.kill(-r,"SIGTERM")}catch(i){if(i.code!=="ESRCH")throw i;try{process.kill(r,"SIGTERM")}catch(s){if(s.code!=="ESRCH")throw s}}let o=Date.now()+Ol;while(this.isProcessRunning(r)){if(Date.now()>=o)throw new y(`Runner ${t} did not stop`,"Wait for its current job to finish and retry");await Bun.sleep(Ll)}}await this.removePidFile(n)}}async list(){let e=this.profile.directory;if(!Ue(e))return[];let t=await cs(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let o=I(e,r.name);n.push(await this.getRunnerStatus(o,r.name))}return n}async currentVersion(e){let t=I(this.profile.directory,e);return this.detectVersion(t)}async logFiles(e){return mn(I(this.profile.directory,e,fn))}async update(e){let t=Se(this.profile.jobHooks),n=await this.ensureDownloaded();for(let r of e){let o=I(this.profile.directory,r);await this.removeRunnerBinaries(o),await this.setupRunnerDir(n,o),await pn(o,t)}}async configureJobHooks(e){let t=Se(this.profile.jobHooks),n=I(this.profile.directory,e);if(!Ue(I(n,".runner")))return{envChanged:!1,scriptsChanged:!1};return pn(n,t)}async getRunnerStatus(e,t){let{agentId:n,name:r}=await Ct(e),o=await this.readPidFile(e),i=o!==null&&this.isProcessRunning(o),s="unknown";if(i)s="running";else if(Ue(I(e,".runner")))s="registered";let c=i?await this.readStartTime(e):void 0;return{agentId:n,directory:e,id:t,name:r,pid:i?o:void 0,startedAt:c,status:s}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:e}=await this.download();return e}async isCompleteDownload(e){try{return(await Promise.all(["bin","externals","config.sh","run.sh"].map((n)=>ds(I(e,n))))).every((n,r)=>r<Hr.length+Or.length?n.isDirectory():n.isFile())}catch(t){if(t.code==="ENOENT")return!1;throw t}}async publishDownload(e,t,n){let r=I(this.sharedDir,`.github-${n}.lock`),o=Date.now()+Nl;while(!0)try{await hn(r);break}catch(i){if(i.code!=="EEXIST")throw i;if(Date.now()>=o)throw new y(`Runner download is locked: ${r}`,"Retry after other Hydra downloads finish; remove a stale lock only when no download is running");await Bun.sleep(Dl)}try{if(await this.isCompleteDownload(t))return;await je(t,{force:!0,recursive:!0}),await Tl(e,t)}finally{await je(r,{force:!0,recursive:!0})}}async setupRunnerDir(e,t){await hn(t,{recursive:!0});for(let n of Hr)await this.hardLinkDir(I(e,n),I(t,n));for(let n of Or){let r=Ir(e,n),o=I(t,n);if(!Ue(o))await Pl(r,o)}for(let n of["*.sh","*.sh.template"]){let r=await Array.fromAsync(new Bun.Glob(n).scan(e));for(let o of r)await xl(I(e,o),I(t,o))}}async registerRunner(e,t,n){let r=await this.fetchRegistrationToken(),o=["--url",this.profile.url,"--name",t,"--unattended","--disableupdate"];if(this.profile.labels)o.push("--labels",this.profile.labels);if(this.profile.runnerGroup)o.push("--runnergroup",this.profile.runnerGroup);await Bun.$`bash ./config.sh ${o}`.cwd(e).env(ms(r)).quiet(),await pn(e,n)}async fetchRegistrationToken(){return this.fetchRunnerToken(ue(this.profile.url),"registration-token")}async fetchRemovalToken(e){let t=await ls(I(e,".runner"),"utf-8"),r=JSON.parse(this.stripBom(t)).gitHubUrl;if(!r)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(ue(r),"remove-token")}async fetchRunnerToken(e,t){let n=e.kind==="repo"?`repos/${e.owner}/${e.repo}`:`orgs/${e.org}`,{token:r}=await this.callGitHub({idempotent:!0,method:"POST",operation:`${Kl[t]} for ${Pe(e)}`,path:`/${n}/actions/runners/${t}`,schema:Ul},an(this.github.credentials.kind,e));return r}async getLatestVersion(){let{tag_name:e}=await this.callGitHub({operation:"Read the latest runner release",path:`/repos/${fs}/releases/latest`,schema:jl},Bl[this.github.credentials.kind]),t=e.replace(Fl,"");if(!Ml.test(t))throw new y(`The latest runner release has an unexpected tag: ${e}`);return t}async callGitHub(e,t){try{return await this.github.client.request(e)}catch(n){throw n instanceof V?new y(n.message,t):n}}pidFilePath(e){return Ir(e,".pid")}async writePidFile(e,t){await Al(this.pidFilePath(e),String(t))}async readPidFile(e){try{let t=await ls(this.pidFilePath(e),"utf-8"),n=Number(t.trim());return Number.isSafeInteger(n)&&n>Hl?n:null}catch{return null}}async readStartTime(e){try{return(await ds(this.pidFilePath(e))).mtime}catch{return}}async removePidFile(e){try{await ps(this.pidFilePath(e))}catch{}}async hardLinkDir(e,t){await hn(t,{recursive:!0});let n=await cs(e,{withFileTypes:!0});for(let r of n){let o=I(e,r.name),i=I(t,r.name);if(r.isDirectory())await this.hardLinkDir(o,i);else await El(o,i)}}async detectVersion(e){try{let t=await _l(I(e,"externals"));return et(t)}catch{return null}}async removeRunnerBinaries(e){for(let t of Hr)await je(I(e,t),{force:!0,recursive:!0});for(let t of Or)await je(I(e,t),{force:!0});for(let t of["*.sh","*.sh.template"]){let n=await Array.fromAsync(new Bun.Glob(t).scan(e));for(let r of n)await je(I(e,r),{force:!0})}}stripBom(e){return e.replace(/^\uFEFF/,"")}isProcessRunning(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}}function ms(e){return{...process.env,[Gl]:e}}import{existsSync as Nr}from"fs";import{readdir as Dr,readFile as Vl,readlink as Jl,rm as Gr,stat as Wl}from"fs/promises";import{join as Ae}from"path";var ql="_work",zl="externals",Yl=".pid",Xl="github",Zl=["runner","worker"],Ql=24,gs=3600000,hs=10,ed=1,td=Q().map((e)=>Number.isSafeInteger(e)&&e>ed?e:F());function gn(e){return{auto:e?.auto??ii,intervalHours:e?.intervalHours??si,lastRun:e?.lastRun,olderThanDays:e?.olderThanDays??zt,targets:e?.targets??ai}}function nd(e,t){return e-t*Ql*gs}function Mr(e,t){if(!e.lastRun)return!0;let n=Date.parse(e.lastRun);if(Number.isNaN(n))return!0;return t-n>=e.intervalHours*gs}function rd(e,t){let n=Tr(e),r=new Set;for(let o of Zl){let i=n.find((s)=>s.type===o);if(i)r.add(i.path)}return n.filter((o)=>!r.has(o.path)&&o.mtime.getTime()<t)}function od(e){return[...e].sort(dd)[0]??null}function id(e,t){let n=od(e),r=new Set(t);return e.filter((o)=>o!==n&&!r.has(o))}function yn(e){return Object.values(e).reduce((t,n)=>t+n.freedBytes,0)}async function sd(e){let t;try{t=await Vl(Ae(e,Yl),"utf-8")}catch(r){if(r.code==="ENOENT")return!1;throw r}let n;try{n=td(Number(t.trim()))}catch{return!1}try{return process.kill(n,0),!0}catch(r){let o=r.code;if(o==="EPERM")return!0;if(o==="ESRCH")return!1;throw r}}async function Fr(e){if(!Nr(e))return 0;let t=await Dr(e,{withFileTypes:!0}),n=0;for(let r of t){if(r.isSymbolicLink())continue;let o=Ae(e,r.name);if(r.isDirectory()){n+=await Fr(o);continue}if(r.isFile()){let i=await Wl(o);n+=i.size}}return n}async function bn(e){let t=nd(e.now,e.olderThanDays),n={};for(let r of e.targets)switch(r){case"logs":n.logs=await ad(e.entries,t,e.dryRun);break;case"work":n.work=await ud(e.entries,e.dryRun);break;case"shared":n.shared=await cd(e.entries,e.dryRun,e.sharedDir);break}return n}async function ad(e,t,n){let r={freedBytes:0,removed:0,skipped:[]};for(let o of e){let i=await mn(Ae(o.directory,fn));for(let s of rd(i,t)){if(!n)await Gr(s.path,{force:!0});r.removed++,r.freedBytes+=s.size}}return r}async function ud(e,t){let n={freedBytes:0,removed:0,skipped:[]};for(let r of e){if(await sd(r.directory)){n.skipped.push(r.id);continue}let o=Ae(r.directory,ql);if(!Nr(o))continue;let i=await Dr(o);if(i.length===0)continue;if(n.freedBytes+=await Fr(o),n.removed+=i.length,t)continue;for(let s of i)await Gr(Ae(o,s),{force:!0,recursive:!0})}return n}async function cd(e,t,n){let r={freedBytes:0,removed:0,skipped:[]},o=Ae(n,Xl);if(!Nr(o))return r;let s=(await Dr(o,{withFileTypes:!0})).filter((a)=>a.isDirectory()).map((a)=>a.name),c=await ld(e);for(let a of id(s,c)){let u=Ae(o,a);if(r.freedBytes+=await Fr(u),r.removed++,!t)await Gr(u,{force:!0,recursive:!0})}return r}async function ld(e){let t=[];for(let n of e)try{let r=await Jl(Ae(n.directory,zl)),o=et(r);if(o)t.push(o)}catch{}return t}function dd(e,t){let n=e.split(".").map((i)=>Number.parseInt(i,hs)),r=t.split(".").map((i)=>Number.parseInt(i,hs)),o=Math.max(n.length,r.length);for(let i=0;i<o;i++){let s=n[i]??0,c=r[i]??0,a=Number.isNaN(s)?0:s,u=Number.isNaN(c)?0:c;if(a!==u)return u-a}return 0}import{readFile as pd}from"fs/promises";var fd=1e4,md="/etc/resolv.conf",hd=/^\s*nameserver\[\d+\]\s*:\s*(\S+)/gm,gd=/^\s*nameserver\s+(\S+)/gm,yd=/^(?:ip|ipv6)_address:\s*(\S+)/gm,bd=/^(\S+)\s/gm;async function Ur(){let[e,t]=Bun.which("scutil")?[await ys(["scutil","--dns"]),hd]:[await wd(),gd];return ws(bs(e,t))}function jr(){return Bun.which("dscacheutil")!==null||Bun.which("getent")!==null}async function Br(e){let[t,n]=Bun.which("dscacheutil")?[["dscacheutil","-q","host","-a","name",e],yd]:[["getent","hosts",e],bd],r=performance.now(),o=await ys(t);return{addresses:ws(bs(o,n)),durationMs:Math.round(performance.now()-r),host:e}}async function ys(e){let t=Bun.spawn(e,{stderr:"ignore",stdin:"ignore",stdout:"pipe",timeout:fd}),[n]=await Promise.all([new Response(t.stdout).text(),t.exited]);return n}async function wd(){try{return await pd(md,"utf-8")}catch(e){if(e.code==="ENOENT")return"";throw e}}function bs(e,t){return[...e.matchAll(t)].flatMap((n)=>n[1]?[n[1]]:[])}function ws(e){return[...new Set(e)]}function M(e,t){switch(e.provider){case"github":return new Lr(e,Ce(fe(t)).shared,nn(t));default:throw Error(`Runner provider "${e.provider}" is not yet implemented`)}}var vs=0,$d={logs:"file(s)",shared:"version(s)",work:"item(s)"},$s=L({days:{alias:"d",default:vs,description:"Override log retention",displayDefault:`config or ${zt} days`,type:"number"},dryRun:{alias:"n",default:!1,description:"Preview cleanup without deleting",type:"boolean"},logs:{alias:"l",default:!1,description:"Remove old diagnostic logs",type:"boolean"},shared:{alias:"s",default:!1,description:"Remove unused runner versions",type:"boolean"},work:{alias:"w",default:!1,description:"Clear stopped runners' workspaces",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip workspace confirmation",type:"boolean"}});class wn extends x{name="cleanup";description="Remove logs, workspaces, and old runner versions";args=$s;async execute(e){T(e.args,$s,"Run 'hydra cleanup --help' for supported options");let t=e.config.get("profiles");if(Object.keys(t).length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let n=gn(e.config.get("cleanup")),r=this.explicitTargets(e),o=r.length>0?r:n.targets,i=e.args.days>vs?e.args.days:n.olderThanDays;if(o.includes("work")&&!e.args.dryRun&&!e.args.yes){if(!await pe({message:"Delete _work contents (checkouts and caches) of stopped runners?"}))o=o.filter((a)=>a!=="work")}let s=await bn({dryRun:e.args.dryRun,entries:e.config.get("runners")??[],now:Date.now(),olderThanDays:i,sharedDir:Ce(fe(e.config)).shared,targets:o});if(this.printReport(s,e.args.dryRun),e.args.dryRun)return;e.config.set("cleanup",{...e.config.get("cleanup"),lastRun:new Date().toISOString()})}explicitTargets(e){let t=[];if(e.args.logs)t.push("logs");if(e.args.work)t.push("work");if(e.args.shared)t.push("shared");return t}printReport(e,t){let n=[];for(let[i,s]of Object.entries(e)){if(!s)continue;let c=$d[i],a=Fe(s.freedBytes),u=t?`would remove ${s.removed} ${c}, ${a}`:`removed ${s.removed} ${c}, freed ${a}`;if(n.push(`${l.bold(i)}: ${s.removed>0?u:l.dim("nothing to do")}`),s.skipped.length>0)n.push(l.dim(` skipped running runner(s): ${s.skipped.join(", ")}`))}if(n.length===0){b.info(l.dim("Nothing to clean."));return}let r=yn(e),o=t?"Would free":"Freed";n.push(l.dim(`${o} ${Fe(r)} total`)),b.info(n.join(`
|
|
245
|
+
`))}}async function $n(e){try{let t=gn(e.config.get("cleanup"));if(!t.auto)return;if(!Mr(t,Date.now()))return;let n=await bn({dryRun:!1,entries:e.config.get("runners")??[],now:Date.now(),olderThanDays:t.olderThanDays,sharedDir:Ce(fe(e.config)).shared,targets:t.targets});e.config.set("cleanup",{...e.config.get("cleanup"),lastRun:new Date().toISOString()});let r=yn(n);if(r>0)b.info(l.dim(`Auto cleanup freed ${Fe(r)}`))}catch(t){let n=t instanceof Error?t.message:String(t);b.warn(l.yellow(`Auto cleanup failed: ${n}`))}}import{existsSync as Cs}from"fs";import{join as Ss}from"path";var Rs="Runner count must be a positive safe integer",Kr=Q().map((e)=>Number.isSafeInteger(e)&&e>0?e:F());function Be(e){try{return Kr(typeof e==="string"?Number(e):e)}catch{throw new y(Rs)}}function vn(e){try{Be(e);return}catch{return Rs}}function tt(e,t){if(e.length===0)return t;for(let n of e)if(!t.includes(n))throw new y(`Runner "${n}" not found`);return e}function q(e,t){let n=e.get("profiles");if(Object.keys(n).length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let r=t??e.get("defaultProfile")??$t,o=Object.hasOwn(n,r)?n[r]:void 0;if(!o)throw new y(`Profile "${r}" not found`);return{name:r,profile:o}}async function ce(e){let t=e.get("profiles"),n=Object.keys(t);if(n.length===0)throw new y("No profiles configured","Run hydra init to set up a profile");if(n.length===1)return n[0];return De({message:"Select profile",options:n.map((r)=>({label:r,value:r,hint:t[r]?.url}))})}var vd=B({profile:{description:"Profile to use"},count:{description:"Runner count override"}});class Rn extends x{name="create";description="Download and register runners";positionals=vd;async execute(e){T(e.args,this.args,"Run 'hydra create --help' for supported options");let{name:t,profile:n}=e.interactive?q(e.config,await ce(e.config)):q(e.config,e.positionals.profile),r=e.interactive?await this.promptCount(n.numberOfMachines):Be(e.positionals.count??n.numberOfMachines),o=e.config.get("runners")??[],i=o.filter((f)=>f.profile===t),s=r-i.length;if(s<=0){b.warn(`Already have ${i.length} runner(s) for profile "${t}". Nothing to create.`);return}let c=M(n,e.config),a=Z();a.start("Downloading runner binary...");let{version:u}=await c.download();a.stop(`Runner v${u} ready`);let d=new Set(o.map((f)=>f.id)),p=1;for(let f=0;f<s;){let w=`${n.name}-${p++}`;if(d.has(w))continue;f++;let v={createdAt:new Date().toISOString(),directory:Ss(n.directory,w),id:w,name:w,profile:t,provider:n.provider,url:n.url},C=Cs(v.directory);a.start(`Registering ${w}...`);try{await c.create([w])}finally{if(!C&&Cs(Ss(v.directory,xe))){let{agentId:R}=await Ct(v.directory);o.push(R===void 0?v:{...v,agentId:R}),e.config.set("runners",o)}}a.stop(`${l.green("+")} ${w}`)}let h=t===e.config.get("defaultProfile")?"":` ${t}`;b.info(`${l.green("Created")} ${s} runner(s) for "${t}". Run ${l.green(`hydra start${h}`)} to start them.`)}async promptCount(e){let t=await ve({initialValue:String(e),message:"Number of runners to create",validate:vn});return Be(t)}}import{isAbsolute as Rd}from"path";var nt=U().map((e)=>e.trim().length>0?e:F()),Cd=wt(["osx","linux","windows"]),xs=wt(["github","gitlab"]),Sd=Wt(wt(["logs","work","shared"])),xd=wt(["app","gh"]),Vr=Q().map((e)=>Number.isSafeInteger(e)&&e>0?e:F()),Ed=U().map((e)=>Rd(e)?e:F()),kd={app:["mode","appId","installationId","privateKeyPath"],gh:["mode"]};function Es(e){return new fr(Ce(e).config,oi,{parse:(t)=>_d(t,e),strict:!0})}function Cn(e){if(!e.failure)return;return new y(e.failure.message,`Repair ${e.path} or select another home with ${j}; hydra doctor lists the homes it finds`)}function _d(e,t){let n=Ke(e,"the config");X(n.defaultProfile,U(),"defaultProfile","a string"),Ad(n.cleanup),Id(n.credentials);let r=Object.fromEntries(Object.entries(Ke(n.profiles,"profiles")).map(([i,s])=>[i,Td(s,`profiles.${i}`,t)])),o=n.runners===void 0?void 0:Pd(n.runners,t);return{...e,profiles:r,...o?{runners:o}:{}}}function Td(e,t,n){let r=Ke(e,t);if(le(r.url,nt,`${t}.url`,"a URL"),le(r.name,nt,`${t}.name`,"a runner name prefix"),le(r.directory,nt,`${t}.directory`,"a directory"),le(r.os,Cd,`${t}.os`,"osx, linux or windows"),le(r.provider,xs,`${t}.provider`,"github or gitlab"),X(r.labels,U(),`${t}.labels`,"a comma-separated string"),X(r.runnerGroup,U(),`${t}.runnerGroup`,"a string"),X(r.numberOfMachines,Kr,`${t}.numberOfMachines`,"a positive safe integer"),X(r.overwrite,te(),`${t}.overwrite`,"a boolean"),X(r.run,te(),`${t}.run`,"a boolean"),r.jobHooks!==void 0)Ke(r.jobHooks,`${t}.jobHooks`);let o=e;return{...o,directory:br(n,o.directory)}}function Pd(e,t){if(!Array.isArray(e))throw Error("runners must be a list");return e.map((n,r)=>{let o=`runners[${r}]`,i=Ke(n,o);le(i.id,nt,`${o}.id`,"a runner id"),le(i.profile,nt,`${o}.profile`,"a profile name"),le(i.directory,nt,`${o}.directory`,"a directory");for(let c of["name","url","createdAt"])X(i[c],U(),`${o}.${c}`,"a string");X(i.provider,xs,`${o}.provider`,"github or gitlab"),X(i.agentId,Vr,`${o}.agentId`,"a positive GitHub runner id");let s=n;return{...s,directory:br(t,s.directory)}})}function Ad(e){if(e===void 0)return;let t=Ke(e,"cleanup");X(t.auto,te(),"cleanup.auto","a boolean"),X(t.intervalHours,Q(),"cleanup.intervalHours","a number of hours"),X(t.olderThanDays,Q(),"cleanup.olderThanDays","a number of days"),X(t.targets,Sd,"cleanup.targets","a list of logs, work and shared"),X(t.lastRun,U(),"cleanup.lastRun","a timestamp")}function Id(e){if(e===void 0)return;let t=Ke(e,"credentials");le(t.mode,xd,"credentials.mode","app or gh");let n=t.mode,r=Object.keys(t).find((o)=>!kd[n].includes(o));if(r)throw Error(`credentials.${r} is not a setting of the ${n} mode`);if(n==="gh")return;le(t.appId,Vr,"credentials.appId","a GitHub App id"),le(t.installationId,Vr,"credentials.installationId","an installation id"),le(t.privateKeyPath,Ed,"credentials.privateKeyPath","an absolute path")}function Ke(e,t){if(typeof e==="object"&&e!==null&&!Array.isArray(e))return e;throw Error(`${t} must be an object`)}function le(e,t,n,r){if(e===void 0)throw Error(`${n} is missing; expected ${r}`);X(e,t,n,r)}function X(e,t,n,r){if(e===void 0)return;try{t(e)}catch{throw Error(`${n} must be ${r}`)}}var Hd={configured:{paint:l.green,text:"configured"},foreign:{paint:l.yellow,text:"set to another script"},missing:{paint:l.yellow,text:"missing"},off:{paint:l.dim,text:"off"},outdated:{paint:l.yellow,text:"outdated"}},ks=new Set(["missing","outdated"]);class Sn extends x{name="doctor";description="Check DNS and each runner's job hooks";async execute(e){T(e.args,this.args,"Run 'hydra doctor --help' for supported options");let t=fe(e.config),n=Qt(t,process.cwd(),process.env),r=Cn(e.config),o=r?[]:await this.credentialLines(e.config.get("credentials"));if(b.info([...this.homeLines(t,n),...o].join(`
|
|
246
|
+
`)),r)throw r;let i=e.config.get("profiles");if(Object.keys(i).length===0)throw new y("No profiles configured",n.length>0?`Run hydra init, or pass ${j} with one of the homes above`:"Run hydra init to set up a profile");let s=e.config.get("runners")??[],c=await Ur(),a=[`${l.bold("DNS servers")} ${c.length>0?c.join(", "):l.dim("unknown")}`],u=!1,d=!1;for(let[p,m]of Object.entries(i)){let h=Se(m.jobHooks);a.push("",`${l.bold(p)} ${l.dim(m.url)}`),a.push(...await this.dnsLines(h.dns)),a.push(this.cleanupLine(h));let f=await this.runnerLines(e.config,m,h,s.filter((w)=>w.profile===p));a.push(...f.lines),u||=f.needsUpdate,d||=f.needsRestart}if(u)a.push("",l.yellow(`Run ${l.green("hydra update")} to write the missing hooks.`));if(d)a.push("",l.yellow('Restart runners marked "restart" once they are idle: hydra stop <profile> && hydra start <profile>'));b.info(a.join(`
|
|
247
|
+
`))}homeLines(e,t){let n=[`${l.bold("Home")} ${e}`];if(t.length===0)return n;n.push(l.yellow("Other Hydra homes, not used by this run:"));for(let r of t){let o=r.counts?`${_s(r.counts.profiles,"profile")}, ${_s(r.counts.runners,"runner")}`:"unreadable config";n.push(` ${r.path} ${l.dim(o)}`)}return n.push(l.dim(` Manage one with ${j} <path> or ${ae}=<path>`)),n}async dnsLines(e){let t=[` DNS wait: ${e.enabled?`on, up to ${e.timeoutSeconds} s`:l.dim("off")}`];if(!jr())return[...t,l.yellow(" No dscacheutil or getent to look hosts up with")];for(let n of e.hosts){let r=await Br(n);t.push(r.addresses.length>0?` ${l.green("\u2713")} ${n} ${l.dim(`${r.durationMs} ms \xB7 ${r.addresses.join(", ")}`)}`:` ${l.red("\u2717")} ${n} ${l.red(`no address after ${r.durationMs} ms`)}`)}return t}cleanupLine(e){let{enabled:t,keepToolCache:n}=e.workspaceCleanup;return` Workspace cleanup: ${t?`on, ${n?"keeps _tool":"empties _tool"}`:l.dim("off")}`}async credentialLines(e){let t=[`${l.bold("GitHub credentials")} ${Ni(e)}`,...this.apiRootLines()];if(e?.mode!=="app")return t;let n=await Di(e.privateKeyPath);return n?[...t,l.yellow(` The private key ${n}`)]:t}apiRootLines(){if(!process.env[Xe])return[];try{let e=l.dim(`(from ${Xe}; Hydra sends its tokens there)`);return[`${l.bold("GitHub API")} ${tn(process.env)} ${e}`]}catch(e){if(!(e instanceof y))throw e;return[l.yellow(` ${e.message}`),...e.hint?[l.dim(` ${e.hint}`)]:[]]}}async runnerLines(e,t,n,r){if(r.length===0)return{lines:[l.dim(" No runners.")],needsRestart:!1,needsUpdate:!1};let o=new Map((await M(t,e).list()).map((u)=>[u.id,u])),i=[...r].sort((u,d)=>u.id.localeCompare(d.id,void 0,{numeric:!0})),s=[],c=!1,a=!1;for(let u of i){let d=o.get(u.id),{envModifiedAt:p,states:m}=await _r(u.directory,n),h=this.loadedBefore(d,p);c||=h,a||=ks.has(m.started)||ks.has(m.completed),s.push([` ${u.id}`,l.dim(d?.status??"unknown"),`DNS wait ${this.stateLabel(m.started)}`,`cleanup ${this.stateLabel(m.completed)}`,h?l.yellow("restart"):""].filter(Boolean).join(" "))}return{lines:s,needsRestart:c,needsUpdate:a}}stateLabel(e){let{paint:t,text:n}=Hd[e];return t(n)}loadedBefore(e,t){if(e?.status!=="running"||!e.startedAt||!t)return!1;return t>e.startedAt}}function _s(e,t){return`${e} ${t}${e===1?"":"s"}`}import{mkdir as Jr}from"fs/promises";var Ts=1,Od=448,Ld=B({url:{description:"GitHub repository or organization URL"}}),Nd=L({force:{alias:"f",default:!1,description:"Overwrite an existing profile",type:"boolean"},labels:{alias:"l",description:"Set comma-separated runner labels",type:"string"},name:{alias:"n",description:"Set the runner name prefix",type:"string"},profile:{alias:"p",description:"Set the profile name",type:"string"},runners:{alias:"c",description:"Set the runner count",type:"number"}});class xn extends x{name="init";description="Set up a runner profile";positionals=Ld;args=Nd;prompts=!0;async execute(e){T(e.args,this.args,"Run 'hydra init --help' for supported options");let t=e.interactive?await this.promptProfileName(e):e.args.profile??$t,n=!e.config.exists();if(!n&&Object.hasOwn(e.config.get("profiles"),t)&&!e.args.force){if(!e.interactive)throw new y(`Profile "${t}" already exists. Use --force to overwrite.`);if(!await pe({initialValue:!1,message:`Profile "${t}" already exists. Overwrite?`}))return}let o=Ce(fe(e.config)),i=e.interactive?await this.runInitForm(o.runners):this.buildProfileFromArgs(e,o.runners);await this.ensureDirectories(o);let s={...n?{}:e.config.get("profiles"),[t]:i};if(e.config.set("profiles",s),!e.config.get("defaultProfile"))e.config.set("defaultProfile",t);We([`${l.dim("Profile:")} ${t}`,`${l.dim("URL:")} ${i.url}`,`${l.dim("Runners:")} ${i.numberOfMachines}`,`${l.dim("Name:")} ${i.name}`,i.labels?`${l.dim("Labels:")} ${i.labels}`:"","",`Run ${l.green(`${qt} create${t!==e.config.get("defaultProfile")?` ${t}`:""}`)} to provision runners.`].filter(Boolean).join(`
|
|
248
|
+
`),l.green(n?"Hydra initialized":`Profile "${t}" added`))}async promptProfileName(e){return ve({initialValue:e.args.profile??$t,message:"Profile name"})}async ensureDirectories(e){await Jr(e.home,{mode:Od,recursive:!0}),await Jr(e.shared,{recursive:!0}),await Jr(e.runners,{recursive:!0})}async runInitForm(e){let t=await Lt({url:()=>ve({message:"GitHub repository or organization URL",placeholder:"https://github.com/owner/repo",validate:(n)=>{if(!n)return"URL is required";try{ue(n)}catch{return"Must be a GitHub repository or organization URL (https://github.com/<owner>/<repo> or https://github.com/<org>)"}return}}),name:()=>ve({initialValue:"runner",message:"Base name for runners",placeholder:"runner"}),runners:()=>ve({initialValue:String(Ts),message:"Number of runners",placeholder:"1",validate:vn}),labels:()=>ve({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new de}});return{directory:e,jobHooks:dn(),labels:t.labels||void 0,name:t.name,numberOfMachines:Be(t.runners),os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:t.url}}buildProfileFromArgs(e,t){if(!e.positionals.url)throw new y("URL is required","Usage: hydra init <url>");return this.validateUrl(e.positionals.url),{directory:t,jobHooks:dn(),labels:e.args.labels,name:e.args.name??"runner",numberOfMachines:Be(e.args.runners??Ts),os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:e.positionals.url}}validateUrl(e){try{ue(e)}catch(t){throw new y(t instanceof Error?t.message:`Invalid GitHub URL: ${e}`,"Expected https://github.com/<owner>/<repo> or https://github.com/<org>")}}detectOs(){let e=process.platform;if(e==="darwin")return"osx";if(e==="win32")return"windows";return"linux"}}import{existsSync as Fd}from"fs";import{join as Ud}from"path";var Dd=/[.*+?^${}()|[\]\\]/g,Gd="-[1-9][0-9]*",Md=["unrecorded","online","busy","foreign","local","elsewhere"];function Os({elsewhere:e,elsewhereUnreadable:t,github:n,local:r,prefixes:o}){let i=o.map((h)=>new RegExp(`^${h.replace(Dd,"\\$&")}${Gd}$`)),s=r.filter((h)=>!h.orphaned),c=r.filter((h)=>h.orphaned),a=Hs(s),u=Hs(r),d=new Set([...e].map(St)),p=new Set,m=[];for(let h of n){let f=St(h.name),w=Is(h,s,p);if(w){p.add(w),m.push({github:h,local:w,placement:"both"});continue}let v={elsewhere:d.has(f),foreign:!i.some((P)=>P.test(h.name))},C=Is(h,c,p);if(!C){let P=As({...v,local:u.has(f),unrecorded:!0});m.push({github:h,keep:P,placement:"github"});continue}p.add(C);let R=As({...v,busy:h.busy,local:a.has(f),online:!on(h)});m.push({github:h,keep:R.length===0&&t?["unreadable"]:R,local:C,placement:"recorded"})}for(let h of r)if(!p.has(h))m.push({local:h,placement:"local"});return m.sort((h,f)=>Ps(h).localeCompare(Ps(f),void 0,{numeric:!0}))}function Ie(e){return e.placement==="recorded"&&e.keep.length===0}function Ls(e){return e.placement==="recorded"&&e.keep.includes("unreadable")}function Ps(e){return e.placement==="github"?e.github.name:e.local.name}function As(e){return Md.filter((t)=>e[t])}function Is(e,t,n){let r=t.filter((o)=>!n.has(o));return r.find((o)=>o.agentId===e.id)??r.find((o)=>o.agentId===void 0&&o.names.some((i)=>St(i)===St(e.name)))}function Hs(e){return new Set(e.flatMap((t)=>t.names.map(St)))}function St(e){return e.toLowerCase()}var jd=new Set([401,403,404]),Bd="Nothing was changed; retry once GitHub answers",Kd="Registrations reported as deleted stay deleted; run hydra reconcile again to finish";function rt(e){return nn(e)}async function En(e,t){let n=await Vd(e),r=qd(e),o=[];for(let i of n){let s=await ne(t,i.target,Bd,()=>sn(t.client,i.target)),c=Os({elsewhere:r.names,elsewhereUnreadable:r.unreadable.length>0,github:s,local:i.local,prefixes:i.prefixes});o.push({...i,rows:c})}return{scopes:o,unreadableHomes:r.unreadable}}async function kn(e,t,n,r=Kd){return ne(e,t,r,async()=>{let o=await Ze(e.client,t,n.id);if(!o)return"gone";if(o.name!==n.name)return"renamed";if(!on(o)||o.busy)return"changed";return Ui(e.client,t,n.id)})}function Ds(e){return Fd(Ud(e.directory,xe))}async function Vd(e){let t=e.get("runners")??[],n=new Map;for(let[r,o]of Object.entries(e.get("profiles"))){if(o.provider!=="github")continue;let i=Wr(r,o.url),s=ot(i),c=n.get(s)??{key:s,local:[],prefixes:[],target:i};n.set(s,c),c.prefixes.push(o.name);let a=await M(o,e).list(),u=t.filter((d)=>d.profile===r);c.local.push(...Jd(u,a))}return[...n.values()]}function Jd(e,t){let n=new Map(t.map((o)=>[o.id,o]));return[...e.map((o)=>{let i=n.get(o.id);return n.delete(o.id),Ns(o.id,o.directory,i,o)}),...[...n.values()].map((o)=>Ns(o.id,o.directory,o,void 0))]}function Ns(e,t,n,r){let o=n?Wd(n):void 0,i=n?.status??"unknown",s=[...new Set([o,r?.name,e].filter((c)=>Boolean(c)))];return{agentId:n?.agentId??r?.agentId,directory:t,id:e,name:o??r?.name??e,names:s,orphaned:r!==void 0&&i==="unknown",status:i}}function Wd(e){return e.name===Qe?void 0:e.name}function qd(e){let t=new Set,n=[];for(let r of Qt(fe(e),process.cwd(),process.env)){let o=vi(r.path);if(!o)n.push(r.path);for(let i of o??[])t.add(i)}return{names:t,unreadable:n}}function Wr(e,t){try{return ue(t)}catch(n){throw new y(`profiles.${e}.url: ${n.message}`,"Use a github.com repository or organisation URL")}}function ot(e){return(e.kind==="repo"?`repo:${e.owner}/${e.repo}`:`org:${e.org}`).toLowerCase()}async function ne(e,t,n,r){try{return await r()}catch(o){if(!(o instanceof V))throw o;let i=o.status!==void 0&&jd.has(o.status);throw new y(o.message,i?an(e.credentials.kind,t):n)}}var Gs="hydra-drain",Ms="Nothing was changed; retry once GitHub answers",zd="Drained runners move only into a group no repository can use; name another one with --group";async function _n(e,t,n){return ne(e,t,Ms,async()=>{let r=await Vi(e.client,t.org,n);if(!r)return;await Us(e,t,r);let o=await qi(e.client,t.org,r);return{group:r,members:new Map(o.map((i)=>[i.id,i]))}})}async function Fs(e,t,n){let r=await _n(e,t,n);if(r)return r;return ne(e,t,Ms,async()=>{let o=await Ji(e.client,t.org,n);return await Us(e,t,o),{group:o,members:new Map}})}async function Us(e,t,n){let r=Yi(n,await Wi(e.client,t.org,n));if(r)throw new y(`The runner group ${n.name} of ${t.org} is not closed: ${r}`,zd)}function Ve(e){return e.kind==="org"?e:void 0}async function it(e,t,n){let r=new Map;for(let o of t){let i=Ve(o.target),s=i?await _n(e,i,n):void 0;if(s)r.set(o.key,s)}return r}function xt(e,t){return t.github!==void 0&&t.scope!==void 0?e.get(t.scope.key)?.members.has(t.github.id)??!1:!1}var He=L({dryRun:{alias:"n",default:!1,description:"List what would change, change nothing",type:"boolean"},yes:{alias:"y",default:!1,description:"Go ahead without a confirmation prompt",type:"boolean"}}),st=L({group:{default:Gs,description:"Runner group that drained runners move into; no repository may use it",type:"string"}});function Oe(e){if(e.dryRun&&e.yes)throw new y("Pass either --dry-run or --yes, not both")}async function Le(e,t){if(e.yes)return!0;if(!process.stdout.isTTY)throw new y("This step requires confirmation","Pass --yes to go ahead, or --dry-run to only list what it would do");return pe({initialValue:!1,message:t})}function re(e){let t="worker"in e&&e.worker?", running a job":"";switch(e.kind){case"stopped":return"stopped";case"running":return`running, pid ${e.pid}${t}`;case"stale":return`stale .pid: pid ${e.pid} runs no runner from its directory`;case"unproven":return`running outside Hydra's record, pid ${e.pids.join(", ")}${t}`}}function at(e){switch(e.kind){case"stale":return`delete its .pid file once you have checked that pid ${e.pid} is not this runner`;case"unproven":return"Hydra signals only a process group it can prove, so stop those processes by hand";case"running":case"stopped":return"run hydra legacy stop first"}}function Yd(e){let t=e.registration&&!e.registration.disableUpdate?", updates itself":"";return`${Zd(e.layout)}${t}`}function Xd(e,t){if(!e.scope)return"no GitHub profile";if(!e.github)return e.registration?.agentId===void 0?"no runner id":"not on GitHub";let{busy:n,id:r,status:o}=e.github;return`${o}, ${n?"busy":"idle"} \xB7 id ${r}${t?" \xB7 drained":""}`}function js(e,t){let n=` ${e.name} ${[re(e.process),Xd(e,t),Yd(e)].join(" \xB7 ")}`;return e.refusal?`${n} \xB7 ${l.dim(`left alone: ${e.refusal}`)}`:n}function ee(e,t){return` ${l.dim("leave")} ${e.name} \xB7 ${t}`}function me(e,t,n=""){return` ${e} ${t.name}${n?` \xB7 ${n}`:""}`}function Zd(e){switch(e.kind){case"shared":return`shared ${e.version}`;case"self-updated":return`self-updated ${e.version}`;case"copied":return"own copy of the runner";case"missing":return"no runner binaries";case"unknown":return"unrecognised externals link"}}import{lstat as bp,readdir as wp}from"fs/promises";import{basename as $p,dirname as vp,join as Rp,resolve as An}from"path";import{readdir as Qd,readFile as ep,readlink as tp}from"fs/promises";import{join as Bs}from"path";var np="externals",rp=/(?:^|\/)externals\.(\d+\.\d+\.\d+)$/,op=/^(?:bin|externals)\.\d+\.\d+\.\d+$/,ip=/^[\w.-]+\.sh(?:\.template)?$/,sp=/^\uFEFF/,ap=new Set([".DS_Store",".credentials",".credentials_migrated",".credentials_rsaparams",".env",".path",".pid",".runner",".runner_migrated","_diag","_update","_work","bin","externals","hydra-hooks"]);async function Ks(e){try{let t=await tp(Bs(e,np)),n=et(t);if(n)return{kind:"shared",version:n};let r=t.match(rp)?.[1];return r?{kind:"self-updated",version:r}:{kind:"unknown"}}catch(t){return t.code==="EINVAL"?{kind:"copied"}:{kind:"missing"}}}async function Vs(e){let t;try{t=JSON.parse((await ep(Bs(e,".runner"),"utf-8")).replace(sp,""))}catch{return}if(typeof t!=="object"||t===null)return;let{agentId:n,agentName:r,disableUpdate:o,gitHubUrl:i}=t;return{agentId:Number.isSafeInteger(n)&&n>0?n:void 0,agentName:typeof r==="string"&&r?r:void 0,disableUpdate:o===!0,gitHubUrl:typeof i==="string"?i:void 0}}async function qr(e){return(await Qd(e)).filter((n)=>!Ws(n)).sort()}function Js(e){return e.filter(Ws)}function Ws(e){return ap.has(e)||op.test(e)||ip.test(e)}import{realpathSync as up}from"fs";import{readFile as cp,unlink as lp}from"fs/promises";import{join as zs}from"path";var Ys=".pid",dp=1,pp=30000,fp=200,mp=/^\s*(\d+)\s+(\d+)\s+(.*)$/,hp=/[.*+?^${}()|[\]\\]/g,qs="Listener";async function Tn(){let e=await Bun.$`ps -A -o pid= -o pgid= -o command=`.quiet().nothrow();if(e.exitCode!==0)throw new y("Cannot list the host's processes with ps",e.stderr.toString().trim()||"Nothing was changed");return e.stdout.toString().split(`
|
|
249
|
+
`).flatMap((t)=>{let n=t.match(mp);return n?[{command:n[3],pgid:Number(n[2]),pid:Number(n[1])}]:[]})}async function zr(e){try{let t=Number((await cp(zs(e,Ys),"utf-8")).trim());return Number.isSafeInteger(t)&&t>dp?t:void 0}catch{return}}function Pn(e,t,n){let r=gp(e),o=n.flatMap((u)=>{let d=u.command.match(r)?.[1];return d?[{...u,role:d}]:[]}),i=o.some((u)=>u.role!==qs),s=t!==void 0&&n.some((u)=>u.pid===t);if(o.length===0)return s&&t!==void 0?{kind:"stale",pid:t}:{kind:"stopped"};if(s&&o.some((u)=>u.role===qs)&&o.every((u)=>u.pgid===t)&&t!==void 0)return{kind:"running",pid:t,worker:i};return{kind:"unproven",pids:[...new Set([...s&&t!==void 0?[t]:[],...o.map(({pid:u})=>u)])],worker:i}}async function Xs(e,t){try{process.kill(-t,"SIGTERM")}catch(r){if(r.code!=="ESRCH")throw r}let n=Date.now()+pp;while(Date.now()<n){if(Pn(e,t,await Tn()).kind==="stopped")return await lp(zs(e,Ys)).catch(()=>{return}),"stopped";await Bun.sleep(fp)}return"timeout"}function gp(e){let t=[...new Set([e,yp(e)])].map((n)=>n.replace(hp,"\\$&"));return new RegExp(`(?:^|\\s)(?:${t.join("|")})/bin(?:\\.[^/\\s]+)?/Runner\\.(Listener|Worker)(?:\\s|$)`)}function yp(e){try{return up(e)}catch{return e}}var Cp="Nothing was changed; retry once GitHub answers",Zs="config.json does not record it",Qs="its directory is missing";async function Sp(e,t){let n=e.get("profiles"),r=new Map;for(let[a,u]of Object.entries(n)){if(u.provider!=="github")continue;let d=Wr(a,u.url);r.set(ot(d),{key:ot(d),registered:new Map,target:d})}for(let a of r.values()){let u=await ne(t,a.target,Cp,()=>sn(t.client,a.target));for(let d of u)a.registered.set(d.id,d)}let o=await Tn(),i=[],s=new Set;for(let a of e.get("runners")??[]){s.add(An(a.directory));let u=Object.hasOwn(n,a.profile)?n[a.profile]:void 0;i.push(await xp(a,u,r,o))}let c=new Set(Object.values(n).filter((a)=>a.provider==="github").map((a)=>An(a.directory)));for(let a of c)for(let u of await Tp(a)){if(s.has(u))continue;s.add(u),i.push(await Ep(u,r,o))}return{runners:i,scopes:[...r.values()]}}function ye(e){return e.refusal===void 0&&e.entry!==void 0&&e.scope!==void 0}function ea(e){return e.refusal===Qs&&e.entry!==void 0&&e.scope!==void 0&&e.process.kind==="stopped"}function ta(e){let{agentId:t,id:n,name:r}=e.entry;return[...e.scope.registered.values()].find((o)=>t===void 0?[n,r].some((i)=>typeof i==="string"&&Yr(i,o.name)):o.id===t)}async function Je(e){return Pn(e.directory,await zr(e.directory),await Tn())}async function xp(e,t,n,r){let o=await na(An(e.directory),r),i=t?.provider==="github"?n.get(ot(ue(t.url))):void 0,s=o.registration?.agentId===void 0?void 0:i?.registered.get(o.registration.agentId),c={...o,entry:e,github:s,name:e.id,profile:e.profile,scope:i};return{...c,refusal:await kp(c,t)}}async function Ep(e,t,n){let r=await na(e,n),o=_p(r.registration,t),i=r.registration?.agentId,s=i===void 0?void 0:o?.registered.get(i),c=r.registration?.agentName??$p(e);return{...r,github:s,name:c,refusal:Zs,scope:o}}async function na(e,t){let n=await zr(e);return{directory:e,layout:await Ks(e),pid:n,process:Pn(e,n,t),registration:await Vs(e)}}async function kp(e,t){let{directory:n,entry:r,github:o,registration:i,scope:s}=e;if(!r)return Zs;if(!t)return`its profile ${r.profile} is not in config.json`;if(t.provider!=="github"||!s)return"its profile does not use GitHub";if(vp(n)!==An(t.directory))return"its directory is not in its profile's directory";let c=await Xr(n);if(c==="missing")return Qs;if(c!=="directory")return"its directory is a symbolic link or not a directory";if(!i)return"it has no readable .runner file";if(i.agentId===void 0||i.agentName===void 0)return"its .runner file records no runner id or name";if(![r.id,r.name].filter((u)=>typeof u==="string").some((u)=>Yr(u,i.agentName)))return`it is registered as ${i.agentName}, not as ${r.id}`;if(ra(i)!==s.key)return"its .runner file names another organisation or repository";if(o&&!Yr(o.name,i.agentName))return`GitHub lists runner ${o.id} as ${o.name}`;return}function _p(e,t){let n=ra(e);return n===void 0?void 0:t.get(n)}function ra(e){if(!e?.gitHubUrl)return;try{return ot(ue(e.gitHubUrl))}catch{return}}async function Tp(e){try{return(await wp(e,{withFileTypes:!0})).filter((n)=>n.isDirectory()).map((n)=>Rp(e,n.name))}catch{return[]}}async function Xr(e){try{return(await bp(e)).isDirectory()?"directory":"other"}catch(t){return t.code==="ENOENT"?"missing":"other"}}function Yr(e,t){return e.toLowerCase()===t.toLowerCase()}async function be(e){if(Object.keys(e.get("profiles")).length===0)throw new y("No profiles configured",`Select the 0.x fleet's home with ${j} <path> or ${ae}`);let t=rt(e);return{github:t,inventory:await Sp(e,t)}}var Pp={busy:"busy",elsewhere:"recorded in another Hydra home",foreign:"name not managed here",local:"name used by a runner in this home",unreadable:"another Hydra home cannot be read",unrecorded:"not recorded in this home"},ia="recorded, no runner here";function Zr(e){return`${l.bold(Pe(e.target))} ${l.dim("on GitHub")}`}function In(e){return`${e.status}, ${e.busy?"busy":"idle"}`}function Qr(e){return e.keep.map((t)=>t==="online"?e.github.status:Pp[t]).join(", ")}function sa(e){let t=[Zr(e)];if(e.rows.length===0)return[...t,l.dim(" No runners here or on GitHub.")];for(let n of e.rows)t.push(` ${Ap(n)}`);return t.push(l.dim(` ${Hp(e.rows)}`)),t}function Ap(e){switch(e.placement){case"both":return`${e.local.name} ${e.local.status} \xB7 ${In(e.github)} \xB7 id ${e.github.id}`;case"local":return`${e.local.name} ${Ip(e.local)} \xB7 ${l.yellow("not on GitHub")}`;case"recorded":return`${e.local.name} ${ia} \xB7 ${oa(e)}`;case"github":return`${e.github.name} not in this home \xB7 ${oa(e)}`}}function Ip(e){return e.orphaned?ia:e.status}function oa(e){let t=Ie(e)?l.yellow("stale"):l.dim(`left alone: ${Qr(e)}`);return`${In(e.github)} \xB7 id ${e.github.id} \xB7 ${t}`}function Hp(e){let t=(c)=>e.filter((a)=>a.placement===c).length,n=t("both"),r=t("local"),o=t("recorded"),i=t("github"),s=e.filter(Ie).length;return[`${n+o+i} on GitHub, ${n+o+r} in this home:`,`${n} in both, ${o} recorded without a runner, ${r} only here, ${i} only on GitHub, ${s} stale`].join(" ")}var aa=L({...He}),Op="Registrations reported as deleted stay deleted; run hydra legacy deregister again to finish",Lp={busy:"kept: GitHub reports it busy",changed:"kept: GitHub no longer reports it offline and idle",deleted:"deregistered",gone:"already gone",renamed:"kept: GitHub lists it under another name now"};class eo extends x{name="deregister";description="Delete the GitHub registrations of stopped 0.x runners by id";args=aa;async execute(e){T(e.args,aa,"Run 'hydra legacy deregister --help' for supported options"),Oe(e.args);let{github:t,inventory:n}=await be(e.config),r=[],o=[];for(let s of n.runners)if(!ye(s))o.push(ee(s,s.refusal??"config.json does not record it"));else if(!s.github)o.push(me(l.dim("done"),s,"not registered on GitHub"));else if(s.process.kind!=="stopped")o.push(ee(s,`${re(s.process)}; ${at(s.process)}`));else{r.push(s);let c=l.red(e.args.dryRun?"would deregister":"deregister");o.push(me(c,s,`id ${s.github.id} \xB7 ${s.github.status}`))}if(b.info(o.join(`
|
|
250
|
+
`)),r.length===0){b.info(l.dim("Nothing to deregister."));return}if(e.args.dryRun){b.info(`Would deregister ${r.length} runner(s). Run ${l.green("hydra legacy deregister --yes")} to do it.`);return}if(!await Le(e.args,`Delete ${r.length} registration(s) from GitHub?`))return;let i=0;for(let s of r){let c=await Je(s);if(c.kind!=="stopped"||!s.github){b.info(`${s.name} \xB7 ${l.yellow(`kept: ${re(c)}`)}`);continue}let a=await kn(t,s.scope.target,s.github,Op);if(a==="deleted")i++;let u=Lp[a];b.info(`${s.name} \xB7 id ${s.github.id} \xB7 ${a==="deleted"?l.green(u):u}`)}b.info(`${l.green("Deregistered")} ${i} of ${r.length} runner(s).`)}}var ua=L({...He,...st}),Np="Runners reported as moved stay drained; run hydra legacy drain again to finish";class to extends x{name="drain";description="Move a 0.x fleet's runners into a runner group no repository can use";args=ua;async execute(e){T(e.args,ua,"Run 'hydra legacy drain --help' for supported options"),Oe(e.args);let{group:t,dryRun:n}=e.args,{github:r,inventory:o}=await be(e.config),i=await it(r,o.scopes,t),s=new Map,c=[];for(let d of o.runners){if(!ye(d)){c.push(ee(d,d.refusal??"config.json does not record it"));continue}if(!d.github){c.push(ee(d,"not registered on GitHub"));continue}if(!Ve(d.scope.target)){c.push(ee(d,"repository runners have no runner groups; stop it with hydra stop once idle"));continue}if(i.get(d.scope.key)?.members.has(d.github.id)){c.push(me(l.dim("drained"),d,`already in ${t}`));continue}s.set(d.scope,[...s.get(d.scope)??[],{id:d.github.id,runner:d}]);let p=d.github.busy?"busy, its job keeps running":"idle";c.push(me(l.yellow(n?"would move":"move"),d,`id ${d.github.id} \xB7 ${p}`))}for(let d of s.keys())if(!i.has(d.key))c.push(l.dim(` ${n?"would create":"create"} ${t}`));b.info(c.join(`
|
|
251
|
+
`));let a=[...s.values()].reduce((d,p)=>d+p.length,0);if(a===0){b.info(l.dim("Nothing to drain."));return}if(n){b.info(`Would move ${a} runner(s) into ${t}. Run ${l.green("hydra legacy drain --yes")} to move them.`);return}if(!await Le(e.args,`Move ${a} runner(s) into ${t}?`))return;let u=0;for(let[d,p]of s){let m=Ve(d.target);if(!m)continue;let h=i.get(d.key)??await Fs(r,m,t);for(let{id:f,runner:w}of p)await ne(r,m,Np,()=>zi(r.client,m.org,h.group,f)),u++,b.info(`${w.name} \xB7 id ${f} \xB7 ${l.green(`moved into ${h.group.name}`)}`)}b.info(`${l.green("Drained")} ${u} runner(s). They take no new jobs; run ${l.green("hydra legacy stop --wait")} to stop them once their jobs finish.`)}}var ca=L({...st});class no extends x{name="inventory";description="List a 0.x fleet's runners, here and on GitHub";args=ca;async execute(e){T(e.args,ca,"Run 'hydra legacy inventory --help' for supported options");let{github:t,inventory:n}=await be(e.config),r=await it(t,n.scopes,e.args.group),o=e.config.get("profiles"),i=new Map;for(let u of n.runners){let d=u.entry?u.entry.profile:"";i.set(d,[...i.get(d)??[],u])}let s=[];for(let[u,d]of i){if(s.length>0)s.push("");let p=Object.hasOwn(o,u)?o[u]?.url:void 0;s.push(u?`${l.bold(u)} ${l.dim(p??"no such profile")}`:l.bold("Not recorded"));let m=d.sort((h,f)=>h.name.localeCompare(f.name,void 0,{numeric:!0}));for(let h of m)s.push(js(h,xt(r,h)))}if(s.length===0)s.push(l.dim("No runners in this home."));let c=n.runners,a=(u)=>c.filter(u).length;s.push("",l.dim([`${c.length} runner(s)`,`${a(ye)} provably this home's`,`${a((u)=>u.process.kind==="running"||u.process.kind==="unproven")} running`,`${a((u)=>u.github?.busy===!0)} busy`,`${a((u)=>xt(r,u))} drained into ${e.args.group}`,`${a((u)=>u.layout.kind==="self-updated")} self-updated`,`${a((u)=>u.refusal!==void 0)} left alone`].join(", "))),b.info(s.join(`
|
|
252
|
+
`))}}var la=L({...He,...st,interval:{default:15,description:"Seconds between checks while waiting",type:"number"},timeout:{default:60,description:"Minutes to wait for busy runners",type:"number"},wait:{alias:"w",default:!1,description:"Wait for busy runners to finish their jobs",type:"boolean"}}),ro=1000,Dp=60,Gp="Nothing more was stopped; run hydra legacy stop again";class oo extends x{name="stop";description="Stop drained 0.x runners once GitHub and the host show them idle";args=la;async execute(e){T(e.args,la,"Run 'hydra legacy stop --help' for supported options"),Oe(e.args);let{dryRun:t,group:n,interval:r,timeout:o,wait:i}=e.args;if(!(r>0)||!(o>=0))throw new y("--interval must be above 0 and --timeout at least 0");let{github:s,inventory:c}=await be(e.config),a=await it(s,c.scopes,n),u=[],d=[],p=0;for(let f of c.runners.filter((w)=>w.process.kind!=="stopped")){let w=Mp(f,xt(a,f),n);if(w||!ye(f)){if(f.process.kind!=="stale")p++;d.push(ee(f,w??"config.json does not record it"));continue}u.push(f);let v=f.github?.busy||"worker"in f.process&&f.process.worker?"busy":"idle";d.push(me(l.yellow(t?"would stop":"stop"),f,`${re(f.process)} \xB7 ${v}`))}if(d.length===0)d.push(l.dim(" No runner of this home is running."));if(b.info(d.join(`
|
|
253
|
+
`)),u.length===0)return da(p,0,i);if(t){b.info(`Would stop ${u.length} runner(s), each only once it is idle.`);return}if(!await Le(e.args,`Stop ${u.length} runner(s) once each is idle?`))return;let m=Date.now()+o*Dp*ro,h=u;while(!0){let f=[],w=await this.drainGroups(s,h,n);for(let v of h){let C=await this.attempt(s,v,w.get(v.scope.key));if(C==="busy")f.push(v);if(C==="left")p++}if(h=f,h.length===0||!i||Date.now()+r*ro>m)break;b.info(l.dim(`Waiting for ${h.length} busy runner(s)...`)),await Bun.sleep(r*ro)}for(let f of h)b.info(`${f.name} \xB7 ${l.yellow("still busy, left running")}`);da(p,h.length,i)}async drainGroups(e,t,n){let r=new Map;for(let o of t){let i=Ve(o.scope.target);if(!i||r.has(o.scope.key))continue;r.set(o.scope.key,await _n(e,i,n))}return r}async attempt(e,t,n){let r=t.github?.id;if(r===void 0||!n?.members.has(r))return b.info(`${t.name} \xB7 ${l.yellow("left running: it is no longer in the drain group")}`),"left";if(n.members.get(r)?.busy)return"busy";let o=await ne(e,t.scope.target,Gp,()=>Ze(e.client,t.scope.target,r));if(!o||o.name.toLowerCase()!==t.github?.name.toLowerCase())return b.info(`${t.name} \xB7 ${l.yellow("left running: GitHub no longer lists it under this id and name")}`),"left";if(o.busy)return"busy";let i=await Je(t);if(i.kind==="stopped")return b.info(`${t.name} \xB7 already stopped`),"stopped";if(i.kind==="unproven"||i.kind==="stale")return b.info(`${t.name} \xB7 ${l.yellow(`left running: ${re(i)}`)}`),"left";if(i.worker)return"busy";if(await Xs(t.directory,i.pid)==="timeout")return b.info(`${t.name} \xB7 ${l.yellow("did not stop in time; check it with hydra legacy inventory")}`),"left";return b.info(`${t.name} \xB7 ${l.green("stopped")}`),"stopped"}}function da(e,t,n){if(e+t===0)return;let r=t===0?"Check why they were left alone with hydra legacy inventory":n?"Their jobs outlasted --timeout; run hydra legacy stop --wait again":"Pass --wait to stop busy runners once their jobs finish";throw new y(`${e+t} runner(s) are still running`,r)}function Mp(e,t,n){if(e.refusal)return e.refusal;if(e.process.kind==="stale")return`${re(e.process)}; ${at(e.process)}`;if(e.process.kind==="unproven")return re(e.process);if(!e.github)return"not registered on GitHub, so Hydra cannot prove it takes no jobs";if(e.scope&&!Ve(e.scope.target))return"repository runners have no runner groups; stop it with hydra stop once idle";if(!t)return`not in ${n}; run hydra legacy drain first`;return}import{readdir as Fp,rm as pa,rmdir as Up}from"fs/promises";import{join as fa}from"path";var ma=L({...He}),jp="Nothing more was wiped; run hydra legacy wipe again",Et="Its .runner file is kept; fix the cause, then run hydra legacy wipe again",Bp="Delete what is left of the directory, then run hydra legacy wipe again to drop its record",Kp=2;class io extends x{name="wipe";description="Delete the directories and records of stopped, deregistered 0.x runners";args=ma;async execute(e){T(e.args,ma,"Run 'hydra legacy wipe --help' for supported options"),Oe(e.args);let{github:t,inventory:n}=await be(e.config),r=(d)=>l.red(e.args.dryRun?`would ${d}`:d),o=[],i=[],s=[],c=[];for(let d of n.runners)if(ea(d)){let p=ta(d);if(p){c.push(ee(d,`its directory is missing but GitHub lists id ${p.id}; run hydra reconcile`));continue}i.push(d),c.push(me(r("drop"),d,"its directory is missing, so only its record is left"))}else if(!ye(d))c.push(ee(d,d.refusal??"config.json does not record it"));else if(d.github)c.push(ee(d,`registered on GitHub as id ${d.github.id}; run hydra legacy deregister first`));else if(d.process.kind!=="stopped")c.push(ee(d,`${re(d.process)}; ${at(d.process)}`));else{let p=await ut(d,Et,()=>qr(d.directory));if(p.length>0)s.push(` ${d.name}: ${p.join(", ")}`);o.push(d),c.push(me(r("wipe"),d,d.directory))}if(b.info(c.join(`
|
|
254
|
+
`)),s.length>0)throw b.warn(l.yellow(["Unexpected entries in runner directories:",...s].join(`
|
|
255
|
+
`))),new y("Not wiping: a runner directory holds entries a 0.x runner does not create","Move those entries out of the runner directory, then run hydra legacy wipe again");let a=o.length+i.length;if(a===0){b.info(l.dim("Nothing to wipe."));return}if(e.args.dryRun){b.info(`Would wipe ${a} runner(s). Run ${l.green("hydra legacy wipe --yes")} to do it.`);return}if(!await Le(e.args,`Delete ${o.length} runner directory(ies) and ${a} record(s)?`))return;let u=0;for(let d of o){let p=await this.keepReason(t,d);if(p){b.info(`${d.name} \xB7 ${l.yellow(`kept: ${p}`)}`);continue}await Jp(d),ha(e.config,d.entry),u++,b.info(`${d.name} \xB7 ${l.green("wiped")}`)}for(let d of i){let p=await Vp(d);if(p){b.info(`${d.name} \xB7 ${l.yellow(`kept: ${p}`)}`);continue}ha(e.config,d.entry),u++,b.info(`${d.name} \xB7 ${l.green("record dropped")}`)}b.info(`${l.green("Wiped")} ${u} of ${a} runner(s).`)}async keepReason(e,t){let n=await Je(t);if(n.kind!=="stopped")return re(n);let r=t.registration?.agentId;if(r===void 0)return"its .runner file records no runner id";if(await ne(e,t.scope.target,jp,()=>Ze(e.client,t.scope.target,r)))return`GitHub lists it again as id ${r}`;let i=await ut(t,Et,()=>qr(t.directory));return i.length>0?`unexpected entries: ${i.join(", ")}`:void 0}}async function Vp(e){let t=await Je(e);if(t.kind!=="stopped")return re(t);return await Xr(e.directory)==="missing"?void 0:"its directory exists again"}async function Jp(e){let{directory:t}=e;for(let n=0;n<Kp;n++){let r=await ut(e,Et,()=>Fp(t));for(let o of Js(r).filter((i)=>i!==xe))await ut(e,Et,()=>pa(fa(t,o),{force:!0,recursive:!0}))}await ut(e,Et,()=>pa(fa(t,xe),{force:!0})),await ut(e,Bp,()=>Up(t))}async function ut(e,t,n){try{return await n()}catch(r){throw new y(`Cannot wipe ${e.name} in ${e.directory}: ${r.message}`,t)}}function ha(e,t){e.set("runners",(e.get("runners")??[]).filter((n)=>n.id!==t.id||n.profile!==t.profile))}class Hn extends x{name="legacy";description="Drain, stop, deregister and wipe a 0.x fleet";init(){this.registerSubcommands([new no,new to,new oo,new eo,new io])}}import{existsSync as Wp}from"fs";import{readFile as qp}from"fs/promises";var zp=100,Yp={runner:"runner daemon log",worker:"job log"},Xp=L({lines:{alias:"n",default:zp,description:"Number of lines to show",type:"number"},list:{alias:"l",default:!1,description:"List log files instead of showing one",type:"boolean"},open:{alias:"o",default:!1,description:"Open the log file",type:"boolean"},runner:{alias:"r",default:!1,description:"Show the runner log instead of a job log",type:"boolean"}}),Zp=B({id:{description:"Runner ID"}});class On extends x{name="logs";description="Show recent runner logs";args=Xp;positionals=Zp;async execute(e){let t=e.config.get("runners")??[];if(t.length===0)throw new y("No runners found","Run hydra create to provision runners");let n=await this.resolveEntry(e,t),r=e.config.get("profiles"),o=Object.hasOwn(r,n.profile)?r[n.profile]:void 0;if(!o)throw new y(`Profile "${n.profile}" not found for runner "${n.id}"`,"Run hydra init to set it up");if(!Wp(n.directory))throw new y(`Runner directory not found: ${n.directory}`,"Run hydra create to provision this runner");let s=await M(o,e.config).logFiles(n.id);if(s.length===0)this.noLogs(n.id);if(e.args.list){this.printList(n,s);return}let c=this.selectFile(e,n,s);if(e.args.open){await this.openFile(c);return}await this.printTail(n,c,e.args.lines)}async resolveEntry(e,t){let n=e.positionals.id;if(n){let o=t.find((i)=>i.id===n);if(!o)throw new y(`Runner "${n}" not found`,`Known runners: ${t.map((i)=>i.id).join(", ")}`);return o}if(e.interactive)return De({message:"Select runner",options:t.map((o)=>({hint:o.profile,label:o.name,value:o}))});let r=t[0];if(t.length===1&&r)return r;throw new y("Multiple runners found",`Pass a runner id: hydra logs <id> (${t.map((o)=>o.id).join(", ")})`)}selectFile(e,t,n){if(e.args.runner){let o=n.find((i)=>i.type==="runner");if(!o)throw new y(`No runner daemon logs found for "${t.id}"`,"Start the runner first: hydra start");return o}let r=Pr(n,"worker");if(!r)this.noLogs(t.id);if(r.fallback)b.warn(l.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return r.file}noLogs(e){throw new y(`No logs found for runner "${e}"`,"Logs appear once the runner has started; run hydra start")}printList(e,t){let n=[`${l.bold(e.name)} ${l.dim(e.directory)}`];for(let r of t){let o=r.type==="worker"?l.green("worker"):l.blue("runner");n.push(` ${o} ${r.name} ${l.dim(`${r.mtime.toISOString()} \xB7 ${Fe(r.size)}`)}`)}b.info(n.join(`
|
|
256
|
+
`))}async printTail(e,t,n){let r=await qp(t.path,"utf-8"),o=[`${l.bold(e.name)} ${l.dim(Yp[t.type])}`,l.dim(t.path),l.dim(`Last modified: ${t.mtime.toISOString()}`)];b.info(o.join(`
|
|
257
|
+
`)),console.log(Ar(r,n))}async openFile(e){let t=(process.env.EDITOR??"").split(" ").filter(Boolean),n=t[0];if(n){await Bun.spawn([n,...t.slice(1),e.path],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited;return}if(process.platform==="darwin"){await Bun.$`open ${e.path}`.quiet();return}throw new y("No editor configured","Set $EDITOR to open log files")}}var Qp=B({name:{description:"Profile name to set as default"}});class so extends x{name="default";description="Set the default profile";positionals=Qp;async execute(e){T(e.args,this.args,"Run 'hydra profile default --help' for supported options");let t=e.interactive?await ce(e.config):e.positionals.name;if(!t)throw new y("Profile name is required","Usage: hydra profile default <name>");let{name:n}=q(e.config,t);if(e.config.get("defaultProfile")===n){b.info(`"${n}" is already the default profile.`);return}e.config.set("defaultProfile",n),b.info(`${l.green("Default profile set to")} "${n}".`)}}class ao extends x{name="list";description="List profiles";async execute(e){let t=e.config.get("profiles"),n=Object.keys(t);if(n.length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let r=e.config.get("runners")??[],o=e.config.get("defaultProfile");for(let i of n){let s=t[i],a=await M(s,e.config).list(),u=r.filter((w)=>w.profile===i),d=new Set(a.filter((w)=>w.status==="running").map((w)=>w.id)),p=u.filter((w)=>d.has(w.id)).length,m=i===o,h=[`${l.dim("URL:")} ${s.url}`,`${l.dim("Provider:")} ${s.provider}`,`${l.dim("OS:")} ${s.os}`,`${l.dim("Name:")} ${s.name}`,`${l.dim("Runners:")} ${u.length}/${s.numberOfMachines} created, ${l.green(`${p} running`)}`];if(s.labels)h.push(`${l.dim("Labels:")} ${s.labels}`);let f=m?`${i} ${l.dim("(default)")}`:i;We(h.join(`
|
|
258
|
+
`),f)}b.info(l.dim(`${n.length} profile(s)`))}}import{rm as ef}from"fs/promises";import{join as tf}from"path";var nf=B({name:{description:"Profile name to remove"}}),rf=L({yes:{alias:"y",default:!1,description:"Skip runner removal confirmation",type:"boolean"}});class uo extends x{name="remove";description="Delete a profile and its runners";positionals=nf;args=rf;async execute(e){T(e.args,this.args,"Run 'hydra profile remove --help' for supported options");let t=e.interactive?await ce(e.config):e.positionals.name;if(!t)throw new y("Profile name is required","Usage: hydra profile remove <name>");let{profile:n}=q(e.config,t),r=e.config.get("runners")??[],o=r.filter((a)=>a.profile===t);if(o.length>0){if(!e.args.yes){if(!process.stdout.isTTY)throw new y("Runner removal requires confirmation","Pass --yes to remove the profile and its runners without a prompt");if(!await pe({initialValue:!0,message:`This will stop and remove ${o.length} runner(s). Continue?`}))return}await this.removeRunners(e,n,o.map((u)=>u.id));let a=r.filter((u)=>u.profile!==t);e.config.set("runners",a)}let{[t]:i,...s}=e.config.get("profiles");if(e.config.set("profiles",s),e.config.get("defaultProfile")===t){let a=Object.keys(s);e.config.set("defaultProfile",a[0])}b.info(`${l.green("Removed")} profile "${t}".`)}async removeRunners(e,t,n){let r=M(t,e.config),o=Z();for(let i of n)o.start(`Stopping and removing ${i}...`),await r.remove([i]),await ef(tf(t.directory,i),{force:!0,recursive:!0}),e.config.set("runners",(e.config.get("runners")??[]).filter((s)=>s.id!==i)),o.stop(`${l.red("-")} ${i}`)}}class Ln extends x{name="profile";description="Manage profiles";init(){this.registerSubcommands([new ao,new uo,new so])}}var ga=L({dryRun:{alias:"n",default:!1,description:"List what would be deleted, delete nothing",type:"boolean"},yes:{alias:"y",default:!1,description:"Delete without a confirmation prompt",type:"boolean"}}),of={busy:"kept: GitHub reports it busy",changed:"kept: it is no longer offline and idle",deleted:"deleted",gone:"already gone",renamed:"kept: GitHub lists it under another name now",returned:"kept: its directory in this home holds a runner again"};class Nn extends x{name="reconcile";description="Delete stale GitHub registrations of this home's runners";args=ga;async execute(e){if(T(e.args,ga,"Run 'hydra reconcile --help' for supported options"),e.args.dryRun&&e.args.yes)throw new y("Pass either --dry-run or --yes, not both");if(Object.keys(e.config.get("profiles")).length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let t=rt(e.config),{scopes:n,unreadableHomes:r}=await En(e.config,t);if(n.length===0){b.info(l.dim("No GitHub profiles to reconcile."));return}let o=n.flatMap((i)=>i.rows.filter(Ie).map((s)=>({row:s,scope:i})));b.info(this.planLines(n,e.args.dryRun).join(`
|
|
259
|
+
`));for(let i of r)b.warn(l.yellow(`Cannot read the runner records of ${i}`));if(n.some((i)=>i.rows.some(Ls)))throw new y("Not deleting: another Hydra home may record these runners","Repair or move the home named above, then run hydra reconcile again");if(o.length===0){b.info(l.dim("Nothing to delete."));return}if(e.args.dryRun){b.info(`Would delete ${o.length} registration(s). Run ${l.green("hydra reconcile --yes")} to delete them.`);return}if(!await this.confirmed(e,o.length))return;await this.deleteStale(t,o)}planLines(e,t){let n=[];for(let r of e){if(n.length>0)n.push("");n.push(Zr(r));let o=r.rows.filter((i)=>i.placement!=="both");if(o.length===0)n.push(l.dim(" Every runner here matches a registration on GitHub."));for(let i of o){if(i.placement==="local"){n.push(` ${i.local.name} ${l.dim("is in this home but not registered on GitHub")}`);continue}let s=`${i.github.name} \xB7 id ${i.github.id}`;n.push(Ie(i)?` ${l.red(t?"would delete":"delete")} ${s} \xB7 ${In(i.github)}`:` ${l.dim("keep")} ${s} \xB7 ${Qr(i)}`)}}return n}async confirmed(e,t){if(e.args.yes)return!0;if(!process.stdout.isTTY)throw new y("Deleting registrations requires confirmation","Pass --yes to delete them, or --dry-run to only list them");return pe({initialValue:!1,message:`Delete ${t} registration(s) from GitHub?`})}async deleteStale(e,t){let n=0;for(let{row:r,scope:o}of t){let i=Ds(r.local)?"returned":await kn(e,o.target,r.github);if(i==="deleted")n++;let s=of[i];b.info(`${r.github.name} \xB7 id ${r.github.id} \xB7 ${i==="deleted"?l.green(s):s}`)}b.info(`${l.green("Deleted")} ${n} of ${t.length} registration(s).`)}}import{rm as sf}from"fs/promises";import{join as af}from"path";var uf=B({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class Dn extends x{name="remove";description="Deregister and delete runners";positionals=uf;async execute(e){T(e.args,this.args,"Run 'hydra remove --help' for supported options");let{name:t,profile:n}=e.interactive?q(e.config,await ce(e.config)):q(e.config,e.positionals.profile),o=(e.config.get("runners")??[]).filter((a)=>a.profile===t);if(o.length===0)throw new y(`No runners found for profile "${t}"`,"Run hydra create to provision runners");let i=e.interactive?await this.promptRunnerSelection(o.map((a)=>a.id)):tt(e.positionals.ids??[],o.map((a)=>a.id)),s=M(n,e.config),c=Z();for(let a of i)c.start(`Stopping and removing ${a}...`),await s.remove([a]),await sf(af(n.directory,a),{force:!0,recursive:!0}),e.config.set("runners",(e.config.get("runners")??[]).filter((u)=>u.id!==a)),c.stop(`${l.red("-")} ${a}`);b.info(`${l.green("Removed")} ${i.length} runner(s).`)}async promptRunnerSelection(e){return Ge({message:"Select runners to remove",options:e.map((t)=>({label:t,value:t})),required:!0})}}var cf=B({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class Gn extends x{name="start";description="Start runners";positionals=cf;async execute(e){T(e.args,this.args,"Run 'hydra start --help' for supported options");let{name:t,profile:n}=e.interactive?q(e.config,await ce(e.config)):q(e.config,e.positionals.profile),o=(e.config.get("runners")??[]).filter((m)=>m.profile===t);if(o.length===0)throw new y(`No runners found for profile "${t}"`,"Run hydra create to provision runners");let i=M(n,e.config),s=Z();s.start("Fetching runner status...");let c=await i.list();s.stop("Runner status fetched");let a=new Set(c.filter((m)=>m.status==="running").map((m)=>m.id)),u=o.map((m)=>m.id).filter((m)=>!a.has(m)),d=e.interactive?await this.promptRunnerSelection(u):tt(e.positionals.ids??[],o.map((m)=>m.id)),p=0;for(let m of d){if(a.has(m)){s.start(""),s.stop(`${l.dim("\u25CF")} ${m} ${l.dim("already running")}`);continue}s.start(`Starting ${m}...`),await i.start([m]),s.stop(`${l.green("\u25B6")} ${m}`),p++}b.info(`${l.green("Started")} ${p} runner(s).`),await $n(e)}async promptRunnerSelection(e){if(e.length===0)throw new y("All runners are already running");return Ge({message:"Select runners to start",options:e.map((t)=>({label:t,value:t})),required:!0})}}var ya=L({github:{alias:"g",default:!1,description:"Compare with the runners registered on GitHub",type:"boolean"}}),lf={registered:l.yellow,running:l.green,stopped:l.red,unknown:l.dim};class Mn extends x{name="status";description="Show status across profiles";args=ya;async execute(e){T(e.args,ya,"Run 'hydra status --help' for supported options");let t=e.config.get("profiles"),n=Object.keys(t);if(n.length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let r=e.config.get("runners")??[],o=0,i=0,s=[];for(let c of n){let a=t[c],d=await M(a,e.config).list();if(s.length>0)s.push("");s.push(`${l.bold(c)} ${l.dim(a.url)}`);let p=new Set(r.filter((h)=>h.profile===c).map((h)=>h.id)),m=d.filter((h)=>p.has(h.id)).sort((h,f)=>h.name.localeCompare(f.name,void 0,{numeric:!0}));this.formatRunners(m,s),o+=m.length,i+=m.filter((h)=>h.status==="running").length}if(s.push(""),s.push(l.dim(`${o} runner(s) total, ${i} running`)),b.info(s.join(`
|
|
260
|
+
`)),e.args.github)await this.printGitHubComparison(e)}async printGitHubComparison(e){let{scopes:t,unreadableHomes:n}=await En(e.config,rt(e.config));if(t.length===0){b.info(l.dim("No GitHub profiles to compare."));return}let r=t.flatMap((i,s)=>[...s>0?[""]:[],...sa(i)]),o=t.flatMap((i)=>i.rows.filter(Ie)).length;if(o>0)r.push("",l.yellow(`Run ${l.green("hydra reconcile --dry-run")} to review ${o} stale registration(s).`));b.info(r.join(`
|
|
261
|
+
`));for(let i of n)b.warn(l.yellow(`Cannot read the runner records of ${i}`))}formatRunners(e,t){if(e.length===0){t.push(l.dim(" No runners."));return}for(let n of e){let r=lf[n.status]??l.dim,o=n.pid?l.dim(` (pid: ${n.pid})`):"";t.push(` ${r("\u25CF")} ${n.name} ${r(n.status)}${o}`)}}}var df=B({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class Fn extends x{name="stop";description="Stop runners";positionals=df;async execute(e){T(e.args,this.args,"Run 'hydra stop --help' for supported options");let{name:t,profile:n}=e.interactive?q(e.config,await ce(e.config)):q(e.config,e.positionals.profile),o=(e.config.get("runners")??[]).filter((m)=>m.profile===t);if(o.length===0)throw new y(`No runners found for profile "${t}"`,"Run hydra create to provision runners");let i=M(n,e.config),s=Z();s.start("Fetching runner status...");let c=await i.list();s.stop("Runner status fetched");let a=new Set(c.filter((m)=>m.status==="running").map((m)=>m.id)),u=o.map((m)=>m.id).filter((m)=>a.has(m)),d=e.interactive?await this.promptRunnerSelection(u):tt(e.positionals.ids??[],o.map((m)=>m.id)),p=0;for(let m of d){if(!a.has(m)){s.start(""),s.stop(`${l.dim("\u25CF")} ${m} ${l.dim("not running")}`);continue}s.start(`Stopping ${m}...`),await i.stop([m]),s.stop(`${l.red("\u25A0")} ${m}`),p++}b.info(`${l.green("Stopped")} ${p} runner(s).`)}async promptRunnerSelection(e){if(e.length===0)throw new y("No runners are currently running");return Ge({message:"Select runners to stop",options:e.map((t)=>({label:t,value:t})),required:!0})}}class Un extends x{name="update";description="Update runner binaries and job hooks";async execute(e){T(e.args,this.args,"Run 'hydra update --help' for supported options");let t=e.config.get("profiles"),n=e.config.get("runners")??[];if(n.length===0)throw new y("No runners found","Run hydra create to provision runners");let r=Z(),o=Map.groupBy(n,(a)=>a.profile);for(let a of o.keys()){let u=Object.hasOwn(t,a)?t[a]:void 0;if(u)Se(u.jobHooks)}let i=0,s=0,c=new Map;for(let[a,u]of o){let d=Object.hasOwn(t,a)?t[a]:void 0;if(!d)continue;let p=M(d,e.config);r.start(`Checking for updates for "${a}"...`);let{version:m}=await p.download();r.stop(`Latest: v${m}`);let h=await p.list(),f=new Set(h.filter((w)=>w.status==="running").map((w)=>w.id));for(let w of u){let v=f.has(w.id);if(await p.currentVersion(w.id)===m){let R=await p.configureJobHooks(w.id);if(!R.envChanged&&!R.scriptsChanged)continue;if(s++,R.envChanged&&v){let P=c.get(a)??{ids:[],total:u.length};c.set(a,{...P,ids:[...P.ids,w.id]})}r.start(""),r.stop(`${l.green("\u2713")} ${w.id} ${l.dim("(job hooks)")}`);continue}if(r.start(`Updating ${w.id}...`),v)await p.stop([w.id]);if(await p.update([w.id]),v)await p.start([w.id]);i++;let C=v?` ${l.dim("(restarted)")}`:"";r.stop(`${l.green("\u2713")} ${w.id}${C}`)}}if(b.info(i>0?`${l.green("Updated")} ${i} runner(s).`:"All runners are already on the latest version."),s>0)b.info(`${l.green("Refreshed")} job hooks on ${s} runner(s).`);this.printRestartHint(c),await $n(e)}printRestartHint(e){if(e.size===0)return;let t=["Running runners load job hook settings only when they start. Restart them once they are idle:"];for(let[n,{ids:r,total:o}]of e){let i=r.length===o?n:`${n} ${r.join(" ")}`;t.push(` ${l.green(`hydra stop ${i} && hydra start ${i}`)}`)}b.warn(t.join(`
|
|
262
|
+
`))}}var pf="--",ff=new Set(["--help","-h"]),mf="help",hf="doctor",ba=new Set(["logs","profile list","status"]),gf={...cr,home:Zt};function wa(e){let t=yf(e);if(!t)return"write";let{command:n,flags:r,restArgs:o}=t;if(!n)return r.version||!r.interactive?"help":"write";if(n===mf)return"help";if(n===hf)return"diagnose";if(bf(Boolean(r.help),o))return"help";return ba.has(n)||ba.has(`${n} ${o[0]}`)?"read":"write"}function $a({home:e,source:t},n,r){if(n==="help"||n==="diagnose")return;let o=bi(e,r);if(!o||t!=="default"||n!=="write")return o;throw new y(`This directory holds the Hydra home ${o}, but no home was selected, so this command would act on ${e}`,`Pass ${j} <path> or set ${ae} to choose ${o} or ${e}`)}function yf(e){try{return gt([...e],gf)}catch{return}}function bf(e,t){let[n]=t;if(e&&(n===void 0||n.startsWith("-")))return!0;let r=t.indexOf(pf);return(r<0?t:t.slice(0,r)).some((o)=>ff.has(o))}class va extends lr{constructor(e,t){super(e,{bin:qt,clearOnStart:t,description:"Manage GitHub Actions runners on this machine.",exitLabel:"Exit",goodbyeMessage:"Heads down.",name:"HYDRA",promptMessage:"What do you need?",version:ri})}init(){this.globalArgs.home=Zt,this.registerCommands([new xn,new Rn,new Gn,new Fn,new Mn,new Nn,new On,new Sn,new wn,new Dn,new Un,new Ln,new Hn])}}function wf(e,t){b.warn(l.yellow(`Ignoring ${t}: Hydra keeps its state in ${e}`)),b.info(l.dim(`To manage that fleet, pass ${j} ${t} or set ${ae}=${t}`))}function $f(e){if(e instanceof y){if(b.warn(l.yellow(e.message)),e.hint)b.info(l.dim(e.hint));process.exit(e.exitCode)}b.error(l.red(e instanceof Error?e.message:String(e))),process.exit(1)}async function vf(){let e=yi(process.argv.slice(2),process.env),t=wa(e.argv),n=$a(e,t,process.cwd()),r=Es(e.home);if(n)wf(e.home,n);let o=t==="read"||t==="write"?Cn(r):void 0;if(o)throw o;await new va(r,n===void 0).run(e.argv)}vf().catch($f);
|