@r5n/sisyphus 0.13.1 → 0.13.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +115 -115
- package/package.json +2 -3
package/dist/cli.js
CHANGED
|
@@ -1,75 +1,75 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`),p=!1;for(let
|
|
5
|
-
`){if(i)s+=
|
|
6
|
-
`){if(n&&
|
|
7
|
-
`)}var re=
|
|
3
|
+
var cl=Object.create;var{getPrototypeOf:ll,defineProperty:Oi,getOwnPropertyNames:ul}=Object;var _i=Object.prototype.hasOwnProperty;function pl(e){return this[e]}var dl,ml,Li=(e,t,r)=>{var s=e!=null&&typeof e==="object";if(s){var n=t?dl??=new WeakMap:ml??=new WeakMap,i=n.get(e);if(i)return i}r=e!=null?cl(ll(e)):{};let o=t||!e||!e.__esModule||!_i.call(e,"default")?Oi(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of ul(e))if(!_i.call(o,a))Oi(o,a,{get:pl.bind(e,a),enumerable:!0})}if(s)n.set(e,o);return o};var gl=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var _s=gl(function(_g,Ki){var Os={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let r="";if(e<0)r+=`\x1B[${-e}D`;else if(e>0)r+=`\x1B[${e}C`;if(t<0)r+=`\x1B[${-t}A`;else if(t>0)r+=`\x1B[${t}B`;return r},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"},Tl={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},El={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 r=0;r<e;r++)t+=this.line+(r<e-1?Os.up():"");if(e)t+=Os.left;return t}};Ki.exports={cursor:Os,scroll:Tl,erase:El,beep:"\x07"}});class we extends Error{constructor(e="Operation cancelled"){super(e)}}class u extends Error{hint;exitCode;constructor(e,t,r=1){super(e);this.hint=t;this.exitCode=r}}import{styleText as Il}from"util";import{stdout as Ms,stdin as Xi}from"process";import*as Ne from"readline";import Al from"readline";var Mi=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let r=0;e.lastIndex=0;while(e.test(t))r+=1;return t.length-r}})(),Di=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ni=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var hl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,fl=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ji=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,yl=/\t{1,1000}/y,Fi=/[\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,wl=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,bl=/\p{M}+/gu,vl={limit:1/0,ellipsis:""},Bi=(e,t={},r={})=>{let s=t.limit??1/0,n=t.ellipsis??"",i=t?.ellipsisWidth??(n?Bi(n,vl,r).width:0),o=0,a=r.controlWidth??0,c=r.tabWidth??8,l=r.emojiWidth??2,p=2,m=r.regularWidth??1,h=r.wideWidth??2,f=[[wl,m],[hl,0],[fl,a],[yl,c],[Fi,l],[ji,h]],g=0,y=0,R=e.length,S=0,k=!1,H=R,L=Math.max(0,s-i),T=0,W=0,B=0,C=0;e:while(!0){if(W>T||y>=R&&y>g){let A=e.slice(T,W)||e.slice(g,y);S=0;for(let te of A.replaceAll(bl,"")){let ne=te.codePointAt(0)||0;if(Di(ne))C=2;else if(Ni(ne))C=h;else C=m;if(B+C>L)H=Math.min(H,Math.max(T,g)+S);if(B+C>s){k=!0;break e}S+=te.length,B+=C}T=W=0}if(y>=R)break e;for(let A=0,te=f.length;A<te;A++){let[ne,br]=f[A];if(ne.lastIndex=y,ne.test(e)){if(S=ne===ji?Mi(e.slice(y,ne.lastIndex)):ne===Fi?1:ne.lastIndex-y,C=S*br,B+C>L)H=Math.min(H,y+Math.floor((L-B)/br));if(B+C>s){k=!0;break e}B+=C,T=g,W=y,y=g=ne.lastIndex;continue e}}y+=1}return{width:k?L:B,index:k?H:R,truncated:k,ellipsed:k&&s>=i}},Vi=Bi;var $l={limit:1/0,ellipsis:"",ellipsisWidth:0},Pl=(e,t={})=>Vi(e,$l,t).width,ie=Pl;var $r="\x1B",Wi="\x9B",Rl=39,Is="\x07",Ji="[",Sl="]",zi="m",As=`${Sl}8;;`,Ui=new RegExp(`(?:\\${Ji}(?<code>\\d+)m|\\${As}(?<uri>.*)${Is})`,"y"),Gi=(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},Hi=(e)=>`${$r}${Ji}${e}${zi}`,qi=(e)=>`${$r}${As}${e}${Is}`,Es=(e,t,r)=>{let s=t[Symbol.iterator](),n=!1,i=!1,o=e.at(-1),a=o===void 0?0:ie(o),c=s.next(),l=s.next(),p=0;while(!c.done){let m=c.value,h=ie(m);if(a+h<=r)e[e.length-1]+=m;else e.push(m),a=0;if(m===$r||m===Wi)n=!0,i=t.startsWith(As,p+1);if(n){if(i){if(m===Is)n=!1,i=!1}else if(m===zi)n=!1}else if(a+=h,a===r&&!l.done)e.push(""),a=0;c=l,l=s.next(),p+=m.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},Cl=(e)=>{let t=e.split(" "),r=t.length;while(r){if(ie(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},kl=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let s="",n,i,o=e.split(" "),a=[""],c=0;for(let m=0;m<o.length;m++){let h=o[m];if(r.trim!==!1){let g=a.at(-1)??"",y=g.trimStart();if(g.length!==y.length)a[a.length-1]=y,c=ie(y)}if(m!==0){if(c>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),c=0;if(c||r.trim===!1)a[a.length-1]+=" ",c++}let f=ie(h);if(r.hard&&f>t){let g=t-c,y=1+Math.floor((f-g-1)/t);if(Math.floor((f-1)/t)<y)a.push("");Es(a,h,t),c=ie(a.at(-1)??"");continue}if(c+f>t&&c&&f){if(r.wordWrap===!1&&c<t){Es(a,h,t),c=ie(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>t&&r.wordWrap===!1){Es(a,h,t),c=ie(a.at(-1)??"");continue}a[a.length-1]+=h,c+=f}if(r.trim!==!1)a=a.map((m)=>Cl(m));let l=a.join(`
|
|
4
|
+
`),p=!1;for(let m=0;m<l.length;m++){let h=l[m];if(s+=h,!p){if(p=h>="\uD800"&&h<="\uDBFF",p)continue}else p=!1;if(h===$r||h===Wi){Ui.lastIndex=m+1;let g=Ui.exec(l)?.groups;if(g?.code!==void 0){let y=Number.parseFloat(g.code);n=y===Rl?void 0:y}else if(g?.uri!==void 0)i=g.uri.length===0?void 0:g.uri}if(l[m+1]===`
|
|
5
|
+
`){if(i)s+=qi("");let f=n?Gi(n):void 0;if(n&&f)s+=Hi(f)}else if(h===`
|
|
6
|
+
`){if(n&&Gi(n))s+=Hi(n);if(i)s+=qi(i)}}return s},xl=/\r?\n/;function Se(e,t,r){return String(e).normalize().split(xl).map((s)=>kl(s,t,r)).join(`
|
|
7
|
+
`)}var re=Li(_s(),1);import{ReadStream as Yi}from"tty";function Ye(e,t,r){if(!r.some((o)=>!o.disabled))return e;let s=e+t,n=Math.max(r.length-1,0),i=s<0?n:s>n?0:s;return r[i]?.disabled?Ye(i,t<0?-1:1,r):i}var Ol=["up","down","left","right","space","enter","cancel"],_l=["January","February","March","April","May","June","July","August","September","October","November","December"],Q={actions:new Set(Ol),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:[..._l],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 Ds(e,t){if(typeof e=="string")return Q.aliases.get(e)===t;for(let r of e)if(r!==void 0&&Ds(r,t))return!0;return!1}function Ll(e,t){if(e===t)return;let r=e.split(`
|
|
8
8
|
`),s=t.split(`
|
|
9
|
-
`),n=Math.max(r.length,s.length),i=[];for(let o=0;o<n;o++)r[o]!==s[o]&&i.push(o);return{lines:i,numLinesBefore:r.length,numLinesAfter:s.length,numLines:n}}var
|
|
9
|
+
`),n=Math.max(r.length,s.length),i=[];for(let o=0;o<n;o++)r[o]!==s[o]&&i.push(o);return{lines:i,numLinesBefore:r.length,numLinesAfter:s.length,numLines:n}}var Ml=globalThis.process.platform.startsWith("win"),Ls=Symbol("clack:cancel");function Mt(e){return e===Ls}function Pr(e,t){let r=e;r.isTTY&&r.setRawMode(t)}function Zi({input:e=Xi,output:t=Ms,overwrite:r=!0,hideCursor:s=!0}={}){let n=Ne.createInterface({input:e,output:t,prompt:"",tabSize:1});Ne.emitKeypressEvents(e,n),e instanceof Yi&&e.isTTY&&e.setRawMode(!0);let i=(o,{name:a,sequence:c})=>{let l=String(o);if(Ds([l,a,c],"cancel")){s&&t.write(re.cursor.show),process.exit(0);return}if(!r)return;Ne.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{Ne.clearLine(t,1,()=>{e.once("keypress",i)})})};return s&&t.write(re.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),s&&t.write(re.cursor.show),e instanceof Yi&&e.isTTY&&!Ml&&e.setRawMode(!1),n.terminal=!1,n.close()}}var Dt=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Ns=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function je(e,t,r,s=r,n=r,i){let o=Dt(e??Ms);return Se(t,o-r.length,{hard:!0,trim:!1}).split(`
|
|
10
10
|
`).map((a,c,l)=>{let p=i?i(a,c):a;return c===0?`${s}${p}`:c===l.length-1?`${n}${p}`:`${r}${p}`}).join(`
|
|
11
|
-
`)}function
|
|
11
|
+
`)}function Qi(e,t){if("~standard"in e){let r=e["~standard"].validate(t);if(r instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return r.issues?.at(0)?.message}return e(t)}class Nt{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:r=Xi,output:s=Ms,render:n,signal:i,...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=n.bind(this),this._track=t,this._abortSignal=i,this.input=r,this.output=s}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let r=this._subscribers.get(e)??[];r.push(t),this._subscribers.set(e,r)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let r=this._subscribers.get(e)??[],s=[];for(let n of r)n.cb(...t),n.once&&s.push(()=>r.splice(r.indexOf(n),1));for(let n of s)n()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Ls);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Al.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),Pr(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(re.cursor.show),this.output.off("resize",this.render),Pr(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(re.cursor.show),this.output.off("resize",this.render),Pr(this.input,!1),e(Ls)})})}_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&&Q.aliases.has(t.name)&&this.emit("cursor",Q.aliases.get(t.name)),Q.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 r=Qi(this.opts.validate,this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Ds([e,t?.name,t?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
12
12
|
`),Pr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Se(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
13
|
-
`).length-1;this.output.write(re.cursor.move(-999,e*-1))}render(){let e=Se(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(re.cursor.hide);else{let t=
|
|
13
|
+
`).length-1;this.output.write(re.cursor.move(-999,e*-1))}render(){let e=Se(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(re.cursor.hide);else{let t=Ll(this._prevFrame,e),r=Ns(this.output);if(this.restoreCursor(),t){let s=Math.max(0,t.numLinesAfter-r),n=Math.max(0,t.numLinesBefore-r),i=t.lines.find((o)=>o>=s);if(i===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(re.cursor.move(0,i-n)),this.output.write(re.erase.lines(1));let o=e.split(`
|
|
14
14
|
`);this.output.write(o[i]),this._prevFrame=e,this.output.write(re.cursor.move(0,o.length-i-1));return}else if(t.lines.length>1){if(s<n)i=s;else{let a=i-n;a>0&&this.output.write(re.cursor.move(0,a))}this.output.write(re.erase.down());let o=e.split(`
|
|
15
15
|
`).slice(i);this.output.write(o.join(`
|
|
16
|
-
`)),this._prevFrame=e;return}}this.output.write(re.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}class js extends Nt{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(re.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class Fs extends Nt{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((r)=>r.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((r)=>!e.includes(r.value));this.value=t.map((r)=>r.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:r})=>r===e.cursorAt),0);this.cursor=this.options[t]?.disabled?Ye(t,1,this.options):t,this.on("key",(r,s)=>{s.name==="a"&&this.toggleAll(),s.name==="i"&&this.toggleInvert()}),this.on("cursor",(r)=>{switch(r){case"left":case"up":this.cursor=Ye(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ye(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var
|
|
17
|
-
`);R.push(C),S+=C.length}if(S>p){let T=0,W=0,B=S,C=e-k,A=p,te=()=>
|
|
16
|
+
`)),this._prevFrame=e;return}}this.output.write(re.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}class js extends Nt{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(re.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class Fs extends Nt{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((r)=>r.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((r)=>!e.includes(r.value));this.value=t.map((r)=>r.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:r})=>r===e.cursorAt),0);this.cursor=this.options[t]?.disabled?Ye(t,1,this.options):t,this.on("key",(r,s)=>{s.name==="a"&&this.toggleAll(),s.name==="i"&&this.toggleInvert()}),this.on("cursor",(r)=>{switch(r){case"left":case"up":this.cursor=Ye(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ye(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var eo=class extends Nt{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 r=this.options.findIndex(({value:n})=>n===t.initialValue),s=r===-1?0:r;this.cursor=this.options[s]?.disabled?Ye(s,1,this.options):s,this.changeValue(),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=Ye(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ye(this.cursor,1,this.options);break}this.changeValue()})}};class Bs extends Nt{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),r=e.slice(this.cursor,this.cursor+1),s=e.slice(this.cursor+1);return`${t}${Il("inverse",r)}${s}`}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 w,stripVTControlCharacters as Kg}from"util";import pe from"process";var Ft=Li(_s(),1);function Dl(){if(pe.platform!=="win32")return pe.env.TERM!=="linux";return Boolean(pe.env.CI)||Boolean(pe.env.WT_SESSION)||Boolean(pe.env.TERMINUS_SUBLIME)||pe.env.ConEmuTask==="{cmd::Cmder}"||pe.env.TERM_PROGRAM==="Terminus-Sublime"||pe.env.TERM_PROGRAM==="vscode"||pe.env.TERM==="xterm-256color"||pe.env.TERM==="alacritty"||pe.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Vs=Dl(),Nl=()=>process.env.CI==="true";var N=(e,t)=>Vs?e:t,jl=N("\u25C6","*"),io=N("\u25A0","x"),oo=N("\u25B2","x"),Cr=N("\u25C7","o"),Fl=N("\u250C","T"),E=N("\u2502","|"),Fe=N("\u2514","\u2014"),Qg=N("\u2510","T"),eh=N("\u2518","\u2014"),Us=N("\u25CF",">"),Sr=N("\u25CB"," "),Bl=N("\u25FB","[\u2022]"),to=N("\u25FC","[+]"),ro=N("\u25FB","[ ]"),th=N("\u25AA","\u2022"),so=N("\u2500","-"),Vl=N("\u256E","+"),Ul=N("\u251C","+"),Gl=N("\u256F","+"),Hl=N("\u2570","+"),rh=N("\u256D","+"),ql=N("\u25CF","\u2022"),Wl=N("\u25C6","*"),Jl=N("\u25B2","!"),zl=N("\u25A0","x"),kr=(e)=>{switch(e){case"initial":case"active":return w("cyan",jl);case"cancel":return w("red",io);case"error":return w("yellow",oo);case"submit":return w("green",Cr)}},ao=(e)=>{switch(e){case"initial":case"active":return w("cyan",E);case"cancel":return w("red",E);case"error":return w("yellow",E);case"submit":return w("green",E)}};function co(e,t){let r=[`${t?`${w("cyan",E)} `:""}${e.join(" \u2022 ")}`];return t&&r.push(w("cyan",Fe)),r}var no=(e,t,r,s,n,i=!1)=>{let o=t,a=0;if(i)for(let c=s-1;c>=r;c--){let l=e[c];if(l&&(o-=l.length),a++,o<=n)break}else for(let c=r;c<s;c++){let l=e[c];if(l&&(o-=l.length),a++,o<=n)break}return{lineCount:o,removals:a}},Gs=({cursor:e,options:t,style:r,output:s=process.stdout,maxItems:n=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=Dt(s)-i,c=Ns(s),l=w("dim","..."),p=Math.max(c-o,0),m=Math.max(Math.min(n,p),5),h=0;e>=m-3&&(h=Math.max(Math.min(e-m+3,t.length-m),0));let f=m<t.length&&h>0,g=m<t.length&&h+m<t.length,y=Math.min(h+m,t.length),R=[],S=0;f&&S++,g&&S++;let k=h+(f?1:0),H=y-(g?1:0);for(let T=k;T<H;T++){let W=t[T],B=W?r(W,T===e):"",C=Se(B,a,{hard:!0,trim:!1}).split(`
|
|
17
|
+
`);R.push(C),S+=C.length}if(S>p){let T=0,W=0,B=S,C=e-k,A=p,te=()=>no(R,B,0,C,A),ne=()=>no(R,B,C+1,R.length,A,!0);f?({lineCount:B,removals:T}=te(),B>A&&(g||(A-=1),{lineCount:B,removals:W}=ne())):(g||(A-=1),{lineCount:B,removals:W}=ne(),B>A&&(A-=1,{lineCount:B,removals:T}=te())),T>0&&(f=!0,R.splice(0,T)),W>0&&(g=!0,R.splice(R.length-W,W))}let L=[];f&&L.push(l);for(let T of R)for(let W of T)L.push(W);return g&&L.push(l),L};var lo=(e)=>{let t=e.active??"Yes",r=e.inactive??"No";return new js({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let s=e.withGuide??Q.withGuide,n=`${kr(this.state)} `,i=s?`${w("gray",E)} `:"",o=je(e.output,e.message,i,n),a=`${s?`${w("gray",E)}
|
|
18
18
|
`:""}${o}
|
|
19
19
|
`,c=this.value?t:r;switch(this.state){case"submit":{let l=s?`${w("gray",E)} `:"";return`${a}${l}${w("dim",c)}`}case"cancel":{let l=s?`${w("gray",E)} `:"";return`${a}${l}${w(["strikethrough","dim"],c)}${s?`
|
|
20
20
|
${w("gray",E)}`:""}`}default:{let l=s?`${w("cyan",E)} `:"",p=s?w("cyan",Fe):"";return`${a}${l}${this.value?`${w("green",Us)} ${t}`:`${w("dim",Sr)} ${w("dim",t)}`}${e.vertical?s?`
|
|
21
21
|
${w("cyan",E)} `:`
|
|
22
22
|
`:` ${w("dim","/")} `}${this.value?`${w("dim",Sr)} ${w("dim",r)}`:`${w("green",Us)} ${r}`}
|
|
23
23
|
${p}
|
|
24
|
-
`}}}}).prompt()};var xr=async(e,t)=>{let r={},s=Object.keys(e);for(let n of s){let i=e[n],o=await i({results:r})?.catch((a)=>{throw a});if(typeof t?.onCancel=="function"&&Mt(o)){r[n]="canceled",t.onCancel({results:r});continue}r[n]=o}return r},
|
|
24
|
+
`}}}}).prompt()};var xr=async(e,t)=>{let r={},s=Object.keys(e);for(let n of s){let i=e[n],o=await i({results:r})?.catch((a)=>{throw a});if(typeof t?.onCancel=="function"&&Mt(o)){r[n]="canceled",t.onCancel({results:r});continue}r[n]=o}return r},Kl=[`${w("dim","\u2191/\u2193")} to navigate`,`${w("dim","Space:")} select`,`${w("dim","Enter:")} confirm`],jt=(e,t)=>e.split(`
|
|
25
25
|
`).map((r)=>t(r)).join(`
|
|
26
|
-
`),
|
|
27
|
-
${w("reset",w("dim",`Press ${w(["gray","bgWhite","inverse"]," space ")} to select, ${w("gray",w("bgWhite",w("inverse"," enter ")))} to submit`))}`},render(){let n=e.withGuide??Q.withGuide,i=je(e.output,e.message,n?`${
|
|
26
|
+
`),uo=(e)=>{let t=(n,i)=>{let o=n.label??String(n.value);return i==="disabled"?`${w("gray",ro)} ${jt(o,(a)=>w(["strikethrough","gray"],a))}${n.hint?` ${w("dim",`(${n.hint??"disabled"})`)}`:""}`:i==="active"?`${w("cyan",Bl)} ${o}${n.hint?` ${w("dim",`(${n.hint})`)}`:""}`:i==="selected"?`${w("green",to)} ${jt(o,(a)=>w("dim",a))}${n.hint?` ${w("dim",`(${n.hint})`)}`:""}`:i==="cancelled"?`${jt(o,(a)=>w(["strikethrough","dim"],a))}`:i==="active-selected"?`${w("green",to)} ${o}${n.hint?` ${w("dim",`(${n.hint})`)}`:""}`:i==="submitted"?`${jt(o,(a)=>w("dim",a))}`:`${w("dim",ro)} ${jt(o,(a)=>w("dim",a))}`},r=e.required??!0,s=e.showInstructions??!0;return new Fs({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:r,cursorAt:e.cursorAt,validate(n){if(r&&(n===void 0||n.length===0))return`Please select at least one option.
|
|
27
|
+
${w("reset",w("dim",`Press ${w(["gray","bgWhite","inverse"]," space ")} to select, ${w("gray",w("bgWhite",w("inverse"," enter ")))} to submit`))}`},render(){let n=e.withGuide??Q.withGuide,i=je(e.output,e.message,n?`${ao(this.state)} `:"",`${kr(this.state)} `),o=`${n?`${w("gray",E)}
|
|
28
28
|
`:""}${i}
|
|
29
|
-
`,a=this.value??[],c=(l,p)=>{if(l.disabled)return t(l,"disabled");let
|
|
29
|
+
`,a=this.value??[],c=(l,p)=>{if(l.disabled)return t(l,"disabled");let m=a.includes(l.value);return p&&m?t(l,"active-selected"):m?t(l,"selected"):t(l,p?"active":"inactive")};switch(this.state){case"submit":{let l=this.options.filter(({value:m})=>a.includes(m)).map((m)=>t(m,"submitted")).join(w("dim",", "))||w("dim","none"),p=je(e.output,l,n?`${w("gray",E)} `:"");return`${o}${p}`}case"cancel":{let l=this.options.filter(({value:m})=>a.includes(m)).map((m)=>t(m,"cancelled")).join(w("dim",", "));if(l.trim()==="")return`${o}${w("gray",E)}`;let p=je(e.output,l,n?`${w("gray",E)} `:"");return`${o}${p}${n?`
|
|
30
30
|
${w("gray",E)}`:""}`}case"error":{let l=n?`${w("yellow",E)} `:"",p=this.error.split(`
|
|
31
31
|
`).map((f,g)=>g===0?`${n?`${w("yellow",Fe)} `:""}${w("yellow",f)}`:` ${f}`).join(`
|
|
32
|
-
`),
|
|
32
|
+
`),m=o.split(`
|
|
33
33
|
`).length,h=p.split(`
|
|
34
|
-
`).length+1;return`${o}${l}${Gs({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:
|
|
34
|
+
`).length+1;return`${o}${l}${Gs({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:m+h,style:c}).join(`
|
|
35
35
|
${l}`)}
|
|
36
36
|
${p}
|
|
37
37
|
`}default:{let l=n?`${w("cyan",E)} `:"",p=o.split(`
|
|
38
|
-
`).length,
|
|
39
|
-
`),f=
|
|
38
|
+
`).length,m=s?co(Kl,n):n?[w("cyan",Fe)]:[],h=m.join(`
|
|
39
|
+
`),f=m.length+1;return`${o}${l}${Gs({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:p+f,style:c}).join(`
|
|
40
40
|
${l}`)}
|
|
41
41
|
${h}
|
|
42
|
-
`}}}}).prompt()};var v={message:(e=[],{symbol:t=w("gray",E),secondarySymbol:r=w("gray",E),output:s=process.stdout,spacing:n=1,withGuide:i}={})=>{let o=[],a=i??Q.withGuide,c=a?r:"",l=a?`${t} `:"",p=a?`${r} `:"";for(let h=0;h<n;h++)o.push(c);let
|
|
43
|
-
`);if(
|
|
42
|
+
`}}}}).prompt()};var v={message:(e=[],{symbol:t=w("gray",E),secondarySymbol:r=w("gray",E),output:s=process.stdout,spacing:n=1,withGuide:i}={})=>{let o=[],a=i??Q.withGuide,c=a?r:"",l=a?`${t} `:"",p=a?`${r} `:"";for(let h=0;h<n;h++)o.push(c);let m=Array.isArray(e)?e:e.split(`
|
|
43
|
+
`);if(m.length>0){let[h,...f]=m;h.length>0?o.push(`${l}${h}`):o.push(a?t:"");for(let g of f)g.length>0?o.push(`${p}${g}`):o.push(a?r:"")}s.write(`${o.join(`
|
|
44
44
|
`)}
|
|
45
|
-
`)},info:(e,t)=>{v.message(e,{...t,symbol:w("blue",
|
|
45
|
+
`)},info:(e,t)=>{v.message(e,{...t,symbol:w("blue",ql)})},success:(e,t)=>{v.message(e,{...t,symbol:w("green",Wl)})},step:(e,t)=>{v.message(e,{...t,symbol:w("green",Cr)})},warn:(e,t)=>{v.message(e,{...t,symbol:w("yellow",Jl)})},warning:(e,t)=>{v.warn(e,t)},error:(e,t)=>{v.message(e,{...t,symbol:w("red",zl)})}};var Tr=(e="",t)=>{let r=t?.output??process.stdout,s=t?.withGuide??Q.withGuide?`${w("gray",Fl)} `:"";r.write(`${s}${e}
|
|
46
46
|
`)},Er=(e="",t)=>{let r=t?.output??process.stdout,s=t?.withGuide??Q.withGuide?`${w("gray",E)}
|
|
47
47
|
${w("gray",Fe)} `:"";r.write(`${s}${e}
|
|
48
48
|
|
|
49
|
-
`)};var
|
|
50
|
-
`),i=n.reduce((c,l)=>Math.max(ie(l),c),0),o=n.map(r).reduce((c,l)=>Math.max(ie(l),c),0),a=t-(o-i);return Se(e,a,s)},q=(e="",t="",r)=>{let s=r?.output??pe.stdout,n=r?.withGuide??Q.withGuide,i=r?.format??
|
|
49
|
+
`)};var Yl=(e)=>e,Xl=(e,t,r)=>{let s={hard:!0,trim:!1},n=Se(e,t,s).split(`
|
|
50
|
+
`),i=n.reduce((c,l)=>Math.max(ie(l),c),0),o=n.map(r).reduce((c,l)=>Math.max(ie(l),c),0),a=t-(o-i);return Se(e,a,s)},q=(e="",t="",r)=>{let s=r?.output??pe.stdout,n=r?.withGuide??Q.withGuide,i=r?.format??Yl,o=["",...Xl(e,Dt(s)-6,i).split(`
|
|
51
51
|
`).map(i),""],a=ie(t),c=Math.max(o.reduce((h,f)=>{let g=ie(f);return g>h?g:h},0),a)+2,l=o.map((h)=>`${w("gray",E)} ${h}${" ".repeat(c-ie(h))}${w("gray",E)}`).join(`
|
|
52
52
|
`),p=n?`${w("gray",E)}
|
|
53
|
-
`:"",
|
|
53
|
+
`:"",m=n?Ul:Hl;s.write(`${p}${w("green",Cr)} ${w("reset",t)} ${w("gray",so.repeat(Math.max(c-a-1,1))+Vl)}
|
|
54
54
|
${l}
|
|
55
|
-
${w("gray",
|
|
56
|
-
`)};var
|
|
55
|
+
${w("gray",m+so.repeat(c+2)+Gl)}
|
|
56
|
+
`)};var Zl=(e)=>w("magenta",e),be=({indicator:e="dots",onCancel:t,output:r=process.stdout,cancelMessage:s,errorMessage:n,frames:i=Vs?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Vs?80:120,signal:a,...c}={})=>{let l=Nl(),p,m,h=!1,f=!1,g="",y,R=performance.now(),S=Dt(r),k=c?.styleFrame??Zl,H=(J)=>{let ue=J>1?n??Q.messages.error:s??Q.messages.cancel;f=J===1,h&&(Lt(ue,J),f&&typeof t=="function"&&t())},L=()=>H(2),T=()=>H(1),W=()=>{process.on("uncaughtExceptionMonitor",L),process.on("unhandledRejection",L),process.on("SIGINT",T),process.on("SIGTERM",T),process.on("exit",H),a&&a.addEventListener("abort",T)},B=()=>{process.removeListener("uncaughtExceptionMonitor",L),process.removeListener("unhandledRejection",L),process.removeListener("SIGINT",T),process.removeListener("SIGTERM",T),process.removeListener("exit",H),a&&a.removeEventListener("abort",T)},C=()=>{if(y===void 0)return;l&&r.write(`
|
|
57
57
|
`);let J=Se(y,S,{hard:!0,trim:!1}).split(`
|
|
58
|
-
`);J.length>1&&r.write(Ft.cursor.up(J.length-1)),r.write(Ft.cursor.to(0)),r.write(Ft.erase.down())},A=(J)=>J.replace(/\.+$/,""),te=(J)=>{let ue=(performance.now()-J)/1000,Ce=Math.floor(ue/60),ke=Math.floor(ue%60);return Ce>0?`[${Ce}m ${ke}s]`:`[${ke}s]`},ne=c.withGuide??Q.withGuide,br=(J="")=>{h=!0,p=
|
|
59
|
-
`);let ue=0,Ce=0;W(),
|
|
58
|
+
`);J.length>1&&r.write(Ft.cursor.up(J.length-1)),r.write(Ft.cursor.to(0)),r.write(Ft.erase.down())},A=(J)=>J.replace(/\.+$/,""),te=(J)=>{let ue=(performance.now()-J)/1000,Ce=Math.floor(ue/60),ke=Math.floor(ue%60);return Ce>0?`[${Ce}m ${ke}s]`:`[${ke}s]`},ne=c.withGuide??Q.withGuide,br=(J="")=>{h=!0,p=Zi({output:r}),g=A(J),R=performance.now(),ne&&r.write(`${w("gray",E)}
|
|
59
|
+
`);let ue=0,Ce=0;W(),m=setInterval(()=>{if(l&&g===y)return;C(),y=g;let ke=k(i[ue]),vr;if(l)vr=`${ke} ${g}...`;else if(e==="timer")vr=`${ke} ${g} ${te(R)}`;else{let al=".".repeat(Math.floor(Ce)).slice(0,3);vr=`${ke} ${g}${al}`}let ol=Se(vr,S,{hard:!0,trim:!1});r.write(ol),ue=ue+1<i.length?ue+1:0,Ce=Ce<4?Ce+0.125:0},o)},Lt=(J="",ue=0,Ce=!1)=>{if(!h)return;h=!1,clearInterval(m),C();let ke=ue===0?w("green",Cr):ue===1?w("red",io):w("red",oo);g=J??g,Ce||(e==="timer"?r.write(`${ke} ${g} ${te(R)}
|
|
60
60
|
`):r.write(`${ke} ${g}
|
|
61
|
-
`)),B(),p()};return{start:br,stop:(J="")=>Lt(J,0),message:(J="")=>{g=A(J??g)},cancel:(J="")=>Lt(J,1),error:(J="")=>Lt(J,2),clear:()=>Lt("",0,!0),get isCancelled(){return f}}},
|
|
61
|
+
`)),B(),p()};return{start:br,stop:(J="")=>Lt(J,0),message:(J="")=>{g=A(J??g)},cancel:(J="")=>Lt(J,1),error:(J="")=>Lt(J,2),clear:()=>Lt("",0,!0),get isCancelled(){return f}}},sh={light:N("\u2500","-"),heavy:N("\u2501","="),block:N("\u2588","#")};var Ql=[`${w("dim","\u2191/\u2193")} to navigate`,`${w("dim","Enter:")} confirm`],Rr=(e,t)=>e.includes(`
|
|
62
62
|
`)?e.split(`
|
|
63
63
|
`).map((r)=>t(r)).join(`
|
|
64
|
-
`):t(e),
|
|
64
|
+
`):t(e),po=(e)=>{let t=(s,n)=>{if(s===void 0)return"";let i=s.label??String(s.value);switch(n){case"disabled":return`${w("gray",Sr)} ${Rr(i,(o)=>w("gray",o))}${s.hint?` ${w("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${Rr(i,(o)=>w("dim",o))}`;case"active":return`${w("green",Us)} ${i}${s.hint?` ${w("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${Rr(i,(o)=>w(["strikethrough","dim"],o))}`;default:return`${w("dim",Sr)} ${Rr(i,(o)=>w("dim",o))}`}},r=e.showInstructions??!0;return new eo({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??Q.withGuide,n=`${kr(this.state)} `,i=`${ao(this.state)} `,o=je(e.output,e.message,i,n),a=`${s?`${w("gray",E)}
|
|
65
65
|
`:""}${o}
|
|
66
66
|
`;switch(this.state){case"submit":{let c=s?`${w("gray",E)} `:"",l=je(e.output,t(this.options[this.cursor],"selected"),c);return`${a}${l}`}case"cancel":{let c=s?`${w("gray",E)} `:"",l=je(e.output,t(this.options[this.cursor],"cancelled"),c);return`${a}${l}${s?`
|
|
67
67
|
${w("gray",E)}`:""}`}default:{let c=s?`${w("cyan",E)} `:"",l=a.split(`
|
|
68
|
-
`).length,p=r?
|
|
68
|
+
`).length,p=r?co(Ql,s):s?[w("cyan",Fe)]:[],m=p.join(`
|
|
69
69
|
`),h=p.length+1;return`${a}${c}${Gs({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+h,style:(f,g)=>t(f,f.disabled?"disabled":g?"active":"inactive")}).join(`
|
|
70
70
|
${c}`)}
|
|
71
|
-
${
|
|
72
|
-
`}}}}).prompt()};var
|
|
71
|
+
${m}
|
|
72
|
+
`}}}}).prompt()};var nh=`${w("gray",E)} `;var mo=(e)=>new Bs({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??Q.withGuide,r=`${`${t?`${w("gray",E)}
|
|
73
73
|
`:""}${kr(this.state)} `}${e.message}
|
|
74
74
|
`,s=e.placeholder&&e.placeholder.length>0?w("inverse",e.placeholder[0])+w("dim",e.placeholder.slice(1)):w(["inverse","hidden"],"_"),n=this.userInput?this.userInputWithCursor:s,i=this.value??"";switch(this.state){case"error":{let o=this.error?` ${w("yellow",this.error)}`:"",a=t?`${w("yellow",E)} `:"",c=t?w("yellow",Fe):"";return`${r.trim()}
|
|
75
75
|
${a}${n}
|
|
@@ -77,53 +77,53 @@ ${c}${o}
|
|
|
77
77
|
`}case"submit":{let o=i?` ${w("dim",i)}`:"",a=t?w("gray",E):"";return`${r}${a}${o}`}case"cancel":{let o=i?` ${w(["strikethrough","dim"],i)}`:"",a=t?w("gray",E):"";return`${r}${a}${o}${i.trim()?`
|
|
78
78
|
${a}`:""}`}default:{let o=t?`${w("cyan",E)} `:"",a=t?w("cyan",Fe):"";return`${r}${o}${n}
|
|
79
79
|
${a}
|
|
80
|
-
`}}}}).prompt();var
|
|
80
|
+
`}}}}).prompt();var tu=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),fo=["black","blue","cyan","gray","green","magenta","red","white","yellow"],ru=["bold","dim","italic","underline","reset"],yo={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},su={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"},nu={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"},go={"\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 Ir(e){return(t)=>tu?`${e}${t}${yo.reset}`:t}function iu(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32&&r!==27)return!1}return!0}function ho({bright:e=!1,color:t}){let r=Bun.color(t,"ansi"),s=typeof r==="string"&&r.length>0&&iu(r)?r:su[t];if(!s)return"";return e&&s in go?go[s]:s}var ou=fo.reduce((e,t)=>{let r=ho({color:t});if(r)e[t]=Ir(r);let s=ho({bright:!0,color:t});if(s)e[`${t}Bright`]=Ir(s);return e},{}),au=ru.reduce((e,t)=>(e[t]=Ir(yo[t]),e),{}),cu=fo.reduce((e,t)=>{let r=nu[t];if(r){let s=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[s]=Ir(r)}return e},{}),d={...ou,...au,...cu};function Ar(e){if(Mt(e))throw new we;return e}function uu(e){return e.map((t)=>t.key?`${d.bold(t.key)} ${d.dim(t.text)}`:d.dim(t.text)).join(d.dim(" \xB7 "))}function Or(e){v.info(uu(e))}var _r={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 V(e){return Or(_r.confirm),Ar(await lo(e))}async function le(e){return Or(_r.text),Ar(await mo(e))}async function Xe(e){return Or(_r.select),Ar(await po({showInstructions:!1,...e}))}async function xe(e){return Or(_r.multiselect),Ar(await uo({showInstructions:!1,...e}))}var pu=4;function pt(e,t=0){if(t>=pu)return;let r=[...e instanceof AggregateError?e.errors:[],...e.cause!==void 0?[e.cause]:[]];for(let s of r){if(v.info(d.dim(`caused by: ${s instanceof Error?s.message:String(s)}`)),s instanceof u&&s.hint)v.info(d.dim(` ${s.hint}`));if(s instanceof Error)pt(s,t+1)}}function Hs(e){return e==null?[]:Array.isArray(e)?e:[e]}function du(e,t,r,s){var n,i=e[t],o=~s.string.indexOf(t)?r==null||r===!0?"":String(r):typeof r==="boolean"?r:~s.boolean.indexOf(t)?r==="false"?!1:r==="true"||(e._.push((n=+r,n*0===0)?n:r),!!r):(n=+r,n*0===0)?n:r;e[t]=i==null?o:Array.isArray(i)?i.concat(o):[i,o]}function Bt(e,t){e=e||[],t=t||{};var r,s,n,i,o,a={_:[]},c=0,l=0,p=0,m=e.length;let h=t.alias!==void 0,f=t.unknown!==void 0,g=t.default!==void 0;if(t.alias=t.alias||{},t.string=Hs(t.string),t.boolean=Hs(t.boolean),h)for(r in t.alias){s=t.alias[r]=Hs(t.alias[r]);for(c=0;c<s.length;c++)(t.alias[s[c]]=s.concat(r)).splice(c,1)}for(c=t.boolean.length;c-- >0;){s=t.alias[t.boolean[c]]||[];for(l=s.length;l-- >0;)t.boolean.push(s[l])}for(c=t.string.length;c-- >0;){s=t.alias[t.string[c]]||[];for(l=s.length;l-- >0;)t.string.push(s[l])}if(g){for(r in t.default)if(i=typeof t.default[r],s=t.alias[r]=t.alias[r]||[],t[i]!==void 0){t[i].push(r);for(c=0;c<s.length;c++)t[i].push(s[c])}}let y=f?Object.keys(t.alias):[];for(c=0;c<m;c++){if(n=e[c],n==="--"){a._=a._.concat(e.slice(++c));break}for(l=0;l<n.length;l++)if(n.charCodeAt(l)!==45)break;if(l===0)a._.push(n);else if(n.substring(l,l+3)==="no-"){if(i=n.substring(l+3),f&&!~y.indexOf(i))return t.unknown(n);a[i]=!1}else{for(p=l+1;p<n.length;p++)if(n.charCodeAt(p)===61)break;i=n.substring(l,p),o=n.substring(++p)||(c+1===m||(""+e[c+1]).charCodeAt(0)===45||e[++c]),s=l===2?[i]:i;for(p=0;p<s.length;p++){if(i=s[p],f&&!~y.indexOf(i))return t.unknown("-".repeat(l)+i);du(a,i,p+1<s.length||o,t)}}}if(g){for(r in t.default)if(a[r]===void 0)a[r]=t.default[r]}if(h)for(r in a){s=t.alias[r]||[];while(s.length>0)a[s.shift()]=a[r]}return a}var wo=1,mu=2;function dt(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function qs(e){let t={alias:{},boolean:[],default:{},string:[]};for(let[r,s]of Object.entries(e)){if(s.type==="boolean")t.boolean.push(r);else t.string.push(r);if(s.alias)t.alias[s.alias]=r;let n=dt(r);if(n!==r)t.alias[n]=r;if(s.default!==void 0)t.default[r]=s.default}return t}function Lr(e,t){if(e in t)return`--${dt(e)}`;let r=Object.entries(t).find(([,s])=>s.alias===e)?.[0];if(r)return`--${dt(r)}`;return e.length===wo?`-${e}`:`--${dt(e)}`}function Be(e,t,r){let{alias:s}=qs(t),n=Object.keys(e).find((i)=>!Object.hasOwn(t,i)&&!Object.hasOwn(s,i));if(n!==void 0)throw new u(`Unknown option: ${Lr(n,t)}`,r)}function bo(e,t){for(let[s,n]of Object.entries(e))if(Array.isArray(n))throw new u(`${Lr(s,t)} can only be provided once`);let r={...e};for(let[s,n]of Object.entries(t)){if(n.type!=="number")continue;let i=e[s];if(i===void 0)continue;let o=Number(i);if(typeof i==="boolean"||typeof i==="string"&&i.trim().length===0||!Number.isFinite(o)){let a=Lr(s,t);throw new u(`Invalid number for ${a}: "${i}"`,`Use ${a}=<number> with a finite numeric value`)}r[s]=o}return r}function Ws(e,t){let r=qs(t);vo(e,r,t,!0);let s=Bt(e,r),n=s._[0],i=n?e.indexOf(n):-1,o=Bt(i>=0?e.slice(0,i):e,r),{_:a,...c}=o;Be(c,t,"Place command options after the command name");let{_:l,...p}=s,m=Object.fromEntries(Object.entries(p).filter(([f])=>(f in t)||(f in r.alias))),h=bo(m,t);return{command:n,flags:h,restArgs:i>=0?e.slice(i+1):[]}}function Js(e,t={}){let r=qs(t),s=gu(e,r);vo(s,r,t);let n=Bt(s,r),{_:i,...o}=n;return{args:bo(o,t),rawPositionals:i}}function vo(e,t,r,s=!1){let n=new Set;for(let i of e){if(i==="--")break;let o=i.match(/^-+/)?.[0];if(!o)continue;let a=i.slice(o.length),c=a.split("=",wo)[0]??"",l=a.startsWith("no-")?[a.slice(3)]:o.length===mu?[c]:[...c];for(let p of l){let m=Object.hasOwn(t.alias,p)?t.alias[p]??p:p;if(s&&!Object.hasOwn(r,m))continue;if(n.has(m))throw new u(`${Lr(m,r)} can only be provided once`);n.add(m)}}}function gu(e,t){let r=!0;return e.map((s)=>{if(s==="--")r=!1;if(!r)return s;return s.replace(/^--(no-[^=]+)(=.*)?$/,(n,i,o)=>{let a=t.alias[i];return a&&t.boolean.includes(a)?`--${a}${o??""}`:n})})}function zs(e,t){let r={},s=Object.entries(t);for(let[n,[i,o]]of s.entries())r[i]=o.variadic?e.slice(n):e[n];return r}function $o(e,t){for(let[r,s]of Object.entries(t)){if(!s.required)continue;let n=e[r];if(Array.isArray(n)?n.length===0:!n)return`Missing required argument: <${r}${s.variadic?"...":""}>`}return null}var hu=(e)=>e,x={arg:d.magenta,cmd:d.cyan,default:d.bold,desc:hu,flag:d.green,header:(e)=>d.bold(d.yellow(e)),hint:d.dim,name:(e)=>d.bold(d.cyan(e)),placeholder:d.magenta};class Ks{metadata;commands;globalArgs;constructor(e,t,r){this.metadata=e;this.commands=t;this.globalArgs=r}version(){return`${x.name(this.metadata.name)} ${x.hint(this.metadata.version??"0.0.0")}`}global(){let e=[],{name:t,bin:r,version:s,description:n}=this.metadata;if(e.push(`${x.name(t)}${s?` ${x.hint(`v${s}`)}`:""}`),n)e.push(x.desc(n));e.push(""),e.push(x.header("Usage:")),e.push(` ${x.cmd(r)} ${x.placeholder("[command]")} ${x.placeholder("[options]")}`),e.push(""),e.push(x.header("Commands:"));let i=Array.from(this.commands.values()).map((o)=>[` ${x.cmd(o.name)}`,x.desc(o.description)]);return e.push(...this.formatColumns(i)),e.push(""),e.push(x.header("Options:")),e.push(...this.formatArgDefs(this.globalArgs)),e.push(""),e.push(`${x.hint("Run")} ${x.cmd(`${r} <command> --help`)} ${x.hint("for command details.")}`),e.join(`
|
|
81
81
|
`).trimEnd()}command(e,t){let r=[],s=t??this.metadata.bin,n=`${s} ${e.name}`,i=`${x.cmd(s)} ${x.cmd(e.name)}`;r.push(x.name(n)),r.push(x.desc(e.description)),r.push(""),r.push(x.header("Usage:"));let o=this.formatPositionalUsage(e.positionals);if(e.hasSubcommands())r.push(` ${i} ${x.placeholder("<subcommand>")} ${x.placeholder("[options]")}`);else{let l=[i];if(o)l.push(o);l.push(x.placeholder("[options]")),r.push(` ${l.join(" ")}`)}if(e.prompts&&Object.keys(e.positionals).length>0)r.push(` ${x.hint("Omit positional arguments to run interactively.")}`);if(r.push(""),e.hasSubcommands()){r.push(x.header("Subcommands:"));let l=e.getSubcommands().map((p)=>[` ${x.cmd(p.name)}`,x.desc(p.description)]);r.push(...this.formatColumns(l)),r.push("")}if(Object.entries(e.positionals).length>0)r.push(x.header("Arguments:")),r.push(...this.formatPositionalDefs(e.positionals)),r.push("");if(Object.entries(e.args).length>0)r.push(x.header("Options:")),r.push(...this.formatArgDefs(e.args));return r.join(`
|
|
82
|
-
`).trimEnd()}formatPositionalUsage(e){return Object.entries(e).map(([t,r])=>{let s=r.variadic?`${t}...`:t;return r.required?x.arg(`<${s}>`):x.arg(`[${s}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([r,s])=>{let n=s.variadic?`${r}...`:r,i=x.desc(s.description??""),o=s.required?"":x.hint(" (optional)");return[` ${x.arg(n)}`,`${i}${o}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[r,s]of Object.entries(e)){let n=s.alias?`${x.flag(`-${s.alias}`)}, `:" ",i=s.type==="boolean"?"":` ${x.placeholder(`<${s.type==="number"?"number":"value"}>`)}`,o=`${n}${x.flag(`--${
|
|
83
|
-
Run "${s} --help" for usage.`),process.exit(1)}function
|
|
84
|
-
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&s.length===0&&process.stdout.isTTY===!0,a=this.buildContext(n,r,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=
|
|
82
|
+
`).trimEnd()}formatPositionalUsage(e){return Object.entries(e).map(([t,r])=>{let s=r.variadic?`${t}...`:t;return r.required?x.arg(`<${s}>`):x.arg(`[${s}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([r,s])=>{let n=s.variadic?`${r}...`:r,i=x.desc(s.description??""),o=s.required?"":x.hint(" (optional)");return[` ${x.arg(n)}`,`${i}${o}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[r,s]of Object.entries(e)){let n=s.alias?`${x.flag(`-${s.alias}`)}, `:" ",i=s.type==="boolean"?"":` ${x.placeholder(`<${s.type==="number"?"number":"value"}>`)}`,o=`${n}${x.flag(`--${dt(r)}`)}${i}`,a=x.desc(s.description??""),c=this.formatDefault(s),l=c===void 0?"":` (default: ${x.default(c)})`;t.push([` ${o}`,`${a}${l}`])}return this.formatColumns(t)}formatDefault(e){if(typeof e.displayDefault==="string")return e.displayDefault;if(e.default===void 0)return;if(e.type==="boolean"&&e.default===!1)return;if(e.type==="string")return`"${e.default}"`;return String(e.default)}formatColumns(e){if(e.length===0)return[];let t=Math.max(...e.map(([s])=>this.stripAnsi(s).length)),r=2;return e.map(([s,n])=>{let i=t-this.stripAnsi(s).length+r;return`${s}${" ".repeat(i)}${n}`})}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}}var Te=new Uint32Array(65536),fu=(e,t)=>{let r=e.length,s=t.length,n=1<<r-1,i=-1,o=0,a=r,c=r;while(c--)Te[e.charCodeAt(c)]|=1<<c;for(c=0;c<s;c++){let l=Te[t.charCodeAt(c)],p=l|o;if(l|=(l&i)+i^i,o|=~(l|i),i&=l,o&n)a++;if(i&n)a--;o=o<<1|1,i=i<<1|~(p|o),o&=p}c=r;while(c--)Te[e.charCodeAt(c)]=0;return a},yu=(e,t)=>{let r=t.length,s=e.length,n=[],i=[],o=Math.ceil(r/32),a=Math.ceil(s/32);for(let g=0;g<o;g++)i[g]=-1,n[g]=0;let c=0;for(;c<a-1;c++){let g=0,y=-1,R=c*32,S=Math.min(32,s)+R;for(let k=R;k<S;k++)Te[e.charCodeAt(k)]|=1<<k;for(let k=0;k<r;k++){let H=Te[t.charCodeAt(k)],L=i[k/32|0]>>>k&1,T=n[k/32|0]>>>k&1,W=H|g,B=((H|T)&y)+y^y|H|T,C=g|~(B|y),A=y&B;if(C>>>31^L)i[k/32|0]^=1<<k;if(A>>>31^T)n[k/32|0]^=1<<k;C=C<<1|L,A=A<<1|T,y=A|~(W|C),g=C&W}for(let k=R;k<S;k++)Te[e.charCodeAt(k)]=0}let l=0,p=-1,m=c*32,h=Math.min(32,s-m)+m;for(let g=m;g<h;g++)Te[e.charCodeAt(g)]|=1<<g;let f=s;for(let g=0;g<r;g++){let y=Te[t.charCodeAt(g)],R=i[g/32|0]>>>g&1,S=n[g/32|0]>>>g&1,k=y|l,H=((y|S)&p)+p^p|y|S,L=l|~(H|p),T=p&H;if(f+=L>>>s-1&1,f-=T>>>s-1&1,L>>>31^R)i[g/32|0]^=1<<g;if(T>>>31^S)n[g/32|0]^=1<<g;L=L<<1|R,T=T<<1|S,p=T|~(k|L),l=L&k}for(let g=m;g<h;g++)Te[e.charCodeAt(g)]=0;return f},wu=(e,t)=>{if(e.length<t.length){let r=t;t=e,e=r}if(t.length===0)return e.length;if(e.length<=32)return fu(e,t);return yu(e,t)},Po=(e,t)=>{let r=1/0,s=0;for(let n=0;n<t.length;n++){let i=wu(e,t[n]);if(i<r)r=i,s=n}return t[s]};function Mr(e,t,r,s){let n=Po(t,r);if(console.error(d.red(`Unknown ${e}: ${t}`)),n)console.error(d.yellow(`Did you mean "${n}"?`));console.error(`
|
|
83
|
+
Run "${s} --help" for usage.`),process.exit(1)}function mt(e,t){if(Array.isArray(t))return[...t];if(!Ro(e)||!Ro(t))return t;return Object.fromEntries([...Object.entries(e),...Object.entries(t).map(([r,s])=>[r,mt(Object.hasOwn(e,r)?e[r]:void 0,s)])])}function Ro(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var Ys="__exit__";class gt{command;env;prefix;options;selections;constructor(e,t,r,s={}){this.command=e;this.env=t;this.prefix=r;this.options=s;this.selections=s.selections??new Map}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(e,t){if(t&&process.stdout.isTTY!==!0)throw new u("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(t)await this.routeInteractive();else await this.routeDirect(e)}async routeDirect(e){let[t,...r]=e;if(t&&this.command.hasSubcommands()){let s=this.command.getSubcommand(t);if(s){await this.handleSubcommandRoute(s,r);return}if(!t.startsWith("-")){this.handleUnknownSubcommand(t);return}}await this.executeCommand(e)}handleUnknownSubcommand(e){let t=this.command.getSubcommands().map((r)=>r.name);Mr("subcommand",e,t,this.commandPath)}async handleSubcommandRoute(e,t){await new gt(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:r,rawPositionals:s}=Js(e,this.command.args),n=zs(s,this.command.positionals),i=$o(n,this.command.positionals);if(i)v.error(i),console.error(`
|
|
84
|
+
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&s.length===0&&process.stdout.isTTY===!0,a=this.buildContext(n,r,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=Js([],this.command.args),t=zs([],this.command.positionals),r=this.buildContext(t,e,!0);await this.command.execute?.(r)}async runSubcommandMenu(){while(!0){let e=await this.promptSubcommandSelectionOrBack();if(e===null)return;if(e===Ys){this.options.onExit?.();return}let t=this.command.getSubcommand(e);if(t)this.selections.set(this.commandPath,e),await this.executeSubcommand(t)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(e){if(e instanceof we){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new gt(e,this.env,this.commandPath,{selections:this.selections}).route([],!0)}catch(t){if(t instanceof we)return;if(t instanceof u){if(v.warn(d.yellow(t.message)),t.hint)v.info(d.dim(t.hint));pt(t);return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Ys}:{hint:"Return to previous menu",label:"Back",value:Ys};return Xe({message:e?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,initialValue:this.selections.get(this.commandPath),options:[...this.command.getSubcommands().map((r)=>({hint:r.description,label:r.name,value:r.name})),t]})}buildContext(e,t,r){return{...this.env,args:t,interactive:r,positionals:e}}isHelpRequest(e){let t=e.indexOf("--"),r=t<0?e:e.slice(0,t);return r.includes("--help")||r.includes("-h")}printHelp(e){let t=e===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(e,t))}}var bu="--",So="--help",vu=new Set([So,"-h"]),$u={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"},Pu={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};class Xs{commands=new Map;metadata;configManager;help;bin;globalArgs={...Pu};constructor(e,t){this.configManager=e,this.metadata={...$u,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Ks({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(e){for(let t of e)t.init?.(),this.commands.set(t.name,t)}async run(e=process.argv.slice(2)){try{let{command:t,flags:r,restArgs:s}=Ws(e,this.globalArgs);if(r.version&&!t)return console.log(this.help.version());if(r.interactive&&!t)return await this.runInteractive();if(!t)return console.log(this.help.global());if(t==="help")return this.printHelpFor(s[0]);await this.runDirect(t,s,!!r.help)}catch(t){this.handleError(t)}}printHelpFor(e){if(!e)return console.log(this.help.global());let t=this.commands.get(e);if(!t)return this.handleUnknownCommand(e);console.log(this.help.command(t))}async runInteractive(){this.showIntro();let e=this.createVirtualRootCommand(),t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},r=new gt(e,t,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await r.route([],!0)}catch(s){this.handleError(s)}}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(){Er(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(e,t,r){let s=this.commands.get(e);if(!s)return this.handleUnknownCommand(e);let n=t.length>0&&!t[0]?.startsWith("-");if(r&&!n)return console.log(this.help.command(s));try{let i={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new gt(s,i,this.bin).route(r?Ru(t):t,!1)}catch(i){this.handleError(i)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";Tr(`${d.bgCyan(d.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());Mr("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof we)process.exit(0);if(e instanceof u){if(v.warn(d.yellow(e.message)),e.hint)v.info(d.dim(e.hint));pt(e),process.exit(e.exitCode)}if(e instanceof Error)v.error(d.red(e.message)),pt(e),process.exit(1);console.error(d.red("Error:"),e),process.exit(1)}}function Ru(e){let t=e.indexOf(bu),r=t<0?e:e.slice(0,t);if(r.some((s)=>vu.has(s)))return e;return[...r,So,...t<0?[]:e.slice(t)]}class Vt{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 U(e){return e}function de(e){return e}import ge from"fs";import Eo from"path";var ht=(e)=>(e.map=(t)=>ht((r)=>t(e(r))),e.or=(t)=>ht((r)=>{try{return e(r)}catch(s){return t(r)}}),e),me=()=>"bad banditype"();var Co=()=>ht((e)=>e),ko=(e)=>ht((t)=>e.includes(t)?t:me()),Zs=(e)=>ht((t)=>typeof t===typeof e?t:me()),ve=()=>Zs("");var xo=()=>Zs(!0);var Ut=()=>Zs();var ft=(e)=>ht((t)=>t instanceof e?t:me()),To=(e)=>ft(Object).map((t)=>{let r={};for(let s in t){let n=e(t[s]);n!==void 0&&(r[s]=n)}return r}),Gt=(e)=>ft(Object).map((t)=>{let r={};for(let s in e){let n=e[s](t[s]);n!==void 0&&(r[s]=n)}return r}),Qs=(e)=>ft(Object).map((t)=>{let r={...t};for(let s in e){let n=e[s](t[s]);n!==void 0&&(r[s]=n)}return r}),Ze=(e)=>ft(Array).map((t)=>t.map(e));function Ht(e,t){JSON.parse(e);let r=JSON.parse(JSON.stringify(t)),s=Su(e),n=e.match(/^[\t ]+(?=\S)/m)?.[0]??" ",i=e.includes(`\r
|
|
85
85
|
`)?`\r
|
|
86
86
|
`:`
|
|
87
|
-
`,o=/\s/.test(e[s.start+1]??"")||s.entries.some((l)=>/:\s+$/.test(e.slice(l.start,l.node.start)))?" ":"";function a(l,p){let
|
|
88
|
-
`));let f=h?p.map((C,A)=>String(A)):[...new Set([...l.entries.map((C)=>C.key).filter((C)=>Object.hasOwn(p,C)),...Object.keys(p)])];if(f.length===0)return h?"[]":"{}";let g=l.entries[0],y=l.entries.at(-1);if(!g||!y)return c(p,l.start,
|
|
87
|
+
`,o=/\s/.test(e[s.start+1]??"")||s.entries.some((l)=>/:\s+$/.test(e.slice(l.start,l.node.start)))?" ":"";function a(l,p){let m=e.slice(l.start,l.end);if(JSON.stringify(l.value)===JSON.stringify(p))return m;let h=Array.isArray(p);if(p===null||typeof p!=="object"||l.value===null||typeof l.value!=="object"||Array.isArray(l.value)!==h)return c(p,l.start,m.includes(`
|
|
88
|
+
`));let f=h?p.map((C,A)=>String(A)):[...new Set([...l.entries.map((C)=>C.key).filter((C)=>Object.hasOwn(p,C)),...Object.keys(p)])];if(f.length===0)return h?"[]":"{}";let g=l.entries[0],y=l.entries.at(-1);if(!g||!y)return c(p,l.start,m.includes(`
|
|
89
89
|
`));let R=(C)=>h?p[Number(C)]:p[C];if(f.length===l.entries.length&&f.every((C,A)=>C===l.entries[A]?.key)){let C=l.start,A="";for(let te of l.entries)A+=e.slice(C,te.node.start)+a(te.node,R(te.key)),C=te.node.end;return A+e.slice(C,l.end)}let S=e.slice(l.start+1,g.start),k=e.slice(y.node.end,l.end-1),H=l.entries[1],L=H?e.slice(g.node.end,H.start):`,${S.includes(`
|
|
90
90
|
`)?S:o}`,T=h?"":e.slice(g.start,g.node.start).match(/:\s*$/)?.[0]??": ",W=new Map(l.entries.map((C)=>[C.key,C])),B=f.map((C)=>{let A=W.get(C);if(A)return e.slice(A.start,A.node.start)+a(A.node,R(C));return(h?"":JSON.stringify(C)+T)+c(R(C),g.start,S.includes(`
|
|
91
|
-
`))});return`${h?"[":"{"}${S}${B.join(L)}${k}${h?"]":"}"}`}function c(l,p,
|
|
91
|
+
`))});return`${h?"[":"{"}${S}${B.join(L)}${k}${h?"]":"}"}`}function c(l,p,m){if(!m)return en(l,o);let h=e.lastIndexOf(`
|
|
92
92
|
`,p-1)+1,f=e.slice(h,p).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(l,null,n).replaceAll(`
|
|
93
|
-
`,i+f)}return e.slice(0,s.start)+a(s,r)+e.slice(s.end)}function
|
|
94
|
-
`;if(ge.writeFileSync(r,n,{flag:"wx",mode:s}),s!==void 0)ge.chmodSync(r,s);ge.renameSync(r,t)}catch(s){throw Error(`Failed to save config to ${this.configPath}`,{cause:s})}finally{ge.rmSync(r,{force:!0})}}ensureDirectoryExists(){let e=
|
|
95
|
-
`).filter(Boolean)}catch{return[]}}async getPrFiles(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e}/files --paginate --slurp`.quiet(),r=
|
|
93
|
+
`,i+f)}return e.slice(0,s.start)+a(s,r)+e.slice(s.end)}function en(e,t){if(Array.isArray(e))return`[${e.map((n)=>en(n,t)).join(`,${t}`)}]`;if(e===null||typeof e!=="object")return JSON.stringify(e);let r=Object.entries(e);if(r.length===0)return"{}";let s=r.map(([n,i])=>`${JSON.stringify(n)}:${t}${en(i,t)}`);return`{${t}${s.join(`,${t}`)}${t}}`}function Su(e){let t=e.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),r=t.next().value;function s(){if(!r)throw Error("Unexpected end of JSON");let i=r;return r=t.next().value,i}function n(){let i=s(),o=[],a=i[0]==="{";if(!a&&i[0]!=="[")return{end:i.index+i[0].length,entries:o,start:i.index,value:JSON.parse(i[0])};let c=a?"}":"]";while(r&&r[0]!==c){let p=r.index,m=a?JSON.parse(s()[0]):String(o.length);if(a)s();if(o.push({key:m,node:n(),start:p}),r?.[0]===",")s()}let l=s().index+1;return{end:l,entries:o,start:i.index,value:JSON.parse(e.slice(i.index,l))}}return n()}var Cu=2,ku=ft(Object);class tn{config;configPath;defaultConfig;loadError;loadFailure;constructor(e,t,r={}){this.configPath=Eo.resolve(e),this.defaultConfig=t,this.config=this.loadConfig(r)}get path(){return this.configPath}get failure(){return this.loadFailure}get(e){return this.assertLoaded(),this.config[e]}set(e,t){this.assertLoaded(),this.config={...this.config,[e]:t},this.save()}delete(e){this.assertLoaded(),delete this.config[e],this.save()}exists(){return ge.existsSync(this.configPath)}getAll(){return this.assertLoaded(),structuredClone(this.config)}save(e){if(this.assertLoaded(),this.loadError)throw Error(`Cannot overwrite unreadable config at ${this.configPath}; repair the file and try again`,{cause:this.loadError});if(e)this.config={...e};this.ensureDirectoryExists();let t=this.exists()?ge.realpathSync(this.configPath):this.configPath,r=`${t}.${crypto.randomUUID()}.tmp`;try{let s=this.exists()?ge.statSync(this.configPath).mode:void 0,n=this.exists()?Ht(ge.readFileSync(this.configPath,"utf-8"),this.config):`${JSON.stringify(this.config,null,Cu)}
|
|
94
|
+
`;if(ge.writeFileSync(r,n,{flag:"wx",mode:s}),s!==void 0)ge.chmodSync(r,s);ge.renameSync(r,t)}catch(s){throw Error(`Failed to save config to ${this.configPath}`,{cause:s})}finally{ge.rmSync(r,{force:!0})}}assertLoaded(){if(this.loadFailure)throw this.loadFailure}ensureDirectoryExists(){let e=Eo.dirname(this.configPath);if(!ge.existsSync(e))try{ge.mkdirSync(e,{recursive:!0})}catch(t){throw Error(`Failed to create config directory at ${e}`,{cause:t})}}loadConfig({parse:e,strict:t}){if(!t&&!ge.existsSync(this.configPath))return structuredClone(this.defaultConfig);try{let r=this.readConfigFile();if(r===void 0)return structuredClone(this.defaultConfig);let s=JSON.parse(r);if(Array.isArray(s))throw Error("Config must be an object");let n=mt(structuredClone(this.defaultConfig),ku(s));return e?e(n):n}catch(r){if(t){let s=r instanceof Error?r.message:String(r);return this.loadFailure=Error(`Cannot read config at ${this.configPath}: ${s}`,{cause:r}),structuredClone(this.defaultConfig)}return this.loadError=r,console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),structuredClone(this.defaultConfig)}}readConfigFile(){try{return ge.readFileSync(this.configPath,"utf-8")}catch(e){if(e.code==="ENOENT")return;throw e}}}var Io="0.13.3";class j extends Vt{}import{existsSync as qu}from"fs";import{mkdir as Wu,writeFile as Ju}from"fs/promises";import{dirname as zu}from"path";class Ve{owner;repo;constructor(e){this.owner=e.owner,this.repo=e.repo}}class Dr extends Ve{name="bitbucket";notImplemented(){throw new u("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 getRelease(e){this.notImplemented()}async createRelease(e){this.notImplemented()}async deleteRelease(e){this.notImplemented()}}var F="sis",rn="\uD83E\uDEA8",Qe="other",yt={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},wt=50,bt=".sisyphus",Ao="stones",Oo="released",Nr=7,_o="unknown",qt="unknown",Lo="0.0.0",he="latest",sn=["bun","run","build"],Ee="main",Mo=4,Do=8,jr="config.json";var Ue={$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",email:"r5n-bot@users.noreply.github.com",message:"chore(release): {message}"},commits:{skip:{authors:["r5n-bot[bot]"],messagePatterns:["^chore\\(release\\):","^chore: add stone"]}},dependents:{kinds:["dependencies","devDependencies","optionalDependencies","peerDependencies"],updateInternal:"always"},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:{build:{command:[...sn],outputs:[],root:[]},createRelease:!1,npm:!1,npmVisibilityTimeout:0,push:!1,tags:!1},scripts:{post:{},pre:{}},single:!1,sisyphusDir:".sisyphus",stones:[],tag:"latest"};var Tu=200,Eu=404,Iu=10,Au=3000,No=ve().map((e)=>e.length>0?e:me()),Ou=Ze(Ze(Gt({filename:No,previous_filename:No.or(Ut()),status:ve()}).map((e)=>e.status==="renamed"&&e.previous_filename===void 0?me():e)));function _u(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.tag_name==="string"&&typeof t.draft==="boolean"&&(typeof t.name==="string"||t.name===null)&&(typeof t.body==="string"||t.body===null)}class Fr extends Ve{name="github";get apiPath(){return`repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}`}async ensureAvailable(){try{await Bun.$`which gh`.quiet()}catch{throw new u("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 u("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()||Ee}catch{return Ee}}async findPr(e){try{let t=[];if(e.head)t.push("--head",e.head);if(e.label)t.push("--label",e.label);let r=await Bun.$`gh pr list --json number,url,title,body,labels,author,headRefName,baseRefName,mergeCommit,state --limit 1 ${t}`.quiet(),s=JSON.parse(r.stdout.toString());if(!s[0])return null;return this.mapPrResponse(s[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}`,s=JSON.parse(t.stdout.toString()).number;if(e.labels&&e.labels.length>0){let n=e.labels.flatMap((i)=>["-f",`labels[]=${i}`]);await Bun.$`gh api ${this.apiPath}/issues/${s}/labels --method POST ${n}`}return this.getPr(s)}async updatePr(e,t){let r=[];if(t.title)r.push("--title",t.title);if(t.body)r.push("--body",t.body);await Bun.$`gh pr edit ${e} ${r}`}async getPr(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e}`.quiet(),r=JSON.parse(t.stdout.toString());return this.mapRestApiResponse(r)}catch{throw new u(`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 u("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(`
|
|
95
|
+
`).filter(Boolean)}catch{return[]}}async getPrFiles(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e}/files --paginate --slurp`.quiet(),r=Ou(JSON.parse(t.stdout.toString())).flat();if(r.length>=Au)throw new u(`PR #${e} reaches the GitHub file limit`,"The complete changed file list cannot be established; create the stone from a complete local checkout");return[...new Set(r.flatMap((s)=>s.status==="renamed"&&s.previous_filename!==void 0?[s.previous_filename,s.filename]:[s.filename]))]}catch(t){if(t instanceof u)throw t;throw new u(`Failed to fetch PR #${e} files`,"Check GitHub access and retry the analysis")}}async ensureLabelExists(e,t){try{let r=t?.description??"",s=t?.color?["--color",t.color]:[];await Bun.$`gh label create ${e} --description ${r} ${s} --force`.quiet()}catch{}}async getRelease(e){let t=`${this.apiPath}/releases/tags/${encodeURIComponent(e)}`,r=await Bun.$`gh api ${t} --include`.quiet().nothrow(),s=r.stdout.toString().replaceAll(`\r
|
|
96
96
|
`,`
|
|
97
97
|
`),[n="",...i]=s.split(`
|
|
98
98
|
|
|
99
|
-
`),o=n.match(/^HTTP\/\S+\s+(\d{3})\b/m)?.[1],a=o?Number.parseInt(o,
|
|
99
|
+
`),o=n.match(/^HTTP\/\S+\s+(\d{3})\b/m)?.[1],a=o?Number.parseInt(o,Iu):null;if(r.exitCode!==0){if(a===Eu)return null;let l=a?`GitHub API returned HTTP ${a}`:`gh api failed with exit code ${r.exitCode}; check authentication and network connectivity`;throw this.releaseReadError(e,l)}if(a!==Tu)throw this.releaseReadError(e,a?`GitHub API returned HTTP ${a}`:"missing HTTP status");let c;try{c=JSON.parse(i.join(`
|
|
100
100
|
|
|
101
|
-
`))}catch{throw this.releaseReadError(e,"response was not valid JSON")}if(!
|
|
101
|
+
`))}catch{throw this.releaseReadError(e,"response was not valid JSON")}if(!_u(c))throw this.releaseReadError(e,"response did not contain tag_name, name, and body");return{draft:c.draft,notes:c.body??"",tag:c.tag_name,title:c.name??""}}async createRelease(e){await Bun.$`gh release create ${e.tag} --repo ${`${this.owner}/${this.repo}`} --title ${e.title} --notes ${e.notes} --verify-tag`.quiet()}async deleteRelease(e){try{await Bun.$`gh release delete ${e} --yes`.quiet()}catch{}}mapRestApiResponse(e){return{author:e.user?.login??qt,baseBranch:e.base?.ref??Ee,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??qt,baseBranch:e.baseRefName??Ee,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}}releaseReadError(e,t){return Error(`Failed to fetch GitHub release "${e}" from ${this.owner}/${this.repo}: ${t}`)}}var Lu="https://gitlab.com/api/v4",Mu=404,jo=ve().map((e)=>e.length>0?e:me()),Du=Gt({changes:Ze(Gt({new_path:jo,old_path:jo})),overflow:xo()});class Br extends Ve{name="gitlab";authHeader={};apiUrl;projectPath;constructor(e){super(e);this.apiUrl=process.env.CI_API_V4_URL??Lu,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||Ee}catch{return Ee}}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 r=await this.api(`/projects/${this.projectPath}/merge_requests?${t}`);if(!r[0])return null;return this.mapMrResponse(r[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 r=await this.api(`/projects/${this.projectPath}/merge_requests`,{body:JSON.stringify(t),method:"POST"});return this.mapMrResponse(r)}async updatePr(e,t){let r={};if(t.title)r.title=t.title;if(t.body)r.description=t.body;await this.api(`/projects/${this.projectPath}/merge_requests/${e}`,{body:JSON.stringify(r),method:"PUT"})}async getPr(e){try{let t=await this.api(`/projects/${this.projectPath}/merge_requests/${e}`);return this.mapMrResponse(t)}catch{throw new u(`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(),r=new URLSearchParams({per_page:"1",source_branch:t,state:"opened"}),s=await this.api(`/projects/${this.projectPath}/merge_requests?${r}`);if(!s[0])throw Error("No MR found");return this.mapMrResponse(s[0])}catch{throw new u("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((r)=>r.id)}catch{return[]}}async getPrFiles(e){try{let t=Du(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/changes`));if(t.overflow)throw new u(`GitLab file list is incomplete for MR !${e}`,"Create the stone from a complete local checkout; GitLab reported truncated changes");return[...new Set(t.changes.flatMap((r)=>[r.old_path,r.new_path]))]}catch(t){if(t instanceof u)throw t;throw new u(`Failed to fetch MR !${e} files`,"Check GitLab access and retry the analysis")}}async ensureLabelExists(e,t){try{let r={name:e};if(t?.description)r.description=t.description;if(t?.color)r.color=`#${t.color}`;await this.api(`/projects/${this.projectPath}/labels`,{body:JSON.stringify(r),method:"POST"})}catch{}}async getRelease(e){let t=await this.api(`/projects/${this.projectPath}/releases/${encodeURIComponent(e)}`,void 0,!0);if(t===void 0)return null;if(!Nu(t))throw Error(`GitLab release response for ${e} did not contain tag_name, name, and description`);return{draft:!1,notes:t.description??"",tag:t.tag_name,title:t.name}}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(),r=(e.stdout.toString()+e.stderr.toString()).match(/Token found:\s*(\S+)/);if(r?.[1])return{Authorization:`Bearer ${r[1]}`}}catch{}throw new u("GitLab token not found","Set GITLAB_TOKEN environment variable or install glab CLI and run: glab auth login")}async api(e,t,r=!1){let s=await fetch(`${this.apiUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...this.authHeader,...t?.headers}});if(r&&s.status===Mu)return;if(!s.ok){let n=await s.text().catch(()=>"");throw Error(`GitLab API error: ${s.status} ${s.statusText}${n?` \u2014 ${n}`:""}`)}return s.json()}mapMrResponse(e){return{author:e.author?.username??qt,baseBranch:e.target_branch??Ee,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}}}function Nu(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.tag_name==="string"&&typeof t.name==="string"&&(typeof t.description==="string"||t.description===null)}var ju={github:/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/|$)/,gitlab:/^\/(.+)\/([^/]+)\/-\/merge_requests\/([1-9]\d*)(?:\/|$)/,bitbucket:/^\/([^/]+)\/([^/]+)\/pull-requests\/([1-9]\d*)(?:\/|$)/};async function vt(e){let t=e??await Fo();if(!t)throw new u("Could not detect git provider","Make sure you have a git remote configured (origin)");let r=Fu(t);return await r.ensureAvailable(),r}function Fu(e){switch(e.provider){case"github":return new Fr(e);case"gitlab":return new Br(e);case"bitbucket":return new Dr(e);default:throw new u(`Unsupported provider: ${e.provider}`)}}async function Fo(){let e=await Wt();if(!e)return null;return et(e)}async function Bo(){let e=await Fo();if(!e)throw new u("Could not detect git provider","Make sure you have a git remote configured (origin)");return e.provider}async function Wt(){try{return(await Bun.$`git remote get-url origin`.quiet()).stdout.toString().trim()||null}catch{return null}}function et(e){let t=Bu(e);if(!t)return null;let r=Vo(t.hostname);if(!r)return null;let s=t.path.replace(/^\/+|\/+$/g,"").replace(/\.git$/,"").split("/").filter(Boolean),n=s.pop();if(!n||s.length===0)return null;if(r!=="gitlab"&&s.length!==1)return null;return{owner:s.join("/"),provider:r,repo:n}}function Bu(e){try{let t=new URL(e);return{hostname:t.hostname.toLowerCase(),path:t.pathname}}catch{let t=e.match(/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/),r=t?.[1],s=t?.[2];return r&&s?{hostname:r.toLowerCase(),path:s}:null}}function Vo(e){if(e==="github.com")return"github";if(e==="gitlab.com")return"gitlab";if(e==="bitbucket.org")return"bitbucket";return null}function Uo(e){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return null;let r=Vo(t.hostname.toLowerCase());if(!r)return null;let s=t.pathname.match(ju[r]),[,n,i,o]=s??[],a=Number(o);if(!n||!i||!Number.isSafeInteger(a))return null;return{number:a,owner:n,provider:r,repo:i}}catch{return null}}import{existsSync as Go}from"fs";import{readFile as Vu}from"fs/promises";import{dirname as Uu,join as nn}from"path";import{fileURLToPath as Gu}from"url";var Vr={"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"}},Hu=nn(Uu(Gu(import.meta.url)),"templates"),Ho={"create-stone":"sis-create-stone.yml",release:"sis-release.yml"};class on{async generate(e){let t=[];for(let r of e){let s=await this.readTemplate(r),n=this.getOutputPath(r);t.push({content:s,path:n})}return t}getExistingFiles(e){return e.map((t)=>this.getOutputPath(t)).filter((t)=>Go(t))}async readTemplate(e){let t=nn(Hu,this.provider,Ho[e]);return Vu(t,"utf-8")}}class Ur extends on{provider="github";outputDir=".github/workflows";getOutputPath(e){return nn(this.outputDir,Ho[e])}}var Jt=".gitlab-ci-sisyphus.yml";class Gr extends on{provider="gitlab";outputDir=".";async generate(e){let t=[];t.push(`stages:
|
|
102
102
|
- sisyphus
|
|
103
103
|
`);for(let r of e){let s=await this.readTemplate(r);t.push(s)}return[{content:t.join(`
|
|
104
|
-
`),path:Jt}]}getExistingFiles(e){return
|
|
105
|
-
- local: '${Jt}'`}getOutputPath(e){return Jt}}function
|
|
106
|
-
`);let s=await this.selectWorkflows(e);if(s.length===0){v.info(
|
|
104
|
+
`),path:Jt}]}getExistingFiles(e){return Go(Jt)?[Jt]:[]}getIncludeInstruction(){return`include:
|
|
105
|
+
- local: '${Jt}'`}getOutputPath(e){return Jt}}function qo(e){switch(e){case"github":return new Ur;case"gitlab":return new Gr;default:throw Error(`CI generation is not supported for ${e}`)}}var Ku={bitbucket:"Bitbucket Pipelines",github:"GitHub Actions",gitlab:"GitLab CI"},Yu=U({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 an extends j{name="init";description="Set up CI workflows for automated releases";args=Yu;prompts=!0;async execute(e){let t=await Bo(),r=qo(t);v.info(`Detected ${d.bold(Ku[t])} repository
|
|
106
|
+
`);let s=await this.selectWorkflows(e);if(s.length===0){v.info(d.dim("No workflows selected"));return}let n=r.getExistingFiles(s);if(n.length>0&&!e.args.yes){if(!e.interactive)throw new u(`Workflows already exist: ${n.join(", ")}`,"Use --yes to overwrite existing workflows");if(v.warn(`The following files already exist:
|
|
107
107
|
${n.map((a)=>` ${a}`).join(`
|
|
108
108
|
`)}`),!await V({initialValue:!1,message:"Overwrite existing files?"}))return}let i=await r.generate(s);if(e.args.dryRun){for(let o of i)v.info(`
|
|
109
|
-
${
|
|
110
|
-
`),
|
|
111
|
-
Add this to your ${
|
|
112
|
-
`),v.info(
|
|
113
|
-
${
|
|
114
|
-
`,
|
|
115
|
-
`));return r}static merge(e,t){let r=new Map,s=[],n=[];for(let
|
|
109
|
+
${d.bold(o.path)}:`),v.info(d.dim(o.content));return}for(let o of i){let a=zu(o.path);if(a!=="."&&!qu(a))await Wu(a,{recursive:!0});await Ju(o.path,o.content,"utf-8")}if(q(i.map((o)=>` ${d.green("+")} ${o.path}`).join(`
|
|
110
|
+
`),d.green("CI workflows created")),r instanceof Gr)v.info(`
|
|
111
|
+
Add this to your ${d.bold(".gitlab-ci.yml")}:
|
|
112
|
+
`),v.info(d.cyan(r.getIncludeInstruction())),v.info(""),v.info(`${d.yellow("Note:")} Add a ${d.bold("GITLAB_TOKEN")} CI/CD variable (Personal Access Token with ${d.bold("api")} + ${d.bold("write_repository")} scopes)`),v.info(d.dim("Required for creating release PRs. Settings \u2192 CI/CD \u2192 Variables")),v.info("");if(r instanceof Ur)v.info(`
|
|
113
|
+
${d.yellow("Note:")} Enable ${d.bold('"Allow GitHub Actions to create and approve pull requests"')}`),v.info(d.dim("Settings \u2192 Actions \u2192 General \u2192 Workflow permissions")),v.info("");v.info(d.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 u("No workflows specified","Use --all or specify workflows with --createStone, --release");return xe({initialValues:Object.keys(Vr),message:"Select workflows to create",options:Object.entries(Vr).map(([r,s])=>({hint:s.description,label:s.name,value:r})),required:!1})}getWorkflowsFromFlags(e){if(e.args.all)return Object.keys(Vr);let t=[];if(e.args.createStone)t.push("create-stone");if(e.args.release)t.push("release");return t}}var Wo={["major"]:5,["minor"]:4,["patch"]:3,["dependency"]:2,["snapshot"]:1},$t={["major"]:"\uD83D\uDEA8",["minor"]:"\u2728",["patch"]:"\uD83D\uDC1B",["dependency"]:"\uD83D\uDCE6",["snapshot"]:"\uD83D\uDCF8"},Pt={["major"]:d.red,["minor"]:d.yellow,["patch"]:d.green,["dependency"]:d.blue,["snapshot"]:d.magenta},Ie=["major","minor","patch","dependency","snapshot"];function Xu(e,t){return Wo[e]-Wo[t]}function Hr(e,t){return Xu(e,t)>=0?e:t}var Jo=/^(\w+)(?:\(([^)]+)\))?(!)?: (.+)$/,Zu=/^BREAKING(?: CHANGE|-CHANGE):[\t ]+\S/m,Qu="%x00%H%x00%s%x00%an%x00%b",zo=4,Ko=`
|
|
114
|
+
`,ep=new Set(["build","chore","ci","docs","feat","fix","perf","refactor","style","test"]);class Y{hash;subject;author;body;type;scope;breaking;message;files;constructor(e){let[,,,t]=e.subject.match(Jo)??[];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=!!t||Zu.test(e.body??""),this.message=e.message,this.files=e.files}static async since(e){if(e!==void 0)try{let r=(await Bun.$`git rev-parse --verify --end-of-options ${`${e}^{commit}`}`.quiet()).stdout.toString().trim();return await Y.fetchFromRange(`${r}..HEAD`)}catch(t){let r=new u(`Failed to read commits since ${e}`,"Fetch the missing commit or correct the configured baseline before creating stones");throw r.cause=t,r}return Y.fetchFromRange("HEAD")}static async inRange(e,t){let r=[`origin/${e}..origin/${t}`,`${e}..${t}`];for(let s of r){let n=await Y.tryFetchFromRange(s);if(n)return n}return[]}static async fromHash(e){try{let[t]=await Y.readCommits(["-1",e]);return t??null}catch{return null}}static async fromMerge(e){try{let r=(await Bun.$`git rev-parse ${e}^2`.quiet()).stdout.toString().trim();if(!r)return[];return Y.fetchFromRange(`${e}^1..${r}`)}catch{return[]}}static async tryFetchFromRange(e){try{return await Y.fetchFromRange(e)}catch{return null}}static async fetchFromRange(e){return Y.readCommits([e,"--no-merges"])}static async readCommits(e){let r=(await Bun.$`git log ${e} -z --format=${Qu} --name-only --root`.quiet()).stdout.toString().split("\x00"),s=[],n=0;while(n<r.length){n++;let[i,o,a,c]=r.slice(n,n+zo);n+=zo;let l=[];while(n<r.length&&r[n]!==""){let p=r[n++];if(p===void 0)continue;l.push(l.length===0&&p.startsWith(Ko)?p.slice(Ko.length):p)}if(!i||!o||!a)continue;s.push(Y.parse(i,o,a).withFiles(l).withBody(c?.trim()||void 0))}return s}static parse(e,t,r){let s=t.match(Jo);if(s){let[,n="",i,,o=""]=s,a=n.toLowerCase();if(a&&ep.has(a))return new Y({author:r,files:[],hash:e,message:o,scope:i,subject:t,type:a})}return new Y({author:r,files:[],hash:e,message:t,subject:t,type:Qe})}get shortHash(){return this.hash.slice(0,Nr)}withFiles(e){return new Y({...this.toOptions(),files:e})}withBody(e){return new Y({...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,files:this.files,hash:this.hash,message:this.message,scope:this.scope,subject:this.subject,type:this.type}}}var K=(e)=>e.length>0?e:void 0;var tp=/^[A-Za-z][0-9A-Za-z]*$/,rp=ve().map((e)=>tp.test(e)?e:me());function tt(e,t="Invalid prerelease tag"){try{return rp(e)}catch{throw new u(t,"Start with a letter and use only letters or numbers")}}var sp=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/,np=/^(0|[1-9]\d*)$/,Yo=10,cn=1,ip=2;function Ae(e){let t=sp.exec(e);if(!t)return null;let[,r="0",s="0",n="0",i,o]=t,a=[r,s,n].map((l)=>Number.parseInt(l,Yo)),c=i?i.split(".").map(op):[];if(a.some((l)=>!Number.isSafeInteger(l)))return null;if(c.some((l)=>typeof l==="number"&&!Number.isSafeInteger(l)))return null;return{build:o?o.split("."):[],major:a[0],minor:a[1],patch:a[2],prerelease:c}}function qr(e,t){let r=Ae(e);if(r)return r;throw new u(`Cannot ${t}: "${e}" is not a valid version`,'Set the package version to MAJOR.MINOR.PATCH (no leading "v") before releasing')}function Wr(e){let t=e.prerelease.length>0?`-${e.prerelease.join(".")}`:"",r=e.build.length>0?`+${e.build.join(".")}`:"";return`${e.major}.${e.minor}.${e.patch}${t}${r}`}function Oe(e){return e.prerelease.length>0}function Xo(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}function Zo(e,t){let r=e.major-t.major||e.minor-t.minor||e.patch-t.patch;if(r!==0)return r<0?-1:1;return ap(e.prerelease,t.prerelease)}function Qo(e,t){let r=Oe(e);if(t==="major"){let s=r&&e.minor===0&&e.patch===0;return ln(s?e.major:e.major+cn,0,0)}if(t==="minor"){let s=r&&e.patch===0;return ln(e.major,s?e.minor:e.minor+cn,0)}return ln(e.major,e.minor,r?e.patch:e.patch+cn)}function Jr(e,t,r){return{...e,build:[],prerelease:[t,r]}}function zt(e){return ta(e)?.tag}function ea(e){return ta(e)?.counter}function ta(e){if(e.prerelease.length!==ip)return;let[t,r]=e.prerelease;if(typeof t!=="string"||typeof r!=="number")return;return{counter:r,tag:t}}function ln(e,t,r){return{build:[],major:e,minor:t,patch:r,prerelease:[]}}function op(e){return np.test(e)?Number.parseInt(e,Yo):e}function ap(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return 1;if(t.length===0)return-1;let r=Math.max(e.length,t.length);for(let s=0;s<r;s+=1){let n=e[s],i=t[s];if(n===void 0)return-1;if(i===void 0)return 1;if(n===i)continue;let o=typeof n==="number",a=typeof i==="number";if(o&&a)return n<i?-1:1;if(o)return-1;if(a)return 1;return n<i?-1:1}return 0}var cp=1,ra=0,lp=/[.ZT:-]/g,up=14,pp="0.0.0",dp=/^0\.0\.0-[0-9A-Za-z.-]+-\d{14,}$/,mp="nightly",gp={dependency:"patch",major:"major",minor:"minor",patch:"patch"};class fe{static bump(e,t,r,s=!1){if(r!==void 0)tt(r);if(t==="snapshot")return fe.formatSnapshot(r);let n=`apply a ${t} bump`,i=gp[t];if(!i)throw new u(`Unknown bump type "${t}"`,"Use major, minor, patch, dependency, or snapshot");if(fe.isSnapshotVersion(e))throw new u(`Cannot ${n} to snapshot version ${e}`,"Restore the package version from its last real release before releasing it again");let o=qr(e,n),a=fe.resolveTag(o,t,r,s),c=Qo(o,i),l=a===void 0?c:fe.applyPrerelease(c,o,a,e);if(Zo(l,o)<=0)throw new u(`A ${t} bump would move ${e} to ${Wr(l)}, which is not a later version`,"Prerelease tags must increase in semver precedence (alpha < beta < rc)");return Wr(l)}static formatLabel(e,t,r,s,n){let i=n??fe.bump(t,r,s),o=$t[r];return`${e}@${t} => ${i} ${o}`}static isSnapshotVersion(e){return dp.test(e)}static resolveTag(e,t,r,s){if(r!==void 0)return r;if(s||t!=="dependency")return;let n=zt(e);if(n===void 0&&Oe(e))throw new u(`Cannot continue the prerelease of ${Wr(e)}`,"Set the package version to a <tag>.<number> prerelease, or roll a graduating release to leave the channel");return n}static applyPrerelease(e,t,r,s){if(tt(r),!Xo(e,t))return Jr(e,r,ra);let n=ea(t);if(zt(t)===r&&n!==void 0)return Jr(e,r,n+cp);if(t.prerelease[0]===r){let i=`${e.major}.${e.minor}.${e.patch}`;throw new u(`Cannot continue the "${r}" prerelease from ${s}`,`Set the package version to ${i}-${r}.<number> first`)}return Jr(e,r,ra)}static formatSnapshot(e){let t=new Date().toISOString().replace(lp,"").slice(0,up);return`${pp}-${e||mp}-${t}`}}var hp={build:[],major:0,minor:0,patch:0,prerelease:[]},zr="workspace:",sa=["dependencies","devDependencies","optionalDependencies","peerDependencies"];function fp(e){let t=[];for(let r of sa)for(let[s,n]of Object.entries(e[r]??{})){if(!n?.startsWith(zr))continue;t.push({kind:r,name:s,specifier:n})}return t}class z{name;version;file;workspaceDependencies;bump;tag;isPrivate;_newVersion;constructor(e){this.name=e.name,this.version=e.version,this.file=e.file,this.workspaceDependencies=e.workspaceDependencies??[],this.bump=e.bump,this.tag=e.tag,this.isPrivate=e.isPrivate??!1,this._newVersion=e.newVersion}static fromJson(e,t){return new z({file:t,isPrivate:e.private??!1,name:e.name,version:e.version||Lo,workspaceDependencies:fp(e)})}static applyStone(e,t,r=sa){let s=[],n=new Set,i=z.graduatingPackages(e,t,new Set(r));for(let o of Ie)for(let a of e.getPackages(o)){let c=t.get(a);if(!c||n.has(a))continue;n.add(a),s.push(c.withBump(o,e.tag,i.has(a)))}return s}static graduatingPackages(e,t,r){let s=new Set;if(e.tag!==void 0)return s;let n=Ie.filter((a)=>a!=="dependency"&&a!=="snapshot");for(let a of n)for(let c of e.getPackages(a))if(z.isPrereleaseVersion(t.get(c)?.version))s.add(c);let i=e.getPackages("dependency").map((a)=>t.get(a)).filter((a)=>a!==void 0&&z.isPrereleaseVersion(a.version)),o=!0;while(o){o=!1;for(let a of i){if(s.has(a.name))continue;if(!a.workspaceDependencies.some((c)=>r.has(c.kind)&&s.has(c.name)))continue;s.add(a.name),o=!0}}return s}static isPrereleaseVersion(e){return e!==void 0&&Oe(Ae(e)??hp)}get newVersion(){if(this._newVersion)return this._newVersion;if(!this.bump)return;return fe.bump(this.version,this.bump,this.tag)}get label(){if(!this.bump)return`${this.name}@${this.version}`;return fe.formatLabel(this.name,this.version,this.bump,this.tag,this._newVersion)}withBump(e,t,r=!1){return new z({...this.toOptions(),bump:e,newVersion:fe.bump(this.version,e,t,r),tag:t})}withVersions(e,t){return new z({...this.toOptions(),newVersion:t,version:e})}toOptions(){return{bump:this.bump,file:this.file,isPrivate:this.isPrivate,name:this.name,newVersion:this._newVersion,tag:this.tag,version:this.version,workspaceDependencies:this.workspaceDependencies}}}import{randomUUID as yp}from"crypto";var wp=Ze(ve());class M{id;message;tag;description;commits;_packages;constructor(e){this.id=e.id,this.message=e.message,this.tag=e.tag===void 0?void 0:tt(e.tag),this.description=e.description,this.commits=e.commits,this._packages=e.packages}static create(e,t=0){let r=M.generateId(t);return M.fromData(r,e)}static fromJson(e){return M.fromData(e.id,e)}static mergeAll(e){if(e.length===0)throw Error("No stones to merge");let t=e.map((n)=>n.message).join("; "),{stone:r,errors:s}=M.merge(e,t);if(s.length>0)throw new u("Pending stones conflict and cannot be released together",s.join(`
|
|
115
|
+
`));return r}static merge(e,t){let r=new Map,s=[],n=[];for(let m of e)for(let h of Ie)M.collectBumps(m,h,r,s,n);let i=M.categorizeBumps(r),o=e.map((m)=>m.description).filter(Boolean).join(`
|
|
116
116
|
|
|
117
|
-
`),a=M.mergeCommits(e),c=M.resolveTag(e,n),l=`merged-${Date.now()}`,p=new M({commits:a.length>0?a:void 0,description:o||void 0,id:l,message:t,packages:i,tag:c});return{conflicts:[...new Set(s)],errors:[...new Set(n)],stone:p}}static resolveTag(e,t){let r=e.filter((i)=>!i.isEmpty),s=new Map;for(let i of r){if(!i.tag)continue;s.set(i.tag,[...s.get(i.tag)??[],i.id])}if(s.size===0)return;let n=r.filter((i)=>!i.tag).map((i)=>i.id);if(s.size>1||n.length>0){let i=[...s.entries()].map(([o,a])=>`${o}: ${a.join(", ")}`);if(n.length>0)i.push(`no tag: ${n.join(", ")}`);t.push(`Stones disagree on the prerelease tag (${i.join("; ")})`)}return[...s.keys()][0]}static mergeCommits(e){let t=new Map;for(let r of e.flatMap((s)=>s.commits??[])){let s=t.get(r.hash);if(!s){t.set(r.hash,{...r,packages:[...r.packages??[]]});continue}let n=new Set([...s.packages,...r.packages??[]]);t.set(r.hash,{...s,packages:[...n]})}return[...t.values()]}static collectBumps(e,t,r,s,n){for(let i of e.getPackages(t)){let o=r.get(i);if(!o){r.set(i,t);continue}if(o===t)continue;if(o==="snapshot"||t==="snapshot"){n.push(`Package ${i} is requested as both a snapshot and a ${o==="snapshot"?t:o} release`);continue}s.push(i);let a=Hr(t,o);if(a!==o)r.set(i,a)}}static categorizeBumps(e){let t=new Map;for(let r of Ie)t.set(r,[]);for(let[r,s]of e)t.get(s)?.push(r);return t}static fromData(e,t){let r=new Map;for(let s of Ie){let n=t[s];try{r.set(s,n===void 0?[]:
|
|
117
|
+
`),a=M.mergeCommits(e),c=M.resolveTag(e,n),l=`merged-${Date.now()}`,p=new M({commits:a.length>0?a:void 0,description:o||void 0,id:l,message:t,packages:i,tag:c});return{conflicts:[...new Set(s)],errors:[...new Set(n)],stone:p}}static resolveTag(e,t){let r=e.filter((i)=>!i.isEmpty),s=new Map;for(let i of r){if(!i.tag)continue;s.set(i.tag,[...s.get(i.tag)??[],i.id])}if(s.size===0)return;let n=r.filter((i)=>!i.tag).map((i)=>i.id);if(s.size>1||n.length>0){let i=[...s.entries()].map(([o,a])=>`${o}: ${a.join(", ")}`);if(n.length>0)i.push(`no tag: ${n.join(", ")}`);t.push(`Stones disagree on the prerelease tag (${i.join("; ")})`)}return[...s.keys()][0]}static mergeCommits(e){let t=new Map;for(let r of e.flatMap((s)=>s.commits??[])){let s=t.get(r.hash);if(!s){t.set(r.hash,{...r,packages:[...r.packages??[]]});continue}let n=new Set([...s.packages,...r.packages??[]]);t.set(r.hash,{...s,packages:[...n]})}return[...t.values()]}static collectBumps(e,t,r,s,n){for(let i of e.getPackages(t)){let o=r.get(i);if(!o){r.set(i,t);continue}if(o===t)continue;if(o==="snapshot"||t==="snapshot"){n.push(`Package ${i} is requested as both a snapshot and a ${o==="snapshot"?t:o} release`);continue}s.push(i);let a=Hr(t,o);if(a!==o)r.set(i,a)}}static categorizeBumps(e){let t=new Map;for(let r of Ie)t.set(r,[]);for(let[r,s]of e)t.get(s)?.push(r);return t}static fromData(e,t){let r=new Map;for(let s of Ie){let n=t[s];try{r.set(s,n===void 0?[]:wp(n))}catch{throw new u(`Invalid ${s} packages in stone ${e}`,"Each bump field must contain an array of package names")}}return new M({commits:t.commits,description:t.description,id:e,message:t.message,packages:r,tag:t.tag})}static generateId(e){let t=String(e+1).padStart(Mo,"0"),r=yp().slice(0,Do);return`${t}-${r}`}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 M({...this.toOptions(),message:e})}withPackages(e,t){let r=new Map(this._packages);return r.set(e,t),new M({...this.toOptions(),packages:r})}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:K(this.dependency),description:this.description,id:this.id,major:K(this.major),message:this.message,minor:K(this.minor),patch:K(this.patch),snapshot:K(this.snapshot),tag:this.tag}}}import{readFile as $p,rm as Pp,writeFile as na}from"fs/promises";import{dirname as Rp,join as Sp}from"path";var bp={bitbucket:"commits",github:"commit",gitlab:"-/commit"},vp={bitbucket:"bitbucket.org",github:"github.com",gitlab:"gitlab.com"};function un(e){let t=vp[e.provider],r=bp[e.provider],s=`https://${t}/${e.owner}/${e.repo}`;return(n)=>`${s}/${r}/${n}`}class Kt{cached=void 0;async getRemoteInfo(){if(this.cached!==void 0)return this.cached;let e=await Wt();if(!e)return this.cached=null,null;let t=et(e);if(!t)return this.cached=null,null;return this.cached={...t,commitUrl:un(t)},this.cached}}class rt{config;originals=new Map;remoteParser=new Kt;commitUrlFn=null;constructor(e){this.config=e}async generate(e,t){await this.initCommitLinks();let r=new Map(t.map((s)=>[s.name,s]));for(let s of t){let n=this.filterStonesForPackage(e,s.name),i=this.getBumpedDependencies(e,s.name,r);await this.generateForPackage(n,s,i)}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,r){let s=new Set;for(let n of e){if(!n.dependency.includes(t))continue;for(let i of[...n.major,...n.minor,...n.patch])s.add(i)}return[...s].map((n)=>r.get(n)).filter((n)=>n!==void 0)}filterStonesForPackage(e,t){return e.filter((r)=>this.hasDirectChanges(r,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 Pp(e,{force:!0});else await na(e,t,"utf-8");this.originals.clear()}async generateForPackage(e,t,r){let s=Sp(Rp(t.file),this.config.filename),n=this.formatEntry(e,t,r);await this.prependToChangelog(s,n,t.name)}async generateRoot(e,t){let r=this.config.filename,s=this.formatRootEntry(e,t);await this.prependToChangelog(r,s,"Changelog")}async prependToChangelog(e,t,r){let s=await this.readExisting(e);if(!this.originals.has(e))this.originals.set(e,s);let n=s?this.extractTitle(s):`# ${r}`,i=s?this.extractRest(s):"",o=`${n}
|
|
118
118
|
|
|
119
119
|
${t}${i?`
|
|
120
120
|
|
|
121
121
|
${i}`:""}
|
|
122
|
-
`;await
|
|
122
|
+
`;await na(e,o,"utf-8")}async readExisting(e){try{return await $p(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}extractTitle(e){let t=e.split(`
|
|
123
123
|
`)[0]??"";return t.startsWith("#")?t:"# Changelog"}extractRest(e){let t=e.split(`
|
|
124
124
|
`);if(!(t[0]??"").startsWith("#"))return e;let s=1;while(s<t.length&&t[s]?.trim()==="")s++;return t.slice(s).join(`
|
|
125
|
-
`).trim()}formatEntry(e,t,r){let s=this.formatPackageHeader(t),n=r.length>0,i=[`## ${s}`];for(let o of e)i.push("",`### ${
|
|
126
|
-
`)}formatRootEntry(e,t){let s=[`## ${this.formatRootHeader(t)}`];s.push("","**Packages**");for(let n of t){let i=this.getEmoji(n),o=n.newVersion?`${n.version} \u2192 ${n.newVersion}`:n.version;s.push(`- ${i} \`${n.name}\` ${o}`)}for(let n of e)s.push("",`### ${
|
|
125
|
+
`).trim()}formatEntry(e,t,r){let s=this.formatPackageHeader(t),n=r.length>0,i=[`## ${s}`];for(let o of e)i.push("",`### ${rn} ${o.message}`),i.push("",this.formatStoneContent(o,t.name));if(n){i.push("",`### ${this.config.sections.dependencies}`);for(let o of r)i.push(`- \`${o.name}\` ${o.version} \u2192 ${o.newVersion}`)}return i.join(`
|
|
126
|
+
`)}formatRootEntry(e,t){let s=[`## ${this.formatRootHeader(t)}`];s.push("","**Packages**");for(let n of t){let i=this.getEmoji(n),o=n.newVersion?`${n.version} \u2192 ${n.newVersion}`:n.version;s.push(`- ${i} \`${n.name}\` ${o}`)}for(let n of e)s.push("",`### ${rn} ${n.message}`),s.push(this.formatStonePackages(n)),s.push("",this.formatRootStoneContent(n));return s.join(`
|
|
127
127
|
`)}formatPackageHeader(e){let t=e.newVersion??e.version,r=this.getDate(),s=this.getEmoji(e);return this.config.packageHeader.replace("{emoji}",()=>s).replace("{version}",()=>t).replace("{date}",()=>r)}formatRootHeader(e){let t=this.getDate(),r=e.map((s)=>`${s.name}@${s.newVersion??s.version}`).join(", ");return this.config.rootHeader.replace("{date}",()=>t).replace("{packages}",()=>r)}formatRootStoneContent(e){let t=[];if(e.description)t.push(this.formatDescription(e.description));if(e.commits?.length){let r=!this.isSectionName(e.message);t.push(this.formatRootCommits(e.commits,r))}return t.join(`
|
|
128
128
|
|
|
129
129
|
`)}formatRootCommits(e,t){let r=this.formatCommits(e,t);return`<details>
|
|
@@ -150,82 +150,82 @@ ${this.convertHeadersToBold(e).split(`
|
|
|
150
150
|
<summary>Details</summary>
|
|
151
151
|
|
|
152
152
|
${s}
|
|
153
|
-
</details>`}return r}}import{readdir as
|
|
154
|
-
`);if(r[
|
|
155
|
-
`));if(Array.isArray(n))return null;let i=
|
|
156
|
-
`).trim()}}catch{return null}}async parseConfig(){try{let e=
|
|
153
|
+
</details>`}return r}}import{readdir as ia,readFile as oa}from"fs/promises";import{join as pn}from"path";var Cp=".changeset",kp="config.json",xp=To(ve()),aa=0,dn=1;class mn{root;constructor(e=process.cwd()){this.root=e}get changesetDir(){return pn(this.root,Cp)}async exists(){try{return await ia(this.changesetDir),!0}catch{return!1}}async parse(){let e=[],t=[],r=await this.findChangesetFiles();for(let n of r){let i=await this.parseFile(n);if(i)t.push(i);else e.push(`Failed to parse: ${n}`)}let s=await this.parseConfig();return{changesets:t,config:s,errors:e}}async findChangesetFiles(){try{return(await ia(this.changesetDir)).filter((t)=>t.endsWith(".md")&&t!=="README.md").map((t)=>pn(this.changesetDir,t))}catch{return[]}}async parseFile(e){try{let r=(await oa(e,"utf-8")).split(`
|
|
154
|
+
`);if(r[aa]?.trim()!=="---")return null;let s=r.findIndex((a,c)=>c>aa&&a.trim()==="---");if(s<dn)return null;let n=Bun.YAML.parse(r.slice(dn,s).join(`
|
|
155
|
+
`));if(Array.isArray(n))return null;let i=xp(n);if(Object.keys(i).length===0)return null;return{filename:e.split("/").pop()??"",packages:i,summary:r.slice(s+dn).join(`
|
|
156
|
+
`).trim()}}catch{return null}}async parseConfig(){try{let e=pn(this.changesetDir,kp),t=await oa(e,"utf-8");return JSON.parse(t)}catch{return null}}toStoneData(e){let t=[],r=[],s=[],n=[];for(let[c,l]of Object.entries(e.packages))switch(l){case"major":t.push(c);break;case"minor":r.push(c);break;case"patch":s.push(c);break;default:n.push(`${c} uses an unsupported bump type "${l}"`)}if(n.length>0)throw new u(`Changeset ${e.filename}: ${n.join("; ")}`,"Rewrite them as major, minor, or patch before migrating");let i=e.summary.split(`
|
|
157
157
|
`),o=i[0]?.trim()||"Migrated from changeset";return{description:i.slice(1).join(`
|
|
158
|
-
`).trim()||void 0,major:K(t),message:o,minor:K(r),patch:K(s)}}}function Kr(e){let t=new Map;for(let[r,s]of e){let n=s.file.replace(/\\/g,"/"),i=n.substring(0,n.lastIndexOf("/"))||".";t.set(i,r)}return t}function Yt(e,t,r=!0){let s=new Set;for(let n of e)for(let[i,o]of t){let a=i===".",c=n.startsWith(`${i}/`);if(a?r:c)s.add(o)}return s}var la="*",ua="^",dn="~",aa=new Map;function ee(e,t){return t.some((r)=>r===e||Ep(e,r))}function ce(e,t){let r=e.get("dependents")??Ue.dependents;return{ignore:e.get("ignore")??[],kinds:r.kinds,tag:t,updateInternal:r.updateInternal}}function Rp(e,t,r){let s=e.slice(zr.length);if(s===la)return t!==r;if(s!==ua&&s!==dn)return!1;let n=Ae(t),i=Ae(r);if(!n||!i)return!0;if(Oe(n)||Oe(i))return!0;if(n.major!==i.major)return!0;if(s===dn)return n.minor!==i.minor;if(n.major!==0)return!1;if(n.minor!==0)return n.minor!==i.minor;return n.minor!==i.minor||n.patch!==i.patch}function St(e,t,r){let s=r.ignore??[],n=xp(t,new Set(r.kinds),s),i=new Map,o=new Set,a=[];for(let c of[...e].sort((l,p)=>Rt(l.name,p.name))){if(!t.has(c.name)||ee(c.name,s))continue;if(o.add(c.name),ca(i,c.name,c.bump))Yr(a,c.name)}while(a.length>0){let c=a.shift();if(!c)continue;let l=t.get(c),p=i.get(c),d=n.get(c);if(!l||!p||!d)continue;let h=r.updateInternal==="outOfRange",f=Ae(l.version),g=f!==null&&Oe(f),y=h&&!g?fe.bump(l.version,p,r.tag):l.version;for(let R of d){let S=g?Sp(R.specifier):Rp(R.specifier,l.version,y);if(h&&!S)continue;if(ca(i,R.dependent,"dependency"))Yr(a,R.dependent)}}return[...i.keys()].filter((c)=>!o.has(c)).sort(Rt)}function Sp(e){let t=e.slice(zr.length);return t===la||t===ua||t===dn}function gn(e,t){if(t.length===0)return{skipped:[],stone:e};let r=[],s=e;for(let n of Ie){let i=e.getPackages(n),o=i.filter((a)=>!ee(a,t));if(o.length===i.length)continue;r.push(...i.filter((a)=>!o.includes(a))),s=s.withPackages(n,o)}return{skipped:[...new Set(r)].sort(Rt),stone:s}}function pa(e,t){if(t.length===0)return{kept:[...e],skipped:[]};let r=[],s=[];for(let n of e)if(ee(n.name,t))s.push(n.name);else r.push(n);return{kept:r,skipped:s}}function Xt(e){let t=new Map(e.map((p)=>[p.name,p])),r=[...t.keys()].sort(Rt),s=new Map,n=new Map,i=new Map;for(let p of r){let d=new Set((t.get(p)?.workspaceDependencies??[]).filter((h)=>h.kind!=="devDependencies").map((h)=>h.name).filter((h)=>h!==p&&t.has(h)));s.set(p,d.size),i.set(p,d);for(let h of d)n.set(h,[...n.get(h)??[],p])}let o=r.filter((p)=>s.get(p)===0),a=[],c=new Set,l=[];while(c.size<r.length){if(o.length===0){let h=Cp(r,c,n,i);if(!h)break;l.push(h),Yr(o,h)}let p=o.shift();if(!p||c.has(p))continue;c.add(p);let d=t.get(p);if(d)a.push(d);for(let h of n.get(p)??[]){if(c.has(h))continue;let f=(s.get(h)??0)-1;if(s.set(h,f),f===0)Yr(o,h)}}return{cycle:l,ordered:a}}function Cp(e,t,r,s){let n=kp(e,t,s),i=n.size>0?e.filter((c)=>n.has(c)):e,o,a=-1;for(let c of i){if(t.has(c))continue;let l=(r.get(c)??[]).filter((p)=>!t.has(p)).length;if(l<=a)continue;o=c,a=l}return o}function kp(e,t,r){let s=new Map,n=new Map,i=[],o=new Set,a=new Set,c=(l)=>{let p=s.size;s.set(l,p),n.set(l,p),i.push(l),o.add(l);for(let g of r.get(l)??[]){if(t.has(g))continue;if(!s.has(g))c(g),n.set(l,Math.min(n.get(l)??p,n.get(g)??p));else if(o.has(g))n.set(l,Math.min(n.get(l)??p,s.get(g)??p))}if(n.get(l)!==p)return;let d=new Set,h;do{if(h=i.pop(),h===void 0)break;o.delete(h),d.add(h)}while(h!==l);if([...d].some((g)=>[...r.get(g)??[]].some((y)=>!t.has(y)&&!d.has(y))))return;for(let g of d)a.add(g)};for(let l of e)if(!t.has(l)&&!s.has(l))c(l);return a}function xp(e,t,r){let s=new Map;for(let n of[...e.keys()].sort(Rt)){if(ee(n,r))continue;for(let i of e.get(n)?.workspaceDependencies??[]){if(!Tp(i,t,e,r))continue;s.set(i.name,[...s.get(i.name)??[],{dependent:n,specifier:i.specifier}])}}return s}function Tp(e,t,r,s){if(!t.has(e.kind))return!1;if(!r.has(e.name))return!1;return!ee(e.name,s)}function ca(e,t,r){let s=e.get(t),n=s===void 0?r:Hr(s,r);if(s!==void 0&&n===s)return!1;return e.set(t,n),!0}function Yr(e,t){if(e.includes(t))return;let r=e.findIndex((s)=>Rt(s,t)>0);if(r<0)e.push(t);else e.splice(r,0,t)}function Rt(e,t){if(e===t)return 0;return e<t?-1:1}function Ep(e,t){let r=aa.get(t);if(!r)r=new Bun.Glob(t),aa.set(t,r);return r.match(e)}import{existsSync as Ct}from"fs";import{mkdir as ma,readdir as hn,readFile as da,unlink as ga,writeFile as ha}from"fs/promises";import{dirname as Ip,join as Zt,resolve as fa}from"path";var ya=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,wa=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/;class O{config;constructor(e){this.config=e}get sisyphusDir(){return this.config.get("sisyphusDir")||bt}get stonesPath(){return this.config.get("stonesPath")||Zt(this.sisyphusDir,Io)}get releasedPath(){return Zt(this.sisyphusDir,Ao)}async list(){let e=await this.listIds(),t=[];for(let r of e){let s=await this.get(r);if(s)t.push(s)}return t}async listIds(){return await this.ensureStorageExists(),(await hn(this.stonesPath)).filter((t)=>t.endsWith(".json")).map((t)=>this.toStoneId(t)).sort()}async get(e){let t=this.getFilePath(e);if(!Ct(t))return null;let r=await da(t,"utf-8"),s=this.parseStoneJson(r,t);if(s.id!==e)throw Error(`Stone file ID mismatch: expected "${e}", found "${String(s.id)}"`);return M.fromJson(s)}parseStoneJson(e,t){try{return JSON.parse(e)}catch{throw new u(`Failed to parse stone file ${t}`,"Remove or fix the file")}}async save(e){await this.ensureStorageExists();let t=this.getFilePath(e.id),r=JSON.stringify(e.toJson(),null,2);await ha(t,r,"utf-8"),this.addToConfigStones(e.id)}async delete(e){let t=this.getFilePath(e);if(!Ct(t))return!1;return await ga(t),this.removeFromConfigStones(e),!0}async deleteMany(e){let t=0;for(let r of e)if(await this.delete(r))t++;return t}async create(e){let t=await this.listIds(),r=M.create(e,t.length);return await this.save(r),r}async archive(e){if(e.length===0)return"";let t=this.createTimestamp(),r=Zt(this.releasedPath,t);await ma(r,{recursive:!0});for(let s of e){let n=this.getFilePath(s.id),i=Zt(r,`${s.id}.json`);if(Ct(n))await ha(i,JSON.stringify(s.toJson(),null,2),"utf-8"),await ga(n),this.removeFromConfigStones(s.id)}return t}async getReleasedStones(e,t){let r=this.getArchivePath(e);if(!Ct(r))return[];let n=(await hn(r)).filter((a)=>a.endsWith(".json")).sort(),i=t?.map((a)=>`${this.validateId(a)}.json`).sort();if(i&&JSON.stringify(n)!==JSON.stringify(i))throw Error(`Released stone archive ${e} does not match currentRelease: expected ${i.join(", ")||"no stones"}, found ${n.join(", ")||"no stones"}`);let o=[];for(let a of n)try{let c=this.validateId(a.slice(0,-5)),l=Zt(r,a),p=await da(l,"utf-8"),d=this.parseStoneJson(p,l);if(d.id!==c)throw Error(`Stone file ID mismatch: expected "${c}", found "${String(d.id)}"`);o.push(M.fromJson(d))}catch(c){if(t)throw c;v.warn(m.dim(`Failed to parse stone "${a}": ${c}`))}return o}async listReleasedTimestamps(){if(!Ct(this.releasedPath))return[];return(await hn(this.releasedPath,{withFileTypes:!0})).filter((t)=>t.isDirectory()&&wa.test(t.name)).map((t)=>t.name)}async getTrackedCommitPackages(){let e=await this.list(),t=new Map;for(let r of e.flatMap((s)=>s.commits??[])){let s=t.get(r.hash)??new Set;for(let n of r.packages)s.add(n);t.set(r.hash,s)}return t}getFilePath(e){let t=this.validateId(e);return this.resolveChildPath(this.stonesPath,`${t}.json`,`Stone path must be a direct child of the stones directory: ${e}`)}getFilePaths(e){return e.map((t)=>this.getFilePath(t.id))}createTimestamp(){return new Date().toISOString().replace(/[:.]/g,"-")}getArchivePath(e){if(!wa.test(e))throw Error(`Invalid released stone timestamp "${e}"`);return this.resolveChildPath(this.releasedPath,e,`Released stone archive must be a direct child of the released directory: ${e}`)}resolveChildPath(e,t,r){let s=fa(e),n=fa(s,t);if(Ip(n)!==s)throw Error(r);return n}validateId(e){if(!ya.test(e))throw Error(`Invalid stone ID "${e}"`);return e}toStoneId(e){let t=e.slice(0,-5);if(ya.test(t))return t;throw new u(`Invalid stone ID "${t}" from stone file ${e} in ${this.stonesPath}`,"Remove or rename the file; stone files must match <seq>-<hash>.json")}async ensureStorageExists(){if(!Ct(this.stonesPath))await ma(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(),r=t.stones.filter((s)=>s!==e);if(r.length!==t.stones.length)this.config.set("stones",r)}}class G{static async scan(e={}){let{filter:t,single:r}=e;if(r)return G.scanRootPackage(t);let s=await G.getWorkspaces();G.validateWorkspaces(s);let n=await G.scanWorkspaces(s);return{packageNames:G.filterNames(Array.from(n.keys()),t),packages:n}}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 u("Could not read package.json","Ensure you're in a project root directory.")}}static validateWorkspaces(e){if(e.length===0)throw new u("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((r)=>r.includes(t))}static async scanRootPackage(e){let t=await Bun.file("package.json").json(),r=z.fromJson(t,"package.json"),s=new Map;return s.set(r.name,r),{packageNames:G.filterNames([r.name],e),packages:s}}static async scanWorkspaces(e){let t=new Map;for(let r of e){let s=new Bun.Glob(`${r}/package.json`).scanSync({cwd:process.cwd()});for(let n of s){let i=await Bun.file(n).json(),o=z.fromJson(i,n);t.set(o.name,o)}}return t}}var Ap={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch",[Qe]:"patch"};class st{config;stoneManager;constructor(e){this.config=e;this.stoneManager=new O(e)}async analyze(e={}){let t=await this.getCommitsSinceLastRelease();if(t.length===0)return[];let r=this.config.get("commits")?.skip??Ue.commits.skip;if(t=t.filter((n)=>!this.shouldSkipCommit(n,r)),t.length===0)return[];let s=await this.stoneManager.getTrackedCommitPackages();return this.groupByPackage(t,e,s)}shouldSkipCommit(e,t){if(t.authors.includes(e.author))return!0;for(let r of t.messagePatterns)try{if(new RegExp(r,"i").test(e.subject))return!0}catch{v.warn(m.yellow(`Invalid regex pattern in commits.skip.messagePatterns: "${r}"`))}return!1}async getCommitsSinceLastRelease(){let t=this.config.get("lastStone")?.commit||void 0;if(!t)return[];return Y.since(t)}async groupByPackage(e,t,r){let{packages:s,packageNames:n}=await G.scan({filter:t.filter,single:t.single}),i=this.config.get("ignore")??[],o=new Set(n.filter((p)=>!ee(p,i))),a=new Map([...s].filter(([p])=>o.has(p))),c=Kr(a),l=new Map;for(let p of e){let d=Yt(p.files,c);for(let y of r.get(p.shortHash)??[])d.delete(y);if(d.size===0)continue;let h=p.breaking?"major":Ap[p.type]||"patch",f=`${p.type}${p.breaking?"!":""}`,g=l.get(f);if(!g){let y=this.getGroupMessage(p);g={bump:h,commits:[],message:y,packages:new Set},l.set(f,g)}g.commits.push(p.toInfo([...d]));for(let y of d)g.packages.add(y)}return Array.from(l.entries()).sort(([p],[d])=>(yt[p]??wt)-(yt[d]??wt)).map(([,p])=>p)}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,r){let s=Array.from(e.packages),n=s.map((i)=>({bump:e.bump,name:i}));return{[e.bump]:s,commits:K(e.commits),dependency:K(St(n,t,r)),message:e.message,tag:r.tag}}}import{readFile as Op,writeFile as ba}from"fs/promises";class Qt{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 ba(e,t,"utf-8");this.originals.clear()}async updatePackage(e){let t=e.newVersion;if(!t)return;qr(t,`write the new version of ${e.name}`);let r=await Op(e.file,"utf-8");this.originals.set(e.file,r),await ba(e.file,Ht(r,{...JSON.parse(r),version:t}),"utf-8")}}var _p=/^[\t ]+/m,Lp=new Set(["*","^","~"]);class Ge extends Error{hint;_tag="PublishManifestError";constructor(e,t){super(e);this.hint=t}}function va(e){let t=Array.isArray(e.workspaces)?void 0:e.workspaces;return{["default"]:{...e.catalog,...t?.catalog},...e.catalogs,...t?.catalogs}}function Mp(e,t,r,s){let n=t.slice(8)||"default",i=Object.hasOwn(r,n)?r[n]:void 0,o=i&&Object.hasOwn(i,e)?i[e]:void 0;if(!o)throw new Ge(`Catalog "${n}" has no entry for "${e}" (required by ${s})`,"Add the entry to the root package.json catalog before publishing");return o}function Dp(e,t,r,s){let n=t.slice(10),i=Object.hasOwn(r,e)?r[e]:void 0;if(!i)throw new Ge(`Workspace package "${e}" (required by ${s}) was not found in the workspace`,"Check the dependency name against your workspaces globs");if(i.isPrivate)throw new Ge(`"${s}" depends on private workspace package "${e}", which is not published to the registry`,`Move "${e}" to devDependencies (bundled CLIs do not need it at runtime) or publish it first`);if(!Lp.has(n)){if(!n)throw new Ge(`Invalid workspace specifier "${t}" for "${e}" (required by ${s})`,"Use workspace:*, workspace:^, workspace:~, or workspace:<range>");return n}let o=i.version;if(!o)throw new Ge(`Workspace package "${e}" (required by ${s}) has no version in its package.json`,"Add a version field before publishing");return n==="*"?o:`${n}${o}`}function fn(e,t,r,s){if(!e)return e;return Object.fromEntries(Object.entries(e).map(([n,i])=>{if(i.startsWith("catalog:"))return[n,Mp(n,i,t,s)];if(i.startsWith("workspace:"))return[n,Dp(n,i,r,s)];return[n,i]}))}function Np(e,t,r){let{devDependencies:s,...n}=e;return{...n,dependencies:fn(e.dependencies,t,r,e.name),optionalDependencies:fn(e.optionalDependencies,t,r,e.name),peerDependencies:fn(e.peerDependencies,t,r,e.name)}}function $a(e,t,r){let s=JSON.parse(e),n=Np(s,t,r),i=e.match(_p)?.[0]??2;return`${JSON.stringify(n,null,i)}
|
|
159
|
-
`}function
|
|
160
|
-
`).filter(Boolean).length}catch{return 1}}inferCommitType(e){return e.match(/^(\w+)(?:\(.*?\))?!?:/)?.[1]??Qe}async getProvider(){if(!this.provider)this.provider=await vt();return this.provider}async fetchFromCurrentBranch(e){let t=await e.getPrFromCurrentBranch();return this.mapPullRequest(t)}async fetchFromUrl(e,t){let r=Vo(t);if(!r)throw new u("Invalid PR URL","Expected a PR/MR URL from GitHub, GitLab, or Bitbucket");if(r.provider!==e.name)throw new u(`PR URL is from ${r.provider}, but repository is on ${e.name}`,"Make sure the PR URL matches the repository provider");let s=et(await Wt()??"");if(!s||s.owner.toLowerCase()!==r.owner.toLowerCase()||s.repo.toLowerCase()!==r.repo.toLowerCase())throw new u("PR URL does not match this repository","Use a PR/MR URL from the repository configured as origin");let n=await e.getPr(r.number);return this.mapPullRequest(n)}mapPullRequest({headBranch:e,...t}){return{...t,branch:e}}inferBumpFromLabels(e){let t=this.config.get("pr").labelMapping;for(let r of e){let s=r.toLowerCase();for(let[n,i]of Object.entries(t))if(s===n.toLowerCase())return i}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}}import{mkdtemp as Td,readFile as Ed,rm as qc}from"fs/promises";import{tmpdir as Id}from"os";import{dirname as Wc,join as ui,resolve as Ad}from"path";var Sa=So().map((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:de()),Fp=Sa.map(Zs({publishConfig:Sa.map(Zs({access:Co(["public","restricted"]).or(Ut())})).or(Ut())}));function Xr(e){try{return Fp(JSON.parse(e)).publishConfig?.access??"public"}catch(t){throw Error("Invalid publishConfig.access: expected public or restricted",{cause:t})}}import{rm as am}from"fs/promises";import{isAbsolute as cm,resolve as Ua}from"path";import{createHash as Zr}from"crypto";import{constants as Ca}from"fs";import{lstat as Bp,open as Vp,readlink as xa}from"fs/promises";import{isAbsolute as Up,relative as wn,resolve as Le,sep as bn}from"path";var vn=new Set(["100644","100755"]),kt="120000",er="160000",Ta=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;async function es(e){let t=await Bun.$`git rev-parse --show-toplevel`.quiet(),r=Le(t.stdout.toString().trim()),s=Le(r,e),n=wn(r,s);if(!n||oe(n))throw new u("Sisyphus directory is outside the repository","Use a repository-relative sisyphusDir");let i=n.split(bn).join("/"),o=await Gp(r,i),a=Zr("sha256");for(let c of o){if(c.kind==="tracked"&&!Hp(c.mode))throw new u(`Release source has unsupported Git mode ${c.mode}: ${c.path}`);let l=await Aa(r,c.path),p=await Pn(l);if(a.update(c.path),a.update("\x00"),a.update(c.kind),a.update("\x00"),!p){if(c.kind==="tracked"&&c.mode===er)throw new u(`Release source gitlink is not initialized: ${c.path}`);a.update("deleted")}else if(c.kind==="untracked"||vn.has(c.mode)){if(!p.isFile()||p.isSymbolicLink())throw new u(`Release source path is not a regular file: ${c.path}`);await qp(a,l,c.path)}else if(c.mode===kt){if(!p.isSymbolicLink())throw new u(`Release source path does not match Git mode ${kt}: ${c.path}`);a.update(Zr("sha256").update(await xa(l,{encoding:"buffer"})).digest("hex")),a.update(kt)}else{if(!p.isDirectory()||p.isSymbolicLink())throw new u(`Release source path does not match Git mode ${er}: ${c.path}`);a.update(await _a(r,l,c)),await $n(l),a.update(er)}a.update("\x00")}return a.digest("hex")}async function $n(e=process.cwd()){let t=await Bun.$`git rev-parse --show-toplevel`.cwd(e).quiet(),r=Le(t.stdout.toString().trim());await Ea(r)}async function Ea(e){let[t,r]=await Promise.all([Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),Bun.$`git ls-files -v -z --cached`.cwd(e).quiet()]),s=new Set,n=new Map;for(let i of Qr(r.stdout)){let o=i.slice(0,1),a=i.slice(2);if(!o||i.slice(1,2)!==" "||!a)throw new u("Unable to parse Git index flags while validating release source");n.set(a,o)}for(let i of Qr(t.stdout)){let o=Ia(i);if(o.stage!=="0")throw new u(`Release source has an unresolved index entry: ${o.path}`);if(s.has(o.path))throw new u(`Release source has duplicate index entries: ${o.path}`);if(s.add(o.path),n.get(o.path)!=="H")throw new u(`Release source index flags hide working tree changes: ${o.path}`);let a={kind:"tracked",mode:o.mode,objectId:o.objectId,path:o.path},c=await Aa(e,o.path),l=await Pn(c);if(!l)throw new u(`Release source path is missing: ${o.path}`);if(vn.has(o.mode)){if(!l.isFile()||l.isSymbolicLink())throw new u(`Release source path is not a regular file: ${o.path}`);let d=(await Bun.$`git hash-object ${`--path=${o.path}`} ${c}`.cwd(e).quiet()).stdout.toString().trim(),h=l.mode&73?"100755":"100644";if(d!==o.objectId||h!==o.mode)throw new u(`Release source path differs from the Git index: ${o.path}`);continue}if(o.mode===kt){if(!l.isSymbolicLink())throw new u(`Release source path does not match Git mode ${kt}: ${o.path}`);let p=await Bun.$`git cat-file blob ${o.objectId}`.cwd(e).quiet(),d=await xa(c,{encoding:"buffer"});if(!Buffer.from(p.stdout).equals(d))throw new u(`Release source symlink differs from the Git index: ${o.path}`);continue}if(o.mode!==er)throw new u(`Release source has unsupported Git mode ${o.mode}: ${o.path}`);if(!l.isDirectory()||l.isSymbolicLink())throw new u(`Release source gitlink is not initialized: ${o.path}`);await _a(e,c,a),await Ea(c)}}function ts(e,t){return Zr("sha256").update(JSON.stringify(xt({...e,stones:t}))).digest("hex")}function xt(e){if(Array.isArray(e))return e.map(xt);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>[t,xt(r)]))}function oe(e){return e===".."||e.startsWith(`..${bn}`)||Up(e)}async function Gp(e,t){let[r,s]=await Promise.all([Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),Bun.$`git ls-files -z --others --exclude-standard`.cwd(e).quiet()]),n=[],i=new Set;for(let o of Qr(r.stdout)){let a=Ia(o);if(ka(a.path,t))continue;if(a.stage!=="0")throw new u(`Release source has an unresolved index entry: ${a.path}`);if(i.has(a.path))throw new u(`Release source has duplicate index entries: ${a.path}`);i.add(a.path),n.push({kind:"tracked",mode:a.mode,objectId:a.objectId,path:a.path})}for(let o of Qr(s.stdout)){if(ka(o,t))continue;if(i.has(o))throw new u(`Release source path is both tracked and untracked: ${o}`);i.add(o),n.push({kind:"untracked",path:o})}return n.sort((o,a)=>o.path<a.path?-1:o.path>a.path?1:0)}function Qr(e){let t=e.toString();if(!Buffer.from(t).equals(e))throw new u("Release source contains paths that are not valid UTF-8");return t.split("\x00").filter(Boolean)}function Ia(e){let t=e.indexOf("\t");if(t<0)throw new u("Unable to parse Git index entry while hashing release source");let[r,s,n,...i]=e.slice(0,t).split(" "),o=e.slice(t+1);if(!r||!/^[0-7]{6}$/.test(r)||!s||!Ta.test(s)||!n||i.length>0||!o)throw new u("Unable to parse Git index entry while hashing release source");return{mode:r,objectId:s,path:o,stage:n}}function ka(e,t){return e===t||e.startsWith(`${t}/`)}function Hp(e){return vn.has(e)||e===kt||e===er}async function Aa(e,t){let r=t.split("/"),s=Le(e,t),n=wn(e,s);if(r.some((o)=>!o||o==="."||o==="..")||oe(n)||n.split(bn).join("/")!==t)throw new u(`Release source path escapes the repository: ${t}`);let i=e;for(let o of r.slice(0,-1)){i=Le(i,o);let a=await Pn(i);if(!a)break;if(!a.isDirectory()||a.isSymbolicLink())throw new u(`Release source path has an unsafe parent: ${t}`)}return s}async function Pn(e){try{return await Bp(e)}catch(t){if(Oa(t,"ENOENT"))return null;throw t}}function Oa(e,t){return e instanceof Error&&"code"in e&&e.code===t}async function qp(e,t,r){let s=await Vp(t,Ca.O_RDONLY|Ca.O_NOFOLLOW).catch((n)=>{if(Oa(n,"ELOOP"))throw new u(`Release source path is not a regular file: ${r}`);throw n});try{let n=await s.stat();if(!n.isFile())throw new u(`Release source path is not a regular file: ${r}`);e.update(Zr("sha256").update(await s.readFile()).digest("hex")),e.update(n.mode&73?"100755":"100644")}finally{await s.close()}}async function _a(e,t,r){let[s,n,i,o]=await Promise.all([Bun.$`git rev-parse --show-toplevel`.cwd(t).quiet(),Bun.$`git rev-parse --show-superproject-working-tree`.cwd(t).quiet(),Bun.$`git rev-parse --absolute-git-dir`.cwd(t).quiet(),Bun.$`git rev-parse --git-path modules`.cwd(e).quiet()]),a=Le(s.stdout.toString().trim()),c=n.stdout.toString().trim(),l=c?Le(c):null,p=Le(i.stdout.toString().trim()),d=Le(e,o.stdout.toString().trim()),h=wn(d,p);if(a!==t||l!==e||!h||oe(h))throw new u(`Release source gitlink is not initialized: ${r.path}`);if((await Bun.$`git status --porcelain=v1 -z --untracked-files=all --ignore-submodules=none`.cwd(t).quiet()).stdout.byteLength>0)throw new u(`Release source gitlink is dirty: ${r.path}`,"Commit or discard submodule changes before releasing");let y=(await Bun.$`git rev-parse --verify HEAD`.cwd(t).quiet()).stdout.toString().trim();if(!Ta.test(y))throw new u(`Release source gitlink has an invalid object ID: ${r.path}`);if(y!==r.objectId)throw new u(`Release source gitlink does not match the recorded commit: ${r.path}`,"Check out the submodule commit recorded by the repository before releasing");return r.objectId}var nt={isOutput:()=>!1};function La(e){if(e.length===0)return nt;let t=e.flatMap((r)=>{let s=r.endsWith("/")?`${r}**`:r;if(s.endsWith("**"))return[new Bun.Glob(s)];return[new Bun.Glob(s),new Bun.Glob(`${s}/**`)]});return{isOutput:(r)=>t.some((s)=>s.match(r))}}import{cp as Wp,mkdir as Jp,mkdtemp as zp,rename as Kp,rm as Yp,writeFile as Xp}from"fs/promises";import{tmpdir as Zp}from"os";import{dirname as Da,join as Ma,relative as Cn,resolve as He,sep as Qp}from"path";function Rn(e){let t=JSON.parse(e),r=Array.isArray(t)?t:typeof t==="object"&&t!==null?Object.values(t):[],[s]=r;return typeof s==="object"&&s!==null&&!Array.isArray(s)?s:void 0}var rs=512,em=100,tm=124,rm=12,sm=345,nm=155,im="package/package.json",om=20;async function Na(e,t){let r=Da(t),s=await Bun.$`npm pack --ignore-scripts --json --pack-destination ${r}`.cwd(e).quiet(),n=Rn(s.stdout.toString());if(typeof n?.filename!=="string"||!n.filename||typeof n.name!=="string"||!n.name||typeof n.version!=="string"||!n.version)throw Error("npm pack did not return a valid artifact identity");let i=He(r,n.filename);if(oe(Cn(r,i)))throw Error("npm pack returned an artifact outside the destination directory");if(i!==He(t))await Kp(i,t);return{name:n.name,version:n.version}}async function ja(e,t){let r=await Bun.$`npm pack --dry-run --ignore-scripts --json`.cwd(t).quiet(),s=Rn(r.stdout.toString())?.files;if(!Array.isArray(s))throw Error(`npm pack did not return a file list for ${e.name}`);return s.map((n)=>{if(typeof n!=="object"||n===null||Array.isArray(n)||!("path"in n))throw Error(`npm pack returned an invalid file entry for ${e.name}`);let i=n.path;if(typeof i!=="string"||!i)throw Error(`npm pack returned an invalid file path for ${e.name}`);if(oe(Cn(t,He(t,i))))throw new u(`Package ${e.name} includes a file outside its directory: ${i}`);return i})}async function Fa(e,t,r){let s=await ja(e,t),n=await zp(Ma(Zp(),"sisyphus-package-stage-"));try{for(let i of s){let o=He(n,i);await Jp(Da(o),{recursive:!0}),await Wp(He(t,i),o,{errorOnExist:!0,force:!1,recursive:!1,verbatimSymlinks:!0})}return await Xp(Ma(n,"package.json"),r,"utf-8"),n}catch(i){try{await Yp(n,{force:!0,recursive:!0})}catch(o){throw AggregateError([i,o],"Failed to clean staged npm package")}throw i}}async function Ba(e,t,r,s=nt){let[n,i]=await Promise.all([ja(e,t),ns(r)]);for(let o of n){let a=Cn(r,He(t,o)).split(Qp).join("/");if(!i.has(a)&&!s.isOutput(a))throw new u(`Package ${e.name} includes an untracked or ignored pre-build file: ${o}`)}}async function kn(e,t){return(await Bun.$`git ls-files --others --ignored --exclude-standard -z`.cwd(e).quiet()).stdout.toString().split("\x00").filter(Boolean).filter((s)=>!s.split("/").includes("node_modules")).map((s)=>`${t}${s}`)}async function xn(e,t,r=nt){let[s,n]=await Promise.all([kn(e,t),Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet()]),i=s.filter((o)=>!r.isOutput(o));if(i.length>0){let o=i.slice(0,om),a=i.length-o.length;throw new u(`Repository contains ${i.length} ignored build input(s) outside node_modules`,`Remove ignored source and stale build outputs before preparing npm artifacts (preview with git clean -ndX):
|
|
158
|
+
`).trim()||void 0,major:K(t),message:o,minor:K(r),patch:K(s)}}}function Kr(e){let t=new Map;for(let[r,s]of e){let n=s.file.replace(/\\/g,"/"),i=n.substring(0,n.lastIndexOf("/"))||".";t.set(i,r)}return t}function Yt(e,t,r=!0){let s=new Set;for(let n of e)for(let[i,o]of t){let a=i===".",c=n.startsWith(`${i}/`);if(a?r:c)s.add(o)}return s}var ua="*",pa="^",gn="~",ca=new Map;function ee(e,t){return t.some((r)=>r===e||Lp(e,r))}function ce(e,t){let r=e.get("dependents")??Ue.dependents;return{ignore:e.get("ignore")??[],kinds:r.kinds,tag:t,updateInternal:r.updateInternal}}function Tp(e,t,r){let s=e.slice(zr.length);if(s===ua)return t!==r;if(s!==pa&&s!==gn)return!1;let n=Ae(t),i=Ae(r);if(!n||!i)return!0;if(Oe(n)||Oe(i))return!0;if(n.major!==i.major)return!0;if(s===gn)return n.minor!==i.minor;if(n.major!==0)return!1;if(n.minor!==0)return n.minor!==i.minor;return n.minor!==i.minor||n.patch!==i.patch}function St(e,t,r){let s=r.ignore??[],n=Op(t,new Set(r.kinds),s),i=new Map,o=new Set,a=[];for(let c of[...e].sort((l,p)=>Rt(l.name,p.name))){if(!t.has(c.name)||ee(c.name,s))continue;if(o.add(c.name),la(i,c.name,c.bump))Yr(a,c.name)}while(a.length>0){let c=a.shift();if(!c)continue;let l=t.get(c),p=i.get(c),m=n.get(c);if(!l||!p||!m)continue;let h=r.updateInternal==="outOfRange",f=Ae(l.version),g=f!==null&&Oe(f),y=h&&!g?fe.bump(l.version,p,r.tag):l.version;for(let R of m){let S=g?Ep(R.specifier):Tp(R.specifier,l.version,y);if(h&&!S)continue;if(la(i,R.dependent,"dependency"))Yr(a,R.dependent)}}return[...i.keys()].filter((c)=>!o.has(c)).sort(Rt)}function Ep(e){let t=e.slice(zr.length);return t===ua||t===pa||t===gn}function hn(e,t){if(t.length===0)return{skipped:[],stone:e};let r=[],s=e;for(let n of Ie){let i=e.getPackages(n),o=i.filter((a)=>!ee(a,t));if(o.length===i.length)continue;r.push(...i.filter((a)=>!o.includes(a))),s=s.withPackages(n,o)}return{skipped:[...new Set(r)].sort(Rt),stone:s}}function da(e,t){if(t.length===0)return{kept:[...e],skipped:[]};let r=[],s=[];for(let n of e)if(ee(n.name,t))s.push(n.name);else r.push(n);return{kept:r,skipped:s}}function Xt(e){let t=new Map(e.map((p)=>[p.name,p])),r=[...t.keys()].sort(Rt),s=new Map,n=new Map,i=new Map;for(let p of r){let m=new Set((t.get(p)?.workspaceDependencies??[]).filter((h)=>h.kind!=="devDependencies").map((h)=>h.name).filter((h)=>h!==p&&t.has(h)));s.set(p,m.size),i.set(p,m);for(let h of m)n.set(h,[...n.get(h)??[],p])}let o=r.filter((p)=>s.get(p)===0),a=[],c=new Set,l=[];while(c.size<r.length){if(o.length===0){let h=Ip(r,c,n,i);if(!h)break;l.push(h),Yr(o,h)}let p=o.shift();if(!p||c.has(p))continue;c.add(p);let m=t.get(p);if(m)a.push(m);for(let h of n.get(p)??[]){if(c.has(h))continue;let f=(s.get(h)??0)-1;if(s.set(h,f),f===0)Yr(o,h)}}return{cycle:l,ordered:a}}function Ip(e,t,r,s){let n=Ap(e,t,s),i=n.size>0?e.filter((c)=>n.has(c)):e,o,a=-1;for(let c of i){if(t.has(c))continue;let l=(r.get(c)??[]).filter((p)=>!t.has(p)).length;if(l<=a)continue;o=c,a=l}return o}function Ap(e,t,r){let s=new Map,n=new Map,i=[],o=new Set,a=new Set,c=(l)=>{let p=s.size;s.set(l,p),n.set(l,p),i.push(l),o.add(l);for(let g of r.get(l)??[]){if(t.has(g))continue;if(!s.has(g))c(g),n.set(l,Math.min(n.get(l)??p,n.get(g)??p));else if(o.has(g))n.set(l,Math.min(n.get(l)??p,s.get(g)??p))}if(n.get(l)!==p)return;let m=new Set,h;do{if(h=i.pop(),h===void 0)break;o.delete(h),m.add(h)}while(h!==l);if([...m].some((g)=>[...r.get(g)??[]].some((y)=>!t.has(y)&&!m.has(y))))return;for(let g of m)a.add(g)};for(let l of e)if(!t.has(l)&&!s.has(l))c(l);return a}function Op(e,t,r){let s=new Map;for(let n of[...e.keys()].sort(Rt)){if(ee(n,r))continue;for(let i of e.get(n)?.workspaceDependencies??[]){if(!_p(i,t,e,r))continue;s.set(i.name,[...s.get(i.name)??[],{dependent:n,specifier:i.specifier}])}}return s}function _p(e,t,r,s){if(!t.has(e.kind))return!1;if(!r.has(e.name))return!1;return!ee(e.name,s)}function la(e,t,r){let s=e.get(t),n=s===void 0?r:Hr(s,r);if(s!==void 0&&n===s)return!1;return e.set(t,n),!0}function Yr(e,t){if(e.includes(t))return;let r=e.findIndex((s)=>Rt(s,t)>0);if(r<0)e.push(t);else e.splice(r,0,t)}function Rt(e,t){if(e===t)return 0;return e<t?-1:1}function Lp(e,t){let r=ca.get(t);if(!r)r=new Bun.Glob(t),ca.set(t,r);return r.match(e)}import{existsSync as Ct}from"fs";import{mkdir as ma,readdir as fn,readFile as ga,unlink as ha,writeFile as fa}from"fs/promises";import{dirname as Mp,join as Zt,resolve as ya}from"path";var wa=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,ba=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/;class O{config;constructor(e){this.config=e}get sisyphusDir(){return this.config.get("sisyphusDir")||bt}get stonesPath(){return this.config.get("stonesPath")||Zt(this.sisyphusDir,Ao)}get releasedPath(){return Zt(this.sisyphusDir,Oo)}async list(){let e=await this.listIds(),t=[];for(let r of e){let s=await this.get(r);if(s)t.push(s)}return t}async listIds(){return await this.ensureStorageExists(),(await fn(this.stonesPath)).filter((t)=>t.endsWith(".json")).map((t)=>this.toStoneId(t)).sort()}async get(e){let t=this.getFilePath(e);if(!Ct(t))return null;let r=await ga(t,"utf-8"),s=this.parseStoneJson(r,t);if(s.id!==e)throw Error(`Stone file ID mismatch: expected "${e}", found "${String(s.id)}"`);return M.fromJson(s)}parseStoneJson(e,t){try{return JSON.parse(e)}catch{throw new u(`Failed to parse stone file ${t}`,"Remove or fix the file")}}async save(e){await this.ensureStorageExists();let t=this.getFilePath(e.id),r=JSON.stringify(e.toJson(),null,2);await fa(t,r,"utf-8"),this.addToConfigStones(e.id)}async delete(e){let t=this.getFilePath(e);if(!Ct(t))return!1;return await ha(t),this.removeFromConfigStones(e),!0}async deleteMany(e){let t=0;for(let r of e)if(await this.delete(r))t++;return t}async create(e){let t=await this.listIds(),r=M.create(e,t.length);return await this.save(r),r}async archive(e){if(e.length===0)return"";let t=this.createTimestamp(),r=Zt(this.releasedPath,t);await ma(r,{recursive:!0});for(let s of e){let n=this.getFilePath(s.id),i=Zt(r,`${s.id}.json`);if(Ct(n))await fa(i,JSON.stringify(s.toJson(),null,2),"utf-8"),await ha(n),this.removeFromConfigStones(s.id)}return t}async getReleasedStones(e,t){let r=this.getArchivePath(e);if(!Ct(r))return[];let n=(await fn(r)).filter((a)=>a.endsWith(".json")).sort(),i=t?.map((a)=>`${this.validateId(a)}.json`).sort();if(i&&JSON.stringify(n)!==JSON.stringify(i))throw Error(`Released stone archive ${e} does not match currentRelease: expected ${i.join(", ")||"no stones"}, found ${n.join(", ")||"no stones"}`);let o=[];for(let a of n)try{let c=this.validateId(a.slice(0,-5)),l=Zt(r,a),p=await ga(l,"utf-8"),m=this.parseStoneJson(p,l);if(m.id!==c)throw Error(`Stone file ID mismatch: expected "${c}", found "${String(m.id)}"`);o.push(M.fromJson(m))}catch(c){if(t)throw c;v.warn(d.dim(`Failed to parse stone "${a}": ${c}`))}return o}async listReleasedTimestamps(){if(!Ct(this.releasedPath))return[];return(await fn(this.releasedPath,{withFileTypes:!0})).filter((t)=>t.isDirectory()&&ba.test(t.name)).map((t)=>t.name)}async getTrackedCommitPackages(){let e=await this.list(),t=new Map;for(let r of e.flatMap((s)=>s.commits??[])){let s=t.get(r.hash)??new Set;for(let n of r.packages)s.add(n);t.set(r.hash,s)}return t}getFilePath(e){let t=this.validateId(e);return this.resolveChildPath(this.stonesPath,`${t}.json`,`Stone path must be a direct child of the stones directory: ${e}`)}getFilePaths(e){return e.map((t)=>this.getFilePath(t.id))}createTimestamp(){return new Date().toISOString().replace(/[:.]/g,"-")}getArchivePath(e){if(!ba.test(e))throw Error(`Invalid released stone timestamp "${e}"`);return this.resolveChildPath(this.releasedPath,e,`Released stone archive must be a direct child of the released directory: ${e}`)}resolveChildPath(e,t,r){let s=ya(e),n=ya(s,t);if(Mp(n)!==s)throw Error(r);return n}validateId(e){if(!wa.test(e))throw Error(`Invalid stone ID "${e}"`);return e}toStoneId(e){let t=e.slice(0,-5);if(wa.test(t))return t;throw new u(`Invalid stone ID "${t}" from stone file ${e} in ${this.stonesPath}`,"Remove or rename the file; stone files must match <seq>-<hash>.json")}async ensureStorageExists(){if(!Ct(this.stonesPath))await ma(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(),r=t.stones.filter((s)=>s!==e);if(r.length!==t.stones.length)this.config.set("stones",r)}}class G{static async scan(e={}){let{filter:t,single:r}=e;if(r)return G.scanRootPackage(t);let s=await G.getWorkspaces();G.validateWorkspaces(s);let n=await G.scanWorkspaces(s);return{packageNames:G.filterNames(Array.from(n.keys()),t),packages:n}}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 u("Could not read package.json","Ensure you're in a project root directory.")}}static validateWorkspaces(e){if(e.length===0)throw new u("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((r)=>r.includes(t))}static async scanRootPackage(e){let t=await Bun.file("package.json").json(),r=z.fromJson(t,"package.json"),s=new Map;return s.set(r.name,r),{packageNames:G.filterNames([r.name],e),packages:s}}static async scanWorkspaces(e){let t=new Map;for(let r of e){let s=new Bun.Glob(`${r}/package.json`).scanSync({cwd:process.cwd()});for(let n of s){let i=await Bun.file(n).json(),o=z.fromJson(i,n);t.set(o.name,o)}}return t}}var Dp={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch",[Qe]:"patch"};class st{config;stoneManager;constructor(e){this.config=e;this.stoneManager=new O(e)}async analyze(e={}){let t=await this.getCommitsSinceLastRelease();if(t.length===0)return[];let r=this.config.get("commits")?.skip??Ue.commits.skip;if(t=t.filter((n)=>!this.shouldSkipCommit(n,r)),t.length===0)return[];let s=await this.stoneManager.getTrackedCommitPackages();return this.groupByPackage(t,e,s)}shouldSkipCommit(e,t){if(t.authors.includes(e.author))return!0;for(let r of t.messagePatterns)try{if(new RegExp(r,"i").test(e.subject))return!0}catch{v.warn(d.yellow(`Invalid regex pattern in commits.skip.messagePatterns: "${r}"`))}return!1}async getCommitsSinceLastRelease(){let t=this.config.get("lastStone")?.commit||void 0;if(!t)return[];return Y.since(t)}async groupByPackage(e,t,r){let{packages:s,packageNames:n}=await G.scan({filter:t.filter,single:t.single}),i=this.config.get("ignore")??[],o=new Set(n.filter((p)=>!ee(p,i))),a=new Map([...s].filter(([p])=>o.has(p))),c=Kr(a),l=new Map;for(let p of e){let m=Yt(p.files,c);for(let y of r.get(p.shortHash)??[])m.delete(y);if(m.size===0)continue;let h=p.breaking?"major":Dp[p.type]||"patch",f=`${p.type}${p.breaking?"!":""}`,g=l.get(f);if(!g){let y=this.getGroupMessage(p);g={bump:h,commits:[],message:y,packages:new Set},l.set(f,g)}g.commits.push(p.toInfo([...m]));for(let y of m)g.packages.add(y)}return Array.from(l.entries()).sort(([p],[m])=>(yt[p]??wt)-(yt[m]??wt)).map(([,p])=>p)}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,r){let s=Array.from(e.packages),n=s.map((i)=>({bump:e.bump,name:i}));return{[e.bump]:s,commits:K(e.commits),dependency:K(St(n,t,r)),message:e.message,tag:r.tag}}}import{readFile as Np,writeFile as va}from"fs/promises";class Qt{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 va(e,t,"utf-8");this.originals.clear()}async updatePackage(e){let t=e.newVersion;if(!t)return;qr(t,`write the new version of ${e.name}`);let r=await Np(e.file,"utf-8");this.originals.set(e.file,r),await va(e.file,Ht(r,{...JSON.parse(r),version:t}),"utf-8")}}var jp=/^[\t ]+/m,Fp=new Set(["*","^","~"]);class Ge extends Error{hint;_tag="PublishManifestError";constructor(e,t){super(e);this.hint=t}}function $a(e){let t=Array.isArray(e.workspaces)?void 0:e.workspaces;return{["default"]:{...e.catalog,...t?.catalog},...e.catalogs,...t?.catalogs}}function Bp(e,t,r,s){let n=t.slice(8)||"default",i=Object.hasOwn(r,n)?r[n]:void 0,o=i&&Object.hasOwn(i,e)?i[e]:void 0;if(!o)throw new Ge(`Catalog "${n}" has no entry for "${e}" (required by ${s})`,"Add the entry to the root package.json catalog before publishing");return o}function Vp(e,t,r,s){let n=t.slice(10),i=Object.hasOwn(r,e)?r[e]:void 0;if(!i)throw new Ge(`Workspace package "${e}" (required by ${s}) was not found in the workspace`,"Check the dependency name against your workspaces globs");if(i.isPrivate)throw new Ge(`"${s}" depends on private workspace package "${e}", which is not published to the registry`,`Move "${e}" to devDependencies (bundled CLIs do not need it at runtime) or publish it first`);if(!Fp.has(n)){if(!n)throw new Ge(`Invalid workspace specifier "${t}" for "${e}" (required by ${s})`,"Use workspace:*, workspace:^, workspace:~, or workspace:<range>");return n}let o=i.version;if(!o)throw new Ge(`Workspace package "${e}" (required by ${s}) has no version in its package.json`,"Add a version field before publishing");return n==="*"?o:`${n}${o}`}function yn(e,t,r,s){if(!e)return e;return Object.fromEntries(Object.entries(e).map(([n,i])=>{if(i.startsWith("catalog:"))return[n,Bp(n,i,t,s)];if(i.startsWith("workspace:"))return[n,Vp(n,i,r,s)];return[n,i]}))}function Up(e,t,r){let{devDependencies:s,...n}=e;return{...n,dependencies:yn(e.dependencies,t,r,e.name),optionalDependencies:yn(e.optionalDependencies,t,r,e.name),peerDependencies:yn(e.peerDependencies,t,r,e.name)}}function Pa(e,t,r){let s=JSON.parse(e),n=Up(s,t,r),i=e.match(jp)?.[0]??2;return`${JSON.stringify(n,null,i)}
|
|
159
|
+
`}function Ra(e){return Object.fromEntries(Array.from(e,(t)=>[t.name,{isPrivate:t.isPrivate,version:t.version||null}]))}function Sa(e,t,r){try{return Pa(e,t,r)}catch(s){throw s instanceof Ge?new u(s.message,s.hint):s}}class wn{config;provider=null;constructor(e){this.config=e}async analyze(e){let t=await this.getProvider(),r=e?await this.fetchFromUrl(t,e):await this.fetchFromCurrentBranch(t),s=this.config.get("single"),{packages:n}=await G.scan({single:s}),i=Kr(n),o={isSinglePackage:s,packagePaths:i,provider:t},{commits:a,affectedPackages:c}=r.merged?await this.analyzeAfterMerge(r,o):await this.analyzeBeforeMerge(r,o),l=this.inferBumpFromLabels(r.labels)??this.inferBumpFromTitle(r.title);return{commits:a,packages:c,pr:r,suggestedBump:l}}async analyzeBeforeMerge(e,t){let r=await Y.inRange(e.baseBranch,e.branch);return this.processCommits(r,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 r=await t.provider.getPrCommits(e.number);if(e.mergeCommitSha&&r.includes(e.mergeCommitSha)){let o=await Promise.all(r.map((a)=>Y.fromHash(a)));if(o.every((a)=>a!==null))return this.processCommits(o,t)}let s=await t.provider.getPrFiles(e.number);if(s.length===0)throw new u(`Could not determine changed files for PR #${e.number}`,"Check provider access and retry the analysis");let n=Yt(s,t.packagePaths,t.isSinglePackage),i={body:e.body||void 0,hash:e.mergeCommitSha?.slice(0,Nr)??_o,message:e.title,packages:[...n],subject:e.title,type:this.inferCommitType(e.title)};return{affectedPackages:n,commits:[i]}}async analyzeMergeCommit(e,t){if(!e.mergeCommitSha)return{affectedPackages:new Set,commits:[]};let r=await Y.fromMerge(e.mergeCommitSha);return this.processCommits(r,t)}processCommits(e,t){let r=[],s=new Set;for(let n of e){let i=Yt(n.files,t.packagePaths,t.isSinglePackage);if(i.size===0)continue;r.push(n.toInfo([...i]));for(let o of i)s.add(o)}return{affectedPackages:s,commits:r}}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(`
|
|
160
|
+
`).filter(Boolean).length}catch{return 1}}inferCommitType(e){return e.match(/^(\w+)(?:\(.*?\))?!?:/)?.[1]??Qe}async getProvider(){if(!this.provider)this.provider=await vt();return this.provider}async fetchFromCurrentBranch(e){let t=await e.getPrFromCurrentBranch();return this.mapPullRequest(t)}async fetchFromUrl(e,t){let r=Uo(t);if(!r)throw new u("Invalid PR URL","Expected a PR/MR URL from GitHub, GitLab, or Bitbucket");if(r.provider!==e.name)throw new u(`PR URL is from ${r.provider}, but repository is on ${e.name}`,"Make sure the PR URL matches the repository provider");let s=et(await Wt()??"");if(!s||s.owner.toLowerCase()!==r.owner.toLowerCase()||s.repo.toLowerCase()!==r.repo.toLowerCase())throw new u("PR URL does not match this repository","Use a PR/MR URL from the repository configured as origin");let n=await e.getPr(r.number);return this.mapPullRequest(n)}mapPullRequest({headBranch:e,...t}){return{...t,branch:e}}inferBumpFromLabels(e){let t=this.config.get("pr").labelMapping;for(let r of e){let s=r.toLowerCase();for(let[n,i]of Object.entries(t))if(s===n.toLowerCase())return i}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}}import{mkdtemp as _m,readFile as Lm,rm as Wc}from"fs/promises";import{tmpdir as Mm}from"os";import{dirname as Jc,join as pi,resolve as Dm}from"path";var Ca=Co().map((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:me()),Hp=Ca.map(Qs({publishConfig:Ca.map(Qs({access:ko(["public","restricted"]).or(Ut())})).or(Ut())}));function Xr(e){try{return Hp(JSON.parse(e)).publishConfig?.access??"public"}catch(t){throw Error("Invalid publishConfig.access: expected public or restricted",{cause:t})}}import{rm as dd}from"fs/promises";import{isAbsolute as md,resolve as Ga}from"path";import{createHash as Zr}from"crypto";import{constants as ka}from"fs";import{lstat as qp,open as Wp,readlink as Ta}from"fs/promises";import{isAbsolute as Jp,relative as bn,resolve as Le,sep as vn}from"path";var $n=new Set(["100644","100755"]),kt="120000",er="160000",Ea=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;async function es(e){let t=await Bun.$`git rev-parse --show-toplevel`.quiet(),r=Le(t.stdout.toString().trim()),s=Le(r,e),n=bn(r,s);if(!n||oe(n))throw new u("Sisyphus directory is outside the repository","Use a repository-relative sisyphusDir");let i=n.split(vn).join("/"),o=await zp(r,i),a=Zr("sha256");for(let c of o){if(c.kind==="tracked"&&!Kp(c.mode))throw new u(`Release source has unsupported Git mode ${c.mode}: ${c.path}`);let l=await Oa(r,c.path),p=await Rn(l);if(a.update(c.path),a.update("\x00"),a.update(c.kind),a.update("\x00"),!p){if(c.kind==="tracked"&&c.mode===er)throw new u(`Release source gitlink is not initialized: ${c.path}`);a.update("deleted")}else if(c.kind==="untracked"||$n.has(c.mode)){if(!p.isFile()||p.isSymbolicLink())throw new u(`Release source path is not a regular file: ${c.path}`);await Yp(a,l,c.path)}else if(c.mode===kt){if(!p.isSymbolicLink())throw new u(`Release source path does not match Git mode ${kt}: ${c.path}`);a.update(Zr("sha256").update(await Ta(l,{encoding:"buffer"})).digest("hex")),a.update(kt)}else{if(!p.isDirectory()||p.isSymbolicLink())throw new u(`Release source path does not match Git mode ${er}: ${c.path}`);a.update(await La(r,l,c)),await Pn(l),a.update(er)}a.update("\x00")}return a.digest("hex")}async function Pn(e=process.cwd()){let t=await Bun.$`git rev-parse --show-toplevel`.cwd(e).quiet(),r=Le(t.stdout.toString().trim());await Ia(r)}async function Ia(e){let[t,r]=await Promise.all([Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),Bun.$`git ls-files -v -z --cached`.cwd(e).quiet()]),s=new Set,n=new Map;for(let i of Qr(r.stdout)){let o=i.slice(0,1),a=i.slice(2);if(!o||i.slice(1,2)!==" "||!a)throw new u("Unable to parse Git index flags while validating release source");n.set(a,o)}for(let i of Qr(t.stdout)){let o=Aa(i);if(o.stage!=="0")throw new u(`Release source has an unresolved index entry: ${o.path}`);if(s.has(o.path))throw new u(`Release source has duplicate index entries: ${o.path}`);if(s.add(o.path),n.get(o.path)!=="H")throw new u(`Release source index flags hide working tree changes: ${o.path}`);let a={kind:"tracked",mode:o.mode,objectId:o.objectId,path:o.path},c=await Oa(e,o.path),l=await Rn(c);if(!l)throw new u(`Release source path is missing: ${o.path}`);if($n.has(o.mode)){if(!l.isFile()||l.isSymbolicLink())throw new u(`Release source path is not a regular file: ${o.path}`);let m=(await Bun.$`git hash-object ${`--path=${o.path}`} ${c}`.cwd(e).quiet()).stdout.toString().trim(),h=l.mode&73?"100755":"100644";if(m!==o.objectId||h!==o.mode)throw new u(`Release source path differs from the Git index: ${o.path}`);continue}if(o.mode===kt){if(!l.isSymbolicLink())throw new u(`Release source path does not match Git mode ${kt}: ${o.path}`);let p=await Bun.$`git cat-file blob ${o.objectId}`.cwd(e).quiet(),m=await Ta(c,{encoding:"buffer"});if(!Buffer.from(p.stdout).equals(m))throw new u(`Release source symlink differs from the Git index: ${o.path}`);continue}if(o.mode!==er)throw new u(`Release source has unsupported Git mode ${o.mode}: ${o.path}`);if(!l.isDirectory()||l.isSymbolicLink())throw new u(`Release source gitlink is not initialized: ${o.path}`);await La(e,c,a),await Ia(c)}}function ts(e,t){return Zr("sha256").update(JSON.stringify(xt({...e,stones:t}))).digest("hex")}function xt(e){if(Array.isArray(e))return e.map(xt);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>[t,xt(r)]))}function oe(e){return e===".."||e.startsWith(`..${vn}`)||Jp(e)}async function zp(e,t){let[r,s]=await Promise.all([Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),Bun.$`git ls-files -z --others --exclude-standard`.cwd(e).quiet()]),n=[],i=new Set;for(let o of Qr(r.stdout)){let a=Aa(o);if(xa(a.path,t))continue;if(a.stage!=="0")throw new u(`Release source has an unresolved index entry: ${a.path}`);if(i.has(a.path))throw new u(`Release source has duplicate index entries: ${a.path}`);i.add(a.path),n.push({kind:"tracked",mode:a.mode,objectId:a.objectId,path:a.path})}for(let o of Qr(s.stdout)){if(xa(o,t))continue;if(i.has(o))throw new u(`Release source path is both tracked and untracked: ${o}`);i.add(o),n.push({kind:"untracked",path:o})}return n.sort((o,a)=>o.path<a.path?-1:o.path>a.path?1:0)}function Qr(e){let t=e.toString();if(!Buffer.from(t).equals(e))throw new u("Release source contains paths that are not valid UTF-8");return t.split("\x00").filter(Boolean)}function Aa(e){let t=e.indexOf("\t");if(t<0)throw new u("Unable to parse Git index entry while hashing release source");let[r,s,n,...i]=e.slice(0,t).split(" "),o=e.slice(t+1);if(!r||!/^[0-7]{6}$/.test(r)||!s||!Ea.test(s)||!n||i.length>0||!o)throw new u("Unable to parse Git index entry while hashing release source");return{mode:r,objectId:s,path:o,stage:n}}function xa(e,t){return e===t||e.startsWith(`${t}/`)}function Kp(e){return $n.has(e)||e===kt||e===er}async function Oa(e,t){let r=t.split("/"),s=Le(e,t),n=bn(e,s);if(r.some((o)=>!o||o==="."||o==="..")||oe(n)||n.split(vn).join("/")!==t)throw new u(`Release source path escapes the repository: ${t}`);let i=e;for(let o of r.slice(0,-1)){i=Le(i,o);let a=await Rn(i);if(!a)break;if(!a.isDirectory()||a.isSymbolicLink())throw new u(`Release source path has an unsafe parent: ${t}`)}return s}async function Rn(e){try{return await qp(e)}catch(t){if(_a(t,"ENOENT"))return null;throw t}}function _a(e,t){return e instanceof Error&&"code"in e&&e.code===t}async function Yp(e,t,r){let s=await Wp(t,ka.O_RDONLY|ka.O_NOFOLLOW).catch((n)=>{if(_a(n,"ELOOP"))throw new u(`Release source path is not a regular file: ${r}`);throw n});try{let n=await s.stat();if(!n.isFile())throw new u(`Release source path is not a regular file: ${r}`);e.update(Zr("sha256").update(await s.readFile()).digest("hex")),e.update(n.mode&73?"100755":"100644")}finally{await s.close()}}async function La(e,t,r){let[s,n,i,o]=await Promise.all([Bun.$`git rev-parse --show-toplevel`.cwd(t).quiet(),Bun.$`git rev-parse --show-superproject-working-tree`.cwd(t).quiet(),Bun.$`git rev-parse --absolute-git-dir`.cwd(t).quiet(),Bun.$`git rev-parse --git-path modules`.cwd(e).quiet()]),a=Le(s.stdout.toString().trim()),c=n.stdout.toString().trim(),l=c?Le(c):null,p=Le(i.stdout.toString().trim()),m=Le(e,o.stdout.toString().trim()),h=bn(m,p);if(a!==t||l!==e||!h||oe(h))throw new u(`Release source gitlink is not initialized: ${r.path}`);if((await Bun.$`git status --porcelain=v1 -z --untracked-files=all --ignore-submodules=none`.cwd(t).quiet()).stdout.byteLength>0)throw new u(`Release source gitlink is dirty: ${r.path}`,"Commit or discard submodule changes before releasing");let y=(await Bun.$`git rev-parse --verify HEAD`.cwd(t).quiet()).stdout.toString().trim();if(!Ea.test(y))throw new u(`Release source gitlink has an invalid object ID: ${r.path}`);if(y!==r.objectId)throw new u(`Release source gitlink does not match the recorded commit: ${r.path}`,"Check out the submodule commit recorded by the repository before releasing");return r.objectId}var nt={isOutput:()=>!1};function Ma(e){if(e.length===0)return nt;let t=e.flatMap((r)=>{let s=r.endsWith("/")?`${r}**`:r;if(s.endsWith("**"))return[new Bun.Glob(s)];return[new Bun.Glob(s),new Bun.Glob(`${s}/**`)]});return{isOutput:(r)=>t.some((s)=>s.match(r))}}import{cp as Xp,mkdir as Zp,mkdtemp as Qp,rename as ed,rm as td,writeFile as rd}from"fs/promises";import{tmpdir as sd}from"os";import{dirname as Na,join as Da,relative as kn,resolve as He,sep as nd}from"path";function Sn(e){let t=JSON.parse(e),r=Array.isArray(t)?t:typeof t==="object"&&t!==null?Object.values(t):[],[s]=r;return typeof s==="object"&&s!==null&&!Array.isArray(s)?s:void 0}var rs=512,id=100,od=124,ad=12,cd=345,ld=155,ud="package/package.json",pd=20;async function ja(e,t){let r=Na(t),s=await Bun.$`npm pack --ignore-scripts --json --pack-destination ${r}`.cwd(e).quiet(),n=Sn(s.stdout.toString());if(typeof n?.filename!=="string"||!n.filename||typeof n.name!=="string"||!n.name||typeof n.version!=="string"||!n.version)throw Error("npm pack did not return a valid artifact identity");let i=He(r,n.filename);if(oe(kn(r,i)))throw Error("npm pack returned an artifact outside the destination directory");if(i!==He(t))await ed(i,t);return{name:n.name,version:n.version}}async function Fa(e,t){let r=await Bun.$`npm pack --dry-run --ignore-scripts --json`.cwd(t).quiet(),s=Sn(r.stdout.toString())?.files;if(!Array.isArray(s))throw Error(`npm pack did not return a file list for ${e.name}`);return s.map((n)=>{if(typeof n!=="object"||n===null||Array.isArray(n)||!("path"in n))throw Error(`npm pack returned an invalid file entry for ${e.name}`);let i=n.path;if(typeof i!=="string"||!i)throw Error(`npm pack returned an invalid file path for ${e.name}`);if(oe(kn(t,He(t,i))))throw new u(`Package ${e.name} includes a file outside its directory: ${i}`);return i})}async function Ba(e,t,r){let s=await Fa(e,t),n=await Qp(Da(sd(),"sisyphus-package-stage-"));try{for(let i of s){let o=He(n,i);await Zp(Na(o),{recursive:!0}),await Xp(He(t,i),o,{errorOnExist:!0,force:!1,recursive:!1,verbatimSymlinks:!0})}return await rd(Da(n,"package.json"),r,"utf-8"),n}catch(i){try{await td(n,{force:!0,recursive:!0})}catch(o){throw AggregateError([i,o],"Failed to clean staged npm package")}throw i}}async function Va(e,t,r,s=nt){let[n,i]=await Promise.all([Fa(e,t),ns(r)]);for(let o of n){let a=kn(r,He(t,o)).split(nd).join("/");if(!i.has(a)&&!s.isOutput(a))throw new u(`Package ${e.name} includes an untracked or ignored pre-build file: ${o}`)}}async function xn(e,t){return(await Bun.$`git ls-files --others --ignored --exclude-standard -z`.cwd(e).quiet()).stdout.toString().split("\x00").filter(Boolean).filter((s)=>!s.split("/").includes("node_modules")).map((s)=>`${t}${s}`)}async function Tn(e,t,r=nt){let[s,n]=await Promise.all([xn(e,t),Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet()]),i=s.filter((o)=>!r.isOutput(o));if(i.length>0){let o=i.slice(0,pd),a=i.length-o.length;throw new u(`Repository contains ${i.length} ignored build input(s) outside node_modules`,`Remove ignored source and stale build outputs before preparing npm artifacts (preview with git clean -ndX):
|
|
161
161
|
${o.join(`
|
|
162
162
|
`)}${a>0?`
|
|
163
|
-
...and ${a} more`:""}`)}for(let{mode:o,path:a}of ss(n.stdout.toString()))if(o==="160000")await
|
|
163
|
+
...and ${a} more`:""}`)}for(let{mode:o,path:a}of ss(n.stdout.toString()))if(o==="160000")await Tn(He(e,a),`${t}${a}/`,r)}function ss(e){return e.split("\x00").filter(Boolean).map((t)=>{let r=t.indexOf("\t"),s=r<0?[]:t.slice(0,r).split(" "),[n,,i,...o]=s,a=r<0?"":t.slice(r+1);if(!n||!i||o.length>0||!a)throw Error("Unable to parse Git index while collecting tracked package inputs");return{mode:n,path:a,stage:i}})}async function ns(e,t=""){let r=await Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),s=new Set;for(let{mode:n,stage:i,path:o}of ss(r.stdout.toString())){if(i!=="0")throw new u(`Repository has an unresolved index entry: ${o}`);let a=`${t}${o}`;if(s.add(a),n!=="160000")continue;let c=await ns(He(e,o),`${a}/`);for(let l of c)s.add(l)}return s}async function is(e){let t=new Uint8Array(await Bun.file(e).arrayBuffer()),r=Bun.gunzipSync(t),s=new TextDecoder;for(let n=0;n+rs<=r.length;){let i=Cn(r,n,id,s);if(!i)break;let o=Cn(r,n+cd,ld,s),a=o?`${o}/${i}`:i,c=Cn(r,n+od,ad,s).trim(),l=Number.parseInt(c,8);if(!Number.isSafeInteger(l)||l<0)throw Error(`Invalid tar entry size for ${a}`);let p=n+rs,m=p+l;if(m>r.length)throw Error(`Truncated tar entry for ${a}`);if(a===ud)return s.decode(r.subarray(p,m));n=p+Math.ceil(l/rs)*rs}throw Error("Packed artifact does not contain package/package.json")}function Cn(e,t,r,s){let n=e.subarray(t,t+r),i=n.indexOf(0);return s.decode(i<0?n:n.subarray(0,i))}function Ua(e,t){return JSON.stringify(xt(JSON.parse(e)))===JSON.stringify(xt(JSON.parse(t)))}var gd="160000",hd="./";function qa(e){let t=e?.command??[...sn],r=e?.root??[],s=e?.outputs??[];os(t,"release.build.command"),os(r,"release.build.root"),os(s,"release.build.outputs"),Ha(t,"release.build.command");for(let[n,i]of r.entries())if(os(i,`release.build.root[${n}]`),Ha(i,`release.build.root[${n}]`),i.length===0)throw new u(`Invalid release.build.root[${n}]`,'Each root build command must be a non-empty array of arguments, e.g. ["bun", "run", "build:dts"]');for(let n of s)if(!n||md(n)||n.startsWith(hd)||yd(n))throw new u(`Invalid release.build.outputs entry: ${n||"(empty)"}`,"Build output globs must be relative to the repository root, e.g. packages/*/dist/**");if(s.length>0&&t.length===0&&r.length===0)throw new u("release.build.outputs is declared but no build command runs","Set release.build.command or release.build.root, or remove the declared outputs");return{command:t,matcher:Ma(s),outputs:s,root:r}}async function Wa(e,t){if(t===nt)return;let r=await ns(e);for(let s of r){if(!t.isOutput(s))continue;throw new u(`Declared build output ${s} is tracked by Git`,"Add it to .gitignore, or narrow release.build.outputs so it excludes committed files")}}async function En(e,t,r){if(r===nt)return 0;let s=0;for(let i of await xn(e,t)){if(!r.isOutput(i))continue;await dd(Ga(e,i.slice(t.length)),{force:!0}),s+=1}let n=await Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet();for(let{mode:i,path:o}of ss(n.stdout.toString())){if(i!==gd)continue;s+=await En(Ga(e,o),`${t}${o}/`,r)}return s}async function In(e,t,r){let s=fd(e,t,r),n,i;try{[n,i]=await Promise.all([s.exited,new Response(s.stderr).text(),new Response(s.stdout).text()])}catch(o){throw s.kill(),o}if(n!==0)throw Error(`${r}: ${i.trim()||`${e[0]} exited with code ${n}`}`)}function fd(e,t,r){try{return Bun.spawn([...e],{cwd:t,stderr:"pipe",stdout:"pipe"})}catch(s){throw Error(`${r}: ${s instanceof Error?s.message:String(s)}`)}}function os(e,t){if(Array.isArray(e))return;throw new u(`Invalid ${t}`,`${t} must be an array`)}function yd(e){if(oe(e))return!0;return e.split("/").includes("..")}function Ha(e,t){for(let r of e){if(typeof r==="string"&&r.length>0)continue;throw new u(`Invalid ${t}`,"Every build command argument must be a non-empty string")}}import{dirname as wd,join as bd}from"path";function Ja(e,t,r){let s=r.map((i)=>`- ${i.name}@${i.newVersion??i.version}`).join(`
|
|
164
164
|
`);return`${e.replace("{message}",()=>t.message).replace("{packages}",()=>r.map((i)=>i.name).join(", "))}
|
|
165
165
|
|
|
166
|
-
${s}`}function
|
|
167
|
-
`));await I(async()=>{let a=Bun.spawn(["git","update-ref","--stdin"],{cwd:i,stderr:"pipe",stdin:o,stdout:"pipe"}),[c,l]=await Promise.all([a.exited,new Response(a.stderr).text()]);if(c!==0)throw Error(l.trim()||`git update-ref exited with code ${c}`)},"Failed to atomically restore release refs")}async function
|
|
168
|
-
`,"utf-8"),await r.sync()}catch(s){throw await
|
|
169
|
-
`,i=lr(cr(e),`.${
|
|
170
|
-
${c.stderr.toString()}`))throw new u(`Cannot safely resume npm publication for ${o}: ${n} did not confirm whether it exists`,"Check the registry connectivity and authentication, then re-run sis roll --resume");await
|
|
171
|
-
`).filter(Boolean);if(r.length!==1)throw new u(`Push remote ${e} must have exactly one push URL, found ${r.length}`,"Remove additional push URLs before starting or resuming a release");let[s]=r;if(!s)throw new u(`Push remote ${e} has no URL`);return s}async function Ot(e,t){let r=await Rs(e.remote),s=await $s(r,t);if(JSON.stringify(s)!==JSON.stringify(e.destination))throw new u(`Push remote ${e.remote} no longer matches the recorded release destination`,"Restore the original remote before resuming the release");return r}async function
|
|
172
|
-
`).filter(Boolean).map((o)=>{let[a="",c=""]=o.split("\t");return[c,a]}))}async function
|
|
173
|
-
`).filter(Boolean);if(o.length===1&&o[0]==="origin")n="origin"}if(!n){let i=e?` for branch ${e}`:"";throw new u(`No push remote is configured${i}`,e?"Configure a branch push remote or remote.pushDefault":"Configure remote.pushDefault")}return await I(()=>Bun.$`git remote get-url --push ${n}`.quiet(),`Invalid push remote ${n}`),n}async function
|
|
174
|
-
`);s.push(""),s.push("<details>"),s.push(`<summary>Stones (${e.length})</summary>`),s.push("");for(let i of e){if(s.push(`### ${i.message}`),s.push(""),i.description)s.push(i.description),s.push("");let o=
|
|
175
|
-
`)}function id(e,t){if(!e)return[];return e.filter((r)=>r.packages.includes(t))}function od(e,t){return`- ${t?`[\`${e.hash}\`](${t(e.hash)})`:`\`${e.hash}\``} ${e.subject}`}import{createHash as wd,randomUUID as bd}from"crypto";import{constants as vd}from"fs";import{copyFile as $d,link as Pd,lstat as Uc,readFile as li,rename as Gc,rm as Hc,stat as Rd,unlink as Sd}from"fs/promises";import{extname as Cd,join as kd,resolve as xd}from"path";import{isAbsolute as Lc,relative as ad,resolve as cd}from"path";function ri(e){if(Object.values(e.operations.npm).some((t)=>t.state!=="pending"))return!0;if(e.operations.push&&e.operations.push.state!=="pending")return!0;return Object.values(e.operations.providerReleases).some((t)=>t.state!=="pending")}function Mc(e){return e.map((t,r)=>{let s=`create.packages[${r}]`,n=t.oldVersion??t.version;if(t.oldVersion!==void 0&&t.version!==void 0&&t.oldVersion!==t.version)P(s,"oldVersion and version must match when both are provided");return Nc({file:t.file,isPrivate:t.isPrivate,name:t.name,newVersion:t.newVersion,oldVersion:n},s)})}function Dc(e){return e.map((t,r)=>{let s=typeof t==="object"&&t!==null&&"toJson"in t&&typeof t.toJson==="function"?t.toJson():t,n;try{n=JSON.parse(JSON.stringify(s))}catch(i){throw new b(`Invalid release ledger at create.stones[${r}]: ${D(i)}`)}return jc(n,`create.stones[${r}]`)})}function lt(e,t){let r=Z(e,"root");if(ye(r,["schemaVersion","id","baseCommit","createdAt","updatedAt","phase","options","packages","releaseTags","tagsReady","stones","artifacts","operations"],["expectedReleaseTree","releaseCommit"],"root"),r.schemaVersion!==sr)P("schemaVersion",`unsupported schema version ${String(r.schemaVersion)}`);let s=ir(r.id,"id"),n=_t(r.baseCommit,"baseCommit"),i=Cs(r.createdAt,"createdAt"),o=Cs(r.updatedAt,"updatedAt");if(Date.parse(o)<Date.parse(i))P("updatedAt","must not precede createdAt");let a=Fc(r.phase,Tt,"phase","release phase"),c=ud(r.options,"options"),l=pd(r.packages,t.repositoryRoot),p=ld(r.releaseTags,l,c),d=Ke(r.tagsReady,"tagsReady");if(!c.tags&&!d)P("tagsReady","must be true when tags are disabled");let h=md(r.stones),f=r.expectedReleaseTree===void 0?void 0:_t(r.expectedReleaseTree,"expectedReleaseTree"),g=r.releaseCommit===void 0?void 0:_t(r.releaseCommit,"releaseCommit"),y=gd(r.artifacts,l,t,s),R=hd(r.operations,l,c,i,o),S={artifacts:y,baseCommit:n,createdAt:i,id:s,operations:R,options:c,packages:l,phase:a,releaseTags:p,schemaVersion:sr,stones:h,tagsReady:d,updatedAt:o};if(f!==void 0)S.expectedReleaseTree=f;if(g!==void 0)S.releaseCommit=g;if(c.tags&&d&&!g)P("tagsReady","cannot be true before releaseCommit is recorded");if(a==="completed")ii(S);return S}function ld(e,t,r){if(!Array.isArray(e))P("releaseTags","must be an array");let s=e.map((i,o)=>{let a=_(i,`releaseTags[${o}]`);return ti(`refs/tags/${a}`,`releaseTags[${o}]`),a});if(new Set(s).size!==s.length)P("releaseTags","must not contain duplicates");let n=r.tags?t.map((i)=>`${i.name}@${i.newVersion}`).sort():[];if(JSON.stringify([...s].sort())!==JSON.stringify(n))P("releaseTags","must exactly match the release package versions when tags are enabled");return s}function ud(e,t){let r=Z(e,t);return ye(r,["changelog","createRelease","dryRun","npm","npmTag","publishOnly","push","tags"],[],t),{changelog:Ke(r.changelog,`${t}.changelog`),createRelease:Ke(r.createRelease,`${t}.createRelease`),dryRun:oi(r.dryRun),npm:Ke(r.npm,`${t}.npm`),npmTag:_(r.npmTag,`${t}.npmTag`),publishOnly:Ke(r.publishOnly,`${t}.publishOnly`),push:Ke(r.push,`${t}.push`),tags:Ke(r.tags,`${t}.tags`)}}function pd(e,t){if(!Array.isArray(e)||e.length===0)P("packages","must be a nonempty array");let r=new Set,s=new Set;return e.map((n,i)=>{let o=`packages[${i}]`,a=Nc(n,o);if(Lc(a.file))P(`${o}.file`,"must be repository-relative");if(r.has(a.name))P(o,`duplicate package name ${a.name}`);let c=cd(t,a.file),l=ad(t,c);if(!l||oe(l))P(`${o}.file`,"must resolve inside the repository");if(s.has(c))P(o,`duplicate package file ${a.file}`);return r.add(a.name),s.add(c),a})}function Nc(e,t){let r=Z(e,t);ye(r,["name","file","oldVersion","newVersion","isPrivate"],[],t);let s=_(r.file,`${t}.file`);if(s.includes("\x00"))P(`${t}.file`,"must not contain a null byte");return{file:s,isPrivate:Ke(r.isPrivate,`${t}.isPrivate`),name:_(r.name,`${t}.name`),newVersion:_(r.newVersion,`${t}.newVersion`),oldVersion:_(r.oldVersion,`${t}.oldVersion`)}}function md(e){if(!Array.isArray(e))P("stones","must be an array");let t=new Set;return e.map((r,s)=>{let n=jc(r,`stones[${s}]`);if(t.has(n.id))P(`stones[${s}].id`,`duplicate stone ID ${n.id}`);return t.add(n.id),n})}function jc(e,t){let r=Z(e,t);ye(r,["id","message"],["tag","description","commits","major","minor","patch","dependency","snapshot"],t);let s={id:_(r.id,`${t}.id`),message:_(r.message,`${t}.message`)};if(r.tag!==void 0)s.tag=_(r.tag,`${t}.tag`);if(r.description!==void 0)s.description=nr(r.description,`${t}.description`);if(r.commits!==void 0)s.commits=dd(r.commits,`${t}.commits`);for(let n of["major","minor","patch","dependency","snapshot"])if(r[n]!==void 0)s[n]=Vc(r[n],`${t}.${n}`);return s}function dd(e,t){if(!Array.isArray(e))P(t,"must be an array");return e.map((r,s)=>{let n=`${t}[${s}]`,i=Z(r,n);return ye(i,["hash","subject","type","message","packages"],["body","scope"],n),{...{hash:_(i.hash,`${n}.hash`),message:_(i.message,`${n}.message`),packages:Vc(i.packages,`${n}.packages`),subject:_(i.subject,`${n}.subject`),type:_(i.type,`${n}.type`)},...i.body===void 0?{}:{body:nr(i.body,`${n}.body`)},...i.scope===void 0?{}:{scope:_(i.scope,`${n}.scope`)}}})}function gd(e,t,r,s){let n=Z(e,"artifacts"),i=new Map(t.map((a)=>[a.name,a])),o=Me();for(let[a,c]of Object.entries(n)){let l=i.get(a);if(!l)P(`artifacts.${a}`,"references an unknown package");if(l.isPrivate)P(`artifacts.${a}`,"private packages cannot have artifacts");let p=`artifacts.${a}`,d=Z(c,p);ye(d,["path","integrity"],[],p);let h=_(d.path,`${p}.path`);if(Lc(h))P(`${p}.path`,"must be relative to the release directory");let f=ys(r,s,a);if(h!==f)P(`${p}.path`,`must be ${f}`);let g=_(d.integrity,`${p}.integrity`);if(!ic.test(g))P(`${p}.integrity`,"must be a sha512 SRI value");Pe(o,a,{integrity:g,path:h})}return o}function hd(e,t,r,s,n){let i=Z(e,"operations");ye(i,["npm","npmRegistries","providerReleases"],["push"],"operations");let o=new Map(t.map((y)=>[y.name,y])),a=Z(i.npm,"operations.npm"),c=Me();for(let[y,R]of Object.entries(a)){let S=o.get(y);if(!S)P(`operations.npm.${y}`,"references an unknown package");if(S.isPrivate)P(`operations.npm.${y}`,"private packages cannot have npm operations");if(!r.npm)P(`operations.npm.${y}`,"npm is disabled");let k=Qn(R,`operations.npm.${y}`);ei(k,s,n,`operations.npm.${y}`),Pe(c,y,k)}let l=r.npm?t.filter((y)=>!y.isPrivate).map((y)=>y.name):[];for(let y of l)if(!c[y])P("operations.npm",`missing public package ${y}`);let p=Z(i.npmRegistries,"operations.npmRegistries"),d=Me();for(let[y,R]of Object.entries(p)){if(!c[y])P(`operations.npmRegistries.${y}`,"references an unknown npm operation");Pe(d,y,ai(R,`operations.npmRegistries.${y}`))}let h;if(i.push!==void 0){if(!r.push&&!r.tags)P("operations.push","push and tags are disabled");let y=Z(i.push,"operations.push");ye(y,["destination","remote","refs","state"],["startedAt","completedAt"],"operations.push");let R=si(y,"operations.push"),S=Qn(y,"operations.push",["destination","remote","refs"]);ei(S,s,n,"operations.push"),h={...R,...S}}let f=Z(i.providerReleases,"operations.providerReleases"),g=Me();for(let[y,R]of Object.entries(f)){if(!o.has(y))P(`operations.providerReleases.${y}`,"references an unknown package");if(!r.createRelease)P(`operations.providerReleases.${y}`,"createRelease is disabled");let S=`operations.providerReleases.${y}`,k=Z(R,S);ye(k,["tag","title","notes","state"],["startedAt","completedAt"],S);let H=ni(k,S),L=Qn(k,S,["tag","title","notes"]);ei(L,s,n,S),Pe(g,y,{...H,...L})}return{npm:c,npmRegistries:d,providerReleases:g,...h?{push:h}:{}}}function Qn(e,t,r=[]){let s=Z(e,t);ye(s,["state",...r],["startedAt","completedAt"],t);let n=Fc(s.state,Nn,`${t}.state`,"operation state");if(n==="pending"){if(s.startedAt!==void 0||s.completedAt!==void 0)P(t,"pending operations cannot have timestamps");return{state:n}}let i=Cs(s.startedAt,`${t}.startedAt`);if(n==="started"){if(s.completedAt!==void 0)P(t,"started operations cannot have completedAt");return{startedAt:i,state:n}}let o=Cs(s.completedAt,`${t}.completedAt`);if(Date.parse(o)<Date.parse(i))P(t,"completedAt must not precede startedAt");return{completedAt:o,startedAt:i,state:n}}function si(e,t){let r=Z(e,t),s=fd(r.destination,`${t}.destination`),n=_(r.remote,`${t}.remote`);if(!oc.test(n)||n.includes("..")||n.includes("//"))P(`${t}.remote`,"must be a git remote name, not a URL or credential-bearing value");if(!Array.isArray(r.refs)||r.refs.length===0)P(`${t}.refs`,"must be a nonempty array");let i=new Set,o=new Set,a=r.refs.map((c,l)=>{let p=`${t}.refs[${l}]`,d=Z(c,p);ye(d,["source","destination","oid"],[],p);let h=ti(d.source,`${p}.source`),f=ti(d.destination,`${p}.destination`),g=_(d.oid,`${p}.oid`);if(!ot.test(g))P(`${p}.oid`,"must be a full 40- or 64-character git object ID");if(i.has(h))P(`${p}.source`,`duplicate source ref ${h}`);if(o.has(f))P(`${p}.destination`,`duplicate destination ref ${f}`);return i.add(h),o.add(f),{destination:f,oid:g,source:h}});return{destination:s,refs:a,remote:n}}function fd(e,t){let r=Z(e,t);ye(r,["canonicalUrl"],["owner","provider","repo"],t);let s=_(r.canonicalUrl,`${t}.canonicalUrl`),n;try{n=new URL(s)}catch{P(`${t}.canonicalUrl`,"must be an absolute credential-free URL")}let i=n.protocol==="ssh:"||n.protocol==="git+ssh:";if(n.password||n.username&&!i||n.search||n.hash)P(`${t}.canonicalUrl`,"must not contain credentials, query parameters, or fragments");let o=[r.provider,r.owner,r.repo];if(o.every((c)=>c===void 0))return{canonicalUrl:s};if(o.some((c)=>c===void 0))P(t,"provider, owner, and repo must be set together");let a=_(r.provider,`${t}.provider`);if(a!=="github"&&a!=="gitlab"&&a!=="bitbucket")P(`${t}.provider`,"must be github, gitlab, or bitbucket");return{canonicalUrl:s,owner:_(r.owner,`${t}.owner`),provider:a,repo:_(r.repo,`${t}.repo`)}}function ni(e,t){let r=Z(e,t);return{notes:nr(r.notes,`${t}.notes`),tag:_(r.tag,`${t}.tag`),title:_(r.title,`${t}.title`)}}function ks(e,t,r){if(!yd(t))throw new b(`Unknown release operation state ${String(t)}`);if(e.state===t)return e;if(e.state==="pending"&&t==="started")return{startedAt:r,state:t};if(e.state==="started"&&t==="completed")return{completedAt:r,startedAt:e.startedAt,state:t};throw new b(`Invalid release operation transition from ${e.state} to ${t}`)}function ii(e){if(!e.tagsReady)throw new b(`Cannot complete release ${e.id}: local release tags are not ready`);for(let[t,r]of Object.entries(e.operations.npm)){if(r.state!=="completed")throw new b(`Cannot complete release ${e.id}: npm operation for ${t} is ${r.state}`);if(!e.artifacts[t])throw new b(`Cannot complete release ${e.id}: npm artifact for ${t} is missing`);if(!e.operations.npmRegistries[t])throw new b(`Cannot complete release ${e.id}: npm registry for ${t} is missing`)}if((e.options.push||e.options.publishOnly&&e.options.tags)&&!e.operations.push)throw new b(`Cannot complete release ${e.id}: push operation is not configured`);if(e.operations.push&&e.operations.push.state!=="completed")throw new b(`Cannot complete release ${e.id}: push operation is ${e.operations.push.state}`);if(e.options.createRelease)for(let t of e.packages){let r=e.operations.providerReleases[t.name];if(!r)throw new b(`Cannot complete release ${e.id}: provider release for ${t.name} is not configured`);if(r.state!=="completed")throw new b(`Cannot complete release ${e.id}: provider release for ${t.name} is ${r.state}`)}}function oi(e){if(e!==!1)P("options.dryRun","durable ledgers require dryRun to be false");return!1}function ai(e,t){let r=_(e,t),s;try{s=new URL(r)}catch{P(t,"must be an absolute HTTP or HTTPS URL")}if(s.protocol!=="http:"&&s.protocol!=="https:"||s.username||s.password||s.search||s.hash)P(t,"must be a credential-free HTTP or HTTPS URL");return s.href}function ei(e,t,r,s){if(e.state==="pending")return;let n=Date.parse(e.startedAt);if(n<Date.parse(t)||n>Date.parse(r))P(`${s}.startedAt`,"must be between createdAt and updatedAt");if(e.state==="completed"){let i=Date.parse(e.completedAt);if(i<n||i>Date.parse(r))P(`${s}.completedAt`,"must be between startedAt and updatedAt")}}function ti(e,t){let r=_(e,t);if(!r.startsWith("refs/")||r.includes("..")||r.includes("//")||/[\s~^:?*[\\]/.test(r))P(t,"must be an exact full git ref");return r}function Fc(e,t,r,s){if(typeof e!=="string"||!t.includes(e))P(r,`unknown ${s} ${String(e)}`);return e}function Bc(e){return Tt.includes(e)}function yd(e){return Nn.includes(e)}function Z(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))P(t,"must be an object");return e}function ye(e,t,r,s){let n=new Set([...t,...r]);for(let i of t)if(!Object.hasOwn(e,i))P(s,`missing required key ${i}`);for(let i of Object.keys(e))if(!n.has(i))P(s,`unknown key ${i}`)}function Ke(e,t){if(typeof e!=="boolean")P(t,"must be a boolean");return e}function Cs(e,t){let r=_(e,t);if(!us(r))P(t,"must be a canonical ISO timestamp");return r}function _t(e,t){let r=_(e,t);if(!ot.test(r))P(t,"must be a full 40- or 64-character git object ID");return r}function Vc(e,t){if(!Array.isArray(e))P(t,"must be an array");return e.map((r,s)=>_(r,`${t}[${s}]`))}function ci(e){return new Date(Math.max(Date.now(),Date.parse(e)+1)).toISOString()}function Me(){return Object.create(null)}function Pe(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0})}class Re{value;paths;releaseDirectory;artifactsDirectory;activePath;active=!0;constructor(e,t){this.value=e;this.paths=t;this.releaseDirectory=t.releaseDirectory,this.artifactsDirectory=hr(t,e.id),this.activePath=t.activePath}static async create(e,t=process.cwd()){let r=await Un(t);if(await ct(r.activePath))throw new b(`Cannot create release ledger: active ledger already exists at ${r.activePath}`);if(await ct(r.removingPath))throw new b(`Cannot create release ledger: an interrupted removal left ${r.removingPath}; delete it and its artifacts directory to finish cleanup`);let s=new Date().toISOString(),n=await Bun.$`git rev-parse HEAD`.cwd(r.repositoryRoot).quiet().nothrow(),i=n.stdout.toString().trim();if(n.exitCode!==0||!ot.test(i))throw new b("Cannot create release ledger: failed to resolve the current commit");let o=e.options.publishOnly?await vc(r.repositoryRoot,i):void 0,a=Mc(e.packages),c=Dc(e.stones),l=wd("sha256").update(JSON.stringify({baseCommit:i,options:e.options,packages:a,stones:c})).digest("hex"),p=Me(),d=e.options.tags?a.map((y)=>`${y.name}@${y.newVersion}`).sort():[];if(e.options.npm){for(let y of a)if(!y.isPrivate)Pe(p,y.name,{state:"pending"})}let h={artifacts:Me(),baseCommit:i,createdAt:s,id:l,operations:{npm:p,npmRegistries:Me(),providerReleases:Me()},options:{changelog:e.options.changelog,createRelease:e.options.createRelease,dryRun:oi(e.options.dryRun),npm:e.options.npm,npmTag:_(e.options.npmTag,"create.options.npmTag"),publishOnly:e.options.publishOnly,push:e.options.push,tags:e.options.tags},packages:a,phase:"planned",releaseTags:d,schemaVersion:sr,stones:c,tagsReady:!e.options.tags,updatedAt:s};if(o)h.expectedReleaseTree=o;let f=lt(h,r);if(await dr(f,r),await mr(r,l),await ct(r.activePath))throw new b(`Cannot create release ledger: active ledger already exists at ${r.activePath}`);let g=Wn(r,l);if(await ct(g))throw new b(`Release ${l} is already completed at ${g}`);return await Gn(r.activePath,f,!1),new Re(f,r)}static async loadActive(e=process.cwd()){let t=await Un(e),r;try{r=await Uc(t.activePath)}catch(o){if(X(o,"ENOENT")){if(await ct(t.removingPath))throw new b(`Release cleanup is incomplete: an interrupted removal left ${t.removingPath}; delete it and its artifacts directory to finish cleanup`);return null}throw new b(`Failed to inspect active release ledger at ${t.activePath}: ${D(o)}`)}if(!r.isFile()||r.isSymbolicLink())throw new b(`Invalid active release ledger at ${t.activePath}: expected a regular file`);let s;try{s=await li(t.activePath,"utf-8")}catch(o){if(X(o,"ENOENT"))return null;throw new b(`Failed to read active release ledger at ${t.activePath}: ${D(o)}`)}let n;try{n=JSON.parse(s)}catch(o){throw new b(`Failed to parse active release ledger at ${t.activePath}: ${D(o)}`)}let i=lt(n,t);return await dr(i,t),await mr(t,i.id),await fs(i,t),new Re(i,t)}get data(){return lt(this.value,this.paths)}get id(){return this.value.id}get phase(){return this.value.phase}async setPhase(e){if(this.assertActive("set phase"),e==="completed")throw new b("Cannot set release phase to completed: use complete() instead");if(!Bc(e))throw new b(`Cannot set release phase: unknown phase ${String(e)}`);if(e===this.value.phase)return;let t=Tt.indexOf(this.value.phase);if(Tt.indexOf(e)<t)throw new b(`Cannot move release phase backwards from ${this.value.phase} to ${e}`);let s=structuredClone(this.value);s.phase=e,await this.persist(s)}async setReleaseCommit(e){this.assertActive("set release commit");let t=_t(e,"releaseCommit");if(!this.value.expectedReleaseTree)throw new b("Cannot set release commit before the expected release tree");if(this.value.releaseCommit===t)return;if(this.value.releaseCommit)throw new b(`Cannot replace release commit ${this.value.releaseCommit} with ${t} in release ${this.value.id}`);let r=structuredClone(this.value);r.releaseCommit=t,await this.persist(r)}async setExpectedReleaseTree(e){this.assertActive("set expected release tree");let t=_t(e,"expectedReleaseTree");if(this.value.expectedReleaseTree===t)return;if(this.value.expectedReleaseTree)throw new b(`Cannot replace expected release tree ${this.value.expectedReleaseTree} with ${t} in release ${this.value.id}`);if(this.value.releaseCommit)throw new b(`Cannot set expected release tree after release commit ${this.value.releaseCommit}`);let r=structuredClone(this.value);r.expectedReleaseTree=t,await this.persist(r)}async markTagsReady(){if(this.assertActive("mark release tags ready"),!this.value.options.tags)return;if(!this.value.releaseCommit)throw new b("Cannot mark release tags ready without a release commit");if(this.value.tagsReady)return;let e=structuredClone(this.value);e.tagsReady=!0,await this.persist(e)}async setArtifact(e,t){if(this.assertActive("set artifact"),this.getPackage(e).isPrivate)throw new b(`Cannot store an artifact for private package ${e}`);let s=this.value.operations.npm[e];if(!s)throw new b(`Cannot store an artifact for unconfigured npm package ${e}`);if(s.state!=="pending")throw new b(`Cannot replace artifact for ${e} after its npm operation has started`);if(Cd(t)!==".tgz")throw new b(`Cannot store artifact for ${e}: source must be a .tgz file`);let n;try{n=await Rd(t)}catch(p){throw new b(`Cannot read source artifact for ${e} at ${t}: ${D(p)}`)}if(!n.isFile())throw new b(`Cannot store artifact for ${e}: source is not a regular file`);await mr(this.paths,this.value.id);let i=qn(this.paths,this.value.id,e),o=kd(this.artifactsDirectory,`.${bd()}.tgz.tmp`),a;try{await $d(t,o,vd.COPYFILE_EXCL),await ae(o),await gr(this.paths,this.value.id,o),a=await It(o);try{await Pd(o,i)}catch(p){if(!X(p,"EEXIST"))throw p;if(await gr(this.paths,this.value.id,i),await It(i)!==a){let d=this.value.artifacts[e]?`A different durable artifact already exists for ${e} at ${i}`:`A different durable artifact already exists for ${e} at ${i}; the ledger records no artifact for it, so it is likely left by an interrupted run - delete the file and retry`;throw new b(d)}}await Hc(o,{force:!0}),await ae(this.artifactsDirectory),await gr(this.paths,this.value.id,i)}catch(p){await Hn(o,p,`Failed to clean temporary artifact for ${e}`)}if(!a)throw new b(`Failed to calculate artifact integrity for ${e}`);let c={integrity:a,path:ys(this.paths,this.value.id,e)},l=structuredClone(this.value);return Pe(l.artifacts,e,c),await this.persist(l),{...c}}resolveArtifactPath(e){let t=this.value.artifacts[e];if(!t)throw new b(`Release artifact is not configured for ${e}`);return xd(this.releaseDirectory,t.path)}async configurePush(e,t,r){if(this.assertActive("configure push"),!this.value.options.push&&!this.value.options.tags)throw new b("Cannot configure push: neither push nor tags are enabled for this release");let s=si({destination:t,refs:r,remote:e},"configurePush"),n=this.value.operations.push;if(n){if(JSON.stringify([n.remote,n.destination,n.refs])===JSON.stringify([s.remote,s.destination,s.refs]))return;throw new b("Cannot replace an existing push configuration")}let i=structuredClone(this.value);i.operations.push={...s,state:"pending"},await this.persist(i)}async configureProviderRelease(e,t){if(this.assertActive("configure provider release"),this.getPackage(e),!this.value.options.createRelease)throw new b("Cannot configure a provider release when createRelease is disabled");let r=ni(t,`providerReleases.${e}`),s=this.value.operations.providerReleases[e];if(s){if(s.tag===r.tag&&s.title===r.title&&s.notes===r.notes)return;throw new b(`Cannot replace provider release configuration for ${e}`)}let n=structuredClone(this.value);Pe(n.operations.providerReleases,e,{...r,state:"pending"}),await this.persist(n)}async markNpm(e,t){this.assertActive("mark npm operation");let r=this.value.operations.npm[e];if(!r)throw new b(`Npm operation is not configured for package ${e}`);if(r.state===t)return;if(t==="started"&&!this.value.artifacts[e])throw new b(`Cannot start npm operation for ${e} without a durable artifact`);let s=structuredClone(this.value);Pe(s.operations.npm,e,ks(r,t,this.operationTimestamp())),await this.persist(s)}async setNpmRegistry(e,t){this.assertActive("set npm registry");let r=this.value.operations.npm[e];if(!r)throw new b(`Npm operation is not configured for package ${e}`);if(r.state!=="pending")throw new b(`Cannot change npm registry for ${e} after publication has started`);let s=ai(t,`operations.npmRegistries.${e}`),n=this.value.operations.npmRegistries[e];if(n===s)return;if(n)throw new b(`Cannot replace npm registry for ${e}`);let i=structuredClone(this.value);Pe(i.operations.npmRegistries,e,s),await this.persist(i)}async markPush(e){this.assertActive("mark push operation");let t=this.value.operations.push;if(!t)throw new b("Push operation is not configured");if(t.state===e)return;let r=structuredClone(this.value);r.operations.push={destination:t.destination,refs:t.refs,remote:t.remote,...ks(t,e,this.operationTimestamp())},await this.persist(r)}async markProviderRelease(e,t){this.assertActive("mark provider release operation");let r=this.value.operations.providerReleases[e];if(!r)throw new b(`Provider release is not configured for package ${e}`);if(r.state===t)return;let s=structuredClone(this.value);Pe(s.operations.providerReleases,e,{notes:r.notes,tag:r.tag,title:r.title,...ks(r,t,this.operationTimestamp())}),await this.persist(s)}hasExternalProgress(){return ri(this.value)}async complete(){if(this.assertActive("complete"),this.value.phase!=="completed"){let r=structuredClone(this.value);ii(r),r.phase="completed",await this.persist(r)}let e=Wn(this.paths,this.value.id),t=await ar(this.releaseDirectory);try{let r=await Uc(this.activePath);if(!r.isFile()||r.isSymbolicLink())throw new b(`Invalid active release ledger at ${this.activePath}: expected a regular file`);let s=lt(JSON.parse(await li(this.activePath,"utf-8")),this.paths);if(s.id!==this.value.id||s.updatedAt!==this.value.updatedAt||s.phase!=="completed")throw new b("Active release ledger changed in another process");if(await Pc(this.paths),await ct(e))throw new b(`Cannot complete release ${s.id}: history ledger already exists at ${e}`);await Gc(this.activePath,e),await ae(this.paths.historyDirectory),await ae(this.releaseDirectory)}catch(r){if(r instanceof b)throw r;throw new b(`Failed to move completed release ${this.value.id} to history: ${D(r)}`)}finally{await Et(t)}return this.active=!1,e}async remove(){this.assertActive("remove");let e=await ar(this.releaseDirectory);try{await mr(this.paths,this.value.id);let t=lt(JSON.parse(await li(this.activePath,"utf-8")),this.paths);if(await dr(t,this.paths),await fs(t,this.paths),t.id!==this.value.id||t.updatedAt!==this.value.updatedAt)throw new b("Active release ledger changed in another process");if(ri(t))throw new b(`Cannot remove release ${t.id}: an external operation has started`);await Gc(this.activePath,this.paths.removingPath),await ae(this.releaseDirectory),await Hc(this.artifactsDirectory,{force:!0,recursive:!0}),await Sd(this.paths.removingPath),await ae(this.releaseDirectory)}catch(t){if(t instanceof b)throw t;throw new b(`Failed to remove release ${this.value.id}: ${D(t)}`)}finally{await Et(e)}this.active=!1}async persist(e){e.updatedAt=ci(this.value.updatedAt);let t=lt(e,this.paths);await dr(t,this.paths),await fs(t,this.paths),await Gn(this.activePath,t,!0,this.value.updatedAt),this.value=t}getPackage(e){let t=this.value.packages.find((r)=>r.name===e);if(!t)throw new b(`Unknown release package ${e}`);return t}operationTimestamp(){return ci(this.value.updatedAt)}assertActive(e){if(!this.active)throw new b(`Cannot ${e}: release ledger ${this.value.id} is no longer active`)}}class De{config;packageUpdater=new Qt;changelogGenerator;remoteParser=new Kt;stoneManager;provider=null;commitUrlFn=null;options;createdTags=[];createdTagTargets=new Map;commitCreated=!1;createdCommit=null;irreversibleOperation=null;ownedPaths=null;repositoryRoot=null;rollbackBlockedReason=null;ignoredBuildInputsValidated=!1;buildConfig=null;buildOutputsPrepared=!1;preparedNpmPublish=null;ledger=null;publishContext=null;constructor(e,t){this.config=e;this.options=t,this.changelogGenerator=new rt(this.config.get("changelog")),this.stoneManager=new O(this.config)}static async assertNoActiveRelease(){let e=await Re.loadActive();if(!e)return;throw new u(`Release ${e.id} is incomplete`,"Run sis roll --resume before starting another release")}static async resume(e){let t=await Re.loadActive();if(!t)throw new u("No incomplete release found","Run sis roll to start a release");let r=t.data,s=new De(e,r.options);s.ledger=t;let n=r.packages.map((o)=>new z({file:o.file,isPrivate:o.isPrivate,name:o.name,newVersion:o.newVersion,version:o.oldVersion})),i=r.stones.map((o)=>M.fromJson(o));if(s.createdTags=[...r.releaseTags],r.phase==="completed")return await t.complete(),{ledger:s.getLedgerSnapshot(),packages:n,stones:i};try{if(await s.recoverReleaseCommit(r),await nc(t.data),await sc(t.data),await s.ensureLedgerPlan(n,i),r.options.npm){if(n.some((a)=>t.data.operations.npm[a.name]&&!t.data.artifacts[a.name]))await tr(await s.getRepositoryRoot());await s.prepareNpmPublish(n)}if(t.phase==="planned")await t.setPhase("local-ready");return await s.resumeExternalOperations(n,i),{ledger:s.getLedgerSnapshot(),packages:n,stones:i}}catch(o){if(o instanceof u||!s.hasCrossedIrreversibleBoundary())throw o;throw s.createIncompleteReleaseError(o)}}async initializeExternalRelease(e,t,r){if(this.options.dryRun||!this.needsReleaseLedger(r))return;this.ledger=await Re.create({options:{...this.options,npmTag:this.options.npm?fr(e,this.config.get("tag")):he,publishOnly:r},packages:e.map((s)=>({file:s.file,isPrivate:s.isPrivate,name:s.name,newVersion:s.newVersion,version:s.version})),stones:t})}async finalizeExternalRelease(e,t){if(!this.ledger)return;if(this.options.npm||this.ledger.data.options.publishOnly)await tr(await this.getRepositoryRoot());let r=await se();await this.ensureExpectedReleaseTree(this.ledger.data,r),await it(this.ledger.data,r),await this.ledger.setReleaseCommit(r),await this.ensureLedgerPlan(e,t)}async markExternalReleaseReady(){if(this.ledger)await this.ledger.setPhase("local-ready")}async completeRelease(){if(this.ledger)await this.ledger.complete()}async getProvider(){if(!this.provider){let e=this.ledger?.data.operations.push?.destination,t=Ps(e);this.provider=await vt(t)}return this.provider}async initCommitLinks(){if(this.commitUrlFn!==null)return;let e=this.ledger?.data.operations.push?.destination,t=Ps(e);if(t){this.commitUrlFn=ln(t);return}let r=await this.remoteParser.getRemoteInfo();this.commitUrlFn=r?.commitUrl??null}async preflight(e,t){if(this.options.dryRun)return;await De.assertNoActiveRelease();let r=await this.getOwnedPaths(e,t);await Qa(r,await this.getRepositoryRoot());let s=r.map((i)=>qe(i));if((await I(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${s}`.quiet(),"Failed to inspect release files")).stdout.length===0)return;throw new u("Release files have uncommitted changes",`Commit or stash these files:
|
|
166
|
+
${s}`}function za(e){let{author:t,email:r}=e,s=t.trim(),n=r?.trim()??"";if(!s&&!n)return[];if(!s||!/^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/.test(n))throw new u("Invalid release commit author","Set valid commit.author and commit.email");return["--author",`${s} <${n}>`]}function Ka(e){let{author:t,email:r}=e,s={...process.env};if(!t)return s;if(s.GIT_COMMITTER_NAME=t,r)s.GIT_COMMITTER_EMAIL=r;return s}function as(e,t){let{filename:r,root:s}=e,n=t.map((i)=>bd(wd(i.file),r));if(s)n.push(r);return n}import{mkdtemp as kd,rm as xd}from"fs/promises";import{tmpdir as Td}from"os";import{join as rc}from"path";import{createHash as $d}from"crypto";import{lstat as Pd,realpath as Ya}from"fs/promises";import{dirname as Rd,isAbsolute as Sd,relative as Xa,resolve as An,sep as Cd}from"path";async function I(e,t){try{return await e()}catch(r){let s=cs(r);throw Error(s?`${t}: ${s}`:t)}}function cs(e){let t=vd(e);if(t)return t;return e instanceof Error?e.message:String(e)}function vd(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}function qe(e){return`:(top,literal)${e}`}async function se(){let t=(await I(()=>Bun.$`git rev-parse HEAD`.quiet(),"Failed to resolve release commit")).stdout.toString().trim();if(!t)throw Error("Release commit is empty");return t}async function On(){let e=await Bun.$`git symbolic-ref -q HEAD`.quiet().nothrow();if(e.exitCode===1)return null;if(e.exitCode!==0)throw new u("Failed to resolve the current Git reference");return e.stdout.toString().trim()||null}async function Za(e){let t=await Bun.$`git rev-parse --verify ${e}`.quiet().nothrow();if(t.exitCode!==0)return null;return t.stdout.toString().trim()||null}async function _n(e){let t=e.map((o)=>qe(o)),[r,s,n]=await Promise.all([Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${t}`.quiet(),Bun.$`git diff --cached --binary --no-ext-diff -- ${t}`.quiet(),Bun.$`git diff --binary --no-ext-diff -- ${t}`.quiet()]),i=$d("sha256");for(let o of[r.stdout,s.stdout,n.stdout])i.update(String(o.length)),i.update("\x00"),i.update(o);return i.digest("hex")}function Qa(e,t){let r=Sd(t)?An(t):An(e,t),s=Xa(e,r);if(!s||oe(s))throw new u(`Release-owned path is outside the repository: ${t}`);return s.split(Cd).join("/")}async function ec(e,t){let r=await Ya(t);for(let s of e){let n=An(t,s),i=await Pd(n).catch(()=>null);if(i?.isSymbolicLink())throw new u(`Release-owned path is a symbolic link: ${s}`);let o=i?n:Rd(n),a=await Ya(o);if(oe(Xa(r,a)))throw new u(`Release-owned path escapes the repository: ${s}`)}}async function Ln(e){let t=e.map((r)=>qe(r));await I(()=>Bun.$`git reset --quiet HEAD -- ${t}`.quiet(),"Failed to unstage release-owned files")}async function tr(e){if((await rr(e)).length===0)return;throw new u("Repository source files changed after the release commit","Commit or stash all source changes before preparing npm artifacts")}async function rr(e){return await Pn(e),(await I(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all --ignore-submodules=none`.cwd(e).quiet(),"Failed to inspect release source files")).stdout}async function tc(e,t,r,s){let n=[];if(e)n.push(`update ${e.ref??"HEAD"} ${e.baseCommit} ${e.oid}`);for(let a of t){let c=r.get(a);if(!c)throw Error(`Missing rollback target for release tag ${a}`);n.push(`delete refs/tags/${a} ${c}`)}if(n.length===0)return;let i=await s(),o=Buffer.from(["start",...n,"prepare","commit",""].join(`
|
|
167
|
+
`));await I(async()=>{let a=Bun.spawn(["git","update-ref","--stdin"],{cwd:i,stderr:"pipe",stdin:o,stdout:"pipe"}),[c,l]=await Promise.all([a.exited,new Response(a.stderr).text()]);if(c!==0)throw Error(l.trim()||`git update-ref exited with code ${c}`)},"Failed to atomically restore release refs")}async function sc(e,t,r){let s=await kd(rc(Td(),"sisyphus-index-")),n=rc(s,"index"),i={...process.env,GIT_INDEX_FILE:n},o=t.map((a)=>qe(a));try{await I(()=>Bun.$`git read-tree ${e}`.cwd(r).env(i).quiet(),"Failed to initialize release tree"),await I(()=>Bun.$`git add -A -- ${o}`.cwd(r).env(i).quiet(),"Failed to build release tree");let c=(await I(()=>Bun.$`git write-tree`.cwd(r).env(i).quiet(),"Failed to write release tree")).stdout.toString().trim();if(!c)throw Error("Git returned an empty release tree object ID");return c}finally{await xd(s,{force:!0,recursive:!0})}}async function nc(e){if(!e.releaseCommit)throw new u(`Release ${e.id} has no recorded source commit`,"No external operation will be retried; inspect the local release state manually");let t=await se();if(t!==e.releaseCommit)throw new u(`Release ${e.id} was prepared from ${e.releaseCommit}, but HEAD is ${t}`,`Check out ${e.releaseCommit} before resuming`);if(!e.expectedReleaseTree)throw new u(`Release ${e.id} has no recorded expected release tree`,"No external operation will be retried; inspect the release ledger manually");await it(e,t)}async function ic(e){let{baseCommit:t,releaseCommit:r}=e;if(!r||r===t)return;if(await se()!==t)return;if(!await Ed(r)||!await Id())return;await it(e,r),await I(()=>Bun.$`git checkout --quiet --detach ${r}`.quiet(),`Failed to check out release commit ${r} from base commit ${t}`)}async function Ed(e){return(await Bun.$`git cat-file -e ${`${e}^{commit}`}`.quiet().nothrow()).exitCode===0}async function Id(){return(await I(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=no --ignore-submodules=none`.quiet(),"Failed to inspect tracked files before resuming")).stdout.length===0}async function it(e,t){if(!e.expectedReleaseTree)throw new u(`Release ${e.id} has no recorded expected release tree`,"No external operation was attempted; inspect the release state manually");if(e.options.publishOnly){if(t!==e.baseCommit)throw new u(`Publish-only release ${e.id} must use commit ${e.baseCommit}, found ${t}`,`Check out ${e.baseCommit} before resuming`)}else await Mn(t,e.baseCommit,e.id);await Dn(t,e.expectedReleaseTree,e.id)}async function Mn(e,t,r){let s=await I(()=>Bun.$`git rev-list --parents -n 1 ${e}`.quiet(),"Failed to resolve release commit parent"),[n,...i]=s.stdout.toString().trim().split(/\s+/);if(n===e&&i.length===1&&i[0]===t)return;let o=r?` for release ${r}`:"";throw new u(`Release commit parent${o} does not match ${t}`,"No external operation was attempted; inspect the release commit ancestry")}async function Dn(e,t,r){let s=await Nn(e);if(s===t)return;let n=r?` for release ${r}`:"";throw new u(`Release commit tree${n} is ${s}, expected ${t}`,"No external operation was attempted; inspect the release commit for unrelated tracked changes")}async function Nn(e){let t=`${e}^{tree}`,s=(await I(()=>Bun.$`git rev-parse ${t}`.quiet(),"Failed to resolve release commit tree")).stdout.toString().trim();if(!s)throw Error(`Git returned an empty tree object ID for ${e}`);return s}import{dirname as Qd}from"path";import{createHash as wc,randomUUID as Bd}from"crypto";import{link as Vd,lstat as pr,mkdir as hs,open as Ud,readFile as bc,realpath as Je,rename as Gd,rm as Hd,unlink as qd}from"fs/promises";import{dirname as cr,isAbsolute as yc,join as lr,relative as vc,resolve as $e,sep as Wd}from"path";var sr=1,Tt=["planned","local-ready","external","completed"],jn=["pending","started","completed"],Ad=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,ot=/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/,oc=/^sha512-[0-9A-Za-z+/]{86}==$/,ac=/^[0-9A-Za-z][0-9A-Za-z._/-]*$/,Fn=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,cc=/^(?:linux:[0-9a-f-]{36}:[0-9]+|ps:.+|windows:[0-9]+)$/i,ls=2,lc=3,uc=19;class b extends Error{_tag="ReleaseLedgerError"}function P(e,t){throw new b(`Invalid release ledger at ${e}: ${t}`)}function nr(e,t){if(typeof e!=="string")P(t,"must be a string");return e}function _(e,t){let r=nr(e,t);if(!r.trim())P(t,"must be nonempty");return r}function ir(e,t){let r=_(e,t);if(!Ad.test(r))P(t,`invalid release ID ${r}`);return r}function us(e){let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function X(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function D(e){return e instanceof Error?e.message:String(e)}import{randomUUID as Od}from"crypto";import{constants as pc,readFileSync as dc}from"fs";import{link as _d,lstat as at,open as Un,readFile as mc,rename as Ld,rm as ds,unlink as ms}from"fs/promises";import{hostname as gc}from"os";import{dirname as We,join as Bn}from"path";async function ar(e){let t=Bn(e,".write.lock");for(let r=0;r<lc;r+=1){let s=hc(process.pid);if(!s)throw new b("Failed to identify the release ledger lock owner process");let n={acquiredAt:new Date().toISOString(),hostname:gc(),ownerId:Od(),pid:process.pid,processStartedAt:s,schemaVersion:ls},i=gs(e,n.ownerId,"owner");await Md(i,n);try{await _d(i,t)}catch(a){if(await ds(i,{force:!0}),!X(a,"EEXIST"))throw new b(`Failed to acquire release ledger lock at ${t}: ${D(a)}`);let c=await Dd(t);if(!c)continue;await Nd(c);continue}let o={lockPath:t,metadata:n,ownerPath:i};try{return await ae(e),o}catch(a){try{await Et(o)}catch(c){throw AggregateError([a,c],`Failed to durably acquire release ledger lock at ${t}`)}throw new b(`Failed to durably acquire release ledger lock at ${t}: ${D(a)}`)}}throw new b(`Release ledger is locked by another process at ${t}: lock changed during acquisition`)}async function Md(e,t){let r;try{r=await Un(e,"wx",384),await r.writeFile(`${JSON.stringify(t)}
|
|
168
|
+
`,"utf-8"),await r.sync()}catch(s){throw await ds(e,{force:!0}),new b(`Failed to create release ledger lock owner: ${D(s)}`)}finally{await r?.close()}await ae(We(e))}async function Dd(e){let t,r,s;try{s=await Un(e,pc.O_RDONLY|pc.O_NOFOLLOW),t=await s.stat(),r=await s.readFile("utf-8")}catch(p){if(X(p,"ENOENT"))return null;throw new b(`Failed to inspect release ledger lock at ${e}: ${D(p)}`)}finally{await s?.close()}if(!t.isFile())throw new b(`Release ledger is locked by another process at ${e}: lock owner is unknown`);let n=null;try{n=Vn(JSON.parse(r))}catch{n=null}if(!n)return await ps(e,t,"lock metadata is malformed");let i=gs(We(e),n.ownerId,"owner"),o=gs(We(e),n.ownerId,"claim"),a;try{a=await at(i)}catch(p){if(X(p,"ENOENT")){try{await at(o)}catch(m){if(X(m,"ENOENT"))return await ps(e,t,"stale lock ownership is incomplete");throw new b(`Failed to inspect release ledger lock claim: ${D(m)}`)}throw new b(`Release ledger is locked by another process at ${e}: stale lock recovery is incomplete (claim ${o} remains; remove both after verifying the owner process is dead)`)}throw new b(`Failed to inspect release ledger lock owner: ${D(p)}`)}if(!a.isFile()||a.isSymbolicLink())return await ps(e,t,"stale lock ownership is invalid");let c=null;try{c=Vn(JSON.parse(await mc(i,"utf-8")))}catch{c=null}if(!c||!Fd(n,c))return await ps(e,t,"stale lock ownership is invalid");if(!await fc(e,t))return null;if(!or(t,a))return{lockPath:e,lockStat:t,metadata:n,ownerPath:i,ownerStat:a};if(n.hostname!==gc())throw new b(`Release ledger is locked by another process at ${e}: lock owner is on an unknown host ${n.hostname} (pid ${n.pid})`);let l=jd(n);if(l==="alive")throw new b(`Release ledger is locked by another process at ${e}: lock owner is still live (pid ${n.pid} on ${n.hostname})`);if(l==="unknown")throw new b(`Release ledger is locked by another process at ${e}: lock owner liveness is unknown (pid ${n.pid} on ${n.hostname})`);return{lockPath:e,lockStat:t,metadata:n,ownerPath:i,ownerStat:a}}async function Nd(e){let t=gs(We(e.lockPath),e.metadata.ownerId,"claim");if(e.ownerPath!==t)try{await Ld(e.ownerPath,t),await ae(We(e.lockPath))}catch(n){if(X(n,"ENOENT")||X(n,"EEXIST"))return;throw new b(`Failed to claim stale release ledger lock: ${D(n)}`)}let r,s;try{[r,s]=await Promise.all([at(e.lockPath),at(t)])}catch(n){if(X(n,"ENOENT"))return;throw new b(`Failed to verify stale release ledger lock: ${D(n)}`)}if(!or(e.lockStat,r))return;if(!or(e.ownerStat,s))return;try{await ms(e.lockPath),await ae(We(e.lockPath)),await ms(t),await ae(We(e.lockPath))}catch(n){if(X(n,"ENOENT"))return;throw new b(`Failed to recover stale release ledger lock: ${D(n)}`)}}async function Et(e){let t,r;try{[t,r]=await Promise.all([at(e.lockPath),at(e.ownerPath)])}catch(n){if(X(n,"ENOENT"))throw await ds(e.ownerPath,{force:!0}),new b("Failed to release ledger write lock: ownership record is missing");throw new b(`Failed to inspect release ledger lock during release: ${D(n)}`)}if(!or(t,r))throw await ds(e.ownerPath,{force:!0}),new b("Failed to release ledger write lock: ownership changed");let s=null;try{s=Vn(JSON.parse(await mc(e.lockPath,"utf-8")))}catch{s=null}if(s?.ownerId!==e.metadata.ownerId)throw new b("Failed to release ledger write lock: owner identity changed");try{await ms(e.lockPath),await ms(e.ownerPath),await ae(We(e.lockPath))}catch(n){throw new b(`Failed to release ledger write lock: ${D(n)}`)}}function Vn(e){if(typeof e!=="object"||e===null||Array.isArray(e))return null;let t=e,r=Object.keys(t);if(r.length!==6||!r.every((s)=>["acquiredAt","hostname","ownerId","pid","processStartedAt","schemaVersion"].includes(s))||t.schemaVersion!==ls||typeof t.ownerId!=="string"||!Fn.test(t.ownerId)||typeof t.hostname!=="string"||!t.hostname||typeof t.pid!=="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.processStartedAt!=="string"||!cc.test(t.processStartedAt)||typeof t.acquiredAt!=="string"||!us(t.acquiredAt))return null;return{acquiredAt:t.acquiredAt,hostname:t.hostname,ownerId:t.ownerId,pid:t.pid,processStartedAt:t.processStartedAt,schemaVersion:ls}}function gs(e,t,r){if(!Fn.test(t))throw new b(`Release ledger is locked by another process at ${Bn(e,".write.lock")}: lock owner identity is malformed`);return Bn(e,`.write.lock.${t}.${r}`)}function jd(e){try{process.kill(e.pid,0)}catch(r){return X(r,"ESRCH")?"dead":"unknown"}let t=hc(e.pid);if(!t)return"unknown";if(t.split(":",1)[0]!==e.processStartedAt.split(":",1)[0])return"unknown";return t===e.processStartedAt?"alive":"dead"}function hc(e){if(process.platform==="linux")try{let t=dc("/proc/sys/kernel/random/boot_id","utf-8").trim(),r=dc(`/proc/${e}/stat`,"utf-8"),s=r.lastIndexOf(")"),n=s<0?void 0:r.slice(s+1).trim().split(/\s+/)[uc];if(t&&n)return`linux:${t}:${n}`}catch{}if(process.platform==="win32")try{let t=Bun.spawnSync({cmd:["powershell.exe","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().Ticks`],stderr:"pipe",stdout:"pipe"}),r=t.stdout.toString().trim();if(t.exitCode===0&&/^[0-9]+$/.test(r))return`windows:${r}`}catch{return null}try{let t=Bun.spawnSync({cmd:["ps","-o","lstart=","-p",String(e)],env:{...process.env,LC_ALL:"C",TZ:"UTC"},stderr:"pipe",stdout:"pipe"});if(t.exitCode!==0)return null;let r=t.stdout.toString().trim().replace(/\s+/g," ");return r?`ps:${r}`:null}catch{return null}}function or(e,t){return e.dev===t.dev&&e.ino===t.ino}async function fc(e,t){try{return or(t,await at(e))}catch(r){if(X(r,"ENOENT"))return!1;throw new b(`Failed to verify release ledger lock at ${e}: ${D(r)}`)}}async function ps(e,t,r){if(!await fc(e,t))return null;throw new b(`Release ledger is locked by another process at ${e}: ${r}`)}function Fd(e,t){return e.schemaVersion===t.schemaVersion&&e.ownerId===t.ownerId&&e.hostname===t.hostname&&e.pid===t.pid&&e.processStartedAt===t.processStartedAt&&e.acquiredAt===t.acquiredAt}async function ae(e){let t=await Un(e,"r");try{await t.sync()}finally{await t.close()}}async function Gn(e){let t=$e(e),r=await Bun.$`git rev-parse --show-toplevel`.cwd(t).quiet().nothrow();if(r.exitCode!==0)throw new b(`Failed to resolve repository root from ${t}: ${r.stderr.toString().trim()||"git exited unsuccessfully"}`);let s=r.stdout.toString().trim();if(!s)throw new b(`Failed to resolve repository root from ${t}: empty git output`);let n=yc(s)?$e(s):$e(t,s),i=await Bun.$`git rev-parse --git-path sisyphus/release`.cwd(n).quiet().nothrow();if(i.exitCode!==0)throw new b(`Failed to resolve release ledger git path from ${n}: ${i.stderr.toString().trim()||"git exited unsuccessfully"}`);let o=i.stdout.toString().trim();if(!o)throw new b(`Failed to resolve release ledger git path from ${n}: empty git output`);let a=yc(o)?$e(o):$e(n,o);return{activePath:lr(a,"active.json"),artifactsRoot:lr(a,"artifacts"),historyDirectory:lr(a,"history"),releaseDirectory:a,removingPath:lr(a,"removing.json"),repositoryRoot:n}}async function $c(e,t){let r=`${t}^{tree}`,s=await Bun.$`git rev-parse ${r}`.cwd(e).quiet().nothrow(),n=s.stdout.toString().trim();if(s.exitCode!==0||!ot.test(n))throw new b(`Cannot resolve release tree for commit ${t}`);return n}async function dr(e,t){await hs(e.releaseDirectory,{recursive:!0}),await ze(e.releaseDirectory,"release directory"),await hs(e.artifactsRoot,{recursive:!0}),await ze(e.artifactsRoot,"artifacts root"),await hs(hr(e,t),{recursive:!0}),await Pc(e,t)}async function Pc(e,t){let r=hr(e,t);await ze(e.releaseDirectory,"release directory"),await ze(e.artifactsRoot,"artifacts root"),await ze(r,`artifacts directory for release ${t}`);let s=await Je(e.releaseDirectory),n=await Je(e.artifactsRoot),i=await Je(r);return ur(s,n,"Artifacts root escapes the release directory"),ur(n,i,`Artifacts directory for release ${t} escapes the artifacts root`),i}async function Rc(e){await ze(e.releaseDirectory,"release directory"),await hs(e.historyDirectory,{recursive:!0}),await ze(e.historyDirectory,"history directory");let t=await Je(e.releaseDirectory),r=await Je(e.historyDirectory);ur(t,r,"History directory escapes the release directory")}async function fs(e,t){for(let[r,s]of Object.entries(e.artifacts)){let n=$e(t.releaseDirectory,s.path);if(await gr(t,e.id,n),await It(n)!==s.integrity)throw new b(`Invalid release ledger artifact for ${r}: sha512 integrity mismatch`)}}async function mr(e,t){let r=await Je(t.repositoryRoot);for(let s of e.packages){let n=$e(t.repositoryRoot,s.file),i;try{i=await pr(n)}catch(a){throw new b(`Invalid package manifest for ${s.name} at ${s.file}: ${D(a)}`)}if(!i.isFile()||i.isSymbolicLink())throw new b(`Invalid package manifest for ${s.name} at ${s.file}: expected a regular file`);let o=await Je(n);ur(r,o,`Package manifest for ${s.name} escapes the repository: ${s.file}`)}}async function gr(e,t,r){let s=await Pc(e,t),n;try{n=await pr(r)}catch(o){throw new b(`Invalid release artifact at ${r}: ${D(o)}`)}if(!n.isFile()||n.isSymbolicLink())throw new b(`Invalid release artifact at ${r}: expected a regular file`);let i=await Je(r);ur(s,i,`Release artifact escapes artifacts directory: ${r}`)}async function Hn(e,t,r,s){let n=`${JSON.stringify(t,null,2)}
|
|
169
|
+
`,i=lr(cr(e),`.${Bd()}.json.tmp`),o=await ar(cr(e));try{if(await ze(cr(e),"release directory"),r){await Jd(e,"active release ledger");let c;try{c=JSON.parse(await bc(e,"utf-8"))}catch(l){throw new b(`Failed to read active release ledger at ${e} before writing: ${D(l)}`)}if(c.updatedAt!==s)throw new b("Active release ledger changed in another process")}let a=await Ud(i,"wx",384);try{await a.writeFile(n,"utf-8"),await a.sync()}finally{await a.close()}if(r)await Gd(i,e);else{try{await Vd(i,e)}catch(c){if(X(c,"EEXIST"))throw new b(`Cannot create release ledger: active ledger already exists at ${e}`);throw c}await qd(i)}await ae(cr(e))}catch(a){await qn(i,a,`Failed to clean temporary ledger file at ${i}`)}finally{await Et(o)}}async function qn(e,t,r){try{await Hd(e,{force:!0})}catch(s){throw AggregateError([t,s],r)}throw t}async function It(e){let t;try{t=await bc(e)}catch(r){throw new b(`Failed to read release artifact at ${e}: ${D(r)}`)}return`sha512-${wc("sha512").update(t).digest("base64")}`}async function ze(e,t){let r;try{r=await pr(e)}catch(s){throw new b(`Invalid ${t} at ${e}: ${D(s)}`)}if(!r.isDirectory()||r.isSymbolicLink())throw new b(`Invalid ${t} at ${e}: expected a real directory`)}async function Jd(e,t){let r;try{r=await pr(e)}catch(s){throw new b(`Invalid ${t} at ${e}: ${D(s)}`)}if(!r.isFile()||r.isSymbolicLink())throw new b(`Invalid ${t} at ${e}: expected a regular file`)}async function ct(e){try{return await pr(e),!0}catch(t){if(X(t,"ENOENT"))return!1;throw t}}function hr(e,t){return $e(e.artifactsRoot,ir(t,"id"))}function Wn(e,t,r){let s=`${wc("sha256").update(r).digest("hex")}.tgz`;return $e(hr(e,t),s)}function ys(e,t,r){return vc(e.releaseDirectory,Wn(e,t,r)).split(Wd).join("/")}function Jn(e,t){let r=$e(e.historyDirectory,`${ir(t,"id")}.json`);if(cr(r)!==$e(e.historyDirectory))throw new b(`Invalid release history path for ID ${t}`);return r}function ur(e,t,r){let s=vc(e,t);if(!s||oe(s))throw new b(r)}import{readFile as zd}from"fs/promises";import{dirname as Sc}from"path";var Kd=/^[A-Za-z][0-9A-Za-z._-]*$/,Yd=/-\d{14,}$/,Xd=/^(?:[vV]?\d+(?:\.(?:\d+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?|[xX])$/;function Cc(e){return Kd.test(e)&&!Xd.test(e)}function bs(e){let t=(e||he).trim();if(!Cc(t))throw new u(`Invalid npm dist-tag "${t}"`,"Use a non-semver tag containing only letters, numbers, dots, underscores, or hyphens");return t}function fr(e,t){let r=bs(t),s=new Set;for(let n of e){if(n.isPrivate)continue;let i=n.newVersion??n.version,o=Ae(i);if(!o)throw new u(`Cannot derive an npm dist-tag for ${n.name}@${i}`,"The version is not valid SemVer; fix it before publishing");if(o.prerelease.length===0){s.add(r);continue}let a=Zd(o);if(!a||!Cc(a))throw new u(`Cannot derive an npm dist-tag for ${n.name}@${i}`,"Use a prerelease identifier that is a valid npm dist-tag (e.g. beta, rc)");s.add(a)}if(s.size<=1)return[...s][0]??r;throw new u(`Release mixes npm dist-tags (${[...s].sort().join(", ")})`,"Roll stable and prerelease packages separately, or give every prerelease the same tag")}function Zd(e){let t=zt(e);if(t)return t;let[r]=e.prerelease;if(typeof r!=="string")return;return r.replace(Yd,"")}function kc(e){return e.startsWith("@")?e.split("/")[0]:void 0}function At(e,t){let r=kc(e);return r?[`--${r}:registry=${t}`]:[]}async function xc(e){let t=kc(e.name);if(t){let o=await Bun.$`npm config get ${`${t}:registry`}`.cwd(Sc(e.file)).quiet().nothrow();if(o.exitCode===0){let a=o.stdout.toString().trim();if(a&&a!=="undefined"&&a!=="null"){let c=ws(a);if(c)return c;throw new u(`Invalid ${t}:registry for ${e.name}`,"Registry must be a credential-free HTTP or HTTPS URL")}}}let s=(await Tc(e)).publishConfig;if(s!==void 0){if(typeof s!=="object"||s===null||Array.isArray(s))throw new u(`Invalid publishConfig in ${e.name}`,"publishConfig must be an object");let o=Reflect.get(s,"registry");if(o!==void 0){if(typeof o!=="string")throw new u(`Invalid publishConfig.registry in ${e.name}`,"Registry must be an HTTP or HTTPS URL");let a=ws(o);if(!a)throw new u(`Invalid publishConfig.registry in ${e.name}`,"Registry must be a credential-free HTTP or HTTPS URL");return a}}let n=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(n){let o=ws(n);if(o)return o}let i=await Bun.$`npm config get registry`.cwd(Sc(e.file)).quiet().nothrow();if(i.exitCode===0){let o=i.stdout.toString().trim();if(o&&o!=="undefined"&&o!=="null"){let a=ws(o);if(a)return a}}throw new u(`Cannot resolve a credential-free npm registry for ${e.name}`,"Configure registry or @scope:registry as an HTTP or HTTPS URL without embedded credentials")}function ws(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password||t.search||t.hash)return;return t.href}catch{return}}function vs(e){let t=Array.isArray(e)?e.length===1?e[0]:void 0:e;if(typeof t!=="object"||t===null||Array.isArray(t))return;let r=Reflect.get(t,"name"),s=Reflect.get(t,"version"),n=Reflect.get(t,"dist");if(typeof n!=="object"||n===null||Array.isArray(n))return;let i=Reflect.get(n,"integrity");if(typeof r!=="string"||typeof s!=="string"||typeof i!=="string")return;return{integrity:i,name:r,version:s}}async function Tc(e){let t;try{t=await zd(e.file,"utf-8")}catch(s){throw Error(`Failed to read ${e.name}: ${cs(s)}`)}let r;try{r=JSON.parse(t)}catch(s){throw Error(`Failed to parse ${e.name}: ${cs(s)}`)}if(typeof r!=="object"||r===null||Array.isArray(r))throw Error(`Invalid ${e.name} manifest object`);return r}async function Ec(e){let t=[];for(let r of e){let n=(await Tc(r)).private;if(n!==void 0&&typeof n!=="boolean")throw Error(`Failed to validate ${r.name} manifest: "private" must be a boolean`);if(n)continue;t.push(r)}return t}var em=/\bE404\b/,tm=/cannot publish over|EPUBLISHCONFLICT/i;async function Ic(e,t,r){let s=e.data.artifacts[t.name];if(!s)throw Error(`Release artifact is missing for ${t.name}`);let n=e.data.operations.npmRegistries[t.name];if(!n)throw Error(`Npm registry is not configured for ${t.name}`);let i=t.newVersion??t.version,o=`${t.name}@${i}`,a=At(t.name,n),c=await Bun.$`npm view ${o} --json --registry ${n} ${a}`.cwd(Qd(t.file)).quiet().nothrow();if(c.exitCode!==0){if(!em.test(`${c.stdout.toString()}
|
|
170
|
+
${c.stderr.toString()}`))throw new u(`Cannot safely resume npm publication for ${o}: ${n} did not confirm whether it exists`,"Check the registry connectivity and authentication, then re-run sis roll --resume");await rm(e,t,o,n,r);return}let l;try{l=JSON.parse(c.stdout.toString())}catch{throw new u(`Cannot safely resume npm publication for ${o}`,"Registry metadata is not valid JSON")}let p=vs(l);if(!p)throw new u(`Cannot safely resume npm publication for ${o}`,"Registry metadata does not report name, version, and dist.integrity; verify the upload manually");if(p.name!==t.name||p.version!==i||p.integrity!==s.integrity)throw new u(`Cannot safely resume npm publication for ${o}: artifact integrity does not match`,"Do not republish this version; compare the registry artifact with the durable release artifact");await e.markNpm(t.name,"completed")}async function rm(e,t,r,s,n){let i=e.resolveArtifactPath(t.name);if(await It(i)!==e.data.artifacts[t.name]?.integrity)throw new u(`Cannot safely republish ${r}: the durable artifact no longer matches the release ledger`,`Restore ${i} from the original release before resuming`);try{await n()}catch(o){if(o instanceof Error&&tm.test(o.message))throw new u(`${r} was already accepted by ${s} but is not listed yet`,"npm may still be processing or holding the upload; re-run sis roll --resume once the version is visible");throw o}await e.markNpm(t.name,"completed")}import{resolve as sm}from"path";import{pathToFileURL as nm}from"url";async function $s(e,t){let r=et(e);return{canonicalUrl:await im(e,t),...r?{owner:r.owner,provider:r.provider,repo:r.repo}:{}}}async function im(e,t){let r=null;try{r=new URL(e)}catch{r=null}if(r){let n=r.protocol==="ssh:"||r.protocol==="git+ssh:";if(r.password||r.username&&!n)throw new u("Push URL contains embedded credentials","Configure git authentication outside the remote URL");return r.search="",r.hash="",r.href}let s=e.match(/^(?:([^@/\s]+)@)?([^:/\s]+):(.+)$/);if(s?.[2]&&s[3])return`ssh://${s[1]?`${s[1]}@`:""}${s[2].toLowerCase()}/${s[3].replace(/^\/+/,"")}`;return nm(sm(await t(),e)).href}function Ps(e){if(!e?.provider||!e.owner||!e.repo)return;return{owner:e.owner,provider:e.provider,repo:e.repo}}async function Rs(e){let r=(await I(()=>Bun.$`git remote get-url --push --all ${e}`.quiet(),`Failed to resolve push URL for ${e}`)).stdout.toString().trim().split(`
|
|
171
|
+
`).filter(Boolean);if(r.length!==1)throw new u(`Push remote ${e} must have exactly one push URL, found ${r.length}`,"Remove additional push URLs before starting or resuming a release");let[s]=r;if(!s)throw new u(`Push remote ${e} has no URL`);return s}async function Ot(e,t){let r=await Rs(e.remote),s=await $s(r,t);if(JSON.stringify(s)!==JSON.stringify(e.destination))throw new u(`Push remote ${e.remote} no longer matches the recorded release destination`,"Restore the original remote before resuming the release");return r}async function Kn(e){for(let t of e){let s=(await I(()=>Bun.$`git rev-parse ${t.source}`.quiet(),`Failed to resolve ${t.source}`)).stdout.toString().trim();if(s!==t.oid)throw new u(`Release ref ${t.source} points to ${s}, expected ${t.oid}`,"Do not move release refs before the release completes")}}async function Ss(e,t){let r=await Ot(e,t),s=e.refs.map((n)=>`${n.oid}:${n.destination}`);await I(()=>Bun.$`git push --atomic ${r} ${s}`.quiet(),"Failed to atomically push release refs")}async function Ac(e,t,r=e.refs){let s=await Yn(e,r,t),n=r.find((i)=>s.get(i.destination)!==i.oid);if(n)throw new u(`Cannot safely resume remote push: ${n.destination} is not at ${n.oid}`,"The previous push may not have completed; inspect the remote refs manually")}async function Yn(e,t,r){let s=await Ot(e,r),n=t.map((o)=>o.destination),i=await I(()=>Bun.$`git ls-remote --refs ${s} ${n}`.quiet(),"Failed to inspect remote release refs");return new Map(i.stdout.toString().trim().split(`
|
|
172
|
+
`).filter(Boolean).map((o)=>{let[a="",c=""]=o.split("\t");return[c,a]}))}async function Xn(){let e=await Bun.$`git symbolic-ref --quiet --short HEAD`.quiet().nothrow();if(e.exitCode!==0)return;return e.stdout.toString().trim()||void 0}async function Oc(){let e=await Xn();if(!e)throw new u("Cannot push a release from detached HEAD","Check out the branch that should receive the release");return{branch:e,remote:await Zn(e)}}async function Zn(e){let t=e?await zn(`branch.${e}.pushRemote`):null,r=await zn("remote.pushDefault"),s=e?await zn(`branch.${e}.remote`):null,n=t??r??s;if(!n){let o=(await I(()=>Bun.$`git remote`.quiet(),"Failed to list git remotes")).stdout.toString().trim().split(`
|
|
173
|
+
`).filter(Boolean);if(o.length===1&&o[0]==="origin")n="origin"}if(!n){let i=e?` for branch ${e}`:"";throw new u(`No push remote is configured${i}`,e?"Configure a branch push remote or remote.pushDefault":"Configure remote.pushDefault")}return await I(()=>Bun.$`git remote get-url --push ${n}`.quiet(),`Invalid push remote ${n}`),n}async function zn(e){let t=await Bun.$`git config --get ${e}`.quiet().nothrow();if(t.exitCode===1)return null;if(t.exitCode!==0){let s=t.stderr.toString().trim();throw Error(s?`Failed to read git config ${e}: ${s}`:`Failed to read git config ${e}`)}let r=t.stdout.toString().trim();if(!r)throw Error(`Git config ${e} is empty`);return r}var om=1;async function Lc(e,t,r){let s=await Yn(t,t.refs,r),n=[];for(let i of t.refs){let o=s.get(i.destination);if(o===i.oid)continue;if(!o){n.push(i);continue}if(i.destination.startsWith("refs/heads/")){if(await am(o,t,r),await _c(i.oid,o))continue;if(await _c(o,i.oid)){n.push(i);continue}}throw new u(`Cannot safely resume remote push: ${i.destination} is not at ${i.oid}`,"The remote ref diverged from the recorded release; inspect it manually before resuming")}if(n.length>0)await Ss({...t,refs:n},r);await e.markPush("completed")}async function am(e,t,r){if((await Bun.$`git cat-file -e ${`${e}^{commit}`}`.quiet().nothrow()).exitCode===0)return;let n=await Ot(t,r);await I(()=>Bun.$`git fetch --no-tags --no-write-fetch-head --no-recurse-submodules ${n} ${e}`.quiet(),"Failed to inspect the remote branch ancestry")}async function _c(e,t){let r=await Bun.$`git merge-base --is-ancestor ${e} ${t}`.quiet().nothrow();if(r.exitCode===0)return!0;if(r.exitCode===om)return!1;throw Error(`Failed to inspect remote branch ancestry: ${r.stderr.toString().trim()}`)}function Qn(e,t,r){let s=t.newVersion??t.version;return{notes:lm(cm(e,t.name),t,r),tag:`${t.name}@${s}`,title:`${t.name} v${s}`}}function cm(e,t){return e.filter((r)=>r.affectsPackage(t))}function lm(e,t,r){let s=[],n=t.newVersion??t.version;if(s.push(`\`${t.name}\` ${t.version} \u2192 ${n}`),e.length===0)return s.join(`
|
|
174
|
+
`);s.push(""),s.push("<details>"),s.push(`<summary>Stones (${e.length})</summary>`),s.push("");for(let i of e){if(s.push(`### ${i.message}`),s.push(""),i.description)s.push(i.description),s.push("");let o=um(i.commits,t.name);if(o.length>0){s.push("<details>"),s.push(`<summary>Commits (${o.length})</summary>`),s.push("");for(let a of o)s.push(pm(a,r));s.push(""),s.push("</details>"),s.push("")}}return s.push("</details>"),s.join(`
|
|
175
|
+
`)}function um(e,t){if(!e)return[];return e.filter((r)=>r.packages.includes(t))}function pm(e,t){return`- ${t?`[\`${e.hash}\`](${t(e.hash)})`:`\`${e.hash}\``} ${e.subject}`}import{createHash as Rm,randomUUID as Sm}from"crypto";import{constants as Cm}from"fs";import{copyFile as km,link as xm,lstat as Gc,readFile as ui,rename as Hc,rm as qc,stat as Tm,unlink as Em}from"fs/promises";import{extname as Im,join as Am,resolve as Om}from"path";import{isAbsolute as Mc,relative as dm,resolve as mm}from"path";function si(e){if(Object.values(e.operations.npm).some((t)=>t.state!=="pending"))return!0;if(e.operations.push&&e.operations.push.state!=="pending")return!0;return Object.values(e.operations.providerReleases).some((t)=>t.state!=="pending")}function Dc(e){return e.map((t,r)=>{let s=`create.packages[${r}]`,n=t.oldVersion??t.version;if(t.oldVersion!==void 0&&t.version!==void 0&&t.oldVersion!==t.version)P(s,"oldVersion and version must match when both are provided");return jc({file:t.file,isPrivate:t.isPrivate,name:t.name,newVersion:t.newVersion,oldVersion:n},s)})}function Nc(e){return e.map((t,r)=>{let s=typeof t==="object"&&t!==null&&"toJson"in t&&typeof t.toJson==="function"?t.toJson():t,n;try{n=JSON.parse(JSON.stringify(s))}catch(i){throw new b(`Invalid release ledger at create.stones[${r}]: ${D(i)}`)}return Fc(n,`create.stones[${r}]`)})}function lt(e,t){let r=Z(e,"root");if(ye(r,["schemaVersion","id","baseCommit","createdAt","updatedAt","phase","options","packages","releaseTags","tagsReady","stones","artifacts","operations"],["expectedReleaseTree","releaseCommit"],"root"),r.schemaVersion!==sr)P("schemaVersion",`unsupported schema version ${String(r.schemaVersion)}`);let s=ir(r.id,"id"),n=_t(r.baseCommit,"baseCommit"),i=Cs(r.createdAt,"createdAt"),o=Cs(r.updatedAt,"updatedAt");if(Date.parse(o)<Date.parse(i))P("updatedAt","must not precede createdAt");let a=Bc(r.phase,Tt,"phase","release phase"),c=hm(r.options,"options"),l=fm(r.packages,t.repositoryRoot),p=gm(r.releaseTags,l,c),m=Ke(r.tagsReady,"tagsReady");if(!c.tags&&!m)P("tagsReady","must be true when tags are disabled");let h=ym(r.stones),f=r.expectedReleaseTree===void 0?void 0:_t(r.expectedReleaseTree,"expectedReleaseTree"),g=r.releaseCommit===void 0?void 0:_t(r.releaseCommit,"releaseCommit"),y=bm(r.artifacts,l,t,s),R=vm(r.operations,l,c,i,o),S={artifacts:y,baseCommit:n,createdAt:i,id:s,operations:R,options:c,packages:l,phase:a,releaseTags:p,schemaVersion:sr,stones:h,tagsReady:m,updatedAt:o};if(f!==void 0)S.expectedReleaseTree=f;if(g!==void 0)S.releaseCommit=g;if(c.tags&&m&&!g)P("tagsReady","cannot be true before releaseCommit is recorded");if(a==="completed")oi(S);return S}function gm(e,t,r){if(!Array.isArray(e))P("releaseTags","must be an array");let s=e.map((i,o)=>{let a=_(i,`releaseTags[${o}]`);return ri(`refs/tags/${a}`,`releaseTags[${o}]`),a});if(new Set(s).size!==s.length)P("releaseTags","must not contain duplicates");let n=r.tags?t.map((i)=>`${i.name}@${i.newVersion}`).sort():[];if(JSON.stringify([...s].sort())!==JSON.stringify(n))P("releaseTags","must exactly match the release package versions when tags are enabled");return s}function hm(e,t){let r=Z(e,t);return ye(r,["changelog","createRelease","dryRun","npm","npmTag","publishOnly","push","tags"],[],t),{changelog:Ke(r.changelog,`${t}.changelog`),createRelease:Ke(r.createRelease,`${t}.createRelease`),dryRun:ai(r.dryRun),npm:Ke(r.npm,`${t}.npm`),npmTag:_(r.npmTag,`${t}.npmTag`),publishOnly:Ke(r.publishOnly,`${t}.publishOnly`),push:Ke(r.push,`${t}.push`),tags:Ke(r.tags,`${t}.tags`)}}function fm(e,t){if(!Array.isArray(e)||e.length===0)P("packages","must be a nonempty array");let r=new Set,s=new Set;return e.map((n,i)=>{let o=`packages[${i}]`,a=jc(n,o);if(Mc(a.file))P(`${o}.file`,"must be repository-relative");if(r.has(a.name))P(o,`duplicate package name ${a.name}`);let c=mm(t,a.file),l=dm(t,c);if(!l||oe(l))P(`${o}.file`,"must resolve inside the repository");if(s.has(c))P(o,`duplicate package file ${a.file}`);return r.add(a.name),s.add(c),a})}function jc(e,t){let r=Z(e,t);ye(r,["name","file","oldVersion","newVersion","isPrivate"],[],t);let s=_(r.file,`${t}.file`);if(s.includes("\x00"))P(`${t}.file`,"must not contain a null byte");return{file:s,isPrivate:Ke(r.isPrivate,`${t}.isPrivate`),name:_(r.name,`${t}.name`),newVersion:_(r.newVersion,`${t}.newVersion`),oldVersion:_(r.oldVersion,`${t}.oldVersion`)}}function ym(e){if(!Array.isArray(e))P("stones","must be an array");let t=new Set;return e.map((r,s)=>{let n=Fc(r,`stones[${s}]`);if(t.has(n.id))P(`stones[${s}].id`,`duplicate stone ID ${n.id}`);return t.add(n.id),n})}function Fc(e,t){let r=Z(e,t);ye(r,["id","message"],["tag","description","commits","major","minor","patch","dependency","snapshot"],t);let s={id:_(r.id,`${t}.id`),message:_(r.message,`${t}.message`)};if(r.tag!==void 0)s.tag=_(r.tag,`${t}.tag`);if(r.description!==void 0)s.description=nr(r.description,`${t}.description`);if(r.commits!==void 0)s.commits=wm(r.commits,`${t}.commits`);for(let n of["major","minor","patch","dependency","snapshot"])if(r[n]!==void 0)s[n]=Uc(r[n],`${t}.${n}`);return s}function wm(e,t){if(!Array.isArray(e))P(t,"must be an array");return e.map((r,s)=>{let n=`${t}[${s}]`,i=Z(r,n);return ye(i,["hash","subject","type","message","packages"],["body","scope"],n),{...{hash:_(i.hash,`${n}.hash`),message:_(i.message,`${n}.message`),packages:Uc(i.packages,`${n}.packages`),subject:_(i.subject,`${n}.subject`),type:_(i.type,`${n}.type`)},...i.body===void 0?{}:{body:nr(i.body,`${n}.body`)},...i.scope===void 0?{}:{scope:_(i.scope,`${n}.scope`)}}})}function bm(e,t,r,s){let n=Z(e,"artifacts"),i=new Map(t.map((a)=>[a.name,a])),o=Me();for(let[a,c]of Object.entries(n)){let l=i.get(a);if(!l)P(`artifacts.${a}`,"references an unknown package");if(l.isPrivate)P(`artifacts.${a}`,"private packages cannot have artifacts");let p=`artifacts.${a}`,m=Z(c,p);ye(m,["path","integrity"],[],p);let h=_(m.path,`${p}.path`);if(Mc(h))P(`${p}.path`,"must be relative to the release directory");let f=ys(r,s,a);if(h!==f)P(`${p}.path`,`must be ${f}`);let g=_(m.integrity,`${p}.integrity`);if(!oc.test(g))P(`${p}.integrity`,"must be a sha512 SRI value");Pe(o,a,{integrity:g,path:h})}return o}function vm(e,t,r,s,n){let i=Z(e,"operations");ye(i,["npm","npmRegistries","providerReleases"],["push"],"operations");let o=new Map(t.map((y)=>[y.name,y])),a=Z(i.npm,"operations.npm"),c=Me();for(let[y,R]of Object.entries(a)){let S=o.get(y);if(!S)P(`operations.npm.${y}`,"references an unknown package");if(S.isPrivate)P(`operations.npm.${y}`,"private packages cannot have npm operations");if(!r.npm)P(`operations.npm.${y}`,"npm is disabled");let k=ei(R,`operations.npm.${y}`);ti(k,s,n,`operations.npm.${y}`),Pe(c,y,k)}let l=r.npm?t.filter((y)=>!y.isPrivate).map((y)=>y.name):[];for(let y of l)if(!c[y])P("operations.npm",`missing public package ${y}`);let p=Z(i.npmRegistries,"operations.npmRegistries"),m=Me();for(let[y,R]of Object.entries(p)){if(!c[y])P(`operations.npmRegistries.${y}`,"references an unknown npm operation");Pe(m,y,ci(R,`operations.npmRegistries.${y}`))}let h;if(i.push!==void 0){if(!r.push&&!r.tags)P("operations.push","push and tags are disabled");let y=Z(i.push,"operations.push");ye(y,["destination","remote","refs","state"],["startedAt","completedAt"],"operations.push");let R=ni(y,"operations.push"),S=ei(y,"operations.push",["destination","remote","refs"]);ti(S,s,n,"operations.push"),h={...R,...S}}let f=Z(i.providerReleases,"operations.providerReleases"),g=Me();for(let[y,R]of Object.entries(f)){if(!o.has(y))P(`operations.providerReleases.${y}`,"references an unknown package");if(!r.createRelease)P(`operations.providerReleases.${y}`,"createRelease is disabled");let S=`operations.providerReleases.${y}`,k=Z(R,S);ye(k,["tag","title","notes","state"],["startedAt","completedAt"],S);let H=ii(k,S),L=ei(k,S,["tag","title","notes"]);ti(L,s,n,S),Pe(g,y,{...H,...L})}return{npm:c,npmRegistries:m,providerReleases:g,...h?{push:h}:{}}}function ei(e,t,r=[]){let s=Z(e,t);ye(s,["state",...r],["startedAt","completedAt"],t);let n=Bc(s.state,jn,`${t}.state`,"operation state");if(n==="pending"){if(s.startedAt!==void 0||s.completedAt!==void 0)P(t,"pending operations cannot have timestamps");return{state:n}}let i=Cs(s.startedAt,`${t}.startedAt`);if(n==="started"){if(s.completedAt!==void 0)P(t,"started operations cannot have completedAt");return{startedAt:i,state:n}}let o=Cs(s.completedAt,`${t}.completedAt`);if(Date.parse(o)<Date.parse(i))P(t,"completedAt must not precede startedAt");return{completedAt:o,startedAt:i,state:n}}function ni(e,t){let r=Z(e,t),s=$m(r.destination,`${t}.destination`),n=_(r.remote,`${t}.remote`);if(!ac.test(n)||n.includes("..")||n.includes("//"))P(`${t}.remote`,"must be a git remote name, not a URL or credential-bearing value");if(!Array.isArray(r.refs)||r.refs.length===0)P(`${t}.refs`,"must be a nonempty array");let i=new Set,o=new Set,a=r.refs.map((c,l)=>{let p=`${t}.refs[${l}]`,m=Z(c,p);ye(m,["source","destination","oid"],[],p);let h=ri(m.source,`${p}.source`),f=ri(m.destination,`${p}.destination`),g=_(m.oid,`${p}.oid`);if(!ot.test(g))P(`${p}.oid`,"must be a full 40- or 64-character git object ID");if(i.has(h))P(`${p}.source`,`duplicate source ref ${h}`);if(o.has(f))P(`${p}.destination`,`duplicate destination ref ${f}`);return i.add(h),o.add(f),{destination:f,oid:g,source:h}});return{destination:s,refs:a,remote:n}}function $m(e,t){let r=Z(e,t);ye(r,["canonicalUrl"],["owner","provider","repo"],t);let s=_(r.canonicalUrl,`${t}.canonicalUrl`),n;try{n=new URL(s)}catch{P(`${t}.canonicalUrl`,"must be an absolute credential-free URL")}let i=n.protocol==="ssh:"||n.protocol==="git+ssh:";if(n.password||n.username&&!i||n.search||n.hash)P(`${t}.canonicalUrl`,"must not contain credentials, query parameters, or fragments");let o=[r.provider,r.owner,r.repo];if(o.every((c)=>c===void 0))return{canonicalUrl:s};if(o.some((c)=>c===void 0))P(t,"provider, owner, and repo must be set together");let a=_(r.provider,`${t}.provider`);if(a!=="github"&&a!=="gitlab"&&a!=="bitbucket")P(`${t}.provider`,"must be github, gitlab, or bitbucket");return{canonicalUrl:s,owner:_(r.owner,`${t}.owner`),provider:a,repo:_(r.repo,`${t}.repo`)}}function ii(e,t){let r=Z(e,t);return{notes:nr(r.notes,`${t}.notes`),tag:_(r.tag,`${t}.tag`),title:_(r.title,`${t}.title`)}}function ks(e,t,r){if(!Pm(t))throw new b(`Unknown release operation state ${String(t)}`);if(e.state===t)return e;if(e.state==="pending"&&t==="started")return{startedAt:r,state:t};if(e.state==="started"&&t==="completed")return{completedAt:r,startedAt:e.startedAt,state:t};throw new b(`Invalid release operation transition from ${e.state} to ${t}`)}function oi(e){if(!e.tagsReady)throw new b(`Cannot complete release ${e.id}: local release tags are not ready`);for(let[t,r]of Object.entries(e.operations.npm)){if(r.state!=="completed")throw new b(`Cannot complete release ${e.id}: npm operation for ${t} is ${r.state}`);if(!e.artifacts[t])throw new b(`Cannot complete release ${e.id}: npm artifact for ${t} is missing`);if(!e.operations.npmRegistries[t])throw new b(`Cannot complete release ${e.id}: npm registry for ${t} is missing`)}if((e.options.push||e.options.publishOnly&&e.options.tags)&&!e.operations.push)throw new b(`Cannot complete release ${e.id}: push operation is not configured`);if(e.operations.push&&e.operations.push.state!=="completed")throw new b(`Cannot complete release ${e.id}: push operation is ${e.operations.push.state}`);if(e.options.createRelease)for(let t of e.packages){let r=e.operations.providerReleases[t.name];if(!r)throw new b(`Cannot complete release ${e.id}: provider release for ${t.name} is not configured`);if(r.state!=="completed")throw new b(`Cannot complete release ${e.id}: provider release for ${t.name} is ${r.state}`)}}function ai(e){if(e!==!1)P("options.dryRun","durable ledgers require dryRun to be false");return!1}function ci(e,t){let r=_(e,t),s;try{s=new URL(r)}catch{P(t,"must be an absolute HTTP or HTTPS URL")}if(s.protocol!=="http:"&&s.protocol!=="https:"||s.username||s.password||s.search||s.hash)P(t,"must be a credential-free HTTP or HTTPS URL");return s.href}function ti(e,t,r,s){if(e.state==="pending")return;let n=Date.parse(e.startedAt);if(n<Date.parse(t)||n>Date.parse(r))P(`${s}.startedAt`,"must be between createdAt and updatedAt");if(e.state==="completed"){let i=Date.parse(e.completedAt);if(i<n||i>Date.parse(r))P(`${s}.completedAt`,"must be between startedAt and updatedAt")}}function ri(e,t){let r=_(e,t);if(!r.startsWith("refs/")||r.includes("..")||r.includes("//")||/[\s~^:?*[\\]/.test(r))P(t,"must be an exact full git ref");return r}function Bc(e,t,r,s){if(typeof e!=="string"||!t.includes(e))P(r,`unknown ${s} ${String(e)}`);return e}function Vc(e){return Tt.includes(e)}function Pm(e){return jn.includes(e)}function Z(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))P(t,"must be an object");return e}function ye(e,t,r,s){let n=new Set([...t,...r]);for(let i of t)if(!Object.hasOwn(e,i))P(s,`missing required key ${i}`);for(let i of Object.keys(e))if(!n.has(i))P(s,`unknown key ${i}`)}function Ke(e,t){if(typeof e!=="boolean")P(t,"must be a boolean");return e}function Cs(e,t){let r=_(e,t);if(!us(r))P(t,"must be a canonical ISO timestamp");return r}function _t(e,t){let r=_(e,t);if(!ot.test(r))P(t,"must be a full 40- or 64-character git object ID");return r}function Uc(e,t){if(!Array.isArray(e))P(t,"must be an array");return e.map((r,s)=>_(r,`${t}[${s}]`))}function li(e){return new Date(Math.max(Date.now(),Date.parse(e)+1)).toISOString()}function Me(){return Object.create(null)}function Pe(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0})}class Re{value;paths;releaseDirectory;artifactsDirectory;activePath;active=!0;constructor(e,t){this.value=e;this.paths=t;this.releaseDirectory=t.releaseDirectory,this.artifactsDirectory=hr(t,e.id),this.activePath=t.activePath}static async create(e,t=process.cwd()){let r=await Gn(t);if(await ct(r.activePath))throw new b(`Cannot create release ledger: active ledger already exists at ${r.activePath}`);if(await ct(r.removingPath))throw new b(`Cannot create release ledger: an interrupted removal left ${r.removingPath}; delete it and its artifacts directory to finish cleanup`);let s=new Date().toISOString(),n=await Bun.$`git rev-parse HEAD`.cwd(r.repositoryRoot).quiet().nothrow(),i=n.stdout.toString().trim();if(n.exitCode!==0||!ot.test(i))throw new b("Cannot create release ledger: failed to resolve the current commit");let o=e.options.publishOnly?await $c(r.repositoryRoot,i):void 0,a=Dc(e.packages),c=Nc(e.stones),l=Rm("sha256").update(JSON.stringify({baseCommit:i,options:e.options,packages:a,stones:c})).digest("hex"),p=Me(),m=e.options.tags?a.map((y)=>`${y.name}@${y.newVersion}`).sort():[];if(e.options.npm){for(let y of a)if(!y.isPrivate)Pe(p,y.name,{state:"pending"})}let h={artifacts:Me(),baseCommit:i,createdAt:s,id:l,operations:{npm:p,npmRegistries:Me(),providerReleases:Me()},options:{changelog:e.options.changelog,createRelease:e.options.createRelease,dryRun:ai(e.options.dryRun),npm:e.options.npm,npmTag:_(e.options.npmTag,"create.options.npmTag"),publishOnly:e.options.publishOnly,push:e.options.push,tags:e.options.tags},packages:a,phase:"planned",releaseTags:m,schemaVersion:sr,stones:c,tagsReady:!e.options.tags,updatedAt:s};if(o)h.expectedReleaseTree=o;let f=lt(h,r);if(await mr(f,r),await dr(r,l),await ct(r.activePath))throw new b(`Cannot create release ledger: active ledger already exists at ${r.activePath}`);let g=Jn(r,l);if(await ct(g))throw new b(`Release ${l} is already completed at ${g}`);return await Hn(r.activePath,f,!1),new Re(f,r)}static async loadActive(e=process.cwd()){let t=await Gn(e),r;try{r=await Gc(t.activePath)}catch(o){if(X(o,"ENOENT")){if(await ct(t.removingPath))throw new b(`Release cleanup is incomplete: an interrupted removal left ${t.removingPath}; delete it and its artifacts directory to finish cleanup`);return null}throw new b(`Failed to inspect active release ledger at ${t.activePath}: ${D(o)}`)}if(!r.isFile()||r.isSymbolicLink())throw new b(`Invalid active release ledger at ${t.activePath}: expected a regular file`);let s;try{s=await ui(t.activePath,"utf-8")}catch(o){if(X(o,"ENOENT"))return null;throw new b(`Failed to read active release ledger at ${t.activePath}: ${D(o)}`)}let n;try{n=JSON.parse(s)}catch(o){throw new b(`Failed to parse active release ledger at ${t.activePath}: ${D(o)}`)}let i=lt(n,t);return await mr(i,t),await dr(t,i.id),await fs(i,t),new Re(i,t)}get data(){return lt(this.value,this.paths)}get id(){return this.value.id}get phase(){return this.value.phase}async setPhase(e){if(this.assertActive("set phase"),e==="completed")throw new b("Cannot set release phase to completed: use complete() instead");if(!Vc(e))throw new b(`Cannot set release phase: unknown phase ${String(e)}`);if(e===this.value.phase)return;let t=Tt.indexOf(this.value.phase);if(Tt.indexOf(e)<t)throw new b(`Cannot move release phase backwards from ${this.value.phase} to ${e}`);let s=structuredClone(this.value);s.phase=e,await this.persist(s)}async setReleaseCommit(e){this.assertActive("set release commit");let t=_t(e,"releaseCommit");if(!this.value.expectedReleaseTree)throw new b("Cannot set release commit before the expected release tree");if(this.value.releaseCommit===t)return;if(this.value.releaseCommit)throw new b(`Cannot replace release commit ${this.value.releaseCommit} with ${t} in release ${this.value.id}`);let r=structuredClone(this.value);r.releaseCommit=t,await this.persist(r)}async setExpectedReleaseTree(e){this.assertActive("set expected release tree");let t=_t(e,"expectedReleaseTree");if(this.value.expectedReleaseTree===t)return;if(this.value.expectedReleaseTree)throw new b(`Cannot replace expected release tree ${this.value.expectedReleaseTree} with ${t} in release ${this.value.id}`);if(this.value.releaseCommit)throw new b(`Cannot set expected release tree after release commit ${this.value.releaseCommit}`);let r=structuredClone(this.value);r.expectedReleaseTree=t,await this.persist(r)}async markTagsReady(){if(this.assertActive("mark release tags ready"),!this.value.options.tags)return;if(!this.value.releaseCommit)throw new b("Cannot mark release tags ready without a release commit");if(this.value.tagsReady)return;let e=structuredClone(this.value);e.tagsReady=!0,await this.persist(e)}async setArtifact(e,t){if(this.assertActive("set artifact"),this.getPackage(e).isPrivate)throw new b(`Cannot store an artifact for private package ${e}`);let s=this.value.operations.npm[e];if(!s)throw new b(`Cannot store an artifact for unconfigured npm package ${e}`);if(s.state!=="pending")throw new b(`Cannot replace artifact for ${e} after its npm operation has started`);if(Im(t)!==".tgz")throw new b(`Cannot store artifact for ${e}: source must be a .tgz file`);let n;try{n=await Tm(t)}catch(p){throw new b(`Cannot read source artifact for ${e} at ${t}: ${D(p)}`)}if(!n.isFile())throw new b(`Cannot store artifact for ${e}: source is not a regular file`);await dr(this.paths,this.value.id);let i=Wn(this.paths,this.value.id,e),o=Am(this.artifactsDirectory,`.${Sm()}.tgz.tmp`),a;try{await km(t,o,Cm.COPYFILE_EXCL),await ae(o),await gr(this.paths,this.value.id,o),a=await It(o);try{await xm(o,i)}catch(p){if(!X(p,"EEXIST"))throw p;if(await gr(this.paths,this.value.id,i),await It(i)!==a){let m=this.value.artifacts[e]?`A different durable artifact already exists for ${e} at ${i}`:`A different durable artifact already exists for ${e} at ${i}; the ledger records no artifact for it, so it is likely left by an interrupted run - delete the file and retry`;throw new b(m)}}await qc(o,{force:!0}),await ae(this.artifactsDirectory),await gr(this.paths,this.value.id,i)}catch(p){await qn(o,p,`Failed to clean temporary artifact for ${e}`)}if(!a)throw new b(`Failed to calculate artifact integrity for ${e}`);let c={integrity:a,path:ys(this.paths,this.value.id,e)},l=structuredClone(this.value);return Pe(l.artifacts,e,c),await this.persist(l),{...c}}resolveArtifactPath(e){let t=this.value.artifacts[e];if(!t)throw new b(`Release artifact is not configured for ${e}`);return Om(this.releaseDirectory,t.path)}async configurePush(e,t,r){if(this.assertActive("configure push"),!this.value.options.push&&!this.value.options.tags)throw new b("Cannot configure push: neither push nor tags are enabled for this release");let s=ni({destination:t,refs:r,remote:e},"configurePush"),n=this.value.operations.push;if(n){if(JSON.stringify([n.remote,n.destination,n.refs])===JSON.stringify([s.remote,s.destination,s.refs]))return;throw new b("Cannot replace an existing push configuration")}let i=structuredClone(this.value);i.operations.push={...s,state:"pending"},await this.persist(i)}async configureProviderRelease(e,t){if(this.assertActive("configure provider release"),this.getPackage(e),!this.value.options.createRelease)throw new b("Cannot configure a provider release when createRelease is disabled");let r=ii(t,`providerReleases.${e}`),s=this.value.operations.providerReleases[e];if(s){if(s.tag===r.tag&&s.title===r.title&&s.notes===r.notes)return;throw new b(`Cannot replace provider release configuration for ${e}`)}let n=structuredClone(this.value);Pe(n.operations.providerReleases,e,{...r,state:"pending"}),await this.persist(n)}async markNpm(e,t){this.assertActive("mark npm operation");let r=this.value.operations.npm[e];if(!r)throw new b(`Npm operation is not configured for package ${e}`);if(r.state===t)return;if(t==="started"&&!this.value.artifacts[e])throw new b(`Cannot start npm operation for ${e} without a durable artifact`);let s=structuredClone(this.value);Pe(s.operations.npm,e,ks(r,t,this.operationTimestamp())),await this.persist(s)}async setNpmRegistry(e,t){this.assertActive("set npm registry");let r=this.value.operations.npm[e];if(!r)throw new b(`Npm operation is not configured for package ${e}`);if(r.state!=="pending")throw new b(`Cannot change npm registry for ${e} after publication has started`);let s=ci(t,`operations.npmRegistries.${e}`),n=this.value.operations.npmRegistries[e];if(n===s)return;if(n)throw new b(`Cannot replace npm registry for ${e}`);let i=structuredClone(this.value);Pe(i.operations.npmRegistries,e,s),await this.persist(i)}async markPush(e){this.assertActive("mark push operation");let t=this.value.operations.push;if(!t)throw new b("Push operation is not configured");if(t.state===e)return;let r=structuredClone(this.value);r.operations.push={destination:t.destination,refs:t.refs,remote:t.remote,...ks(t,e,this.operationTimestamp())},await this.persist(r)}async markProviderRelease(e,t){this.assertActive("mark provider release operation");let r=this.value.operations.providerReleases[e];if(!r)throw new b(`Provider release is not configured for package ${e}`);if(r.state===t)return;let s=structuredClone(this.value);Pe(s.operations.providerReleases,e,{notes:r.notes,tag:r.tag,title:r.title,...ks(r,t,this.operationTimestamp())}),await this.persist(s)}hasExternalProgress(){return si(this.value)}async complete(){if(this.assertActive("complete"),this.value.phase!=="completed"){let r=structuredClone(this.value);oi(r),r.phase="completed",await this.persist(r)}let e=Jn(this.paths,this.value.id),t=await ar(this.releaseDirectory);try{let r=await Gc(this.activePath);if(!r.isFile()||r.isSymbolicLink())throw new b(`Invalid active release ledger at ${this.activePath}: expected a regular file`);let s=lt(JSON.parse(await ui(this.activePath,"utf-8")),this.paths);if(s.id!==this.value.id||s.updatedAt!==this.value.updatedAt||s.phase!=="completed")throw new b("Active release ledger changed in another process");if(await Rc(this.paths),await ct(e))throw new b(`Cannot complete release ${s.id}: history ledger already exists at ${e}`);await Hc(this.activePath,e),await ae(this.paths.historyDirectory),await ae(this.releaseDirectory)}catch(r){if(r instanceof b)throw r;throw new b(`Failed to move completed release ${this.value.id} to history: ${D(r)}`)}finally{await Et(t)}return this.active=!1,e}async remove(){this.assertActive("remove");let e=await ar(this.releaseDirectory);try{await dr(this.paths,this.value.id);let t=lt(JSON.parse(await ui(this.activePath,"utf-8")),this.paths);if(await mr(t,this.paths),await fs(t,this.paths),t.id!==this.value.id||t.updatedAt!==this.value.updatedAt)throw new b("Active release ledger changed in another process");if(si(t))throw new b(`Cannot remove release ${t.id}: an external operation has started`);await Hc(this.activePath,this.paths.removingPath),await ae(this.releaseDirectory),await qc(this.artifactsDirectory,{force:!0,recursive:!0}),await Em(this.paths.removingPath),await ae(this.releaseDirectory)}catch(t){if(t instanceof b)throw t;throw new b(`Failed to remove release ${this.value.id}: ${D(t)}`)}finally{await Et(e)}this.active=!1}async persist(e){e.updatedAt=li(this.value.updatedAt);let t=lt(e,this.paths);await mr(t,this.paths),await fs(t,this.paths),await Hn(this.activePath,t,!0,this.value.updatedAt),this.value=t}getPackage(e){let t=this.value.packages.find((r)=>r.name===e);if(!t)throw new b(`Unknown release package ${e}`);return t}operationTimestamp(){return li(this.value.updatedAt)}assertActive(e){if(!this.active)throw new b(`Cannot ${e}: release ledger ${this.value.id} is no longer active`)}}class De{config;packageUpdater=new Qt;changelogGenerator;remoteParser=new Kt;stoneManager;provider=null;commitUrlFn=null;options;createdTags=[];createdTagTargets=new Map;commitCreated=!1;createdCommit=null;irreversibleOperation=null;ownedPaths=null;repositoryRoot=null;rollbackBlockedReason=null;ignoredBuildInputsValidated=!1;buildConfig=null;buildOutputsPrepared=!1;preparedNpmPublish=null;ledger=null;publishContext=null;constructor(e,t){this.config=e;this.options=t,this.changelogGenerator=new rt(this.config.get("changelog")),this.stoneManager=new O(this.config)}static async assertNoActiveRelease(){let e=await Re.loadActive();if(!e)return;throw new u(`Release ${e.id} is incomplete`,"Run sis roll --resume before starting another release")}static async resume(e){let t=await Re.loadActive();if(!t)throw new u("No incomplete release found","Run sis roll to start a release");let r=t.data,s=new De(e,r.options);s.ledger=t;let n=r.packages.map((o)=>new z({file:o.file,isPrivate:o.isPrivate,name:o.name,newVersion:o.newVersion,version:o.oldVersion})),i=r.stones.map((o)=>M.fromJson(o));if(s.createdTags=[...r.releaseTags],r.phase==="completed")return await t.complete(),{ledger:s.getLedgerSnapshot(),packages:n,stones:i};try{if(await s.recoverReleaseCommit(r),await ic(t.data),await nc(t.data),await s.ensureLedgerPlan(n,i),r.options.npm){if(n.some((a)=>t.data.operations.npm[a.name]&&!t.data.artifacts[a.name]))await tr(await s.getRepositoryRoot());await s.prepareNpmPublish(n)}if(t.phase==="planned")await t.setPhase("local-ready");return await s.resumeExternalOperations(n,i),{ledger:s.getLedgerSnapshot(),packages:n,stones:i}}catch(o){if(o instanceof u||!s.hasCrossedIrreversibleBoundary())throw o;throw s.createIncompleteReleaseError(o)}}async initializeExternalRelease(e,t,r){if(this.options.dryRun||!this.needsReleaseLedger(r))return;this.ledger=await Re.create({options:{...this.options,npmTag:this.options.npm?fr(e,this.config.get("tag")):he,publishOnly:r},packages:e.map((s)=>({file:s.file,isPrivate:s.isPrivate,name:s.name,newVersion:s.newVersion,version:s.version})),stones:t})}async finalizeExternalRelease(e,t){if(!this.ledger)return;if(this.options.npm||this.ledger.data.options.publishOnly)await tr(await this.getRepositoryRoot());let r=await se();await this.ensureExpectedReleaseTree(this.ledger.data,r),await it(this.ledger.data,r),await this.ledger.setReleaseCommit(r),await this.ensureLedgerPlan(e,t)}async markExternalReleaseReady(){if(this.ledger)await this.ledger.setPhase("local-ready")}async completeRelease(){if(this.ledger)await this.ledger.complete()}async getProvider(){if(!this.provider){let e=this.ledger?.data.operations.push?.destination,t=Ps(e);this.provider=await vt(t)}return this.provider}async initCommitLinks(){if(this.commitUrlFn!==null)return;let e=this.ledger?.data.operations.push?.destination,t=Ps(e);if(t){this.commitUrlFn=un(t);return}let r=await this.remoteParser.getRemoteInfo();this.commitUrlFn=r?.commitUrl??null}async preflight(e,t){if(this.options.dryRun)return;await De.assertNoActiveRelease();let r=await this.getOwnedPaths(e,t);await ec(r,await this.getRepositoryRoot());let s=r.map((i)=>qe(i));if((await I(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${s}`.quiet(),"Failed to inspect release files")).stdout.length===0)return;throw new u("Release files have uncommitted changes",`Commit or stash these files:
|
|
176
176
|
${r.join(`
|
|
177
|
-
`)}`)}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,r){if(this.options.dryRun)return;let s=await this.getOwnedPaths(t,r),n=s.map((h)=>qe(h)),i=Wa(this.config.get("commit").message,e,t),o=Ja(this.config.get("commit")),a=this.ledger?.data.baseCommit??await se(),c=await An(),l,p;try{if(await I(()=>Bun.$`git add -A -- ${n}`.quiet(),"Failed to stage release files"),await se()!==a)throw new u("Release base commit changed before commit creation","Restart the release from the intended branch");l=await rc(a,s,await this.getRepositoryRoot()),await this.ledger?.setExpectedReleaseTree(l),p=await On(s),await I(()=>Bun.$`git commit --only ${o} -m ${i} -- ${n}`.env(za(this.config.get("commit"))).quiet(),"Failed to create commit"),this.commitCreated=!0}catch(h){if(p){let f;try{f=await On(s)}catch(g){throw this.rollbackBlockedReason="release files could not be verified after commit failure",AggregateError([h,g],"Commit failed and release files could not be verified")}if(f!==p)throw this.rollbackBlockedReason="release-owned files changed while commit hooks ran",AggregateError([h],"Commit failed after a hook changed release-owned files")}try{await _n(s)}catch(f){throw AggregateError([h,f],"Commit and index cleanup failed")}throw h}let d=await se();if(this.createdCommit={baseCommit:a,oid:d,ref:c},!l)throw Error("Expected release tree was not recorded before commit");if(this.ledger){await it(this.ledger.data,d);return}await Ln(d,a),await Mn(d,l)}async createGitTags(e){if(this.options.dryRun)return;let t=await se();for(let r of e){let s=`${r.name}@${r.newVersion??r.version}`;await I(()=>Bun.$`git -c tag.gpgSign=false tag -- ${s}`.quiet(),`Failed to create tag ${s}`),this.createdTags.push(s),this.createdTagTargets.set(s,t)}}async prepareNpmPublish(e){if(this.options.dryRun)return;let t=this.getPackageSetKey(e);if(this.preparedNpmPublish?.key===t)return;let r=this.requireLedger("prepare npm artifacts");this.preparedNpmPublish=null;let s=await Tc(e);if(s.length===0){this.preparedNpmPublish={key:t,packages:[]};return}if(s.some((o)=>!r.data.artifacts[o.name]))await this.prepareBuildOutputs();let n=await Td(ui(Id(),"sisyphus-publish-")),i=[];try{for(let[o,a]of s.entries()){if(!r.data.artifacts[a.name]){let l=ui(n,`${String(o).padStart(4,"0")}.tgz`);await I(()=>this.prepareNpmArtifact(a,l),`Failed to prepare ${a.name}`),await r.setArtifact(a.name,l)}let c=r.resolveArtifactPath(a.name);Xr(await is(c)),i.push({artifactPath:c,pkg:a})}}finally{await qc(n,{force:!0,recursive:!0})}this.preparedNpmPublish={key:t,packages:i}}async publishToNpm(e){if(this.options.dryRun)return;let t=this.getPackageSetKey(e);if(this.preparedNpmPublish?.key!==t)await this.prepareNpmPublish(e);let r=this.preparedNpmPublish?.packages??[];if(r.length===0)return;try{for(let s of r)await this.publishPreparedPackage(s)}finally{this.preparedNpmPublish=null}}async pushRelease(){if(this.options.dryRun)return;await this.pushConfiguredRefs()}async createGitRelease(e,t){if(this.options.dryRun)return;if(t.length===0)return;await this.initCommitLinks();let r=await this.getProvider(),s=this.ledger?.data.operations.push;if(s){let n=s.refs.filter((i)=>i.destination.startsWith("refs/tags/"));if(n.length>0)await Ic(s,()=>this.getRepositoryRoot(),n)}for(let n of t){let i=Zn(e,n,this.commitUrlFn);await this.createProviderRelease(r,n.name,i)}}hasCrossedIrreversibleBoundary(){return this.irreversibleOperation!==null||this.ledger?.hasExternalProgress()===!0}createIncompleteReleaseError(e){let t=this.irreversibleOperation??"an external release operation",r=new u(`Release incomplete after ${t} began`,"Local state preserved; run sis roll --resume to reconcile and continue.");return r.cause=e,r}async rollback(e=!0){if(this.hasCrossedIrreversibleBoundary())return!1;if(await this.validateRollbackState(),this.preparedNpmPublish=null,await ec(this.createdCommit,this.createdTags,this.createdTagTargets,()=>this.getRepositoryRoot()),this.commitCreated){if(this.ownedPaths)await _n(this.ownedPaths);this.commitCreated=!1,this.createdCommit=null}if(this.createdTags=[],this.createdTagTargets.clear(),await this.changelogGenerator.rollback(),await this.packageUpdater.rollback(),e)await this.removeReleaseLedger();return!0}async validateRollbackState(){if(this.rollbackBlockedReason)throw new u(`Cannot roll back release because ${this.rollbackBlockedReason}`,"Local release state and the recovery ledger were preserved");if(this.commitCreated&&!this.createdCommit)throw new u("Cannot identify the release commit for rollback","Local release state and the recovery ledger were preserved");if(this.commitCreated&&this.createdCommit){let[e,t]=await Promise.all([se(),An()]);if(e!==this.createdCommit.oid||t!==this.createdCommit.ref)throw new u(`Cannot roll back release commit because HEAD changed from ${this.createdCommit.oid}`,"Local release state and the recovery ledger were preserved")}if(this.commitCreated&&this.ownedPaths){let e=this.ownedPaths.map((r)=>qe(r));if((await I(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${e}`.quiet(),"Failed to inspect release files before rollback")).stdout.length>0)throw new u("Cannot roll back release because release-owned files changed after commit creation","Local release state and the recovery ledger were preserved")}for(let e of this.createdTags){let t=this.createdTagTargets.get(e),r=await Xa(`refs/tags/${e}`);if(!t||r!==t)throw new u(`Cannot roll back release because tag ${e} changed after creation`,"Local release state and the recovery ledger were preserved")}}async removeReleaseLedger(){if(!this.ledger)return;await this.ledger.remove(),this.ledger=null}needsReleaseLedger(e){return this.options.npm||this.options.push||this.options.createRelease||e&&this.options.tags}async recoverReleaseCommit(e){if(e.releaseCommit||!this.ledger)return;let t=await se();if(!e.expectedReleaseTree&&!e.options.publishOnly)throw new u(`Release ${e.id} stopped before its expected release tree was recorded`,`No external operation was attempted; inspect the local changes and release ledger manually; delete ${this.ledger.activePath} to abort the release`);if(!e.options.publishOnly&&t===e.baseCommit)throw new u(`Release ${e.id} stopped before its release commit was created`,`No external operation was attempted; restore the release-owned files from ${e.baseCommit} and delete ${this.ledger.activePath} to abort the release`);await this.ensureExpectedReleaseTree(e,t),await it(this.ledger.data,t),await this.ledger.setReleaseCommit(t)}async ensureLedgerPlan(e,t){if(!this.ledger)return;let r=this.ledger.data;if(await this.reconcileReleaseTags(r),r.options.npm)for(let s of e){if(!r.operations.npm[s.name]||r.operations.npmRegistries[s.name])continue;await this.ledger.setNpmRegistry(s.name,await kc(s))}if(!r.operations.push&&(r.options.push||r.options.publishOnly&&r.options.tags))await this.configureLedgerPush(r);if(r.options.createRelease){await this.initCommitLinks();for(let s of e)await this.ledger.configureProviderRelease(s.name,Zn(t,s,this.commitUrlFn));await this.getProvider()}}async reconcileReleaseTags(e){if(!this.ledger||!e.options.tags)return;if(!e.releaseCommit)throw Error("Cannot reconcile release tags without a release commit");for(let t of e.releaseTags){let r=`refs/tags/${t}`,s=await Bun.$`git rev-parse --verify ${r}`.quiet().nothrow();if(s.exitCode!==0){await I(()=>Bun.$`git -c tag.gpgSign=false tag -- ${t} ${e.releaseCommit}`.quiet(),`Failed to create tag ${t}`);continue}let n=s.stdout.toString().trim();if(n!==e.releaseCommit)throw new u(`Release tag ${t} points to ${n}, expected ${e.releaseCommit}`,"Do not move release tags before the release completes")}if(!e.tagsReady)await this.ledger.markTagsReady()}async configureLedgerPush(e){if(!this.ledger||!e.releaseCommit)throw Error("Cannot configure release push without a recorded release commit");let t=e.releaseCommit,r=e.releaseTags.map((c)=>({destination:`refs/tags/${c}`,oid:t,source:`refs/tags/${c}`}));if(e.options.publishOnly){let c=await Xn(await Yn()),l=await $s(await Rs(c),()=>this.getRepositoryRoot());this.validateProviderDestination(l),await zn(r),await this.ledger.configurePush(c,l,r);return}let{branch:s,remote:n}=await Ac(),i=await $s(await Rs(n),()=>this.getRepositoryRoot());this.validateProviderDestination(i);let o=`refs/heads/${s}`,a=[{destination:o,oid:e.releaseCommit,source:o},...r];await zn(a),await this.ledger.configurePush(n,i,a)}validateProviderDestination(e){if(this.options.createRelease&&!Ps(e))throw new u("Push destination is not a supported git provider repository","Provider releases require GitHub, GitLab, or Bitbucket")}async resumeExternalOperations(e,t){let r=this.requireLedger("resume external operations");if(r.phase==="completed"){await this.completeRelease();return}if(r.data.operations.push)await this.pushConfiguredRefs();if(this.options.npm)await this.publishToNpm(e);if(this.options.createRelease)await this.createGitRelease(t,e);await this.completeRelease()}async pushConfiguredRefs(){let e=this.requireLedger("push release refs"),t=e.data.operations.push;if(!t)throw Error("Release push is not configured");if(t.state==="completed")return;if(await Ot(t,()=>this.getRepositoryRoot()),t.state==="started"){await _c(e,t,()=>this.getRepositoryRoot());return}await e.setPhase("external"),await e.markPush("started"),this.crossIrreversibleBoundary("remote push"),await Ss(t,()=>this.getRepositoryRoot()),await e.markPush("completed")}async publishPreparedPackage(e){let t=this.requireLedger(`publish ${e.pkg.name}`),r=t.data.operations.npm[e.pkg.name];if(!r)throw Error(`Npm operation is not configured for ${e.pkg.name}`);if(r.state==="completed")return;if(r.state==="started"){await Ec(t,e.pkg,()=>this.publishPackage(e));return}await t.setPhase("external"),await t.markNpm(e.pkg.name,"started"),this.crossIrreversibleBoundary("npm publication"),await this.publishPackage(e),await t.markNpm(e.pkg.name,"completed")}requireLedger(e){if(!this.ledger)throw Error(`Cannot ${e} without an active release ledger`);return this.ledger}async createProviderRelease(e,t,r){let s=this.requireLedger(`create the provider release for ${r.tag}`),n=s.data.operations.providerReleases[t];if(!n)throw Error(`Provider release is not configured for ${t}`);if(n.state==="completed")return;if(n.state==="started"){await this.reconcileStartedProviderRelease(e,t,n);return}await s.setPhase("external"),await s.markProviderRelease(t,"started"),this.crossIrreversibleBoundary(`git provider release creation for ${r.tag}`),await I(()=>e.createRelease(r),`Failed to create release for ${r.tag}`),await s.markProviderRelease(t,"completed")}async reconcileStartedProviderRelease(e,t,r){let s=await I(()=>e.getRelease(r.tag),`Failed to inspect release for ${r.tag}`);if(!s)throw new u(`Cannot safely resume provider release ${r.tag}`,"The provider does not confirm the previous creation; inspect the release manually");if(s.draft||s.tag!==r.tag||s.title!==r.title||s.notes!==r.notes)throw new u(`Cannot safely resume provider release ${r.tag}: existing release does not match`,"Do not overwrite the existing release; compare its title and notes with the release ledger");await this.ledger?.markProviderRelease(t,"completed")}async getOwnedPaths(e,t){let r=await this.getRepositoryRoot(),s=this.options.changelog?as(this.config.get("changelog"),e):[],n=[...e.map((o)=>o.file),...s,ui(bt,jr),...this.stoneManager.getFilePaths(t)],i=[...new Set(n.map((o)=>Za(r,o)))].sort();if(this.ownedPaths&&(this.ownedPaths.length!==i.length||this.ownedPaths.some((o,a)=>o!==i[a])))throw Error("Release paths changed");return this.ownedPaths=i,i}async getRepositoryRoot(){if(this.repositoryRoot)return this.repositoryRoot;let t=(await I(()=>Bun.$`git rev-parse --show-toplevel`.quiet(),"Failed to resolve git repository root")).stdout.toString().trim();if(!t)throw Error("Git repository root is empty");return this.repositoryRoot=Ad(t),this.repositoryRoot}async validatePublishCommitBinding(e){let t=this.requireLedger("bind npm artifacts to a release commit").data;if(!t.releaseCommit||!t.expectedReleaseTree||e!==t.releaseCommit)throw new u(`Publish source does not match the recorded release commit for ${t.id}`,t.releaseCommit?`Check out ${t.releaseCommit} before publishing`:"Resume the release before publishing");await it(t,e)}async ensureExpectedReleaseTree(e,t){if(e.expectedReleaseTree)return;if(!this.ledger||!e.options.publishOnly||t!==e.baseCommit)throw new u(`Release ${e.id} has no recorded expected release tree`,"No external operation was attempted; inspect the release state manually");await this.ledger.setExpectedReleaseTree(await Dn(e.baseCommit))}getPackageSetKey(e){return e.map((t)=>`${t.name}\x00${t.file}`).join("\x00")}async publishPackage(e){let t=this.requireLedger(`publish ${e.pkg.name}`),r=t.data.options.npmTag,s=Xr(await is(e.artifactPath)),n=t.data.operations.npmRegistries[e.pkg.name];if(!n)throw Error(`Npm registry is not configured for ${e.pkg.name}`);let i=At(e.pkg.name,n);await I(()=>Bun.$`npm publish ${e.artifactPath} --tag ${r} --access ${s} --ignore-scripts --registry ${n} ${i}`.cwd(Wc(e.pkg.file)).quiet(),`Failed to publish ${e.pkg.name}`)}async prepareNpmArtifact(e,t){let r=Wc(e.file),s=null;try{let n=await se();await this.validatePublishCommitBinding(n),await tr(await this.getRepositoryRoot()),await this.validateIgnoredBuildInputs();let i=this.getBuildConfig();if(await Ba(e,r,await this.getRepositoryRoot(),i.matcher),i.command.length>0)await En(i.command,r,`Failed to build ${e.name}`);let o=await se();await this.validatePublishCommitBinding(o);let a=await rr(await this.getRepositoryRoot());if(o!==n||a.length>0)throw new u(`Package build changed repository source files for ${e.name}`,"This package was not packed and nothing was published; restore the build changes before retrying");let c=await Ed(e.file,"utf-8"),{catalogs:l,workspaceVersions:p}=await this.getPublishContext(),d=Ra(c,l,p);Xr(d);let h=JSON.parse(d),f=e.newVersion??e.version;if(h.name!==e.name||h.version!==f)throw Error(`Packed manifest identity mismatch for ${e.name}: expected ${e.name}@${f}, found ${String(h.name)}@${String(h.version)}`);s=await Fa(e,r,d);let g=await Na(s,t);if(g.name!==e.name||g.version!==f)throw new u(`Packed artifact identity mismatch for ${e.name}: found ${g.name}@${g.version}`,"This package was not recorded and nothing was published");if(!Va(d,await is(t)))throw new u(`Packed manifest does not match the prepared manifest for ${e.name}`,"This package was not recorded and nothing was published");let y=await se();await this.validatePublishCommitBinding(y);let R=await rr(await this.getRepositoryRoot());if(y!==n||R.length>0)throw new u(`Package packing changed repository source files for ${e.name}`,"This package was not recorded and nothing was published; restore the changes before retrying")}finally{if(s)await qc(s,{force:!0,recursive:!0})}}async validateIgnoredBuildInputs(){if(this.ignoredBuildInputsValidated)return;await xn(await this.getRepositoryRoot(),"",this.getBuildConfig().matcher),this.ignoredBuildInputsValidated=!0}getLedgerSnapshot(){return this.ledger?.data??null}getBuildConfig(){return this.buildConfig??=Ha(this.config.get("release")?.build),this.buildConfig}async prepareBuildOutputs(){if(this.buildOutputsPrepared)return;let e=this.getBuildConfig(),t=await this.getRepositoryRoot(),r=await se();await this.validatePublishCommitBinding(r),await tr(t),await qa(t,e.matcher),await Tn(t,"",e.matcher);for(let[s,n]of e.root.entries())await En(n,t,`Failed to run release root build command ${s}`);if(e.root.length>0){let s=await se();if(await this.validatePublishCommitBinding(s),s!==r||(await rr(t)).length>0)throw new u("Root build changed repository source files","No package was packed and nothing was published; restore the build changes before retrying")}await this.validateIgnoredBuildInputs(),this.buildOutputsPrepared=!0}async getPublishContext(){if(!this.publishContext){let e=await Bun.file("package.json").json(),{packages:t}=await G.scan({single:this.config.get("single")});this.publishContext={catalogs:va(e),workspaceVersions:Pa(t.values())}}return this.publishContext}crossIrreversibleBoundary(e){this.irreversibleOperation??=e}}import{dirname as Od}from"path";var _d=1000,Ld=5000;function pi(e){if(e===void 0)return 0;if(typeof e==="number"&&Number.isSafeInteger(e)&&e>=0)return e;throw new u(`Invalid release.npmVisibilityTimeout: ${JSON.stringify(e)}`,"Use a whole number of seconds, or 0 to skip the registry visibility check")}async function mi(e,t){let r=t>0?Md(e):[];if(r.length===0)return[];let s=Date.now()+t*_d,n=new Map,i=r;while(i.length>0){for(let a of i)n.set(a.name,await Dd(a));i=i.filter((a)=>n.get(a.name)==="pending");let o=s-Date.now();if(i.length===0||o<=0)break;await Bun.sleep(Math.min(Ld,o))}return r.map(({name:o,registry:a,version:c})=>({name:o,registry:a,state:n.get(o)??"pending",version:c}))}function di(e,t){return e.filter((r)=>r.state!=="visible").map((r)=>{let s=`${r.name}@${r.version}`;return r.state==="mismatch"?`${s} on ${r.registry} does not match the integrity of the published artifact`:`${s} is not visible on ${r.registry} after ${t}s; npm may still be processing or holding it`})}function Md(e){return e.packages.flatMap((t)=>{let r=e.artifacts[t.name],s=e.operations.npmRegistries[t.name];return e.operations.npm[t.name]?.state==="completed"&&r&&s?[{cwd:Od(t.file),integrity:r.integrity,name:t.name,registry:s,version:t.newVersion}]:[]})}async function Dd(e){let t=`${e.name}@${e.version}`,r=At(e.name,e.registry),s=await Bun.$`npm view ${t} --json --prefer-online --registry ${e.registry} ${r}`.cwd(e.cwd).quiet().nothrow();if(s.exitCode!==0)return"pending";let n=vs(Nd(s.stdout.toString()));if(!n||n.name!==e.name||n.version!==e.version)return"pending";return n.integrity===e.integrity?"visible":"mismatch"}function Nd(e){try{return JSON.parse(e)}catch{return}}var jd=6;function xs(e,t){let r=e.map((s)=>gn(s,t));return{skipped:[...new Set(r.flatMap((s)=>s.skipped))].sort(),stones:r.map((s)=>s.stone)}}function yr(e,t,r){let s=[...new Set(e.allPackages)].filter((n)=>!t.has(n)&&!ee(n,r)).sort();if(s.length>0)return{kind:"unknown-packages",names:s};return{kind:"ignored-only"}}function gi(e,t,r,s){let{stone:n}=gn(e,r),i=yr(n,t,r);if(i.kind==="unknown-packages")return{kind:"invalid",message:`Pending stones reference unknown packages: ${i.names.join(", ")}`};try{return{kind:"ok",packages:z.applyStone(n,t,s).flatMap((a)=>a.bump&&a.newVersion?[{bump:a.bump,name:a.name,newVersion:a.newVersion,version:a.version}]:[])}}catch(o){if(o instanceof u)return{kind:"invalid",message:o.message};throw o}}function Jc(e,t){let r=t.map((o)=>`${o.name}@${o.newVersion??o.version}`),s=r.slice(0,jd),n=r.length-s.length,i=n>0?` +${n} more`:"";return`${e} ${s.join(", ")}${i}`}var Fd=1;function zc(e){let{ledger:t}=e,r=t?Bd(t,e.npmVisibility??[]):Ud(e.packages),s=r.filter((i)=>i.published).map((i)=>({name:i.name,version:i.newVersion})),n={baseCommit:t?.baseCommit??null,command:"roll",mode:e.mode,operations:{npmTag:t?.options.npmTag??e.npmTag,providerReleases:Hd(t),pushed:t?.operations.push?.state==="completed"},packages:r,published:s.length>0,publishedPackages:s,releaseCommit:t?.releaseCommit??e.releaseCommit??null,releaseId:t?.id??null,schemaVersion:Fd,status:e.status,stones:t?t.stones.map((i)=>i.id):e.stones.map((i)=>i.id),tags:t?t.tagsReady?[...t.releaseTags]:[]:Gd(e.packages,e.tagsEnabled),warnings:[...e.warnings??[]]};if(e.changelogFiles)n.changelogFiles=[...e.changelogFiles];if(e.error!==void 0)n.error=qd(e.error);return n}function Bd(e,t){return e.packages.map((r)=>({integrity:e.artifacts[r.name]?.integrity??null,name:r.name,newVersion:r.newVersion,oldVersion:r.oldVersion,private:r.isPrivate,published:e.operations.npm[r.name]?.state==="completed",registry:e.operations.npmRegistries[r.name]??null,tag:e.tagsReady?e.releaseTags.find((s)=>s===Kc(r.name,r.newVersion))??null:null,visible:Vd(t,r.name)}))}function Vd(e,t){let r=e.find((s)=>s.name===t);return r?r.state==="visible":null}function Kc(e,t){return`${e}@${t}`}function Ud(e){return e.map((t)=>({integrity:null,name:t.name,newVersion:t.newVersion??t.version,oldVersion:t.version,private:t.isPrivate,published:!1,registry:null,tag:null,visible:null}))}function Gd(e,t){if(!t)return[];return e.map((r)=>Kc(r.name,r.newVersion??r.version)).sort()}function Hd(e){let t=Object.values(e?.operations.providerReleases??{});return t.length>0&&t.every((r)=>r.state==="completed")}function qd(e){let t=e instanceof Error?e.message:String(e),r=e instanceof u?e.hint:void 0,s=Yc(e);return{...s.length>0?{causes:s}:{},...r?{hint:r}:{},message:t}}function Yc(e,t=new Set){if(!(e instanceof Error)||t.has(e))return[];return t.add(e),[...e instanceof AggregateError?e.errors:[],e.cause].filter((n)=>n instanceof Error).flatMap((n)=>[n.message,...Yc(n,t)])}var Ts="sisyphus/release",hi="sisyphus-release",Wd="Sisyphus release PR",Jd="6f42c1",Xc="chore(release):",zd=U({dryRun:{alias:"d",default:!1,description:"Preview without making changes",type:"boolean"}});class fi extends j{name="release-pr";description="Create or update a release PR from pending stones";args=zd;provider=null;async getProvider(){if(!this.provider)this.provider=await vt();return this.provider}async execute(e){let t=await this.checkoutReleaseBranch(e.args.dryRun);try{let{stones:r,packages:s}=await this.collectReleaseData(e);if(r.length===0){v.info(m.dim("No pending stones found, skipping release PR"));return}let n=this.buildPrTitle(s),i=this.buildPrBody(s,r);if(v.info(`${m.bold("Release PR:")} ${n}`),v.info(`${m.dim("Packages:")} ${s.map((o)=>o.name).join(", ")}`),e.args.dryRun){v.info(m.yellow(`
|
|
178
|
-
[dry-run] Would create/update release PR`)),v.info(
|
|
179
|
-
PR Body preview:`)),v.info(i);return}await this.commitAndPushChanges(e,r,s),await this.createOrUpdatePr(n,i)}finally{await this.restoreBranch(t)}}async checkoutReleaseBranch(e){if((await Bun.$`git status --porcelain=v1 --untracked-files=all`.quiet()).stdout.length>0)throw new u("Working tree must be clean before preparing a release PR","Commit or stash your changes before running sis actions release-pr");let s=(await Bun.$`git branch --show-current`.quiet()).stdout.toString().trim()||(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim(),i=await(await this.getProvider()).getDefaultBranch();if(await Bun.$`git fetch origin ${i}`,e)await Bun.$`git checkout --detach origin/${i}`;else await Bun.$`git checkout -B ${Ts} origin/${i}`;return s}async collectReleaseData(e){let t=new O(e.config),r=await this.generateStonesFromCommits(e,t,e.args.dryRun),s=await t.list(),n=e.args.dryRun?[...s,...r]:s;if(n.length===0)return{packages:[],stones:[]};let i=e.config.get("ignore")??[],{stones:o,skipped:a}=xs(n,i);if(a.length>0)v.warn(
|
|
180
|
-
${
|
|
181
|
-
${
|
|
177
|
+
`)}`)}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,r){if(this.options.dryRun)return;let s=await this.getOwnedPaths(t,r),n=s.map((h)=>qe(h)),i=Ja(this.config.get("commit").message,e,t),o=za(this.config.get("commit")),a=this.ledger?.data.baseCommit??await se(),c=await On(),l,p;try{if(await I(()=>Bun.$`git add -A -- ${n}`.quiet(),"Failed to stage release files"),await se()!==a)throw new u("Release base commit changed before commit creation","Restart the release from the intended branch");l=await sc(a,s,await this.getRepositoryRoot()),await this.ledger?.setExpectedReleaseTree(l),p=await _n(s),await I(()=>Bun.$`git commit --only ${o} -m ${i} -- ${n}`.env(Ka(this.config.get("commit"))).quiet(),"Failed to create commit"),this.commitCreated=!0}catch(h){if(p){let f;try{f=await _n(s)}catch(g){throw this.rollbackBlockedReason="release files could not be verified after commit failure",AggregateError([h,g],"Commit failed and release files could not be verified")}if(f!==p)throw this.rollbackBlockedReason="release-owned files changed while commit hooks ran",AggregateError([h],"Commit failed after a hook changed release-owned files")}try{await Ln(s)}catch(f){throw AggregateError([h,f],"Commit and index cleanup failed")}throw h}let m=await se();if(this.createdCommit={baseCommit:a,oid:m,ref:c},!l)throw Error("Expected release tree was not recorded before commit");if(this.ledger){await it(this.ledger.data,m);return}await Mn(m,a),await Dn(m,l)}async createGitTags(e){if(this.options.dryRun)return;let t=await se();for(let r of e){let s=`${r.name}@${r.newVersion??r.version}`;await I(()=>Bun.$`git -c tag.gpgSign=false tag -- ${s}`.quiet(),`Failed to create tag ${s}`),this.createdTags.push(s),this.createdTagTargets.set(s,t)}}async prepareNpmPublish(e){if(this.options.dryRun)return;let t=this.getPackageSetKey(e);if(this.preparedNpmPublish?.key===t)return;let r=this.requireLedger("prepare npm artifacts");this.preparedNpmPublish=null;let s=await Ec(e);if(s.length===0){this.preparedNpmPublish={key:t,packages:[]};return}if(s.some((o)=>!r.data.artifacts[o.name]))await this.prepareBuildOutputs();let n=await _m(pi(Mm(),"sisyphus-publish-")),i=[];try{for(let[o,a]of s.entries()){if(!r.data.artifacts[a.name]){let l=pi(n,`${String(o).padStart(4,"0")}.tgz`);await I(()=>this.prepareNpmArtifact(a,l),`Failed to prepare ${a.name}`),await r.setArtifact(a.name,l)}let c=r.resolveArtifactPath(a.name);Xr(await is(c)),i.push({artifactPath:c,pkg:a})}}finally{await Wc(n,{force:!0,recursive:!0})}this.preparedNpmPublish={key:t,packages:i}}async publishToNpm(e){if(this.options.dryRun)return;let t=this.getPackageSetKey(e);if(this.preparedNpmPublish?.key!==t)await this.prepareNpmPublish(e);let r=this.preparedNpmPublish?.packages??[];if(r.length===0)return;try{for(let s of r)await this.publishPreparedPackage(s)}finally{this.preparedNpmPublish=null}}async pushRelease(){if(this.options.dryRun)return;await this.pushConfiguredRefs()}async createGitRelease(e,t){if(this.options.dryRun)return;if(t.length===0)return;await this.initCommitLinks();let r=await this.getProvider(),s=this.ledger?.data.operations.push;if(s){let n=s.refs.filter((i)=>i.destination.startsWith("refs/tags/"));if(n.length>0)await Ac(s,()=>this.getRepositoryRoot(),n)}for(let n of t){let i=Qn(e,n,this.commitUrlFn);await this.createProviderRelease(r,n.name,i)}}hasCrossedIrreversibleBoundary(){return this.irreversibleOperation!==null||this.ledger?.hasExternalProgress()===!0}createIncompleteReleaseError(e){let t=this.irreversibleOperation??"an external release operation",r=new u(`Release incomplete after ${t} began`,"Local state preserved; run sis roll --resume to reconcile and continue.");return r.cause=e,r}async rollback(e=!0){if(this.hasCrossedIrreversibleBoundary())return!1;if(await this.validateRollbackState(),this.preparedNpmPublish=null,await tc(this.createdCommit,this.createdTags,this.createdTagTargets,()=>this.getRepositoryRoot()),this.commitCreated){if(this.ownedPaths)await Ln(this.ownedPaths);this.commitCreated=!1,this.createdCommit=null}if(this.createdTags=[],this.createdTagTargets.clear(),await this.changelogGenerator.rollback(),await this.packageUpdater.rollback(),e)await this.removeReleaseLedger();return!0}async validateRollbackState(){if(this.rollbackBlockedReason)throw new u(`Cannot roll back release because ${this.rollbackBlockedReason}`,"Local release state and the recovery ledger were preserved");if(this.commitCreated&&!this.createdCommit)throw new u("Cannot identify the release commit for rollback","Local release state and the recovery ledger were preserved");if(this.commitCreated&&this.createdCommit){let[e,t]=await Promise.all([se(),On()]);if(e!==this.createdCommit.oid||t!==this.createdCommit.ref)throw new u(`Cannot roll back release commit because HEAD changed from ${this.createdCommit.oid}`,"Local release state and the recovery ledger were preserved")}if(this.commitCreated&&this.ownedPaths){let e=this.ownedPaths.map((r)=>qe(r));if((await I(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${e}`.quiet(),"Failed to inspect release files before rollback")).stdout.length>0)throw new u("Cannot roll back release because release-owned files changed after commit creation","Local release state and the recovery ledger were preserved")}for(let e of this.createdTags){let t=this.createdTagTargets.get(e),r=await Za(`refs/tags/${e}`);if(!t||r!==t)throw new u(`Cannot roll back release because tag ${e} changed after creation`,"Local release state and the recovery ledger were preserved")}}async removeReleaseLedger(){if(!this.ledger)return;await this.ledger.remove(),this.ledger=null}needsReleaseLedger(e){return this.options.npm||this.options.push||this.options.createRelease||e&&this.options.tags}async recoverReleaseCommit(e){if(e.releaseCommit||!this.ledger)return;let t=await se();if(!e.expectedReleaseTree&&!e.options.publishOnly)throw new u(`Release ${e.id} stopped before its expected release tree was recorded`,`No external operation was attempted; inspect the local changes and release ledger manually; delete ${this.ledger.activePath} to abort the release`);if(!e.options.publishOnly&&t===e.baseCommit)throw new u(`Release ${e.id} stopped before its release commit was created`,`No external operation was attempted; restore the release-owned files from ${e.baseCommit} and delete ${this.ledger.activePath} to abort the release`);await this.ensureExpectedReleaseTree(e,t),await it(this.ledger.data,t),await this.ledger.setReleaseCommit(t)}async ensureLedgerPlan(e,t){if(!this.ledger)return;let r=this.ledger.data;if(await this.reconcileReleaseTags(r),r.options.npm)for(let s of e){if(!r.operations.npm[s.name]||r.operations.npmRegistries[s.name])continue;await this.ledger.setNpmRegistry(s.name,await xc(s))}if(!r.operations.push&&(r.options.push||r.options.publishOnly&&r.options.tags))await this.configureLedgerPush(r);if(r.options.createRelease){await this.initCommitLinks();for(let s of e)await this.ledger.configureProviderRelease(s.name,Qn(t,s,this.commitUrlFn));await this.getProvider()}}async reconcileReleaseTags(e){if(!this.ledger||!e.options.tags)return;if(!e.releaseCommit)throw Error("Cannot reconcile release tags without a release commit");for(let t of e.releaseTags){let r=`refs/tags/${t}`,s=await Bun.$`git rev-parse --verify ${r}`.quiet().nothrow();if(s.exitCode!==0){await I(()=>Bun.$`git -c tag.gpgSign=false tag -- ${t} ${e.releaseCommit}`.quiet(),`Failed to create tag ${t}`);continue}let n=s.stdout.toString().trim();if(n!==e.releaseCommit)throw new u(`Release tag ${t} points to ${n}, expected ${e.releaseCommit}`,"Do not move release tags before the release completes")}if(!e.tagsReady)await this.ledger.markTagsReady()}async configureLedgerPush(e){if(!this.ledger||!e.releaseCommit)throw Error("Cannot configure release push without a recorded release commit");let t=e.releaseCommit,r=e.releaseTags.map((c)=>({destination:`refs/tags/${c}`,oid:t,source:`refs/tags/${c}`}));if(e.options.publishOnly){let c=await Zn(await Xn()),l=await $s(await Rs(c),()=>this.getRepositoryRoot());this.validateProviderDestination(l),await Kn(r),await this.ledger.configurePush(c,l,r);return}let{branch:s,remote:n}=await Oc(),i=await $s(await Rs(n),()=>this.getRepositoryRoot());this.validateProviderDestination(i);let o=`refs/heads/${s}`,a=[{destination:o,oid:e.releaseCommit,source:o},...r];await Kn(a),await this.ledger.configurePush(n,i,a)}validateProviderDestination(e){if(this.options.createRelease&&!Ps(e))throw new u("Push destination is not a supported git provider repository","Provider releases require GitHub, GitLab, or Bitbucket")}async resumeExternalOperations(e,t){let r=this.requireLedger("resume external operations");if(r.phase==="completed"){await this.completeRelease();return}if(r.data.operations.push)await this.pushConfiguredRefs();if(this.options.npm)await this.publishToNpm(e);if(this.options.createRelease)await this.createGitRelease(t,e);await this.completeRelease()}async pushConfiguredRefs(){let e=this.requireLedger("push release refs"),t=e.data.operations.push;if(!t)throw Error("Release push is not configured");if(t.state==="completed")return;if(await Ot(t,()=>this.getRepositoryRoot()),t.state==="started"){await Lc(e,t,()=>this.getRepositoryRoot());return}await e.setPhase("external"),await e.markPush("started"),this.crossIrreversibleBoundary("remote push"),await Ss(t,()=>this.getRepositoryRoot()),await e.markPush("completed")}async publishPreparedPackage(e){let t=this.requireLedger(`publish ${e.pkg.name}`),r=t.data.operations.npm[e.pkg.name];if(!r)throw Error(`Npm operation is not configured for ${e.pkg.name}`);if(r.state==="completed")return;if(r.state==="started"){await Ic(t,e.pkg,()=>this.publishPackage(e));return}await t.setPhase("external"),await t.markNpm(e.pkg.name,"started"),this.crossIrreversibleBoundary("npm publication"),await this.publishPackage(e),await t.markNpm(e.pkg.name,"completed")}requireLedger(e){if(!this.ledger)throw Error(`Cannot ${e} without an active release ledger`);return this.ledger}async createProviderRelease(e,t,r){let s=this.requireLedger(`create the provider release for ${r.tag}`),n=s.data.operations.providerReleases[t];if(!n)throw Error(`Provider release is not configured for ${t}`);if(n.state==="completed")return;if(n.state==="started"){await this.reconcileStartedProviderRelease(e,t,n);return}await s.setPhase("external"),await s.markProviderRelease(t,"started"),this.crossIrreversibleBoundary(`git provider release creation for ${r.tag}`),await I(()=>e.createRelease(r),`Failed to create release for ${r.tag}`),await s.markProviderRelease(t,"completed")}async reconcileStartedProviderRelease(e,t,r){let s=await I(()=>e.getRelease(r.tag),`Failed to inspect release for ${r.tag}`);if(!s)throw new u(`Cannot safely resume provider release ${r.tag}`,"The provider does not confirm the previous creation; inspect the release manually");if(s.draft||s.tag!==r.tag||s.title!==r.title||s.notes!==r.notes)throw new u(`Cannot safely resume provider release ${r.tag}: existing release does not match`,"Do not overwrite the existing release; compare its title and notes with the release ledger");await this.ledger?.markProviderRelease(t,"completed")}async getOwnedPaths(e,t){let r=await this.getRepositoryRoot(),s=this.options.changelog?as(this.config.get("changelog"),e):[],n=[...e.map((o)=>o.file),...s,pi(bt,jr),...this.stoneManager.getFilePaths(t)],i=[...new Set(n.map((o)=>Qa(r,o)))].sort();if(this.ownedPaths&&(this.ownedPaths.length!==i.length||this.ownedPaths.some((o,a)=>o!==i[a])))throw Error("Release paths changed");return this.ownedPaths=i,i}async getRepositoryRoot(){if(this.repositoryRoot)return this.repositoryRoot;let t=(await I(()=>Bun.$`git rev-parse --show-toplevel`.quiet(),"Failed to resolve git repository root")).stdout.toString().trim();if(!t)throw Error("Git repository root is empty");return this.repositoryRoot=Dm(t),this.repositoryRoot}async validatePublishCommitBinding(e){let t=this.requireLedger("bind npm artifacts to a release commit").data;if(!t.releaseCommit||!t.expectedReleaseTree||e!==t.releaseCommit)throw new u(`Publish source does not match the recorded release commit for ${t.id}`,t.releaseCommit?`Check out ${t.releaseCommit} before publishing`:"Resume the release before publishing");await it(t,e)}async ensureExpectedReleaseTree(e,t){if(e.expectedReleaseTree)return;if(!this.ledger||!e.options.publishOnly||t!==e.baseCommit)throw new u(`Release ${e.id} has no recorded expected release tree`,"No external operation was attempted; inspect the release state manually");await this.ledger.setExpectedReleaseTree(await Nn(e.baseCommit))}getPackageSetKey(e){return e.map((t)=>`${t.name}\x00${t.file}`).join("\x00")}async publishPackage(e){let t=this.requireLedger(`publish ${e.pkg.name}`),r=t.data.options.npmTag,s=Xr(await is(e.artifactPath)),n=t.data.operations.npmRegistries[e.pkg.name];if(!n)throw Error(`Npm registry is not configured for ${e.pkg.name}`);let i=At(e.pkg.name,n);await I(()=>Bun.$`npm publish ${e.artifactPath} --tag ${r} --access ${s} --ignore-scripts --registry ${n} ${i}`.cwd(Jc(e.pkg.file)).quiet(),`Failed to publish ${e.pkg.name}`)}async prepareNpmArtifact(e,t){let r=Jc(e.file),s=null;try{let n=await se();await this.validatePublishCommitBinding(n),await tr(await this.getRepositoryRoot()),await this.validateIgnoredBuildInputs();let i=this.getBuildConfig();if(await Va(e,r,await this.getRepositoryRoot(),i.matcher),i.command.length>0)await In(i.command,r,`Failed to build ${e.name}`);let o=await se();await this.validatePublishCommitBinding(o);let a=await rr(await this.getRepositoryRoot());if(o!==n||a.length>0)throw new u(`Package build changed repository source files for ${e.name}`,"This package was not packed and nothing was published; restore the build changes before retrying");let c=await Lm(e.file,"utf-8"),{catalogs:l,workspaceVersions:p}=await this.getPublishContext(),m=Sa(c,l,p);Xr(m);let h=JSON.parse(m),f=e.newVersion??e.version;if(h.name!==e.name||h.version!==f)throw Error(`Packed manifest identity mismatch for ${e.name}: expected ${e.name}@${f}, found ${String(h.name)}@${String(h.version)}`);s=await Ba(e,r,m);let g=await ja(s,t);if(g.name!==e.name||g.version!==f)throw new u(`Packed artifact identity mismatch for ${e.name}: found ${g.name}@${g.version}`,"This package was not recorded and nothing was published");if(!Ua(m,await is(t)))throw new u(`Packed manifest does not match the prepared manifest for ${e.name}`,"This package was not recorded and nothing was published");let y=await se();await this.validatePublishCommitBinding(y);let R=await rr(await this.getRepositoryRoot());if(y!==n||R.length>0)throw new u(`Package packing changed repository source files for ${e.name}`,"This package was not recorded and nothing was published; restore the changes before retrying")}finally{if(s)await Wc(s,{force:!0,recursive:!0})}}async validateIgnoredBuildInputs(){if(this.ignoredBuildInputsValidated)return;await Tn(await this.getRepositoryRoot(),"",this.getBuildConfig().matcher),this.ignoredBuildInputsValidated=!0}getLedgerSnapshot(){return this.ledger?.data??null}getBuildConfig(){return this.buildConfig??=qa(this.config.get("release")?.build),this.buildConfig}async prepareBuildOutputs(){if(this.buildOutputsPrepared)return;let e=this.getBuildConfig(),t=await this.getRepositoryRoot(),r=await se();await this.validatePublishCommitBinding(r),await tr(t),await Wa(t,e.matcher),await En(t,"",e.matcher);for(let[s,n]of e.root.entries())await In(n,t,`Failed to run release root build command ${s}`);if(e.root.length>0){let s=await se();if(await this.validatePublishCommitBinding(s),s!==r||(await rr(t)).length>0)throw new u("Root build changed repository source files","No package was packed and nothing was published; restore the build changes before retrying")}await this.validateIgnoredBuildInputs(),this.buildOutputsPrepared=!0}async getPublishContext(){if(!this.publishContext){let e=await Bun.file("package.json").json(),{packages:t}=await G.scan({single:this.config.get("single")});this.publishContext={catalogs:$a(e),workspaceVersions:Ra(t.values())}}return this.publishContext}crossIrreversibleBoundary(e){this.irreversibleOperation??=e}}import{dirname as Nm}from"path";var jm=1000,Fm=5000;function di(e){if(e===void 0)return 0;if(typeof e==="number"&&Number.isSafeInteger(e)&&e>=0)return e;throw new u(`Invalid release.npmVisibilityTimeout: ${JSON.stringify(e)}`,"Use a whole number of seconds, or 0 to skip the registry visibility check")}async function mi(e,t){let r=t>0?Bm(e):[];if(r.length===0)return[];let s=Date.now()+t*jm,n=new Map,i=r;while(i.length>0){for(let a of i)n.set(a.name,await Vm(a));i=i.filter((a)=>n.get(a.name)==="pending");let o=s-Date.now();if(i.length===0||o<=0)break;await Bun.sleep(Math.min(Fm,o))}return r.map(({name:o,registry:a,version:c})=>({name:o,registry:a,state:n.get(o)??"pending",version:c}))}function gi(e,t){return e.filter((r)=>r.state!=="visible").map((r)=>{let s=`${r.name}@${r.version}`;return r.state==="mismatch"?`${s} on ${r.registry} does not match the integrity of the published artifact`:`${s} is not visible on ${r.registry} after ${t}s; npm may still be processing or holding it`})}function Bm(e){return e.packages.flatMap((t)=>{let r=e.artifacts[t.name],s=e.operations.npmRegistries[t.name];return e.operations.npm[t.name]?.state==="completed"&&r&&s?[{cwd:Nm(t.file),integrity:r.integrity,name:t.name,registry:s,version:t.newVersion}]:[]})}async function Vm(e){let t=`${e.name}@${e.version}`,r=At(e.name,e.registry),s=await Bun.$`npm view ${t} --json --prefer-online --registry ${e.registry} ${r}`.cwd(e.cwd).quiet().nothrow();if(s.exitCode!==0)return"pending";let n=vs(Um(s.stdout.toString()));if(!n||n.name!==e.name||n.version!==e.version)return"pending";return n.integrity===e.integrity?"visible":"mismatch"}function Um(e){try{return JSON.parse(e)}catch{return}}var Gm=6;function xs(e,t){let r=e.map((s)=>hn(s,t));return{skipped:[...new Set(r.flatMap((s)=>s.skipped))].sort(),stones:r.map((s)=>s.stone)}}function yr(e,t,r){let s=[...new Set(e.allPackages)].filter((n)=>!t.has(n)&&!ee(n,r)).sort();if(s.length>0)return{kind:"unknown-packages",names:s};return{kind:"ignored-only"}}function hi(e,t,r,s){let{stone:n}=hn(e,r),i=yr(n,t,r);if(i.kind==="unknown-packages")return{kind:"invalid",message:`Pending stones reference unknown packages: ${i.names.join(", ")}`};try{return{kind:"ok",packages:z.applyStone(n,t,s).flatMap((a)=>a.bump&&a.newVersion?[{bump:a.bump,name:a.name,newVersion:a.newVersion,version:a.version}]:[])}}catch(o){if(o instanceof u)return{kind:"invalid",message:o.message};throw o}}function zc(e,t){let r=t.map((o)=>`${o.name}@${o.newVersion??o.version}`),s=r.slice(0,Gm),n=r.length-s.length,i=n>0?` +${n} more`:"";return`${e} ${s.join(", ")}${i}`}var Hm=1;function Kc(e){let{ledger:t}=e,r=t?qm(t,e.npmVisibility??[]):Jm(e.packages),s=r.filter((i)=>i.published).map((i)=>({name:i.name,version:i.newVersion})),n={baseCommit:t?.baseCommit??null,command:"roll",mode:e.mode,operations:{npmTag:t?.options.npmTag??e.npmTag,providerReleases:Km(t),pushed:t?.operations.push?.state==="completed"},packages:r,published:s.length>0,publishedPackages:s,releaseCommit:t?.releaseCommit??e.releaseCommit??null,releaseId:t?.id??null,schemaVersion:Hm,status:e.status,stones:t?t.stones.map((i)=>i.id):e.stones.map((i)=>i.id),tags:t?t.tagsReady?[...t.releaseTags]:[]:zm(e.packages,e.tagsEnabled),warnings:[...e.warnings??[]]};if(e.changelogFiles)n.changelogFiles=[...e.changelogFiles];if(e.error!==void 0)n.error=Ym(e.error);return n}function qm(e,t){return e.packages.map((r)=>({integrity:e.artifacts[r.name]?.integrity??null,name:r.name,newVersion:r.newVersion,oldVersion:r.oldVersion,private:r.isPrivate,published:e.operations.npm[r.name]?.state==="completed",registry:e.operations.npmRegistries[r.name]??null,tag:e.tagsReady?e.releaseTags.find((s)=>s===Yc(r.name,r.newVersion))??null:null,visible:Wm(t,r.name)}))}function Wm(e,t){let r=e.find((s)=>s.name===t);return r?r.state==="visible":null}function Yc(e,t){return`${e}@${t}`}function Jm(e){return e.map((t)=>({integrity:null,name:t.name,newVersion:t.newVersion??t.version,oldVersion:t.version,private:t.isPrivate,published:!1,registry:null,tag:null,visible:null}))}function zm(e,t){if(!t)return[];return e.map((r)=>Yc(r.name,r.newVersion??r.version)).sort()}function Km(e){let t=Object.values(e?.operations.providerReleases??{});return t.length>0&&t.every((r)=>r.state==="completed")}function Ym(e){let t=e instanceof Error?e.message:String(e),r=e instanceof u?e.hint:void 0,s=Xc(e);return{...s.length>0?{causes:s}:{},...r?{hint:r}:{},message:t}}function Xc(e,t=new Set){if(!(e instanceof Error)||t.has(e))return[];return t.add(e),[...e instanceof AggregateError?e.errors:[],e.cause].filter((n)=>n instanceof Error).flatMap((n)=>[n.message,...Xc(n,t)])}var Ts="sisyphus/release",fi="sisyphus-release",Xm="Sisyphus release PR",Zm="6f42c1",Zc="chore(release):",Qm=U({dryRun:{alias:"d",default:!1,description:"Preview without making changes",type:"boolean"}});class yi extends j{name="release-pr";description="Create or update a release PR from pending stones";args=Qm;provider=null;async getProvider(){if(!this.provider)this.provider=await vt();return this.provider}async execute(e){let t=await this.checkoutReleaseBranch(e.args.dryRun);try{let{stones:r,packages:s}=await this.collectReleaseData(e);if(r.length===0){v.info(d.dim("No pending stones found, skipping release PR"));return}let n=this.buildPrTitle(s),i=this.buildPrBody(s,r);if(v.info(`${d.bold("Release PR:")} ${n}`),v.info(`${d.dim("Packages:")} ${s.map((o)=>o.name).join(", ")}`),e.args.dryRun){v.info(d.yellow(`
|
|
178
|
+
[dry-run] Would create/update release PR`)),v.info(d.dim(`
|
|
179
|
+
PR Body preview:`)),v.info(i);return}await this.commitAndPushChanges(e,r,s),await this.createOrUpdatePr(n,i)}finally{await this.restoreBranch(t)}}async checkoutReleaseBranch(e){if((await Bun.$`git status --porcelain=v1 --untracked-files=all`.quiet()).stdout.length>0)throw new u("Working tree must be clean before preparing a release PR","Commit or stash your changes before running sis actions release-pr");let s=(await Bun.$`git branch --show-current`.quiet()).stdout.toString().trim()||(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim(),i=await(await this.getProvider()).getDefaultBranch();if(await Bun.$`git fetch origin ${i}`,e)await Bun.$`git checkout --detach origin/${i}`;else await Bun.$`git checkout -B ${Ts} origin/${i}`;return s}async collectReleaseData(e){let t=new O(e.config),r=await this.generateStonesFromCommits(e,t,e.args.dryRun),s=await t.list(),n=e.args.dryRun?[...s,...r]:s;if(n.length===0)return{packages:[],stones:[]};let i=e.config.get("ignore")??[],{stones:o,skipped:a}=xs(n,i);if(a.length>0)v.warn(d.yellow(`Excluded by config.ignore: ${a.join(", ")}`));let{packages:c}=await G.scan({single:e.config.get("single")}),l=M.mergeAll(o),p=yr(l,c,i);if(p.kind==="unknown-packages")throw new u(`Pending stones reference unknown packages: ${p.names.join(", ")}`,"Remove or update the stale stones before creating a release PR");let{cycle:m,ordered:h}=Xt(z.applyStone(l,c,ce(e.config).kinds));if(m.length>0)v.warn(d.yellow(`Dependency cycle between ${m.join(", ")}; publish order may not satisfy every pin`));if(h.length===0)return v.warn(d.yellow("Pending stones reference no releasable packages")),{packages:[],stones:[]};return{packages:h,stones:o}}async commitAndPushChanges(e,t,r){let s=be();s.start("Applying release changes...");try{let n=[...await this.updatePackages(r),...await this.generateChangelogs(e,t,r)],i=await this.archiveStones(e,t);if(await this.stageFiles(n),await this.recordCurrentRelease(e,t,r,i),await this.stageFiles([e.config.get("sisyphusDir")]),(await Bun.$`git diff --cached --quiet`.nothrow()).exitCode!==0)await Bun.$`git commit -m ${`${Zc} prepare release`}`;await Bun.$`git push origin ${Ts} --force`,s.stop("Release branch ready")}catch(n){throw s.error("Release preparation failed"),n}}async createOrUpdatePr(e,t){let r=be(),s=await this.findExistingReleasePr();if(s)r.start("Updating PR..."),await this.updatePr(s.number,e,t),r.stop(`PR #${s.number} updated`),v.info(`
|
|
180
|
+
${d.green("Release PR updated:")} ${s.url}`);else{r.start("Creating PR...");let n=await this.createPr(e,t);r.stop(`PR #${n.number} created`),v.info(`
|
|
181
|
+
${d.green("Release PR created:")} ${n.url}`)}}buildPrTitle(e){return zc(Zc,e)}buildPrBody(e,t){return[this.buildChangesSection(t),this.buildPackagesSection(e),this.buildStonesSection(t),this.buildFooter()].join(`
|
|
182
182
|
`)}buildChangesSection(e){let t=["## Changes",""];for(let r of e){if(t.push(`### ${r.message}`,""),r.commits&&r.commits.length>0)for(let s of r.commits)t.push(`- ${s.message} (\`${s.hash}\`)`);else if(r.description)t.push(r.description);t.push("")}return t.join(`
|
|
183
183
|
`)}buildPackagesSection(e){let t=["## Packages",""];for(let r of e)t.push(`- \`${r.name}\` ${r.version} \u2192 ${r.newVersion}`);return t.push(""),t.join(`
|
|
184
184
|
`)}buildStonesSection(e){let t=["## Stones",""];for(let r of e)t.push(`- \`${r.id}\`: ${r.message}`);return t.push(""),t.join(`
|
|
185
185
|
`)}buildFooter(){return["---","*This PR was automatically created by [Sisyphus](https://github.com/r5n-labs/clis).*","*Merging this PR will trigger the release workflow.*"].join(`
|
|
186
|
-
`)}async findExistingReleasePr(){let t=await(await this.getProvider()).findPr({head:Ts,label:
|
|
187
|
-
${t}`)}printRootInfo(e){if(!e)return;let t=e.version?
|
|
186
|
+
`)}async findExistingReleasePr(){let t=await(await this.getProvider()).findPr({head:Ts,label:fi});return t?{number:t.number,url:t.url}:null}async generateStonesFromCommits(e,t,r){let n=await new st(e.config).analyze({single:e.config.get("single")});if(n.length===0)return[];let{packages:i}=await G.scan({single:e.config.get("single")}),o=[];for(let[a,c]of n.entries()){let l=st.buildStoneData(c,i,ce(e.config));if(r)v.info(`${d.dim("[dry-run] Would generate stone:")} ${c.message}`),o.push(M.create(l,a));else{let p=await t.create(l);o.push(p),v.info(`${d.dim("Generated stone:")} ${p.id}`)}}return o}async findNewestCommitHash(e){let t=e.flatMap((s)=>s.commits??[]).map((s)=>s.hash);if(t.length===0)return null;return(await Bun.$`git log -1 --format=%H ${t}`.quiet().nothrow()).stdout.toString().trim()||null}async stageFiles(e){await Bun.$`git --literal-pathspecs add -- ${e}`}async updatePackages(e){return await new Qt().updateAll(e),e.map((r)=>r.file)}async generateChangelogs(e,t,r){let s=e.config.get("changelog");if(!s.generate)return[];return await new rt(s).generate(t,r),as(s,r)}async archiveStones(e,t){return new O(e.config).archive(t)}async recordCurrentRelease(e,t,r,s){let n=this.buildPackageVersions(r),i=await es(e.config.get("sisyphusDir")),o={packages:n,sourceHash:i,stoneIds:t.map((a)=>a.id),timestamp:s};e.config.set("currentRelease",{...o,planHash:ts(o,t.map((a)=>a.toJson()))}),await this.updateLastStone(e,t)}buildPackageVersions(e){let t={};for(let r of e)if(r.newVersion)t[r.name]={newVersion:r.newVersion,oldVersion:r.version};return t}async updateLastStone(e,t){let r=await this.findNewestCommitHash(t);if(r)e.config.set("lastStone",{commit:r,date:new Date().toISOString()})}async createPr(e,t){let r=await this.getProvider(),s=await r.getDefaultBranch();await r.ensureLabelExists(fi,{color:Zm,description:Xm});let n=await r.createPr({base:s,body:t,head:Ts,labels:[fi],title:e});return{number:n.number,url:n.url}}async updatePr(e,t,r){await(await this.getProvider()).updatePr(e,{body:r,title:t})}async restoreBranch(e){try{await Bun.$`git checkout ${e}`.quiet()}catch(t){v.warn(d.dim(`Failed to restore branch: ${t}`))}}}class wi extends j{name="actions";description="CI/CD integration";init(){this.registerSubcommands([new an,new yi])}}var eg=U({config:{alias:"c",default:!1,description:"Include config in output",type:"boolean"},json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}});class bi extends j{name="check";description="Show workspace packages and pending stones";args=eg;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"),r=e.config.get("ignore")??[],s=await G.scan({single:t}),n=s.packages,i=s.packageNames.filter((p)=>!ee(p,r)),a=(t?null:await G.scan({single:!0}))?.packages.values().next().value??n.values().next().value,l=await new O(e.config).list();return{config:e.args.config?e.config.getAll():void 0,ignore:r,kinds:ce(e.config).kinds,packageNames:i,packages:n,root:a,stones:l}}printJson(e){let t={config:e.config,packages:e.packageNames.map((r)=>({name:r,version:e.packages.get(r)?.version??"0.0.0"})),root:{name:e.root?.name??"",version:e.root?.version??"0.0.0"},stones:e.stones.map((r)=>this.stoneToJson(r,e))};console.log(JSON.stringify(t,null,2))}stoneToJson(e,t){let r=hi(e,t.packages,t.ignore,t.kinds);if(r.kind==="invalid")return{id:e.id,invalid:r.message,message:e.message,packages:[],tag:e.tag};return{id:e.id,message:e.message,packages:r.packages,tag:e.tag}}printFormatted(e){if(this.printRootInfo(e.root),this.printPackages(e),e.stones.length>0)this.printStones(e);if(e.config)this.printConfig(e.config);q(d.green("Sisyphus check complete."))}printConfig(e){let t=d.dim(JSON.stringify(e,null,2));v.step(`${d.bold(d.green("Config:"))}
|
|
187
|
+
${t}`)}printRootInfo(e){if(!e)return;let t=e.version?d.dim(`@${e.version}`):"";v.step(`${d.bold(d.green("Root package:"))} ${d.cyan(e.name)}${t}`)}printPackages(e){let t=[`${d.bold(d.green("Packages:"))}`];for(let r of e.packageNames){let s=e.packages.get(r),n=s?.version?d.dim(`@${s.version}`):"";t.push(` ${d.dim("\u2022")} ${d.cyan(r)}${n}`)}v.step(t.join(`
|
|
188
188
|
`))}printStones(e){let t=e.stones.map((r)=>this.formatStone(r,e)).join(`
|
|
189
189
|
|
|
190
|
-
`);v.step(`${
|
|
190
|
+
`);v.step(`${d.bold(d.green("Stones:"))}
|
|
191
191
|
|
|
192
|
-
${t}`)}formatStone(e,t){let r=[];if(r.push(`${
|
|
193
|
-
`);for(let n of s.packages){let i=Pt[n.bump],o=$t[n.bump];r.push(` ${o} ${
|
|
194
|
-
`)}}var
|
|
192
|
+
${t}`)}formatStone(e,t){let r=[];if(r.push(`${d.bold("Stone:")} ${d.cyan(e.id)}`),e.tag)r.push(`${d.dim("Tag:")} ${e.tag}`);r.push(`${d.dim("Message:")} ${e.message}`),r.push(`${d.bold("Packages:")}`);let s=hi(e,t.packages,t.ignore,t.kinds);if(s.kind==="invalid")return r.push(` ${d.yellow(`invalid: ${s.message}`)}`),r.join(`
|
|
193
|
+
`);for(let n of s.packages){let i=Pt[n.bump],o=$t[n.bump];r.push(` ${o} ${d.cyan(n.name)}@${i(n.newVersion)} ${d.dim(`(${n.bump})`)}`)}return r.join(`
|
|
194
|
+
`)}}var tg=U({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 vi extends j{name="init";description="Initializes Sisyphus config or edits it";args=tg;async execute(e){let{default:t,force:r}=e.args;if(t){e.config.save(Ue),await this.setLastStoneToHead(e),this.displaySuccessNote(e.cli.version);return}if(!e.interactive&&e.config.exists()&&!r){q(d.yellow("Config already exists. Use --force to replace."));return}let s=e.config.getAll(),{default:n,force:i,...o}=e.args,a=e.interactive?await this.runInitForm(s):o,c=this.mapValuesToConfig(a),l=mt({...s},c);e.config.save(l),await this.setLastStoneToHead(e),this.displaySuccessNote(e.cli.version)}mapValuesToConfig(e){let t=(o)=>Object.fromEntries(Object.entries(o).filter(([,a])=>a!==void 0)),r=(o)=>Object.keys(o).length>0,s=t({author:e.commitAuthor,email:e.commitEmail,message:e.commitMessage}),n=t({generate:e.changelog,root:e.rootChangelog}),i=t({createRelease:e.createRelease,npm:e.npm,push:e.push,tags:e.tags});return{...t({single:e.single,tag:e.tag}),...r(s)&&{commit:s},...r(n)&&{changelog:n},...r(i)&&{release:i}}}async runInitForm(e){let t=await xr({changelog:()=>V({active:"Yes, generate changelog",inactive:"Skip changelog",initialValue:e.changelog?.generate??!0,message:"Generate changelog for release?"}),configureCommit:()=>V({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>`"}),commitAuthor:({results:{configureCommit:r}})=>r?le({initialValue:e.commit?.author??"",message:"Commit author",placeholder:"r5n-bot"}):void 0,commitEmail:({results:{configureCommit:r}})=>r?le({initialValue:e.commit?.email??"",message:"Commit author email",placeholder:"r5n-bot@users.noreply.github.com"}):void 0,commitMessage:({results:{configureCommit:r}})=>r?le({initialValue:e.commit?.message??"",message:"Commit message",placeholder:"release: <packageName@version>"}):void 0,createRelease:()=>V({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:()=>V({active:"Yes, publish packages to NPM",inactive:"Skip NPM release",initialValue:e.release?.npm??!1,message:"Publish packages to NPM when releasing packages?"}),push:()=>V({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:r}})=>r?V({active:"Yes, generate combined changelog",inactive:"Skip root changelog",initialValue:e.changelog?.root??!1,message:"Generate combined changelog for monorepo?"}):void 0,single:()=>V({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:()=>le({initialValue:e.tag??"latest",message:"Tag used when versioning packages. Leave `latest` if you are not sure.",placeholder:"latest"}),tags:()=>V({active:"Yes, create tags for the release",inactive:"Skip tags",initialValue:e.release?.tags??!1,message:"Create tags for the release?"})},{onCancel:()=>{throw new we}});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 r=(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim();if(r)e.config.set("lastStone",{commit:r,date:new Date().toISOString()})}catch{}}displaySuccessNote(e){q(`${d.magenta(`${d.bold("Sisyphus ")}${d.underline(d.italic(`v${e??"unknown"}`))}`)}${d.green(" is setup to roll stones.")}
|
|
195
195
|
|
|
196
|
-
You can now start by creating a new stone by running ${
|
|
196
|
+
You can now start by creating a new stone by running ${d.green(F)}${d.blue(" version")}
|
|
197
197
|
and following the prompts.
|
|
198
198
|
|
|
199
|
-
After you finished, you can release it by running ${
|
|
200
|
-
`)}}var
|
|
199
|
+
After you finished, you can release it by running ${d.green(F)}${d.blue(" roll")}
|
|
200
|
+
`)}}var rg=U({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 $i extends j{name="migrate";description="Migrate from changesets to sisyphus";args=rg;parser=new mn;async execute(e){if(!await this.parser.exists())throw new u("No .changeset directory found","This command migrates existing changesets to sisyphus stones");let{changesets:t,config:r}=await this.analyzeChangesets();if(this.displayPreview(t,r),e.args.dryRun){q("No changes made",d.yellow("Dry run"));return}let s=this.collectStoneData(t);if(!e.args.yes&&process.stdout.isTTY!==!0)throw new u("Non-interactive migration requires --yes","Use --yes to migrate or --dry-run to preview without changes");if(!e.args.yes&&!await this.confirmMigration(t.length))return;let n=await this.createStones(e,s);await this.applyConfigMigration(e,r),this.displaySuccess(n)}async analyzeChangesets(){let e=be();e.start("Analyzing changesets...");let t=await this.parser.parse();if(t.errors.length>0){e.error("Found issues while parsing");for(let r of t.errors)v.warn(d.yellow(r))}if(t.changesets.length===0)throw e.stop("No changesets found"),new u("No changeset files to migrate");return e.stop(`Found ${d.bold(String(t.changesets.length))} changeset(s)`),t}displayPreview(e,t){if(this.displayChangesets(e),t)this.displayConfigMapping(t)}async confirmMigration(e){return V({initialValue:!0,message:`Migrate ${e} changeset(s) to stones?`})}collectStoneData(e){let t=[],r=[];for(let s of e)try{t.push(this.parser.toStoneData(s))}catch(n){if(!(n instanceof u))throw n;r.push(n.message)}if(r.length>0)throw new u(`Cannot migrate changesets:
|
|
201
201
|
${r.join(`
|
|
202
|
-
`)}`,"Rewrite them as major, minor, or patch before migrating; no stones were created");return t}async createStones(e,t){let r=be();r.start("Creating stones...");let s=new O(e.config),n=[];for(let i of t){let o=await s.create(i);n.push(o.id)}return r.stop(`Created ${
|
|
202
|
+
`)}`,"Rewrite them as major, minor, or patch before migrating; no stones were created");return t}async createStones(e,t){let r=be();r.start("Creating stones...");let s=new O(e.config),n=[];for(let i of t){let o=await s.create(i);n.push(o.id)}return r.stop(`Created ${d.bold(String(n.length))} stone(s)`),n}async applyConfigMigration(e,t){if(!t)return;let r=be();r.start("Migrating config..."),this.migrateConfig(e,t),r.stop("Config migrated")}displaySuccess(e){let t=e.map((r)=>` ${d.dim("-")} ${r}`).join(`
|
|
203
203
|
`);q(`${t}
|
|
204
204
|
|
|
205
|
-
Run ${
|
|
206
|
-
Run ${
|
|
207
|
-
${
|
|
208
|
-
${
|
|
209
|
-
`),s.color(s.title))}migrateConfig(e,t){if(t.ignore?.length){let r=e.config.get("ignore")??[],s=[...new Set([...r,...t.ignore])];e.config.set("ignore",s)}if(t.commit===!0){let r=e.config.get("commit")??{},s=e.config.get("release")??{};e.config.set("commit",{...r,author:r.author??"Sisyphus"}),e.config.set("release",{...s,push:!0})}if(t.access==="public"){let r=e.config.get("release")??{};e.config.set("release",{...r,npm:!0})}if(t.changelog===!1){let r=e.config.get("changelog")??{};e.config.set("changelog",{...r,generate:!1})}}}var
|
|
210
|
-
or create another stone with ${
|
|
211
|
-
`))}}import{rm as
|
|
205
|
+
Run ${d.green(`${F} stone list`)} to view stones
|
|
206
|
+
Run ${d.green(`${F} roll --preview`)} to see what will be released`,d.green("Migration complete"))}displayChangesets(e){for(let t of e){let r=Object.entries(t.packages).map(([n,i])=>{let o=i==="major"?d.red:i==="minor"?d.yellow:d.green;return`${n} ${d.dim("(")}${o(i)}${d.dim(")")}`}).join(", "),s=t.summary.length>60?`${t.summary.slice(0,60)}...`:t.summary;v.info(`${d.dim(t.filename)}
|
|
207
|
+
${d.dim("Packages:")} ${r}
|
|
208
|
+
${d.dim("Message:")} ${s||d.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)`}],r={info:{color:d.blue,items:[],title:"Info (not migrated)"},migrate:{color:d.green,items:[],title:"Will migrate"},unsupported:{color:d.yellow,items:[],title:"Not yet supported"}};for(let s of t)if(s.check())r[s.category].items.push(d.dim(s.format()));for(let s of[r.migrate,r.info,r.unsupported])if(s.items.length>0)q(s.items.join(`
|
|
209
|
+
`),s.color(s.title))}migrateConfig(e,t){if(t.ignore?.length){let r=e.config.get("ignore")??[],s=[...new Set([...r,...t.ignore])];e.config.set("ignore",s)}if(t.commit===!0){let r=e.config.get("commit")??{},s=e.config.get("release")??{};e.config.set("commit",{...r,author:r.author??"Sisyphus"}),e.config.set("release",{...s,push:!0})}if(t.access==="public"){let r=e.config.get("release")??{};e.config.set("release",{...r,npm:!0})}if(t.changelog===!1){let r=e.config.get("changelog")??{};e.config.set("changelog",{...r,generate:!1})}}}var Qc=100;function sg(e,t){if(!e)return;let r=new Set(t),s=e.map((n)=>({...n,packages:n.packages.filter((i)=>r.has(i))})).filter((n)=>n.packages.length>0);return s.length>0?s:void 0}var ng=U({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 Pi extends j{name="pr";description="Create a stone from a Pull Request";args=ng;prompts=!0;async execute(e){let r=await new wn(e.config).analyze(e.args.url);this.displayPrSummary(r.pr);let s=this.shouldSkipPr(e,r.pr);if(s){v.info(d.dim(`Skipping: ${s}`));return}if(r.packages.size===0)throw new u("No packages affected by this PR","The PR only modifies root files or files outside packages");let n=await this.determineBumpType(e,r.suggestedBump,r.pr.labels),i=await this.determinePackages(e,r.packages);if(i.length===0)throw new u("No packages selected");let o=e.config.get("ignore")??[];if(e.args.packages){let y=i.filter((R)=>ee(R,o));if(y.length>0)throw new u(`Packages are excluded by config.ignore: ${y.join(", ")}`,"Remove them from ignore before releasing them")}let a=i.filter((y)=>!ee(y,o));if(a.length===0){v.info(d.dim("Skipping: every affected package is excluded by config.ignore"));return}let{packages:c}=await G.scan({single:e.config.get("single")}),l=`[#${r.pr.number}](${r.pr.url})`,p=e.args.message??`${r.pr.title} (${l})`,m=r.pr.body||void 0,h=this.buildStoneData({allPackages:c,bump:n,commits:r.commits,dependents:ce(e.config),description:m,message:p,packages:a});if(this.logPreview(h,e.args.dryRun),e.args.dryRun)return;if(!e.args.yes&&e.interactive){if(!await V({initialValue:!0,message:"Create this stone?"}))return}let g=await new O(e.config).create(h);q(`Run ${d.green(`${F} roll`)} to release packages
|
|
210
|
+
or create another stone with ${d.green(`${F} version`)}`,`Stone ${d.bold(g.id)} ${d.green("created")}`)}displayPrSummary(e){if(v.info(`PR #${d.bold(String(e.number))}: ${e.title}`),v.info(`${d.dim("Author:")} ${e.author}`),v.info(`${d.dim("Branch:")} ${e.branch}`),e.labels.length>0)v.info(`${d.dim("Labels:")} ${e.labels.map((t)=>d.cyan(t)).join(", ")}`)}shouldSkipPr(e,t){let r=e.config.get("pr").skip;for(let s of t.labels)if(r.labels.some((n)=>n.toLowerCase()===s.toLowerCase()))return`label "${s}" is in skip list`;if(r.authors.some((s)=>s.toLowerCase()===t.author.toLowerCase()))return`author "${t.author}" is in skip list`;for(let s of r.titlePatterns)try{if(new RegExp(s,"i").test(t.title))return`title matches skip pattern "${s}"`}catch{v.warn(d.yellow(`Invalid regex pattern in pr.skip.titlePatterns: "${s}"`))}return null}async determineBumpType(e,t,r){if(e.args.bump!==void 0){if(e.args.bump!=="major"&&e.args.bump!=="minor"&&e.args.bump!=="patch")throw new u(`Invalid bump type: ${e.args.bump}`,"Use major, minor, or patch");return e.args.bump}if(t)return v.info(`${d.dim("Detected bump:")} ${d.bold(t)} (from ${this.getBumpSource(t,r,e)})`),t;if(e.args.yes)throw new u("Cannot determine bump type automatically","Add a label to the PR or use --bump to specify explicitly");if(!e.interactive)throw new u("Cannot determine bump type","Use --bump to specify explicitly");return Xe({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,r){let s=r.config.get("pr").labelMapping;for(let n of t){let i=n.toLowerCase();for(let[o,a]of Object.entries(s))if(i===o.toLowerCase()&&a===e)return`label: ${n}`}return"title"}async determinePackages(e,t){let r=Array.from(t);if(e.args.packages){let s=e.args.packages.split(",").map((i)=>i.trim()).filter(Boolean),n=s.filter((i)=>!t.has(i));if(n.length>0)throw new u(`Packages not affected by this PR: ${n.join(", ")}`,`Affected packages: ${r.join(", ")}`);return s}if(r.length===1||e.args.yes||!e.interactive)return v.info(`${d.dim("Affected packages:")} ${r.map((s)=>d.bold(s)).join(", ")}`),r;return xe({initialValues:r,message:"Select packages to include",options:r.map((s)=>({label:s,value:s})),required:!0})}buildStoneData(e){let{allPackages:t,bump:r,commits:s,dependents:n,description:i,message:o,packages:a}=e,c={commits:sg(s,a),description:i,message:o};if(r==="major")c.major=a;else if(r==="minor")c.minor=a;else c.patch=a;return c.dependency=K(St(a.map((l)=>({bump:r,name:l})),t,n)),c}logPreview(e,t){let r=[];if(t)r.push(d.bold(d.yellow("[dry-run]")));if(r.push(`${d.dim("Stone:")} ${d.bold(e.message)}`),e.major?.length)r.push(` ${d.red("major")}: ${e.major.join(", ")}`);if(e.minor?.length)r.push(` ${d.yellow("minor")}: ${e.minor.join(", ")}`);if(e.patch?.length)r.push(` ${d.green("patch")}: ${e.patch.join(", ")}`);if(e.commits?.length)r.push(` ${d.dim(`${e.commits.length} commit(s)`)}`);if(e.description){let s=e.description.length>Qc?`${e.description.slice(0,Qc)}...`:e.description;r.push(` ${d.dim("Description:")} ${s}`)}v.step(r.join(`
|
|
211
|
+
`))}}import{rm as og}from"fs/promises";import{dirname as ag,join as cg}from"path";var ig=1;function el(){let e=process.stdout.write.bind(process.stdout),t=console.log;return process.stdout.write=(r,...s)=>process.stderr.write(r,...s),console.log=(...r)=>console.error(...r),()=>{process.stdout.write=e,console.log=t}}function wr(e){if(e){let r=()=>{return};return{info:r,json:e,note:r,start:r,step:r,stop:r,warn:r}}let t=be();return{info:(r)=>v.info(r),json:e,note:(r,s)=>q(r,s),start:(r)=>t.start(r),step:(r)=>v.step(r),stop:(r)=>t.stop(r),warn:(r)=>v.warn(r)}}function Ri(e,t){t?.(),console.log(JSON.stringify(e,null,2))}function tl(e,t,r){if(Ri(e,r),console.error(t instanceof Error?t.message:String(t)),t instanceof u&&t.hint)console.error(t.hint);for(let s of e.error?.causes??[])console.error(s);process.exit(t instanceof u?t.exitCode:ig)}var rl=/\d{14}$/,lg="Pending stones reference only ignored packages",ug="--json requires --yes in an interactive terminal",pg="Pass --yes to consent to the release, or use --dryRun to preview it",sl=U({abort:{default:!1,description:"Abandon the incomplete release if nothing external has started",type:"boolean"},changelog:{alias:"c",description:"Generate changelogs",type:"boolean"},createRelease:{alias:"r",description:"Create a release on git provider",type:"boolean"},dryRun:{alias:"d",description:"Preview without making changes",type:"boolean"},json:{alias:"j",default:!1,description:"Output the release result as JSON",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 and optionally keep the files",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"},resume:{default:!1,description:"Resume an incomplete release",type:"boolean"},tags:{alias:"t",description:"Create git tags",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class Si extends j{name="roll";description="Execute a release from pending stones";args=sl;reportContext={mode:"release",npmTag:he,packages:[],stones:[]};restoreStdout;npmVisibilityTimeout=0;stdoutWasTTY=!1;warnings=[];async execute(e){if(this.stdoutWasTTY=process.stdout.isTTY===!0,!e.args.json){await this.run(e);return}let t=el();this.restoreStdout=t;try{await this.run(e),t()}catch(r){this.reportContext.ledger??=(await Re.loadActive().catch(()=>null))?.data,tl(this.buildReport(e,"failed",{error:r}),r,t)}}buildReport(e,t,r={}){return Kc({ledger:this.reportContext.ledger??null,mode:this.reportContext.mode,npmTag:this.reportContext.npmTag,npmVisibility:this.reportContext.npmVisibility,packages:this.reportContext.packages,releaseCommit:this.reportContext.releaseCommit,status:t,stones:this.reportContext.stones,tagsEnabled:this.reportContext.tagsEnabled??e.args.tags??e.config.get("release").tags,warnings:this.warnings,...r})}emit(e,t,r={}){if(!e.args.json)return;Ri(this.buildReport(e,t,r),this.restoreStdout)}async run(e){if(Be(e.args,sl,"Run 'sis roll --help' for supported options"),this.validateModeFlags(e),e.args.abort){this.reportContext.mode="abort",await this.executeAbort(e);return}if(this.npmVisibilityTimeout=di(e.config.get("release").npmVisibilityTimeout),e.args.resume){this.reportContext.mode="resume",await this.executeResume(e);return}if(e.args.publishOnly){this.reportContext.mode="publish-only",await this.executePublishOnly(e);return}await De.assertNoActiveRelease();let t=this.resolveOptions(e),s=await new O(e.config).list();if(s.length===0)throw new u("No pending stones found",`Create a stone with ${d.green(`${F} version`)} first`);let{packages:n}=await G.scan({single:e.config.get("single")}),i=e.config.get("ignore")??[],{skipped:o,stones:a}=xs(s,i);if(o.length>0)this.recordWarning(e,`Excluded by config.ignore: ${o.join(", ")}`);let c=M.mergeAll(a),l=yr(c,n,i);if(l.kind==="unknown-packages")throw new u(`Pending stones reference unknown packages: ${l.names.join(", ")}`,"Remove the stale stones or restore the packages before rolling");let p=this.planPackages(e,z.applyStone(c,n,ce(e.config).kinds)),m=t.dryRun?"dry-run":e.args.preview?"preview":"release";if(p.length===0){this.recordWarning(e,lg),this.reportContext={mode:m,npmTag:he,packages:[],stones:s,tagsEnabled:t.tags},this.emit(e,"planned");return}if(this.reportContext={mode:m,npmTag:he,packages:p,stones:s,tagsEnabled:t.tags},this.reportContext.npmTag=this.resolveReportNpmTag(e,p,t.npm),e.args.preview){await this.previewChangelogs(e,s,p);return}let h=wr(e.args.json);if(this.printPreview(h,c,p,t),!t.dryRun&&!e.args.yes&&this.stdoutWasTTY){if(this.assertJsonConsent(e),!await V({initialValue:!0,message:"Proceed with release?"}))return}if(t.dryRun){h.info(d.yellow("Dry run complete - no changes made")),this.emit(e,"planned");return}await this.executeRelease(e,h,c,p,s,t)}planPackages(e,t){let{kept:r,skipped:s}=da(t,e.config.get("ignore")??[]);if(s.length>0)this.recordWarning(e,`Excluded by config.ignore: ${s.join(", ")}`);let{cycle:n,ordered:i}=Xt(r);if(n.length>0)this.recordWarning(e,`Dependency cycle between ${n.join(", ")}; publish order may not satisfy every pin`);return i}recordWarning(e,t){if(this.warnings.push(t),!e.args.json)v.warn(d.yellow(t))}async verifyNpmVisibility(e,t){let r=this.reportContext.ledger;if(!r?.options.npm||this.npmVisibilityTimeout===0)return;t.start("Checking npm registry visibility...");try{this.reportContext.npmVisibility=await mi(r,this.npmVisibilityTimeout),t.stop("Npm registry visibility checked")}catch(s){t.stop("Npm registry visibility check failed"),this.recordWarning(e,`Could not check npm registry visibility: ${s instanceof Error?s.message:String(s)}`);return}for(let s of gi(this.reportContext.npmVisibility,this.npmVisibilityTimeout))this.recordWarning(e,s)}assertJsonConsent(e){if(!e.args.json)return;throw new u(ug,pg)}resolveReportNpmTag(e,t,r){if(!r)return he;try{return fr(t,e.config.get("tag"))}catch(s){let n=bs(e.config.get("tag"));return this.recordWarning(e,`Npm publication would fail: ${s instanceof Error?s.message:String(s)}`),n}}async previewChangelogs(e,t,r){let s=e.config.get("changelog"),n=new rt(s),i=wr(e.args.json);i.start("Generating changelog preview..."),await n.generate(t,r),i.stop("Changelog preview generated");let o=r.map((c)=>cg(ag(c.file),s.filename));if(s.root)o.push(s.filename);if(i.info(`
|
|
212
212
|
Preview files created:
|
|
213
|
-
${o.map((c)=>
|
|
214
|
-
`)}`),i.info(""),await this.resolvePreviewRevert(e,n,i))await n.rollback(),i.info(
|
|
215
|
-
`))}async executeRelease(e,t,r,s,n,i){let o=new De(e.config,i),a={...e.config.get("lastStone")},c=e.config.path,l=await Bun.file(c).exists()?await Bun.file(c).text():null,p=new O(e.config),
|
|
216
|
-
Run ${
|
|
217
|
-
Run ${
|
|
218
|
-
Run ${
|
|
213
|
+
${o.map((c)=>d.dim(` ${c}`)).join(`
|
|
214
|
+
`)}`),i.info(""),await this.resolvePreviewRevert(e,n,i))await n.rollback(),i.info(d.dim("Changes reverted"));else i.info(d.yellow("Changes kept"));this.emit(e,"previewed",{changelogFiles:o})}async resolvePreviewRevert(e,t,r){if(e.args.json||e.args.yes||!this.stdoutWasTTY)return!0;try{return await V({initialValue:!0,message:"Revert changes?"})}catch(s){throw await t.rollback(),r.info(d.dim("Changes reverted")),s}}resolveOptions(e){let t=e.config.get("release"),r=e.config.get("changelog"),s=!e.args.noCommit;if(!s){let i=[e.args.createRelease?"--createRelease":void 0,e.args.push?"--push":void 0,e.args.tags?"--tags":void 0].filter((o)=>o!==void 0);if(i.length>0)throw new u(`--noCommit cannot be combined with ${i.join(", ")}`,"Tags, pushes, and provider releases require the release commit")}let n={changelog:e.args.changelog??r.generate,commit:s,createRelease:s?e.args.createRelease??t.createRelease:!1,dryRun:e.args.dryRun??!1,npm:e.args.npm??t.npm,push:s?e.args.push??t.push:!1,tags:s?e.args.tags??t.tags:!1};if(n.createRelease&&(!n.tags||!n.push))throw new u("Provider releases require both git tags and a remote push","Enable --tags and --push so the provider cannot create an implicit tag");if(!n.commit&&n.npm)throw new u("Npm publication requires a release commit","Remove --noCommit so package artifacts are bound to committed source");return n}printPreview(e,t,r,s){let n=[];if(s.dryRun)n.push(d.bold(d.yellow("[dry-run]")));if(n.push(`${d.bold("Release:")} ${t.message}`),t.tag)n.push(`${d.dim("Tag:")} ${t.tag}`);n.push(""),n.push(d.bold("Packages:"));for(let i of r)n.push(` ${i.label}`);n.push(""),n.push(d.dim(`Changelog: ${s.changelog?"yes":"no"}`)),n.push(d.dim(`Git tags: ${s.tags?"yes":"no"}`)),n.push(d.dim(`NPM publish: ${s.npm?"yes":"no"}`)),n.push(d.dim(`Push to remote: ${s.push?"yes":"no"}`)),n.push(d.dim(`Create release: ${s.createRelease?"yes":"no"}`)),e.step(n.join(`
|
|
215
|
+
`))}async executeRelease(e,t,r,s,n,i){let o=new De(e.config,i),a={...e.config.get("lastStone")},c=e.config.path,l=await Bun.file(c).exists()?await Bun.file(c).text():null,p=new O(e.config),m=new Map;for(let g of n){let y=p.getFilePath(g.id);if(await Bun.file(y).exists())m.set(y,await Bun.file(y).text())}let h=await this.getCurrentCommit();await o.preflight(s,n);let f=t;try{if(await o.initializeExternalRelease(s,n,!1),this.reportContext.ledger=o.getLedgerSnapshot()??void 0,f.start("Updating package versions..."),await o.updatePackageVersions(s),f.stop("Package versions updated"),i.changelog)f.start("Generating changelogs..."),await o.generateChangelogs(n,s),f.stop("Changelogs generated");if(await this.deleteStones(e,n),i.commit)f.start("Creating release commit..."),e.config.set("lastStone",{commit:h,date:new Date().toISOString()}),await o.createCommit(r,s,n),this.reportContext.releaseCommit=await this.getCurrentCommit(),f.stop("Release commit created");if(i.tags)f.start("Creating git tags..."),await o.createGitTags(s),f.stop("Git tags created");if(await o.finalizeExternalRelease(s,n),i.npm)f.start("Preparing NPM packages..."),await o.prepareNpmPublish(s),f.stop("NPM packages prepared");if(await o.markExternalReleaseReady(),i.push)f.start("Pushing to remote..."),await o.pushRelease(),f.stop("Pushed to remote");if(i.npm)f.start("Publishing to NPM..."),await o.publishToNpm(s),f.stop("Published to NPM");if(i.createRelease)f.start("Creating release..."),await o.createGitRelease(n,s),f.stop("Release created");await o.completeRelease(),this.reportContext.ledger=o.getLedgerSnapshot()??this.reportContext.ledger,await this.verifyNpmVisibility(e,f),f.note(`Released ${d.bold(String(s.length))} package(s)
|
|
216
|
+
Run ${d.green(`${F} check`)} to verify`,d.green("Release complete")),this.emit(e,"completed")}catch(g){if(this.reportContext.ledger=o.getLedgerSnapshot()??this.reportContext.ledger,o.hasCrossedIrreversibleBoundary())throw f.stop("Release incomplete, local state preserved"),o.createIncompleteReleaseError(g);f.stop("Release failed, rolling back...");try{await o.rollback(!1)}catch(y){throw AggregateError([g,y],"Release failed and rollback could not be completed; local release state was preserved")}try{e.config.set("lastStone",a),await this.restoreStones(e,n);for(let[y,R]of m)await Bun.write(y,R);if(l===null)await og(c,{force:!0});else await Bun.write(c,l)}catch(y){throw AggregateError([g,y],"Release failed and local metadata could not be restored; local release state was preserved")}try{await o.removeReleaseLedger()}catch(y){throw AggregateError([g,y],"Release failed and the recovery ledger could not be removed; remove it before the next roll")}throw g}}async deleteStones(e,t){let r=new O(e.config);for(let s of t)await r.delete(s.id)}async restoreStones(e,t){let r=new O(e.config);for(let s of t)await r.save(s)}async getCurrentCommit(){try{return(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim()}catch{return""}}validateModeFlags(e){if(e.args.abort){let r=[e.args.changelog!==void 0?"--changelog":void 0,e.args.createRelease!==void 0?"--createRelease":void 0,e.args.dryRun!==void 0?"--dryRun":void 0,e.args.noCommit?"--noCommit":void 0,e.args.npm!==void 0?"--npm":void 0,e.args.preview?"--preview":void 0,e.args.publishOnly?"--publishOnly":void 0,e.args.push!==void 0?"--push":void 0,e.args.resume?"--resume":void 0,e.args.tags!==void 0?"--tags":void 0].filter((s)=>s!==void 0);if(r.length>0)throw new u(`--abort cannot be combined with ${r.join(", ")}`,"Abort only removes the recovery ledger of an incomplete release");return}if(e.args.resume){let r=[e.args.changelog!==void 0?"--changelog":void 0,e.args.createRelease!==void 0?"--createRelease":void 0,e.args.dryRun!==void 0?"--dryRun":void 0,e.args.noCommit?"--noCommit":void 0,e.args.npm!==void 0?"--npm":void 0,e.args.preview?"--preview":void 0,e.args.publishOnly?"--publishOnly":void 0,e.args.push!==void 0?"--push":void 0,e.args.tags!==void 0?"--tags":void 0].filter((s)=>s!==void 0);if(r.length>0)throw new u(`--resume cannot be combined with ${r.join(", ")}`,"Resume uses the operation settings recorded in the active release ledger");return}if(e.args.preview&&e.args.dryRun)throw new u("--preview cannot be combined with --dryRun","Preview writes changelog files and then offers to revert them");if(!e.args.publishOnly)return;let t=[e.args.changelog!==void 0?"--changelog":void 0,e.args.noCommit?"--noCommit":void 0,e.args.preview?"--preview":void 0,e.args.push!==void 0?"--push":void 0].filter((r)=>r!==void 0);if(t.length>0)throw new u(`--publishOnly cannot be combined with ${t.join(", ")}`,"Publish-only supports --createRelease, --dryRun, --npm, --tags, and --yes")}async executePublishOnly(e){await De.assertNoActiveRelease();let t=e.config.get("currentRelease");if(!t)throw new u("No currentRelease found in config","Run `sis actions release-pr` first to prepare a release");if(await es(e.config.get("sisyphusDir"))!==t.sourceHash)throw new u("Current checkout does not match the prepared release source","Recreate the release PR before publishing");let n=await new O(e.config).getReleasedStones(t.timestamp,t.stoneIds).catch((g)=>{throw new u(g instanceof Error?g.message:String(g),"Recreate the release PR before publishing")});if(n.length===0)throw new u("No archived stones found for currentRelease","Recreate the release PR before publishing");if(ts({packages:t.packages,sourceHash:t.sourceHash,stoneIds:t.stoneIds,timestamp:t.timestamp},n.map((g)=>g.toJson()))!==t.planHash)throw new u("Prepared release plan has changed","Recreate the release PR before publishing");let o=Object.entries(t.packages);if(o.length===0)throw new u("No packages in currentRelease","The release config appears to be empty");let{packages:a}=await G.scan({single:e.config.get("single")}),c=[];for(let[g,{oldVersion:y,newVersion:R}]of o){let S=a.get(g);if(!S)throw new u(`Package ${g} from currentRelease is missing from the workspace`);if(S.version!==R)throw new u(`Package ${g} is at ${S.version}, but currentRelease expects ${R}`,"Check out the exact release commit before publishing");c.push(S.withVersions(y,R))}this.validateArchivedPackagePlan(e,n,t.packages,c);let l=wr(e.args.json),{cycle:p,ordered:m}=Xt(c);if(p.length>0)this.recordWarning(e,`Dependency cycle between ${p.join(", ")}; publish order may not satisfy every pin`);l.info(d.bold("Publish-only mode")),l.info(d.dim(`Timestamp: ${t.timestamp}`)),l.info(d.dim(`Stones: ${t.stoneIds.join(", ")}`)),l.info(""),l.info(d.bold("Packages to publish:"));for(let g of m)l.info(` ${g.name}@${g.newVersion??g.version}`);l.info("");let h=e.config.get("release"),f={createRelease:e.args.createRelease??h.createRelease,dryRun:e.args.dryRun??!1,npm:e.args.npm??h.npm,tags:e.args.tags??h.tags};if(l.info(d.dim(`Operations: npm=${f.npm} tags=${f.tags} createRelease=${f.createRelease}`)),this.reportContext={mode:"publish-only",npmTag:he,packages:m,stones:n,tagsEnabled:f.tags},this.reportContext.npmTag=this.resolveReportNpmTag(e,m,f.npm),f.createRelease&&!f.tags)throw new u("Provider releases require pushed git tags","Enable --tags so the provider cannot create an implicit tag");if(!f.npm&&!f.tags&&!f.createRelease)throw new u("Nothing to publish: npm, tags, and provider release are all disabled","Enable --npm, --tags, or --createRelease");if(f.dryRun){l.info(d.yellow("[dry-run] Would publish packages")),this.emit(e,"planned");return}if(!e.args.yes&&this.stdoutWasTTY){if(this.assertJsonConsent(e),!await V({initialValue:!0,message:"Proceed with publishing?"}))return}await this.executePublish(e,l,m,n,f)}async executePublish(e,t,r,s,n){let i=new De(e.config,{changelog:!1,createRelease:n.createRelease,dryRun:n.dryRun,npm:n.npm,push:!1,tags:n.tags}),o=t;try{if(await i.initializeExternalRelease(r,s,!0),this.reportContext.ledger=i.getLedgerSnapshot()??void 0,n.tags)o.start("Creating git tags..."),await i.createGitTags(r),o.stop("Git tags created");if(await i.finalizeExternalRelease(r,s),n.npm)o.start("Preparing NPM packages..."),await i.prepareNpmPublish(r),o.stop("NPM packages prepared");if(await i.markExternalReleaseReady(),n.tags)o.start("Pushing git tags..."),await i.pushRelease(),o.stop("Git tags pushed");if(n.npm)o.start("Publishing to NPM..."),await i.publishToNpm(r),o.stop("Published to NPM");if(n.createRelease)o.start("Creating release..."),await i.createGitRelease(s,r),o.stop("Release created");await i.completeRelease(),this.reportContext.ledger=i.getLedgerSnapshot()??this.reportContext.ledger,await this.verifyNpmVisibility(e,o),o.note(`Published ${d.bold(String(r.length))} package(s)
|
|
217
|
+
Run ${d.green(`${F} check`)} to verify`,d.green("Publish complete")),this.emit(e,"completed")}catch(a){if(this.reportContext.ledger=i.getLedgerSnapshot()??this.reportContext.ledger,i.hasCrossedIrreversibleBoundary())throw o.stop("Publish incomplete, local state preserved"),i.createIncompleteReleaseError(a);o.stop("Publish failed");try{await i.rollback()}catch(c){throw AggregateError([a,c],"Publish failed and rollback could not be completed; local release state was preserved")}throw a}}async executeAbort(e){let t=await Re.loadActive();if(!t)throw new u("No incomplete release found","Nothing to abort");if(t.hasExternalProgress())throw new u(`Release ${t.id} already performed external operations`,`Run ${F} roll --resume to reconcile; aborting after a push or publish is not supported`);if(this.reportContext={ledger:t.data,mode:"abort",npmTag:he,packages:[],stones:[]},await t.remove(),!e.args.json)v.warn("Release abandoned; version bumps, changelogs, the release commit, and local tags were kept");this.emit(e,"aborted")}async executeResume(e){let{ledger:t,packages:r,stones:s}=await De.resume(e.config);if(this.reportContext={ledger:t??void 0,mode:"resume",npmTag:t?.options.npmTag??he,packages:r,stones:s,tagsEnabled:t?.options.tags??!1},await this.verifyNpmVisibility(e,wr(e.args.json)),!e.args.json)q(`Released ${d.bold(String(r.length))} package(s)
|
|
218
|
+
Run ${d.green(`${F} check`)} to verify`,d.green("Release resumed"));this.emit(e,"completed")}validateArchivedPackagePlan(e,t,r,s){let n=M.mergeAll(t),i=Object.keys(r).sort(),o=[...new Set(n.allPackages)].sort();if(JSON.stringify(i)!==JSON.stringify(o))throw new u("Archived stones do not match currentRelease packages","Recreate the release PR before publishing");let a=z.applyStone(n,new Map(s.map((c)=>[c.name,c])),ce(e.config).kinds);for(let c of a){let l=r[c.name]?.newVersion,p=c.bump==="snapshot"?c.newVersion?.replace(rl,""):c.newVersion,m=c.bump==="snapshot"?l?.replace(rl,""):l;if(p!==m)throw new u(`Archived stones do not produce ${c.name}@${l??"missing"}`,"Recreate the release PR before publishing")}}}class ut extends j{async resolveStone(e,t,r){if(r)return this.promptStone(t);if(!e)throw new u("Stone ID is required",`Usage: ${F} stone ${this.name} <id>`);let s=await t.get(e);if(!s)throw new u(`Stone '${e}' not found`,`Run '${F} stone list' to see available stones`);return s}async promptStone(e){let t=await e.list();if(t.length===0)throw new u("No pending stones found");let r=t.map((s)=>({label:`${s.id} - ${s.message}`,value:s}));return Xe({message:`Select a stone to ${this.name}`,options:r})}}var dg=de({id:{description:"Stone ID to delete"}});class Ci extends ut{name="delete";description="Delete a pending stone";positionals=dg;prompts=!0;async execute(e){Be(e.args,this.args,"Run 'sis stone delete --help' for supported options");let t=new O(e.config),r=await this.resolveStone(e.positionals.id,t,e.interactive);if(e.interactive){if(!await V({initialValue:!1,message:`Delete stone '${r.id}'?`}))return}await t.delete(r.id),v.success(`Stone '${d.bold(r.id)}' deleted`)}}var mg=de({id:{description:"Stone ID to edit"}}),gg=U({message:{alias:"m",description:"New commit message",type:"string"}});class ki extends ut{name="edit";description="Edit a pending stone";positionals=mg;args=gg;prompts=!0;async execute(e){let t=new O(e.config),r=await this.resolveStone(e.positionals.id,t,e.interactive),s=await this.resolveMessage(e,r.message),n=r.withMessage(s);await t.save(n),v.success(`Updated commit message for stone '${d.bold(r.id)}'`)}async resolveMessage(e,t){if(e.args.message)return e.args.message;if(!e.interactive)throw new u("--message is required in non-interactive mode");return le({initialValue:t,message:"Commit message",placeholder:t})}}var hg=U({json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"},verbose:{alias:"v",default:!1,description:"Show detailed info",type:"boolean"}});class xi extends j{name="list";description="List all pending stones";args=hg;async execute(e){let t=new O(e.config),r=await t.list();if(r.length===0){this.printEmpty(e.args.json);return}if(e.args.json)this.printJson(r,t);else this.printFormatted(r,e.args.verbose)}printEmpty(e){if(e)console.log(JSON.stringify([]));else v.info("No pending stones found")}printJson(e,t){let r=e.map((s)=>({path:t.getFilePath(s.id),...s.toJson()}));console.log(JSON.stringify(r,null,2))}printFormatted(e,t){let r=`Found ${d.bold(String(e.length))} pending stone${e.length>1?"s":""}`,s=e.map((n)=>this.formatStone(n,t)).join(`
|
|
219
219
|
|
|
220
220
|
`);v.info(`${r}
|
|
221
221
|
|
|
222
|
-
${s}`)}formatStone(e,t){let r=[];if(r.push(`${
|
|
223
|
-
`))r.push(` ${
|
|
224
|
-
`)}}var
|
|
225
|
-
`));if(await t.save(n),await this.resolveDelete(e))await t.deleteMany(r.map((c)=>c.id));this.printResult(n.id,i)}async resolveStones(e,t){let r=await t.list();if(r.length<2)throw new u("Need at least 2 stones to merge");if(e.interactive)return this.promptStones(r);let s=e.positionals.ids;if(s.length<2)throw new u("Need at least 2 stone IDs",`Usage: ${F} stone merge <id1> <id2> [...] -m "message"`);let n=r.filter((i)=>s.includes(i.id));if(n.length!==s.length){let i=n.map((a)=>a.id),o=s.filter((a)=>!i.includes(a));throw new u(`Stone(s) not found: ${o.join(", ")}`)}return n}async resolveMessage(e){if(e.args.message)return e.args.message;if(!e.interactive)throw new u("--message is required in non-interactive mode");return le({message:"Commit message for merged stone",placeholder:"feat: combined changes"})}async resolveDelete(e){if(e.args.delete)return!0;if(e.interactive)return V({initialValue:!1,message:"Delete original stones?"});return!1}async promptStones(e){let t=e.map((s)=>({label:`${s.id} - ${s.message}`,value:s})),r=await xe({message:"Select stones to merge (at least 2)",options:t,required:!0});if(r.length<2)throw new u("Need to select at least 2 stones");return r}printResult(e,t){if(v.success(`Created merged stone: ${
|
|
226
|
-
`+t.map((r)=>` ${
|
|
227
|
-
`),
|
|
228
|
-
`))}}class
|
|
229
|
-
Run ${
|
|
230
|
-
or create another stone with ${
|
|
231
|
-
`))}previewLabels(e,t,r){let s=M.create(t);try{return z.applyStone(s,r,ce(e.config).kinds).map((n)=>n.label)}catch(n){if(n instanceof u)return s.allPackages.filter((i)=>r.has(i));throw n}}}class
|
|
222
|
+
${s}`)}formatStone(e,t){let r=[];if(r.push(`${d.dim("-")} ${d.bold(e.id)}`),r.push(` ${d.dim("Message:")} ${e.message}`),e.tag)r.push(` ${d.dim("Tag:")} ${d.cyan(e.tag)}`);if(e.major.length)r.push(` ${d.red("Major:")} ${e.major.join(", ")}`);if(e.minor.length)r.push(` ${d.yellow("Minor:")} ${e.minor.join(", ")}`);if(e.patch.length)r.push(` ${d.green("Patch:")} ${e.patch.join(", ")}`);if(t&&e.description){r.push(` ${d.dim("Description:")}`);for(let s of e.description.split(`
|
|
223
|
+
`))r.push(` ${d.dim(s)}`)}return r.join(`
|
|
224
|
+
`)}}var fg=de({ids:{description:"Stone IDs to merge (at least 2)",variadic:!0}}),nl=U({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 Ti extends j{name="merge";description="Merge multiple stones into one";positionals=fg;args=nl;prompts=!0;async execute(e){Be(e.args,nl,"Run 'sis stone merge --help' for supported options");let t=new O(e.config),r=await this.resolveStones(e,t),s=await this.resolveMessage(e),{stone:n,conflicts:i,errors:o}=M.merge(r,s);if(o.length>0)throw new u("Selected stones cannot be merged",o.join(`
|
|
225
|
+
`));if(await t.save(n),await this.resolveDelete(e))await t.deleteMany(r.map((c)=>c.id));this.printResult(n.id,i)}async resolveStones(e,t){let r=await t.list();if(r.length<2)throw new u("Need at least 2 stones to merge");if(e.interactive)return this.promptStones(r);let s=e.positionals.ids;if(s.length<2)throw new u("Need at least 2 stone IDs",`Usage: ${F} stone merge <id1> <id2> [...] -m "message"`);let n=r.filter((i)=>s.includes(i.id));if(n.length!==s.length){let i=n.map((a)=>a.id),o=s.filter((a)=>!i.includes(a));throw new u(`Stone(s) not found: ${o.join(", ")}`)}return n}async resolveMessage(e){if(e.args.message)return e.args.message;if(!e.interactive)throw new u("--message is required in non-interactive mode");return le({message:"Commit message for merged stone",placeholder:"feat: combined changes"})}async resolveDelete(e){if(e.args.delete)return!0;if(e.interactive)return V({initialValue:!1,message:"Delete original stones?"});return!1}async promptStones(e){let t=e.map((s)=>({label:`${s.id} - ${s.message}`,value:s})),r=await xe({message:"Select stones to merge (at least 2)",options:t,required:!0});if(r.length<2)throw new u("Need to select at least 2 stones");return r}printResult(e,t){if(v.success(`Created merged stone: ${d.bold(e)}`),t.length>0)q(`Resolved ${t.length} package conflict(s) using highest bump type:
|
|
226
|
+
`+t.map((r)=>` ${d.dim("-")} ${r}`).join(`
|
|
227
|
+
`),d.yellow("Conflicts resolved"))}}var yg=40,wg=de({id:{description:"Stone ID to display"}}),bg=U({json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}});class Ei extends ut{name="show";description="Show details of a specific stone";positionals=wg;args=bg;prompts=!0;async execute(e){let t=new O(e.config),r=await this.resolveStone(e.positionals.id,t,e.interactive);this.printStone(r,t,e.args.json)}printStone(e,t,r){if(r)console.log(JSON.stringify({path:t.getFilePath(e.id),...e.toJson()},null,2));else this.printFormatted(e,t)}printFormatted(e,t){let r=[];if(r.push(d.bold(`Stone: ${e.id}`)),r.push(d.dim(`Path: ${t.getFilePath(e.id)}`)),r.push(d.dim("-".repeat(yg))),r.push(""),r.push(`${d.dim("Message:")} ${e.message}`),e.tag)r.push(`${d.dim("Tag:")} ${d.cyan(e.tag)}`);if(e.description)r.push(`${d.dim("Description:")} ${e.description}`);r.push("");let s=[{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:n,packages:i}of s)if(i.length>0){let o=Pt[n];r.push(`${o(n)}: ${i.join(", ")}`)}v.info(r.join(`
|
|
228
|
+
`))}}class Ii extends j{name="stone";description="Manage version stones";init(){this.registerSubcommands([new xi,new Ei,new Ci,new ki,new Ti])}}var vg=de({message:{description:"Stone message (commit message)"},description:{description:"Stone description (optional details)"}}),$g=U({all:{alias:"a",default:!1,description:"Select all (filtered) packages without prompting",type:"boolean"},bump:{alias:"b",description:"Bump type applied to all selected packages (major|minor|patch)",type:"string"},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"},message:{description:"Stone message (skips the message prompt)",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 Ai extends j{name="version";description="Create a new version stone";positionals=vg;args=$g;prompts=!0;async execute(e){let t=this.normalizeInput(e);if(this.validateFromCommitsInput(e,t),!e.args.fromCommits)this.validateManualSelectionInput(e,t);if(e.args.fromCommits)await this.executeFromCommits(e,t);else if(this.isInteractiveSession(e)&&!t.hasManualSelection)await this.executeInteractive(e,t);else await this.executeDirect(e,t)}isInteractiveSession(e){return e.interactive&&process.stdout.isTTY===!0}normalizeInput(e){let t=e.args.major!==void 0||e.args.minor!==void 0||e.args.patch!==void 0,r={major:this.parsePackageList(e.args.major,"--major"),minor:this.parsePackageList(e.args.minor,"--minor"),patch:this.parsePackageList(e.args.patch,"--patch")};this.validateExclusiveBumpGroups(r);let s=e.positionals.message!==void 0,n=e.args.message!==void 0;if(s&&n)throw new u("Message cannot be provided both positionally and with --message");let i=s?e.positionals.message:e.args.message,o=this.normalizeNonEmptyValue(e.args.bump,"--bump"),a=this.normalizeNonEmptyValue(e.args.filter,"--filter");return{bump:o,description:e.positionals.description?.trim()||void 0,filter:a,hasManualSelection:o!==void 0||t||e.args.all,message:this.normalizeNonEmptyValue(i,"Message"),packageSelection:r,packageSelectionSupplied:t,tag:this.normalizeTag(e.args.tag)}}normalizeNonEmptyValue(e,t){if(e===void 0)return;let r=e.trim();if(!r)throw new u(`${t} cannot be empty`);return r}normalizeTag(e){let t=this.normalizeNonEmptyValue(e,"--tag");if(t===void 0)return;return tt(t,"--tag must be a supported prerelease identifier")}parsePackageList(e,t){if(e===void 0)return[];let r=e.split(",").map((s)=>s.trim());if(r.some((s)=>!s))throw new u(`${t} must contain one or more non-empty package names`);return[...new Set(r)]}validateExclusiveBumpGroups(e){let t=new Map,r=[["major",e.major],["minor",e.minor],["patch",e.patch]];for(let[s,n]of r)for(let i of n){let o=t.get(i);if(o)throw new u(`Package "${i}" cannot be assigned to both --${o} and --${s}`);t.set(i,s)}}validateFromCommitsInput(e,t){if(!e.args.fromCommits)return;if(!t.hasManualSelection&&t.message===void 0)return;throw new u("--fromCommits cannot be combined with --bump, --all, --major, --minor, --patch, or a message")}validateManualSelectionInput(e,t){if(e.args.all&&t.bump===void 0)throw new u("--all requires a valid --bump","Use --bump major, --bump minor, or --bump patch");if(t.bump!==void 0&&t.packageSelectionSupplied)throw new u("--bump cannot be combined with --major, --minor, or --patch");if(t.bump!==void 0&&t.bump!=="major"&&t.bump!=="minor"&&t.bump!=="patch")throw new u(`Invalid bump type "${t.bump}"`,"Use major, minor, or patch")}async scanPackages(e,t){let r=await G.scan({filter:t,single:e.config.get("single")}),s=e.config.get("ignore")??[],n=r.packageNames.filter((i)=>!ee(i,s));if(n.length===0)throw new u("No packages found matching the criteria");return{packageNames:n,packages:r.packages}}async executeInteractive(e,t){let{packages:r,packageNames:s}=await this.scanPackages(e,t.filter),n=await this.selectPackagesInteractive(r,s,t.tag),i=t.message??await this.promptMessage(),o=t.description??await this.promptDescription(),a=this.buildStoneData({ctx:e,description:o,message:i,packages:r,selection:n,tag:t.tag});await this.createStone(e,a,r)}async executeDirect(e,t){let r=t.message??(this.isInteractiveSession(e)?await this.promptMessage():void 0);if(!r)throw new u("Message is required",'Pass --message "..." or a positional message');let{packages:s,packageNames:n}=await this.scanPackages(e,t.filter),i=this.resolveSelection(e,t,n);this.validatePackages(i,s,n,e.config.get("ignore")??[],t.filter);let o=this.buildStoneData({ctx:e,description:t.description,message:r,packages:s,selection:i,tag:t.tag});await this.createStone(e,o,s)}resolveSelection(e,t,r){let s=t.bump;if(!s)return this.requirePackageSelection(t.packageSelection);if(!e.args.all&&!e.args.yes)throw new u("--bump selects every (filtered) package","Confirm the selection with --all or --yes");let n=[...r];if(s==="major")return{major:n,minor:[],patch:[]};if(s==="minor")return{major:[],minor:n,patch:[]};return{major:[],minor:[],patch:n}}requirePackageSelection(e){if(!(e.major.length>0||e.minor.length>0||e.patch.length>0))throw new u("At least one of --major (-M), --minor (-m), or --patch (-p) is required","Or use --bump <type> with --all to select every package");return e}validatePackages(e,t,r,s,n){let i=[...e.major,...e.minor,...e.patch],o=i.filter((p)=>!t.has(p));if(o.length>0)throw new u(`Unknown packages: ${o.join(", ")}`);let a=i.filter((p)=>ee(p,s));if(a.length>0)throw new u(`Packages are excluded by config.ignore: ${a.join(", ")}`,"Remove them from ignore before releasing them");let c=new Set(r),l=i.filter((p)=>!c.has(p));if(l.length>0)throw new u(`Packages do not match --filter "${n}": ${l.join(", ")}`)}async executeFromCommits(e,t){if(!e.config.get("lastStone")?.commit)throw new u("No release baseline recorded",`Set lastStone.commit (run ${F} init in an existing repo, or complete one release) before using --fromCommits`);let s=await new st(e.config).analyze({filter:t.filter,single:e.config.get("single")});if(s.length===0){v.info("No conventional commits found since last release");return}let{packages:n}=await this.scanPackages(e,t.filter);v.info(`Found ${d.bold(String(s.length))} commit group(s) to process`);let i=new O(e.config),o=0;for(let a of s){let c=st.buildStoneData(a,n,ce(e.config,t.tag));if(e.args.dryRun)this.logPreview(e,c,n);else{let l=await i.create(c);o++,v.success(`Created stone: ${d.bold(l.id)}`)}}if(!e.args.dryRun&&o>0)q(`Created ${d.bold(String(o))} stone(s) from commits.
|
|
229
|
+
Run ${d.green(`${F} check`)} to see what will be released.`,d.green("Success"))}async selectPackagesInteractive(e,t,r){let s=[],n={major:[],minor:[],patch:[]};for(let i of["major","minor","patch"]){let o=t.filter((c)=>!s.includes(c));if(o.length===0)break;let a=await this.promptPackages(i,o,e,r);if(s.push(...a),i==="major")n.major=a;else if(i==="minor")n.minor=a;else n.patch=a}if(s.length===0)throw new u("No packages selected");return n}async promptPackages(e,t,r,s){let n=Pt[e],i=t.map((o)=>{let a=r.get(o);return{label:a?this.safeLabel(a,e,s):o,value:o}});return xe({message:`Select packages for ${d.bold(n(e))} bump`,options:i,required:!1})}safeLabel(e,t,r){try{return e.withBump(t,r).label}catch(s){if(s instanceof u)return e.name;throw s}}async promptMessage(){return(await le({message:"Stone message (used as commit message)",placeholder:"feat: add new feature",validate:(t)=>t?.trim()?void 0:"Message is required"})).trim()}async promptDescription(){return(await le({message:"Description (optional, press enter to skip)",placeholder:"Additional details about this change..."}))?.trim()||void 0}buildStoneData(e){let{ctx:t,selection:r,message:s,packages:n,tag:i,description:o}=e,a=[...r.major.map((l)=>({bump:"major",name:l})),...r.minor.map((l)=>({bump:"minor",name:l})),...r.patch.map((l)=>({bump:"patch",name:l}))],c=St(a,n,ce(t.config,i));return{dependency:K(c),description:o,major:K(r.major),message:s,minor:K(r.minor),patch:K(r.patch),tag:i}}async createStone(e,t,r){let s=new O(e.config);if(this.logPreview(e,t,r),e.args.dryRun)return;if(!e.args.yes&&this.isInteractiveSession(e)){if(!await V({initialValue:!0,message:"Create this stone?"}))return}let n=await s.create(t);q(`Run ${d.green(`${F} roll`)} to release packages
|
|
230
|
+
or create another stone with ${d.green(`${F} version`)}`,`Stone ${d.bold(n.id)} ${d.green("created")}`)}logPreview(e,t,r){let s=[];if(e.args.dryRun)s.push(d.bold(d.yellow("[dry-run]")));if(s.push(`${d.dim("Stone:")} ${d.bold(t.message)}`),t.tag)s.push(`${d.dim("Tag:")} ${t.tag}`);for(let n of this.previewLabels(e,t,r))s.push(` ${n}`);v.step(s.join(`
|
|
231
|
+
`))}previewLabels(e,t,r){let s=M.create(t);try{return z.applyStone(s,r,ce(e.config).kinds).map((n)=>n.label)}catch(n){if(n instanceof u)return s.allPackages.filter((i)=>r.has(i));throw n}}}class il extends Xs{constructor(){super(new tn(`${bt}/${jr}`,Ue),{bin:F,clearOnStart:!0,exitLabel:"Give Up",goodbyeMessage:"The boulder rolls back down...",name:"SISYPHUS",promptMessage:"Choose your boulder:",version:Io})}init(){this.registerCommands([new wi,new bi,new vi,new $i,new Pi,new Si,new Ii,new Ai])}}var Pg=new il;Pg.run();
|