@r5n/hydra 0.9.3 → 0.9.4
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 +3 -1
- package/dist/cli.js +88 -94
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -89,7 +89,7 @@ Passing any of `-l`/`-w`/`-s` cleans only those targets; with none, the targets
|
|
|
89
89
|
|
|
90
90
|
- `hydra profile list` — profiles with URL, OS, and created/running counts
|
|
91
91
|
- `hydra profile default <name>` — set the default profile
|
|
92
|
-
- `hydra profile remove <name
|
|
92
|
+
- `hydra profile remove <name> [--yes]` — remove a profile; if it has runners, stops and deregisters them first. Pass `--yes` to skip confirmation in scripts.
|
|
93
93
|
|
|
94
94
|
## Configuration
|
|
95
95
|
|
|
@@ -131,6 +131,8 @@ The `url` is either a repository URL (`https://github.com/owner/repo`) or an org
|
|
|
131
131
|
|
|
132
132
|
Runner binaries are downloaded once per version into `.hydra/shared/github/<version>`. Each runner directory under `.hydra/runners/<id>` gets hardlinks for `bin`, a symlink for `externals`, and its own copies of the shell scripts, so ten runners cost roughly one copy of the runner distribution on disk. Start/stop is plain process management: a detached `bash run.sh` plus a pid file per runner.
|
|
133
133
|
|
|
134
|
+
Hydra disables the runner's automatic updater when registering it; use `hydra update` to update the shared binaries. Failed downloads are discarded, and completed registrations and removals are saved as each runner finishes, so a later failure in the batch can be retried. Failed deregistrations preserve the runner's files and record.
|
|
135
|
+
|
|
134
136
|
## License
|
|
135
137
|
|
|
136
138
|
Apache-2.0 — see [LICENSE](./LICENSE)
|
package/dist/cli.js
CHANGED
|
@@ -1,99 +1,93 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`),
|
|
5
|
-
`){if(
|
|
6
|
-
`){if(
|
|
7
|
-
`)}var
|
|
8
|
-
`),
|
|
9
|
-
`),o=n.split(`
|
|
10
|
-
`)
|
|
11
|
-
`).
|
|
12
|
-
`)
|
|
13
|
-
`)
|
|
14
|
-
`)
|
|
15
|
-
`)
|
|
16
|
-
`).
|
|
17
|
-
`)),this._prevFrame=r;return}}this.output.write(q.erase.down())}this.output.write(r),this.state==="initial"&&(this.state="active"),this._prevFrame=r}}}function ei(r,n){if(r===void 0||n.length===0)return 0;let e=n.findIndex((o)=>o.value===r);return e!==-1?e:0}function oi(r,n){return(n.label??String(n.value)).toLowerCase().includes(r.toLowerCase())}function ii(r,n){if(n)return r?n:n[0]}var ti=class extends T{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#n=0;#i="";#r;#t;#s;get cursor(){return this.#n}get userInputWithCursor(){if(!this.userInput)return xr(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let n=this.userInput.slice(0,this.cursor),e=this.userInput.slice(this.cursor,this.cursor+1),o=this.userInput.slice(this.cursor+1);return`${n}${xr("inverse",e)}${o}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(n){super(n),this.#t=n.options,this.#s=n.placeholder;let e=this.options;this.filteredOptions=[...e],this.multiple=n.multiple===!0,this.#r=typeof n.options=="function"?n.filter:n.filter??oi;let o;if(n.initialValue&&Array.isArray(n.initialValue)?this.multiple?o=n.initialValue:o=n.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(o=[this.options[0]?.value]),o)for(let i of o){let t=e.findIndex((a)=>a.value===i);t!==-1&&(this.toggleSelected(i),this.#n=t)}this.focusedValue=this.options[this.#n]?.value,this.on("key",(i,t)=>this.#e(i,t)),this.on("userInput",(i)=>this.#o(i))}_isActionKey(n,e){return n==="\t"||this.multiple&&this.isNavigating&&e.name==="space"&&n!==void 0&&n!==""}#e(n,e){let o=e.name==="up",i=e.name==="down",t=e.name==="return",a=this.userInput===""||this.userInput==="\t",s=this.#s,c=this.options,f=s!==void 0&&s!==""&&c.some((d)=>!d.disabled&&(this.#r?this.#r(s,d):!0));if(e.name==="tab"&&a&&f){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(s,!0),this.isNavigating=!1;return}o||i?(this.#n=_(this.#n,o?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#n]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):t?this.value=ii(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(e.name==="tab"||this.isNavigating&&e.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(n){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(n)?this.selectedValues=this.selectedValues.filter((e)=>e!==n):this.selectedValues=[...this.selectedValues,n]:this.selectedValues=[n])}#o(n){if(n!==this.#i){this.#i=n;let e=this.options;n&&this.#r?this.filteredOptions=e.filter((t)=>this.#r?.(n,t)):this.filteredOptions=[...e];let o=ei(this.focusedValue,this.filteredOptions);this.#n=_(o,0,this.filteredOptions);let i=this.filteredOptions[this.#n];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class En extends T{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(r){super(r,!1),this.value=!!r.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(n)=>{this.output.write(q.cursor.move(0,-1)),this.value=n,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var ai={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function Ce(r){return[...r].map((n)=>ai[n])}function si(r){let n=new Intl.DateTimeFormat(r,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),e=[],o="/";for(let i of n)i.type==="literal"?o=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&e.push({type:i.type,len:i.type==="year"?4:2});return{segments:e,separator:o}}function Fn(r){return Number.parseInt((r||"0").replace(/_/g,"0"),10)||0}function Gr(r){return{year:Fn(r.year),month:Fn(r.month),day:Fn(r.day)}}function kn(r,n){return new Date(r||2001,n||1,0).getDate()}function Re(r){let{year:n,month:e,day:o}=Gr(r);if(!n||n<0||n>9999||!e||e<1||e>12||!o||o<1)return;let i=new Date(Date.UTC(n,e-1,o));if(!(i.getUTCFullYear()!==n||i.getUTCMonth()!==e-1||i.getUTCDate()!==o))return{year:n,month:e,day:o}}function $e(r){let n=Re(r);return n?new Date(Date.UTC(n.year,n.month-1,n.day)):void 0}function ci(r,n,e,o){let i=e?{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}:null,t=o?{year:o.getUTCFullYear(),month:o.getUTCMonth()+1,day:o.getUTCDate()}:null;return r==="year"?{min:i?.year??1,max:t?.year??9999}:r==="month"?{min:i&&n.year===i.year?i.month:1,max:t&&n.year===t.year?t.month:12}:{min:i&&n.year===i.year&&n.month===i.month?i.day:1,max:t&&n.year===t.year&&n.month===t.month?t.day:kn(n.year,n.month)}}class ke extends T{#n;#i;#r;#t;#s;#e={segmentIndex:0,positionInSegment:0};#o=!0;#a=null;inlineError="";get segmentCursor(){return{...this.#e}}get segmentValues(){return{...this.#r}}get segments(){return this.#n}get separator(){return this.#i}get formattedValue(){return this.#p(this.#r)}#p(r){return this.#n.map((n)=>r[n.type]).join(this.#i)}#c(){this._setUserInput(this.#p(this.#r)),this._setValue($e(this.#r)??void 0)}constructor(r){let n=r.format?{segments:Ce(r.format),separator:r.separator??"/"}:si(r.locale),e=r.separator??n.separator,o=r.format?Ce(r.format):n.segments,i=r.initialValue??r.defaultValue,t=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},a=o.map((s)=>t[s.type]).join(e);super({...r,initialUserInput:a},!1),this.#n=o,this.#i=e,this.#r=t,this.#t=r.minDate,this.#s=r.maxDate,this.#c(),this.on("cursor",(s)=>this.#d(s)),this.on("key",(s,c)=>this.#g(s,c)),this.on("finalize",()=>this.#h(r))}#f(){let r=Math.max(0,Math.min(this.#e.segmentIndex,this.#n.length-1)),n=this.#n[r];if(n)return this.#e.positionInSegment=Math.max(0,Math.min(this.#e.positionInSegment,n.len-1)),{segment:n,index:r}}#u(r){this.inlineError="",this.#a=null;let n=this.#f();n&&(this.#e.segmentIndex=Math.max(0,Math.min(this.#n.length-1,n.index+r)),this.#e.positionInSegment=0,this.#o=!0)}#m(r){let n=this.#f();if(!n)return;let{segment:e}=n,o=this.#r[e.type],i=!o||o.replace(/_/g,"")==="",t=Number.parseInt((o||"0").replace(/_/g,"0"),10)||0,a=ci(e.type,Gr(this.#r),this.#t,this.#s),s;i?s=r===1?a.min:a.max:s=Math.max(Math.min(a.max,t+r),a.min),this.#r={...this.#r,[e.type]:s.toString().padStart(e.len,"0")},this.#o=!0,this.#a=null,this.#c()}#d(r){if(r)switch(r){case"right":return this.#u(1);case"left":return this.#u(-1);case"up":return this.#m(1);case"down":return this.#m(-1)}}#g(r,n){if(n?.name==="backspace"||n?.sequence==="\x7F"||n?.sequence==="\b"||r==="\x7F"||r==="\b"){this.inlineError="";let e=this.#f();if(!e)return;if(!this.#r[e.segment.type].replace(/_/g,"")){this.#u(-1);return}this.#r[e.segment.type]="_".repeat(e.segment.len),this.#o=!0,this.#e.positionInSegment=0,this.#c();return}if(n?.name==="tab"){this.inlineError="";let e=this.#f();if(!e)return;let o=n.shift?-1:1,i=e.index+o;i>=0&&i<this.#n.length&&(this.#e.segmentIndex=i,this.#e.positionInSegment=0,this.#o=!0);return}if(r&&/^[0-9]$/.test(r)){let e=this.#f();if(!e)return;let{segment:o}=e,i=!this.#r[o.type].replace(/_/g,"");if(this.#o&&this.#a!==null&&!i){let p=this.#a+r,h={...this.#r,[o.type]:p},l=this.#l(h,o);if(l){this.inlineError=l,this.#a=null,this.#o=!1;return}this.inlineError="",this.#r[o.type]=p,this.#a=null,this.#o=!1,this.#c(),e.index<this.#n.length-1&&(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#o=!0);return}this.#o&&!i&&(this.#r[o.type]="_".repeat(o.len),this.#e.positionInSegment=0),this.#o=!1,this.#a=null;let t=this.#r[o.type],a=t.indexOf("_"),s=a>=0?a:Math.min(this.#e.positionInSegment,o.len-1);if(s<0||s>=o.len)return;let c=t.slice(0,s)+r+t.slice(s+1),f=!1;if(s===0&&t==="__"&&(o.type==="month"||o.type==="day")){let p=Number.parseInt(r,10);c=`0${r}`,f=p<=(o.type==="month"?1:2)}if(o.type==="year"&&(c=(t.replace(/_/g,"")+r).padStart(o.len,"_")),!c.includes("_")){let p={...this.#r,[o.type]:c},h=this.#l(p,o);if(h){this.inlineError=h;return}}this.inlineError="",this.#r[o.type]=c;let d=c.includes("_")?void 0:Re(this.#r);if(d){let{year:p,month:h}=d,l=kn(p,h);this.#r={year:String(Math.max(0,Math.min(9999,p))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,h))).padStart(2,"0"),day:String(Math.max(1,Math.min(l,d.day))).padStart(2,"0")}}this.#c();let g=c.indexOf("_");f?(this.#o=!0,this.#a=r):g>=0?this.#e.positionInSegment=g:a>=0&&e.index<this.#n.length-1?(this.#e.segmentIndex=e.index+1,this.#e.positionInSegment=0,this.#o=!0):this.#e.positionInSegment=Math.min(s+1,o.len-1)}}#l(r,n){let{month:e,day:o}=Gr(r);if(n.type==="month"&&(e<0||e>12))return M.date.messages.invalidMonth;if(n.type==="day"&&(o<0||o>31))return M.date.messages.invalidDay(31,"any month")}#h(r){let{year:n,month:e,day:o}=Gr(this.#r);if(n&&e&&o){let i=kn(n,e);this.#r={...this.#r,day:String(Math.min(o,i)).padStart(2,"0")}}this.value=$e(this.#r)??r.defaultValue??void 0}}var fi=class extends T{options;cursor=0;#n;getGroupItems(n){return this.options.filter((e)=>e.group===n)}isGroupSelected(n){let e=this.getGroupItems(n),o=this.value;return o===void 0?!1:e.every((i)=>o.includes(i.value))}toggleValue(){let n=this.options[this.cursor];if(n!==void 0)if(this.value===void 0&&(this.value=[]),n.group===!0){let e=n.value,o=this.getGroupItems(e);this.isGroupSelected(e)?this.value=this.value.filter((i)=>o.findIndex((t)=>t.value===i)===-1):this.value=[...this.value,...o.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let e=this.value.includes(n.value);this.value=e?this.value.filter((o)=>o!==n.value):[...this.value,n.value]}}constructor(n){super(n,!1);let{options:e}=n;this.#n=n.selectableGroups!==!1,this.options=Object.entries(e).flatMap(([o,i])=>[{value:o,group:!0,label:o},...i.map((t)=>({...t,group:o}))]),this.value=[...n.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:o})=>o===n.cursorAt),this.#n?0:1),this.on("cursor",(o)=>{switch(o){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#n&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},ui=new Set(["up","down","left","right"]);class Le extends T{#n=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let r=this.userInput;if(this.cursor>=r.length)return`${r}\u2588`;let n=r.slice(0,this.cursor),e=r.slice(this.cursor,this.cursor+1),o=r.slice(this.cursor+1);return e===`
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
`),this.
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
${u("gray"
|
|
27
|
-
${
|
|
28
|
-
|
|
29
|
-
${
|
|
30
|
-
|
|
31
|
-
`).map((
|
|
32
|
-
`),
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
${
|
|
37
|
-
`
|
|
38
|
-
`),
|
|
39
|
-
`).length,
|
|
40
|
-
|
|
41
|
-
${f}`)}
|
|
3
|
+
var Ii=Object.create;var{getPrototypeOf:Ei,defineProperty:ir,getOwnPropertyNames:Pi}=Object;var nr=Object.prototype.hasOwnProperty;function _i(t){return this[t]}var Ai,Ti,sr=(t,e,r)=>{var i=t!=null&&typeof t==="object";if(i){var n=e?Ai??=new WeakMap:Ti??=new WeakMap,s=n.get(t);if(s)return s}r=t!=null?Ii(Ei(t)):{};let o=e||!t||!t.__esModule||!nr.call(t,"default")?ir(r,"default",{value:t,enumerable:!0}):r;if(t&&typeof t==="object"||typeof t==="function"){for(let u of Pi(t))if(!nr.call(o,u))ir(o,u,{get:_i.bind(t,u),enumerable:!0})}if(i)n.set(t,o);return o};var Di=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var xe=Di(function(no,wr){var Ce={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let r="";if(t<0)r+=`\x1B[${-t}D`;else if(t>0)r+=`\x1B[${t}C`;if(e<0)r+=`\x1B[${-e}A`;else if(e>0)r+=`\x1B[${e}B`;return r},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Ki={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},qi={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?Ce.up():"");if(t)e+=Ce.left;return e}};wr.exports={cursor:Ce,scroll:Ki,erase:qi,beep:"\x07"}});class Y extends Error{constructor(t="Operation cancelled"){super(t)}}class y extends Error{hint;exitCode;constructor(t,e,r=1){super(t);this.hint=e;this.exitCode=r}}import{styleText as zi}from"util";import{stdout as Se,stdin as Cr}from"process";import*as st from"readline";import Yi from"readline";var or=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let r=0;t.lastIndex=0;while(t.test(e))r+=1;return e.length-r}})(),ar=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,ur=(t)=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var ki=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Li=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,lr=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Fi=/\t{1,1000}/y,cr=/[\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,Oi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ni=/\p{M}+/gu,Mi={limit:1/0,ellipsis:""},pr=(t,e={},r={})=>{let i=e.limit??1/0,n=e.ellipsis??"",s=e?.ellipsisWidth??(n?pr(n,Mi,r).width:0),o=0,u=r.controlWidth??0,a=r.tabWidth??8,l=r.emojiWidth??2,f=2,h=r.regularWidth??1,d=r.wideWidth??2,g=[[Oi,h],[ki,0],[Li,u],[Fi,a],[cr,l],[lr,d]],m=0,v=0,I=t.length,A=0,x=!1,N=I,T=Math.max(0,i-s),R=0,F=0,D=0,_=0;t:while(!0){if(F>R||v>=I&&v>m){let L=t.slice(R,F)||t.slice(m,v);A=0;for(let X of L.replaceAll(Ni,"")){let H=X.codePointAt(0)||0;if(ar(H))_=2;else if(ur(H))_=d;else _=h;if(D+_>T)N=Math.min(N,Math.max(R,m)+A);if(D+_>i){x=!0;break t}A+=X.length,D+=_}R=F=0}if(v>=I)break t;for(let L=0,X=g.length;L<X;L++){let[H,Lt]=g[L];if(H.lastIndex=v,H.test(t)){if(A=H===lr?or(t.slice(v,H.lastIndex)):H===cr?1:H.lastIndex-v,_=A*Lt,D+_>T)N=Math.min(N,v+Math.floor((T-D)/Lt));if(D+_>i){x=!0;break t}D+=_,R=m,F=v,v=m=H.lastIndex;continue t}}v+=1}return{width:x?T:D,index:x?N:I,truncated:x,ellipsed:x&&i>=s}},dr=pr;var Ui={limit:1/0,ellipsis:"",ellipsisWidth:0},Vi=(t,e={})=>dr(t,Ui,e).width,B=Vi;var Ot="\x1B",yr="\x9B",Gi=39,we="\x07",$r="[",ji="]",vr="m",be=`${ji}8;;`,mr=new RegExp(`(?:\\${$r}(?<code>\\d+)m|\\${be}(?<uri>.*)${we})`,"y"),hr=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},fr=(t)=>`${Ot}${$r}${t}${vr}`,gr=(t)=>`${Ot}${be}${t}${we}`,ve=(t,e,r)=>{let i=e[Symbol.iterator](),n=!1,s=!1,o=t.at(-1),u=o===void 0?0:B(o),a=i.next(),l=i.next(),f=0;while(!a.done){let h=a.value,d=B(h);if(u+d<=r)t[t.length-1]+=h;else t.push(h),u=0;if(h===Ot||h===yr)n=!0,s=e.startsWith(be,f+1);if(n){if(s){if(h===we)n=!1,s=!1}else if(h===vr)n=!1}else if(u+=d,u===r&&!l.done)t.push(""),u=0;a=l,l=i.next(),f+=h.length}if(o=t.at(-1),!u&&o!==void 0&&o.length&&t.length>1)t[t.length-2]+=t.pop()},Hi=(t)=>{let e=t.split(" "),r=e.length;while(r){if(B(e[r-1]))break;r--}if(r===e.length)return t;return e.slice(0,r).join(" ")+e.slice(r).join("")},Bi=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let i="",n,s,o=t.split(" "),u=[""],a=0;for(let h=0;h<o.length;h++){let d=o[h];if(r.trim!==!1){let m=u.at(-1)??"",v=m.trimStart();if(m.length!==v.length)u[u.length-1]=v,a=B(v)}if(h!==0){if(a>=e&&(r.wordWrap===!1||r.trim===!1))u.push(""),a=0;if(a||r.trim===!1)u[u.length-1]+=" ",a++}let g=B(d);if(r.hard&&g>e){let m=e-a,v=1+Math.floor((g-m-1)/e);if(Math.floor((g-1)/e)<v)u.push("");ve(u,d,e),a=B(u.at(-1)??"");continue}if(a+g>e&&a&&g){if(r.wordWrap===!1&&a<e){ve(u,d,e),a=B(u.at(-1)??"");continue}u.push(""),a=0}if(a+g>e&&r.wordWrap===!1){ve(u,d,e),a=B(u.at(-1)??"");continue}u[u.length-1]+=d,a+=g}if(r.trim!==!1)u=u.map((h)=>Hi(h));let l=u.join(`
|
|
4
|
+
`),f=!1;for(let h=0;h<l.length;h++){let d=l[h];if(i+=d,!f){if(f=d>="\uD800"&&d<="\uDBFF",f)continue}else f=!1;if(d===Ot||d===yr){mr.lastIndex=h+1;let m=mr.exec(l)?.groups;if(m?.code!==void 0){let v=Number.parseFloat(m.code);n=v===Gi?void 0:v}else if(m?.uri!==void 0)s=m.uri.length===0?void 0:m.uri}if(l[h+1]===`
|
|
5
|
+
`){if(s)i+=gr("");let g=n?hr(n):void 0;if(n&&g)i+=fr(g)}else if(d===`
|
|
6
|
+
`){if(n&&hr(n))i+=fr(n);if(s)i+=gr(s)}}return i},Wi=/\r?\n/;function Z(t,e,r){return String(t).normalize().split(Wi).map((i)=>Bi(i,e,r)).join(`
|
|
7
|
+
`)}var G=sr(xe(),1);import{ReadStream as br}from"tty";function lt(t,e,r){if(!r.some((o)=>!o.disabled))return t;let i=t+e,n=Math.max(r.length-1,0),s=i<0?n:i>n?0:i;return r[s]?.disabled?lt(s,e<0?-1:1,r):s}var Ji=["up","down","left","right","space","enter","cancel"],Xi=["January","February","March","April","May","June","July","August","September","October","November","December"],V={actions:new Set(Ji),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:[...Xi],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function Ie(t,e){if(typeof t=="string")return V.aliases.get(t)===e;for(let r of t)if(r!==void 0&&Ie(r,e))return!0;return!1}function Zi(t,e){if(t===e)return;let r=t.split(`
|
|
8
|
+
`),i=e.split(`
|
|
9
|
+
`),n=Math.max(r.length,i.length),s=[];for(let o=0;o<n;o++)r[o]!==i[o]&&s.push(o);return{lines:s,numLinesBefore:r.length,numLinesAfter:i.length,numLines:n}}var Qi=globalThis.process.platform.startsWith("win"),Re=Symbol("clack:cancel");function xt(t){return t===Re}function Nt(t,e){let r=t;r.isTTY&&r.setRawMode(e)}function xr({input:t=Cr,output:e=Se,overwrite:r=!0,hideCursor:i=!0}={}){let n=st.createInterface({input:t,output:e,prompt:"",tabSize:1});st.emitKeypressEvents(t,n),t instanceof br&&t.isTTY&&t.setRawMode(!0);let s=(o,{name:u,sequence:a})=>{let l=String(o);if(Ie([l,u,a],"cancel")){i&&e.write(G.cursor.show),process.exit(0);return}if(!r)return;st.moveCursor(e,u==="return"?0:-1,u==="return"?-1:0,()=>{st.clearLine(e,1,()=>{t.once("keypress",s)})})};return i&&e.write(G.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),i&&e.write(G.cursor.show),t instanceof br&&t.isTTY&&!Qi&&t.setRawMode(!1),n.terminal=!1,n.close()}}var Rt=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,Ee=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function ot(t,e,r,i=r,n=r,s){let o=Rt(t??Se);return Z(e,o-r.length,{hard:!0,trim:!1}).split(`
|
|
10
|
+
`).map((u,a,l)=>{let f=s?s(u,a):u;return a===0?`${i}${f}`:a===l.length-1?`${n}${f}`:`${r}${f}`}).join(`
|
|
11
|
+
`)}function Rr(t,e){if("~standard"in t){let r=t["~standard"].validate(e);if(r instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return r.issues?.at(0)?.message}return t(e)}class St{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,e=!0){let{input:r=Cr,output:i=Se,render:n,signal:s,...o}=t;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=n.bind(this),this._track=e,this._abortSignal=s,this.input=r,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(t,e){let r=this._subscribers.get(t)??[];r.push(e),this._subscribers.set(t,r)}on(t,e){this.setSubscriber(t,{cb:e})}once(t,e){this.setSubscriber(t,{cb:e,once:!0})}emit(t,...e){let r=this._subscribers.get(t)??[],i=[];for(let n of r)n.cb(...e),n.once&&i.push(()=>r.splice(r.indexOf(n),1));for(let n of i)n()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Re);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Yi.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),Nt(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(G.cursor.show),this.output.off("resize",this.render),Nt(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(G.cursor.show),this.output.off("resize",this.render),Nt(this.input,!1),t(Re)})})}_isActionKey(t,e){return t==="\t"}_shouldSubmit(t,e){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,e){this.userInput=t??"",this.emit("userInput",this.userInput),e&&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(t,e){if(this._track&&e.name!=="return"&&(e.name&&this._isActionKey(t,e)&&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"),e?.name&&(!this._track&&V.aliases.has(e.name)&&this.emit("cursor",V.aliases.get(e.name)),V.actions.has(e.name)&&this.emit("cursor",e.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,e),e?.name==="return"&&this._shouldSubmit(t,e)){if(this.opts.validate){let r=Rr(this.opts.validate,this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Ie([t,e?.name,e?.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
|
+
`),Nt(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Z(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
13
|
+
`).length-1;this.output.write(G.cursor.move(-999,t*-1))}render(){let t=Z(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(G.cursor.hide);else{let e=Zi(this._prevFrame,t),r=Ee(this.output);if(this.restoreCursor(),e){let i=Math.max(0,e.numLinesAfter-r),n=Math.max(0,e.numLinesBefore-r),s=e.lines.find((o)=>o>=i);if(s===void 0){this._prevFrame=t;return}if(e.lines.length===1){this.output.write(G.cursor.move(0,s-n)),this.output.write(G.erase.lines(1));let o=t.split(`
|
|
14
|
+
`);this.output.write(o[s]),this._prevFrame=t,this.output.write(G.cursor.move(0,o.length-s-1));return}else if(e.lines.length>1){if(i<n)s=i;else{let u=s-n;u>0&&this.output.write(G.cursor.move(0,u))}this.output.write(G.erase.down());let o=t.split(`
|
|
15
|
+
`).slice(s);this.output.write(o.join(`
|
|
16
|
+
`)),this._prevFrame=t;return}}this.output.write(G.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}class Pe extends St{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(e)=>{this.output.write(G.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class _e extends St{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,e=this.value!==void 0&&this.value.length===t.length;this.value=e?[]:t.map((r)=>r.value)}toggleInvert(){let t=this.value;if(!t)return;let e=this._enabledOptions.filter((r)=>!t.includes(r.value));this.value=e.map((r)=>r.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((e)=>e!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let e=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),0);this.cursor=this.options[e]?.disabled?lt(e,1,this.options):e,this.on("key",(r,i)=>{i.name==="a"&&this.toggleAll(),i.name==="i"&&this.toggleInvert()}),this.on("cursor",(r)=>{switch(r){case"left":case"up":this.cursor=lt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=lt(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Sr=class extends St{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let r=this.options.findIndex(({value:n})=>n===e.initialValue),i=r===-1?0:r;this.cursor=this.options[i]?.disabled?lt(i,1,this.options):i,this.changeValue(),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=lt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=lt(this.cursor,1,this.options);break}this.changeValue()})}};class Ae extends St{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let e=t.slice(0,this.cursor),r=t.slice(this.cursor,this.cursor+1),i=t.slice(this.cursor+1);return`${e}${zi("inverse",r)}${i}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as c,stripVTControlCharacters as bo}from"util";import q from"process";var Et=sr(xe(),1);function tn(){if(q.platform!=="win32")return q.env.TERM!=="linux";return Boolean(q.env.CI)||Boolean(q.env.WT_SESSION)||Boolean(q.env.TERMINUS_SUBLIME)||q.env.ConEmuTask==="{cmd::Cmder}"||q.env.TERM_PROGRAM==="Terminus-Sublime"||q.env.TERM_PROGRAM==="vscode"||q.env.TERM==="xterm-256color"||q.env.TERM==="alacritty"||q.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Te=tn(),en=()=>process.env.CI==="true";var E=(t,e)=>Te?t:e,rn=E("\u25C6","*"),Ar=E("\u25A0","x"),Tr=E("\u25B2","x"),Vt=E("\u25C7","o"),nn=E("\u250C","T"),C=E("\u2502","|"),at=E("\u2514","\u2014"),So=E("\u2510","T"),Io=E("\u2518","\u2014"),De=E("\u25CF",">"),Ut=E("\u25CB"," "),sn=E("\u25FB","[\u2022]"),Ir=E("\u25FC","[+]"),Er=E("\u25FB","[ ]"),Eo=E("\u25AA","\u2022"),Pr=E("\u2500","-"),on=E("\u256E","+"),an=E("\u251C","+"),un=E("\u256F","+"),ln=E("\u2570","+"),Po=E("\u256D","+"),cn=E("\u25CF","\u2022"),pn=E("\u25C6","*"),dn=E("\u25B2","!"),mn=E("\u25A0","x"),Gt=(t)=>{switch(t){case"initial":case"active":return c("cyan",rn);case"cancel":return c("red",Ar);case"error":return c("yellow",Tr);case"submit":return c("green",Vt)}},Dr=(t)=>{switch(t){case"initial":case"active":return c("cyan",C);case"cancel":return c("red",C);case"error":return c("yellow",C);case"submit":return c("green",C)}};function kr(t,e){let r=[`${e?`${c("cyan",C)} `:""}${t.join(" \u2022 ")}`];return e&&r.push(c("cyan",at)),r}var _r=(t,e,r,i,n,s=!1)=>{let o=e,u=0;if(s)for(let a=i-1;a>=r;a--){let l=t[a];if(l&&(o-=l.length),u++,o<=n)break}else for(let a=r;a<i;a++){let l=t[a];if(l&&(o-=l.length),u++,o<=n)break}return{lineCount:o,removals:u}},ke=({cursor:t,options:e,style:r,output:i=process.stdout,maxItems:n=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let u=Rt(i)-s,a=Ee(i),l=c("dim","..."),f=Math.max(a-o,0),h=Math.max(Math.min(n,f),5),d=0;t>=h-3&&(d=Math.max(Math.min(t-h+3,e.length-h),0));let g=h<e.length&&d>0,m=h<e.length&&d+h<e.length,v=Math.min(d+h,e.length),I=[],A=0;g&&A++,m&&A++;let x=d+(g?1:0),N=v-(m?1:0);for(let R=x;R<N;R++){let F=e[R],D=F?r(F,R===t):"",_=Z(D,u,{hard:!0,trim:!1}).split(`
|
|
17
|
+
`);I.push(_),A+=_.length}if(A>f){let R=0,F=0,D=A,_=t-x,L=f,X=()=>_r(I,D,0,_,L),H=()=>_r(I,D,_+1,I.length,L,!0);g?({lineCount:D,removals:R}=X(),D>L&&(m||(L-=1),{lineCount:D,removals:F}=H())):(m||(L-=1),{lineCount:D,removals:F}=H(),D>L&&(L-=1,{lineCount:D,removals:R}=X())),R>0&&(g=!0,I.splice(0,R)),F>0&&(m=!0,I.splice(I.length-F,F))}let T=[];g&&T.push(l);for(let R of I)for(let F of R)T.push(F);return m&&T.push(l),T};var Lr=(t)=>{let e=t.active??"Yes",r=t.inactive??"No";return new Pe({active:e,inactive:r,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let i=t.withGuide??V.withGuide,n=`${Gt(this.state)} `,s=i?`${c("gray",C)} `:"",o=ot(t.output,t.message,s,n),u=`${i?`${c("gray",C)}
|
|
18
|
+
`:""}${o}
|
|
19
|
+
`,a=this.value?e:r;switch(this.state){case"submit":{let l=i?`${c("gray",C)} `:"";return`${u}${l}${c("dim",a)}`}case"cancel":{let l=i?`${c("gray",C)} `:"";return`${u}${l}${c(["strikethrough","dim"],a)}${i?`
|
|
20
|
+
${c("gray",C)}`:""}`}default:{let l=i?`${c("cyan",C)} `:"",f=i?c("cyan",at):"";return`${u}${l}${this.value?`${c("green",De)} ${e}`:`${c("dim",Ut)} ${c("dim",e)}`}${t.vertical?i?`
|
|
21
|
+
${c("cyan",C)} `:`
|
|
22
|
+
`:` ${c("dim","/")} `}${this.value?`${c("dim",Ut)} ${c("dim",r)}`:`${c("green",De)} ${r}`}
|
|
23
|
+
${f}
|
|
24
|
+
`}}}}).prompt()};var jt=async(t,e)=>{let r={},i=Object.keys(t);for(let n of i){let s=t[n],o=await s({results:r})?.catch((u)=>{throw u});if(typeof e?.onCancel=="function"&&xt(o)){r[n]="canceled",e.onCancel({results:r});continue}r[n]=o}return r},hn=[`${c("dim","\u2191/\u2193")} to navigate`,`${c("dim","Space:")} select`,`${c("dim","Enter:")} confirm`],It=(t,e)=>t.split(`
|
|
25
|
+
`).map((r)=>e(r)).join(`
|
|
26
|
+
`),Fr=(t)=>{let e=(n,s)=>{let o=n.label??String(n.value);return s==="disabled"?`${c("gray",Er)} ${It(o,(u)=>c(["strikethrough","gray"],u))}${n.hint?` ${c("dim",`(${n.hint??"disabled"})`)}`:""}`:s==="active"?`${c("cyan",sn)} ${o}${n.hint?` ${c("dim",`(${n.hint})`)}`:""}`:s==="selected"?`${c("green",Ir)} ${It(o,(u)=>c("dim",u))}${n.hint?` ${c("dim",`(${n.hint})`)}`:""}`:s==="cancelled"?`${It(o,(u)=>c(["strikethrough","dim"],u))}`:s==="active-selected"?`${c("green",Ir)} ${o}${n.hint?` ${c("dim",`(${n.hint})`)}`:""}`:s==="submitted"?`${It(o,(u)=>c("dim",u))}`:`${c("dim",Er)} ${It(o,(u)=>c("dim",u))}`},r=t.required??!0,i=t.showInstructions??!0;return new _e({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:r,cursorAt:t.cursorAt,validate(n){if(r&&(n===void 0||n.length===0))return`Please select at least one option.
|
|
27
|
+
${c("reset",c("dim",`Press ${c(["gray","bgWhite","inverse"]," space ")} to select, ${c("gray",c("bgWhite",c("inverse"," enter ")))} to submit`))}`},render(){let n=t.withGuide??V.withGuide,s=ot(t.output,t.message,n?`${Dr(this.state)} `:"",`${Gt(this.state)} `),o=`${n?`${c("gray",C)}
|
|
28
|
+
`:""}${s}
|
|
29
|
+
`,u=this.value??[],a=(l,f)=>{if(l.disabled)return e(l,"disabled");let h=u.includes(l.value);return f&&h?e(l,"active-selected"):h?e(l,"selected"):e(l,f?"active":"inactive")};switch(this.state){case"submit":{let l=this.options.filter(({value:h})=>u.includes(h)).map((h)=>e(h,"submitted")).join(c("dim",", "))||c("dim","none"),f=ot(t.output,l,n?`${c("gray",C)} `:"");return`${o}${f}`}case"cancel":{let l=this.options.filter(({value:h})=>u.includes(h)).map((h)=>e(h,"cancelled")).join(c("dim",", "));if(l.trim()==="")return`${o}${c("gray",C)}`;let f=ot(t.output,l,n?`${c("gray",C)} `:"");return`${o}${f}${n?`
|
|
30
|
+
${c("gray",C)}`:""}`}case"error":{let l=n?`${c("yellow",C)} `:"",f=this.error.split(`
|
|
31
|
+
`).map((g,m)=>m===0?`${n?`${c("yellow",at)} `:""}${c("yellow",g)}`:` ${g}`).join(`
|
|
32
|
+
`),h=o.split(`
|
|
33
|
+
`).length,d=f.split(`
|
|
34
|
+
`).length+1;return`${o}${l}${ke({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:l.length,rowPadding:h+d,style:a}).join(`
|
|
35
|
+
${l}`)}
|
|
36
|
+
${f}
|
|
37
|
+
`}default:{let l=n?`${c("cyan",C)} `:"",f=o.split(`
|
|
38
|
+
`).length,h=i?kr(hn,n):n?[c("cyan",at)]:[],d=h.join(`
|
|
39
|
+
`),g=h.length+1;return`${o}${l}${ke({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:l.length,rowPadding:f+g,style:a}).join(`
|
|
40
|
+
${l}`)}
|
|
42
41
|
${d}
|
|
43
|
-
`}
|
|
44
|
-
`).length
|
|
45
|
-
`),h=g.length+1;return`${a}${f}${jn({output:r.output,options:this.options,cursor:this.cursor,maxItems:r.maxItems,columnPadding:f.length,rowPadding:d+h,style:c}).join(`
|
|
46
|
-
${f}`)}
|
|
47
|
-
${p}
|
|
48
|
-
`}}}}).prompt()};var v={message:(r=[],{symbol:n=u("gray",$),secondarySymbol:e=u("gray",$),output:o=process.stdout,spacing:i=1,withGuide:t}={})=>{let a=[],s=t??M.withGuide,c=s?e:"",f=s?`${n} `:"",d=s?`${e} `:"";for(let p=0;p<i;p++)a.push(c);let g=Array.isArray(r)?r:r.split(`
|
|
49
|
-
`);if(g.length>0){let[p,...h]=g;p.length>0?a.push(`${f}${p}`):a.push(s?n:"");for(let l of h)l.length>0?a.push(`${d}${l}`):a.push(s?e:"")}o.write(`${a.join(`
|
|
42
|
+
`}}}}).prompt()};var w={message:(t=[],{symbol:e=c("gray",C),secondarySymbol:r=c("gray",C),output:i=process.stdout,spacing:n=1,withGuide:s}={})=>{let o=[],u=s??V.withGuide,a=u?r:"",l=u?`${e} `:"",f=u?`${r} `:"";for(let d=0;d<n;d++)o.push(a);let h=Array.isArray(t)?t:t.split(`
|
|
43
|
+
`);if(h.length>0){let[d,...g]=h;d.length>0?o.push(`${l}${d}`):o.push(u?e:"");for(let m of g)m.length>0?o.push(`${f}${m}`):o.push(u?r:"")}i.write(`${o.join(`
|
|
50
44
|
`)}
|
|
51
|
-
`)},info:(
|
|
52
|
-
`)},
|
|
53
|
-
${
|
|
45
|
+
`)},info:(t,e)=>{w.message(t,{...e,symbol:c("blue",cn)})},success:(t,e)=>{w.message(t,{...e,symbol:c("green",pn)})},step:(t,e)=>{w.message(t,{...e,symbol:c("green",Vt)})},warn:(t,e)=>{w.message(t,{...e,symbol:c("yellow",dn)})},warning:(t,e)=>{w.warn(t,e)},error:(t,e)=>{w.message(t,{...e,symbol:c("red",mn)})}};var Ht=(t="",e)=>{let r=e?.output??process.stdout,i=e?.withGuide??V.withGuide?`${c("gray",nn)} `:"";r.write(`${i}${t}
|
|
46
|
+
`)},Bt=(t="",e)=>{let r=e?.output??process.stdout,i=e?.withGuide??V.withGuide?`${c("gray",C)}
|
|
47
|
+
${c("gray",at)} `:"";r.write(`${i}${t}
|
|
54
48
|
|
|
55
|
-
`)};var
|
|
56
|
-
`),
|
|
57
|
-
`).map(
|
|
58
|
-
`),
|
|
59
|
-
`:"",
|
|
60
|
-
${
|
|
61
|
-
${
|
|
62
|
-
`)};var
|
|
63
|
-
`);let
|
|
64
|
-
`);
|
|
65
|
-
`);let K=0,
|
|
66
|
-
`):
|
|
67
|
-
`)),
|
|
68
|
-
`)?
|
|
69
|
-
`).map((
|
|
70
|
-
`):
|
|
71
|
-
`:""}${
|
|
72
|
-
`;switch(this.state){case"submit":{let
|
|
73
|
-
${
|
|
74
|
-
`).length,
|
|
75
|
-
`),
|
|
76
|
-
${
|
|
77
|
-
${
|
|
78
|
-
`}}}}).prompt()};var
|
|
79
|
-
`:""}${
|
|
80
|
-
`,
|
|
81
|
-
${
|
|
82
|
-
${
|
|
83
|
-
`}case"submit":{let
|
|
84
|
-
${
|
|
85
|
-
${
|
|
86
|
-
`}}}}).prompt();var
|
|
87
|
-
`).trimEnd()}command(
|
|
88
|
-
`).trimEnd()}formatPositionalUsage(
|
|
89
|
-
Run "${
|
|
90
|
-
Run "${this.commandPath} --help" for usage.`),process.exit(1);let
|
|
91
|
-
`)?
|
|
92
|
-
`).slice(-
|
|
93
|
-
`)}function mr(r){let n=r,e=0;while(n>=to&&e<ao.length-1)n/=to,e++;return`${e===0?String(n):n.toFixed(nt)} ${ao[e]??"B"}`}var uo="actions/runner",st={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},po=["bin"],mo=["externals"];class on{profile;sharedPath=null;constructor(r){this.profile=r}async download(){let r=st[this.profile.os],n=await this.getLatestVersion(),e=D(ur,"github",n);if(Er(e))return this.sharedPath=e,{path:e,version:n};await On(e,{recursive:!0});let o=`actions-runner-${r}-${n}.tar.gz`,i=D(e,o),t=`https://github.com/${uo}/releases/download/v${n}/${o}`;return await Bun.$`curl -sL -o ${i} ${t}`,await Bun.$`tar xzf ${i} -C ${e}`,await fo(i),this.sharedPath=e,{path:e,version:n}}async create(r){let n=await this.ensureDownloaded(),e=[];for(let o of r){let i=D(this.profile.directory,o);await this.setupRunnerDir(n,i),await this.registerRunner(i,o),e.push({directory:i,id:o,name:o,status:"registered"})}return e}async remove(r){for(let n of r){let e=D(this.profile.directory,n);if(!Er(D(e,".runner")))continue;let o=await this.fetchRemovalToken(e);await Bun.$`bash ./config.sh remove --token ${o}`.cwd(e).quiet().nothrow()}}async start(r){for(let n of r){let e=D(this.profile.directory,n),o=await this.readPidFile(e);if(o&&this.isProcessRunning(o))continue;let i=Bun.spawn(["bash","./run.sh"],{cwd:en(e),stderr:"pipe",stdout:"pipe"});i.unref(),await this.writePidFile(e,i.pid)}}async stop(r){for(let n of r){let e=D(this.profile.directory,n);if(!await this.readPidFile(e))continue;let i=en(e);await Bun.$`pkill -f ${i}`.quiet().nothrow(),await this.removePidFile(e)}}async list(){let r=this.profile.directory;if(!Er(r))return[];let n=await co(r,{withFileTypes:!0}),e=[];for(let o of n){if(!o.isDirectory())continue;let i=D(r,o.name);e.push(await this.getRunnerStatus(i,o.name))}return e}async currentVersion(r){let n=D(this.profile.directory,r);return this.detectVersion(n)}async logFiles(r){return Ir(D(this.profile.directory,r,Dr))}async update(r){let n=await this.ensureDownloaded();for(let e of r){let o=D(this.profile.directory,e);await this.removeRunnerBinaries(o),await this.setupRunnerDir(n,o)}}async getRunnerStatus(r,n){let e=await this.readRunnerName(r),o=await this.readPidFile(r),i=o!==null&&this.isProcessRunning(o),t="unknown";if(i)t="running";else if(Er(D(r,".runner")))t="registered";return{directory:r,id:n,name:e,pid:i?o:void 0,status:t}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:r}=await this.download();return r}async setupRunnerDir(r,n){await On(n,{recursive:!0});for(let e of po)await this.hardLinkDir(D(r,e),D(n,e));for(let e of mo){let o=en(r,e),i=D(n,e);if(!Er(i))await tt(o,i)}for(let e of["*.sh","*.sh.template"]){let o=await Array.fromAsync(new Bun.Glob(e).scan(r));for(let i of o)await et(D(r,i),D(n,i))}}async registerRunner(r,n){let e=await this.fetchRegistrationToken(),o=["--url",this.profile.url,"--token",e,"--name",n,"--unattended"];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(r).quiet()}async fetchRegistrationToken(){return this.fetchRunnerToken(pr(this.profile.url),"registration-token")}async fetchRemovalToken(r){let n=await Zn(D(r,".runner"),"utf-8"),o=JSON.parse(this.stripBom(n)).gitHubUrl;if(!o)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(pr(o),"remove-token")}async fetchRunnerToken(r,n){let e=r.kind==="repo"?`repos/${r.owner}/${r.repo}/actions/runners/${n}`:`orgs/${r.org}/actions/runners/${n}`,o=r.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope",i=await Bun.$`gh api ${e} --method POST --jq .token`.quiet().nothrow();if(i.exitCode!==0){let a=i.stderr.toString().trim();throw Error(`gh api ${e} failed for ${rn(r)} (${o})${a?`: ${a}`:""}`)}let t=i.stdout.toString().trim();if(!t)throw Error(`Failed to fetch ${n} for ${rn(r)}`);return t}async getLatestVersion(){return(await Bun.$`gh api repos/${uo}/releases/latest --jq .tag_name`.quiet()).stdout.toString().trim().replace(/^v/,"")}pidFilePath(r){return en(r,".pid")}async writePidFile(r,n){await at(this.pidFilePath(r),String(n))}async readPidFile(r){try{let n=await Zn(this.pidFilePath(r),"utf-8");return Number.parseInt(n.trim(),10)}catch{return null}}async removePidFile(r){try{await fo(this.pidFilePath(r))}catch{}}async readRunnerName(r){try{let n=await Zn(D(r,".runner"),"utf-8");return JSON.parse(this.stripBom(n)).agentName??"unknown"}catch{return"unknown"}}async hardLinkDir(r,n){await On(n,{recursive:!0});let e=await co(r,{withFileTypes:!0});for(let o of e){let i=D(r,o.name),t=D(n,o.name);if(o.isDirectory())await this.hardLinkDir(i,t);else await ot(i,t)}}async detectVersion(r){try{return(await it(D(r,"externals"))).match(/github\/([^/]+)/)?.[1]??null}catch{return null}}async removeRunnerBinaries(r){for(let n of po)await Qn(D(r,n),{force:!0,recursive:!0});for(let n of mo)await Qn(D(r,n),{force:!0});for(let n of["*.sh","*.sh.template"]){let e=await Array.fromAsync(new Bun.Glob(n).scan(r));for(let o of e)await Qn(D(r,o),{force:!0})}}stripBom(r){return r.replace(/^\uFEFF/,"")}isProcessRunning(r){try{return process.kill(r,0),!0}catch{return!1}}}import{existsSync as Sn}from"fs";import{readdir as Vn,readFile as ct,readlink as ft,rm as Bn,stat as ut}from"fs/promises";import{join as ar}from"path";var lo="_work",pt="externals",mt=".pid",lt="github",dt=/github\/([^/]+)/,gt=["runner","worker"],ht=24,go=3600000,Xn=10;function tn(r){return{auto:r?.auto??ro,intervalHours:r?.intervalHours??no,lastRun:r?.lastRun,olderThanDays:r?.olderThanDays??Tr,targets:r?.targets??eo}}function ho(r,n){return r-n*ht*go}function _n(r,n){if(!r.lastRun)return!0;let e=Date.parse(r.lastRun);if(Number.isNaN(e))return!0;return n-e>=r.intervalHours*go}function bo(r,n){let e=nn(r),o=new Set;for(let i of gt){let t=e.find((a)=>a.type===i);if(t)o.add(t.path)}return e.filter((i)=>!o.has(i.path)&&i.mtime.getTime()<n)}function wo(r){return[...r].sort($t)[0]??null}function vo(r,n){let e=wo(r),o=new Set(n);return r.filter((i)=>i!==e&&!o.has(i))}function Co(r){return r.match(dt)?.[1]??null}function an(r){return Object.values(r).reduce((n,e)=>n+e.freedBytes,0)}async function $o(r){try{let n=await ct(ar(r,mt),"utf-8"),e=Number.parseInt(n.trim(),Xn);if(Number.isNaN(e))return!1;return process.kill(e,0),!0}catch{return!1}}async function sn(r){if(!Sn(r))return 0;let n=await Vn(r,{withFileTypes:!0}),e=0;for(let o of n){if(o.isSymbolicLink())continue;let i=ar(r,o.name);if(o.isDirectory()){e+=await sn(i);continue}if(o.isFile()){let t=await ut(i);e+=t.size}}return e}async function cn(r){let n=ho(r.now,r.olderThanDays),e={};for(let o of r.targets)switch(o){case"logs":e.logs=await bt(r.entries,n,r.dryRun);break;case"work":e.work=await wt(r.entries,r.dryRun);break;case"shared":e.shared=await vt(r.entries,r.dryRun,r.sharedDir);break}return e}async function bt(r,n,e){let o={freedBytes:0,removed:0,skipped:[]};for(let i of r){let t=await Ir(ar(i.directory,Dr));for(let a of bo(t,n)){if(!e)await Bn(a.path,{force:!0});o.removed++,o.freedBytes+=a.size}}return o}async function wt(r,n){let e={freedBytes:0,removed:0,skipped:[]};for(let o of r){if(await $o(o.directory)){e.skipped.push(o.id);continue}let i=ar(o.directory,lo);if(!Sn(i))continue;let t=await Vn(i);if(t.length===0)continue;if(e.freedBytes+=await sn(i),e.removed+=t.length,n)continue;for(let a of t)await Bn(ar(i,a),{force:!0,recursive:!0})}return e}async function vt(r,n,e){let o={freedBytes:0,removed:0,skipped:[]},i=e??ar(ur,lt);if(!Sn(i))return o;let a=(await Vn(i,{withFileTypes:!0})).filter((c)=>c.isDirectory()).map((c)=>c.name),s=await Ct(r);for(let c of vo(a,s)){let f=ar(i,c);if(o.freedBytes+=await sn(f),o.removed++,!n)await Bn(f,{force:!0,recursive:!0})}return o}async function Ct(r){let n=[];for(let e of r)try{let o=await ft(ar(e.directory,pt)),i=Co(o);if(i)n.push(i)}catch{}return n}function $t(r,n){let e=r.split(".").map((t)=>Number.parseInt(t,Xn)),o=n.split(".").map((t)=>Number.parseInt(t,Xn)),i=Math.max(e.length,o.length);for(let t=0;t<i;t++){let a=e[t]??0,s=o[t]??0,c=Number.isNaN(a)?0:a,f=Number.isNaN(s)?0:s;if(c!==f)return f-c}return 0}function x(r){switch(r.provider){case"github":return new on(r);default:throw Error(`Runner provider "${r.provider}" is not yet implemented`)}}var yo=0,yt={logs:"file(s)",shared:"version(s)",work:"item(s)"},Pt=tr({days:{alias:"d",default:yo,description:"Override log retention",displayDefault:`config or ${Tr} 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 fn extends k{name="cleanup";description="Remove logs, workspaces, and old runner versions";args=Pt;async execute(r){let n=r.config.get("profiles");if(Object.keys(n).length===0)throw new w("No profiles configured","Run hydra init to set up a profile");let e=tn(r.config.get("cleanup")),o=this.explicitTargets(r),i=o.length>0?o:e.targets,t=r.args.days>yo?r.args.days:e.olderThanDays;if(i.includes("work")&&!r.args.dryRun&&!r.args.yes){if(!await sr({message:"Delete _work contents (checkouts and caches) of stopped runners?"}))i=i.filter((c)=>c!=="work")}let a=await cn({dryRun:r.args.dryRun,entries:r.config.get("runners")??[],now:Date.now(),olderThanDays:t,targets:i});if(this.printReport(a,r.args.dryRun),r.args.dryRun)return;r.config.set("cleanup",{...r.config.get("cleanup"),lastRun:new Date().toISOString()})}explicitTargets(r){let n=[];if(r.args.logs)n.push("logs");if(r.args.work)n.push("work");if(r.args.shared)n.push("shared");return n}printReport(r,n){let e=[];for(let[t,a]of Object.entries(r)){if(!a)continue;let s=yt[t],c=mr(a.freedBytes),f=n?`would remove ${a.removed} ${s}, ${c}`:`removed ${a.removed} ${s}, freed ${c}`;if(e.push(`${m.bold(t)}: ${a.removed>0?f:m.dim("nothing to do")}`),a.skipped.length>0)e.push(m.dim(` skipped running runner(s): ${a.skipped.join(", ")}`))}if(e.length===0){v.info(m.dim("Nothing to clean."));return}let o=an(r),i=n?"Would free":"Freed";e.push(m.dim(`${i} ${mr(o)} total`)),v.info(e.join(`
|
|
94
|
-
`))}}async function
|
|
95
|
-
`),
|
|
96
|
-
`))}async printTail(
|
|
97
|
-
`)),console.log(
|
|
98
|
-
`),
|
|
99
|
-
`))}formatRunners(
|
|
49
|
+
`)};var fn=(t)=>t,gn=(t,e,r)=>{let i={hard:!0,trim:!1},n=Z(t,e,i).split(`
|
|
50
|
+
`),s=n.reduce((a,l)=>Math.max(B(l),a),0),o=n.map(r).reduce((a,l)=>Math.max(B(l),a),0),u=e-(o-s);return Z(t,u,i)},gt=(t="",e="",r)=>{let i=r?.output??q.stdout,n=r?.withGuide??V.withGuide,s=r?.format??fn,o=["",...gn(t,Rt(i)-6,s).split(`
|
|
51
|
+
`).map(s),""],u=B(e),a=Math.max(o.reduce((d,g)=>{let m=B(g);return m>d?m:d},0),u)+2,l=o.map((d)=>`${c("gray",C)} ${d}${" ".repeat(a-B(d))}${c("gray",C)}`).join(`
|
|
52
|
+
`),f=n?`${c("gray",C)}
|
|
53
|
+
`:"",h=n?an:ln;i.write(`${f}${c("green",Vt)} ${c("reset",e)} ${c("gray",Pr.repeat(Math.max(a-u-1,1))+on)}
|
|
54
|
+
${l}
|
|
55
|
+
${c("gray",h+Pr.repeat(a+2)+un)}
|
|
56
|
+
`)};var yn=(t)=>c("magenta",t),W=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:i,errorMessage:n,frames:s=Te?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Te?80:120,signal:u,...a}={})=>{let l=en(),f,h,d=!1,g=!1,m="",v,I=performance.now(),A=Rt(r),x=a?.styleFrame??yn,N=(k)=>{let K=k>1?n??V.messages.error:i??V.messages.cancel;g=k===1,d&&(Ct(K,k),g&&typeof e=="function"&&e())},T=()=>N(2),R=()=>N(1),F=()=>{process.on("uncaughtExceptionMonitor",T),process.on("unhandledRejection",T),process.on("SIGINT",R),process.on("SIGTERM",R),process.on("exit",N),u&&u.addEventListener("abort",R)},D=()=>{process.removeListener("uncaughtExceptionMonitor",T),process.removeListener("unhandledRejection",T),process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R),process.removeListener("exit",N),u&&u.removeEventListener("abort",R)},_=()=>{if(v===void 0)return;l&&r.write(`
|
|
57
|
+
`);let k=Z(v,A,{hard:!0,trim:!1}).split(`
|
|
58
|
+
`);k.length>1&&r.write(Et.cursor.up(k.length-1)),r.write(Et.cursor.to(0)),r.write(Et.erase.down())},L=(k)=>k.replace(/\.+$/,""),X=(k)=>{let K=(performance.now()-k)/1000,et=Math.floor(K/60),rt=Math.floor(K%60);return et>0?`[${et}m ${rt}s]`:`[${rt}s]`},H=a.withGuide??V.withGuide,Lt=(k="")=>{d=!0,f=xr({output:r}),m=L(k),I=performance.now(),H&&r.write(`${c("gray",C)}
|
|
59
|
+
`);let K=0,et=0;F(),h=setInterval(()=>{if(l&&m===v)return;_(),v=m;let rt=x(s[K]),Ft;if(l)Ft=`${rt} ${m}...`;else if(t==="timer")Ft=`${rt} ${m} ${X(I)}`;else{let Si=".".repeat(Math.floor(et)).slice(0,3);Ft=`${rt} ${m}${Si}`}let Ri=Z(Ft,A,{hard:!0,trim:!1});r.write(Ri),K=K+1<s.length?K+1:0,et=et<4?et+0.125:0},o)},Ct=(k="",K=0,et=!1)=>{if(!d)return;d=!1,clearInterval(h),_();let rt=K===0?c("green",Vt):K===1?c("red",Ar):c("red",Tr);m=k??m,et||(t==="timer"?r.write(`${rt} ${m} ${X(I)}
|
|
60
|
+
`):r.write(`${rt} ${m}
|
|
61
|
+
`)),D(),f()};return{start:Lt,stop:(k="")=>Ct(k,0),message:(k="")=>{m=L(k??m)},cancel:(k="")=>Ct(k,1),error:(k="")=>Ct(k,2),clear:()=>Ct("",0,!0),get isCancelled(){return g}}},_o={light:E("\u2500","-"),heavy:E("\u2501","="),block:E("\u2588","#")};var $n=[`${c("dim","\u2191/\u2193")} to navigate`,`${c("dim","Enter:")} confirm`],Mt=(t,e)=>t.includes(`
|
|
62
|
+
`)?t.split(`
|
|
63
|
+
`).map((r)=>e(r)).join(`
|
|
64
|
+
`):e(t),Or=(t)=>{let e=(i,n)=>{if(i===void 0)return"";let s=i.label??String(i.value);switch(n){case"disabled":return`${c("gray",Ut)} ${Mt(s,(o)=>c("gray",o))}${i.hint?` ${c("dim",`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${Mt(s,(o)=>c("dim",o))}`;case"active":return`${c("green",De)} ${s}${i.hint?` ${c("dim",`(${i.hint})`)}`:""}`;case"cancelled":return`${Mt(s,(o)=>c(["strikethrough","dim"],o))}`;default:return`${c("dim",Ut)} ${Mt(s,(o)=>c("dim",o))}`}},r=t.showInstructions??!0;return new Sr({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let i=t.withGuide??V.withGuide,n=`${Gt(this.state)} `,s=`${Dr(this.state)} `,o=ot(t.output,t.message,s,n),u=`${i?`${c("gray",C)}
|
|
65
|
+
`:""}${o}
|
|
66
|
+
`;switch(this.state){case"submit":{let a=i?`${c("gray",C)} `:"",l=ot(t.output,e(this.options[this.cursor],"selected"),a);return`${u}${l}`}case"cancel":{let a=i?`${c("gray",C)} `:"",l=ot(t.output,e(this.options[this.cursor],"cancelled"),a);return`${u}${l}${i?`
|
|
67
|
+
${c("gray",C)}`:""}`}default:{let a=i?`${c("cyan",C)} `:"",l=u.split(`
|
|
68
|
+
`).length,f=r?kr($n,i):i?[c("cyan",at)]:[],h=f.join(`
|
|
69
|
+
`),d=f.length+1;return`${u}${a}${ke({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:a.length,rowPadding:l+d,style:(g,m)=>e(g,g.disabled?"disabled":m?"active":"inactive")}).join(`
|
|
70
|
+
${a}`)}
|
|
71
|
+
${h}
|
|
72
|
+
`}}}}).prompt()};var Ao=`${c("gray",C)} `;var Nr=(t)=>new Ae({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??V.withGuide,r=`${`${e?`${c("gray",C)}
|
|
73
|
+
`:""}${Gt(this.state)} `}${t.message}
|
|
74
|
+
`,i=t.placeholder&&t.placeholder.length>0?c("inverse",t.placeholder[0])+c("dim",t.placeholder.slice(1)):c(["inverse","hidden"],"_"),n=this.userInput?this.userInputWithCursor:i,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${c("yellow",this.error)}`:"",u=e?`${c("yellow",C)} `:"",a=e?c("yellow",at):"";return`${r.trim()}
|
|
75
|
+
${u}${n}
|
|
76
|
+
${a}${o}
|
|
77
|
+
`}case"submit":{let o=s?` ${c("dim",s)}`:"",u=e?c("gray",C):"";return`${r}${u}${o}`}case"cancel":{let o=s?` ${c(["strikethrough","dim"],s)}`:"",u=e?c("gray",C):"";return`${r}${u}${o}${s.trim()?`
|
|
78
|
+
${u}`:""}`}default:{let o=e?`${c("cyan",C)} `:"",u=e?c("cyan",at):"";return`${r}${o}${n}
|
|
79
|
+
${u}
|
|
80
|
+
`}}}}).prompt();var wn=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Vr=["black","blue","cyan","gray","green","magenta","red","white","yellow"],bn=["bold","dim","italic","underline","reset"],Gr={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Cn={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"},xn={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"},Mr={"\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 Wt(t){return(e)=>wn?`${t}${e}${Gr.reset}`:e}function Rn(t){for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);if(r<32&&r!==27)return!1}return!0}function Ur({bright:t=!1,color:e}){let r=Bun.color(e,"ansi"),i=typeof r==="string"&&r.length>0&&Rn(r)?r:Cn[e];if(!i)return"";return t&&i in Mr?Mr[i]:i}var Sn=Vr.reduce((t,e)=>{let r=Ur({color:e});if(r)t[e]=Wt(r);let i=Ur({bright:!0,color:e});if(i)t[`${e}Bright`]=Wt(i);return t},{}),In=bn.reduce((t,e)=>(t[e]=Wt(Gr[e]),t),{}),En=Vr.reduce((t,e)=>{let r=xn[e];if(r){let i=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[i]=Wt(r)}return t},{}),p={...Sn,...In,...En};function Kt(t){if(xt(t))throw new Y;return t}function _n(t){return t.map((e)=>e.key?`${p.bold(e.key)} ${p.dim(e.text)}`:p.dim(e.text)).join(p.dim(" \xB7 "))}function qt(t){w.info(_n(t))}var zt={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 ct(t){return qt(zt.confirm),Kt(await Lr(t))}async function it(t){return qt(zt.text),Kt(await Nr(t))}async function pt(t){return qt(zt.select),Kt(await Or({showInstructions:!1,...t}))}async function dt(t){return qt(zt.multiselect),Kt(await Fr({showInstructions:!1,...t}))}var An=4;function yt(t,e=0){if(e>=An)return;let r=[...t instanceof AggregateError?t.errors:[],...t.cause!==void 0?[t.cause]:[]];for(let i of r){if(w.info(p.dim(`caused by: ${i instanceof Error?i.message:String(i)}`)),i instanceof y&&i.hint)w.info(p.dim(` ${i.hint}`));if(i instanceof Error)yt(i,e+1)}}function Le(t){return t==null?[]:Array.isArray(t)?t:[t]}function Tn(t,e,r,i){var n,s=t[e],o=~i.string.indexOf(e)?r==null||r===!0?"":String(r):typeof r==="boolean"?r:~i.boolean.indexOf(e)?r==="false"?!1:r==="true"||(t._.push((n=+r,n*0===0)?n:r),!!r):(n=+r,n*0===0)?n:r;t[e]=s==null?o:Array.isArray(s)?s.concat(o):[s,o]}function Pt(t,e){t=t||[],e=e||{};var r,i,n,s,o,u={_:[]},a=0,l=0,f=0,h=t.length;let d=e.alias!==void 0,g=e.unknown!==void 0,m=e.default!==void 0;if(e.alias=e.alias||{},e.string=Le(e.string),e.boolean=Le(e.boolean),d)for(r in e.alias){i=e.alias[r]=Le(e.alias[r]);for(a=0;a<i.length;a++)(e.alias[i[a]]=i.concat(r)).splice(a,1)}for(a=e.boolean.length;a-- >0;){i=e.alias[e.boolean[a]]||[];for(l=i.length;l-- >0;)e.boolean.push(i[l])}for(a=e.string.length;a-- >0;){i=e.alias[e.string[a]]||[];for(l=i.length;l-- >0;)e.string.push(i[l])}if(m){for(r in e.default)if(s=typeof e.default[r],i=e.alias[r]=e.alias[r]||[],e[s]!==void 0){e[s].push(r);for(a=0;a<i.length;a++)e[s].push(i[a])}}let v=g?Object.keys(e.alias):[];for(a=0;a<h;a++){if(n=t[a],n==="--"){u._=u._.concat(t.slice(++a));break}for(l=0;l<n.length;l++)if(n.charCodeAt(l)!==45)break;if(l===0)u._.push(n);else if(n.substring(l,l+3)==="no-"){if(s=n.substring(l+3),g&&!~v.indexOf(s))return e.unknown(n);u[s]=!1}else{for(f=l+1;f<n.length;f++)if(n.charCodeAt(f)===61)break;s=n.substring(l,f),o=n.substring(++f)||(a+1===h||(""+t[a+1]).charCodeAt(0)===45||t[++a]),i=l===2?[s]:s;for(f=0;f<i.length;f++){if(s=i[f],g&&!~v.indexOf(s))return e.unknown("-".repeat(l)+s);Tn(u,s,f+1<i.length||o,e)}}}if(m){for(r in e.default)if(u[r]===void 0)u[r]=e.default[r]}if(d)for(r in u){i=e.alias[r]||[];while(i.length>0)u[i.shift()]=u[r]}return u}var Dn=1;function $t(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Oe(t){let e={alias:{},boolean:[],default:{},string:[]};for(let[r,i]of Object.entries(t)){if(i.type==="boolean")e.boolean.push(r);else e.string.push(r);if(i.alias)e.alias[i.alias]=r;let n=$t(r);if(n!==r)e.alias[n]=r;if(i.default!==void 0)e.default[r]=i.default}return e}function Fe(t,e){if(t in e)return`--${$t(t)}`;let r=Object.entries(e).find(([,i])=>i.alias===t)?.[0];if(r)return`--${$t(r)}`;return t.length===Dn?`-${t}`:`--${$t(t)}`}function O(t,e,r){let{alias:i}=Oe(e),n=Object.keys(t).find((s)=>!Object.hasOwn(e,s)&&!Object.hasOwn(i,s));if(n!==void 0)throw new y(`Unknown option: ${Fe(n,e)}`,r)}function jr(t,e){for(let[i,n]of Object.entries(t))if(Array.isArray(n))throw new y(`${Fe(i,e)} can only be provided once`);let r={...t};for(let[i,n]of Object.entries(e)){if(n.type!=="number")continue;let s=t[i];if(s===void 0)continue;let o=Number(s);if(typeof s==="boolean"||typeof s==="string"&&s.trim().length===0||!Number.isFinite(o)){let u=Fe(i,e);throw new y(`Invalid number for ${u}: "${s}"`,`Use ${u}=<number> with a finite numeric value`)}r[i]=o}return r}function Hr(t,e){let r=Oe(e),i=Pt(t,r),n=i._[0],s=n?t.indexOf(n):-1,o=Pt(s>=0?t.slice(0,s):t,r),{_:u,...a}=o;O(a,e,"Place command options after the command name");let{_:l,...f}=i,h=Object.fromEntries(Object.entries(f).filter(([g])=>(g in e)||(g in r.alias))),d=jr(h,e);return{command:n,flags:d,restArgs:s>=0?t.slice(s+1):[]}}function Ne(t,e={}){let r=Oe(e),i=Pt(kn(t,r),r),{_:n,...s}=i;return{args:jr(s,e),rawPositionals:n}}function kn(t,e){let r=!0;return t.map((i)=>{if(i==="--")r=!1;if(!r)return i;return i.replace(/^--(no-[^=]+)(=.*)?$/,(n,s,o)=>{let u=e.alias[s];return u&&e.boolean.includes(u)?`--${u}${o??""}`:n})})}function Me(t,e){let r={},i=Object.entries(e);for(let[n,[s,o]]of i.entries())r[s]=o.variadic?t.slice(n):t[n];return r}function Br(t,e){for(let[r,i]of Object.entries(e)){if(!i.required)continue;let n=t[r];if(Array.isArray(n)?n.length===0:!n)return`Missing required argument: <${r}${i.variadic?"...":""}>`}return null}var Ln=(t)=>t,b={arg:p.magenta,cmd:p.cyan,default:p.bold,desc:Ln,flag:p.green,header:(t)=>p.bold(p.yellow(t)),hint:p.dim,name:(t)=>p.bold(p.cyan(t)),placeholder:p.magenta};class Ue{metadata;commands;globalArgs;constructor(t,e,r){this.metadata=t;this.commands=e;this.globalArgs=r}version(){return`${b.name(this.metadata.name)} ${b.hint(this.metadata.version??"0.0.0")}`}global(){let t=[],{name:e,bin:r,version:i,description:n}=this.metadata;if(t.push(`${b.name(e)}${i?` ${b.hint(`v${i}`)}`:""}`),n)t.push(b.desc(n));t.push(""),t.push(b.header("Usage:")),t.push(` ${b.cmd(r)} ${b.placeholder("[command]")} ${b.placeholder("[options]")}`),t.push(""),t.push(b.header("Commands:"));let s=Array.from(this.commands.values()).map((o)=>[` ${b.cmd(o.name)}`,b.desc(o.description)]);return t.push(...this.formatColumns(s)),t.push(""),t.push(b.header("Options:")),t.push(...this.formatArgDefs(this.globalArgs)),t.push(""),t.push(`${b.hint("Run")} ${b.cmd(`${r} <command> --help`)} ${b.hint("for command details.")}`),t.join(`
|
|
81
|
+
`).trimEnd()}command(t,e){let r=[],i=e??this.metadata.bin,n=`${i} ${t.name}`,s=`${b.cmd(i)} ${b.cmd(t.name)}`;r.push(b.name(n)),r.push(b.desc(t.description)),r.push(""),r.push(b.header("Usage:"));let o=this.formatPositionalUsage(t.positionals);if(t.hasSubcommands())r.push(` ${s} ${b.placeholder("<subcommand>")} ${b.placeholder("[options]")}`);else{let l=[s];if(o)l.push(o);l.push(b.placeholder("[options]")),r.push(` ${l.join(" ")}`)}if(t.prompts&&Object.keys(t.positionals).length>0)r.push(` ${b.hint("Omit positional arguments to run interactively.")}`);if(r.push(""),t.hasSubcommands()){r.push(b.header("Subcommands:"));let l=t.getSubcommands().map((f)=>[` ${b.cmd(f.name)}`,b.desc(f.description)]);r.push(...this.formatColumns(l)),r.push("")}if(Object.entries(t.positionals).length>0)r.push(b.header("Arguments:")),r.push(...this.formatPositionalDefs(t.positionals)),r.push("");if(Object.entries(t.args).length>0)r.push(b.header("Options:")),r.push(...this.formatArgDefs(t.args));return r.join(`
|
|
82
|
+
`).trimEnd()}formatPositionalUsage(t){return Object.entries(t).map(([e,r])=>{let i=r.variadic?`${e}...`:e;return r.required?b.arg(`<${i}>`):b.arg(`[${i}]`)}).join(" ")}formatPositionalDefs(t){let e=Object.entries(t).map(([r,i])=>{let n=i.variadic?`${r}...`:r,s=b.desc(i.description??""),o=i.required?"":b.hint(" (optional)");return[` ${b.arg(n)}`,`${s}${o}`]});return this.formatColumns(e)}formatArgDefs(t){let e=[];for(let[r,i]of Object.entries(t)){let n=i.alias?`${b.flag(`-${i.alias}`)}, `:" ",s=i.type==="boolean"?"":` ${b.placeholder(`<${i.type==="number"?"number":"value"}>`)}`,o=`${n}${b.flag(`--${$t(r)}`)}${s}`,u=b.desc(i.description??""),a=this.formatDefault(i),l=a===void 0?"":` (default: ${b.default(a)})`;e.push([` ${o}`,`${u}${l}`])}return this.formatColumns(e)}formatDefault(t){if(typeof t.displayDefault==="string")return t.displayDefault;if(t.default===void 0)return;if(t.type==="boolean"&&t.default===!1)return;if(t.type==="string")return`"${t.default}"`;return String(t.default)}formatColumns(t){if(t.length===0)return[];let e=Math.max(...t.map(([i])=>this.stripAnsi(i).length)),r=2;return t.map(([i,n])=>{let s=e-this.stripAnsi(i).length+r;return`${i}${" ".repeat(s)}${n}`})}stripAnsi(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}}var nt=new Uint32Array(65536),Fn=(t,e)=>{let r=t.length,i=e.length,n=1<<r-1,s=-1,o=0,u=r,a=r;while(a--)nt[t.charCodeAt(a)]|=1<<a;for(a=0;a<i;a++){let l=nt[e.charCodeAt(a)],f=l|o;if(l|=(l&s)+s^s,o|=~(l|s),s&=l,o&n)u++;if(s&n)u--;o=o<<1|1,s=s<<1|~(f|o),o&=f}a=r;while(a--)nt[t.charCodeAt(a)]=0;return u},On=(t,e)=>{let r=e.length,i=t.length,n=[],s=[],o=Math.ceil(r/32),u=Math.ceil(i/32);for(let m=0;m<o;m++)s[m]=-1,n[m]=0;let a=0;for(;a<u-1;a++){let m=0,v=-1,I=a*32,A=Math.min(32,i)+I;for(let x=I;x<A;x++)nt[t.charCodeAt(x)]|=1<<x;for(let x=0;x<r;x++){let N=nt[e.charCodeAt(x)],T=s[x/32|0]>>>x&1,R=n[x/32|0]>>>x&1,F=N|m,D=((N|R)&v)+v^v|N|R,_=m|~(D|v),L=v&D;if(_>>>31^T)s[x/32|0]^=1<<x;if(L>>>31^R)n[x/32|0]^=1<<x;_=_<<1|T,L=L<<1|R,v=L|~(F|_),m=_&F}for(let x=I;x<A;x++)nt[t.charCodeAt(x)]=0}let l=0,f=-1,h=a*32,d=Math.min(32,i-h)+h;for(let m=h;m<d;m++)nt[t.charCodeAt(m)]|=1<<m;let g=i;for(let m=0;m<r;m++){let v=nt[e.charCodeAt(m)],I=s[m/32|0]>>>m&1,A=n[m/32|0]>>>m&1,x=v|l,N=((v|A)&f)+f^f|v|A,T=l|~(N|f),R=f&N;if(g+=T>>>i-1&1,g-=R>>>i-1&1,T>>>31^I)s[m/32|0]^=1<<m;if(R>>>31^A)n[m/32|0]^=1<<m;T=T<<1|I,R=R<<1|A,f=R|~(x|T),l=T&x}for(let m=h;m<d;m++)nt[t.charCodeAt(m)]=0;return g},Nn=(t,e)=>{if(t.length<e.length){let r=e;e=t,t=r}if(e.length===0)return t.length;if(t.length<=32)return Fn(t,e);return On(t,e)},Wr=(t,e)=>{let r=1/0,i=0;for(let n=0;n<e.length;n++){let s=Nn(t,e[n]);if(s<r)r=s,i=n}return e[i]};function Yt(t,e,r,i){let n=Wr(e,r);if(console.error(p.red(`Unknown ${t}: ${e}`)),n)console.error(p.yellow(`Did you mean "${n}"?`));console.error(`
|
|
83
|
+
Run "${i} --help" for usage.`),process.exit(1)}function Jt(t,e){let r=(n)=>n&&typeof n==="object";if(!r(t)||!r(e))return e;let i={...t};for(let n of Object.keys(e)){let s=i[n],o=e[n];if(Array.isArray(s)&&Array.isArray(o))i[n]=[...o];else if(r(s)&&r(o))i[n]=Jt(s,o);else i[n]=o}return i}var Ve="__exit__";class vt{command;env;prefix;options;constructor(t,e,r,i={}){this.command=t;this.env=e;this.prefix=r;this.options=i}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(t,e){if(e&&process.stdout.isTTY!==!0)throw new y("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(e)await this.routeInteractive();else await this.routeDirect(t)}async routeDirect(t){let[e,...r]=t;if(e&&this.command.hasSubcommands()){let i=this.command.getSubcommand(e);if(i){await this.handleSubcommandRoute(i,r);return}if(!e.startsWith("-")){this.handleUnknownSubcommand(e);return}}await this.executeCommand(t)}handleUnknownSubcommand(t){let e=this.command.getSubcommands().map((r)=>r.name);Yt("subcommand",t,e,this.commandPath)}async handleSubcommandRoute(t,e){await new vt(t,this.env,this.commandPath).route(e,!1)}async executeCommand(t){if(this.isHelpRequest(t)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:r,rawPositionals:i}=Ne(t,this.command.args),n=Me(i,this.command.positionals),s=Br(n,this.command.positionals);if(s)w.error(s),console.error(`
|
|
84
|
+
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&i.length===0&&process.stdout.isTTY===!0,u=this.buildContext(n,r,o);await this.command.execute(u)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:t}=Ne([],this.command.args),e=Me([],this.command.positionals),r=this.buildContext(e,t,!0);await this.command.execute?.(r)}async runSubcommandMenu(){while(!0){let t=await this.promptSubcommandSelectionOrBack();if(t===null)return;if(t===Ve){this.options.onExit?.();return}let e=this.command.getSubcommand(t);if(e)await this.executeSubcommand(e)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(t){if(t instanceof Y){if(this.options.isRoot)this.options.onExit?.();return null}throw t}}async executeSubcommand(t){try{await new vt(t,this.env,this.commandPath).route([],!0)}catch(e){if(e instanceof Y)return;if(e instanceof y){if(w.warn(p.yellow(e.message)),e.hint)w.info(p.dim(e.hint));yt(e);return}throw e}}promptSubcommandSelection(){let{isRoot:t}=this.options,e=t?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Ve}:{hint:"Return to previous menu",label:"Back",value:Ve};return pt({message:t?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((r)=>({hint:r.description,label:r.name,value:r.name})),e]})}buildContext(t,e,r){return{...this.env,args:e,interactive:r,positionals:t}}isHelpRequest(t){let e=t.indexOf("--"),r=e<0?t:t.slice(0,e);return r.includes("--help")||r.includes("-h")}printHelp(t){let e=t===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(t,e))}}var Mn={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class Ge{commands=new Map;metadata;configManager;help;bin;globalArgs={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"}};constructor(t,e){this.configManager=t,this.metadata={...Mn,...e},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Ue({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(t){for(let e of t)e.init?.(),this.commands.set(e.name,e)}async run(t=process.argv.slice(2)){try{let{command:e,flags:r,restArgs:i}=Hr(t,this.globalArgs);if(r.version&&!e)return console.log(this.help.version());if(r.interactive&&!e)return await this.runInteractive();if(!e)return console.log(this.help.global());if(e==="help")return this.printHelpFor(i[0]);await this.runDirect(e,i,!!r.help)}catch(e){this.handleError(e)}}printHelpFor(t){if(!t)return console.log(this.help.global());let e=this.commands.get(t);if(!e)return this.handleUnknownCommand(t);console.log(this.help.command(e))}async runInteractive(){this.showIntro();let t=this.createVirtualRootCommand(),e={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},r=new vt(t,e,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await r.route([],!0)}catch(i){this.handleError(i)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(t)=>this.commands.get(t),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){Bt(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(t,e,r){let i=this.commands.get(t);if(!i)return this.handleUnknownCommand(t);let n=e.length>0&&!e[0]?.startsWith("-");if(r&&!n)return console.log(this.help.command(i));try{let s={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new vt(i,s,this.bin).route(e,!1)}catch(s){this.handleError(s)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let t=this.metadata.version?` v${this.metadata.version}`:"";Ht(`${p.bgCyan(p.black(` ${this.metadata.name}${t} `))}`)}handleUnknownCommand(t){let e=Array.from(this.commands.keys());Yt("command",t,e,this.bin)}handleError(t){if(this.metadata.onError?.(t))return;if(t instanceof Y)process.exit(0);if(t instanceof y){if(w.warn(p.yellow(t.message)),t.hint)w.info(p.dim(t.hint));yt(t),process.exit(t.exitCode)}if(t instanceof Error)w.error(p.red(t.message)),yt(t),process.exit(1);console.error(p.red("Error:"),t),process.exit(1)}}class _t{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(t){for(let e of t)e.init?.(),this.subcommands.set(e.name,e)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(t){return this.subcommands.get(t)}getSubcommands(){return Array.from(this.subcommands.values())}}function Q(t){return t}function M(t){return t}import J from"fs";import zr from"path";var Xt=(t)=>(t.map=(e)=>Xt((r)=>e(t(r))),t.or=(e)=>Xt((r)=>{try{return t(r)}catch(i){return e(r)}}),t),Un=()=>"bad banditype"();var Kr=()=>Xt((t)=>t);var Vn=(t)=>Xt((e)=>e instanceof t?e:Un()),qr=(t)=>Vn(Object).map((e)=>{let r={};for(let i in e){let n=t(e[i]);n!==void 0&&(r[i]=n)}return r});var Gn=2,jn=qr(Kr());class je{config;configPath;defaultConfig;loadError;constructor(t,e){this.configPath=zr.resolve(t),this.defaultConfig=e,this.config=this.loadConfig()}get path(){return this.configPath}get(t){return this.config[t]}set(t,e){this.config[t]=e,this.save()}delete(t){delete this.config[t],this.save()}exists(){return J.existsSync(this.configPath)}getAll(){return structuredClone(this.config)}save(t){if(this.loadError)throw Error(`Cannot overwrite unreadable config at ${this.configPath}; repair the file and try again`,{cause:this.loadError});if(t)this.config={...t};this.ensureDirectoryExists();let e=this.exists()?J.realpathSync(this.configPath):this.configPath,r=`${e}.${crypto.randomUUID()}.tmp`;try{let i=this.exists()?J.statSync(this.configPath).mode:void 0;if(J.writeFileSync(r,JSON.stringify(this.config,null,Gn),{flag:"wx",mode:i}),i!==void 0)J.chmodSync(r,i);J.renameSync(r,e)}catch(i){throw Error(`Failed to save config to ${this.configPath}`,{cause:i})}finally{J.rmSync(r,{force:!0})}}ensureDirectoryExists(){let t=zr.dirname(this.configPath);if(!J.existsSync(t))try{J.mkdirSync(t,{recursive:!0})}catch(e){throw Error(`Failed to create config directory at ${t}`,{cause:e})}}loadConfig(){if(!J.existsSync(this.configPath))return structuredClone(this.defaultConfig);try{let t=J.readFileSync(this.configPath,"utf-8"),e=JSON.parse(t);if(Array.isArray(e))throw Error("Config must be an object");let r=jn(e);return Jt(structuredClone(this.defaultConfig),r)}catch(t){return this.loadError=t,console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),structuredClone(this.defaultConfig)}}}var Yr="0.9.4";class P extends _t{}var Zt="hydra";var Jr=".hydra/config.json",tt=".hydra/shared",At=".hydra/runners",Tt="default",Xr={profiles:{}},Zr=!1,Qr=24,Qt=7,ti=["logs","shared"];import{spawn as Jn}from"child_process";import{once as Xn}from"events";import{existsSync as wt}from"fs";import{cp as Zn,link as Qn,mkdir as re,mkdtemp as ts,readdir as oi,readFile as We,readlink as es,rename as rs,rm as ft,stat as is,symlink as ns,unlink as ai,writeFile as ss}from"fs/promises";import{join as S,resolve as Ke}from"path";var Bn=new Set(["github.com","www.github.com"]);var ei=/\.git$/;function mt(t){let e;try{e=new URL(t)}catch{throw Error(`Invalid GitHub URL: ${t}`)}if(e.protocol!=="https:"&&e.protocol!=="http:")throw Error(`Invalid GitHub URL (expected http(s)): ${t}`);if(!Bn.has(e.hostname))throw Error(`Invalid GitHub URL (host must be github.com): ${t}`);let r=e.pathname.split("/").filter(Boolean);if(r.length===1){let i=r[0]?.replace(ei,"");if(!i)throw Error(`Invalid GitHub URL: ${t}`);return{kind:"org",org:i}}if(r.length===2){let i=r[0],n=r[1]?.replace(ei,"");if(!i||!n)throw Error(`Invalid GitHub URL: ${t}`);return{kind:"repo",owner:i,repo:n}}throw Error(`Invalid GitHub URL (expected github.com/<owner>/<repo> or github.com/<org>): ${t}`)}function te(t){return t.kind==="repo"?`${t.owner}/${t.repo}`:t.org}import{existsSync as Wn}from"fs";import{readdir as Kn,stat as qn}from"fs/promises";import{join as zn}from"path";var Dt="_diag",ri={runner:/^Runner_.+\.log$/,worker:/^Worker_.+\.log$/},ii=1024,ni=["B","KB","MB","GB"],Yn=1;function si(t){if(ri.worker.test(t))return"worker";if(ri.runner.test(t))return"runner";return null}function ee(t){return[...t].sort((e,r)=>r.mtime.getTime()-e.mtime.getTime())}async function kt(t){if(!Wn(t))return[];let e=await Kn(t,{withFileTypes:!0}),r=[];for(let i of e){if(!i.isFile())continue;let n=si(i.name);if(!n)continue;let s=zn(t,i.name),o=await qn(s);r.push({mtime:o.mtime,name:i.name,path:s,size:o.size,type:n})}return ee(r)}function He(t,e){let r=t.find((n)=>n.type===e);if(r)return{fallback:!1,file:r};let i=t[0];return i?{fallback:!0,file:i}:null}function Be(t,e){if(e<=0)return"";let r=t.endsWith(`
|
|
85
|
+
`)?t.slice(0,-1):t;if(r==="")return"";return r.split(`
|
|
86
|
+
`).slice(-e).join(`
|
|
87
|
+
`)}function ht(t){let e=t,r=0;while(e>=ii&&r<ni.length-1)e/=ii,r++;return`${r===0?String(e):e.toFixed(Yn)} ${ni[r]??"B"}`}var ui="actions/runner",os={linux:"linux-x64",osx:"osx-arm64",windows:"win-x64"},qe=["bin"],ze=["externals"],as=1,us=5000,ls=50,cs=5000,ps=50;class ie{profile;sharedPath=null;constructor(t){this.profile=t}async download(){let t=os[this.profile.os],e=await this.getLatestVersion(),r=S(tt,"github",e);if(await this.isCompleteDownload(r))return this.sharedPath=r,{path:r,version:e};let i=S(tt,"github");await re(i,{recursive:!0});let n=await ts(S(tt,`.github-${e}-`)),s=`actions-runner-${t}-${e}.tar.gz`,o=S(n,s),u=`https://github.com/${ui}/releases/download/v${e}/${s}`;try{if(await Bun.$`curl --fail --silent --show-error --location -o ${o} ${u}`,await Bun.$`tar xzf ${o} -C ${n}`,await ai(o),!await this.isCompleteDownload(n))throw new y(`Runner v${e} archive is incomplete`);await this.publishDownload(n,r,e)}finally{await ft(n,{force:!0,recursive:!0})}return this.sharedPath=r,{path:r,version:e}}async create(t){let e=await this.ensureDownloaded(),r=[];for(let i of t){let n=S(this.profile.directory,i);if(wt(n))throw new y(`Runner directory already exists: ${n}`,"Remove or recover this runner before creating it again");try{await this.setupRunnerDir(e,n),await this.registerRunner(n,i)}catch(s){if(!wt(S(n,".runner")))await ft(n,{force:!0,recursive:!0});throw s}r.push({directory:n,id:i,name:i,status:"registered"})}return r}async remove(t){for(let e of t){let r=S(this.profile.directory,e);if(!wt(S(r,".runner")))continue;let i=await this.fetchRemovalToken(r),n=await Bun.$`bash ./config.sh remove --token ${i}`.cwd(r).quiet().nothrow();if(n.exitCode!==0)throw new y(`Failed to deregister runner ${e}`,n.stderr.toString().trim()||"Runner files have been preserved; retry removal")}}async start(t){for(let e of t){let r=S(this.profile.directory,e),i=await this.readPidFile(r);if(i&&this.isProcessRunning(i))continue;let n=Jn("bash",["./run.sh"],{cwd:Ke(r),detached:!0,stdio:"ignore"});if(await Xn(n,"spawn"),n.pid===void 0)throw new y(`Failed to start runner ${e}`);n.unref(),await this.writePidFile(r,n.pid)}}async stop(t){for(let e of t){let r=S(this.profile.directory,e),i=await this.readPidFile(r);if(i&&this.isProcessRunning(i)){try{process.kill(-i,"SIGTERM")}catch(s){if(s.code!=="ESRCH")throw s;try{process.kill(i,"SIGTERM")}catch(o){if(o.code!=="ESRCH")throw o}}let n=Date.now()+us;while(this.isProcessRunning(i)){if(Date.now()>=n)throw new y(`Runner ${e} did not stop`,"Wait for its current job to finish and retry");await Bun.sleep(ls)}}await this.removePidFile(r)}}async list(){let t=this.profile.directory;if(!wt(t))return[];let e=await oi(t,{withFileTypes:!0}),r=[];for(let i of e){if(!i.isDirectory())continue;let n=S(t,i.name);r.push(await this.getRunnerStatus(n,i.name))}return r}async currentVersion(t){let e=S(this.profile.directory,t);return this.detectVersion(e)}async logFiles(t){return kt(S(this.profile.directory,t,Dt))}async update(t){let e=await this.ensureDownloaded();for(let r of t){let i=S(this.profile.directory,r);await this.removeRunnerBinaries(i),await this.setupRunnerDir(e,i)}}async getRunnerStatus(t,e){let r=await this.readRunnerName(t),i=await this.readPidFile(t),n=i!==null&&this.isProcessRunning(i),s="unknown";if(n)s="running";else if(wt(S(t,".runner")))s="registered";return{directory:t,id:e,name:r,pid:n?i:void 0,status:s}}async ensureDownloaded(){if(this.sharedPath)return this.sharedPath;let{path:t}=await this.download();return t}async isCompleteDownload(t){try{return(await Promise.all(["bin","externals","config.sh","run.sh"].map((r)=>is(S(t,r))))).every((r,i)=>i<qe.length+ze.length?r.isDirectory():r.isFile())}catch(e){if(e.code==="ENOENT")return!1;throw e}}async publishDownload(t,e,r){let i=S(tt,`.github-${r}.lock`),n=Date.now()+cs;while(!0)try{await re(i);break}catch(s){if(s.code!=="EEXIST")throw s;if(Date.now()>=n)throw new y(`Runner download is locked: ${i}`,"Retry after other Hydra downloads finish; remove a stale lock only when no download is running");await Bun.sleep(ps)}try{if(await this.isCompleteDownload(e))return;await ft(e,{force:!0,recursive:!0}),await rs(t,e)}finally{await ft(i,{force:!0,recursive:!0})}}async setupRunnerDir(t,e){await re(e,{recursive:!0});for(let r of qe)await this.hardLinkDir(S(t,r),S(e,r));for(let r of ze){let i=Ke(t,r),n=S(e,r);if(!wt(n))await ns(i,n)}for(let r of["*.sh","*.sh.template"]){let i=await Array.fromAsync(new Bun.Glob(r).scan(t));for(let n of i)await Zn(S(t,n),S(e,n))}}async registerRunner(t,e){let r=await this.fetchRegistrationToken(),i=["--url",this.profile.url,"--token",r,"--name",e,"--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(t).quiet()}async fetchRegistrationToken(){return this.fetchRunnerToken(mt(this.profile.url),"registration-token")}async fetchRemovalToken(t){let e=await We(S(t,".runner"),"utf-8"),i=JSON.parse(this.stripBom(e)).gitHubUrl;if(!i)throw Error("Cannot determine GitHub URL from runner config");return this.fetchRunnerToken(mt(i),"remove-token")}async fetchRunnerToken(t,e){let r=t.kind==="repo"?`repos/${t.owner}/${t.repo}/actions/runners/${e}`:`orgs/${t.org}/actions/runners/${e}`,i=t.kind==="repo"?"gh needs admin access to the repository":"gh needs the admin:org scope",n=await Bun.$`gh api ${r} --method POST --jq .token`.quiet().nothrow();if(n.exitCode!==0){let o=n.stderr.toString().trim();throw Error(`gh api ${r} failed for ${te(t)} (${i})${o?`: ${o}`:""}`)}let s=n.stdout.toString().trim();if(!s)throw Error(`Failed to fetch ${e} for ${te(t)}`);return s}async getLatestVersion(){return(await Bun.$`gh api repos/${ui}/releases/latest --jq .tag_name`.quiet()).stdout.toString().trim().replace(/^v/,"")}pidFilePath(t){return Ke(t,".pid")}async writePidFile(t,e){await ss(this.pidFilePath(t),String(e))}async readPidFile(t){try{let e=await We(this.pidFilePath(t),"utf-8"),r=Number(e.trim());return Number.isSafeInteger(r)&&r>as?r:null}catch{return null}}async removePidFile(t){try{await ai(this.pidFilePath(t))}catch{}}async readRunnerName(t){try{let e=await We(S(t,".runner"),"utf-8");return JSON.parse(this.stripBom(e)).agentName??"unknown"}catch{return"unknown"}}async hardLinkDir(t,e){await re(e,{recursive:!0});let r=await oi(t,{withFileTypes:!0});for(let i of r){let n=S(t,i.name),s=S(e,i.name);if(i.isDirectory())await this.hardLinkDir(n,s);else await Qn(n,s)}}async detectVersion(t){try{return(await es(S(t,"externals"))).match(/github\/([^/]+)/)?.[1]??null}catch{return null}}async removeRunnerBinaries(t){for(let e of qe)await ft(S(t,e),{force:!0,recursive:!0});for(let e of ze)await ft(S(t,e),{force:!0});for(let e of["*.sh","*.sh.template"]){let r=await Array.fromAsync(new Bun.Glob(e).scan(t));for(let i of r)await ft(S(t,i),{force:!0})}}stripBom(t){return t.replace(/^\uFEFF/,"")}isProcessRunning(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}}import{existsSync as Je}from"fs";import{readdir as Xe,readFile as ds,readlink as ms,rm as Ze,stat as hs}from"fs/promises";import{join as ut}from"path";var li="_work",fs="externals",gs=".pid",ys="github",$s=/github\/([^/]+)/,vs=["runner","worker"],ws=24,ci=3600000,Ye=10;function ne(t){return{auto:t?.auto??Zr,intervalHours:t?.intervalHours??Qr,lastRun:t?.lastRun,olderThanDays:t?.olderThanDays??Qt,targets:t?.targets??ti}}function pi(t,e){return t-e*ws*ci}function Qe(t,e){if(!t.lastRun)return!0;let r=Date.parse(t.lastRun);if(Number.isNaN(r))return!0;return e-r>=t.intervalHours*ci}function di(t,e){let r=ee(t),i=new Set;for(let n of vs){let s=r.find((o)=>o.type===n);if(s)i.add(s.path)}return r.filter((n)=>!i.has(n.path)&&n.mtime.getTime()<e)}function mi(t){return[...t].sort(Ss)[0]??null}function hi(t,e){let r=mi(t),i=new Set(e);return t.filter((n)=>n!==r&&!i.has(n))}function fi(t){return t.match($s)?.[1]??null}function se(t){return Object.values(t).reduce((e,r)=>e+r.freedBytes,0)}async function gi(t){try{let e=await ds(ut(t,gs),"utf-8"),r=Number.parseInt(e.trim(),Ye);if(Number.isNaN(r))return!1;return process.kill(r,0),!0}catch{return!1}}async function oe(t){if(!Je(t))return 0;let e=await Xe(t,{withFileTypes:!0}),r=0;for(let i of e){if(i.isSymbolicLink())continue;let n=ut(t,i.name);if(i.isDirectory()){r+=await oe(n);continue}if(i.isFile()){let s=await hs(n);r+=s.size}}return r}async function ae(t){let e=pi(t.now,t.olderThanDays),r={};for(let i of t.targets)switch(i){case"logs":r.logs=await bs(t.entries,e,t.dryRun);break;case"work":r.work=await Cs(t.entries,t.dryRun);break;case"shared":r.shared=await xs(t.entries,t.dryRun,t.sharedDir);break}return r}async function bs(t,e,r){let i={freedBytes:0,removed:0,skipped:[]};for(let n of t){let s=await kt(ut(n.directory,Dt));for(let o of di(s,e)){if(!r)await Ze(o.path,{force:!0});i.removed++,i.freedBytes+=o.size}}return i}async function Cs(t,e){let r={freedBytes:0,removed:0,skipped:[]};for(let i of t){if(await gi(i.directory)){r.skipped.push(i.id);continue}let n=ut(i.directory,li);if(!Je(n))continue;let s=await Xe(n);if(s.length===0)continue;if(r.freedBytes+=await oe(n),r.removed+=s.length,e)continue;for(let o of s)await Ze(ut(n,o),{force:!0,recursive:!0})}return r}async function xs(t,e,r){let i={freedBytes:0,removed:0,skipped:[]},n=r??ut(tt,ys);if(!Je(n))return i;let o=(await Xe(n,{withFileTypes:!0})).filter((a)=>a.isDirectory()).map((a)=>a.name),u=await Rs(t);for(let a of hi(o,u)){let l=ut(n,a);if(i.freedBytes+=await oe(l),i.removed++,!e)await Ze(l,{force:!0,recursive:!0})}return i}async function Rs(t){let e=[];for(let r of t)try{let i=await ms(ut(r.directory,fs)),n=fi(i);if(n)e.push(n)}catch{}return e}function Ss(t,e){let r=t.split(".").map((s)=>Number.parseInt(s,Ye)),i=e.split(".").map((s)=>Number.parseInt(s,Ye)),n=Math.max(r.length,i.length);for(let s=0;s<n;s++){let o=r[s]??0,u=i[s]??0,a=Number.isNaN(o)?0:o,l=Number.isNaN(u)?0:u;if(a!==l)return l-a}return 0}function U(t){switch(t.provider){case"github":return new ie(t);default:throw Error(`Runner provider "${t.provider}" is not yet implemented`)}}var $i=0,Is={logs:"file(s)",shared:"version(s)",work:"item(s)"},yi=Q({days:{alias:"d",default:$i,description:"Override log retention",displayDefault:`config or ${Qt} 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 ue extends P{name="cleanup";description="Remove logs, workspaces, and old runner versions";args=yi;async execute(t){O(t.args,yi,"Run 'hydra cleanup --help' for supported options");let e=t.config.get("profiles");if(Object.keys(e).length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let r=ne(t.config.get("cleanup")),i=this.explicitTargets(t),n=i.length>0?i:r.targets,s=t.args.days>$i?t.args.days:r.olderThanDays;if(n.includes("work")&&!t.args.dryRun&&!t.args.yes){if(!await ct({message:"Delete _work contents (checkouts and caches) of stopped runners?"}))n=n.filter((a)=>a!=="work")}let o=await ae({dryRun:t.args.dryRun,entries:t.config.get("runners")??[],now:Date.now(),olderThanDays:s,targets:n});if(this.printReport(o,t.args.dryRun),t.args.dryRun)return;t.config.set("cleanup",{...t.config.get("cleanup"),lastRun:new Date().toISOString()})}explicitTargets(t){let e=[];if(t.args.logs)e.push("logs");if(t.args.work)e.push("work");if(t.args.shared)e.push("shared");return e}printReport(t,e){let r=[];for(let[s,o]of Object.entries(t)){if(!o)continue;let u=Is[s],a=ht(o.freedBytes),l=e?`would remove ${o.removed} ${u}, ${a}`:`removed ${o.removed} ${u}, freed ${a}`;if(r.push(`${p.bold(s)}: ${o.removed>0?l:p.dim("nothing to do")}`),o.skipped.length>0)r.push(p.dim(` skipped running runner(s): ${o.skipped.join(", ")}`))}if(r.length===0){w.info(p.dim("Nothing to clean."));return}let i=se(t),n=e?"Would free":"Freed";r.push(p.dim(`${n} ${ht(i)} total`)),w.info(r.join(`
|
|
88
|
+
`))}}async function le(t){try{let e=ne(t.config.get("cleanup"));if(!e.auto)return;if(!Qe(e,Date.now()))return;let r=await ae({dryRun:!1,entries:t.config.get("runners")??[],now:Date.now(),olderThanDays:e.olderThanDays,targets:e.targets});t.config.set("cleanup",{...t.config.get("cleanup"),lastRun:new Date().toISOString()});let i=se(r);if(i>0)w.info(p.dim(`Auto cleanup freed ${ht(i)}`))}catch(e){let r=e instanceof Error?e.message:String(e);w.warn(p.yellow(`Auto cleanup failed: ${r}`))}}import{existsSync as vi}from"fs";import{join as wi}from"path";function bt(t,e){if(t.length===0)return e;for(let r of t)if(!e.includes(r))throw new y(`Runner "${r}" not found`);return t}function j(t,e){let r=t.get("profiles");if(Object.keys(r).length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let i=e??t.get("defaultProfile")??Tt,n=r[i];if(!n)throw new y(`Profile "${i}" not found`);return{name:i,profile:n}}async function z(t){let e=t.get("profiles"),r=Object.keys(e);if(r.length===0)throw new y("No profiles configured","Run hydra init to set up a profile");if(r.length===1)return r[0];return pt({message:"Select profile",options:r.map((i)=>({label:i,value:i,hint:e[i]?.url}))})}var Es=M({profile:{description:"Profile to use"},count:{description:"Runner count override"}});class ce extends P{name="create";description="Download and register runners";positionals=Es;async execute(t){O(t.args,this.args,"Run 'hydra create --help' for supported options");let{name:e,profile:r}=t.interactive?j(t.config,await z(t.config)):j(t.config,t.positionals.profile),i=t.interactive?await this.promptCount(r.numberOfMachines):t.positionals.count?Number.parseInt(t.positionals.count,10):r.numberOfMachines;if(!i||i<1)throw new y("Runner count must be at least 1");let n=t.config.get("runners")??[],s=n.filter((m)=>m.profile===e),o=i-s.length;if(o<=0){w.warn(`Already have ${s.length} runner(s) for profile "${e}". Nothing to create.`);return}let u=U(r),a=W();a.start("Downloading runner binary...");let{version:l}=await u.download();a.stop(`Runner v${l} ready`);let f=new Set(n.map((m)=>m.id)),h=1;for(let m=0;m<o;){let v=`${r.name}-${h++}`;if(f.has(v))continue;m++;let I={createdAt:new Date().toISOString(),directory:wi(r.directory,v),id:v,name:v,profile:e,provider:r.provider,url:r.url},A=vi(I.directory);a.start(`Registering ${v}...`);try{await u.create([v])}finally{if(!A&&vi(wi(I.directory,".runner")))n.push(I),t.config.set("runners",n)}a.stop(`${p.green("+")} ${v}`)}let g=e===t.config.get("defaultProfile")?"":` ${e}`;w.info(`${p.green("Created")} ${o} runner(s) for "${e}". Run ${p.green(`hydra start${g}`)} to start them.`)}async promptCount(t){let e=await it({initialValue:String(t),message:"Number of runners to create",validate:(r)=>{let i=Number.parseInt(r??"",10);if(Number.isNaN(i)||i<1)return"Must be a positive number";return}});return Number.parseInt(e,10)}}import{existsSync as bi}from"fs";import{mkdir as Ci}from"fs/promises";var Ps=M({url:{description:"GitHub repository or organization URL"}}),_s=Q({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 pe extends P{name="init";description="Set up a runner profile";positionals=Ps;args=_s;prompts=!0;async execute(t){O(t.args,this.args,"Run 'hydra init --help' for supported options");let e=t.interactive?await this.promptProfileName(t):t.args.profile??Tt,r=!t.config.exists();if(!r&&t.config.get("profiles")[e]&&!t.args.force){if(!t.interactive)throw new y(`Profile "${e}" already exists. Use --force to overwrite.`);if(!await ct({initialValue:!1,message:`Profile "${e}" already exists. Overwrite?`}))return}await this.ensureDirectories();let n=t.interactive?await this.runInitForm():this.buildProfileFromArgs(t),s=r?{}:{...t.config.get("profiles")};if(s[e]=n,t.config.set("profiles",s),!t.config.get("defaultProfile"))t.config.set("defaultProfile",e);gt([`${p.dim("Profile:")} ${e}`,`${p.dim("URL:")} ${n.url}`,`${p.dim("Runners:")} ${n.numberOfMachines}`,`${p.dim("Name:")} ${n.name}`,n.labels?`${p.dim("Labels:")} ${n.labels}`:"","",`Run ${p.green(`${Zt} create${e!==t.config.get("defaultProfile")?` ${e}`:""}`)} to provision runners.`].filter(Boolean).join(`
|
|
89
|
+
`),p.green(r?"Hydra initialized":`Profile "${e}" added`))}async promptProfileName(t){return it({initialValue:t.args.profile??Tt,message:"Profile name"})}async ensureDirectories(){if(!bi(tt))await Ci(tt,{recursive:!0});if(!bi(At))await Ci(At,{recursive:!0})}async runInitForm(){let t=await jt({url:()=>it({message:"GitHub repository or organization URL",placeholder:"https://github.com/owner/repo",validate:(e)=>{if(!e)return"URL is required";try{mt(e)}catch{return"Must be a GitHub repository or organization URL (https://github.com/<owner>/<repo> or https://github.com/<org>)"}return}}),name:()=>it({initialValue:"runner",message:"Base name for runners",placeholder:"runner"}),runners:()=>it({initialValue:"1",message:"Number of runners",placeholder:"1",validate:(e)=>{if(!e)return"Must be a positive number";let r=Number.parseInt(e,10);if(Number.isNaN(r)||r<1)return"Must be a positive number";return}}),labels:()=>it({message:"Additional labels (comma-separated, optional)",placeholder:"self-hosted,macOS,ARM64"})},{onCancel:()=>{throw new Y}});return{directory:At,labels:t.labels||void 0,name:t.name,numberOfMachines:Number.parseInt(t.runners,10)||1,os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:t.url}}buildProfileFromArgs(t){if(!t.positionals.url)throw new y("URL is required","Usage: hydra init <url>");return this.validateUrl(t.positionals.url),this.validateRunnerCount(t.args.runners),{directory:At,labels:t.args.labels,name:t.args.name??"runner",numberOfMachines:t.args.runners??1,os:this.detectOs(),overwrite:!1,provider:"github",run:!1,url:t.positionals.url}}validateUrl(t){try{mt(t)}catch(e){throw new y(e instanceof Error?e.message:`Invalid GitHub URL: ${t}`,"Expected https://github.com/<owner>/<repo> or https://github.com/<org>")}}validateRunnerCount(t){if(t!==void 0&&t<1)throw new y("Runner count must be at least 1")}detectOs(){let t=process.platform;if(t==="darwin")return"osx";if(t==="win32")return"windows";return"linux"}}import{existsSync as As}from"fs";import{readFile as Ts}from"fs/promises";var Ds=100,ks={runner:"runner daemon log",worker:"job log"},Ls=Q({lines:{alias:"n",default:Ds,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"}}),Fs=M({id:{description:"Runner ID"}});class de extends P{name="logs";description="Show recent runner logs";args=Ls;positionals=Fs;async execute(t){let e=t.config.get("runners")??[];if(e.length===0)throw new y("No runners found","Run hydra create to provision runners");let r=await this.resolveEntry(t,e),i=t.config.get("profiles")[r.profile];if(!i)throw new y(`Profile "${r.profile}" not found for runner "${r.id}"`,"Run hydra init to set it up");if(!As(r.directory))throw new y(`Runner directory not found: ${r.directory}`,"Run hydra create to provision this runner");let s=await U(i).logFiles(r.id);if(s.length===0)this.noLogs(r.id);if(t.args.list){this.printList(r,s);return}let o=this.selectFile(t,r,s);if(t.args.open){await this.openFile(o);return}await this.printTail(r,o,t.args.lines)}async resolveEntry(t,e){let r=t.positionals.id;if(r){let n=e.find((s)=>s.id===r);if(!n)throw new y(`Runner "${r}" not found`,`Known runners: ${e.map((s)=>s.id).join(", ")}`);return n}if(t.interactive)return pt({message:"Select runner",options:e.map((n)=>({hint:n.profile,label:n.name,value:n}))});let i=e[0];if(e.length===1&&i)return i;throw new y("Multiple runners found",`Pass a runner id: hydra logs <id> (${e.map((n)=>n.id).join(", ")})`)}selectFile(t,e,r){if(t.args.runner){let n=r.find((s)=>s.type==="runner");if(!n)throw new y(`No runner daemon logs found for "${e.id}"`,"Start the runner first: hydra start");return n}let i=He(r,"worker");if(!i)this.noLogs(e.id);if(i.fallback)w.warn(p.yellow("No job (Worker) logs yet; showing the runner daemon log instead"));return i.file}noLogs(t){throw new y(`No logs found for runner "${t}"`,"Logs appear once the runner has started; run hydra start")}printList(t,e){let r=[`${p.bold(t.name)} ${p.dim(t.directory)}`];for(let i of e){let n=i.type==="worker"?p.green("worker"):p.blue("runner");r.push(` ${n} ${i.name} ${p.dim(`${i.mtime.toISOString()} \xB7 ${ht(i.size)}`)}`)}w.info(r.join(`
|
|
90
|
+
`))}async printTail(t,e,r){let i=await Ts(e.path,"utf-8"),n=[`${p.bold(t.name)} ${p.dim(ks[e.type])}`,p.dim(e.path),p.dim(`Last modified: ${e.mtime.toISOString()}`)];w.info(n.join(`
|
|
91
|
+
`)),console.log(Be(i,r))}async openFile(t){let e=(process.env.EDITOR??"").split(" ").filter(Boolean),r=e[0];if(r){await Bun.spawn([r,...e.slice(1),t.path],{stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited;return}if(process.platform==="darwin"){await Bun.$`open ${t.path}`.quiet();return}throw new y("No editor configured","Set $EDITOR to open log files")}}var Os=M({name:{description:"Profile name to set as default"}});class tr extends P{name="default";description="Set the default profile";positionals=Os;async execute(t){O(t.args,this.args,"Run 'hydra profile default --help' for supported options");let e=t.interactive?await z(t.config):t.positionals.name;if(!e)throw new y("Profile name is required","Usage: hydra profile default <name>");let{name:r}=j(t.config,e);if(t.config.get("defaultProfile")===r){w.info(`"${r}" is already the default profile.`);return}t.config.set("defaultProfile",r),w.info(`${p.green("Default profile set to")} "${r}".`)}}class er extends P{name="list";description="List profiles";async execute(t){let e=t.config.get("profiles"),r=Object.keys(e);if(r.length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let i=t.config.get("runners")??[],n=t.config.get("defaultProfile");for(let s of r){let o=e[s],a=await U(o).list(),l=i.filter((v)=>v.profile===s),f=new Set(a.filter((v)=>v.status==="running").map((v)=>v.id)),h=l.filter((v)=>f.has(v.id)).length,d=s===n,g=[`${p.dim("URL:")} ${o.url}`,`${p.dim("Provider:")} ${o.provider}`,`${p.dim("OS:")} ${o.os}`,`${p.dim("Name:")} ${o.name}`,`${p.dim("Runners:")} ${l.length}/${o.numberOfMachines} created, ${p.green(`${h} running`)}`];if(o.labels)g.push(`${p.dim("Labels:")} ${o.labels}`);let m=d?`${s} ${p.dim("(default)")}`:s;gt(g.join(`
|
|
92
|
+
`),m)}w.info(p.dim(`${r.length} profile(s)`))}}import{rm as Ns}from"fs/promises";import{join as Ms}from"path";var Us=M({name:{description:"Profile name to remove"}}),Vs=Q({yes:{alias:"y",default:!1,description:"Skip runner removal confirmation",type:"boolean"}});class rr extends P{name="remove";description="Delete a profile and its runners";positionals=Us;args=Vs;async execute(t){O(t.args,this.args,"Run 'hydra profile remove --help' for supported options");let e=t.interactive?await z(t.config):t.positionals.name;if(!e)throw new y("Profile name is required","Usage: hydra profile remove <name>");let{profile:r}=j(t.config,e),i=t.config.get("runners")??[],n=i.filter((a)=>a.profile===e);if(n.length>0){if(!t.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 ct({initialValue:!0,message:`This will stop and remove ${n.length} runner(s). Continue?`}))return}await this.removeRunners(t,r,n.map((l)=>l.id));let a=i.filter((l)=>l.profile!==e);t.config.set("runners",a)}let{[e]:s,...o}=t.config.get("profiles");if(t.config.set("profiles",o),t.config.get("defaultProfile")===e){let a=Object.keys(o);t.config.set("defaultProfile",a[0])}w.info(`${p.green("Removed")} profile "${e}".`)}async removeRunners(t,e,r){let i=U(e),n=W();for(let s of r)n.start(`Stopping and removing ${s}...`),await i.stop([s]),await i.remove([s]),await Ns(Ms(e.directory,s),{force:!0,recursive:!0}),t.config.set("runners",(t.config.get("runners")??[]).filter((o)=>o.id!==s)),n.stop(`${p.red("-")} ${s}`)}}class me extends P{name="profile";description="Manage profiles";init(){this.registerSubcommands([new er,new rr,new tr])}}import{rm as Gs}from"fs/promises";import{join as js}from"path";var Hs=M({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class he extends P{name="remove";description="Deregister and delete runners";positionals=Hs;async execute(t){O(t.args,this.args,"Run 'hydra remove --help' for supported options");let{name:e,profile:r}=t.interactive?j(t.config,await z(t.config)):j(t.config,t.positionals.profile),n=(t.config.get("runners")??[]).filter((a)=>a.profile===e);if(n.length===0)throw new y(`No runners found for profile "${e}"`,"Run hydra create to provision runners");let s=t.interactive?await this.promptRunnerSelection(n.map((a)=>a.id)):bt(t.positionals.ids??[],n.map((a)=>a.id)),o=U(r),u=W();for(let a of s)u.start(`Stopping and removing ${a}...`),await o.stop([a]),await o.remove([a]),await Gs(js(r.directory,a),{force:!0,recursive:!0}),t.config.set("runners",(t.config.get("runners")??[]).filter((l)=>l.id!==a)),u.stop(`${p.red("-")} ${a}`);w.info(`${p.green("Removed")} ${s.length} runner(s).`)}async promptRunnerSelection(t){return dt({message:"Select runners to remove",options:t.map((e)=>({label:e,value:e})),required:!0})}}var Bs=M({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class fe extends P{name="start";description="Start runners";positionals=Bs;async execute(t){O(t.args,this.args,"Run 'hydra start --help' for supported options");let{name:e,profile:r}=t.interactive?j(t.config,await z(t.config)):j(t.config,t.positionals.profile),n=(t.config.get("runners")??[]).filter((d)=>d.profile===e);if(n.length===0)throw new y(`No runners found for profile "${e}"`,"Run hydra create to provision runners");let s=U(r),o=W();o.start("Fetching runner status...");let u=await s.list();o.stop("Runner status fetched");let a=new Set(u.filter((d)=>d.status==="running").map((d)=>d.id)),l=n.map((d)=>d.id).filter((d)=>!a.has(d)),f=t.interactive?await this.promptRunnerSelection(l):bt(t.positionals.ids??[],n.map((d)=>d.id)),h=0;for(let d of f){if(a.has(d)){o.start(""),o.stop(`${p.dim("\u25CF")} ${d} ${p.dim("already running")}`);continue}o.start(`Starting ${d}...`),await s.start([d]),o.stop(`${p.green("\u25B6")} ${d}`),h++}w.info(`${p.green("Started")} ${h} runner(s).`),await le(t)}async promptRunnerSelection(t){if(t.length===0)throw new y("All runners are already running");return dt({message:"Select runners to start",options:t.map((e)=>({label:e,value:e})),required:!0})}}var Ws={registered:p.yellow,running:p.green,stopped:p.red,unknown:p.dim};class ge extends P{name="status";description="Show status across profiles";async execute(t){let e=t.config.get("profiles"),r=Object.keys(e);if(r.length===0)throw new y("No profiles configured","Run hydra init to set up a profile");let i=t.config.get("runners")??[],n=0,s=0,o=[];for(let u of r){let a=e[u],f=await U(a).list();if(o.length>0)o.push("");o.push(`${p.bold(u)} ${p.dim(a.url)}`);let h=new Set(i.filter((g)=>g.profile===u).map((g)=>g.id)),d=f.filter((g)=>h.has(g.id)).sort((g,m)=>g.name.localeCompare(m.name,void 0,{numeric:!0}));this.formatRunners(d,o),n+=d.length,s+=d.filter((g)=>g.status==="running").length}o.push(""),o.push(p.dim(`${n} runner(s) total, ${s} running`)),w.info(o.join(`
|
|
93
|
+
`))}formatRunners(t,e){if(t.length===0){e.push(p.dim(" No runners."));return}for(let r of t){let i=Ws[r.status]??p.dim,n=r.pid?p.dim(` (pid: ${r.pid})`):"";e.push(` ${i("\u25CF")} ${r.name} ${i(r.status)}${n}`)}}}var Ks=M({profile:{description:"Profile to use"},ids:{description:"Runner IDs (all by default)",variadic:!0}});class ye extends P{name="stop";description="Stop runners";positionals=Ks;async execute(t){O(t.args,this.args,"Run 'hydra stop --help' for supported options");let{name:e,profile:r}=t.interactive?j(t.config,await z(t.config)):j(t.config,t.positionals.profile),n=(t.config.get("runners")??[]).filter((d)=>d.profile===e);if(n.length===0)throw new y(`No runners found for profile "${e}"`,"Run hydra create to provision runners");let s=U(r),o=W();o.start("Fetching runner status...");let u=await s.list();o.stop("Runner status fetched");let a=new Set(u.filter((d)=>d.status==="running").map((d)=>d.id)),l=n.map((d)=>d.id).filter((d)=>a.has(d)),f=t.interactive?await this.promptRunnerSelection(l):bt(t.positionals.ids??[],n.map((d)=>d.id)),h=0;for(let d of f){if(!a.has(d)){o.start(""),o.stop(`${p.dim("\u25CF")} ${d} ${p.dim("not running")}`);continue}o.start(`Stopping ${d}...`),await s.stop([d]),o.stop(`${p.red("\u25A0")} ${d}`),h++}w.info(`${p.green("Stopped")} ${h} runner(s).`)}async promptRunnerSelection(t){if(t.length===0)throw new y("No runners are currently running");return dt({message:"Select runners to stop",options:t.map((e)=>({label:e,value:e})),required:!0})}}class $e extends P{name="update";description="Update runner binaries";async execute(t){O(t.args,this.args,"Run 'hydra update --help' for supported options");let e=t.config.get("profiles"),r=t.config.get("runners")??[];if(r.length===0)throw new y("No runners found","Run hydra create to provision runners");let i=W(),n=Map.groupBy(r,(o)=>o.profile),s=0;for(let[o,u]of n){let a=e[o];if(!a)continue;let l=U(a);i.start(`Checking for updates for "${o}"...`);let{version:f}=await l.download();i.stop(`Latest: v${f}`);let h=await l.list(),d=new Set(h.filter((g)=>g.status==="running").map((g)=>g.id));for(let g of u){if(await l.currentVersion(g.id)===f)continue;let m=d.has(g.id);if(i.start(`Updating ${g.id}...`),m)await l.stop([g.id]);if(await l.update([g.id]),m)await l.start([g.id]);s++;let v=m?` ${p.dim("(restarted)")}`:"";i.stop(`${p.green("\u2713")} ${g.id}${v}`)}}w.info(s>0?`${p.green("Updated")} ${s} runner(s).`:"All runners are already on the latest version."),await le(t)}}class xi extends Ge{constructor(){super(new je(Jr,Xr),{bin:Zt,clearOnStart:!0,description:"Manage GitHub Actions runners on this machine.",exitLabel:"Exit",goodbyeMessage:"Heads down.",name:"HYDRA",promptMessage:"What do you need?",version:Yr})}init(){this.registerCommands([new pe,new ce,new fe,new ye,new ge,new de,new ue,new he,new $e,new me])}}var qs=new xi;qs.run();
|
package/package.json
CHANGED