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