@r5n/sisyphus 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +125 -234
- package/dist/cli.js +101 -100
- package/package.json +2 -6
package/dist/cli.js
CHANGED
|
@@ -1,116 +1,116 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`),u=!1;for(let f=0;f<
|
|
5
|
-
`){if(s)r+=
|
|
6
|
-
`){if(i&&
|
|
7
|
-
`)}var V
|
|
8
|
-
`),s=0,o=e;for(let g of i){if(o<=g.length)break;o-=g.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+n)),o=Math.min(o,i[s].length)+t;o<0&&s>0;)s--,o+=i[s].length+1;for(;o>i[s].length&&s<i.length-1;)o-=i[s].length+1,s++;o=Math.max(0,Math.min(i[s].length,o));let a=0;for(let g=0;g<s;g++)a+=i[g].length+1;return a+o}var
|
|
3
|
+
var ei=Object.create;var{getPrototypeOf:ti,defineProperty:Cn,getOwnPropertyNames:ni}=Object;var ri=Object.prototype.hasOwnProperty;function ii(e){return this[e]}var si,oi,$n=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?si??=new WeakMap:oi??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?ei(ti(e)):{};let o=t||!e||!e.__esModule?Cn(n,"default",{value:e,enumerable:!0}):n;for(let a of ni(e))if(!ri.call(o,a))Cn(o,a,{get:ii.bind(e,a),enumerable:!0});if(r)i.set(e,o);return o};var ai=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var It=ai((Wo,Un)=>{var Mt={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},vi={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},ki={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?Mt.up():"");if(e)t+=Mt.left;return t}};Un.exports={cursor:Mt,scroll:vi,erase:ki,beep:"\x07"}});class te extends Error{constructor(e="Operation cancelled"){super(e)}}class d extends Error{hint;constructor(e,t){super(e);this.hint=t}}import{styleText as Ze}from"util";import{stdout as Et,stdin as Wn}from"process";import*as le from"readline";import Ci from"readline";var Rn=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let n=0;e.lastIndex=0;while(e.test(t))n+=1;return t.length-n}})(),Sn=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},Mn=(e)=>{return e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141};var ci=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,gi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,In=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,pi=/\t{1,1000}/y,Dn=/[\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,mi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,li=/\p{M}+/gu,ui={limit:1/0,ellipsis:""},Fn=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?Fn(i,ui,n).width:0),o=0,a=n.controlWidth??0,g=n.tabWidth??8,p=n.emojiWidth??2,u=2,f=n.regularWidth??1,y=n.wideWidth??2,b=[[mi,f],[ci,0],[gi,a],[pi,g],[Dn,p],[In,y]],h=0,P=0,j=e.length,B=0,k=!1,H=j,L=Math.max(0,r-s),C=0,G=0,O=0,E=0;e:while(!0){if(G>C||P>=j&&P>h){let U=e.slice(C,G)||e.slice(h,P);B=0;for(let ne of U.replaceAll(li,"")){let z=ne.codePointAt(0)||0;if(Sn(z))E=2;else if(Mn(z))E=y;else E=f;if(O+E>L)H=Math.min(H,Math.max(C,h)+B);if(O+E>r){k=!0;break e}B+=ne.length,O+=E}C=G=0}if(P>=j)break e;for(let U=0,ne=b.length;U<ne;U++){let[z,Ve]=b[U];if(z.lastIndex=P,z.test(e)){if(B=z===In?Rn(e.slice(P,z.lastIndex)):z===Dn?1:z.lastIndex-P,E=B*Ve,O+E>L)H=Math.min(H,P+Math.floor((L-O)/Ve));if(O+E>r){k=!0;break e}O+=E,C=h,G=P,P=h=z.lastIndex;continue e}}P+=1}return{width:k?L:O,index:k?H:j,truncated:k,ellipsed:k&&r>=s}},jn=Fn;var hi={limit:1/0,ellipsis:"",ellipsisWidth:0},fi=(e,t={})=>{return jn(e,hi,t).width},Y=fi;var Ye="\x1B",Nn="\x9B",di=39,Rt="\x07",Bn="[",yi="]",xn="m",St=`${yi}8;;`,En=new RegExp(`(?:\\${Bn}(?<code>\\d+)m|\\${St}(?<uri>.*)${Rt})`,"y"),Ln=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},On=(e)=>`${Ye}${Bn}${e}${xn}`,An=(e)=>`${Ye}${St}${e}${Rt}`,$t=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,s=!1,o=e.at(-1),a=o===void 0?0:Y(o),g=r.next(),p=r.next(),u=0;while(!g.done){let f=g.value,y=Y(f);if(a+y<=n)e[e.length-1]+=f;else e.push(f),a=0;if(f===Ye||f===Nn)i=!0,s=t.startsWith(St,u+1);if(i){if(s){if(f===Rt)i=!1,s=!1}else if(f===xn)i=!1}else if(a+=y,a===n&&!p.done)e.push(""),a=0;g=p,p=r.next(),u+=f.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},bi=(e)=>{let t=e.split(" "),n=t.length;while(n){if(Y(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},Pi=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",i,s,o=e.split(" "),a=[""],g=0;for(let f=0;f<o.length;f++){let y=o[f];if(n.trim!==!1){let h=a.at(-1)??"",P=h.trimStart();if(h.length!==P.length)a[a.length-1]=P,g=Y(P)}if(f!==0){if(g>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),g=0;if(g||n.trim===!1)a[a.length-1]+=" ",g++}let b=Y(y);if(n.hard&&b>t){let h=t-g,P=1+Math.floor((b-h-1)/t);if(Math.floor((b-1)/t)<P)a.push("");$t(a,y,t),g=Y(a.at(-1)??"");continue}if(g+b>t&&g&&b){if(n.wordWrap===!1&&g<t){$t(a,y,t),g=Y(a.at(-1)??"");continue}a.push(""),g=0}if(g+b>t&&n.wordWrap===!1){$t(a,y,t),g=Y(a.at(-1)??"");continue}a[a.length-1]+=y,g+=b}if(n.trim!==!1)a=a.map((f)=>bi(f));let p=a.join(`
|
|
4
|
+
`),u=!1;for(let f=0;f<p.length;f++){let y=p[f];if(r+=y,!u){if(u=y>="\uD800"&&y<="\uDBFF",u)continue}else u=!1;if(y===Ye||y===Nn){En.lastIndex=f+1;let h=En.exec(p)?.groups;if(h?.code!==void 0){let P=Number.parseFloat(h.code);i=P===di?void 0:P}else if(h?.uri!==void 0)s=h.uri.length===0?void 0:h.uri}if(p[f+1]===`
|
|
5
|
+
`){if(s)r+=An("");let b=i?Ln(i):void 0;if(i&&b)r+=On(b)}else if(y===`
|
|
6
|
+
`){if(i&&Ln(i))r+=On(i);if(s)r+=An(s)}}return r},wi=/\r?\n/;function re(e,t,n){return String(e).normalize().split(wi).map((r)=>Pi(r,t,n)).join(`
|
|
7
|
+
`)}var V=$n(It(),1);import{ReadStream as Gn}from"tty";function oe(e,t,n){if(!n.some((o)=>!o.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),s=r<0?i:r>i?0:r;return n[s]?.disabled?oe(s,t<0?-1:1,n):s}function Ke(e,t,n,r){let i=r.split(`
|
|
8
|
+
`),s=0,o=e;for(let g of i){if(o<=g.length)break;o-=g.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+n)),o=Math.min(o,i[s].length)+t;o<0&&s>0;)s--,o+=i[s].length+1;for(;o>i[s].length&&s<i.length-1;)o-=i[s].length+1,s++;o=Math.max(0,Math.min(i[s].length,o));let a=0;for(let g=0;g<s;g++)a+=i[g].length+1;return a+o}var $i=["up","down","left","right","space","enter","cancel"],Ri=["January","February","March","April","May","June","July","August","September","October","November","December"],W={actions:new Set($i),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:[...Ri],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function Lt(e,t){if(typeof e=="string")return W.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Lt(n,t))return!0;return!1}function Si(e,t){if(e===t)return;let n=e.split(`
|
|
9
9
|
`),r=t.split(`
|
|
10
|
-
`),i=Math.max(n.length,r.length),s=[];for(let o=0;o<i;o++)n[o]!==r[o]&&s.push(o);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var
|
|
11
|
-
`).map((a,g,
|
|
12
|
-
`)}function
|
|
13
|
-
`),
|
|
14
|
-
`).length-1;this.output.write(V.cursor.move(-999,e*-1))}render(){let e=re(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(V.cursor.hide);else{let t=
|
|
10
|
+
`),i=Math.max(n.length,r.length),s=[];for(let o=0;o<i;o++)n[o]!==r[o]&&s.push(o);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var Mi=globalThis.process.platform.startsWith("win"),Ft=Symbol("clack:cancel");function Ae(e){return e===Ft}function Te(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Jn({input:e=Wn,output:t=Et,overwrite:n=!0,hideCursor:r=!0}={}){let i=le.createInterface({input:e,output:t,prompt:"",tabSize:1});le.emitKeypressEvents(e,i),e instanceof Gn&&e.isTTY&&e.setRawMode(!0);let s=(o,{name:a,sequence:g})=>{let p=String(o);if(Lt([p,a,g],"cancel")){r&&t.write(V.cursor.show),process.exit(0);return}if(!n)return;le.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{le.clearLine(t,1,()=>{e.once("keypress",s)})})};return r&&t.write(V.cursor.hide),e.once("keypress",s),()=>{e.off("keypress",s),r&&t.write(V.cursor.show),e instanceof Gn&&e.isTTY&&!Mi&&e.setRawMode(!1),i.terminal=!1,i.close()}}var Ne=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Ot=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function ue(e,t,n,r=n,i=n,s){let o=Ne(e??Et);return re(t,o-n.length,{hard:!0,trim:!1}).split(`
|
|
11
|
+
`).map((a,g,p)=>{let u=s?s(a,g):a;return g===0?`${r}${u}`:g===p.length-1?`${i}${u}`:`${n}${u}`}).join(`
|
|
12
|
+
`)}function Vn(e,t){if("~standard"in e){let n=e["~standard"].validate(t);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return e(t)}class ae{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=Wn,output:r=Et,render:i,signal:s,...o}=e;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=t,this._abortSignal=s,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let i of n)i.cb(...t),i.once&&r.push(()=>n.splice(n.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Ft);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Ci.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),Te(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(V.cursor.show),this.output.off("resize",this.render),Te(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(V.cursor.show),this.output.off("resize",this.render),Te(this.input,!1),e(Ft)})})}_isActionKey(e,t){return e==="\t"}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),t?.name&&(!this._track&&W.aliases.has(t.name)&&this.emit("cursor",W.aliases.get(t.name)),W.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let n=Vn(this.opts.validate,this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Lt([e,t?.name,t?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
13
|
+
`),Te(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=re(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
14
|
+
`).length-1;this.output.write(V.cursor.move(-999,e*-1))}render(){let e=re(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(V.cursor.hide);else{let t=Si(this._prevFrame,e),n=Ot(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),s=t.lines.find((o)=>o>=r);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(V.cursor.move(0,s-i)),this.output.write(V.erase.lines(1));let o=e.split(`
|
|
15
15
|
`);this.output.write(o[s]),this._prevFrame=e,this.output.write(V.cursor.move(0,o.length-s-1));return}else if(t.lines.length>1){if(r<i)s=r;else{let a=s-i;a>0&&this.output.write(V.cursor.move(0,a))}this.output.write(V.erase.down());let o=e.split(`
|
|
16
16
|
`).slice(s);this.output.write(o.join(`
|
|
17
|
-
`)),this._prevFrame=e;return}}this.output.write(V.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function wi(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex((r)=>r.value===e);return n!==-1?n:0}function vi(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function ki(e,t){if(t)return e?t:t[0]}var Ci=class extends ae{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#i="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return Qe(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let t=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${t}${Qe("inverse",n)}${r}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(t){super(t),this.#s=t.options,this.#a=t.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=t.multiple===!0,this.#e=typeof t.options=="function"?t.filter:t.filter??vi;let r;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?r=t.initialValue:r=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let s=n.findIndex((o)=>o.value===i);s!==-1&&(this.toggleSelected(i),this.#t=s)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(i,s)=>this.#n(i,s)),this.on("userInput",(i)=>this.#r(i))}_isActionKey(t,n){return t==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&t!==void 0&&t!==""}#n(t,n){let r=n.name==="up",i=n.name==="down",s=n.name==="return",o=this.userInput===""||this.userInput==="\t",a=this.#a,g=this.options,m=a!==void 0&&a!==""&&g.some((u)=>!u.disabled&&(this.#e?this.#e(a,u):!0));if(n.name==="tab"&&o&&m){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}r||i?(this.#t=oe(this.#t,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=ki(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter((n)=>n!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#r(t){if(t!==this.#i){this.#i=t;let n=this.options;t&&this.#e?this.filteredOptions=n.filter((s)=>this.#e?.(t,s)):this.filteredOptions=[...n];let r=wi(this.focusedValue,this.filteredOptions);this.#t=oe(r,0,this.filteredOptions);let i=this.filteredOptions[this.#t];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class At extends ae{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(V.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var $i={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function xn(e){return[...e].map((t)=>$i[t])}function Ri(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of t)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function Ft(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Te(e){return{year:Ft(e.year),month:Ft(e.month),day:Ft(e.day)}}function jt(e,t){return new Date(e||2001,t||1,0).getDate()}function Vn(e){let{year:t,month:n,day:r}=Te(e);if(!t||t<0||t>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(t,n-1,r));if(!(i.getUTCFullYear()!==t||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:t,month:n,day:r}}function qn(e){let t=Vn(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function Si(e,t,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,s=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:s?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:s&&t.year===s.year?s.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:s&&t.year===s.year&&t.month===s.month?s.day:jt(t.year,t.month)}}class zn extends ae{#t;#i;#e;#s;#a;#n={segmentIndex:0,positionInSegment:0};#r=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#n}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#i}get formattedValue(){return this.#p(this.#e)}#p(e){return this.#t.map((t)=>e[t.type]).join(this.#i)}#c(){this._setUserInput(this.#p(this.#e)),this._setValue(qn(this.#e)??void 0)}constructor(e){let t=e.format?{segments:xn(e.format),separator:e.separator??"/"}:Ri(e.locale),n=e.separator??t.separator,r=e.format?xn(e.format):t.segments,i=e.initialValue??e.defaultValue,s=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},o=r.map((a)=>s[a.type]).join(n);super({...e,initialUserInput:o},!1),this.#t=r,this.#i=n,this.#e=s,this.#s=e.minDate,this.#a=e.maxDate,this.#c(),this.on("cursor",(a)=>this.#h(a)),this.on("key",(a,g)=>this.#f(a,g)),this.on("finalize",()=>this.#d(e))}#g(){let e=Math.max(0,Math.min(this.#n.segmentIndex,this.#t.length-1)),t=this.#t[e];if(t)return this.#n.positionInSegment=Math.max(0,Math.min(this.#n.positionInSegment,t.len-1)),{segment:t,index:e}}#m(e){this.inlineError="",this.#o=null;let t=this.#g();t&&(this.#n.segmentIndex=Math.max(0,Math.min(this.#t.length-1,t.index+e)),this.#n.positionInSegment=0,this.#r=!0)}#l(e){let t=this.#g();if(!t)return;let{segment:n}=t,r=this.#e[n.type],i=!r||r.replace(/_/g,"")==="",s=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,o=Si(n.type,Te(this.#e),this.#s,this.#a),a;i?a=e===1?o.min:o.max:a=Math.max(Math.min(o.max,s+e),o.min),this.#e={...this.#e,[n.type]:a.toString().padStart(n.len,"0")},this.#r=!0,this.#o=null,this.#c()}#h(e){if(e)switch(e){case"right":return this.#m(1);case"left":return this.#m(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#f(e,t){if(t?.name==="backspace"||t?.sequence==="\x7F"||t?.sequence==="\b"||e==="\x7F"||e==="\b"){this.inlineError="";let n=this.#g();if(!n)return;if(!this.#e[n.segment.type].replace(/_/g,"")){this.#m(-1);return}this.#e[n.segment.type]="_".repeat(n.segment.len),this.#r=!0,this.#n.positionInSegment=0,this.#c();return}if(t?.name==="tab"){this.inlineError="";let n=this.#g();if(!n)return;let r=t.shift?-1:1,i=n.index+r;i>=0&&i<this.#t.length&&(this.#n.segmentIndex=i,this.#n.positionInSegment=0,this.#r=!0);return}if(e&&/^[0-9]$/.test(e)){let n=this.#g();if(!n)return;let{segment:r}=n,i=!this.#e[r.type].replace(/_/g,"");if(this.#r&&this.#o!==null&&!i){let y=this.#o+e,b={...this.#e,[r.type]:y},h=this.#u(b,r);if(h){this.inlineError=h,this.#o=null,this.#r=!1;return}this.inlineError="",this.#e[r.type]=y,this.#o=null,this.#r=!1,this.#c(),n.index<this.#t.length-1&&(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0);return}this.#r&&!i&&(this.#e[r.type]="_".repeat(r.len),this.#n.positionInSegment=0),this.#r=!1,this.#o=null;let s=this.#e[r.type],o=s.indexOf("_"),a=o>=0?o:Math.min(this.#n.positionInSegment,r.len-1);if(a<0||a>=r.len)return;let g=s.slice(0,a)+e+s.slice(a+1),m=!1;if(a===0&&s==="__"&&(r.type==="month"||r.type==="day")){let y=Number.parseInt(e,10);g=`0${e}`,m=y<=(r.type==="month"?1:2)}if(r.type==="year"&&(g=(s.replace(/_/g,"")+e).padStart(r.len,"_")),!g.includes("_")){let y={...this.#e,[r.type]:g},b=this.#u(y,r);if(b){this.inlineError=b;return}}this.inlineError="",this.#e[r.type]=g;let u=g.includes("_")?void 0:Vn(this.#e);if(u){let{year:y,month:b}=u,h=jt(y,b);this.#e={year:String(Math.max(0,Math.min(9999,y))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,b))).padStart(2,"0"),day:String(Math.max(1,Math.min(h,u.day))).padStart(2,"0")}}this.#c();let f=g.indexOf("_");m?(this.#r=!0,this.#o=e):f>=0?this.#n.positionInSegment=f:o>=0&&n.index<this.#t.length-1?(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0):this.#n.positionInSegment=Math.min(a+1,r.len-1)}}#u(e,t){let{month:n,day:r}=Te(e);if(t.type==="month"&&(n<0||n>12))return W.date.messages.invalidMonth;if(t.type==="day"&&(r<0||r>31))return W.date.messages.invalidDay(31,"any month")}#d(e){let{year:t,month:n,day:r}=Te(this.#e);if(t&&n&&r){let i=jt(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=qn(this.#e)??e.defaultValue??void 0}}var Mi=class extends ae{options;cursor=0;#t;getGroupItems(t){return this.options.filter((n)=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(t!==void 0)if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((s)=>s.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(t.value);this.value=n?this.value.filter((r)=>r!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((s)=>({...s,group:r}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),this.#t?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Ii=new Set(["up","down","left","right"]);class Yn extends ae{#t=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}\u2588`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return n===`
|
|
17
|
+
`)),this._prevFrame=e;return}}this.output.write(V.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function Ii(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex((r)=>r.value===e);return n!==-1?n:0}function Di(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function Fi(e,t){if(t)return e?t:t[0]}var ji=class extends ae{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#i="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return Ze(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let t=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${t}${Ze("inverse",n)}${r}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(t){super(t),this.#s=t.options,this.#a=t.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=t.multiple===!0,this.#e=typeof t.options=="function"?t.filter:t.filter??Di;let r;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?r=t.initialValue:r=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let s=n.findIndex((o)=>o.value===i);s!==-1&&(this.toggleSelected(i),this.#t=s)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(i,s)=>this.#n(i,s)),this.on("userInput",(i)=>this.#r(i))}_isActionKey(t,n){return t==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&t!==void 0&&t!==""}#n(t,n){let r=n.name==="up",i=n.name==="down",s=n.name==="return",o=this.userInput===""||this.userInput==="\t",a=this.#a,g=this.options,p=a!==void 0&&a!==""&&g.some((u)=>!u.disabled&&(this.#e?this.#e(a,u):!0));if(n.name==="tab"&&o&&p){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}r||i?(this.#t=oe(this.#t,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=Fi(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter((n)=>n!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#r(t){if(t!==this.#i){this.#i=t;let n=this.options;t&&this.#e?this.filteredOptions=n.filter((s)=>this.#e?.(t,s)):this.filteredOptions=[...n];let r=Ii(this.focusedValue,this.filteredOptions);this.#t=oe(r,0,this.filteredOptions);let i=this.filteredOptions[this.#t];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class At extends ae{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(V.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var Ei={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function qn(e){return[...e].map((t)=>Ei[t])}function Li(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of t)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function Dt(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function _e(e){return{year:Dt(e.year),month:Dt(e.month),day:Dt(e.day)}}function jt(e,t){return new Date(e||2001,t||1,0).getDate()}function zn(e){let{year:t,month:n,day:r}=_e(e);if(!t||t<0||t>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(t,n-1,r));if(!(i.getUTCFullYear()!==t||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:t,month:n,day:r}}function Hn(e){let t=zn(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function Oi(e,t,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,s=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:s?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:s&&t.year===s.year?s.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:s&&t.year===s.year&&t.month===s.month?s.day:jt(t.year,t.month)}}class Yn extends ae{#t;#i;#e;#s;#a;#n={segmentIndex:0,positionInSegment:0};#r=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#n}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#i}get formattedValue(){return this.#m(this.#e)}#m(e){return this.#t.map((t)=>e[t.type]).join(this.#i)}#c(){this._setUserInput(this.#m(this.#e)),this._setValue(Hn(this.#e)??void 0)}constructor(e){let t=e.format?{segments:qn(e.format),separator:e.separator??"/"}:Li(e.locale),n=e.separator??t.separator,r=e.format?qn(e.format):t.segments,i=e.initialValue??e.defaultValue,s=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},o=r.map((a)=>s[a.type]).join(n);super({...e,initialUserInput:o},!1),this.#t=r,this.#i=n,this.#e=s,this.#s=e.minDate,this.#a=e.maxDate,this.#c(),this.on("cursor",(a)=>this.#h(a)),this.on("key",(a,g)=>this.#f(a,g)),this.on("finalize",()=>this.#d(e))}#g(){let e=Math.max(0,Math.min(this.#n.segmentIndex,this.#t.length-1)),t=this.#t[e];if(t)return this.#n.positionInSegment=Math.max(0,Math.min(this.#n.positionInSegment,t.len-1)),{segment:t,index:e}}#p(e){this.inlineError="",this.#o=null;let t=this.#g();t&&(this.#n.segmentIndex=Math.max(0,Math.min(this.#t.length-1,t.index+e)),this.#n.positionInSegment=0,this.#r=!0)}#l(e){let t=this.#g();if(!t)return;let{segment:n}=t,r=this.#e[n.type],i=!r||r.replace(/_/g,"")==="",s=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,o=Oi(n.type,_e(this.#e),this.#s,this.#a),a;i?a=e===1?o.min:o.max:a=Math.max(Math.min(o.max,s+e),o.min),this.#e={...this.#e,[n.type]:a.toString().padStart(n.len,"0")},this.#r=!0,this.#o=null,this.#c()}#h(e){if(e)switch(e){case"right":return this.#p(1);case"left":return this.#p(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#f(e,t){if(t?.name==="backspace"||t?.sequence==="\x7F"||t?.sequence==="\b"||e==="\x7F"||e==="\b"){this.inlineError="";let n=this.#g();if(!n)return;if(!this.#e[n.segment.type].replace(/_/g,"")){this.#p(-1);return}this.#e[n.segment.type]="_".repeat(n.segment.len),this.#r=!0,this.#n.positionInSegment=0,this.#c();return}if(t?.name==="tab"){this.inlineError="";let n=this.#g();if(!n)return;let r=t.shift?-1:1,i=n.index+r;i>=0&&i<this.#t.length&&(this.#n.segmentIndex=i,this.#n.positionInSegment=0,this.#r=!0);return}if(e&&/^[0-9]$/.test(e)){let n=this.#g();if(!n)return;let{segment:r}=n,i=!this.#e[r.type].replace(/_/g,"");if(this.#r&&this.#o!==null&&!i){let y=this.#o+e,b={...this.#e,[r.type]:y},h=this.#u(b,r);if(h){this.inlineError=h,this.#o=null,this.#r=!1;return}this.inlineError="",this.#e[r.type]=y,this.#o=null,this.#r=!1,this.#c(),n.index<this.#t.length-1&&(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0);return}this.#r&&!i&&(this.#e[r.type]="_".repeat(r.len),this.#n.positionInSegment=0),this.#r=!1,this.#o=null;let s=this.#e[r.type],o=s.indexOf("_"),a=o>=0?o:Math.min(this.#n.positionInSegment,r.len-1);if(a<0||a>=r.len)return;let g=s.slice(0,a)+e+s.slice(a+1),p=!1;if(a===0&&s==="__"&&(r.type==="month"||r.type==="day")){let y=Number.parseInt(e,10);g=`0${e}`,p=y<=(r.type==="month"?1:2)}if(r.type==="year"&&(g=(s.replace(/_/g,"")+e).padStart(r.len,"_")),!g.includes("_")){let y={...this.#e,[r.type]:g},b=this.#u(y,r);if(b){this.inlineError=b;return}}this.inlineError="",this.#e[r.type]=g;let u=g.includes("_")?void 0:zn(this.#e);if(u){let{year:y,month:b}=u,h=jt(y,b);this.#e={year:String(Math.max(0,Math.min(9999,y))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,b))).padStart(2,"0"),day:String(Math.max(1,Math.min(h,u.day))).padStart(2,"0")}}this.#c();let f=g.indexOf("_");p?(this.#r=!0,this.#o=e):f>=0?this.#n.positionInSegment=f:o>=0&&n.index<this.#t.length-1?(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0):this.#n.positionInSegment=Math.min(a+1,r.len-1)}}#u(e,t){let{month:n,day:r}=_e(e);if(t.type==="month"&&(n<0||n>12))return W.date.messages.invalidMonth;if(t.type==="day"&&(r<0||r>31))return W.date.messages.invalidDay(31,"any month")}#d(e){let{year:t,month:n,day:r}=_e(this.#e);if(t&&n&&r){let i=jt(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=Hn(this.#e)??e.defaultValue??void 0}}var Ai=class extends ae{options;cursor=0;#t;getGroupItems(t){return this.options.filter((n)=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(t!==void 0)if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((s)=>s.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(t.value);this.value=n?this.value.filter((r)=>r!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((s)=>({...s,group:r}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),this.#t?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Ni=new Set(["up","down","left","right"]);class Kn extends ae{#t=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}\u2588`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return n===`
|
|
18
18
|
`?`${t}\u2588
|
|
19
|
-
${r}`:`${t}${
|
|
19
|
+
${r}`:`${t}${Ze("inverse",n)}${r}`}get cursor(){return this._cursor}#e(e){if(this.userInput.length===0){this._setUserInput(e);return}this._setUserInput(this.userInput.slice(0,this.cursor)+e+this.userInput.slice(this.cursor))}#s(e){let t=this.value??"";switch(e){case"up":this._cursor=Ke(this._cursor,0,-1,t);return;case"down":this._cursor=Ke(this._cursor,0,1,t);return;case"left":this._cursor=Ke(this._cursor,-1,0,t);return;case"right":this._cursor=Ke(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#i)return this.focused==="submit"?!0:(this.#e(`
|
|
20
20
|
`),this._cursor++,!1);let n=this.#t;return this.#t=!0,n&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
21
21
|
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#e(`
|
|
22
|
-
`),this._cursor++,!1)}constructor(e){let t=e.initialUserInput??e.initialValue;super({...e,initialUserInput:t},!1),t!==void 0&&(this._cursor=t.length),this.#i=e.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&
|
|
23
|
-
`);j.push(E),B+=E.length}if(B>u){let C=0,
|
|
22
|
+
`),this._cursor++,!1)}constructor(e){let t=e.initialUserInput??e.initialValue;super({...e,initialUserInput:t},!1),t!==void 0&&(this._cursor=t.length),this.#i=e.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&Ni.has(r.name)){this.#t=!1,this.#s(r.name);return}if(n==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#t=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}n&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#e(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class Nt extends ae{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?oe(t,1,this.options):t,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=oe(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=oe(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Tn=class extends ae{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let t=this._selectedValue;this.value=t===void 0?void 0:t.value}constructor(t){super(t,!1),this.options=t.options;let n=this.options.findIndex(({value:i})=>i===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?oe(r,1,this.options):r,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=oe(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=oe(this.cursor,1,this.options);break}this.changeValue()})}};class Bt extends ae{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${Ze("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as m,stripVTControlCharacters as ta}from"util";import Z from"process";var xe=$n(It(),1);function Bi(){if(Z.platform!=="win32")return Z.env.TERM!=="linux";return Boolean(Z.env.CI)||Boolean(Z.env.WT_SESSION)||Boolean(Z.env.TERMINUS_SUBLIME)||Z.env.ConEmuTask==="{cmd::Cmder}"||Z.env.TERM_PROGRAM==="Terminus-Sublime"||Z.env.TERM_PROGRAM==="vscode"||Z.env.TERM==="xterm-256color"||Z.env.TERM==="alacritty"||Z.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var xt=Bi(),xi=()=>process.env.CI==="true";var M=(e,t)=>xt?e:t,Ui=M("\u25C6","*"),er=M("\u25A0","x"),tr=M("\u25B2","x"),et=M("\u25C7","o"),Gi=M("\u250C","T"),v=M("\u2502","|"),he=M("\u2514","\u2014"),sa=M("\u2510","T"),oa=M("\u2518","\u2014"),Ut=M("\u25CF",">"),Xe=M("\u25CB"," "),qi=M("\u25FB","[\u2022]"),_n=M("\u25FC","[+]"),Zn=M("\u25FB","[ ]"),aa=M("\u25AA","\u2022"),Qn=M("\u2500","-"),Hi=M("\u256E","+"),Wi=M("\u251C","+"),Ji=M("\u256F","+"),Vi=M("\u2570","+"),ca=M("\u256D","+"),zi=M("\u25CF","\u2022"),Yi=M("\u25C6","*"),Ki=M("\u25B2","!"),Ti=M("\u25A0","x"),tt=(e)=>{switch(e){case"initial":case"active":return m("cyan",Ui);case"cancel":return m("red",er);case"error":return m("yellow",tr);case"submit":return m("green",et)}},nr=(e)=>{switch(e){case"initial":case"active":return m("cyan",v);case"cancel":return m("red",v);case"error":return m("yellow",v);case"submit":return m("green",v)}};function rr(e,t){let n=[`${t?`${m("cyan",v)} `:""}${e.join(" \u2022 ")}`];return t&&n.push(m("cyan",he)),n}var Xn=(e,t,n,r,i,s=!1)=>{let o=t,a=0;if(s)for(let g=r-1;g>=n;g--){let p=e[g];if(p&&(o-=p.length),a++,o<=i)break}else for(let g=n;g<r;g++){let p=e[g];if(p&&(o-=p.length),a++,o<=i)break}return{lineCount:o,removals:a}},Gt=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=Ne(r)-s,g=Ot(r),p=m("dim","..."),u=Math.max(g-o,0),f=Math.max(Math.min(i,u),5),y=0;e>=f-3&&(y=Math.max(Math.min(e-f+3,t.length-f),0));let b=f<t.length&&y>0,h=f<t.length&&y+f<t.length,P=Math.min(y+f,t.length),j=[],B=0;b&&B++,h&&B++;let k=y+(b?1:0),H=P-(h?1:0);for(let C=k;C<H;C++){let G=t[C],O=G?n(G,C===e):"",E=re(O,a,{hard:!0,trim:!1}).split(`
|
|
23
|
+
`);j.push(E),B+=E.length}if(B>u){let C=0,G=0,O=B,E=e-k,U=u,ne=()=>Xn(j,O,0,E,U),z=()=>Xn(j,O,E+1,j.length,U,!0);b?({lineCount:O,removals:C}=ne(),O>U&&(h||(U-=1),{lineCount:O,removals:G}=z())):(h||(U-=1),{lineCount:O,removals:G}=z(),O>U&&(U-=1,{lineCount:O,removals:C}=ne())),C>0&&(b=!0,j.splice(0,C)),G>0&&(h=!0,j.splice(j.length-G,G))}let L=[];b&&L.push(p);for(let C of j)for(let G of C)L.push(G);return h&&L.push(p),L};var ir=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new At({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??W.withGuide,i=`${tt(this.state)} `,s=r?`${m("gray",v)} `:"",o=ue(e.output,e.message,s,i),a=`${r?`${m("gray",v)}
|
|
24
24
|
`:""}${o}
|
|
25
|
-
`,g=this.value?t:n;switch(this.state){case"submit":{let
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
`:` ${
|
|
25
|
+
`,g=this.value?t:n;switch(this.state){case"submit":{let p=r?`${m("gray",v)} `:"";return`${a}${p}${m("dim",g)}`}case"cancel":{let p=r?`${m("gray",v)} `:"";return`${a}${p}${m(["strikethrough","dim"],g)}${r?`
|
|
26
|
+
${m("gray",v)}`:""}`}default:{let p=r?`${m("cyan",v)} `:"",u=r?m("cyan",he):"";return`${a}${p}${this.value?`${m("green",Ut)} ${t}`:`${m("dim",Xe)} ${m("dim",t)}`}${e.vertical?r?`
|
|
27
|
+
${m("cyan",v)} `:`
|
|
28
|
+
`:` ${m("dim","/")} `}${this.value?`${m("dim",Xe)} ${m("dim",n)}`:`${m("green",Ut)} ${n}`}
|
|
29
29
|
${u}
|
|
30
|
-
`}}}}).prompt()};var nt=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let s=e[i],o=await s({results:n})?.catch((a)=>{throw a});if(typeof t?.onCancel=="function"&&Ae(o)){n[i]="canceled",t.onCancel({results:n});continue}n[i]=o}return n},
|
|
30
|
+
`}}}}).prompt()};var nt=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let s=e[i],o=await s({results:n})?.catch((a)=>{throw a});if(typeof t?.onCancel=="function"&&Ae(o)){n[i]="canceled",t.onCancel({results:n});continue}n[i]=o}return n},_i=[`${m("dim","\u2191/\u2193")} to navigate`,`${m("dim","Space:")} select`,`${m("dim","Enter:")} confirm`],Be=(e,t)=>e.split(`
|
|
31
31
|
`).map((n)=>t(n)).join(`
|
|
32
|
-
`),
|
|
33
|
-
${
|
|
32
|
+
`),sr=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${m("gray",Zn)} ${Be(o,(a)=>m(["strikethrough","gray"],a))}${i.hint?` ${m("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${m("cyan",qi)} ${o}${i.hint?` ${m("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${m("green",_n)} ${Be(o,(a)=>m("dim",a))}${i.hint?` ${m("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${Be(o,(a)=>m(["strikethrough","dim"],a))}`:s==="active-selected"?`${m("green",_n)} ${o}${i.hint?` ${m("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${Be(o,(a)=>m("dim",a))}`:`${m("dim",Zn)} ${Be(o,(a)=>m("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new Nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
|
|
33
|
+
${m("reset",m("dim",`Press ${m(["gray","bgWhite","inverse"]," space ")} to select, ${m("gray",m("bgWhite",m("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??W.withGuide,s=ue(e.output,e.message,i?`${nr(this.state)} `:"",`${tt(this.state)} `),o=`${i?`${m("gray",v)}
|
|
34
34
|
`:""}${s}
|
|
35
|
-
`,a=this.value??[],g=(
|
|
36
|
-
${
|
|
37
|
-
`).map((b,h)=>h===0?`${i?`${
|
|
35
|
+
`,a=this.value??[],g=(p,u)=>{if(p.disabled)return t(p,"disabled");let f=a.includes(p.value);return u&&f?t(p,"active-selected"):f?t(p,"selected"):t(p,u?"active":"inactive")};switch(this.state){case"submit":{let p=this.options.filter(({value:f})=>a.includes(f)).map((f)=>t(f,"submitted")).join(m("dim",", "))||m("dim","none"),u=ue(e.output,p,i?`${m("gray",v)} `:"");return`${o}${u}`}case"cancel":{let p=this.options.filter(({value:f})=>a.includes(f)).map((f)=>t(f,"cancelled")).join(m("dim",", "));if(p.trim()==="")return`${o}${m("gray",v)}`;let u=ue(e.output,p,i?`${m("gray",v)} `:"");return`${o}${u}${i?`
|
|
36
|
+
${m("gray",v)}`:""}`}case"error":{let p=i?`${m("yellow",v)} `:"",u=this.error.split(`
|
|
37
|
+
`).map((b,h)=>h===0?`${i?`${m("yellow",he)} `:""}${m("yellow",b)}`:` ${b}`).join(`
|
|
38
38
|
`),f=o.split(`
|
|
39
39
|
`).length,y=u.split(`
|
|
40
|
-
`).length+1;return`${o}${
|
|
41
|
-
${
|
|
40
|
+
`).length+1;return`${o}${p}${Gt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:p.length,rowPadding:f+y,style:g}).join(`
|
|
41
|
+
${p}`)}
|
|
42
42
|
${u}
|
|
43
|
-
`}default:{let
|
|
44
|
-
`).length,f=r?
|
|
45
|
-
`),b=f.length+1;return`${o}${
|
|
46
|
-
${
|
|
43
|
+
`}default:{let p=i?`${m("cyan",v)} `:"",u=o.split(`
|
|
44
|
+
`).length,f=r?rr(_i,i):i?[m("cyan",he)]:[],y=f.join(`
|
|
45
|
+
`),b=f.length+1;return`${o}${p}${Gt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:p.length,rowPadding:u+b,style:g}).join(`
|
|
46
|
+
${p}`)}
|
|
47
47
|
${y}
|
|
48
|
-
`}}}}).prompt()};var l={message:(e=[],{symbol:t=
|
|
49
|
-
`);if(f.length>0){let[y,...b]=f;y.length>0?o.push(`${
|
|
48
|
+
`}}}}).prompt()};var l={message:(e=[],{symbol:t=m("gray",v),secondarySymbol:n=m("gray",v),output:r=process.stdout,spacing:i=1,withGuide:s}={})=>{let o=[],a=s??W.withGuide,g=a?n:"",p=a?`${t} `:"",u=a?`${n} `:"";for(let y=0;y<i;y++)o.push(g);let f=Array.isArray(e)?e:e.split(`
|
|
49
|
+
`);if(f.length>0){let[y,...b]=f;y.length>0?o.push(`${p}${y}`):o.push(a?t:"");for(let h of b)h.length>0?o.push(`${u}${h}`):o.push(a?n:"")}r.write(`${o.join(`
|
|
50
50
|
`)}
|
|
51
|
-
`)},info:(e,t)=>{l.message(e,{...t,symbol:
|
|
52
|
-
`)},it=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??W.withGuide?`${
|
|
53
|
-
${
|
|
54
|
-
|
|
55
|
-
`)};var
|
|
56
|
-
`),s=i.reduce((g,
|
|
57
|
-
`).map(s),""],a=Y(t),g=Math.max(o.reduce((y,b)=>{let h=Y(b);return h>y?h:y},0),a)+2,
|
|
58
|
-
`),u=i?`${
|
|
59
|
-
`:"",f=i?
|
|
60
|
-
${
|
|
61
|
-
${
|
|
62
|
-
`)};var
|
|
63
|
-
`);let
|
|
64
|
-
`);
|
|
65
|
-
`);let
|
|
51
|
+
`)},info:(e,t)=>{l.message(e,{...t,symbol:m("blue",zi)})},success:(e,t)=>{l.message(e,{...t,symbol:m("green",Yi)})},step:(e,t)=>{l.message(e,{...t,symbol:m("green",et)})},warn:(e,t)=>{l.message(e,{...t,symbol:m("yellow",Ki)})},warning:(e,t)=>{l.warn(e,t)},error:(e,t)=>{l.message(e,{...t,symbol:m("red",Ti)})}};var rt=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??W.withGuide?`${m("gray",Gi)} `:"";n.write(`${r}${e}
|
|
52
|
+
`)},it=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??W.withGuide?`${m("gray",v)}
|
|
53
|
+
${m("gray",he)} `:"";n.write(`${r}${e}
|
|
54
|
+
|
|
55
|
+
`)};var Zi=(e)=>e,Qi=(e,t,n)=>{let r={hard:!0,trim:!1},i=re(e,t,r).split(`
|
|
56
|
+
`),s=i.reduce((g,p)=>Math.max(Y(p),g),0),o=i.map(n).reduce((g,p)=>Math.max(Y(p),g),0),a=t-(o-s);return re(e,a,r)},N=(e="",t="",n)=>{let r=n?.output??Z.stdout,i=n?.withGuide??W.withGuide,s=n?.format??Zi,o=["",...Qi(e,Ne(r)-6,s).split(`
|
|
57
|
+
`).map(s),""],a=Y(t),g=Math.max(o.reduce((y,b)=>{let h=Y(b);return h>y?h:y},0),a)+2,p=o.map((y)=>`${m("gray",v)} ${y}${" ".repeat(g-Y(y))}${m("gray",v)}`).join(`
|
|
58
|
+
`),u=i?`${m("gray",v)}
|
|
59
|
+
`:"",f=i?Wi:Vi;r.write(`${u}${m("green",et)} ${m("reset",t)} ${m("gray",Qn.repeat(Math.max(g-a-1,1))+Hi)}
|
|
60
|
+
${p}
|
|
61
|
+
${m("gray",f+Qn.repeat(g+2)+Ji)}
|
|
62
|
+
`)};var Xi=(e)=>m("magenta",e),K=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:i,frames:s=xt?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=xt?80:120,signal:a,...g}={})=>{let p=xi(),u,f,y=!1,b=!1,h="",P,j=performance.now(),B=Ne(n),k=g?.styleFrame??Xi,H=(x)=>{let _=x>1?i??W.messages.error:r??W.messages.cancel;b=x===1,y&&(Oe(_,x),b&&typeof t=="function"&&t())},L=()=>H(2),C=()=>H(1),G=()=>{process.on("uncaughtExceptionMonitor",L),process.on("unhandledRejection",L),process.on("SIGINT",C),process.on("SIGTERM",C),process.on("exit",H),a&&a.addEventListener("abort",C)},O=()=>{process.removeListener("uncaughtExceptionMonitor",L),process.removeListener("unhandledRejection",L),process.removeListener("SIGINT",C),process.removeListener("SIGTERM",C),process.removeListener("exit",H),a&&a.removeEventListener("abort",C)},E=()=>{if(P===void 0)return;p&&n.write(`
|
|
63
|
+
`);let x=re(P,B,{hard:!0,trim:!1}).split(`
|
|
64
|
+
`);x.length>1&&n.write(xe.cursor.up(x.length-1)),n.write(xe.cursor.to(0)),n.write(xe.erase.down())},U=(x)=>x.replace(/\.+$/,""),ne=(x)=>{let _=(performance.now()-x)/1000,ie=Math.floor(_/60),se=Math.floor(_%60);return ie>0?`[${ie}m ${se}s]`:`[${se}s]`},z=g.withGuide??W.withGuide,Ve=(x="")=>{y=!0,u=Jn({output:n}),h=U(x),j=performance.now(),z&&n.write(`${m("gray",v)}
|
|
65
|
+
`);let _=0,ie=0;G(),f=setInterval(()=>{if(p&&h===P)return;E(),P=h;let se=k(s[_]),ze;if(p)ze=`${se} ${h}...`;else if(e==="timer")ze=`${se} ${h} ${ne(j)}`;else{let Xr=".".repeat(Math.floor(ie)).slice(0,3);ze=`${se} ${h}${Xr}`}let Qr=re(ze,B,{hard:!0,trim:!1});n.write(Qr),_=_+1<s.length?_+1:0,ie=ie<4?ie+0.125:0},o)},Oe=(x="",_=0,ie=!1)=>{if(!y)return;y=!1,clearInterval(f),E();let se=_===0?m("green",et):_===1?m("red",er):m("red",tr);h=x??h,ie||(e==="timer"?n.write(`${se} ${h} ${ne(j)}
|
|
66
66
|
`):n.write(`${se} ${h}
|
|
67
|
-
`)),O(),u()};return{start:Ve,stop:(
|
|
67
|
+
`)),O(),u()};return{start:Ve,stop:(x="")=>Oe(x,0),message:(x="")=>{h=U(x??h)},cancel:(x="")=>Oe(x,1),error:(x="")=>Oe(x,2),clear:()=>Oe("",0,!0),get isCancelled(){return b}}},ga={light:M("\u2500","-"),heavy:M("\u2501","="),block:M("\u2588","#")};var es=[`${m("dim","\u2191/\u2193")} to navigate`,`${m("dim","Enter:")} confirm`],Qe=(e,t)=>e.includes(`
|
|
68
68
|
`)?e.split(`
|
|
69
69
|
`).map((n)=>t(n)).join(`
|
|
70
|
-
`):t(e),
|
|
70
|
+
`):t(e),or=(e)=>{let t=(r,i)=>{if(r===void 0)return"";let s=r.label??String(r.value);switch(i){case"disabled":return`${m("gray",Xe)} ${Qe(s,(o)=>m("gray",o))}${r.hint?` ${m("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${Qe(s,(o)=>m("dim",o))}`;case"active":return`${m("green",Ut)} ${s}${r.hint?` ${m("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${Qe(s,(o)=>m(["strikethrough","dim"],o))}`;default:return`${m("dim",Xe)} ${Qe(s,(o)=>m("dim",o))}`}},n=e.showInstructions??!0;return new Tn({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??W.withGuide,i=`${tt(this.state)} `,s=`${nr(this.state)} `,o=ue(e.output,e.message,s,i),a=`${r?`${m("gray",v)}
|
|
71
71
|
`:""}${o}
|
|
72
|
-
`;switch(this.state){case"submit":{let g=r?`${
|
|
73
|
-
${
|
|
74
|
-
`).length,u=n?
|
|
75
|
-
`),y=u.length+1;return`${a}${g}${
|
|
72
|
+
`;switch(this.state){case"submit":{let g=r?`${m("gray",v)} `:"",p=ue(e.output,t(this.options[this.cursor],"selected"),g);return`${a}${p}`}case"cancel":{let g=r?`${m("gray",v)} `:"",p=ue(e.output,t(this.options[this.cursor],"cancelled"),g);return`${a}${p}${r?`
|
|
73
|
+
${m("gray",v)}`:""}`}default:{let g=r?`${m("cyan",v)} `:"",p=a.split(`
|
|
74
|
+
`).length,u=n?rr(es,r):r?[m("cyan",he)]:[],f=u.join(`
|
|
75
|
+
`),y=u.length+1;return`${a}${g}${Gt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:g.length,rowPadding:p+y,style:(b,h)=>t(b,b.disabled?"disabled":h?"active":"inactive")}).join(`
|
|
76
76
|
${g}`)}
|
|
77
77
|
${f}
|
|
78
|
-
`}}}}).prompt()};var
|
|
78
|
+
`}}}}).prompt()};var pa=`${m("gray",v)} `;var ar=(e)=>new Bt({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??W.withGuide,n=`${`${t?`${m("gray",v)}
|
|
79
79
|
`:""}${tt(this.state)} `}${e.message}
|
|
80
|
-
`,r=e.placeholder&&e.placeholder.length>0?
|
|
80
|
+
`,r=e.placeholder&&e.placeholder.length>0?m("inverse",e.placeholder[0])+m("dim",e.placeholder.slice(1)):m(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${m("yellow",this.error)}`:"",a=t?`${m("yellow",v)} `:"",g=t?m("yellow",he):"";return`${n.trim()}
|
|
81
81
|
${a}${i}
|
|
82
82
|
${g}${o}
|
|
83
|
-
`}case"submit":{let o=s?` ${
|
|
84
|
-
${a}`:""}`}default:{let o=t?`${
|
|
83
|
+
`}case"submit":{let o=s?` ${m("dim",s)}`:"",a=t?m("gray",v):"";return`${n}${a}${o}`}case"cancel":{let o=s?` ${m(["strikethrough","dim"],s)}`:"",a=t?m("gray",v):"";return`${n}${a}${o}${s.trim()?`
|
|
84
|
+
${a}`:""}`}default:{let o=t?`${m("cyan",v)} `:"",a=t?m("cyan",he):"";return`${n}${o}${i}
|
|
85
85
|
${a}
|
|
86
|
-
`}}}}).prompt();var
|
|
87
|
-
`)}command(e,t){let n=[],r=t??this.metadata.bin,i=`${w.cmd(r)} ${w.cmd(e.name)}`;n.push(""),n.push(`${w.name(e.name)} ${w.hint("-")} ${w.desc(e.description)}`),n.push(""),n.push(w.header("Usage:"));let s=this.formatPositionalUsage(e.positionals);if(e.hasSubcommands())n.push(` ${i} ${w.placeholder("<subcommand>")} ${w.hint("[options]")}`);else{let g=[i];if(s)g.push(s);g.push(w.hint("[options]")),n.push(` ${g.join(" ")}`)}if(e.prompts)n.push(` ${i} ${w.hint("- runs interactively")}`);if(n.push(""),e.hasSubcommands()){n.push(w.header("Subcommands:"));let g=e.getSubcommands().map((
|
|
88
|
-
`)}formatPositionalUsage(e){return Object.entries(e).map(([t,n])=>{let r=n.variadic?`${t}...`:t;return n.required?w.arg(`<${r}>`):w.arg(`[${r}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([n,r])=>{let i=r.variadic?`${n}...`:n,s=w.desc(r.description??""),o=r.required?"":w.hint(" (optional)");return[` ${w.arg(i)}`,`${s}${o}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[n,r]of Object.entries(e)){let s=`${r.alias?`${w.flag(`-${r.alias}`)}, `:" "}${w.flag(`--${n}`)}`,o=w.desc(r.description??""),a=r.default!==void 0?w.hint(` (default: ${w.default(this.formatDefault(r))})`):"";t.push([` ${s}`,`${o}${a}`])}return this.formatColumns(t)}formatDefault(e){if(e.type==="string")return`"${e.default}"`;return String(e.default)}formatColumns(e){if(e.length===0)return[];let t=Math.max(...e.map(([r])=>this.stripAnsi(r).length)),n=2;return e.map(([r,i])=>{let s=t-this.stripAnsi(r).length+n;return`${r}${" ".repeat(s)}${i}`})}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}}var ge=new Uint32Array(65536),
|
|
89
|
-
Run "${r} --help" for usage.`),process.exit(1)}function be(e,t){let n=(i)=>i&&typeof i==="object";if(!n(e)||!n(t))return t;let r={...e};for(let i of Object.keys(t)){let s=r[i],o=t[i];if(Array.isArray(s)&&Array.isArray(o))r[i]=[...o];else if(n(s)&&n(o))r[i]=be(s,o);else r[i]=o}return r}function Ht(e){return e==null?[]:Array.isArray(e)?e:[e]}function
|
|
90
|
-
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&r.length===0,a=this.buildContext(i,n,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=Wt([],this.command.args),t=Jt([],this.command.positionals),n=this.buildContext(t,e,!0);await this.command.execute?.(n)}async runSubcommandMenu(){while(!0){let e=await this.promptSubcommandSelectionOrBack();if(e===null)return;if(e===Vt){this.options.onExit?.();return}let t=this.command.getSubcommand(e);if(t)await this.executeSubcommand(t)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(e){if(e instanceof te){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new Re(e,this.env,this.commandPath).route([],!0)}catch(t){if(t instanceof te)return;if(t instanceof d){if(l.warn(c.yellow(t.message)),t.hint)l.info(c.dim(t.hint));return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Vt}:{hint:"Return to previous menu",label:"Back",value:Vt};return ye({message:e?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((n)=>({hint:n.description,label:n.name,value:n.name})),t]})}buildContext(e,t,n){return{...this.env,args:t,interactive:n,positionals:e}}isHelpRequest(e){return e.includes("--help")||e.includes("-h")}printHelp(e){let t=e===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(e,t))}}var gs={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class zt{commands=new Map;metadata;configManager;help;bin;globalArgs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Enable interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};constructor(e,t){this.configManager=e,this.metadata={...gs,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new qt({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(e){for(let t of e)t.init?.(),this.commands.set(t.name,t)}async run(e=process.argv.slice(2)){let{command:t,flags:n,restArgs:r}=hr(e,this.globalArgs);if(n.version&&!t)return console.log(this.help.version());if(n.interactive&&!t)return this.runInteractive();if(!t)return console.log(this.help.global());if(t==="help")return this.printHelpFor(r[0]);await this.runDirect(t,r,!!n.help)}printHelpFor(e){if(!e)return console.log(this.help.global());let t=this.commands.get(e);if(!t)return this.handleUnknownCommand(e);console.log(this.help.command(t))}async runInteractive(){this.showIntro();let e=this.createVirtualRootCommand(),t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},n=new Re(e,t,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await n.route([],!0)}catch(r){this.handleError(r)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(e)=>this.commands.get(e),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){it(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(e,t,n){let r=this.commands.get(e);if(!r)return this.handleUnknownCommand(e);let i=t.length>0&&!t[0]?.startsWith("-");if(n&&!i)return console.log(this.help.command(r));try{let s={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new Re(r,s,this.bin).route(t,!1)}catch(s){this.handleError(s)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";rt(`${c.bgCyan(c.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());gt("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof te)process.exit(0);if(e instanceof d){if(l.warn(c.yellow(e.message)),e.hint)l.info(c.dim(e.hint));process.exit(0)}if(e instanceof Error)l.error(c.red(e.message)),process.exit(1);console.error(c.red("Error:"),e),process.exit(1)}}class Ge{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(e){for(let t of e)t.init?.(),this.subcommands.set(t.name,t)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(e){return this.subcommands.get(e)}getSubcommands(){return Array.from(this.subcommands.values())}}function D(e){return e}function _(e){return e}import Se from"fs";import dr from"path";class Yt{config;configPath;defaultConfig;constructor(e,t){this.configPath=dr.resolve(e),this.defaultConfig=t,this.config=this.loadConfig()}get(e){return this.config[e]}set(e,t){this.config[e]=t,this.save()}delete(e){delete this.config[e],this.save()}exists(){return Se.existsSync(this.configPath)}getAll(){return be({},this.config)}save(e){if(e)this.config={...e};this.ensureDirectoryExists();try{Se.writeFileSync(this.configPath,JSON.stringify(this.config,null,2))}catch(t){console.error(`Failed to save config to ${this.configPath}:`,t)}}ensureDirectoryExists(){let e=dr.dirname(this.configPath);if(!Se.existsSync(e))try{Se.mkdirSync(e,{recursive:!0})}catch(t){console.error(`Failed to create config directory at ${e}:`,t)}}loadConfig(){if(!Se.existsSync(this.configPath))return{...this.defaultConfig};try{let e=Se.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return be({...this.defaultConfig},t)}catch{return console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),{...this.defaultConfig}}}}var yr="0.5.1";class I extends Ge{}import{existsSync as Cs}from"fs";import{mkdir as $s,writeFile as Rs}from"fs/promises";import{dirname as Ss}from"path";class fe{owner;repo;constructor(e){this.owner=e.owner,this.repo=e.repo}}class pt extends fe{name="bitbucket";notImplemented(){throw new d("Bitbucket is not supported yet","Bitbucket support is coming soon")}async ensureAvailable(){this.notImplemented()}async getDefaultBranch(){this.notImplemented()}async findPr(e){this.notImplemented()}async createPr(e){this.notImplemented()}async updatePr(e,t){this.notImplemented()}async getPr(e){this.notImplemented()}async getPrFromCurrentBranch(){this.notImplemented()}async getPrCommits(e){this.notImplemented()}async getPrFiles(e){this.notImplemented()}async ensureLabelExists(e,t){this.notImplemented()}async createRelease(e){this.notImplemented()}async deleteRelease(e){this.notImplemented()}}var A="sis",Kt="\uD83E\uDEA8",de="other",Me={build:23,chore:25,ci:24,docs:20,feat:10,"feat!":0,fix:11,"fix!":1,perf:12,refactor:13,style:21,test:22,["other"]:100},Ie=50,lt=".sisyphus",br="stones",Pr="released",ut=7,wr="unknown",xe="unknown",vr="0.0.0",kr="latest",me="main",Cr=4,$r=8,Rr="config.json";var Fe={$schema:"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/sisyphus/schema.json",changelog:{append:!0,filename:"CHANGELOG.md",generate:!0,packageHeader:"{emoji} {version} ({date})",root:!1,rootHeader:"{date} - {packages}",sections:{breaking:"Breaking changes",build:"Build",chore:"Chores",ci:"CI",dependencies:"Dependency updates",docs:"Documentation",feat:"Features",fix:"Bug fixes",other:"Other changes",perf:"Performance",refactor:"Refactoring",style:"Styling",test:"Tests"}},commit:{author:"r5n-bot",message:"chore(release): {message}"},commits:{skip:{authors:["r5n-bot[bot]"],messagePatterns:["^chore\\(release\\):","^chore: add stone"]}},ignore:[],lastStone:{commit:"",date:""},plugins:[],pr:{labelMapping:{breaking:"major","breaking-change":"major",bug:"patch",chore:"patch",docs:"patch",enhancement:"minor",feature:"minor",fix:"patch"},skip:{authors:["r5n-bot[bot]"],labels:["sisyphus-release","skip-stone"],titlePatterns:["^chore\\(release\\):"]}},release:{createRelease:!1,npm:!1,push:!1,tags:!1},scripts:{post:{},pre:{}},single:!1,sisyphusDir:".sisyphus",stones:[],tag:"latest"};class ht extends fe{name="github";get apiPath(){return`repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}`}async ensureAvailable(){try{await Bun.$`which gh`.quiet()}catch{throw new d("GitHub CLI (gh) is not installed","Install from https://cli.github.com and run: gh auth login")}try{await Bun.$`gh auth status`.quiet()}catch{throw new d("GitHub CLI (gh) is not authenticated","Run: gh auth login")}}async getDefaultBranch(){try{return(await Bun.$`gh repo view --json defaultBranchRef --jq .defaultBranchRef.name`.quiet()).stdout.toString().trim()||me}catch{return me}}async findPr(e){try{let t=[];if(e.head)t.push("--head",e.head);if(e.label)t.push("--label",e.label);let n=await Bun.$`gh pr list --json number,url,title,body,labels,author,headRefName,baseRefName,mergeCommit,state --limit 1 ${t}`.quiet(),r=JSON.parse(n.stdout.toString());if(!r[0])return null;return this.mapPrResponse(r[0])}catch{return null}}async createPr(e){let t=await Bun.$`gh api ${this.apiPath}/pulls --method POST -f head=${e.head} -f base=${e.base} -f title=${e.title} -f body=${e.body}`,r=JSON.parse(t.stdout.toString()).number;if(e.labels&&e.labels.length>0){let i=e.labels.flatMap((s)=>["-f",`labels[]=${s}`]);await Bun.$`gh api ${this.apiPath}/issues/${r}/labels --method POST ${i}`}return this.getPr(r)}async updatePr(e,t){let n=[];if(t.title)n.push("--title",t.title);if(t.body)n.push("--body",t.body);await Bun.$`gh pr edit ${e} ${n}`}async getPr(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e}`.quiet(),n=JSON.parse(t.stdout.toString());return this.mapRestApiResponse(n)}catch{throw new d(`Failed to fetch PR #${e}`,"Make sure the PR exists and you have access")}}async getPrFromCurrentBranch(){try{let e=await Bun.$`gh pr view --json number,title,body,labels,author,headRefName,baseRefName,url,mergeCommit,state`.quiet(),t=JSON.parse(e.stdout.toString());return this.mapPrResponse(t)}catch{throw new d("No PR found for current branch","Make sure you have an open PR or provide a URL with --url")}}async getPrCommits(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/commits --jq '.[].sha'`.quiet()).stdout.toString().trim().split(`
|
|
86
|
+
`}}}}).prompt();var ns=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),pr=["black","blue","cyan","gray","green","magenta","red","white","yellow"],rs=["bold","dim","italic","underline","reset"],mr={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},is={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"},ss={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"},cr={"\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 st(e){return(t)=>ns?`${e}${t}${mr.reset}`:t}function os(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32&&n!==27)return!1}return!0}function gr({bright:e=!1,color:t}){let n=Bun.color(t,"ansi"),r=typeof n==="string"&&n.length>0&&os(n)?n:is[t];if(!r)return"";return e&&r in cr?cr[r]:r}var as=pr.reduce((e,t)=>{let n=gr({color:t});if(n)e[t]=st(n);let r=gr({bright:!0,color:t});if(r)e[`${t}Bright`]=st(r);return e},{}),cs=rs.reduce((e,t)=>{return e[t]=st(mr[t]),e},{}),gs=pr.reduce((e,t)=>{let n=ss[t];if(n){let r=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[r]=st(n)}return e},{}),c={...as,...cs,...gs};function ot(e){if(Ae(e))throw new te;return e}function ms(e){return e.map((t)=>t.key?`${c.bold(t.key)} ${c.dim(t.text)}`:c.dim(t.text)).join(c.dim(" \xB7 "))}function at(e){l.info(ms(e))}var ct={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 D(e){return at(ct.confirm),ot(await ir(e))}async function T(e){return at(ct.text),ot(await ar(e))}async function ye(e){return at(ct.select),ot(await or({showInstructions:!1,...e}))}async function ce(e){return at(ct.multiselect),ot(await sr({showInstructions:!1,...e}))}var w={arg:c.magenta,cmd:c.cyan,default:c.blue,desc:c.white,flag:c.green,header:(e)=>c.bold(c.yellow(e)),hint:c.dim,name:(e)=>c.bold(c.cyan(e)),placeholder:c.magenta};class qt{metadata;commands;globalArgs;constructor(e,t,n){this.metadata=e;this.commands=t;this.globalArgs=n}version(){return`${w.name(this.metadata.name)} ${w.hint(this.metadata.version??"0.0.0")}`}global(){let e=[],{name:t,bin:n,version:r,description:i}=this.metadata;if(e.push(""),e.push(`${w.name(t)}${r?` ${w.hint(`v${r}`)}`:""}`),i)e.push(w.desc(i));e.push(""),e.push(w.header("Usage:")),e.push(` ${w.cmd(n)} ${w.placeholder("[command]")} ${w.hint("[options]")}`),e.push(""),e.push(w.header("Commands:"));let s=Array.from(this.commands.values()).map((o)=>[` ${w.cmd(o.name)}`,w.desc(o.description)]);return e.push(...this.formatColumns(s)),e.push(""),e.push(w.header("Options:")),e.push(...this.formatArgDefs(this.globalArgs)),e.push(""),e.push(w.hint(`Run "${n} <command> --help" for command-specific options.`)),e.push(""),e.join(`
|
|
87
|
+
`)}command(e,t){let n=[],r=t??this.metadata.bin,i=`${w.cmd(r)} ${w.cmd(e.name)}`;n.push(""),n.push(`${w.name(e.name)} ${w.hint("-")} ${w.desc(e.description)}`),n.push(""),n.push(w.header("Usage:"));let s=this.formatPositionalUsage(e.positionals);if(e.hasSubcommands())n.push(` ${i} ${w.placeholder("<subcommand>")} ${w.hint("[options]")}`);else{let g=[i];if(s)g.push(s);g.push(w.hint("[options]")),n.push(` ${g.join(" ")}`)}if(e.prompts)n.push(` ${i} ${w.hint("- runs interactively")}`);if(n.push(""),e.hasSubcommands()){n.push(w.header("Subcommands:"));let g=e.getSubcommands().map((p)=>[` ${w.cmd(p.name)}`,w.desc(p.description)]);n.push(...this.formatColumns(g)),n.push("")}if(Object.entries(e.positionals).length>0)n.push(w.header("Arguments:")),n.push(...this.formatPositionalDefs(e.positionals)),n.push("");if(Object.entries(e.args).length>0)n.push(w.header("Options:")),n.push(...this.formatArgDefs(e.args)),n.push("");return n.join(`
|
|
88
|
+
`)}formatPositionalUsage(e){return Object.entries(e).map(([t,n])=>{let r=n.variadic?`${t}...`:t;return n.required?w.arg(`<${r}>`):w.arg(`[${r}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([n,r])=>{let i=r.variadic?`${n}...`:n,s=w.desc(r.description??""),o=r.required?"":w.hint(" (optional)");return[` ${w.arg(i)}`,`${s}${o}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[n,r]of Object.entries(e)){let s=`${r.alias?`${w.flag(`-${r.alias}`)}, `:" "}${w.flag(`--${n}`)}`,o=w.desc(r.description??""),a=r.default!==void 0?w.hint(` (default: ${w.default(this.formatDefault(r))})`):"";t.push([` ${s}`,`${o}${a}`])}return this.formatColumns(t)}formatDefault(e){if(e.type==="string")return`"${e.default}"`;return String(e.default)}formatColumns(e){if(e.length===0)return[];let t=Math.max(...e.map(([r])=>this.stripAnsi(r).length)),n=2;return e.map(([r,i])=>{let s=t-this.stripAnsi(r).length+n;return`${r}${" ".repeat(s)}${i}`})}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}}var ge=new Uint32Array(65536),ls=(e,t)=>{let n=e.length,r=t.length,i=1<<n-1,s=-1,o=0,a=n,g=n;while(g--)ge[e.charCodeAt(g)]|=1<<g;for(g=0;g<r;g++){let p=ge[t.charCodeAt(g)],u=p|o;if(p|=(p&s)+s^s,o|=~(p|s),s&=p,o&i)a++;if(s&i)a--;o=o<<1|1,s=s<<1|~(u|o),o&=u}g=n;while(g--)ge[e.charCodeAt(g)]=0;return a},us=(e,t)=>{let n=t.length,r=e.length,i=[],s=[],o=Math.ceil(n/32),a=Math.ceil(r/32);for(let h=0;h<o;h++)s[h]=-1,i[h]=0;let g=0;for(;g<a-1;g++){let h=0,P=-1,j=g*32,B=Math.min(32,r)+j;for(let k=j;k<B;k++)ge[e.charCodeAt(k)]|=1<<k;for(let k=0;k<n;k++){let H=ge[t.charCodeAt(k)],L=s[k/32|0]>>>k&1,C=i[k/32|0]>>>k&1,G=H|h,O=((H|C)&P)+P^P|H|C,E=h|~(O|P),U=P&O;if(E>>>31^L)s[k/32|0]^=1<<k;if(U>>>31^C)i[k/32|0]^=1<<k;E=E<<1|L,U=U<<1|C,P=U|~(G|E),h=E&G}for(let k=j;k<B;k++)ge[e.charCodeAt(k)]=0}let p=0,u=-1,f=g*32,y=Math.min(32,r-f)+f;for(let h=f;h<y;h++)ge[e.charCodeAt(h)]|=1<<h;let b=r;for(let h=0;h<n;h++){let P=ge[t.charCodeAt(h)],j=s[h/32|0]>>>h&1,B=i[h/32|0]>>>h&1,k=P|p,H=((P|B)&u)+u^u|P|B,L=p|~(H|u),C=u&H;if(b+=L>>>r-1&1,b-=C>>>r-1&1,L>>>31^j)s[h/32|0]^=1<<h;if(C>>>31^B)i[h/32|0]^=1<<h;L=L<<1|j,C=C<<1|B,u=C|~(k|L),p=L&k}for(let h=f;h<y;h++)ge[e.charCodeAt(h)]=0;return b},hs=(e,t)=>{if(e.length<t.length){let n=t;t=e,e=n}if(t.length===0)return e.length;if(e.length<=32)return ls(e,t);return us(e,t)},lr=(e,t)=>{let n=1/0,r=0;for(let i=0;i<t.length;i++){let s=hs(e,t[i]);if(s<n)n=s,r=i}return t[r]};function gt(e,t,n,r){let i=lr(t,n);if(console.error(c.red(`Unknown ${e}: ${t}`)),i)console.error(c.yellow(`Did you mean "${i}"?`));console.error(`
|
|
89
|
+
Run "${r} --help" for usage.`),process.exit(1)}function be(e,t){let n=(i)=>i&&typeof i==="object";if(!n(e)||!n(t))return t;let r={...e};for(let i of Object.keys(t)){let s=r[i],o=t[i];if(Array.isArray(s)&&Array.isArray(o))r[i]=[...o];else if(n(s)&&n(o))r[i]=be(s,o);else r[i]=o}return r}function Ht(e){return e==null?[]:Array.isArray(e)?e:[e]}function fs(e,t,n,r){var i,s=e[t],o=~r.string.indexOf(t)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~r.boolean.indexOf(t)?n==="false"?!1:n==="true"||(e._.push((i=+n,i*0===0)?i:n),!!n):(i=+n,i*0===0)?i:n;e[t]=s==null?o:Array.isArray(s)?s.concat(o):[s,o]}function pt(e,t){e=e||[],t=t||{};var n,r,i,s,o,a={_:[]},g=0,p=0,u=0,f=e.length;let y=t.alias!==void 0,b=t.unknown!==void 0,h=t.default!==void 0;if(t.alias=t.alias||{},t.string=Ht(t.string),t.boolean=Ht(t.boolean),y)for(n in t.alias){r=t.alias[n]=Ht(t.alias[n]);for(g=0;g<r.length;g++)(t.alias[r[g]]=r.concat(n)).splice(g,1)}for(g=t.boolean.length;g-- >0;){r=t.alias[t.boolean[g]]||[];for(p=r.length;p-- >0;)t.boolean.push(r[p])}for(g=t.string.length;g-- >0;){r=t.alias[t.string[g]]||[];for(p=r.length;p-- >0;)t.string.push(r[p])}if(h){for(n in t.default)if(s=typeof t.default[n],r=t.alias[n]=t.alias[n]||[],t[s]!==void 0){t[s].push(n);for(g=0;g<r.length;g++)t[s].push(r[g])}}let P=b?Object.keys(t.alias):[];for(g=0;g<f;g++){if(i=e[g],i==="--"){a._=a._.concat(e.slice(++g));break}for(p=0;p<i.length;p++)if(i.charCodeAt(p)!==45)break;if(p===0)a._.push(i);else if(i.substring(p,p+3)==="no-"){if(s=i.substring(p+3),b&&!~P.indexOf(s))return t.unknown(i);a[s]=!1}else{for(u=p+1;u<i.length;u++)if(i.charCodeAt(u)===61)break;s=i.substring(p,u),o=i.substring(++u)||(g+1===f||(""+e[g+1]).charCodeAt(0)===45||e[++g]),r=p===2?[s]:s;for(u=0;u<r.length;u++){if(s=r[u],b&&!~P.indexOf(s))return t.unknown("-".repeat(p)+s);fs(a,s,u+1<r.length||o,t)}}}if(h){for(n in t.default)if(a[n]===void 0)a[n]=t.default[n]}if(y)for(n in a){r=t.alias[n]||[];while(r.length>0)a[r.shift()]=a[n]}return a}function ds(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function ur(e){let t={alias:{},boolean:[],default:{},string:[]};for(let[n,r]of Object.entries(e)){if(r.type==="boolean")t.boolean.push(n);else t.string.push(n);if(r.alias)t.alias[r.alias]=n;let i=ds(n);if(i!==n)t.alias[i]=n;if(r.default!==void 0)t.default[n]=r.default}return t}function hr(e,t){let n={...e};for(let[r,i]of Object.entries(t)){if(i.type!=="number")continue;let s=e[r];if(s===void 0||typeof s==="boolean")continue;let o=Number(s);if(Number.isNaN(o))throw Error(`Invalid number for --${r}: "${s}"`);n[r]=o}return n}function fr(e,t){let n=ur(t),r=pt(e,n),i=r._[0],s=i?e.indexOf(i):-1,{_:o,...a}=r,g=hr(a,t);return{command:i,flags:g,restArgs:s>=0?e.slice(s+1):[]}}function Wt(e,t={}){let n=ur(t),r=pt(e,n),{_:i,...s}=r;return{args:hr(s,t),rawPositionals:i}}function Jt(e,t){let n={},r=Object.entries(t);for(let[i,[s,o]]of r.entries())n[s]=o.variadic?e.slice(i):e[i];return n}function dr(e,t){for(let[n,r]of Object.entries(t)){if(!r.required)continue;let i=e[n];if(Array.isArray(i)?i.length===0:!i)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}var Vt="__exit__";class Re{command;env;prefix;options;constructor(e,t,n,r={}){this.command=e;this.env=t;this.prefix=n;this.options=r}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(e,t){if(t)await this.routeInteractive();else await this.routeDirect(e)}async routeDirect(e){let[t,...n]=e;if(t&&this.command.hasSubcommands()){let r=this.command.getSubcommand(t);if(r){await this.handleSubcommandRoute(r,n);return}if(!t.startsWith("-")){this.handleUnknownSubcommand(t);return}}await this.executeCommand(e)}handleUnknownSubcommand(e){let t=this.command.getSubcommands().map((n)=>n.name);gt("subcommand",e,t,this.commandPath)}async handleSubcommandRoute(e,t){await new Re(e,this.env,this.commandPath).route(t,!1)}async executeCommand(e){if(this.isHelpRequest(e)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:n,rawPositionals:r}=Wt(e,this.command.args),i=Jt(r,this.command.positionals),s=dr(i,this.command.positionals);if(s)l.error(s),console.error(`
|
|
90
|
+
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&r.length===0,a=this.buildContext(i,n,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=Wt([],this.command.args),t=Jt([],this.command.positionals),n=this.buildContext(t,e,!0);await this.command.execute?.(n)}async runSubcommandMenu(){while(!0){let e=await this.promptSubcommandSelectionOrBack();if(e===null)return;if(e===Vt){this.options.onExit?.();return}let t=this.command.getSubcommand(e);if(t)await this.executeSubcommand(t)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(e){if(e instanceof te){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new Re(e,this.env,this.commandPath).route([],!0)}catch(t){if(t instanceof te)return;if(t instanceof d){if(l.warn(c.yellow(t.message)),t.hint)l.info(c.dim(t.hint));return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Vt}:{hint:"Return to previous menu",label:"Back",value:Vt};return ye({message:e?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((n)=>({hint:n.description,label:n.name,value:n.name})),t]})}buildContext(e,t,n){return{...this.env,args:t,interactive:n,positionals:e}}isHelpRequest(e){return e.includes("--help")||e.includes("-h")}printHelp(e){let t=e===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(e,t))}}var ys={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class zt{commands=new Map;metadata;configManager;help;bin;globalArgs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Enable interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};constructor(e,t){this.configManager=e,this.metadata={...ys,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new qt({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(e){for(let t of e)t.init?.(),this.commands.set(t.name,t)}async run(e=process.argv.slice(2)){let{command:t,flags:n,restArgs:r}=fr(e,this.globalArgs);if(n.version&&!t)return console.log(this.help.version());if(n.interactive&&!t)return this.runInteractive();if(!t)return console.log(this.help.global());if(t==="help")return this.printHelpFor(r[0]);await this.runDirect(t,r,!!n.help)}printHelpFor(e){if(!e)return console.log(this.help.global());let t=this.commands.get(e);if(!t)return this.handleUnknownCommand(e);console.log(this.help.command(t))}async runInteractive(){this.showIntro();let e=this.createVirtualRootCommand(),t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},n=new Re(e,t,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await n.route([],!0)}catch(r){this.handleError(r)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(e)=>this.commands.get(e),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){it(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(e,t,n){let r=this.commands.get(e);if(!r)return this.handleUnknownCommand(e);let i=t.length>0&&!t[0]?.startsWith("-");if(n&&!i)return console.log(this.help.command(r));try{let s={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new Re(r,s,this.bin).route(t,!1)}catch(s){this.handleError(s)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";rt(`${c.bgCyan(c.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());gt("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof te)process.exit(0);if(e instanceof d){if(l.warn(c.yellow(e.message)),e.hint)l.info(c.dim(e.hint));process.exit(0)}if(e instanceof Error)l.error(c.red(e.message)),process.exit(1);console.error(c.red("Error:"),e),process.exit(1)}}class Ue{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(e){for(let t of e)t.init?.(),this.subcommands.set(t.name,t)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(e){return this.subcommands.get(e)}getSubcommands(){return Array.from(this.subcommands.values())}}function F(e){return e}function Q(e){return e}import Se from"fs";import yr from"path";class Yt{config;configPath;defaultConfig;constructor(e,t){this.configPath=yr.resolve(e),this.defaultConfig=t,this.config=this.loadConfig()}get(e){return this.config[e]}set(e,t){this.config[e]=t,this.save()}delete(e){delete this.config[e],this.save()}exists(){return Se.existsSync(this.configPath)}getAll(){return be({},this.config)}save(e){if(e)this.config={...e};this.ensureDirectoryExists();try{Se.writeFileSync(this.configPath,JSON.stringify(this.config,null,2))}catch(t){console.error(`Failed to save config to ${this.configPath}:`,t)}}ensureDirectoryExists(){let e=yr.dirname(this.configPath);if(!Se.existsSync(e))try{Se.mkdirSync(e,{recursive:!0})}catch(t){console.error(`Failed to create config directory at ${e}:`,t)}}loadConfig(){if(!Se.existsSync(this.configPath))return{...this.defaultConfig};try{let e=Se.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return be({...this.defaultConfig},t)}catch{return console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),{...this.defaultConfig}}}}var br="0.6.0";class I extends Ue{}import{existsSync as js}from"fs";import{mkdir as Es,writeFile as Ls}from"fs/promises";import{dirname as Os}from"path";class fe{owner;repo;constructor(e){this.owner=e.owner,this.repo=e.repo}}class mt extends fe{name="bitbucket";notImplemented(){throw new d("Bitbucket is not supported yet","Bitbucket support is coming soon")}async ensureAvailable(){this.notImplemented()}async getDefaultBranch(){this.notImplemented()}async findPr(e){this.notImplemented()}async createPr(e){this.notImplemented()}async updatePr(e,t){this.notImplemented()}async getPr(e){this.notImplemented()}async getPrFromCurrentBranch(){this.notImplemented()}async getPrCommits(e){this.notImplemented()}async getPrFiles(e){this.notImplemented()}async ensureLabelExists(e,t){this.notImplemented()}async createRelease(e){this.notImplemented()}async deleteRelease(e){this.notImplemented()}}var A="sis",Kt="\uD83E\uDEA8",de="other",Me={build:23,chore:25,ci:24,docs:20,feat:10,"feat!":0,fix:11,"fix!":1,perf:12,refactor:13,style:21,test:22,["other"]:100},Ie=50,lt=".sisyphus",Pr="stones",wr="released",ut=7,vr="unknown",Ge="unknown",kr="0.0.0",Cr="latest",pe="main",$r=4,Rr=8,Sr="config.json";var De={$schema:"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/sisyphus/schema.json",changelog:{append:!0,filename:"CHANGELOG.md",generate:!0,packageHeader:"{emoji} {version} ({date})",root:!1,rootHeader:"{date} - {packages}",sections:{breaking:"Breaking changes",build:"Build",chore:"Chores",ci:"CI",dependencies:"Dependency updates",docs:"Documentation",feat:"Features",fix:"Bug fixes",other:"Other changes",perf:"Performance",refactor:"Refactoring",style:"Styling",test:"Tests"}},commit:{author:"r5n-bot",message:"chore(release): {message}"},commits:{skip:{authors:["r5n-bot[bot]"],messagePatterns:["^chore\\(release\\):","^chore: add stone"]}},ignore:[],lastStone:{commit:"",date:""},plugins:[],pr:{labelMapping:{breaking:"major","breaking-change":"major",bug:"patch",chore:"patch",docs:"patch",enhancement:"minor",feature:"minor",fix:"patch"},skip:{authors:["r5n-bot[bot]"],labels:["sisyphus-release","skip-stone"],titlePatterns:["^chore\\(release\\):"]}},release:{createRelease:!1,npm:!1,push:!1,tags:!1},scripts:{post:{},pre:{}},single:!1,sisyphusDir:".sisyphus",stones:[],tag:"latest"};class ht extends fe{name="github";get apiPath(){return`repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}`}async ensureAvailable(){try{await Bun.$`which gh`.quiet()}catch{throw new d("GitHub CLI (gh) is not installed","Install from https://cli.github.com and run: gh auth login")}try{await Bun.$`gh auth status`.quiet()}catch{throw new d("GitHub CLI (gh) is not authenticated","Run: gh auth login")}}async getDefaultBranch(){try{return(await Bun.$`gh repo view --json defaultBranchRef --jq .defaultBranchRef.name`.quiet()).stdout.toString().trim()||pe}catch{return pe}}async findPr(e){try{let t=[];if(e.head)t.push("--head",e.head);if(e.label)t.push("--label",e.label);let n=await Bun.$`gh pr list --json number,url,title,body,labels,author,headRefName,baseRefName,mergeCommit,state --limit 1 ${t}`.quiet(),r=JSON.parse(n.stdout.toString());if(!r[0])return null;return this.mapPrResponse(r[0])}catch{return null}}async createPr(e){let t=await Bun.$`gh api ${this.apiPath}/pulls --method POST -f head=${e.head} -f base=${e.base} -f title=${e.title} -f body=${e.body}`,r=JSON.parse(t.stdout.toString()).number;if(e.labels&&e.labels.length>0){let i=e.labels.flatMap((s)=>["-f",`labels[]=${s}`]);await Bun.$`gh api ${this.apiPath}/issues/${r}/labels --method POST ${i}`}return this.getPr(r)}async updatePr(e,t){let n=[];if(t.title)n.push("--title",t.title);if(t.body)n.push("--body",t.body);await Bun.$`gh pr edit ${e} ${n}`}async getPr(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e}`.quiet(),n=JSON.parse(t.stdout.toString());return this.mapRestApiResponse(n)}catch{throw new d(`Failed to fetch PR #${e}`,"Make sure the PR exists and you have access")}}async getPrFromCurrentBranch(){try{let e=await Bun.$`gh pr view --json number,title,body,labels,author,headRefName,baseRefName,url,mergeCommit,state`.quiet(),t=JSON.parse(e.stdout.toString());return this.mapPrResponse(t)}catch{throw new d("No PR found for current branch","Make sure you have an open PR or provide a URL with --url")}}async getPrCommits(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/commits --jq '.[].sha'`.quiet()).stdout.toString().trim().split(`
|
|
91
91
|
`).filter(Boolean)}catch{return[]}}async getPrFiles(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/files --jq '.[].filename'`.quiet()).stdout.toString().trim().split(`
|
|
92
|
-
`).filter(Boolean)}catch{return[]}}async ensureLabelExists(e,t){try{let n=t?.description??"",r=t?.color?["--color",t.color]:[];await Bun.$`gh label create ${e} --description ${n} ${r} --force`.quiet()}catch{}}async createRelease(e){await Bun.$`gh release create ${e.tag} --title ${e.title} --notes ${e.notes}`}async deleteRelease(e){try{await Bun.$`gh release delete ${e} --yes`.quiet()}catch{}}mapRestApiResponse(e){return{author:e.user?.login??
|
|
92
|
+
`).filter(Boolean)}catch{return[]}}async ensureLabelExists(e,t){try{let n=t?.description??"",r=t?.color?["--color",t.color]:[];await Bun.$`gh label create ${e} --description ${n} ${r} --force`.quiet()}catch{}}async createRelease(e){await Bun.$`gh release create ${e.tag} --title ${e.title} --notes ${e.notes}`}async deleteRelease(e){try{await Bun.$`gh release delete ${e} --yes`.quiet()}catch{}}mapRestApiResponse(e){return{author:e.user?.login??Ge,baseBranch:e.base?.ref??pe,body:e.body??"",headBranch:e.head?.ref??"",labels:e.labels?.map((t)=>t.name)??[],mergeCommitSha:e.merge_commit_sha,merged:e.merged,number:e.number,title:e.title,url:e.html_url}}mapPrResponse(e){return{author:e.author?.login??Ge,baseBranch:e.baseRefName??pe,body:e.body??"",headBranch:e.headRefName??"",labels:e.labels?.map((t)=>t.name)??[],mergeCommitSha:e.mergeCommit?.oid??null,merged:e.state==="MERGED",number:e.number,title:e.title,url:e.url}}}var Ps="https://gitlab.com/api/v4";class ft extends fe{name="gitlab";authHeader={};apiUrl;projectPath;constructor(e){super(e);this.apiUrl=process.env.CI_API_V4_URL??Ps,this.projectPath=encodeURIComponent(`${this.owner}/${this.repo}`)}async ensureAvailable(){this.authHeader=await this.resolveAuth()}async getDefaultBranch(){try{return(await this.api(`/projects/${this.projectPath}`)).default_branch||pe}catch{return pe}}async findPr(e){try{let t=new URLSearchParams({per_page:"1",state:"opened"});if(e.head)t.set("source_branch",e.head);if(e.label)t.set("labels",e.label);let n=await this.api(`/projects/${this.projectPath}/merge_requests?${t}`);if(!n[0])return null;return this.mapMrResponse(n[0])}catch{return null}}async createPr(e){let t={description:e.body,source_branch:e.head,target_branch:e.base,title:e.title};if(e.labels?.length)t.labels=e.labels.join(",");let n=await this.api(`/projects/${this.projectPath}/merge_requests`,{body:JSON.stringify(t),method:"POST"});return this.mapMrResponse(n)}async updatePr(e,t){let n={};if(t.title)n.title=t.title;if(t.body)n.description=t.body;await this.api(`/projects/${this.projectPath}/merge_requests/${e}`,{body:JSON.stringify(n),method:"PUT"})}async getPr(e){try{let t=await this.api(`/projects/${this.projectPath}/merge_requests/${e}`);return this.mapMrResponse(t)}catch{throw new d(`Failed to fetch MR !${e}`,"Make sure the MR exists and you have access")}}async getPrFromCurrentBranch(){try{let t=(await Bun.$`git rev-parse --abbrev-ref HEAD`.quiet()).stdout.toString().trim(),n=new URLSearchParams({per_page:"1",source_branch:t,state:"opened"}),r=await this.api(`/projects/${this.projectPath}/merge_requests?${n}`);if(!r[0])throw Error("No MR found");return this.mapMrResponse(r[0])}catch{throw new d("No MR found for current branch","Make sure you have an open MR or provide a URL with --url")}}async getPrCommits(e){try{return(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/commits`)).map((n)=>n.id)}catch{return[]}}async getPrFiles(e){try{return(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/changes`)).changes?.map((n)=>n.new_path)??[]}catch{return[]}}async ensureLabelExists(e,t){try{let n={name:e};if(t?.description)n.description=t.description;if(t?.color)n.color=`#${t.color}`;await this.api(`/projects/${this.projectPath}/labels`,{body:JSON.stringify(n),method:"POST"})}catch{}}async createRelease(e){await this.api(`/projects/${this.projectPath}/releases`,{body:JSON.stringify({description:e.notes,name:e.title,tag_name:e.tag}),method:"POST"})}async deleteRelease(e){try{await this.api(`/projects/${this.projectPath}/releases/${encodeURIComponent(e)}`,{method:"DELETE"})}catch{}}async resolveAuth(){if(process.env.GITLAB_TOKEN)return{"PRIVATE-TOKEN":process.env.GITLAB_TOKEN};if(process.env.CI_JOB_TOKEN)return{"JOB-TOKEN":process.env.CI_JOB_TOKEN};try{let e=await Bun.$`glab auth status --show-token`.quiet(),n=(e.stdout.toString()+e.stderr.toString()).match(/Token found:\s*(\S+)/);if(n?.[1])return{Authorization:`Bearer ${n[1]}`}}catch{}throw new d("GitLab token not found","Set GITLAB_TOKEN environment variable or install glab CLI and run: glab auth login")}async api(e,t){let n=await fetch(`${this.apiUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...this.authHeader,...t?.headers}});if(!n.ok){let r=await n.text().catch(()=>"");throw Error(`GitLab API error: ${n.status} ${n.statusText}${r?` \u2014 ${r}`:""}`)}return n.json()}mapMrResponse(e){return{author:e.author?.username??Ge,baseBranch:e.target_branch??pe,body:e.description??"",headBranch:e.source_branch??"",labels:e.labels??[],mergeCommitSha:e.merge_commit_sha,merged:e.state==="merged",number:e.iid,title:e.title,url:e.web_url}}}var ws=/github\.com[:/]([^/]+)\/([^/.]+)/,vs=/gitlab\.com[:/]([^/]+)\/([^/.]+)/,ks=/bitbucket\.org[:/]([^/]+)\/([^/.]+)/,Cs=/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/,$s=/gitlab\.com\/([^/]+)\/([^/]+)\/-\/merge_requests\/(\d+)/,Rs=/bitbucket\.org\/([^/]+)\/([^/]+)\/pull-requests\/(\d+)/;async function Fe(){let e=await Mr();if(!e)throw new d("Could not detect git provider","Make sure you have a git remote configured (origin)");let t=Ss(e);return await t.ensureAvailable(),t}function Ss(e){switch(e.provider){case"github":return new ht(e);case"gitlab":return new ft(e);case"bitbucket":return new mt(e);default:throw new d(`Unsupported provider: ${e.provider}`)}}async function Mr(){let e=await Tt();if(!e)return null;return _t(e)}async function Ir(){let e=await Mr();if(!e)throw new d("Could not detect git provider","Make sure you have a git remote configured (origin)");return e.provider}async function Tt(){try{return(await Bun.$`git remote get-url origin`.quiet()).stdout.toString().trim()||null}catch{return null}}function _t(e){let t=[[ws,"github"],[vs,"gitlab"],[ks,"bitbucket"]];for(let[n,r]of t){let i=e.match(n);if(!i)continue;let[,s,o]=i;if(s&&o)return{owner:s,provider:r,repo:o}}return null}function Zt(e){let t=[[Cs,"github"],[$s,"gitlab"],[Rs,"bitbucket"]];for(let[n,r]of t){let i=e.match(n);if(!i)continue;let[,s,o,a]=i;if(s&&o&&a)return{number:Number.parseInt(a,10),owner:s,provider:r,repo:o}}return null}import{existsSync as Dr}from"fs";import{readFile as Ms}from"fs/promises";import{dirname as Is,join as Qt}from"path";import{fileURLToPath as Ds}from"url";var dt={"create-stone":{description:"When a PR is merged, create stone and update release PR",name:"Handle PR merge (stone + release PR)"},release:{description:"When the release PR is merged, publish packages",name:"Publish release"}},Fs=Qt(Is(Ds(import.meta.url)),"templates"),Fr={"create-stone":"sis-create-stone.yml",release:"sis-release.yml"};class Xt{async generate(e){let t=[];for(let n of e){let r=await this.readTemplate(n),i=this.getOutputPath(n);t.push({content:r,path:i})}return t}getExistingFiles(e){return e.map((t)=>this.getOutputPath(t)).filter((t)=>Dr(t))}async readTemplate(e){let t=Qt(Fs,this.provider,Fr[e]);return Ms(t,"utf-8")}}class yt extends Xt{provider="github";outputDir=".github/workflows";getOutputPath(e){return Qt(this.outputDir,Fr[e])}}var qe=".gitlab-ci-sisyphus.yml";class bt extends Xt{provider="gitlab";outputDir=".";async generate(e){let t=[];t.push(`stages:
|
|
93
93
|
- sisyphus
|
|
94
94
|
`);for(let n of e){let r=await this.readTemplate(n);t.push(r)}return[{content:t.join(`
|
|
95
|
-
`),path:qe}]}getExistingFiles(e){return
|
|
96
|
-
- local: '${qe}'`}getOutputPath(e){return qe}}function
|
|
95
|
+
`),path:qe}]}getExistingFiles(e){return Dr(qe)?[qe]:[]}getIncludeInstruction(){return`include:
|
|
96
|
+
- local: '${qe}'`}getOutputPath(e){return qe}}function jr(e){switch(e){case"github":return new yt;case"gitlab":return new bt;default:throw Error(`CI generation is not supported for ${e}`)}}var As={bitbucket:"Bitbucket Pipelines",github:"GitHub Actions",gitlab:"GitLab CI"},Ns=F({all:{alias:"a",default:!1,description:"Install all workflows",type:"boolean"},createStone:{default:!1,description:"Install create-stone workflow",type:"boolean"},dryRun:{alias:"d",default:!1,description:"Preview without writing files",type:"boolean"},release:{default:!1,description:"Install release workflow",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class en extends I{name="init";description="Set up CI workflows for automated releases";args=Ns;prompts=!0;async execute(e){let t=await Ir(),n=jr(t);l.info(`Detected ${c.bold(As[t])} repository
|
|
97
97
|
`);let r=await this.selectWorkflows(e);if(r.length===0){l.info(c.dim("No workflows selected"));return}let i=n.getExistingFiles(r);if(i.length>0&&!e.args.yes){if(!e.interactive)throw new d(`Workflows already exist: ${i.join(", ")}`,"Use --yes to overwrite existing workflows");if(l.warn(`The following files already exist:
|
|
98
98
|
${i.map((a)=>` ${a}`).join(`
|
|
99
|
-
`)}`),!await
|
|
100
|
-
${c.bold(o.path)}:`),l.info(c.dim(o.content));return}for(let o of s){let a=
|
|
99
|
+
`)}`),!await D({initialValue:!1,message:"Overwrite existing files?"}))return}let s=await n.generate(r);if(e.args.dryRun){for(let o of s)l.info(`
|
|
100
|
+
${c.bold(o.path)}:`),l.info(c.dim(o.content));return}for(let o of s){let a=Os(o.path);if(a!=="."&&!js(a))await Es(a,{recursive:!0});await Ls(o.path,o.content,"utf-8")}if(N(s.map((o)=>` ${c.green("+")} ${o.path}`).join(`
|
|
101
101
|
`),c.green("CI workflows created")),n instanceof bt)l.info(`
|
|
102
102
|
Add this to your ${c.bold(".gitlab-ci.yml")}:
|
|
103
103
|
`),l.info(c.cyan(n.getIncludeInstruction())),l.info(""),l.info(`${c.yellow("Note:")} Add a ${c.bold("GITLAB_TOKEN")} CI/CD variable (Personal Access Token with ${c.bold("api")} + ${c.bold("write_repository")} scopes)`),l.info(c.dim("Required for creating release PRs. Settings \u2192 CI/CD \u2192 Variables")),l.info("");if(n instanceof yt)l.info(`
|
|
104
|
-
${c.yellow("Note:")} Enable ${c.bold('"Allow GitHub Actions to create and approve pull requests"')}`),l.info(c.dim("Settings \u2192 Actions \u2192 General \u2192 Workflow permissions")),l.info("");l.info(c.dim("Commit and push these files to enable the workflows."))}async selectWorkflows(e){let t=this.getWorkflowsFromFlags(e);if(t.length>0)return t;if(!e.interactive)throw new d("No workflows specified","Use --all or specify workflows with --createStone, --release");return ce({initialValues:Object.keys(dt),message:"Select workflows to create",options:Object.entries(dt).map(([n,r])=>({hint:r.description,label:r.name,value:n})),required:!1})}getWorkflowsFromFlags(e){if(e.args.all)return Object.keys(dt);let t=[];if(e.args.createStone)t.push("create-stone");if(e.args.release)t.push("release");return t}}var
|
|
105
|
-
`).filter(Boolean);s.push(q.parse(
|
|
106
|
-
`).filter(Boolean)}static async getBody(e){return(await Bun.$`git log -1 --pretty=format:"%b" ${e}`.quiet()).stdout.toString().trim()||void 0}static parse(e,t,n){let r=t.match(
|
|
104
|
+
${c.yellow("Note:")} Enable ${c.bold('"Allow GitHub Actions to create and approve pull requests"')}`),l.info(c.dim("Settings \u2192 Actions \u2192 General \u2192 Workflow permissions")),l.info("");l.info(c.dim("Commit and push these files to enable the workflows."))}async selectWorkflows(e){let t=this.getWorkflowsFromFlags(e);if(t.length>0)return t;if(!e.interactive)throw new d("No workflows specified","Use --all or specify workflows with --createStone, --release");return ce({initialValues:Object.keys(dt),message:"Select workflows to create",options:Object.entries(dt).map(([n,r])=>({hint:r.description,label:r.name,value:n})),required:!1})}getWorkflowsFromFlags(e){if(e.args.all)return Object.keys(dt);let t=[];if(e.args.createStone)t.push("create-stone");if(e.args.release)t.push("release");return t}}var me;((s)=>{s.Major="major";s.Minor="minor";s.Patch="patch";s.Dependency="dependency";s.Snapshot="snapshot"})(me||={});var Er={["major"]:5,["minor"]:4,["patch"]:3,["dependency"]:2,["snapshot"]:1},je={["major"]:"\uD83D\uDEA8",["minor"]:"\u2728",["patch"]:"\uD83D\uDC1B",["dependency"]:"\uD83D\uDCE6",["snapshot"]:"\uD83D\uDCF8"},Ee={["major"]:c.red,["minor"]:c.yellow,["patch"]:c.green,["dependency"]:c.blue,["snapshot"]:c.magenta},Pe=["major","minor","patch","dependency","snapshot"];function Bs(e,t){return Er[e]-Er[t]}function Lr(e,t){return Bs(e,t)>=0?e:t}function Or(e){return Object.values(me).includes(e)}var xs=/^(\w+)(?:\(([^)]+)\))?(!)?: (.+)$/,tn="\x1F",Us=new Set(["build","chore","ci","docs","feat","fix","perf","refactor","style","test"]);class q{hash;subject;author;body;type;scope;breaking;message;files;constructor(e){this.hash=e.hash,this.subject=e.subject,this.author=e.author,this.body=e.body,this.type=e.type,this.scope=e.scope,this.breaking=e.breaking,this.message=e.message,this.files=e.files}static async since(e){if(e){let t=await q.tryFetchFromRange(`${e}..HEAD`);if(t)return t}return q.fetchFromRange("HEAD")}static async inRange(e,t){let n=[`origin/${e}..origin/${t}`,`${e}..${t}`];for(let r of n){let i=await q.tryFetchFromRange(r);if(i)return i}return[]}static async fromHash(e){try{let n=(await Bun.$`git log -1 --pretty=format:"%H%x1f%s%x1f%an" ${e}`.quiet()).stdout.toString().trim();if(!n)return null;let r=n.split(tn);if(r.length<3)return null;let[i,s,o]=r;if(!i||!s||!o)return null;return q.hydrate(i,s,o)}catch{return null}}static async fromMerge(e){try{let n=(await Bun.$`git rev-parse ${e}^2`.quiet()).stdout.toString().trim();if(!n)return[];return q.fetchFromRange(`${e}^1..${n}`)}catch{return[]}}static async tryFetchFromRange(e){try{return await q.fetchFromRange(e)}catch{return null}}static async fetchFromRange(e){let r=(await Bun.$`git log ${e} --pretty=format:${"%x00%H%x1f%s%x1f%an%x1f%b%x00"} --name-only --no-merges`.quiet()).stdout.toString().trim();if(!r)return[];let i=r.split("\x00").filter(Boolean),s=[];for(let o=0;o<i.length;o+=2){let a=i[o];if(!a)continue;let g=a.split(tn);if(g.length<3)continue;let[p,u,f]=g;if(!p||!u||!f)continue;let y=g.slice(3).join(tn).trim()||void 0,b=(i[o+1]??"").split(`
|
|
105
|
+
`).filter(Boolean);s.push(q.parse(p,u,f).withFiles(b).withBody(y))}return s}static async hydrate(e,t,n){let r=await q.getFiles(e),i=await q.getBody(e);return q.parse(e,t,n).withFiles(r).withBody(i)}static async getFiles(e){return(await Bun.$`git diff-tree --no-commit-id --name-only -r ${e}`.quiet()).stdout.toString().trim().split(`
|
|
106
|
+
`).filter(Boolean)}static async getBody(e){return(await Bun.$`git log -1 --pretty=format:"%b" ${e}`.quiet()).stdout.toString().trim()||void 0}static parse(e,t,n){let r=t.match(xs);if(r){let[,i="",s,o,a=""]=r;if(i&&Us.has(i))return new q({author:n,breaking:!!o,files:[],hash:e,message:a,scope:s,subject:t,type:i})}return new q({author:n,breaking:!1,files:[],hash:e,message:t,subject:t,type:de})}get shortHash(){return this.hash.slice(0,ut)}get isConventional(){return this.type!==de}withFiles(e){return new q({...this.toOptions(),files:e})}withBody(e){return new q({...this.toOptions(),body:e})}toInfo(e){return{body:this.body,hash:this.shortHash,message:this.message,packages:e,scope:this.scope,subject:this.subject,type:this.type}}toOptions(){return{author:this.author,body:this.body,breaking:this.breaking,files:this.files,hash:this.hash,message:this.message,scope:this.scope,subject:this.subject,type:this.type}}}var J=(e)=>e.length>0?e:void 0;var Pt=1,Gs=1,wt=10,qs=/[.ZT:-]/g,Hs=14,Ws="nightly";class X{static bump(e,t,n){let[r="0.0.0",i=""]=e.split("-"),[s="",o="0"]=i.split(".");if(t==="snapshot")return X.formatSnapshot(n);if(n&&t!=="dependency")return X.formatTagged(r,n,s,o);if(t==="dependency"&&s)return X.formatTagged(r,s,s,o);return X.bumpBase(r,t)}static formatLabel(e,t,n,r){let i=X.bump(t,n,r),s=je[n];return`${e}@${t} => ${i} ${s}`}static formatSnapshot(e){let t=new Date().toISOString().replace(qs,"").slice(0,Hs);return`0.0.0-${e||Ws}-${t}`}static formatTagged(e,t,n,r){let i=t===n?Number.parseInt(r,wt)+Pt:Gs;return`${e}-${t}.${i}`}static bumpBase(e,t){let[n="0",r="0",i="0"]=e.split("."),s=Number.parseInt(n,wt),o=Number.parseInt(r,wt),a=Number.parseInt(i,wt);switch(t){case"major":return`${s+Pt}.0.0`;case"minor":return`${s}.${o+Pt}.0`;case"dependency":case"patch":return`${s}.${o}.${a+Pt}`;default:return`${s}.${o}.${a}`}}}class ee{name;version;file;dependencyOf;bump;tag;isPrivate;_newVersion;constructor(e){this.name=e.name,this.version=e.version,this.file=e.file,this.dependencyOf=e.dependencyOf??[],this.bump=e.bump,this.tag=e.tag,this.isPrivate=e.isPrivate??!1,this._newVersion=e.newVersion}static fromJson(e,t){return new ee({file:t,isPrivate:e.private??!1,name:e.name,version:e.version||kr})}static applyStone(e,t){let n=[];for(let r of Pe)for(let i of e.getPackages(r)){let s=t.get(i);if(s)n.push(s.withBump(r,e.tag))}return n}get newVersion(){if(this._newVersion)return this._newVersion;if(!this.bump)return;return X.bump(this.version,this.bump,this.tag)}get label(){if(!this.bump)return`${this.name}@${this.version}`;return X.formatLabel(this.name,this.version,this.bump,this.tag)}withDependencyOf(e){return new ee({...this.toOptions(),dependencyOf:e})}withBump(e,t){return new ee({...this.toOptions(),bump:e,newVersion:void 0,tag:t})}withVersions(e,t){return new ee({...this.toOptions(),newVersion:t,version:e})}toOptions(){return{bump:this.bump,dependencyOf:this.dependencyOf,file:this.file,isPrivate:this.isPrivate,name:this.name,newVersion:this._newVersion,tag:this.tag,version:this.version}}}import{randomUUID as Js}from"crypto";class S{id;message;tag;description;commits;_packages;constructor(e){this.id=e.id,this.message=e.message,this.tag=e.tag,this.description=e.description,this.commits=e.commits,this._packages=e.packages}static create(e,t=0){let n=S.generateId(t);return S.fromData(n,e)}static fromJson(e){return S.fromData(e.id,e)}static mergeAll(e){let[t,...n]=e;if(!t)throw Error("No stones to merge");if(n.length===0)return t;let r=e.map((i)=>i.message).join("; ");return S.merge(e,r).stone}static merge(e,t){let n=new Map,r=[];for(let u of e)S.collectBumps(u,"major",n,r),S.collectBumps(u,"minor",n,r),S.collectBumps(u,"patch",n,r),S.collectBumps(u,"dependency",n,r);let i=S.categorizeBumps(n),s=e.map((u)=>u.description).filter(Boolean).join(`
|
|
107
107
|
|
|
108
|
-
`),o=e.flatMap((u)=>u.commits??[]),a=[...new Set(e.map((u)=>u.tag).filter(Boolean))],g=`merged-${Date.now()}`,
|
|
108
|
+
`),o=e.flatMap((u)=>u.commits??[]),a=[...new Set(e.map((u)=>u.tag).filter(Boolean))],g=`merged-${Date.now()}`,p=new S({commits:o.length>0?o:void 0,description:s||void 0,id:g,message:t,packages:i,tag:a[0]});return{conflicts:[...new Set(r)],stone:p}}static collectBumps(e,t,n,r){for(let i of e.getPackages(t)){let s=n.get(i);if(!s){n.set(i,t);continue}if(s===t)continue;r.push(i);let o=Lr(t,s);if(o!==s)n.set(i,o)}}static categorizeBumps(e){let t=new Map;for(let n of Pe)t.set(n,[]);for(let[n,r]of e)t.get(r)?.push(n);return t}static fromData(e,t){let n=new Map;return n.set("major",t.major??[]),n.set("minor",t.minor??[]),n.set("patch",t.patch??[]),n.set("dependency",t.dependency??[]),n.set("snapshot",t.snapshot??[]),new S({commits:t.commits,description:t.description,id:e,message:t.message,packages:n,tag:t.tag})}static generateId(e){let t=String(e+1).padStart($r,"0"),n=Js().slice(0,Rr);return`${t}-${n}`}get major(){return this._packages.get("major")??[]}get minor(){return this._packages.get("minor")??[]}get patch(){return this._packages.get("patch")??[]}get dependency(){return this._packages.get("dependency")??[]}get snapshot(){return this._packages.get("snapshot")??[]}get allPackages(){let e=[];for(let t of this._packages.values())e.push(...t);return e}get isEmpty(){return this.allPackages.length===0}affectsPackage(e){return this.allPackages.includes(e)}getPackages(e){return this._packages.get(e)??[]}withMessage(e){return new S({...this.toOptions(),message:e})}withTag(e){return new S({...this.toOptions(),tag:e})}withDescription(e){return new S({...this.toOptions(),description:e})}withCommits(e){return new S({...this.toOptions(),commits:e})}withPackages(e,t){let n=new Map(this._packages);return n.set(e,t),new S({...this.toOptions(),packages:n})}toOptions(){return{commits:this.commits,description:this.description,id:this.id,message:this.message,packages:new Map(this._packages),tag:this.tag}}toJson(){return{commits:this.commits&&this.commits.length>0?this.commits:void 0,dependency:J(this.dependency),description:this.description,id:this.id,major:J(this.major),message:this.message,minor:J(this.minor),patch:J(this.patch),snapshot:J(this.snapshot),tag:this.tag}}}import{readFile as Ys,rm as Ks,writeFile as Ar}from"fs/promises";import{dirname as Ts,join as _s}from"path";var Vs={bitbucket:"commits",github:"commit",gitlab:"-/commit"},zs={bitbucket:"bitbucket.org",github:"github.com",gitlab:"gitlab.com"};class He{cached=void 0;async getRemoteInfo(){if(this.cached!==void 0)return this.cached;let e=await Tt();if(!e)return this.cached=null,null;let t=_t(e);if(!t)return this.cached=null,null;let n=zs[t.provider],r=Vs[t.provider],i=`https://${n}/${t.owner}/${t.repo}`;return this.cached={...t,commitUrl:(s)=>`${i}/${r}/${s}`},this.cached}}class we{config;originals=new Map;remoteParser=new He;commitUrlFn=null;constructor(e){this.config=e}async generate(e,t){await this.initCommitLinks();let n=new Map(t.map((r)=>[r.name,r]));for(let r of t){let i=this.filterStonesForPackage(e,r.name),s=this.getBumpedDependencies(e,r.name,n);await this.generateForPackage(i,r,s)}if(this.config.root)await this.generateRoot(e,t)}async initCommitLinks(){let e=await this.remoteParser.getRemoteInfo();this.commitUrlFn=e?.commitUrl??null}getBumpedDependencies(e,t,n){let r=new Set;for(let i of e){if(!i.dependency.includes(t))continue;for(let s of[...i.major,...i.minor,...i.patch])r.add(s)}return[...r].map((i)=>n.get(i)).filter((i)=>i!==void 0)}filterStonesForPackage(e,t){return e.filter((n)=>this.hasDirectChanges(n,t))}hasDirectChanges(e,t){return e.major.includes(t)||e.minor.includes(t)||e.patch.includes(t)}async rollback(){for(let[e,t]of this.originals)if(t===null)await Ks(e,{force:!0});else await Ar(e,t,"utf-8");this.originals.clear()}async generateForPackage(e,t,n){let r=_s(Ts(t.file),this.config.filename),i=this.formatEntry(e,t,n);await this.prependToChangelog(r,i,t.name)}async generateRoot(e,t){let n=this.config.filename,r=this.formatRootEntry(e,t);await this.prependToChangelog(n,r,"Changelog")}async prependToChangelog(e,t,n){let r=await this.readExisting(e);this.originals.set(e,r);let i=r?this.extractTitle(r):`# ${n}`,s=r?this.extractRest(r):"",o=`${i}
|
|
109
109
|
|
|
110
110
|
${t}${s?`
|
|
111
111
|
|
|
112
112
|
${s}`:""}
|
|
113
|
-
`;await
|
|
113
|
+
`;await Ar(e,o,"utf-8")}async readExisting(e){try{return await Ys(e,"utf-8")}catch{return null}}extractTitle(e){let t=e.split(`
|
|
114
114
|
`)[0]??"";return t.startsWith("#")?t:"# Changelog"}extractRest(e){let t=e.split(`
|
|
115
115
|
`);if(!(t[0]??"").startsWith("#"))return e;let r=1;while(r<t.length&&t[r]?.trim()==="")r++;return t.slice(r).join(`
|
|
116
116
|
`).trim()}formatEntry(e,t,n){let r=this.formatPackageHeader(t),i=n.length>0,s=[`## ${r}`];for(let o of e)s.push("",`### ${Kt} ${o.message}`),s.push("",this.formatStoneContent(o,t.name));if(i){s.push("",`### ${this.config.sections.dependencies}`);for(let o of n)s.push(`- \`${o.name}\` ${o.version} \u2192 ${o.newVersion}`)}return s.join(`
|
|
@@ -141,69 +141,70 @@ ${this.convertHeadersToBold(e).split(`
|
|
|
141
141
|
<summary>Details</summary>
|
|
142
142
|
|
|
143
143
|
${r}
|
|
144
|
-
</details>`}return n}}import{readdir as
|
|
145
|
-
`),r=!1,i=[],s=[];for(let g of n)if(g.trim()==="---")r=!r;else if(r)i.push(g);else if(i.length>0)s.push(g);let o={};for(let g of i){let
|
|
146
|
-
`).trim()}}catch{return null}}async parseConfig(){try{let e=nn(this.changesetDir,
|
|
144
|
+
</details>`}return n}}import{readdir as Nr,readFile as Br}from"fs/promises";import{join as nn}from"path";var Zs=".changeset",Qs="config.json";class rn{root;constructor(e=process.cwd()){this.root=e}get changesetDir(){return nn(this.root,Zs)}async exists(){try{return await Nr(this.changesetDir),!0}catch{return!1}}async parse(){let e=[],t=[],n=await this.findChangesetFiles();for(let i of n){let s=await this.parseFile(i);if(s)t.push(s);else e.push(`Failed to parse: ${i}`)}let r=await this.parseConfig();return{changesets:t,config:r,errors:e}}async findChangesetFiles(){try{return(await Nr(this.changesetDir)).filter((t)=>t.endsWith(".md")&&t!=="README.md").map((t)=>nn(this.changesetDir,t))}catch{return[]}}async parseFile(e){try{let n=(await Br(e,"utf-8")).split(`
|
|
145
|
+
`),r=!1,i=[],s=[];for(let g of n)if(g.trim()==="---")r=!r;else if(r)i.push(g);else if(i.length>0)s.push(g);let o={};for(let g of i){let p=g.match(/^"(.+)":\s*(major|minor|patch)$/);if(p?.[1]&&p[2])o[p[1]]=p[2]}if(Object.keys(o).length===0)return null;return{filename:e.split("/").pop()??"",packages:o,summary:s.join(`
|
|
146
|
+
`).trim()}}catch{return null}}async parseConfig(){try{let e=nn(this.changesetDir,Qs),t=await Br(e,"utf-8");return JSON.parse(t)}catch{return null}}toStoneData(e){let t=[],n=[],r=[];for(let[a,g]of Object.entries(e.packages))switch(g){case"major":t.push(a);break;case"minor":n.push(a);break;case"patch":r.push(a);break}let i=e.summary.split(`
|
|
147
147
|
`),s=i[0]?.trim()||"Migrated from changeset";return{description:i.slice(1).join(`
|
|
148
|
-
`).trim()||void 0,major:J(t),message:s,minor:J(n),patch:J(r)}}}function vt(e){let t=new Map;for(let[n,r]of e){let i=r.file.replace(/\\/g,"/"),s=i.substring(0,i.lastIndexOf("/"))||".";t.set(s,n)}return t}function Le(e,t){let n=new Set;for(let r of e){let i=t.get(r);if(i?.dependencyOf){for(let s of i.dependencyOf)if(!e.includes(s))n.add(s)}}return Array.from(n)}function We(e,t,n=!0){let r=new Set;for(let i of e)for(let[s,o]of t){let a=s===".",g=i.startsWith(`${s}/`);if(a?n:g)r.add(o)}return r}import{existsSync as ve}from"fs";import{mkdir as
|
|
149
|
-
`;await Gr(e.file,s,"utf-8")}detectIndent(e){let t=e.match(/^[\t ]+/m);return t?t[0]:2}}
|
|
150
|
-
`
|
|
151
|
-
`).filter(Boolean)}catch{return
|
|
148
|
+
`).trim()||void 0,major:J(t),message:s,minor:J(n),patch:J(r)}}}function vt(e){let t=new Map;for(let[n,r]of e){let i=r.file.replace(/\\/g,"/"),s=i.substring(0,i.lastIndexOf("/"))||".";t.set(s,n)}return t}function Le(e,t){let n=new Set;for(let r of e){let i=t.get(r);if(i?.dependencyOf){for(let s of i.dependencyOf)if(!e.includes(s))n.add(s)}}return Array.from(n)}function We(e,t,n=!0){let r=new Set;for(let i of e)for(let[s,o]of t){let a=s===".",g=i.startsWith(`${s}/`);if(a?n:g)r.add(o)}return r}import{existsSync as ve}from"fs";import{mkdir as xr,readdir as sn,readFile as Ur,rename as Xs,unlink as eo,writeFile as to}from"fs/promises";import{join as ke}from"path";class R{config;constructor(e){this.config=e}get sisyphusDir(){return this.config.get("sisyphusDir")||lt}get stonesPath(){return this.config.get("stonesPath")||ke(this.sisyphusDir,Pr)}get releasedPath(){return ke(this.sisyphusDir,wr)}async list(){let e=await this.listIds(),t=[];for(let n of e){let r=await this.get(n);if(r)t.push(r)}return t}async listIds(){return await this.ensureStorageExists(),(await sn(this.stonesPath)).filter((t)=>t.endsWith(".json")).map((t)=>t.replace(".json","")).sort()}async get(e){let t=this.getFilePath(e);if(!ve(t))return null;try{let n=await Ur(t,"utf-8"),r=JSON.parse(n);return S.fromJson(r)}catch{return null}}async exists(e){return ve(this.getFilePath(e))}async save(e){await this.ensureStorageExists();let t=this.getFilePath(e.id),n=JSON.stringify(e.toJson(),null,2);await to(t,n,"utf-8"),this.addToConfigStones(e.id)}async delete(e){let t=this.getFilePath(e);if(!ve(t))return!1;return await eo(t),this.removeFromConfigStones(e),!0}async deleteMany(e){let t=0;for(let n of e)if(await this.delete(n))t++;return t}async create(e){let t=await this.listIds(),n=S.create(e,t.length);return await this.save(n),n}async count(){return(await this.listIds()).length}async archive(e){if(e.length===0)return"";let t=this.createTimestamp(),n=ke(this.releasedPath,t);await xr(n,{recursive:!0});for(let r of e){let i=this.getFilePath(r.id),s=ke(n,`${r.id}.json`);if(ve(i))await Xs(i,s),this.removeFromConfigStones(r.id)}return t}async getReleasedStones(e){let t=ke(this.releasedPath,e);if(!ve(t))return[];let n=await sn(t),r=[];for(let i of n){if(!i.endsWith(".json"))continue;try{let s=await Ur(ke(t,i),"utf-8"),o=JSON.parse(s);r.push(S.fromJson(o))}catch(s){l.warn(c.dim(`Failed to parse stone "${i}": ${s}`))}}return r}async listReleasedTimestamps(){if(!ve(this.releasedPath))return[];return(await sn(this.releasedPath,{withFileTypes:!0})).filter((t)=>t.isDirectory()).map((t)=>t.name)}async getAllTrackedCommitHashes(){let t=(await this.list()).flatMap((n)=>n.commits??[]).map((n)=>n.hash);return new Set(t)}async listAllStones(){let e=await this.list(),t=await this.listReleasedTimestamps(),n=await Promise.all(t.map((r)=>this.getReleasedStones(r)));return[...e,...n.flat()]}getFilePath(e){return ke(this.stonesPath,`${e}.json`)}createTimestamp(){return new Date().toISOString().replace(/[:.]/g,"-")}async ensureStorageExists(){if(!ve(this.stonesPath))await xr(this.stonesPath,{recursive:!0})}addToConfigStones(e){let t=this.config.getAll();if(!t.stones.includes(e))this.config.set("stones",[...t.stones,e])}removeFromConfigStones(e){let t=this.config.getAll(),n=t.stones.filter((r)=>r!==e);if(n.length!==t.stones.length)this.config.set("stones",n)}}class ${static async scan(e={}){let{filter:t,single:n}=e;if(n)return $.scanRootPackage();let r=await $.getWorkspaces();$.validateWorkspaces(r);let i=await $.scanWorkspaces(r);return{packageNames:$.filterNames(Array.from(i.keys()),t),packages:i}}static async getWorkspaces(){try{let t=(await Bun.file("package.json").json())?.workspaces;if(Array.isArray(t))return t;return t?.packages||[]}catch{throw new d("Could not read package.json","Ensure you're in a project root directory.")}}static validateWorkspaces(e){if(e.length===0)throw new d("No workspaces found in package.json.","Use --single flag or set `single: true` in config for single-package mode.")}static filterNames(e,t){if(!t)return e;return e.filter((n)=>n.includes(t))}static async scanRootPackage(){let e=await Bun.file("package.json").json(),t=ee.fromJson(e,"package.json"),n=new Map;return n.set(t.name,t),{packageNames:[t.name],packages:n}}static async scanWorkspaces(e){let t=new Map,n=new Map;for(let r of e){let i=new Bun.Glob(`${r}/package.json`).scanSync({cwd:process.cwd()});for(let s of i){let o=await $.processPackageFile(s,n);if(o)t.set(o.name,o)}}return $.linkDependencies(t,n),t}static async processPackageFile(e,t){let n=await Bun.file(e).json(),r=ee.fromJson(n,e);return $.trackDependencies(r.name,n,t),r}static trackDependencies(e,t,n){let r={...t.dependencies,...t.devDependencies};for(let[i,s]of Object.entries(r)){if(!s?.startsWith("workspace"))continue;let o=n.get(i)||[];if(!o.includes(e))n.set(i,[...o,e])}}static linkDependencies(e,t){for(let[n,r]of t){let i=e.get(n);if(i)e.set(n,i.withDependencyOf(r))}}}var no={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch",[de]:"patch"};class Ce{config;stoneManager;constructor(e){this.config=e;this.stoneManager=new R(e)}async analyze(e={}){let t=await this.getCommitsSinceLastRelease();if(t.length===0)return[];let n=await this.stoneManager.getAllTrackedCommitHashes();if(n.size>0){if(t=t.filter((i)=>!n.has(i.shortHash)),t.length===0)return[]}let r=this.config.get("commits")?.skip??De.commits.skip;if(t=t.filter((i)=>!this.shouldSkipCommit(i,r)),t.length===0)return[];return this.groupByPackage(t,e)}shouldSkipCommit(e,t){if(t.authors.includes(e.author))return!0;for(let n of t.messagePatterns)try{if(new RegExp(n,"i").test(e.subject))return!0}catch{l.warn(c.yellow(`Invalid regex pattern in commits.skip.messagePatterns: "${n}"`))}return!1}get commitCount(){return this.getCommitsSinceLastRelease().then((e)=>e.length)}async getCommitsSinceLastRelease(){let t=this.config.get("lastStone")?.commit||void 0;if(!t)return[];return q.since(t)}async groupByPackage(e,t){let{packages:n}=await $.scan({filter:t.filter,single:t.single}),r=vt(n),i=new Map;for(let s of e){let o=We(s.files,r);if(o.size===0)continue;let a=s.breaking?"major":no[s.type]||"patch",g=`${s.type}${s.breaking?"!":""}`,p=i.get(g);if(!p){let u=this.getGroupMessage(s);p={bump:a,commits:[],message:u,packages:new Set},i.set(g,p)}p.commits.push(s.toInfo([...o]));for(let u of o)p.packages.add(u)}return Array.from(i.entries()).filter(([,s])=>s.packages.size>0).sort(([s],[o])=>(Me[s]??Ie)-(Me[o]??Ie)).map(([,s])=>s)}getGroupMessage(e){let t=this.config.get("changelog").sections;if(e.breaking)return t.breaking;return t[e.type]??`${e.type} updates`}static buildStoneData(e,t,n){let r=Array.from(e.packages),i=e.commits.length>0?e.commits:void 0,s=Le(r,t);return{[e.bump]:r,commits:i,dependency:s.length>0?s:void 0,message:e.message,tag:n}}}import{readFile as ro,writeFile as Gr}from"fs/promises";class Je{originals=new Map;async updateAll(e){this.originals.clear();for(let t of e)await this.updatePackage(t)}async rollback(){for(let[e,t]of this.originals)await Gr(e,t,"utf-8");this.originals.clear()}async updatePackage(e){let t=e.newVersion;if(!t)return;let n=await ro(e.file,"utf-8");this.originals.set(e.file,n);let r=JSON.parse(n);r.version=t;let i=this.detectIndent(n),s=`${JSON.stringify(r,null,i)}
|
|
149
|
+
`;await Gr(e.file,s,"utf-8")}detectIndent(e){let t=e.match(/^[\t ]+/m);return t?t[0]:2}}var qr="catalog:",Hr="workspace:",Wr="default",io=2,so=new Set(["*","^","~"]);function Jr(e){let t=Array.isArray(e.workspaces)?void 0:e.workspaces,n={[Wr]:{...e.catalog,...t?.catalog}};return Object.assign(n,e.catalogs,t?.catalogs),n}function Vr(e){let t={};for(let n of e)t[n.name]=n.version||null;return t}function oo(e,t,n,r){let i=t.slice(qr.length)||Wr,s=n[i]?.[e];if(!s)throw new d(`Catalog "${i}" has no entry for "${e}" (required by ${r})`,"Add the entry to the root package.json catalog before publishing");return s}function ao(e,t,n,r){let i=t.slice(Hr.length);if(!(e in n))throw new d(`Workspace package "${e}" (required by ${r}) was not found in the workspace`,"Check the dependency name against your workspaces globs");if(!so.has(i)){if(!i)throw new d(`Invalid workspace specifier "${t}" for "${e}" (required by ${r})`,"Use workspace:*, workspace:^, workspace:~, or workspace:<range>");return i}let s=n[e];if(!s)throw new d(`Workspace package "${e}" (required by ${r}) has no version in its package.json`,"Add a version field before publishing");return i==="*"?s:`${i}${s}`}function on(e,t,n,r){if(!e)return e;let i={};for(let[s,o]of Object.entries(e))if(o.startsWith(qr))i[s]=oo(s,o,t,r);else if(o.startsWith(Hr))i[s]=ao(s,o,n,r);else i[s]=o;return i}function co(e,t,n){let{devDependencies:r,...i}=e;return{...i,dependencies:on(e.dependencies,t,n,e.name),optionalDependencies:on(e.optionalDependencies,t,n,e.name),peerDependencies:on(e.peerDependencies,t,n,e.name)}}function zr(e,t,n){let r=JSON.parse(e),i=co(r,t,n),s=go(e);return`${JSON.stringify(i,null,s)}
|
|
150
|
+
`}function go(e){let t=e.match(/^[\t ]+/m);return t?t[0]:io}class an{config;provider=null;constructor(e){this.config=e}async analyze(e){let t=await this.getProvider(),n=e?await this.fetchFromUrl(t,e):await this.fetchFromCurrentBranch(t),r=this.config.get("single"),{packages:i}=await $.scan({single:r}),s=vt(i),o={isSinglePackage:r,packagePaths:s,provider:t,url:e},{commits:a,affectedPackages:g}=n.merged?await this.analyzeAfterMerge(n,o):await this.analyzeBeforeMerge(n,o),p=this.inferBumpFromLabels(n.labels)??this.inferBumpFromTitle(n.title);return{commits:a,packages:g,pr:n,suggestedBump:p}}async analyzeBeforeMerge(e,t){let n=await q.inRange(e.baseBranch,e.branch);return this.processCommits(n,t)}async analyzeAfterMerge(e,t){if(await this.detectMergeMethod(e.mergeCommitSha)==="squash")return this.analyzeSquashMerge(e,t);return this.analyzeMergeCommit(e,t)}async analyzeSquashMerge(e,t){let n=t.url?await this.fetchFilesFromApi(t.provider,t.url):await this.getFilesFromCommit(e.mergeCommitSha),r=We(n,t.packagePaths,t.isSinglePackage),i={body:e.body||void 0,hash:e.mergeCommitSha?.slice(0,ut)??vr,message:e.title,packages:[...r],subject:e.title,type:this.inferCommitType(e.title)};return{affectedPackages:r,commits:[i]}}async analyzeMergeCommit(e,t){if(!e.mergeCommitSha)return{affectedPackages:new Set,commits:[]};let n=await q.fromMerge(e.mergeCommitSha);return this.processCommits(n,t)}processCommits(e,t){let n=[],r=new Set;for(let i of e){let s=We(i.files,t.packagePaths,t.isSinglePackage);if(s.size===0)continue;n.push(i.toInfo([...s]));for(let o of s)r.add(o)}return{affectedPackages:r,commits:n}}async detectMergeMethod(e){if(!e)return"squash";if(await this.getCommitParentCount(e)===2)return"merge";return"squash"}async getCommitParentCount(e){try{let t=await Bun.$`git rev-parse ${e}^@`.quiet().nothrow();if(t.exitCode!==0)return 1;return t.stdout.toString().trim().split(`
|
|
151
|
+
`).filter(Boolean).length}catch{return 1}}inferCommitType(e){return e.match(/^(\w+)(?:\(.*?\))?!?:/)?.[1]??de}async getProvider(){if(!this.provider)this.provider=await Fe();return this.provider}async fetchFilesFromApi(e,t){let n=Zt(t);if(!n)return[];return e.getPrFiles(n.number)}async fetchFromCurrentBranch(e){let t=await e.getPrFromCurrentBranch();return this.mapPullRequest(t)}async fetchFromUrl(e,t){let n=Zt(t);if(!n)throw new d("Invalid PR URL","Expected a PR/MR URL from GitHub, GitLab, or Bitbucket");if(n.provider!==e.name)throw new d(`PR URL is from ${n.provider}, but repository is on ${e.name}`,"Make sure the PR URL matches the repository provider");let r=await e.getPr(n.number);return this.mapPullRequest(r)}mapPullRequest({headBranch:e,...t}){return{...t,branch:e}}inferBumpFromLabels(e){let t=this.config.get("pr").labelMapping;for(let n of e){let r=n.toLowerCase();for(let[i,s]of Object.entries(t))if(r===i.toLowerCase())return s}return null}inferBumpFromTitle(e){let t=e.toLowerCase();if(t.includes("breaking")||e.includes("!:"))return"major";if(t.includes("feat")||t.includes("feature"))return"minor";if(t.includes("fix")||t.includes("bug"))return"patch";return null}async getFilesFromCommit(e){if(!e)return[];try{return(await Bun.$`git diff-tree --no-commit-id --name-only -r ${e}`.quiet()).stdout.toString().trim().split(`
|
|
152
|
+
`).filter(Boolean)}catch{return[]}}}import{readFile as po,writeFile as Yr}from"fs/promises";import{dirname as Kr,join as mo}from"path";class kt{config;packageUpdater=new Je;changelogGenerator;remoteParser=new He;provider=null;commitUrlFn=null;options;createdTags=[];createdReleases=[];commitCreated=!1;pushedToRemote=!1;publishContext=null;constructor(e,t){this.config=e;this.options=t,this.changelogGenerator=new we(this.config.get("changelog"))}async getProvider(){if(!this.provider)this.provider=await Fe();return this.provider}async initCommitLinks(){if(this.commitUrlFn!==null)return;let e=await this.remoteParser.getRemoteInfo();this.commitUrlFn=e?.commitUrl??null}async preflight(e){if(this.options.dryRun)return;if(await this.hasStagedChanges())throw new d("You have staged changes","Commit or stash them before running roll");let n=await this.getDirtyPackageFiles(e);if(n.length>0)throw new d("Package files have uncommitted changes",`Commit or stash changes in:
|
|
152
153
|
${n.join(`
|
|
153
|
-
`)}`)}async updatePackageVersions(e){if(this.options.dryRun)return;await this.packageUpdater.updateAll(e)}async generateChangelogs(e,t){if(this.options.dryRun)return;await this.changelogGenerator.generate(e,t)}async createCommit(e,t){if(this.options.dryRun)return;let n=t.map((g)=>g.file),r=this.getChangelogFiles(t),i=this.config.get("sisyphusDir"),s=[...n,...r,i],o=this.formatCommitMessage(e,t),a=this.getCommitAuthorArg();await this.run(()=>Bun.$`git add -A -- ${s}`.quiet(),"Failed to stage files"),await this.run(()=>Bun.$`git commit ${a} -m ${o}`.quiet(),"Failed to create commit"),this.commitCreated=!0}getCommitAuthorArg(){let{author:e,email:t}=this.config.get("commit");if(!e)return[];return["--author",t?`${e} <${t}>`:e]}getChangelogFiles(e){let t=this.config.get("changelog").filename,n=e.map((r)=>
|
|
154
|
+
`)}`)}async updatePackageVersions(e){if(this.options.dryRun)return;await this.packageUpdater.updateAll(e)}async generateChangelogs(e,t){if(this.options.dryRun)return;await this.changelogGenerator.generate(e,t)}async createCommit(e,t){if(this.options.dryRun)return;let n=t.map((g)=>g.file),r=this.getChangelogFiles(t),i=this.config.get("sisyphusDir"),s=[...n,...r,i],o=this.formatCommitMessage(e,t),a=this.getCommitAuthorArg();await this.run(()=>Bun.$`git add -A -- ${s}`.quiet(),"Failed to stage files"),await this.run(()=>Bun.$`git commit ${a} -m ${o}`.quiet(),"Failed to create commit"),this.commitCreated=!0}getCommitAuthorArg(){let{author:e,email:t}=this.config.get("commit");if(!e)return[];return["--author",t?`${e} <${t}>`:e]}getChangelogFiles(e){let t=this.config.get("changelog").filename,n=e.map((r)=>mo(Kr(r.file),t));if(this.config.get("changelog").root)n.push(t);return n}async createGitTags(e){if(this.options.dryRun)return;for(let t of e){let n=t.newVersion??t.version,r=`${t.name}@${n}`;await this.run(()=>Bun.$`git tag ${r}`.quiet(),`Failed to create tag ${r}`),this.createdTags.push(r)}}async publishToNpm(e){if(this.options.dryRun)return;for(let t of e){if(t.isPrivate){l.info(c.dim(`Skipping ${t.name} (private)`));continue}await this.publishPackage(t)}}async pushToRemote(){if(this.options.dryRun)return;if(await this.run(()=>Bun.$`git push`.quiet(),"Failed to push commits"),this.createdTags.length>0)await this.pushTags();this.pushedToRemote=!0}async pushTags(){if(this.options.dryRun)return;if(this.createdTags.length===0)return;await this.run(()=>Bun.$`git push --tags`.quiet(),"Failed to push tags")}async createGitRelease(e,t){if(this.options.dryRun)return;await this.initCommitLinks();let n=await this.getProvider();for(let r of t){let i=r.newVersion??r.version,s=`${r.name}@${i}`,o=`${r.name} v${i}`,a=this.filterStonesForPackage(e,r.name),g=this.formatReleaseNotes(a,r);await this.run(()=>n.createRelease({notes:g,tag:s,title:o}),`Failed to create release for ${s}`),this.createdReleases.push(s)}}filterStonesForPackage(e,t){return e.filter((n)=>n.affectsPackage(t))}formatReleaseNotes(e,t){let n=[],r=t.newVersion??t.version;if(n.push(`\`${t.name}\` ${t.version} \u2192 ${r}`),e.length===0)return n.join(`
|
|
154
155
|
`);n.push(""),n.push("<details>"),n.push(`<summary>Stones (${e.length})</summary>`),n.push("");for(let i of e){if(n.push(`### ${i.message}`),n.push(""),i.description)n.push(i.description),n.push("");let s=this.filterCommitsForPackage(i.commits,t.name);if(s.length>0){n.push("<details>"),n.push(`<summary>Commits (${s.length})</summary>`),n.push("");for(let o of s)n.push(this.formatCommitLine(o));n.push(""),n.push("</details>"),n.push("")}}return n.push("</details>"),n.join(`
|
|
155
|
-
`)}filterCommitsForPackage(e,t){if(!e)return[];return e.filter((n)=>n.packages.includes(t))}formatCommitLine(e){return`- ${this.commitUrlFn?`[\`${e.hash}\`](${this.commitUrlFn(e.hash)})`:`\`${e.hash}\``} ${e.subject}`}async rollback(){if(this.createdReleases.length>0){let e=await this.getProvider();for(let t of this.createdReleases)await e.deleteRelease(t)}if(this.createdReleases=[],this.pushedToRemote)for(let e of this.createdTags)try{await Bun.$`git push origin --delete ${e}`.quiet()}catch(t){l.warn(c.dim(`Failed to delete remote tag "${e}": ${t}`))}for(let e of this.createdTags)try{await Bun.$`git tag -d ${e}`.quiet()}catch(t){l.warn(c.dim(`Failed to delete local tag "${e}": ${t}`))}if(this.createdTags=[],this.commitCreated){try{await Bun.$`git reset HEAD~1`.quiet()}catch(e){l.warn(c.dim(`Failed to reset commit: ${e}`))}this.commitCreated=!1}await this.changelogGenerator.rollback(),await this.packageUpdater.rollback()}async publishPackage(e){let t=this.config.get("tag")||
|
|
156
|
+
`)}filterCommitsForPackage(e,t){if(!e)return[];return e.filter((n)=>n.packages.includes(t))}formatCommitLine(e){return`- ${this.commitUrlFn?`[\`${e.hash}\`](${this.commitUrlFn(e.hash)})`:`\`${e.hash}\``} ${e.subject}`}async rollback(){if(this.createdReleases.length>0){let e=await this.getProvider();for(let t of this.createdReleases)await e.deleteRelease(t)}if(this.createdReleases=[],this.pushedToRemote)for(let e of this.createdTags)try{await Bun.$`git push origin --delete ${e}`.quiet()}catch(t){l.warn(c.dim(`Failed to delete remote tag "${e}": ${t}`))}for(let e of this.createdTags)try{await Bun.$`git tag -d ${e}`.quiet()}catch(t){l.warn(c.dim(`Failed to delete local tag "${e}": ${t}`))}if(this.createdTags=[],this.commitCreated){try{await Bun.$`git reset HEAD~1`.quiet()}catch(e){l.warn(c.dim(`Failed to reset commit: ${e}`))}this.commitCreated=!1}await this.changelogGenerator.rollback(),await this.packageUpdater.rollback()}async publishPackage(e){let t=this.config.get("tag")||Cr,n=Kr(e.file);await this.run(()=>Bun.$`bun run build`.cwd(n).quiet(),`Failed to build ${e.name}`);let r=await po(e.file,"utf-8");try{let{catalogs:i,workspaceVersions:s}=await this.getPublishContext();await Yr(e.file,zr(r,i,s),"utf-8"),await this.run(()=>Bun.$`npm publish --tag ${t} --access public`.cwd(n).quiet(),`Failed to publish ${e.name}`)}finally{await Yr(e.file,r,"utf-8")}}async getPublishContext(){if(!this.publishContext){let e=await Bun.file("package.json").json(),{packages:t}=await $.scan({single:this.config.get("single")});this.publishContext={catalogs:Jr(e),workspaceVersions:Vr(t.values())}}return this.publishContext}formatCommitMessage(e,t){let n=this.config.get("commit").message,r=t.map((s)=>`- ${s.name}@${s.newVersion??s.version}`).join(`
|
|
156
157
|
`);return`${n.replace("{message}",()=>e.message).replace("{packages}",()=>t.map((s)=>s.name).join(", "))}
|
|
157
158
|
|
|
158
|
-
${r}`}async hasStagedChanges(){try{return(await Bun.$`git diff --cached --name-only`.quiet()).stdout.toString().trim().length>0}catch{return!1}}async getDirtyPackageFiles(e){let t=[];for(let n of e)try{if((await Bun.$`git status --porcelain ${n.file}`.quiet()).stdout.toString().trim().length>0)t.push(n.file)}catch{}return t}async run(e,t){try{await e()}catch(n){let r=this.getStderr(n)??(n instanceof Error?n.message:void 0);throw Error(r?`${t}: ${r}`:t)}}getStderr(e){if(e&&typeof e==="object"&&"stderr"in e){let t=e.stderr;if(t instanceof Buffer)return t.toString().trim();if(typeof t==="string")return t.trim()}return}}var Ct="sisyphus/release",
|
|
159
|
+
${r}`}async hasStagedChanges(){try{return(await Bun.$`git diff --cached --name-only`.quiet()).stdout.toString().trim().length>0}catch{return!1}}async getDirtyPackageFiles(e){let t=[];for(let n of e)try{if((await Bun.$`git status --porcelain ${n.file}`.quiet()).stdout.toString().trim().length>0)t.push(n.file)}catch{}return t}async run(e,t){try{await e()}catch(n){let r=this.getStderr(n)??(n instanceof Error?n.message:void 0);throw Error(r?`${t}: ${r}`:t)}}getStderr(e){if(e&&typeof e==="object"&&"stderr"in e){let t=e.stderr;if(t instanceof Buffer)return t.toString().trim();if(typeof t==="string")return t.trim()}return}}var Ct="sisyphus/release",cn="sisyphus-release",lo="Sisyphus release PR",uo="6f42c1",Tr="chore(release):",ho=F({dryRun:{alias:"d",default:!1,description:"Preview without making changes",type:"boolean"}});class gn extends I{name="release-pr";description="Create or update a release PR from pending stones";args=ho;provider=null;async getProvider(){if(!this.provider)this.provider=await Fe();return this.provider}async execute(e){let t=await this.checkoutReleaseBranch();try{let{stones:n,packages:r}=await this.collectReleaseData(e);if(n.length===0){l.info(c.dim("No pending stones found, skipping release PR"));return}let i=this.buildPrTitle(r),s=this.buildPrBody(r,n);if(l.info(`${c.bold("Release PR:")} ${i}`),l.info(`${c.dim("Packages:")} ${r.map((o)=>o.name).join(", ")}`),e.args.dryRun){l.info(c.yellow(`
|
|
159
160
|
[dry-run] Would create/update release PR`)),l.info(c.dim(`
|
|
160
|
-
PR Body preview:`)),l.info(s);return}await this.commitAndPushChanges(e,n,r),await this.createOrUpdatePr(i,s)}finally{await this.restoreMainBranch(t)}}async checkoutReleaseBranch(){let t=await(await this.getProvider()).getDefaultBranch();return await Bun.$`git fetch origin ${t}`,await this.stashChanges(),await Bun.$`git checkout -B ${Ct} origin/${t}`,t}async collectReleaseData(e){let t=new
|
|
161
|
+
PR Body preview:`)),l.info(s);return}await this.commitAndPushChanges(e,n,r),await this.createOrUpdatePr(i,s)}finally{await this.restoreMainBranch(t)}}async checkoutReleaseBranch(){let t=await(await this.getProvider()).getDefaultBranch();return await Bun.$`git fetch origin ${t}`,await this.stashChanges(),await Bun.$`git checkout -B ${Ct} origin/${t}`,t}async collectReleaseData(e){let t=new R(e.config),n=await this.generateStonesFromCommits(e,t,e.args.dryRun),r=await t.list(),i=e.args.dryRun?[...r,...n]:r;if(i.length===0)return{packages:[],stones:[]};let{packages:s}=await $.scan({single:e.config.get("single")}),o=S.mergeAll(i),a=ee.applyStone(o,s);if(a.length===0)throw new d("No packages to update","Stones don't reference any known packages");return{packages:a,stones:i}}async commitAndPushChanges(e,t,n){let r=K();r.start("Applying release changes...");let i=await this.applyReleaseChanges(e,t,n);for(let o of i)await Bun.$`git add ${o}`.nothrow();if((await Bun.$`git diff --cached --quiet`.nothrow()).exitCode!==0)await Bun.$`git commit -m ${`${Tr} prepare release`}`;await Bun.$`git push origin ${Ct} --force`,r.stop("Release branch ready")}async createOrUpdatePr(e,t){let n=K(),r=await this.findExistingReleasePr();if(r)n.start("Updating PR..."),await this.updatePr(r.number,e,t),n.stop(`PR #${r.number} updated`),l.info(`
|
|
161
162
|
${c.green("Release PR updated:")} ${r.url}`);else{n.start("Creating PR...");let i=await this.createPr(e,t);n.stop(`PR #${i.number} created`),l.info(`
|
|
162
|
-
${c.green("Release PR created:")} ${i.url}`)}}buildPrTitle(e){let t=e.map((n)=>`${n.name}@${n.newVersion}`).join(", ");return`${
|
|
163
|
+
${c.green("Release PR created:")} ${i.url}`)}}buildPrTitle(e){let t=e.map((n)=>`${n.name}@${n.newVersion}`).join(", ");return`${Tr} ${t}`}buildPrBody(e,t){return[this.buildChangesSection(t),this.buildPackagesSection(e),this.buildStonesSection(t),this.buildFooter()].join(`
|
|
163
164
|
`)}buildChangesSection(e){let t=["## Changes",""];for(let n of e){if(t.push(`### ${n.message}`,""),n.commits&&n.commits.length>0)for(let r of n.commits)t.push(`- ${r.message} (\`${r.hash}\`)`);else if(n.description)t.push(n.description);t.push("")}return t.join(`
|
|
164
165
|
`)}buildPackagesSection(e){let t=["## Packages",""];for(let n of e)t.push(`- \`${n.name}\` ${n.version} \u2192 ${n.newVersion}`);return t.push(""),t.join(`
|
|
165
166
|
`)}buildStonesSection(e){let t=["## Stones",""];for(let n of e)t.push(`- \`${n.id}\`: ${n.message}`);return t.push(""),t.join(`
|
|
166
167
|
`)}buildFooter(){return["---","*This PR was automatically created by [Sisyphus](https://github.com/r5n-labs/clis).*","*Merging this PR will trigger the release workflow.*"].join(`
|
|
167
|
-
`)}async findExistingReleasePr(){let t=await(await this.getProvider()).findPr({head:Ct,label:
|
|
168
|
+
`)}async findExistingReleasePr(){let t=await(await this.getProvider()).findPr({head:Ct,label:cn});return t?{number:t.number,url:t.url}:null}async generateStonesFromCommits(e,t,n){let i=await new Ce(e.config).analyze({single:e.config.get("single")});if(i.length===0)return[];let{packages:s}=await $.scan({single:e.config.get("single")}),o=[];for(let[a,g]of i.entries()){let p=Ce.buildStoneData(g,s);if(n)l.info(`${c.dim("[dry-run] Would generate stone:")} ${g.message}`),o.push(S.create(p,a));else{let u=await t.create(p);o.push(u),l.info(`${c.dim("Generated stone:")} ${u.id}`)}}return o}async findNewestCommitHash(e){let t=e.flatMap((r)=>r.commits??[]).map((r)=>r.hash);if(t.length===0)return null;return(await Bun.$`git log -1 --format=%H ${t}`.quiet().nothrow()).stdout.toString().trim()||null}async stashChanges(){await Bun.$`git stash --include-untracked`.nothrow()}async applyReleaseChanges(e,t,n){let r=[];return r.push(...await this.updatePackages(n)),r.push(...await this.generateChangelogs(e,t,n)),r.push(...await this.archiveStonesAndUpdateConfig(e,t,n)),r}async updatePackages(e){return await new Je().updateAll(e),e.map((n)=>n.file)}async generateChangelogs(e,t,n){let r=e.config.get("changelog");if(!r.generate)return[];return await new we(r).generate(t,n),[r.filename,`**/${r.filename}`]}async archiveStonesAndUpdateConfig(e,t,n){let i=await new R(e.config).archive(t),s=this.buildPackageVersions(n);return e.config.set("currentRelease",{packages:s,stoneIds:t.map((o)=>o.id),timestamp:i}),await this.updateLastStone(e,t),[e.config.get("sisyphusDir")]}buildPackageVersions(e){let t={};for(let n of e)if(n.newVersion)t[n.name]={newVersion:n.newVersion,oldVersion:n.version};return t}async updateLastStone(e,t){let n=await this.findNewestCommitHash(t);if(n)e.config.set("lastStone",{commit:n,date:new Date().toISOString()})}async createPr(e,t){let n=await this.getProvider(),r=await n.getDefaultBranch();await n.ensureLabelExists(cn,{color:uo,description:lo});let i=await n.createPr({base:r,body:t,head:Ct,labels:[cn],title:e});return{number:i.number,url:i.url}}async updatePr(e,t,n){await(await this.getProvider()).updatePr(e,{body:n,title:t})}async restoreMainBranch(e){try{await Bun.$`git checkout ${e}`.quiet()}catch(t){l.warn(c.dim(`Failed to restore branch: ${t}`))}}}class pn extends I{name="actions";description="CI/CD integration";init(){this.registerSubcommands([new en,new gn])}}var fo=F({config:{alias:"c",default:!1,description:"Include config in output",type:"boolean"},json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}});class mn extends I{name="check";description="Show workspace packages and pending stones";args=fo;async execute(e){let t=await this.gatherData(e);if(e.args.json)this.printJson(t);else this.printFormatted(t)}async gatherData(e){let t=e.config.get("single"),{packages:n,packageNames:r}=await $.scan({single:t}),s=(t?null:await $.scan({single:!0}))?.packages.values().next().value??n.values().next().value,a=await new R(e.config).list();return{config:e.args.config?e.config.getAll():void 0,packageNames:r,packages:n,root:s,stones:a}}printJson(e){let t={config:e.config,packages:e.packageNames.map((n)=>({name:n,version:e.packages.get(n)?.version??"0.0.0"})),root:{name:e.root?.name??"",version:e.root?.version??"0.0.0"},stones:e.stones.map((n)=>this.stoneToJson(n,e.packages))};console.log(JSON.stringify(t,null,2))}stoneToJson(e,t){let n=[];for(let r of Pe)for(let i of e.getPackages(r)){let o=t.get(i)?.version??"0.0.0";n.push({bump:r,name:i,newVersion:X.bump(o,r,e.tag),version:o})}return{id:e.id,message:e.message,packages:n,tag:e.tag}}printFormatted(e){if(this.printRootInfo(e.root),this.printPackages(e),e.stones.length>0)this.printStones(e.stones,e.packages);if(e.config)this.printConfig(e.config);N(c.green("Sisyphus check complete."))}printConfig(e){let t=c.dim(JSON.stringify(e,null,2));l.step(`${c.bold(c.green("Config:"))}
|
|
168
169
|
${t}`)}printRootInfo(e){if(!e)return;let t=e.version?c.dim(`@${e.version}`):"";l.step(`${c.bold(c.green("Root package:"))} ${c.cyan(e.name)}${t}`)}printPackages(e){let t=[`${c.bold(c.green("Packages:"))}`];for(let n of e.packageNames){let r=e.packages.get(n),i=r?.version?c.dim(`@${r.version}`):"";t.push(` ${c.dim("\u2022")} ${c.cyan(n)}${i}`)}l.step(t.join(`
|
|
169
170
|
`))}printStones(e,t){let n=e.map((r)=>this.formatStone(r,t)).join(`
|
|
170
171
|
|
|
171
172
|
`);l.step(`${c.bold(c.green("Stones:"))}
|
|
172
173
|
|
|
173
|
-
${n}`)}formatStone(e,t){let n=[];if(n.push(`${c.bold("Stone:")} ${c.cyan(e.id)}`),e.tag)n.push(`${c.dim("Tag:")} ${e.tag}`);n.push(`${c.dim("Message:")} ${e.message}`),n.push(`${c.bold("Packages:")}`);for(let r of Pe){let i=e.getPackages(r);if(i.length===0)continue;for(let s of i){let a=t.get(s)?.version??"0.0.0",g=X.bump(a,r,e.tag),
|
|
174
|
-
`)}}var
|
|
174
|
+
${n}`)}formatStone(e,t){let n=[];if(n.push(`${c.bold("Stone:")} ${c.cyan(e.id)}`),e.tag)n.push(`${c.dim("Tag:")} ${e.tag}`);n.push(`${c.dim("Message:")} ${e.message}`),n.push(`${c.bold("Packages:")}`);for(let r of Pe){let i=e.getPackages(r);if(i.length===0)continue;for(let s of i){let a=t.get(s)?.version??"0.0.0",g=X.bump(a,r,e.tag),p=Ee[r],u=je[r];n.push(` ${u} ${c.cyan(s)}@${p(g)} ${c.dim(`(${r})`)}`)}}return n.join(`
|
|
175
|
+
`)}}var yo=F({changelog:{description:"Generate changelog for releases",type:"boolean"},commitAuthor:{description:"Commit author name",type:"string"},commitEmail:{description:"Commit author email",type:"string"},commitMessage:{description:"Commit message template",type:"string"},createRelease:{description:"Create a release on git provider",type:"boolean"},default:{alias:"d",default:!1,description:"Reset to default config",type:"boolean"},force:{alias:"f",default:!1,description:"Overwrite existing config",type:"boolean"},npm:{description:"Publish to NPM on release",type:"boolean"},push:{description:"Push commits and tags to remote on release",type:"boolean"},rootChangelog:{description:"Generate combined changelog for monorepo",type:"boolean"},single:{alias:"s",description:"Setup for single package (not monorepo)",type:"boolean"},tag:{alias:"t",description:"Default release tag",type:"string"},tags:{description:"Create git tags on release",type:"boolean"}});class ln extends I{name="init";description="Initializes Sisyphus config or edits it";args=yo;async execute(e){let{default:t,force:n}=e.args;if(t){e.config.save(De),await this.setLastStoneToHead(e),this.displaySuccessNote(e.cli.version);return}if(!e.interactive&&e.config.exists()&&!n){N(c.yellow("Config already exists. Use --force to replace."));return}let r=e.config.getAll(),{default:i,force:s,...o}=e.args,a=e.interactive?await this.runInitForm(r):o,g=this.mapValuesToConfig(a),p=be({...r},g);e.config.save(p),await this.setLastStoneToHead(e),this.displaySuccessNote(e.cli.version)}mapValuesToConfig(e){let t=(o)=>Object.fromEntries(Object.entries(o).filter(([,a])=>a!==void 0)),n=(o)=>Object.keys(o).length>0,r=t({author:e.commitAuthor,email:e.commitEmail,message:e.commitMessage}),i=t({generate:e.changelog,root:e.rootChangelog}),s=t({createRelease:e.createRelease,npm:e.npm,push:e.push,tags:e.tags});return{...t({single:e.single,tag:e.tag}),...n(r)&&{commit:r},...n(i)&&{changelog:i},...n(s)&&{release:s}}}async runInitForm(e){let t=await nt({changelog:()=>D({active:"Yes, generate changelog",inactive:"Skip changelog",initialValue:e.changelog?.generate??!0,message:"Generate changelog for release?"}),commitAuthor:({results:{configureCommit:n}})=>n?T({initialValue:e.commit?.author??"",message:"Commit author",placeholder:"r5n-bot"}):void 0,commitEmail:({results:{configureCommit:n}})=>n?T({initialValue:e.commit?.email??"",message:"Commit author email",placeholder:"r5n-bot@users.noreply.github.com"}):void 0,commitMessage:({results:{configureCommit:n}})=>n?T({initialValue:e.commit?.message??"",message:"Commit message",placeholder:"release: <packageName@version>"}):void 0,configureCommit:()=>D({active:"Yes, configure commit",inactive:"Skip commit config",initialValue:!!(e.commit?.author||e.commit?.email||e.commit?.message),message:"Configure commit for release? Default commit message is `release: <packageName@version>`"}),createRelease:()=>D({active:"Yes, create a release",inactive:"Skip release creation",initialValue:e.release?.createRelease??!1,message:"Create a release on git provider when releasing packages?"}),npm:()=>D({active:"Yes, publish packages to NPM",inactive:"Skip NPM release",initialValue:e.release?.npm??!1,message:"Publish packages to NPM when releasing packages?"}),push:()=>D({active:"Yes, push to remote",inactive:"No, keep local",initialValue:e.release?.push??!1,message:"Should `roll` command push commits and tags to remote?"}),rootChangelog:({results:{changelog:n}})=>n?D({active:"Yes, generate combined changelog",inactive:"Skip root changelog",initialValue:e.changelog?.root??!1,message:"Generate combined changelog for monorepo?"}):void 0,single:()=>D({active:"Yes, setup for root package",inactive:"No, setup for monorepo workspace packages",initialValue:e.single??!1,message:"Setup Sisyphus for only root package?"}),tag:()=>T({initialValue:e.tag??"latest",message:"Tag used when versioning packages. Leave `latest` if you are not sure.",placeholder:"latest"}),tags:()=>D({active:"Yes, create tags for the release",inactive:"Skip tags",initialValue:e.release?.tags??!1,message:"Create tags for the release?"})},{onCancel:()=>{throw new te}});return{changelog:t.changelog,commitAuthor:t.commitAuthor,commitEmail:t.commitEmail,commitMessage:t.commitMessage,createRelease:t.createRelease,npm:t.npm,push:t.push,rootChangelog:t.rootChangelog,single:t.single,tag:t.tag,tags:t.tags}}async setLastStoneToHead(e){try{let n=(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim();if(n)e.config.set("lastStone",{commit:n,date:new Date().toISOString()})}catch{}}displaySuccessNote(e){N(`${c.magenta(`${c.bold("Sisyphus ")}${c.underline(c.italic(`v${e??"unknown"}`))}`)}${c.green(" is setup to roll stones.")}
|
|
175
176
|
|
|
176
177
|
You can now start by creating a new stone by running ${c.green(A)}${c.blue(" version")}
|
|
177
178
|
and following the prompts.
|
|
178
179
|
|
|
179
180
|
After you finished, you can release it by running ${c.green(A)}${c.blue(" roll")}
|
|
180
|
-
`)}}var
|
|
181
|
+
`)}}var bo=F({dryRun:{alias:"d",default:!1,description:"Preview migration without making changes",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class un extends I{name="migrate";description="Migrate from changesets to sisyphus";args=bo;parser=new rn;async execute(e){if(!await this.parser.exists())throw new d("No .changeset directory found","This command migrates existing changesets to sisyphus stones");let{changesets:t,config:n}=await this.analyzeChangesets();if(this.displayPreview(t,n),e.args.dryRun){N("No changes made",c.yellow("Dry run"));return}if(!e.args.yes&&!await this.confirmMigration(t.length))return;let r=await this.createStones(e,t);await this.applyConfigMigration(e,n),this.displaySuccess(r)}async analyzeChangesets(){let e=K();e.start("Analyzing changesets...");let t=await this.parser.parse();if(t.errors.length>0){e.error("Found issues while parsing");for(let n of t.errors)l.warn(c.yellow(n))}if(t.changesets.length===0)throw e.stop("No changesets found"),new d("No changeset files to migrate");return e.stop(`Found ${c.bold(String(t.changesets.length))} changeset(s)`),t}displayPreview(e,t){if(this.displayChangesets(e),t)this.displayConfigMapping(t)}async confirmMigration(e){return D({initialValue:!0,message:`Migrate ${e} changeset(s) to stones?`})}async createStones(e,t){let n=K();n.start("Creating stones...");let r=new R(e.config),i=[];for(let s of t){let o=this.parser.toStoneData(s),a=await r.create(o);i.push(a.id)}return n.stop(`Created ${c.bold(String(i.length))} stone(s)`),i}async applyConfigMigration(e,t){if(!t)return;let n=K();n.start("Migrating config..."),this.migrateConfig(e,t),n.stop("Config migrated")}displaySuccess(e){let t=e.map((n)=>` ${c.dim("-")} ${n}`).join(`
|
|
181
182
|
`);N(`${t}
|
|
182
183
|
|
|
183
184
|
Run ${c.green(`${A} stone list`)} to view stones
|
|
184
185
|
Run ${c.green(`${A} preview`)} to see what will be released`,c.green("Migration complete"))}displayChangesets(e){for(let t of e){let n=Object.entries(t.packages).map(([i,s])=>{let o=s==="major"?c.red:s==="minor"?c.yellow:c.green;return`${i} ${c.dim("(")}${o(s)}${c.dim(")")}`}).join(", "),r=t.summary.length>60?`${t.summary.slice(0,60)}...`:t.summary;l.info(`${c.dim(t.filename)}
|
|
185
186
|
${c.dim("Packages:")} ${n}
|
|
186
187
|
${c.dim("Message:")} ${r||c.dim("(empty)")}`)}}displayConfigMapping(e){let t=[{category:"migrate",check:()=>(e.ignore?.length??0)>0,format:()=>`ignore: ${e.ignore?.join(", ")}`},{category:"migrate",check:()=>e.commit===!0,format:()=>"commit: enabled (will enable commit & push)"},{category:"migrate",check:()=>e.access==="public",format:()=>"access: public (will enable npm publishing)"},{category:"migrate",check:()=>e.changelog===!1,format:()=>"changelog: disabled"},{category:"info",check:()=>!!e.baseBranch&&e.baseBranch!=="master",format:()=>`baseBranch: ${e.baseBranch}`},{category:"info",check:()=>!!e.updateInternalDependencies,format:()=>`updateInternalDependencies: ${e.updateInternalDependencies}`},{category:"info",check:()=>Array.isArray(e.changelog)||typeof e.changelog==="string",format:()=>`changelog: ${Array.isArray(e.changelog)?e.changelog[0]:e.changelog}`},{category:"info",check:()=>Array.isArray(e.commit)||typeof e.commit==="string",format:()=>`commit: ${Array.isArray(e.commit)?e.commit[0]:e.commit}`},{category:"unsupported",check:()=>(e.linked?.length??0)>0,format:()=>`linked: ${e.linked?.length} group(s)`},{category:"unsupported",check:()=>(e.fixed?.length??0)>0,format:()=>`fixed: ${e.fixed?.length} group(s)`}],n={info:{color:c.blue,items:[],title:"Info (not migrated)"},migrate:{color:c.green,items:[],title:"Will migrate"},unsupported:{color:c.yellow,items:[],title:"Not yet supported"}};for(let r of t)if(r.check())n[r.category].items.push(c.dim(r.format()));for(let r of[n.migrate,n.info,n.unsupported])if(r.items.length>0)N(r.items.join(`
|
|
187
|
-
`),r.color(r.title))}migrateConfig(e,t){if(t.ignore?.length){let n=e.config.get("ignore")??[],r=[...new Set([...n,...t.ignore])];e.config.set("ignore",r)}if(t.commit===!0){let n=e.config.get("commit")??{},r=e.config.get("release")??{};e.config.set("commit",{...n,author:n.author??"Sisyphus"}),e.config.set("release",{...r,push:!0})}if(t.access==="public"){let n=e.config.get("release")??{};e.config.set("release",{...n,npm:!0})}if(t.changelog===!1){let n=e.config.get("changelog")??{};e.config.set("changelog",{...n,generate:!1})}}}var
|
|
188
|
-
or create another stone with ${c.green(`${A} version`)}`,`Stone ${c.bold(y.id)} ${c.green("created")}`)}displayPrSummary(e){if(l.info(`PR #${c.bold(String(e.number))}: ${e.title}`),l.info(`${c.dim("Author:")} ${e.author}`),l.info(`${c.dim("Branch:")} ${e.branch}`),e.labels.length>0)l.info(`${c.dim("Labels:")} ${e.labels.map((t)=>c.cyan(t)).join(", ")}`)}shouldSkipPr(e,t){let n=e.config.get("pr").skip;for(let r of t.labels)if(n.labels.some((i)=>i.toLowerCase()===r.toLowerCase()))return`label "${r}" is in skip list`;if(n.authors.some((r)=>r.toLowerCase()===t.author.toLowerCase()))return`author "${t.author}" is in skip list`;for(let r of n.titlePatterns)try{if(new RegExp(r,"i").test(t.title))return`title matches skip pattern "${r}"`}catch{l.warn(c.yellow(`Invalid regex pattern in pr.skip.titlePatterns: "${r}"`))}return null}async determineBumpType(e,t,n){if(e.args.bump){if(!
|
|
189
|
-
`))}}var
|
|
188
|
+
`),r.color(r.title))}migrateConfig(e,t){if(t.ignore?.length){let n=e.config.get("ignore")??[],r=[...new Set([...n,...t.ignore])];e.config.set("ignore",r)}if(t.commit===!0){let n=e.config.get("commit")??{},r=e.config.get("release")??{};e.config.set("commit",{...n,author:n.author??"Sisyphus"}),e.config.set("release",{...r,push:!0})}if(t.access==="public"){let n=e.config.get("release")??{};e.config.set("release",{...n,npm:!0})}if(t.changelog===!1){let n=e.config.get("changelog")??{};e.config.set("changelog",{...n,generate:!1})}}}var _r=100,Po=F({bump:{alias:"b",description:"Explicit bump type (major/minor/patch)",type:"string"},dryRun:{alias:"d",default:!1,description:"Preview without writing",type:"boolean"},message:{alias:"m",description:"Override stone message",type:"string"},packages:{alias:"p",description:"Filter packages (comma-separated)",type:"string"},url:{alias:"u",description:"PR URL",type:"string"},yes:{alias:"y",default:!1,description:"Skip confirmations",type:"boolean"}});class hn extends I{name="pr";description="Create a stone from a Pull Request";args=Po;prompts=!0;async execute(e){let n=await new an(e.config).analyze(e.args.url);this.displayPrSummary(n.pr);let r=this.shouldSkipPr(e,n.pr);if(r){l.info(c.dim(`Skipping: ${r}`));return}if(n.packages.size===0)throw new d("No packages affected by this PR","The PR only modifies root files or files outside packages");let i=await this.determineBumpType(e,n.suggestedBump,n.pr.labels),s=await this.determinePackages(e,n.packages);if(s.length===0)throw new d("No packages selected");let{packages:o}=await $.scan({single:e.config.get("single")}),a=`[#${n.pr.number}](${n.pr.url})`,g=e.args.message??`${n.pr.title} (${a})`,p=n.pr.body||void 0,u=this.buildStoneData({allPackages:o,bump:i,commits:n.commits,description:p,message:g,packages:s});if(this.logPreview(u,e.args.dryRun),e.args.dryRun)return;if(!e.args.yes&&e.interactive){if(!await D({initialValue:!0,message:"Create this stone?"}))return}let y=await new R(e.config).create(u);N(`Run ${c.green(`${A} roll`)} to release packages
|
|
189
|
+
or create another stone with ${c.green(`${A} version`)}`,`Stone ${c.bold(y.id)} ${c.green("created")}`)}displayPrSummary(e){if(l.info(`PR #${c.bold(String(e.number))}: ${e.title}`),l.info(`${c.dim("Author:")} ${e.author}`),l.info(`${c.dim("Branch:")} ${e.branch}`),e.labels.length>0)l.info(`${c.dim("Labels:")} ${e.labels.map((t)=>c.cyan(t)).join(", ")}`)}shouldSkipPr(e,t){let n=e.config.get("pr").skip;for(let r of t.labels)if(n.labels.some((i)=>i.toLowerCase()===r.toLowerCase()))return`label "${r}" is in skip list`;if(n.authors.some((r)=>r.toLowerCase()===t.author.toLowerCase()))return`author "${t.author}" is in skip list`;for(let r of n.titlePatterns)try{if(new RegExp(r,"i").test(t.title))return`title matches skip pattern "${r}"`}catch{l.warn(c.yellow(`Invalid regex pattern in pr.skip.titlePatterns: "${r}"`))}return null}async determineBumpType(e,t,n){if(e.args.bump){if(!Or(e.args.bump))throw new d(`Invalid bump type: ${e.args.bump}`,"Use major, minor, or patch");return e.args.bump}if(t)return l.info(`${c.dim("Detected bump:")} ${c.bold(t)} (from ${this.getBumpSource(t,n,e)})`),t;if(e.args.yes)throw new d("Cannot determine bump type automatically","Add a label to the PR or use --bump to specify explicitly");if(!e.interactive)throw new d("Cannot determine bump type","Use --bump to specify explicitly");return ye({message:"What type of change is this?",options:[{label:"patch - Bug fixes, minor changes",value:"patch"},{label:"minor - New features (backwards compatible)",value:"minor"},{label:"major - Breaking changes",value:"major"}]})}getBumpSource(e,t,n){let r=n.config.get("pr").labelMapping;for(let i of t){let s=i.toLowerCase();for(let[o,a]of Object.entries(r))if(s===o.toLowerCase()&&a===e)return`label: ${i}`}return"title"}async determinePackages(e,t){let n=Array.from(t);if(e.args.packages){let r=e.args.packages.split(",").map((s)=>s.trim()).filter(Boolean),i=r.filter((s)=>!t.has(s));if(i.length>0)throw new d(`Packages not affected by this PR: ${i.join(", ")}`,`Affected packages: ${n.join(", ")}`);return r}if(n.length===1||e.args.yes||!e.interactive)return l.info(`${c.dim("Affected packages:")} ${n.map((r)=>c.bold(r)).join(", ")}`),n;return ce({initialValues:n,message:"Select packages to include",options:n.map((r)=>({label:r,value:r})),required:!0})}buildStoneData(e){let{allPackages:t,bump:n,commits:r,description:i,message:s,packages:o}=e,a={commits:r,description:i,message:s};if(n==="major")a.major=o;else if(n==="minor")a.minor=o;else a.patch=o;return a.dependency=J(Le(o,t)),a}logPreview(e,t){let n=[];if(t)n.push(c.bold(c.yellow("[dry-run]")));if(n.push(`${c.dim("Stone:")} ${c.bold(e.message)}`),e.major?.length)n.push(` ${c.red("major")}: ${e.major.join(", ")}`);if(e.minor?.length)n.push(` ${c.yellow("minor")}: ${e.minor.join(", ")}`);if(e.patch?.length)n.push(` ${c.green("patch")}: ${e.patch.join(", ")}`);if(e.commits?.length)n.push(` ${c.dim(`${e.commits.length} commit(s)`)}`);if(e.description){let r=e.description.length>_r?`${e.description.slice(0,_r)}...`:e.description;n.push(` ${c.dim("Description:")} ${r}`)}l.step(n.join(`
|
|
190
|
+
`))}}var wo=F({changelog:{alias:"c",description:"Generate changelogs",type:"boolean"},createRelease:{alias:"r",description:"Create a release on git provider",type:"boolean"},dryRun:{alias:"d",default:!1,description:"Preview without making changes",type:"boolean"},noCommit:{default:!1,description:"Skip creating release commit",type:"boolean"},npm:{alias:"n",description:"Publish to NPM",type:"boolean"},preview:{default:!1,description:"Preview changelogs then prompt to delete",type:"boolean"},publishOnly:{default:!1,description:"Publish from currentRelease (no file changes)",type:"boolean"},push:{alias:"p",description:"Push commits and tags to remote",type:"boolean"},tags:{alias:"t",description:"Create git tags",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class fn extends I{name="roll";description="Execute a release from pending stones";args=wo;async execute(e){if(e.args.publishOnly){await this.executePublishOnly(e);return}let t=this.resolveOptions(e),r=await new R(e.config).list();if(r.length===0)throw new d("No pending stones found",`Create a stone with ${c.green(`${A} version`)} first`);let{packages:i}=await $.scan({single:e.config.get("single")}),s=S.mergeAll(r),o=ee.applyStone(s,i);if(o.length===0)throw new d("No packages to update","Stones don't reference any known packages");if(e.args.preview){await this.previewChangelogs(e,r,o);return}if(this.printPreview(s,o,t),!t.dryRun&&!e.args.yes&&e.interactive){if(!await D({initialValue:!0,message:"Proceed with release?"}))return}if(t.dryRun){l.info(c.yellow("Dry run complete - no changes made"));return}await this.executeRelease(e,s,o,r,t)}async previewChangelogs(e,t,n){let r=e.config.get("changelog"),i=new we(r),s=K();s.start("Generating changelog preview..."),await i.generate(t,n),s.stop("Changelog preview generated");let o=n.map((g)=>c.dim(` ${g.name}/CHANGELOG.md`)).join(`
|
|
190
191
|
`);if(l.info(`
|
|
191
192
|
Preview files created:
|
|
192
|
-
${o}`),r.root)l.info(c.dim(" CHANGELOG.md (root)"));if(l.info(""),await
|
|
193
|
+
${o}`),r.root)l.info(c.dim(" CHANGELOG.md (root)"));if(l.info(""),await D({initialValue:!0,message:"Revert changes?"}))await i.rollback(),l.info(c.dim("Changes reverted"));else l.info(c.yellow("Changes kept"))}resolveOptions(e){let t=e.config.get("release"),n=e.config.get("changelog"),r=!e.args.noCommit;return{changelog:e.args.changelog??n.generate,commit:r,createRelease:r?e.args.createRelease??t.createRelease:!1,dryRun:e.args.dryRun,npm:e.args.npm??t.npm,push:r?e.args.push??t.push:!1,tags:r?e.args.tags??t.tags:!1}}printPreview(e,t,n){let r=[];if(n.dryRun)r.push(c.bold(c.yellow("[dry-run]")));if(r.push(`${c.bold("Release:")} ${e.message}`),e.tag)r.push(`${c.dim("Tag:")} ${e.tag}`);r.push(""),r.push(c.bold("Packages:"));for(let i of t)r.push(` ${i.label}`);r.push(""),r.push(c.dim(`Changelog: ${n.changelog?"yes":"no"}`)),r.push(c.dim(`Git tags: ${n.tags?"yes":"no"}`)),r.push(c.dim(`NPM publish: ${n.npm?"yes":"no"}`)),r.push(c.dim(`Push to remote: ${n.push?"yes":"no"}`)),r.push(c.dim(`Create release: ${n.createRelease?"yes":"no"}`)),l.step(r.join(`
|
|
193
194
|
`))}async executeRelease(e,t,n,r,i){let s=new kt(e.config,i);await s.preflight(n);let o=K();try{if(o.start("Updating package versions..."),await s.updatePackageVersions(n),o.stop("Package versions updated"),i.changelog)o.start("Generating changelogs..."),await s.generateChangelogs(r,n),o.stop("Changelogs generated");if(await this.deleteStones(e,r),i.commit)o.start("Creating release commit..."),await s.createCommit(t,n),o.stop("Release commit created");if(e.config.set("lastStone",{commit:await this.getCurrentCommit(),date:new Date().toISOString()}),i.tags)o.start("Creating git tags..."),await s.createGitTags(n),o.stop("Git tags created");if(i.npm)o.start("Publishing to NPM..."),await s.publishToNpm(n),o.stop("Published to NPM");if(i.push)o.start("Pushing to remote..."),await s.pushToRemote(),o.stop("Pushed to remote");if(i.createRelease)o.start("Creating release..."),await s.createGitRelease(r,n),o.stop("Release created");N(`Released ${c.bold(String(n.length))} package(s)
|
|
194
|
-
Run ${c.green(`${A} check`)} to verify`,c.green("Release complete"))}catch(a){o.error("Release failed, rolling back...");try{await s.rollback()}finally{await this.restoreStones(e,r)}throw a}}async deleteStones(e,t){let n=new
|
|
195
|
-
Run ${c.green(`${A} check`)} to verify`,c.green("Publish complete"))}catch(o){throw s.error("Publish failed"),o}}createFallbackStone(e){let t=`Release ${e.map((n)=>`${n.name}@${n.newVersion??n.version}`).join(", ")}`;return
|
|
195
|
+
Run ${c.green(`${A} check`)} to verify`,c.green("Release complete"))}catch(a){o.error("Release failed, rolling back...");try{await s.rollback()}finally{await this.restoreStones(e,r)}throw a}}async deleteStones(e,t){let n=new R(e.config);for(let r of t)await n.delete(r.id)}async restoreStones(e,t){let n=new R(e.config);for(let r of t)await n.save(r)}async getCurrentCommit(){try{return(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim()}catch{return""}}async executePublishOnly(e){let t=e.config.get("currentRelease");if(!t)throw new d("No currentRelease found in config","Run `sis actions release-pr` first to prepare a release");let n=Object.entries(t.packages);if(n.length===0)throw new d("No packages in currentRelease","The release config appears to be empty");let{packages:r}=await $.scan({single:e.config.get("single")}),i=[];for(let[a,{oldVersion:g,newVersion:p}]of n){let u=r.get(a);if(u)i.push(u.withVersions(g,p))}if(i.length===0)throw new d("No matching packages found","Packages in currentRelease don't exist in workspace");l.info(c.bold("Publish-only mode")),l.info(c.dim(`Timestamp: ${t.timestamp}`)),l.info(c.dim(`Stones: ${t.stoneIds.join(", ")}`)),l.info(""),l.info(c.bold("Packages to publish:"));for(let a of i)l.info(` ${a.name}@${a.newVersion??a.version}`);l.info("");let s=e.config.get("release"),o={createRelease:e.args.createRelease??s.createRelease,dryRun:e.args.dryRun,npm:e.args.npm??s.npm,tags:e.args.tags??s.tags};if(o.dryRun){l.info(c.yellow("[dry-run] Would publish packages"));return}if(!e.args.yes&&e.interactive){if(!await D({initialValue:!0,message:"Proceed with publishing?"}))return}await this.executePublish(e,i,t,o)}async executePublish(e,t,n,r){let i=new kt(e.config,{changelog:!1,createRelease:r.createRelease,dryRun:r.dryRun,npm:r.npm,push:!1,tags:r.tags}),s=K();try{if(r.tags)s.start("Creating and pushing git tags..."),await i.createGitTags(t),await i.pushTags(),s.stop("Git tags pushed");if(r.npm)s.start("Publishing to NPM..."),await i.publishToNpm(t),s.stop("Published to NPM");if(r.createRelease){s.start("Creating release...");let a=await new R(e.config).getReleasedStones(n.timestamp),g=a.length>0?a:[this.createFallbackStone(t)];await i.createGitRelease(g,t),s.stop("Release created")}e.config.set("lastStone",{commit:await this.getCurrentCommit(),date:new Date().toISOString()}),N(`Published ${c.bold(String(t.length))} package(s)
|
|
196
|
+
Run ${c.green(`${A} check`)} to verify`,c.green("Publish complete"))}catch(o){throw s.error("Publish failed"),o}}createFallbackStone(e){let t=`Release ${e.map((n)=>`${n.name}@${n.newVersion??n.version}`).join(", ")}`;return S.create({message:t},0)}}class $e extends I{async resolveStone(e,t,n){if(n)return this.promptStone(t);if(!e)throw new d("Stone ID is required",`Usage: ${A} stone ${this.name} <id>`);let r=await t.get(e);if(!r)throw new d(`Stone '${e}' not found`,`Run '${A} stone list' to see available stones`);return r}async promptStone(e){let t=await e.list();if(t.length===0)throw new d("No pending stones found");let n=t.map((r)=>({label:`${r.id} - ${r.message}`,value:r}));return ye({message:`Select a stone to ${this.name}`,options:n})}}var vo=Q({id:{description:"Stone ID to delete"}});class dn extends $e{name="delete";description="Delete a pending stone";positionals=vo;prompts=!0;async execute(e){let t=new R(e.config),n=await this.resolveStone(e.positionals.id,t,e.interactive);if(e.interactive){if(!await D({initialValue:!1,message:`Delete stone '${n.id}'?`}))return}await t.delete(n.id),l.success(`Stone '${c.bold(n.id)}' deleted`)}}var ko=Q({id:{description:"Stone ID to edit"}}),Co=F({message:{alias:"m",description:"New commit message",type:"string"}});class yn extends $e{name="edit";description="Edit a pending stone";positionals=ko;args=Co;prompts=!0;async execute(e){let t=new R(e.config),n=await this.resolveStone(e.positionals.id,t,e.interactive),r=await this.resolveMessage(e,n.message),i=n.withMessage(r);await t.save(i),l.success(`Updated commit message for stone '${c.bold(n.id)}'`)}async resolveMessage(e,t){if(e.args.message)return e.args.message;if(!e.interactive)throw new d("--message is required in non-interactive mode");return T({initialValue:t,message:"Commit message",placeholder:t})}}var $o=F({json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"},verbose:{alias:"v",default:!1,description:"Show detailed info",type:"boolean"}});class bn extends I{name="list";description="List all pending stones";args=$o;async execute(e){let t=new R(e.config),n=await t.list();if(n.length===0){this.printEmpty(e.args.json);return}if(e.args.json)this.printJson(n,t);else this.printFormatted(n,e.args.verbose)}printEmpty(e){if(e)console.log(JSON.stringify([]));else l.info("No pending stones found")}printJson(e,t){let n=e.map((r)=>({path:t.getFilePath(r.id),...r.toJson()}));console.log(JSON.stringify(n,null,2))}printFormatted(e,t){let n=`Found ${c.bold(String(e.length))} pending stone${e.length>1?"s":""}`,r=e.map((i)=>this.formatStone(i,t)).join(`
|
|
196
197
|
|
|
197
198
|
`);l.info(`${n}
|
|
198
199
|
|
|
199
200
|
${r}`)}formatStone(e,t){let n=[];if(n.push(`${c.dim("-")} ${c.bold(e.id)}`),n.push(` ${c.dim("Message:")} ${e.message}`),e.tag)n.push(` ${c.dim("Tag:")} ${c.cyan(e.tag)}`);if(e.major.length)n.push(` ${c.red("Major:")} ${e.major.join(", ")}`);if(e.minor.length)n.push(` ${c.yellow("Minor:")} ${e.minor.join(", ")}`);if(e.patch.length)n.push(` ${c.green("Patch:")} ${e.patch.join(", ")}`);if(t&&e.description){n.push(` ${c.dim("Description:")}`);for(let r of e.description.split(`
|
|
200
201
|
`))n.push(` ${c.dim(r)}`)}return n.join(`
|
|
201
|
-
`)}}var
|
|
202
|
+
`)}}var Ro=Q({ids:{description:"Stone IDs to merge (at least 2)",variadic:!0}}),So=F({delete:{alias:"d",default:!1,description:"Delete original stones after merge",type:"boolean"},message:{alias:"m",description:"Commit message for merged stone",type:"string"}});class Pn extends I{name="merge";description="Merge multiple stones into one";positionals=Ro;args=So;prompts=!0;async execute(e){let t=new R(e.config),n=await this.resolveStones(e,t),r=await this.resolveMessage(e),{stone:i,conflicts:s}=S.merge(n,r);if(await t.save(i),await this.resolveDelete(e))await t.deleteMany(n.map((a)=>a.id));this.printResult(i.id,s)}async resolveStones(e,t){let n=await t.list();if(n.length<2)throw new d("Need at least 2 stones to merge");if(e.interactive)return this.promptStones(n);let r=e.positionals.ids;if(r.length<2)throw new d("Need at least 2 stone IDs",`Usage: ${A} stone merge <id1> <id2> [...] -m "message"`);let i=n.filter((s)=>r.includes(s.id));if(i.length!==r.length){let s=i.map((a)=>a.id),o=r.filter((a)=>!s.includes(a));throw new d(`Stone(s) not found: ${o.join(", ")}`)}return i}async resolveMessage(e){if(e.args.message)return e.args.message;if(!e.interactive)throw new d("--message is required in non-interactive mode");return T({message:"Commit message for merged stone",placeholder:"feat: combined changes"})}async resolveDelete(e){if(e.args.delete)return!0;if(e.interactive)return D({initialValue:!1,message:"Delete original stones?"});return!1}async promptStones(e){let t=e.map((r)=>({label:`${r.id} - ${r.message}`,value:r})),n=await ce({message:"Select stones to merge (at least 2)",options:t,required:!0});if(n.length<2)throw new d("Need to select at least 2 stones");return n}printResult(e,t){if(l.success(`Created merged stone: ${c.bold(e)}`),t.length>0)N(`Resolved ${t.length} package conflict(s) using highest bump type:
|
|
202
203
|
`+t.map((n)=>` ${c.dim("-")} ${n}`).join(`
|
|
203
|
-
`),c.yellow("Conflicts resolved"))}}var
|
|
204
|
-
`))}}class
|
|
205
|
-
Run ${c.green(`${A} preview`)} to see what will be released.`,c.green("Success"))}async selectPackagesInteractive(e,t){let n=[],r={major:[],minor:[],patch:[]};for(let i of["major","minor","patch"]){let s=t.filter((a)=>!n.includes(a));if(s.length===0)break;let o=await this.promptPackages(i,s,e);if(n.push(...o),i==="major")r.major=o;else if(i==="minor")r.minor=o;else r.patch=o}if(n.length===0)throw new d("No packages selected");return r}async promptPackages(e,t,n){let r=Ee[e],i=t.map((s)=>{let o=n.get(s);return{label:o?o.withBump(e).label:s,value:s}});return ce({message:`Select packages for ${c.bold(r(e))} bump`,options:i,required:!1})}async promptMessage(){return
|
|
204
|
+
`),c.yellow("Conflicts resolved"))}}var Mo=40,Io=Q({id:{description:"Stone ID to display"}}),Do=F({json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}});class wn extends $e{name="show";description="Show details of a specific stone";positionals=Io;args=Do;prompts=!0;async execute(e){let t=new R(e.config),n=await this.resolveStone(e.positionals.id,t,e.interactive);this.printStone(n,t,e.args.json)}printStone(e,t,n){if(n)console.log(JSON.stringify({path:t.getFilePath(e.id),...e.toJson()},null,2));else this.printFormatted(e,t)}printFormatted(e,t){let n=[];if(n.push(c.bold(`Stone: ${e.id}`)),n.push(c.dim(`Path: ${t.getFilePath(e.id)}`)),n.push(c.dim("-".repeat(Mo))),n.push(""),n.push(`${c.dim("Message:")} ${e.message}`),e.tag)n.push(`${c.dim("Tag:")} ${c.cyan(e.tag)}`);if(e.description)n.push(`${c.dim("Description:")} ${e.description}`);n.push("");let r=[{bump:"major",packages:e.major},{bump:"minor",packages:e.minor},{bump:"patch",packages:e.patch},{bump:"dependency",packages:e.dependency},{bump:"snapshot",packages:e.snapshot}];for(let{bump:i,packages:s}of r)if(s.length>0){let o=Ee[i];n.push(`${o(i)}: ${s.join(", ")}`)}l.info(n.join(`
|
|
205
|
+
`))}}class vn extends I{name="stone";description="Manage version stones";init(){this.registerSubcommands([new bn,new wn,new dn,new yn,new Pn])}}var Fo=Q({message:{description:"Stone message (commit message)"},description:{description:"Stone description (optional details)"}}),jo=F({dryRun:{alias:"d",default:!1,description:"Preview without writing files",type:"boolean"},filter:{alias:"f",description:"Filter packages by name",type:"string"},fromCommits:{default:!1,description:"Generate stones from conventional commits",type:"boolean"},major:{alias:"M",description:"Packages for major bump (comma-separated)",type:"string"},minor:{alias:"m",description:"Packages for minor bump (comma-separated)",type:"string"},patch:{alias:"p",description:"Packages for patch bump (comma-separated)",type:"string"},tag:{alias:"t",description:"Prerelease tag (e.g. beta, alpha)",type:"string"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class kn extends I{name="version";description="Create a new version stone";positionals=Fo;args=jo;prompts=!0;async execute(e){if(e.args.fromCommits)await this.executeFromCommits(e);else if(e.interactive)await this.executeInteractive(e);else await this.executeDirect(e)}async executeInteractive(e){let{packages:t,packageNames:n}=await $.scan({single:e.config.get("single")});if(n.length===0)throw new d("No packages found matching the criteria");let r=await this.selectPackagesInteractive(t,n),i=await this.promptMessage(),s=await this.promptDescription(),o=this.buildStoneData({description:s,message:i,packages:t,selection:r});await this.createStone(e,o,t)}async executeDirect(e){let t=this.parsePackageArgs(e.args);if(!e.positionals.message)throw new d("Message positional is required in non-interactive mode");let{packages:n}=await $.scan({filter:e.args.filter,single:e.config.get("single")}),r=this.validatePackages(t,n);if(r.length>0)throw new d(`Unknown packages: ${r.join(", ")}`);let i=this.buildStoneData({description:e.positionals.description,message:e.positionals.message,packages:n,selection:t,tag:e.args.tag});await this.createStone(e,i,n)}parsePackageArgs(e){let t=(i)=>i?.split(",").map((s)=>s.trim()).filter(Boolean)??[],n={major:t(e.major),minor:t(e.minor),patch:t(e.patch)};if(!(n.major.length>0||n.minor.length>0||n.patch.length>0))throw new d("At least one of --major (-M), --minor (-m), or --patch (-p) is required");return n}validatePackages(e,t){return[...e.major,...e.minor,...e.patch].filter((r)=>!t.has(r))}async executeFromCommits(e){let n=await new Ce(e.config).analyze({filter:e.args.filter,single:e.config.get("single")});if(n.length===0){l.info("No conventional commits found since last release");return}let{packages:r}=await $.scan({filter:e.args.filter,single:e.config.get("single")});l.info(`Found ${c.bold(String(n.length))} commit group(s) to process`);let i=new R(e.config),s=0;for(let o of n){let a=Ce.buildStoneData(o,r,e.args.tag);if(e.args.dryRun)this.logDryRunStone(a);else{let g=await i.create(a);s++,l.success(`Created stone: ${c.bold(g.id)}`)}}if(!e.args.dryRun&&s>0)N(`Created ${c.bold(String(s))} stone(s) from commits.
|
|
206
|
+
Run ${c.green(`${A} preview`)} to see what will be released.`,c.green("Success"))}async selectPackagesInteractive(e,t){let n=[],r={major:[],minor:[],patch:[]};for(let i of["major","minor","patch"]){let s=t.filter((a)=>!n.includes(a));if(s.length===0)break;let o=await this.promptPackages(i,s,e);if(n.push(...o),i==="major")r.major=o;else if(i==="minor")r.minor=o;else r.patch=o}if(n.length===0)throw new d("No packages selected");return r}async promptPackages(e,t,n){let r=Ee[e],i=t.map((s)=>{let o=n.get(s);return{label:o?o.withBump(e).label:s,value:s}});return ce({message:`Select packages for ${c.bold(r(e))} bump`,options:i,required:!1})}async promptMessage(){return T({message:"Stone message (used as commit message)",placeholder:"feat: add new feature",validate:(e)=>e?.trim()?void 0:"Message is required"})}async promptDescription(){return(await T({message:"Description (optional, press enter to skip)",placeholder:"Additional details about this change..."}))?.trim()||void 0}buildStoneData(e){let{selection:t,message:n,packages:r,tag:i,description:s}=e,o=[...t.major,...t.minor,...t.patch],a=Le(o,r);return{dependency:J(a),description:s,major:J(t.major),message:n,minor:J(t.minor),patch:J(t.patch),tag:i}}async createStone(e,t,n){let r=new R(e.config);if(this.logPreview(t,n,e.args.dryRun),e.args.dryRun)return;if(!e.args.yes&&e.interactive){if(!await D({initialValue:!0,message:"Create this stone?"}))return}let i=await r.create(t);N(`Run ${c.green(`${A} roll`)} to release packages
|
|
206
207
|
or create another stone with ${c.green(`${A} version`)}`,`Stone ${c.bold(i.id)} ${c.green("created")}`)}logPreview(e,t,n){let r=[];if(n)r.push(c.bold(c.yellow("[dry-run]")));if(r.push(`${c.dim("Stone:")} ${c.bold(e.message)}`),e.tag)r.push(`${c.dim("Tag:")} ${e.tag}`);let i=[{bump:"major",names:e.major},{bump:"minor",names:e.minor},{bump:"patch",names:e.patch},{bump:"dependency",names:e.dependency}];for(let{bump:s,names:o}of i){if(!o?.length)continue;for(let a of o){let g=t.get(a);if(g)r.push(` ${g.withBump(s,e.tag).label}`)}}l.step(r.join(`
|
|
207
208
|
`))}logDryRunStone(e){let t=[c.bold(c.yellow("[dry-run]")),`Stone: ${e.message}`];if(e.major?.length)t.push(` Major: ${e.major.join(", ")}`);if(e.minor?.length)t.push(` Minor: ${e.minor.join(", ")}`);if(e.patch?.length)t.push(` Patch: ${e.patch.join(", ")}`);if(e.dependency?.length)t.push(` Dependency: ${e.dependency.join(", ")}`);if(e.description)t.push(` ${c.dim("Commits:")}
|
|
208
209
|
${c.dim(e.description)}`);l.info(t.join(`
|
|
209
|
-
`))}}class
|
|
210
|
+
`))}}class Zr extends zt{constructor(){super(new Yt(`${lt}/${Sr}`,De),{bin:A,clearOnStart:!0,exitLabel:"Give Up",goodbyeMessage:"The boulder rolls back down...",name:"SISYPHUS",promptMessage:"Choose your boulder:",version:br})}init(){this.registerCommands([new pn,new mn,new ln,new un,new hn,new fn,new vn,new kn])}}var Eo=new Zr;Eo.run();
|