@r5n/sisyphus 0.13.2 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/cli.js +218 -188
- package/dist/templates/github/sis-create-stone.yml +58 -26
- package/dist/templates/github/sis-release.yml +4 -3
- package/dist/templates/gitlab/sis-create-stone.yml +18 -10
- package/dist/templates/gitlab/sis-release.yml +2 -2
- package/package.json +2 -4
- package/schema.json +26 -1
package/dist/cli.js
CHANGED
|
@@ -1,231 +1,261 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
2
|
// @bun
|
|
3
|
-
var al=Object.create;var{getPrototypeOf:cl,defineProperty:Oi,getOwnPropertyNames:ll}=Object;var _i=Object.prototype.hasOwnProperty;function ul(e){return this[e]}var pl,ml,Li=(e,t,r)=>{var s=e!=null&&typeof e==="object";if(s){var n=t?pl??=new WeakMap:ml??=new WeakMap,i=n.get(e);if(i)return i}r=e!=null?al(cl(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 ll(e))if(!_i.call(o,a))Oi(o,a,{get:ul.bind(e,a),enumerable:!0})}if(s)n.set(e,o);return o};var dl=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var _s=dl(function(Eg,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"},xl={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Tl={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:xl,erase:Tl,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 El}from"util";import{stdout as Ms,stdin as Xi}from"process";import*as Ne from"readline";import Il 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 gl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,hl=/[\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,fl=/\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,yl=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,wl=/\p{M}+/gu,bl={limit:1/0,ellipsis:""},Bi=(e,t={},r={})=>{let s=t.limit??1/0,n=t.ellipsis??"",i=t?.ellipsisWidth??(n?Bi(n,bl,r).width:0),o=0,a=r.controlWidth??0,c=r.tabWidth??8,l=r.emojiWidth??2,p=2,d=r.regularWidth??1,h=r.wideWidth??2,f=[[yl,d],[gl,0],[hl,a],[fl,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(wl,"")){let ne=te.codePointAt(0)||0;if(Di(ne))C=2;else if(Ni(ne))C=h;else C=d;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 vl={limit:1/0,ellipsis:"",ellipsisWidth:0},$l=(e,t={})=>Vi(e,vl,t).width,ie=$l;var $r="\x1B",Wi="\x9B",Pl=39,Is="\x07",Ji="[",Rl="]",zi="m",As=`${Rl}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 d=c.value,h=ie(d);if(a+h<=r)e[e.length-1]+=d;else e.push(d),a=0;if(d===$r||d===Wi)n=!0,i=t.startsWith(As,p+1);if(n){if(i){if(d===Is)n=!1,i=!1}else if(d===zi)n=!1}else if(a+=h,a===r&&!l.done)e.push(""),a=0;c=l,l=s.next(),p+=d.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},Sl=(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("")},Cl=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let s="",n,i,o=e.split(" "),a=[""],c=0;for(let d=0;d<o.length;d++){let h=o[d];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(d!==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((d)=>Sl(d));let l=a.join(`
|
|
4
|
-
`),
|
|
5
|
-
`)
|
|
6
|
-
`){if(n&&
|
|
7
|
-
`)
|
|
8
|
-
`)
|
|
9
|
-
`)
|
|
10
|
-
`).
|
|
11
|
-
`)
|
|
12
|
-
`),
|
|
13
|
-
`).
|
|
14
|
-
`);this.output.
|
|
15
|
-
`).
|
|
16
|
-
`)
|
|
17
|
-
`);
|
|
3
|
+
class Re extends Error{_tag="Cancel";constructor(e="Operation cancelled"){super(e)}}function q(e){return e}function Ci(e){return e==null?[]:Array.isArray(e)?e:[e]}function vm(e,t,r,n){var s,i=e[t],o=~n.string.indexOf(t)?r==null||r===!0?"":String(r):typeof r==="boolean"?r:~n.boolean.indexOf(t)?r==="false"?!1:r==="true"||(e._.push((s=+r,s*0===0)?s:r),!!r):(s=+r,s*0===0)?s:r;e[t]=i==null?o:Array.isArray(i)?i.concat(o):[i,o]}function ki(e,t){e=e||[],t=t||{};var r,n,s,i,o,a={_:[]},c=0,l=0,p=0,m=e.length;let g=t.alias!==void 0,h=t.unknown!==void 0,f=t.default!==void 0;if(t.alias=t.alias||{},t.string=Ci(t.string),t.boolean=Ci(t.boolean),g)for(r in t.alias){n=t.alias[r]=Ci(t.alias[r]);for(c=0;c<n.length;c++)(t.alias[n[c]]=n.concat(r)).splice(c,1)}for(c=t.boolean.length;c-- >0;){n=t.alias[t.boolean[c]]||[];for(l=n.length;l-- >0;)t.boolean.push(n[l])}for(c=t.string.length;c-- >0;){n=t.alias[t.string[c]]||[];for(l=n.length;l-- >0;)t.string.push(n[l])}if(f){for(r in t.default)if(i=typeof t.default[r],n=t.alias[r]=t.alias[r]||[],t[i]!==void 0){t[i].push(r);for(c=0;c<n.length;c++)t[i].push(n[c])}}let y=h?Object.keys(t.alias):[];for(c=0;c<m;c++){if(s=e[c],s==="--"){a._=a._.concat(e.slice(++c));break}for(l=0;l<s.length;l++)if(s.charCodeAt(l)!==45)break;if(l===0)a._.push(s);else if(s.substring(l,l+3)==="no-"){if(i=s.substring(l+3),h&&!~y.indexOf(i))return t.unknown(s);a[i]=!1}else{for(p=l+1;p<s.length;p++)if(s.charCodeAt(p)===61)break;i=s.substring(l,p),o=s.substring(++p)||(c+1===m||(""+e[c+1]).charCodeAt(0)===45||e[++c]),n=l===2?[i]:i;for(p=0;p<n.length;p++){if(i=n[p],h&&!~y.indexOf(i))return t.unknown("-".repeat(l)+i);vm(a,i,p+1<n.length||o,t)}}}if(f){for(r in t.default)if(a[r]===void 0)a[r]=t.default[r]}if(g)for(r in a){n=t.alias[r]||[];while(n.length>0)a[n.shift()]=a[r]}return a}var he=0,Ar=1,Ga=2,Ha=255;function En(e){return Number.isInteger(e)&&e>=0&&e<=255}class u extends Error{hint;exitCode;_tag;constructor(e,t,r=1,n={}){super(e,"cause"in n?{cause:n.cause}:void 0);this.hint=t;this.exitCode=r;this._tag=n.tag??"Exit"}}class N extends u{constructor(e,t,r={}){super(e,t,2,{...r,tag:r.tag??"UsageError"})}}var Wa=1,$m=2,In="--",Ja="-",at="no-",Pm=new Set(["false","true"]),Lr=/^--([^=]+)(?:=(.*))?$/s,Dr=/^-([^-=][^=]*)(?:=(.*))?$/s,Ti=/^(?:---|-no-|-_|-[^-=][^=]*_)/,Sm="_",Or="\x00";function Oe(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function zt(e){let t={alias:{},boolean:[],default:{},string:[]};for(let[r,n]of Object.entries(e)){if(n.type==="boolean")t.boolean.push(r);else t.string.push(r);if(n.alias)t.alias[n.alias]=r;let s=Oe(r);if(s!==r)t.alias[s]=r;if(n.default!==void 0)t.default[r]=n.default}return t}function Tn(e,t){let r={};for(let[o,a]of Object.entries(t.alias))r[a]=[...r[a]??[],o];let{_:n,...s}=ki(Ln(e,Cm),{alias:r,boolean:[...t.boolean],default:{...t.default},string:[...t.string]}),i=Object.entries(s).map(([o,a])=>[xi(o),xi(a)]);return{...Object.fromEntries(i),_:n.map(xi)}}function Cm(e){if(e===Ja)return`${Or}${e}`;let t=Lr.exec(e);if(Ti.test(e)||km(t?.[1]))return`--${Or}${e}`;return(t?t[2]:Dr.exec(e)?.[2])===""?`${e}${Or}`:e}function km(e){if(e===void 0)return!1;let t=e.startsWith(at)?e.slice(at.length):e;return t===Sm||t in Object.prototype}function xi(e){return typeof e==="string"&&e.startsWith(Or)?e.slice(Or.length):e}function _r(e,t){return Object.hasOwn(t.alias,e)?t.alias[e]??e:e}function Jt(e,t){if(Object.hasOwn(t,e))return`--${Oe(e)}`;let r=Object.entries(t).find(([,n])=>n.alias===e)?.[0];if(r)return`--${Oe(r)}`;return e.length===Wa?`-${e}`:`--${e}`}function An(e,t,r,n){let{alias:s}=zt(t),i=Object.keys(e).find((o)=>!Object.hasOwn(t,o)&&!Object.hasOwn(s,o));if(i!==void 0)throw new N(`Unknown option: ${xm(i,n)}`,r)}function xm(e,t){if(e.startsWith("-"))return e;let r=t.indexOf(In);for(let n of r<0?t:t.slice(0,r)){let s=Lr.exec(n)?.[1];if(s===e||n===`--${at}${e}`)return`--${s}`;if(s===void 0&&Dr.exec(n)?.[1]?.includes(e))return`-${e}`}return Jt(e,{})}function za(e,t){for(let[n,s]of Object.entries(e))if(Array.isArray(s))throw new N(`${Jt(n,t)} can only be provided once`);let r={...e};for(let[n,s]of Object.entries(t)){let i=e[n];if(i===void 0)continue;if(s.type==="string"&&typeof i==="boolean")throw Ka(Jt(n,t));if(s.type!=="number")continue;let o=Number(i);if(typeof i==="boolean"||typeof i==="string"&&i.trim().length===0||!Number.isFinite(o)){let a=Jt(n,t);throw new N(`Invalid number for ${a}: "${i}"`,`Use ${a}=<number> with a finite numeric value`)}r[n]=o}return r}function Ka(e){return new N(`${e} needs a value`,`Use ${e}=<value>`)}function On(e,t){let r=zt(t),n=Ai([...e],r),s=Tn(n,r)._[0],i=s===void 0?-1:n.indexOf(s);return{before:i>=0?e.slice(0,i):[...e],command:s,restArgs:i>=0?e.slice(i+1):[]}}function Xa(e,t){let r=zt(t);for(let n=0;n<e.length;n+=1){let s=e[n]??"";if(s===In)return-1;if(s===Ja||!s.startsWith("-"))return n;if(Em(s,r,t))n+=1}return-1}function Em(e,t,r){if(e.startsWith(`--${at}`))return!1;let n=Lr.exec(e),s=n??Dr.exec(e);if(!s||s[2]!==void 0)return!1;let i=n?s[1]??"":s[1]?.at(-1)??"",o=r[_r(i,t)]?.type;return o==="string"||o==="number"}function Ii(e,t,r=t){let n=zt(t),{before:s,command:i,restArgs:o}=On(e,t),a=zt(r);Ei(s,n,t,!0),Ei(e,a,r,!0);let{_:c,...l}=Tn(Ya(s,n,t),n);An(l,t,"Place command options after the command name",s);let{_:p,...m}=Tn(Ai(o,a),a),g=za({...qa(l,t,n),...qa(m,r,a)},t);return{command:i,flags:g,restArgs:o}}function qa(e,t,r){return Object.fromEntries(Object.entries(e).filter(([n])=>Object.hasOwn(t,n)||Object.hasOwn(r.alias,n)))}function _n(e,t){return Object.fromEntries(Object.keys(t).flatMap((r)=>{let n=e[r];return n===void 0?[]:[[r,n]]}))}function Mr(e,t={}){let r=zt(t),n=Tm(e,r);Ei(n,r,t);let s=Tn(Ya(n,r,t),r),{_:i,...o}=s;return{args:za(o,t),rawPositionals:i.map(String)}}function Ei(e,t,r,n=!1){let s=new Set;for(let i of e){if(i===In)break;let o=i.match(/^-+/)?.[0];if(!o||Ti.test(i))continue;let a=i.slice(o.length),c=a.split("=",Wa)[0]??"",l=a.startsWith(at)?[a.slice(at.length)]:o.length===$m?[c]:[...c];for(let p of l){let m=_r(p,t);if(n&&!Object.hasOwn(r,m))continue;if(s.has(m))throw new N(`${Jt(m,r)} can only be provided once`);s.add(m)}}}function Ln(e,t){let r=e.indexOf(In);return e.map((n,s)=>r>=0&&s>=r?n:t(n,e[s+1]))}function Ai(e,t){return Ln(e,(r)=>{let n=Lr.exec(r)??Dr.exec(r);if(!n||n[2]!==void 0||r.startsWith(`--${at}`))return r;let s=r.startsWith("--")?n[1]??"":n[1]?.at(-1)??"";return t.boolean.includes(_r(s,t))?`${r}=true`:r})}function Ya(e,t,r){let n=(o)=>r[_r(o,t)]?.type,s=(o)=>o!==void 0&&!o.startsWith("-"),i=Ln(e,(o,a)=>{let c=Lr.exec(o),l=c?null:Dr.exec(o);if(o.startsWith(`--${at}`)||Ti.test(o))return o;let p=c?[c[1]??""]:[...l?.[1]??""],m=c?c[2]:l?.[2];for(let[g,h]of p.entries()){let f=n(h),y=g===p.length-1,R=Jt(_r(h,t),r),S=!y||m===void 0&&!s(a);if(f==="string"&&(S||m===""))throw Ka(R);if(f==="number"&&S)throw new N(`${R} needs a value`,`Use ${R}=<number>`);if(f==="boolean"&&y&&m!==void 0&&!Pm.has(m))throw new N(`Invalid value for ${R}: "${m}"`,`Use ${R}=true or ${R}=false`)}return o});return Ai(i,t)}function Tm(e,t){return Ln(e,(r)=>r.replace(/^--(no-[^=]+)(=.*)?$/,(n,s,i)=>{let o=t.alias[s];return o&&t.boolean.includes(o)?`--${o}${i??""}`:n}))}function Dn(e,t){let r={},n=Object.entries(t);for(let[s,[i,o]]of n.entries())r[i]=o.variadic?e.slice(s):e[s];return r}function Mn(e,t){for(let[r,n]of Object.entries(t)){if(!n.required)continue;let s=e[r];if(Array.isArray(s)?s.length===0:!s)return`Missing required argument: <${r}${n.variadic?"...":""}>`}return null}function Za(e,t){let r=Object.values(t);if(r.some((n)=>n.variadic))return;return e[r.length]}var Im=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Am=new Set(["help","json"]),Om=/^[a-zA-Z0-9]$/,_m=new Set(["h","j"]);function Nn(){return(e)=>{let t={args:e.args??{},description:e.description,examples:e.examples??[],json:e.json??!1,name:e.name,passthrough:e.passthrough??!1,positionals:e.positionals??{},prompts:e.prompts??!1,run:e.run,strict:e.strict??!0,subcommands:e.subcommands??[]};return Lm(t),Object.freeze(t)}}function jn(e,t){let r=Oi(t.map((n)=>n.name));if(r!==void 0)throw Error(`${e} has more than one command named "${r}"`)}function Lm(e){let t=`Command "${e.name}"`;if(!Im.test(e.name))throw Error(`${t} must be named with a lower-case word such as "list" or "dry-run"`);if(!e.run&&e.subcommands.length===0)throw Error(`${t} needs run or subcommands`);for(let[p,m]of Object.entries(e.args)){if(Am.has(Oe(p)))throw Error(`${t} cannot define the option "${p}": --${Oe(p)} is a global flag`);if(m.alias!==void 0&&_m.has(m.alias))throw Error(`${t} cannot give "${p}" the alias -${m.alias}: it belongs to a global flag`)}let r=Object.keys(e.args).map(Oe),n=Oi(r);if(n!==void 0)throw Error(`${t} has more than one option named --${n}`);let s=Object.values(e.args).flatMap((p)=>p.alias??[]),i=s.find((p)=>!Om.test(p));if(i!==void 0)throw Error(`${t} uses the alias "${i}": an alias is one letter or digit`);let o=s.find((p)=>r.includes(p));if(o!==void 0)throw Error(`${t} uses the alias -${o}, which is also an option's name`);let a=Oi(s);if(a!==void 0)throw Error(`${t} uses the alias -${a} more than once`);let c=Object.keys(e.positionals),l=c.find((p)=>e.positionals[p]?.variadic);if(l!==void 0&&l!==c.at(-1))throw Error(`${t} declares the variadic positional "${l}" before other positionals`);if(e.passthrough&&(!e.run||l===void 0))throw Error(`${t} uses passthrough, which needs run and a variadic last positional`);jn(t,e.subcommands)}function Oi(e){return e.find((t,r)=>e.indexOf(t)!==r)}function $e(e){return e}import{Console as Hm}from"console";import{Writable as qm}from"stream";import{format as Wm,stripVTControlCharacters as Jm}from"util";var ct={active:!1};var Dm=new Set(["0","false"]);function Nr(e){if(process.env.NO_COLOR)return!1;let t=process.env.FORCE_COLOR;if(t!==void 0)return!Dm.has(t);return e?.isTTY===!0}var Mm=Nr(process.stdout),tc=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Nm=["bold","dim","italic","underline","reset"],rc={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},jm={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"},Fm={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"},Qa={"\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 Fn(e){return(t)=>Mm&&!ct.active?`${e}${t}${rc.reset}`:t}function Bm(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32&&r!==27)return!1}return!0}function ec({bright:e=!1,color:t}){let r=Bun.color(t,"ansi"),n=typeof r==="string"&&r.length>0&&Bm(r)?r:jm[t];if(!n)return"";return e&&n in Qa?Qa[n]:n}var Um=tc.reduce((e,t)=>{let r=ec({color:t});if(r)e[t]=Fn(r);let n=ec({bright:!0,color:t});if(n)e[`${t}Bright`]=Fn(n);return e},{}),Vm=Nm.reduce((e,t)=>(e[t]=Fn(rc[t]),e),{}),Gm=tc.reduce((e,t)=>{let r=Fm[t];if(r){let n=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[n]=Fn(r)}return e},{}),d={...Um,...Vm,...Gm};var zm=2,ic=["clear","count","countReset","debug","dir","dirxml","group","groupCollapsed","groupEnd","info","log","table"],Km=[...ic,"trace","write"],Xm=1,Ym="EPIPE",Zm="EIO",W={closedStreams:new Set,documentWritten:!1,jsonRuns:0,outputGuarded:!1,restoreStdout:void 0,sealed:!1,stdoutClosed:!1,stdoutWrite:void 0};function jr(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function _e(e){return jr()&&!ct.active&&e?.json!==!0}function oc(){return ct.active}function lt(e){let t=JSON.stringify(e??null,null,zm);if(t===void 0)throw TypeError("JSON cannot represent the value");return`${t}
|
|
4
|
+
`}function ac(){return W.documentWritten}function cc(){W.sealed=!0}function Ze(e){if(W.documentWritten=!0,W.sealed||W.stdoutClosed)return;let t=W.stdoutWrite??process.stdout.write;try{t.call(process.stdout,e)}catch(r){if(!Bn(r,process.stdout))throw r;W.stdoutClosed=!0}}function lc(){if(W.outputGuarded)return;W.outputGuarded=!0,process.stdout.write=nc(process.stdout.write,!0),console.write=nc(console.write,0),process.stdout.on("error",(e)=>{if(!Bn(e,process.stdout))throw e;W.stdoutClosed=!0}),process.stderr.on("error",(e)=>{if(!Bn(e,process.stderr))throw e});for(let e of[process.stdout,process.stderr])e.once("close",()=>W.closedStreams.add(e))}function nc(e,t){let r=(n)=>{let s=n.at(-1);if(typeof s==="function")queueMicrotask(()=>s());return t};return function(...s){if(W.stdoutClosed)return r(s);try{return e.apply(this,s)}catch(i){if(!Bn(i,process.stdout))throw i;return W.stdoutClosed=!0,r(s)}}}function Bn(e,t){if(!(e instanceof Error))return!1;let r=Reflect.get(e,"code");return r===Ym||r===Zm&&t.isTTY===!0}function Un(){let e=Nr(process.stderr);return new qm({decodeStrings:!1,write(t,r,n){process.stderr.write(e?t:Jm(t)),n()}})}async function uc(e,t){if(!e)return t();W.jsonRuns+=1,W.restoreStdout??=Qm(),ct.active=!0;try{return await t()}finally{if(W.jsonRuns-=1,ct.active=W.jsonRuns>0,!ct.active&&!W.outputGuarded)W.restoreStdout?.(),W.restoreStdout=void 0}}async function pc(e){let t=Promise.all([W.stdoutClosed?void 0:sc(process.stdout),sc(process.stderr)]);await(e===void 0?t:Promise.race([t,Bun.sleep(e)]))}function sc(e){if(e.writableFinished||W.closedStreams.has(e))return Promise.resolve();return new Promise((t)=>{e.once("close",t),e.once("finish",t),e.once("error",()=>t()),e.end(()=>t())})}function Qm(){let e=process.stdout.write,t=new Hm({stderr:process.stderr,stdout:process.stderr}),r=Object.fromEntries(Km.map((s)=>[s,console[s]])),n=Object.fromEntries(ic.map((s)=>[s,t[s].bind(t)]));return W.stdoutWrite=e,process.stdout.write=process.stderr.write.bind(process.stderr),Object.assign(console,n,{trace:eg(t),write:tg}),()=>{process.stdout.write=e,Object.assign(console,r),W.stdoutWrite=void 0}}function eg(e){let t=(...r)=>{let n={};Error.captureStackTrace(n,t);let s=n.stack?.split(`
|
|
5
|
+
`).slice(Xm)??[];e.error([`Trace: ${Wm(...r)}`,...s].join(`
|
|
6
|
+
`))};return t}function tg(...e){let t=Buffer.concat(e.map(rg));return process.stderr.write(t),t.byteLength}function rg(e){if(typeof e==="string")return Buffer.from(e);return ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}var Pe={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"},json:{alias:"j",description:"Write one JSON document to stdout",type:"boolean"}},Kt={help:Pe.help,json:Pe.json},Tt="help",Vn={[he]:"success",[Ar]:"failure",[Ga]:"usage error"};import{stripVTControlCharacters as Ki}from"util";import{styleText as hg}from"util";import{stdout as kc,stdin as yg}from"process";import wg from"readline";var dc=(()=>{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}})(),mc=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,gc=(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 ng=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,sg=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,fc=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,ig=/\t{1,1000}/y,hc=/[\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,og=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ag=/\p{M}+/gu,cg={limit:1/0,ellipsis:""},yc=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?yc(s,cg,r).width:0),o=0,a=r.controlWidth??0,c=r.tabWidth??8,l=r.emojiWidth??2,p=2,m=r.regularWidth??1,g=r.wideWidth??2,h=[[og,m],[ng,0],[sg,a],[ig,c],[hc,l],[fc,g]],f=0,y=0,R=e.length,S=0,k=!1,ee=R,G=Math.max(0,n-i),L=0,Y=0,H=0,x=0;e:while(!0){if(Y>L||y>=R&&y>f){let D=e.slice(L,Y)||e.slice(f,y);S=0;for(let we of D.replaceAll(ag,"")){let be=we.codePointAt(0)||0;if(mc(be))x=2;else if(gc(be))x=g;else x=m;if(H+x>G)ee=Math.min(ee,Math.max(L,f)+S);if(H+x>n){k=!0;break e}S+=we.length,H+=x}L=Y=0}if(y>=R)break e;for(let D=0,we=h.length;D<we;D++){let[be,Va]=h[D];if(be.lastIndex=y,be.test(e)){if(S=be===fc?dc(e.slice(y,be.lastIndex)):be===hc?1:be.lastIndex-y,x=S*Va,H+x>G)ee=Math.min(ee,y+Math.floor((G-H)/Va));if(H+x>n){k=!0;break e}H+=x,L=f,Y=y,y=f=be.lastIndex;continue e}}y+=1}return{width:k?G:H,index:k?ee:R,truncated:k,ellipsed:k&&n>=i}},wc=yc;var lg={limit:1/0,ellipsis:"",ellipsisWidth:0},ug=(e,t={})=>wc(e,lg,t).width,oe=ug;var Gn="\x1B",Pc="\x9B",pg=39,Li="\x07",Sc="[",dg="]",Cc="m",Di=`${dg}8;;`,bc=new RegExp(`(?:\\${Sc}(?<code>\\d+)m|\\${Di}(?<uri>.*)${Li})`,"y"),Rc=(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},vc=(e)=>`${Gn}${Sc}${e}${Cc}`,$c=(e)=>`${Gn}${Di}${e}${Li}`,_i=(e,t,r)=>{let n=t[Symbol.iterator](),s=!1,i=!1,o=e.at(-1),a=o===void 0?0:oe(o),c=n.next(),l=n.next(),p=0;while(!c.done){let m=c.value,g=oe(m);if(a+g<=r)e[e.length-1]+=m;else e.push(m),a=0;if(m===Gn||m===Pc)s=!0,i=t.startsWith(Di,p+1);if(s){if(i){if(m===Li)s=!1,i=!1}else if(m===Cc)s=!1}else if(a+=g,a===r&&!l.done)e.push(""),a=0;c=l,l=n.next(),p+=m.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},mg=(e)=>{let t=e.split(" "),r=t.length;while(r){if(oe(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},gg=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",s,i,o=e.split(" "),a=[""],c=0;for(let m=0;m<o.length;m++){let g=o[m];if(r.trim!==!1){let f=a.at(-1)??"",y=f.trimStart();if(f.length!==y.length)a[a.length-1]=y,c=oe(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 h=oe(g);if(r.hard&&h>t){let f=t-c,y=1+Math.floor((h-f-1)/t);if(Math.floor((h-1)/t)<y)a.push("");_i(a,g,t),c=oe(a.at(-1)??"");continue}if(c+h>t&&c&&h){if(r.wordWrap===!1&&c<t){_i(a,g,t),c=oe(a.at(-1)??"");continue}a.push(""),c=0}if(c+h>t&&r.wordWrap===!1){_i(a,g,t),c=oe(a.at(-1)??"");continue}a[a.length-1]+=g,c+=h}if(r.trim!==!1)a=a.map((m)=>mg(m));let l=a.join(`
|
|
7
|
+
`),p=!1;for(let m=0;m<l.length;m++){let g=l[m];if(n+=g,!p){if(p=g>="\uD800"&&g<="\uDBFF",p)continue}else p=!1;if(g===Gn||g===Pc){bc.lastIndex=m+1;let f=bc.exec(l)?.groups;if(f?.code!==void 0){let y=Number.parseFloat(f.code);s=y===pg?void 0:y}else if(f?.uri!==void 0)i=f.uri.length===0?void 0:f.uri}if(l[m+1]===`
|
|
8
|
+
`){if(i)n+=$c("");let h=s?Rc(s):void 0;if(s&&h)n+=vc(h)}else if(g===`
|
|
9
|
+
`){if(s&&Rc(s))n+=vc(s);if(i)n+=$c(i)}}return n},fg=/\r?\n/;function ut(e,t,r){return String(e).normalize().split(fg).map((n)=>gg(n,t,r)).join(`
|
|
10
|
+
`)}var Se={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"};var Fr={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?Se.up():"");if(e)t+=Se.left;return t}};function It(e,t,r){if(!r.some((o)=>!o.disabled))return e;let n=e+t,s=Math.max(r.length-1,0),i=n<0?s:n>s?0:n;return r[i]?.disabled?It(i,t<0?-1:1,r):i}var bg=["up","down","left","right","space","enter","cancel"],Rg=["January","February","March","April","May","June","July","August","September","October","November","December"],ae={actions:new Set(bg),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...Rg],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 xc(e){if(e!==void 0)return e;if(ae.accessible!==void 0)return ae.accessible;let t=process.env.ACCESSIBLE;return t!==void 0&&t!==""&&t!=="0"&&t!=="false"}function Ec(e,t){if(typeof e=="string")return ae.aliases.get(e)===t;for(let r of e)if(r!==void 0&&Ec(r,t))return!0;return!1}function vg(e,t){if(e===t)return;let r=e.split(`
|
|
11
|
+
`),n=t.split(`
|
|
12
|
+
`),s=Math.max(r.length,n.length),i=[];for(let o=0;o<s;o++)r[o]!==n[o]&&i.push(o);return{lines:i,numLinesBefore:r.length,numLinesAfter:n.length,numLines:s}}var YP=globalThis.process.platform.startsWith("win"),qn=Symbol("clack:cancel");function Br(e){return e===qn}function Hn(e,t){let r=e;r.isTTY&&r.setRawMode(t)}var Xt=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Mi=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function Qe(e,t,r,n=r,s=r,i){let o=Xt(e??kc),a=oe(r);return ut(t,o-a,{hard:!0,trim:!1}).split(`
|
|
13
|
+
`).map((c,l,p)=>{let m=i?i(c,l):c;return l===0?`${n}${m}`:l===p.length-1?`${s}${m}`:`${r}${m}`}).join(`
|
|
14
|
+
`)}function Tc(e,t){if("~standard"in e){let r=e["~standard"].validate(t);return r instanceof Promise?r.then((n)=>n.issues?.at(0)?.message):r.issues?.at(0)?.message}return e(t)}var Wn=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return xc(this.opts.accessible)}constructor(t,r=!0){let{input:n=yg,output:s=kc,render:i,signal:o,...a}=t;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=r,this._abortSignal=o,this.input=n,this.output=s}unsubscribe(){this._subscribers.clear()}setSubscriber(t,r){let n=this._subscribers.get(t)??[];n.push(r),this._subscribers.set(t,n)}on(t,r){this.setSubscriber(t,{cb:r})}once(t,r){this.setSubscriber(t,{cb:r,once:!0})}emit(t,...r){let n=this._subscribers.get(t)??[],s=[];for(let i of n)i.cb(...r),i.once&&s.push(()=>n.splice(n.indexOf(i),1));for(let i of s)i()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(qn);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=wg.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),Hn(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Se.show),this.output.off("resize",this.render),Hn(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Se.show),this.output.off("resize",this.render),Hn(this.input,!1),t(qn)})})}_isActionKey(t,r){return t==="\t"}_shouldSubmit(t,r){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,r){this.userInput=t??"",this.emit("userInput",this.userInput),r&&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("")}async onKeypress(t,r){if(this.state!=="validating"){if(this._track&&r.name!=="return"&&(r.name&&this._isActionKey(t,r)&&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"),r?.name&&(!this._track&&ae.aliases.has(r.name)&&this.emit("cursor",ae.aliases.get(r.name)),ae.actions.has(r.name)&&this.emit("cursor",r.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,r),r?.name==="return"&&this._shouldSubmit(t,r)){if(this.opts.validate){let n=Tc(this.opts.validate,this.value),s;n instanceof Promise?(this.state="validating",this.render(),s=await n):s=n,s&&(this.error=s instanceof Error?s.message:s,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Ec([t,r?.name,r?.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(`
|
|
15
|
+
`),Hn(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=ut(this._prevFrame,Xt(this.output),{hard:!0,trim:!1}).split(`
|
|
16
|
+
`).length-1;this.output.write(Se.move(-999,t*-1))}render(){let t=ut(this._render(this)??"",Xt(this.output),{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Se.hide);else{let r=vg(this._prevFrame,t),n=Mi(this.output);if(this.restoreCursor(),r){let s=Math.max(0,r.numLinesAfter-n),i=Math.max(0,r.numLinesBefore-n),o=r.lines.find((a)=>a>=s);if(o===void 0){this._prevFrame=t;return}if(r.lines.length===1){this.output.write(Se.move(0,o-i)),this.output.write(Fr.lines(1));let a=t.split(`
|
|
17
|
+
`);this.output.write(a[o]),this._prevFrame=t,this.output.write(Se.move(0,a.length-o-1));return}else if(r.lines.length>1){if(s<i)o=s;else{let c=o-i;c>0&&this.output.write(Se.move(0,c))}this.output.write(Fr.down());let a=t.split(`
|
|
18
|
+
`).slice(o);this.output.write(a.join(`
|
|
19
|
+
`)),this._prevFrame=t;return}}this.output.write(Fr.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};class Ni extends Wn{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(Se.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class ji extends Wn{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?It(t,1,this.options):t,this.on("key",(r,n)=>{n.name==="a"&&this.toggleAll(),n.name==="i"&&this.toggleInvert(),n.name===void 0&&r==="\u3000"&&this.toggleValue()}),this.on("cursor",(r)=>{switch(r){case"left":case"up":this.cursor=It(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=It(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Ic=class extends Wn{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:s})=>s===t.initialValue),n=r===-1?0:r;this.cursor=this.options[n]?.disabled?It(n,1,this.options):n,this.changeValue(),this.on("cursor",(s)=>{switch(s){case"left":case"up":this.cursor=It(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=It(this.cursor,1,this.options);break}this.changeValue()})}};class Fi extends Wn{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),n=e.slice(this.cursor+1);return`${t}${hg("inverse",r)}${n}`}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 lS}from"util";import Ce from"process";function $g(){if(Ce.platform!=="win32")return Ce.env.TERM!=="linux";return Boolean(Ce.env.CI)||Boolean(Ce.env.WT_SESSION)||Boolean(Ce.env.TERMINUS_SUBLIME)||Ce.env.ConEmuTask==="{cmd::Cmder}"||Ce.env.TERM_PROGRAM==="Terminus-Sublime"||Ce.env.TERM_PROGRAM==="vscode"||Ce.env.TERM==="xterm-256color"||Ce.env.TERM==="alacritty"||Ce.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Vi=$g(),Mc=()=>process.env.CI==="true";var F=(e,t)=>Vi?e:t,Ac=F("\u25C6","*"),Gi=F("\u25A0","x"),Hi=F("\u25B2","x"),Vr=F("\u25C7","o"),Pg=F("\u250C","T"),E=F("\u2502","|"),et=F("\u2514","\u2014"),gS=F("\u2510","T"),fS=F("\u2518","\u2014"),Bi=F("\u25CF",">"),zn=F("\u25CB"," "),Sg=F("\u25FB","[\u2022]"),Oc=F("\u25FC","[+]"),_c=F("\u25FB","[ ]"),hS=F("\u25AA","\u2022"),Lc=F("\u2500","-"),Cg=F("\u256E","+"),kg=F("\u251C","+"),xg=F("\u256F","+"),Eg=F("\u2570","+"),yS=F("\u256D","+"),Tg=F("\u25CF","\u2022"),Ig=F("\u25C6","*"),Ag=F("\u25B2","!"),Og=F("\u25A0","x"),Kn=(e)=>{switch(e){case"initial":case"active":return w("cyan",Ac);case"cancel":return w("red",Gi);case"error":return w("yellow",Hi);case"submit":return w("green",Vr);case"validating":return w("dim",Ac)}},Nc=(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 jc(e,t,r){let n=r?`${w("cyan",E)} `:"",s=Qe(e,t.join(" \u2022 "),n).split(`
|
|
20
|
+
`);return r&&s.push(w("cyan",et)),s}var Dc=(e,t,r,n,s,i=!1)=>{let o=t,a=0;if(i)for(let c=n-1;c>=r;c--){let l=e[c];if(l&&(o-=l.length),a++,o<=s)break}else for(let c=r;c<n;c++){let l=e[c];if(l&&(o-=l.length),a++,o<=s)break}return{lineCount:o,removals:a}},Ui=({cursor:e,options:t,style:r,output:n=process.stdout,maxItems:s=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=Xt(n)-i,c=Mi(n),l=w("dim","..."),p=Math.max(c-o,0),m=Math.max(Math.min(s,p),5),g=0;e>=m-3&&(g=Math.max(Math.min(e-m+3,t.length-m),0));let h=m<t.length&&g>0,f=m<t.length&&g+m<t.length,y=Math.min(g+m,t.length),R=[],S=0;h&&S++,f&&S++;let k=g+(h?1:0),ee=y-(f?1:0);for(let L=k;L<ee;L++){let Y=t[L],H=Y!==void 0?r(Y,L===e):"",x=ut(H,a,{hard:!0,trim:!1}).split(`
|
|
21
|
+
`);R.push(x),S+=x.length}if(S>p){let L=0,Y=0,H=S,x=e-k,D=p,we=()=>Dc(R,H,0,x,D),be=()=>Dc(R,H,x+1,R.length,D,!0);h?({lineCount:H,removals:L}=we(),H>D&&(f||(D-=1),{lineCount:H,removals:Y}=be())):(f||(D-=1),{lineCount:H,removals:Y}=be(),H>D&&(D-=1,{lineCount:H,removals:L}=we())),L>0&&(h=!0,R.splice(0,L)),Y>0&&(f=!0,R.splice(R.length-Y,Y))}let G=[];h&&G.push(l);for(let L of R)for(let Y of L)G.push(Y);return f&&G.push(l),G};var Fc=(e)=>{let t=e.active??"Yes",r=e.inactive??"No";return new Ni({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let n=e.withGuide??ae.withGuide,s=`${Kn(this.state)} `,i=n?`${w("gray",E)} `:"",o=Qe(e.output,e.message,i,s),a=`${n?`${w("gray",E)}
|
|
18
22
|
`:""}${o}
|
|
19
|
-
`,c=this.value?t:r;switch(this.state){case"submit":{let l=
|
|
20
|
-
${w("gray",E)}`:""}`}default:{let l=
|
|
23
|
+
`,c=this.value?t:r;switch(this.state){case"submit":{let l=n?`${w("gray",E)} `:"";return`${a}${l}${w("dim",c)}`}case"cancel":{let l=n?`${w("gray",E)} `:"";return`${a}${l}${w(["strikethrough","dim"],c)}${n?`
|
|
24
|
+
${w("gray",E)}`:""}`}default:{let l=n?`${w("cyan",E)} `:"",p=n?w("cyan",et):"";return`${a}${l}${this.value?`${w("green",Bi)} ${t}`:`${w("dim",zn)} ${w("dim",t)}`}${e.vertical?n?`
|
|
21
25
|
${w("cyan",E)} `:`
|
|
22
|
-
`:` ${w("dim","/")} `}${this.value?`${w("dim",
|
|
26
|
+
`:` ${w("dim","/")} `}${this.value?`${w("dim",zn)} ${w("dim",r)}`:`${w("green",Bi)} ${r}`}
|
|
23
27
|
${p}
|
|
24
|
-
`}}}}).prompt()};var
|
|
28
|
+
`}}}}).prompt()};var Xn=async(e,t)=>{let r={},n=Object.keys(e);for(let s of n){let i=e[s],o=await i({results:r})?.catch((a)=>{throw a});if(typeof t?.onCancel=="function"&&Br(o)){r[s]="canceled",t.onCancel({results:r});continue}r[s]=o}return r},_g=[`${w("dim","\u2191/\u2193")} to navigate`,`${w("dim","Space:")} select`,`${w("dim","Enter:")} confirm`],Ur=(e,t)=>e.split(`
|
|
25
29
|
`).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
|
|
30
|
+
`),Bc=(e)=>{let t=(s,i)=>{let o=s.label??String(s.value);return i==="disabled"?`${w("gray",_c)} ${Ur(o,(a)=>w(["strikethrough","gray"],a))}${s.hint?` ${w("dim",`(${s.hint??"disabled"})`)}`:""}`:i==="active"?`${w("cyan",Sg)} ${o}${s.hint?` ${w("dim",`(${s.hint})`)}`:""}`:i==="selected"?`${w("green",Oc)} ${Ur(o,(a)=>w("dim",a))}${s.hint?` ${w("dim",`(${s.hint})`)}`:""}`:i==="cancelled"?`${Ur(o,(a)=>w(["strikethrough","dim"],a))}`:i==="active-selected"?`${w("green",Oc)} ${o}${s.hint?` ${w("dim",`(${s.hint})`)}`:""}`:i==="submitted"?`${Ur(o,(a)=>w("dim",a))}`:`${w("dim",_c)} ${Ur(o,(a)=>w("dim",a))}`},r=e.required??!0,n=e.showInstructions??!0;return new ji({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:r,cursorAt:e.cursorAt,validate(s){if(r&&(s===void 0||s.length===0))return`Please select at least one option.
|
|
31
|
+
${w("reset",w("dim",`Press ${w(["gray","bgWhite","inverse"]," space ")} to select, ${w("gray",w("bgWhite",w("inverse"," enter ")))} to submit`))}`},render(){let s=e.withGuide??ae.withGuide,i=Qe(e.output,e.message,s?`${Nc(this.state)} `:"",`${Kn(this.state)} `),o=`${s?`${w("gray",E)}
|
|
28
32
|
`:""}${i}
|
|
29
|
-
`,a=this.value??[],c=(l,p)=>{if(l.disabled)return t(l,"disabled");let
|
|
30
|
-
${w("gray",E)}`:""}`}case"error":{let l=
|
|
31
|
-
`).map((f
|
|
32
|
-
`),
|
|
33
|
-
`).length,
|
|
34
|
-
`).length+1;return`${o}${l}${
|
|
33
|
+
`,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=Qe(e.output,l,s?`${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=Qe(e.output,l,s?`${w("gray",E)} `:"");return`${o}${p}${s?`
|
|
34
|
+
${w("gray",E)}`:""}`}case"error":{let l=s?`${w("yellow",E)} `:"",p=this.error.split(`
|
|
35
|
+
`).map((h,f)=>f===0?`${s?`${w("yellow",et)} `:""}${w("yellow",h)}`:` ${h}`).join(`
|
|
36
|
+
`),m=o.split(`
|
|
37
|
+
`).length,g=p.split(`
|
|
38
|
+
`).length+1;return`${o}${l}${Ui({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:m+g,style:c}).join(`
|
|
35
39
|
${l}`)}
|
|
36
40
|
${p}
|
|
37
|
-
`}default:{let l=
|
|
38
|
-
`).length,
|
|
39
|
-
`),
|
|
41
|
+
`}default:{let l=s?`${w("cyan",E)} `:"",p=o.split(`
|
|
42
|
+
`).length,m=n?jc(e.output,_g,s):s?[w("cyan",et)]:[],g=m.join(`
|
|
43
|
+
`),h=m.length+1;return`${o}${l}${Ui({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:p+h,style:c}).join(`
|
|
40
44
|
${l}`)}
|
|
41
|
-
${
|
|
42
|
-
`}}}}).prompt()};var
|
|
43
|
-
`);if(
|
|
45
|
+
${g}
|
|
46
|
+
`}}}}).prompt()};var ue={message:(e=[],{symbol:t=w("gray",E),secondarySymbol:r=w("gray",E),output:n=process.stdout,spacing:s=1,withGuide:i}={})=>{let o=[],a=i??ae.withGuide,c=a?r:"",l=a?`${t} `:"",p=a?`${r} `:"";for(let g=0;g<s;g++)o.push(c);let m=Array.isArray(e)?e:e.split(`
|
|
47
|
+
`);if(m.length>0){let[g,...h]=m;g.length>0?o.push(`${l}${g}`):o.push(a?t:"");for(let f of h)f.length>0?o.push(`${p}${f}`):o.push(a?r:"")}n.write(`${o.join(`
|
|
44
48
|
`)}
|
|
45
|
-
`)},info:(e,t)=>{
|
|
46
|
-
`)},
|
|
47
|
-
${w("gray",
|
|
48
|
-
|
|
49
|
-
`)};var
|
|
50
|
-
`),i=
|
|
51
|
-
`).map(i),""],a=
|
|
52
|
-
`),p=
|
|
53
|
-
`:"",
|
|
49
|
+
`)},info:(e,t)=>{ue.message(e,{...t,symbol:w("blue",Tg)})},success:(e,t)=>{ue.message(e,{...t,symbol:w("green",Ig)})},step:(e,t)=>{ue.message(e,{...t,symbol:w("green",Vr)})},warn:(e,t)=>{ue.message(e,{...t,symbol:w("yellow",Ag)})},warning:(e,t)=>{ue.warn(e,t)},error:(e,t)=>{ue.message(e,{...t,symbol:w("red",Og)})}};var Uc=(e="",t)=>{let r=t?.output??process.stdout,n=t?.withGuide??ae.withGuide?`${w("gray",Pg)} `:"";r.write(`${n}${e}
|
|
50
|
+
`)},Vc=(e="",t)=>{let r=t?.output??process.stdout,n=t?.withGuide??ae.withGuide?`${w("gray",E)}
|
|
51
|
+
${w("gray",et)} `:"";r.write(`${n}${e}
|
|
52
|
+
|
|
53
|
+
`)};var Lg=(e)=>e,Dg=(e,t,r)=>{let n={hard:!0,trim:!1},s=ut(e,t,n).split(`
|
|
54
|
+
`),i=s.reduce((c,l)=>Math.max(oe(l),c),0),o=s.map(r).reduce((c,l)=>Math.max(oe(l),c),0),a=t-(o-i);return ut(e,a,n)},Gc=(e="",t="",r)=>{let n=r?.output??Ce.stdout,s=r?.withGuide??ae.withGuide,i=r?.format??Lg,o=["",...Dg(e,Xt(n)-6,i).split(`
|
|
55
|
+
`).map(i),""],a=oe(t),c=Math.max(o.reduce((g,h)=>{let f=oe(h);return f>g?f:g},0),a)+2,l=o.map((g)=>`${w("gray",E)} ${g}${" ".repeat(c-oe(g))}${w("gray",E)}`).join(`
|
|
56
|
+
`),p=s?`${w("gray",E)}
|
|
57
|
+
`:"",m=s?kg:Eg;n.write(`${p}${w("green",Vr)} ${w("reset",t)} ${w("gray",Lc.repeat(Math.max(c-a-1,1))+Cg)}
|
|
54
58
|
${l}
|
|
55
|
-
${w("gray",
|
|
56
|
-
`)};var
|
|
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=Zi({output:r}),g=A(J),R=performance.now(),ne&&r.write(`${w("gray",E)}
|
|
59
|
-
`);let ue=0,Ce=0;W(),d=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 ol=".".repeat(Math.floor(Ce)).slice(0,3);vr=`${ke} ${g}${ol}`}let il=Se(vr,S,{hard:!0,trim:!1});r.write(il),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(d),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
|
-
`):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}}},Qg={light:N("\u2500","-"),heavy:N("\u2501","="),block:N("\u2588","#")};var Zl=[`${w("dim","\u2191/\u2193")} to navigate`,`${w("dim","Enter:")} confirm`],Rr=(e,t)=>e.includes(`
|
|
59
|
+
${w("gray",m+Lc.repeat(c+2)+xg)}
|
|
60
|
+
`)};var wS={light:F("\u2500","-"),heavy:F("\u2501","="),block:F("\u2588","#")};var Mg=[`${w("dim","\u2191/\u2193")} to navigate`,`${w("dim","Enter:")} confirm`],Jn=(e,t)=>e.includes(`
|
|
62
61
|
`)?e.split(`
|
|
63
62
|
`).map((r)=>t(r)).join(`
|
|
64
|
-
`):t(e),
|
|
63
|
+
`):t(e),Hc=(e)=>{let t=(n,s)=>{if(n===void 0)return"";let i=n.label??String(n.value);switch(s){case"disabled":return`${w("gray",zn)} ${Jn(i,(o)=>w("gray",o))}${n.hint?` ${w("dim",`(${n.hint??"disabled"})`)}`:""}`;case"selected":return`${Jn(i,(o)=>w("dim",o))}`;case"active":return`${w("green",Bi)} ${i}${n.hint?` ${w("dim",`(${n.hint})`)}`:""}`;case"cancelled":return`${Jn(i,(o)=>w(["strikethrough","dim"],o))}`;default:return`${w("dim",zn)} ${Jn(i,(o)=>w("dim",o))}`}},r=e.showInstructions??!0;return new Ic({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??ae.withGuide,s=`${Kn(this.state)} `,i=`${Nc(this.state)} `,o=Qe(e.output,e.message,i,s),a=`${n?`${w("gray",E)}
|
|
65
64
|
`:""}${o}
|
|
66
|
-
`;switch(this.state){case"submit":{let c=
|
|
67
|
-
${w("gray",E)}`:""}`}default:{let c=
|
|
68
|
-
`).length,p=r?
|
|
69
|
-
`),
|
|
65
|
+
`;switch(this.state){case"submit":{let c=n?`${w("gray",E)} `:"",l=Qe(e.output,t(this.options[this.cursor],"selected"),c);return`${a}${l}`}case"cancel":{let c=n?`${w("gray",E)} `:"",l=Qe(e.output,t(this.options[this.cursor],"cancelled"),c);return`${a}${l}${n?`
|
|
66
|
+
${w("gray",E)}`:""}`}default:{let c=n?`${w("cyan",E)} `:"",l=a.split(`
|
|
67
|
+
`).length,p=r?jc(e.output,Mg,n):n?[w("cyan",et)]:[],m=p.join(`
|
|
68
|
+
`),g=p.length+1;return`${a}${c}${Ui({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:c.length,rowPadding:l+g,style:(h,f)=>t(h,h.disabled?"disabled":f?"active":"inactive")}).join(`
|
|
70
69
|
${c}`)}
|
|
71
|
-
${
|
|
72
|
-
`}}}}).prompt()};var
|
|
73
|
-
`:""}${
|
|
74
|
-
`,
|
|
75
|
-
${a}${
|
|
70
|
+
${m}
|
|
71
|
+
`}}}}).prompt()};var bS=`${w("gray",E)} `;var qc=(e)=>new Fi({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??ae.withGuide,r=`${`${t?`${w("gray",E)}
|
|
72
|
+
`:""}${Kn(this.state)} `}${e.message}
|
|
73
|
+
`,n=e.placeholder&&e.placeholder.length>0?w("inverse",e.placeholder[0])+w("dim",e.placeholder.slice(1)):w(["inverse","hidden"],"_"),s=this.userInput?this.userInputWithCursor:n,i=this.value??"";switch(this.state){case"validating":{let o=t?`${w("cyan",E)} `:"",a=t?w("cyan",et):"",c=w("dim",s),l=w("dim","Validating...");return`${r}${o}${c}
|
|
74
|
+
${a} ${l}
|
|
75
|
+
`}case"error":{let o=this.error?` ${w("yellow",this.error)}`:"",a=t?`${w("yellow",E)} `:"",c=t?w("yellow",et):"";return`${r.trim()}
|
|
76
|
+
${a}${s}
|
|
76
77
|
${c}${o}
|
|
77
|
-
`}case"submit":{let o=i
|
|
78
|
-
${a}`:""}`}default:{let o=t?`${w("cyan",E)} `:"",a=t?w("cyan",
|
|
78
|
+
`}case"submit":{let o=i?`${t?" ":""}${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()?`
|
|
79
|
+
${a}`:""}`}default:{let o=t?`${w("cyan",E)} `:"",a=t?w("cyan",et):"";return`${r}${o}${s}
|
|
79
80
|
${a}
|
|
80
|
-
`}}}}).prompt();
|
|
81
|
-
`)
|
|
82
|
-
`)
|
|
83
|
-
|
|
84
|
-
|
|
81
|
+
`}}}}).prompt();function Wc(e=process.stdin){return e.readableEnded||e.destroyed}async function Jc({edits:e,input:t=process.stdin,signal:r},n){let s=new AbortController,i=()=>s.abort(),o=(c,l)=>{if(l.sequence==="\x04"&&(!e||t.isPaused()))i()},a=n(r?AbortSignal.any([s.signal,r]):s.signal);t.on("keypress",o),t.once("end",i),t.once("close",i);try{return await a}finally{t.off("keypress",o),t.off("end",i),t.off("close",i)}}import{stripVTControlCharacters as jg}from"util";var qi=Vi?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],Fg=80,Bg=8,Ug=3,Vg="...",Wi="\r\x1B[K",Gg=80,Hg=/\s*\n\s*/g,Gr=new Set;function Kc(){for(let e of[...Gr])e.error()}function Xc({output:e=process.stdout}={}){let t=e.isTTY===!0&&!Mc(),r=Nr(e),n="",s=0,i=!1,o,a=(h)=>{e.write(t||r?h:jg(h))},c=()=>{let h=d.magenta(qi[s%qi.length]??""),f=".".repeat(Math.floor(s/Bg)%(Ug+1)),y=`${h} ${n.replace(Hg," ")}${f}`;a(`${Wi}${Bun.sliceAnsi(y,0,(e.columns||Gg)-1)}`),s+=1},l=()=>t?c():a(`${d.magenta(qi[0]??"")} ${n}${Vg}
|
|
82
|
+
`),p=()=>(clearInterval(o),Gr.delete(g)),m=(h,f)=>{if(p())a(`${t?Wi:""}${h} ${f}
|
|
83
|
+
`)},g={cancel(h=n){i=Gr.has(g)||i,m(d.red(Gi),h)},clear(){if(p()&&t)a(Wi)},error(h=n){m(d.red(Hi),h)},get isCancelled(){return i},message(h=n){let f=zc(h);if(f===n)return;if(n=f,Gr.has(g)&&!t)l()},start(h=""){if(g.clear(),i=!1,n=zc(h),s=0,Gr.add(g),a(`${d.gray(E)}
|
|
84
|
+
`),l(),!t)return;o=setInterval(c,Fg),o.unref()},stop(h=n){m(d.green(Vr),h)}};return g}function zc(e){return e.replace(/\.+$/,"")}var qg="Pass the value as an argument or option instead";function Wg(e){if(Br(e))throw new Re;return e}function Jg(e){if(_e())return;throw new N(`Cannot prompt for ${e} without a terminal`,qg)}async function Yn(e,t,{edits:r=!1,hint:n}){if(Jg(t.message),Wc(t.input))throw new Re;return Kg(n),Wg(await Jc({...t,edits:r},(s)=>e({...t,signal:s})))}function zg(e){return e.map((t)=>t.key?`${d.bold(t.key)} ${d.dim(t.text)}`:d.dim(t.text)).join(d.dim(" \xB7 "))}function Kg(e){ue.info(zg(e))}var Zn={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 Yn(Fc,e,{hint:Zn.confirm})}async function ve(e){return Yn(qc,e,{edits:!0,hint:Zn.text})}async function At(e){return Yn(Hc,{showInstructions:!1,...e},{hint:Zn.select})}async function tt(e){return Yn(Bc,{showInstructions:!1,...e},{hint:Zn.multiselect})}function Zt(e){return oc()&&e.output===void 0?{...e,output:process.stderr}:e}function Yt(e){return(t,r={})=>e(t,Zt(r))}var v={error:Yt(ue.error),info:Yt(ue.info),message:(e,t={})=>ue.message(e,Zt(t)),step:Yt(ue.step),success:Yt(ue.success),warn:Yt(ue.warn),warning:Yt(ue.warning)};function Ji(e,t={}){Uc(e,Zt(t))}function zi(e,t={}){Vc(e,Zt(t))}function te(e,t,r={}){Gc(e,t,Zt(r))}function Ve(e={}){return Xc(Zt(e))}import{inspect as Xg}from"util";var Yg=4;function Qn(e,t=[]){if(t.length>=Yg)return[];let r=e instanceof AggregateError?e.errors:[],n=[...t,e];return[...r,...e.cause!==void 0?[e.cause]:[]].filter((i)=>!n.includes(i)).flatMap((i)=>[{hint:ts(i),message:es(i)},...i instanceof Error?Qn(i,n):[]])}function es(e){return rs(e instanceof Error?e.message||e.name:e)}function ts(e){return e instanceof u&&e.hint!==void 0?rs(e.hint):void 0}function rs(e){return typeof e==="string"?e:Xg(e,{breakLength:Number.POSITIVE_INFINITY})}var Zg="Error",Qg=27,ef=new RegExp(`${String.fromCharCode(Qg)}\\[[\\d;]*m`,"g"),tf=9,rf=10,nf=31,sf=127,of=159,af=16,cf=4;function pt(e,{json:t}){if(Kc(),pf(e),t)Ze(lt({error:lf(e)}));return Yc(e)}function lf(e){let t=Yc(e),r=Ki(es(e));if(!(e instanceof Error))return{_tag:Zg,message:r,exitCode:t,causes:[]};let n=ts(e);return{_tag:uf(e),message:r,hint:n===void 0?void 0:Ki(n),exitCode:t,causes:Qn(e).map((s)=>Ki(s.message))}}function Yc(e){if(e instanceof Re)return he;if(e instanceof u)return En(e.exitCode)?e.exitCode:Ar;return Ar}function uf(e){let t=Reflect.get(e,"_tag");return typeof t==="string"?t:rs(e.name)}function pf(e){if(e instanceof Re)return;let t=Un(),r=ns(es(e));if(e instanceof u){let n=ts(e);if(v.warn(d.yellow(r),{output:t}),n)v.info(d.dim(ns(n)),{output:t})}else v.error(d.red(r),{output:t});if(!(e instanceof Error))return;for(let n of Qn(e))if(v.info(d.dim(`caused by: ${ns(n.message)}`),{output:t}),n.hint)v.info(d.dim(` ${ns(n.hint)}`),{output:t})}function ns(e){return Array.from(e.replace(ef,""),(t)=>{let r=t.charCodeAt(0);return r<=nf&&r!==tf&&r!==rf||r>=sf&&r<=of?`\\u${r.toString(af).padStart(cf,"0")}`:t}).join("")}var df=500,mf="The command stopped before it finished because nothing was left for it to wait for";function Zc({json:e}){let t={ending:void 0,failed:!1,settled:!1},r=(s,i)=>(t.ending??=gf(s,i),t.ending),n=(s)=>{if(t.failed||t.ending)return;t.failed=!0;let i=pt(s,{json:e&&!ac()});cc(),r(i,t.settled?void 0:df)};return process.on("uncaughtException",n),process.on("unhandledRejection",n),process.on("beforeExit",()=>{if(!t.settled)n(Error(mf))}),{exit:(s)=>r(s),settle(){t.settled=!0}}}async function gf(e,t){process.exitCode=e,await pc(t),process.exit(e)}var rt=new Uint32Array(65536),ff=(e,t)=>{let r=e.length,n=t.length,s=1<<r-1,i=-1,o=0,a=r,c=r;while(c--)rt[e.charCodeAt(c)]|=1<<c;for(c=0;c<n;c++){let l=rt[t.charCodeAt(c)],p=l|o;if(l|=(l&i)+i^i,o|=~(l|i),i&=l,o&s)a++;if(i&s)a--;o=o<<1|1,i=i<<1|~(p|o),o&=p}c=r;while(c--)rt[e.charCodeAt(c)]=0;return a},hf=(e,t)=>{let r=t.length,n=e.length,s=[],i=[],o=Math.ceil(r/32),a=Math.ceil(n/32);for(let f=0;f<o;f++)i[f]=-1,s[f]=0;let c=0;for(;c<a-1;c++){let f=0,y=-1,R=c*32,S=Math.min(32,n)+R;for(let k=R;k<S;k++)rt[e.charCodeAt(k)]|=1<<k;for(let k=0;k<r;k++){let ee=rt[t.charCodeAt(k)],G=i[k/32|0]>>>k&1,L=s[k/32|0]>>>k&1,Y=ee|f,H=((ee|L)&y)+y^y|ee|L,x=f|~(H|y),D=y&H;if(x>>>31^G)i[k/32|0]^=1<<k;if(D>>>31^L)s[k/32|0]^=1<<k;x=x<<1|G,D=D<<1|L,y=D|~(Y|x),f=x&Y}for(let k=R;k<S;k++)rt[e.charCodeAt(k)]=0}let l=0,p=-1,m=c*32,g=Math.min(32,n-m)+m;for(let f=m;f<g;f++)rt[e.charCodeAt(f)]|=1<<f;let h=n;for(let f=0;f<r;f++){let y=rt[t.charCodeAt(f)],R=i[f/32|0]>>>f&1,S=s[f/32|0]>>>f&1,k=y|l,ee=((y|S)&p)+p^p|y|S,G=l|~(ee|p),L=pⅇif(h+=G>>>n-1&1,h-=L>>>n-1&1,G>>>31^R)i[f/32|0]^=1<<f;if(L>>>31^S)s[f/32|0]^=1<<f;G=G<<1|R,L=L<<1|S,p=L|~(k|G),l=G&k}for(let f=m;f<g;f++)rt[e.charCodeAt(f)]=0;return h},yf=(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 ff(e,t);return hf(e,t)},Qc=(e,t)=>{let r=1/0,n=0;for(let s=0;s<t.length;s++){let i=yf(e,t[s]);if(i<r)r=i,n=s}return t[n]};function ss(e,t,r){let n=t.length>0?Qc(e,[...t]):void 0,s=`Run "${r} --help" for usage.`;return new N(`Unknown command: ${e}`,n?`Did you mean "${n}"? ${s}`:s)}function Ot(e,t){if(Array.isArray(t))return[...t];if(!el(e)||!el(t))return t;return Object.fromEntries([...Object.entries(e),...Object.entries(t).map(([r,n])=>[r,Ot(Object.hasOwn(e,r)?e[r]:void 0,n)])])}function el(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function tl(e,t){return{name:e.name,bin:e.bin,version:e.version,description:e.description,exitCodes:{...Vn},options:rl(Pe),commands:t.map((r)=>is(r,`${e.bin} ${r.name}`))}}function is(e,t){return{name:e.name,path:t,description:e.description,json:e.json,prompts:e.prompts,passthrough:e.passthrough,positionals:Object.entries(e.positionals).map(([r,n])=>({name:r,required:n.required??!1,variadic:n.variadic??!1,description:n.description??""})),options:rl(e.args),examples:[...e.examples],commands:e.subcommands.map((r)=>is(r,`${t} ${r.name}`))}}function rl(e){return Object.entries(e).map(([t,r])=>({name:t,flag:`--${Oe(t)}`,...r.alias?{alias:`-${r.alias}`}:{},type:r.type,...r.default===void 0?{}:{default:r.default},...r.displayDefault===void 0?{}:{displayDefault:r.displayDefault},description:r.description??""}))}import{stripVTControlCharacters as nl}from"util";var wf=2,bf="0.0.0",Rf=(e)=>e,I={arg:d.magenta,cmd:d.cyan,default:d.bold,desc:Rf,flag:d.green,header:(e)=>d.bold(d.yellow(e)),hint:d.dim,name:(e)=>d.bold(d.cyan(e)),placeholder:d.magenta};function sl(e){return`${I.name(e.name)} ${I.hint(e.version??bf)}`}function il(e,t){let r=`${I.name(e.name)}${e.version?` ${I.hint(`v${e.version}`)}`:""}`;return al([[r,...e.description?[I.desc(e.description)]:[]],Ge("Usage:",[` ${I.cmd(e.bin)} ${I.placeholder("[command]")} ${I.placeholder("[options]")}`]),Ge("Commands:",cl(t)),Ge("Options:",ul(Pe)),Ge("Exit codes:",ll()),[`${I.hint("Run")} ${I.cmd(`${e.bin} <command> --help`)} ${I.hint("for command details.")}`]])}function ol(e,t){let r=e.json?{...e.args,json:Pe.json}:e.args,n=[...e.subcommands.length>0?[` ${I.cmd(t)} ${I.placeholder("<command>")} ${I.placeholder("[options]")}`]:[],...e.run?[` ${vf(e,t).join(" ")}`]:[],...e.prompts&&Object.keys(e.positionals).length>0?[` ${I.hint("Omit positional arguments to run interactively.")}`]:[],...e.passthrough?[` ${I.hint("Options end at the first argument; it and everything after it are passed on unchanged.")}`]:[]];return al([[I.name(t),I.desc(e.description)],Ge("Usage:",n),Ge("Commands:",cl(e.subcommands)),Ge("Arguments:",Pf(e.positionals)),Ge("Options:",ul(r)),Ge("Examples:",e.examples.map((s)=>` ${I.cmd(s)}`)),Ge("Exit codes:",ll())])}function vf(e,t){let r=$f(e.positionals);return e.passthrough?[I.cmd(t),I.placeholder("[options]"),I.placeholder("[--]"),...r]:[I.cmd(t),...r,I.placeholder("[options]")]}function Ge(e,t){return t.length>0?[I.header(e),...t]:[]}function al(e){return e.filter((t)=>t.length>0).map((t)=>t.join(`
|
|
85
|
+
`)).join(`
|
|
86
|
+
|
|
87
|
+
`)}function cl(e){return os(e.map((t)=>[` ${I.cmd(t.name)}`,I.desc(t.description)]))}function ll(){return os(Object.entries(Vn).map(([e,t])=>[` ${e}`,t]))}function Xi(e,t){return t.variadic?`${e}...`:e}function $f(e){return Object.entries(e).map(([t,r])=>r.required?I.arg(`<${Xi(t,r)}>`):I.arg(`[${Xi(t,r)}]`))}function Pf(e){return os(Object.entries(e).map(([t,r])=>[` ${I.arg(Xi(t,r))}`,`${I.desc(r.description??"")}${r.required?"":I.hint(" (optional)")}`]))}function ul(e){return os(Object.entries(e).map(([t,r])=>{let n=r.alias?`${I.flag(`-${r.alias}`)}, `:" ",s=r.type==="boolean"?"":` ${I.placeholder(`<${r.type==="number"?"number":"value"}>`)}`,i=Sf(r),o=i===void 0?"":` (default: ${I.default(i)})`;return[` ${n}${I.flag(`--${Oe(t)}`)}${s}`,`${I.desc(r.description??"")}${o}`]}))}function Sf(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)}function os(e){let t=Math.max(0,...e.map(([r])=>nl(r).length));return e.map(([r,n])=>`${r}${" ".repeat(t-nl(r).length+wf)}${n}`)}function as(e){let t=!1;return{emitted:()=>t,json:e,result(r,n){if(t)throw Error("ctx.output.result was called more than once; a command emits one result");let s=Cf(e,r,n);if(t=!0,s!==void 0)Ze(s)}}}function Cf(e,t,r){if(e)return lt(t);return r?`${r(t)}
|
|
88
|
+
`:void 0}function cs(e,t,r){return{args:t.args,cli:e.info,config:e.config,interactive:t.interactive,json:t.json,output:r,positionals:t.positionals}}async function ls(e,t,r,n){let s=await uc(r.json,async()=>{let i=await e.run?.(r);return typeof i==="number"?kf(t,i):he});if(r.json&&!n.emitted())throw Error(`${t} finished in JSON mode without calling ctx.output.result`);return s}function kf(e,t){if(En(t))return t;throw Error(`${e} returned ${t}, which is not an exit code from ${he} to ${Ha}`)}var Yi="__exit__",pl="__run__",xf="Back",Ef="Return to previous menu";async function dl(e,t){if(t)throw new N("Interactive mode cannot be combined with --json","Pass a command and its arguments instead");if(!jr())throw new N("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(e.interactive.clearOnStart)console.clear();let r=e.info.version?` v${e.info.version}`:"";Ji(d.bgCyan(d.black(` ${e.info.name}${r} `)));let n={commands:e.commands,message:e.interactive.promptMessage,path:e.info.bin,root:!0};return await ml(e,new Map,n),zi(e.interactive.goodbyeMessage),he}async function ml(e,t,r){while(!0){let n=await Tf(e,t,r);if(n===void 0)return;if(t.set(r.path,n),n===pl&&r.owner){await gl(e,r.owner,r.path);continue}let s=r.commands.find((i)=>i.name===n);if(s)await If(e,t,s,`${r.path} ${n}`)}}async function Tf(e,t,r){let n=r.root?{hint:e.interactive.exitHint,label:e.interactive.exitLabel,value:Yi}:{hint:Ef,label:xf,value:Yi};try{let s=await At({initialValue:t.get(r.path),message:r.message,options:[...r.owner?[{hint:r.owner.description,label:r.owner.name,value:pl}]:[],...r.commands.map((i)=>({hint:i.description,label:i.name,value:i.name})),n]});return s===Yi?void 0:s}catch(s){if(s instanceof Re)return;throw s}}async function If(e,t,r,n){if(r.subcommands.length===0)return gl(e,r,n);return ml(e,t,{commands:r.subcommands,message:`${r.name}:`,path:n,root:!1,...r.run?{owner:r}:{}})}async function gl(e,t,r){try{await Af(e,t,r)}catch(n){if(n instanceof Re)return;if(!(n instanceof u))throw n;pt(n,{json:!1})}}async function Af(e,t,r){let{args:n}=Mr([],t.args),s=Dn([],t.positionals),i=t.prompts?null:Mn(s,t.positionals);if(i)throw new N(i,`Run "${r} --help" for usage.`);let o=as(!1),a={args:_n(n,t.args),interactive:t.prompts,json:!1,positionals:s};await ls(t,r,cs(e,a,o),o)}var Of="--",_f=/^(?:--json(?:=true)?|-[^-=]*j[^-=]*(?:=true)?)$/,Lf=/^(?:--no-(?:help|json)|(?:--(?:help|json)|-[hj]+)(?:=(?:true|false))?)$/;async function Zi(e,t){try{return await Df(e,t)}catch(r){return{code:pt(r,{json:eo(t)}),menu:!1}}}function Qi(e,t){let{command:r,restArgs:n}=On(t,Pe),s=r===void 0||r===Tt?void 0:yl(e,r,n);if(!s||s instanceof N||!s.command.passthrough)return{operands:[],options:[...t]};let i=Xa(s.tokens,{...s.command.args,...Kt}),o=i<0?[]:s.tokens.slice(i);return{operands:o,options:t.slice(0,t.length-o.length)}}async function Df(e,{options:t,operands:r}){let{command:n,flags:s,restArgs:i}=Ii(t,Pe,Kt),o=s.json===!0,a={code:he,menu:!1};if(n===void 0){if(s.interactive&&!s.help&&!s.version)return{code:await dl(e,o),menu:!0};return Ze(s.version&&!s.help?Nf(e,o):fl(e,o)),a}let c=s.interactive?"--interactive":s.version?"--version":void 0;if(c)throw new N(`${c} cannot be combined with a command`,`Run "${e.info.bin} ${c}" on its own.`);if(n===Tt)return Ze(jf(e,i,o)),a;let l=Ff(e,n,i);if(s.help)return Ze(to(l.command,l.path,o)),a;return{code:await Bf(e,l,r,o),menu:!1}}function eo({options:e}){let{before:t,restArgs:r}=On(e,Pe);return[t,r].some((n)=>Mf(n).some((s)=>_f.test(s)))}function Mf(e){let t=e.indexOf(Of);return t<0?e:e.slice(0,t)}function Nf({info:e},t){return t?lt({name:e.name,bin:e.bin,version:e.version}):`${sl(e)}
|
|
89
|
+
`}function fl(e,t){return t?lt(tl(e.info,e.commands)):`${il(e.info,e.commands)}
|
|
90
|
+
`}function to(e,t,r){return r?lt(is(e,t)):`${ol(e,t)}
|
|
91
|
+
`}function jf(e,t,r){let{args:n,rawPositionals:s}=Mr(t,Kt);if(An(n,Kt,`Run "${e.info.bin} ${Tt} [command]" for usage.`,t),s.length===0)return fl(e,r);let{command:i,path:o}=hl(e.commands,s,e.info.bin);return to(i,o,r)}function hl(e,t,r){let[n="",...s]=t,i=e.find((a)=>a.name===n);if(!i)throw ss(n,ro(e),r);let o=`${r} ${n}`;return s.length===0?{command:i,path:o}:hl(i.subcommands,s,o)}function ro(e){return e.map((t)=>t.name)}function Ff(e,t,r){let n=yl(e,t,r);if(n instanceof N)throw n;return n}function yl(e,t,r){let n=e.commands.find((s)=>s.name===t);if(!n)return ss(t,ro(e.commands),e.info.bin);return wl({command:n,path:`${e.info.bin} ${t}`,tokens:r})}function wl(e){let{command:t,path:r,tokens:n}=e;if(t.subcommands.length===0)return e;let s=n.findIndex((a)=>!Lf.test(a)),i=n[s];if(i===void 0||i.startsWith("-"))return e;let o=t.subcommands.find((a)=>a.name===i);if(o)return wl({command:o,path:`${r} ${i}`,tokens:n.toSpliced(s,1)});if(t.run&&Object.keys(t.positionals).length>0)return e;return ss(i,ro(t.subcommands),r)}async function Bf(e,{command:t,path:r,tokens:n},s,i){let o=`Run "${r} --help" for usage.`,a={...t.args,...Kt},c=Mr(n,a),{args:l}=c,p=[...c.rawPositionals,...s];if(t.strict)An(l,a,o,n);if(i&&!t.json)throw new N(`${r} does not support --json`,o);let m=t.strict?Za(p,t.positionals):void 0;if(m!==void 0)throw new N(`Unexpected argument: ${m}`,o);if(!t.run)return Ze(to(t,r,i)),he;let g=Dn(p,t.positionals),h=Mn(g,t.positionals);if(h)throw new N(h,o);let f=t.prompts&&p.length===0&&jr()&&!i,y={args:_n(l,t.args),interactive:f,json:i,positionals:g},R=as(i);try{return await ls(t,r,cs(e,y,R),R)}catch(S){return pt(S,{json:i&&!R.emitted()})}}var Uf={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",promptMessage:"What would you like to do?"};function no(e){let t=`CLI "${e.name}"`;if(jn(t,e.commands),e.commands.some((n)=>n.name===Tt))throw Error(`${t} cannot define a command named "${Tt}": the framework provides it`);let r={commands:e.commands,config:e.config,info:{bin:e.bin??e.name,description:e.description,name:e.name,version:e.version},interactive:{...Uf,...e.interactive}};return{async main(n=process.argv.slice(2)){lc();let s=Qi(r,n),i=Zc({json:eo(s)}),o=await Zi(r,s);if(i.settle(),o.code===he&&!o.menu)return;await i.exit(o.code)},async run(n=process.argv.slice(2)){return(await Zi(r,Qi(r,n))).code}}}import qe from"fs";import ao from"path";var ke=(e)=>(e.map=(t)=>ke((r)=>t(e(r))),e.or=(t)=>ke((r)=>{try{return e(r)}catch(n){return t(r)}}),e),K=()=>"bad banditype"();var Qt=()=>ke((e)=>e),Le=(e)=>ke((t)=>e.includes(t)?t:K()),us=(e)=>ke((t)=>typeof t===typeof e?t:K()),_=()=>us(""),bl=()=>us(0),er=()=>us(!0);var He=()=>us(),Rl=()=>ke((e)=>e===null?e:K()),tr=(e)=>ke((t)=>t instanceof e?t:K()),dt=(e)=>tr(Object).map((t)=>{let r={};for(let n in t){let s=e(t[n]);s!==void 0&&(r[n]=s)}return r}),Hr=(e)=>tr(Object).map((t)=>{let r={};for(let n in e){let s=e[n](t[n]);s!==void 0&&(r[n]=s)}return r}),nt=(e)=>tr(Object).map((t)=>{let r={...t};for(let n in e){let s=e[n](t[n]);s!==void 0&&(r[n]=s)}return r}),re=(e)=>tr(Array).map((t)=>t.map(e));import rr from"fs";var Vf=".lock",Gf=".break",vl=10,Hf=1e4,qf=5000;function $l(e,t){let r=`${e}${Vf}`,n=crypto.randomUUID();Wf(r,n);try{return t()}finally{Pl(r,n)}}function Wf(e,t){let r=Date.now()+Hf;while(!Sl(e,t)){if(Date.now()>r)throw Error(`timed out waiting for ${e}, which another process holds`);if(so(e))Jf(e,t);else Bun.sleepSync(vl)}}function Pl(e,t){if(zf(e)===t)rr.rmSync(e,{force:!0})}function Jf(e,t){let r=`${e}${Gf}`;if(!Sl(r,t)){if(so(r))rr.rmSync(r,{force:!0});else Bun.sleepSync(vl);return}try{if(so(e))rr.rmSync(e,{force:!0})}finally{Pl(r,t)}}function Sl(e,t){try{return rr.writeFileSync(e,t,{flag:"wx"}),!0}catch(r){if(Cl(r)==="EEXIST")return!1;throw r}}function so(e){let t=rr.statSync(e,{throwIfNoEntry:!1})?.mtimeMs;return t!==void 0&&Date.now()-t>qf}function zf(e){try{return rr.readFileSync(e,"utf8")}catch(t){if(Cl(t)==="ENOENT")return;throw t}}function Cl(e){return e instanceof Error?Reflect.get(e,"code"):void 0}import io from"fs";import _t from"path";var Kf="..",Xf=40;function xl(e){let{root:t}=_t.parse(_t.resolve(e)),r=kl(_t.resolve(e)),n=t,s=0;for(let i=r.shift();i!==void 0;i=r.shift()){if(i===Kf){n=_t.dirname(io.realpathSync(n));continue}let o=_t.join(n,i);if(!io.lstatSync(o,{throwIfNoEntry:!1})?.isSymbolicLink()){n=o;continue}if(s+=1,s>Xf)throw Error(`too many symbolic links in ${e}`);let a=io.readlinkSync(o);if(_t.isAbsolute(a))n=t;r.unshift(...kl(a))}return n}function kl(e){return e.split(_t.sep).filter((t)=>t!==""&&t!==".")}function qr(e,t){JSON.parse(e);let r=JSON.parse(JSON.stringify(t)),n=Yf(e),s=e.match(/^[\t ]+(?=\S)/m)?.[0]??" ",i=e.includes(`\r
|
|
85
92
|
`)?`\r
|
|
86
93
|
`:`
|
|
87
|
-
`,o=/\s/.test(e[
|
|
88
|
-
`));let
|
|
89
|
-
`));let R=(
|
|
90
|
-
`)?S:o}`,
|
|
91
|
-
`))});return`${
|
|
92
|
-
`,p-1)+1,
|
|
93
|
-
`,i+
|
|
94
|
-
`;if(
|
|
95
|
-
`).filter(Boolean)}
|
|
94
|
+
`,o=/\s/.test(e[n.start+1]??"")||n.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 g=Array.isArray(p);if(p===null||typeof p!=="object"||l.value===null||typeof l.value!=="object"||Array.isArray(l.value)!==g)return c(p,l.start,m.includes(`
|
|
95
|
+
`));let h=g?p.map((x,D)=>String(D)):[...new Set([...l.entries.map((x)=>x.key).filter((x)=>Object.hasOwn(p,x)),...Object.keys(p)])];if(h.length===0)return g?"[]":"{}";let f=l.entries[0],y=l.entries.at(-1);if(!f||!y)return c(p,l.start,m.includes(`
|
|
96
|
+
`));let R=(x)=>g?p[Number(x)]:p[x];if(h.length===l.entries.length&&h.every((x,D)=>x===l.entries[D]?.key)){let x=l.start,D="";for(let we of l.entries)D+=e.slice(x,we.node.start)+a(we.node,R(we.key)),x=we.node.end;return D+e.slice(x,l.end)}let S=e.slice(l.start+1,f.start),k=e.slice(y.node.end,l.end-1),ee=l.entries[1],G=ee?e.slice(f.node.end,ee.start):`,${S.includes(`
|
|
97
|
+
`)?S:o}`,L=g?"":e.slice(f.start,f.node.start).match(/:\s*$/)?.[0]??": ",Y=new Map(l.entries.map((x)=>[x.key,x])),H=h.map((x)=>{let D=Y.get(x);if(D)return e.slice(D.start,D.node.start)+a(D.node,R(x));return(g?"":JSON.stringify(x)+L)+c(R(x),f.start,S.includes(`
|
|
98
|
+
`))});return`${g?"[":"{"}${S}${H.join(G)}${k}${g?"]":"}"}`}function c(l,p,m){if(!m)return oo(l,o);let g=e.lastIndexOf(`
|
|
99
|
+
`,p-1)+1,h=e.slice(g,p).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(l,null,s).replaceAll(`
|
|
100
|
+
`,i+h)}return e.slice(0,n.start)+a(n,r)+e.slice(n.end)}function oo(e,t){if(Array.isArray(e))return`[${e.map((s)=>oo(s,t)).join(`,${t}`)}]`;if(e===null||typeof e!=="object")return JSON.stringify(e);let r=Object.entries(e);if(r.length===0)return"{}";let n=r.map(([s,i])=>`${JSON.stringify(s)}:${t}${oo(i,t)}`);return`{${t}${n.join(`,${t}`)}${t}}`}function Yf(e){let t=e.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),r=t.next().value;function n(){if(!r)throw Error("Unexpected end of JSON");let i=r;return r=t.next().value,i}function s(){let i=n(),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(n()[0]):String(o.length);if(a)n();if(o.push({key:m,node:s(),start:p}),r?.[0]===",")n()}let l=n().index+1;return{end:l,entries:o,start:i.index,value:JSON.parse(e.slice(i.index,l))}}return s()}var Zf=2,co="ConfigError",Qf=tr(Object);class lo{loaded;configPath;defaultConfig;options;constructor(e,t,r={}){this.configPath=ao.resolve(e),this.defaultConfig=t,this.options=r}get path(){return this.configPath}get failure(){return this.state().failure}get(e){return this.current()[e]}set(e,t){let r=this.writable();this.update((n)=>({...n,[e]:t})),r.config={...r.config,[e]:t}}delete(e){let t=this.writable();this.update((r)=>(delete r[e],r)),delete t.config[e]}exists(){return qe.existsSync(this.configPath)}getAll(){return structuredClone(this.current())}save(e){let t=this.writable();if(e)t.config={...e};this.update(()=>t.config)}state(){return this.loaded??=this.load(),this.loaded}current(){let{config:e,failure:t}=this.state();if(t)throw t;return e}writable(){let e=this.state();if(e.failure)throw e.failure;if(e.error)throw this.unreadable(e.error);return e}unreadable(e){return new u(`Cannot overwrite unreadable config at ${this.configPath}`,"Repair the file and try again",void 0,{cause:e,tag:co})}readStored(){try{let e=this.readConfigFile();if(e===void 0)return structuredClone(this.defaultConfig);return Ot(structuredClone(this.defaultConfig),El(e))}catch(e){throw this.unreadable(e)}}update(e){try{let t=this.savePath();$l(t,()=>this.write(t,e(this.readStored())))}catch(t){throw t instanceof u?t:this.saveFailure(t)}}savePath(){let e=this.exists()?qe.realpathSync(this.configPath):xl(this.configPath);return qe.mkdirSync(ao.dirname(e),{recursive:!0}),e}write(e,t){let r=`${e}.${crypto.randomUUID()}.tmp`;try{let n=this.exists()?qe.statSync(this.configPath).mode:void 0,s=this.exists()?qr(qe.readFileSync(this.configPath,"utf-8"),t):`${JSON.stringify(t,null,Zf)}
|
|
101
|
+
`;if(qe.writeFileSync(r,s,{flag:"wx",mode:n}),n!==void 0)qe.chmodSync(r,n);qe.renameSync(r,e)}finally{qe.rmSync(r,{force:!0})}}saveFailure(e){return new u(`Cannot save config at ${this.configPath}: ${Tl(e)}`,`Check that ${ao.dirname(this.configPath)} is writable and that no other process is saving the file`,void 0,{cause:e,tag:co})}load(){let{parse:e,strict:t}=this.options;try{let r=this.readConfigFile();if(r===void 0)return{config:structuredClone(this.defaultConfig)};let n=Ot(structuredClone(this.defaultConfig),El(r));return{config:e?e(n):n}}catch(r){if(t)return{config:structuredClone(this.defaultConfig),failure:this.loadFailure(r)};return v.warn(d.yellow(`Config file corrupted at ${this.configPath}. Using defaults.`),{output:Un()}),{config:structuredClone(this.defaultConfig),error:r}}}loadFailure(e){return new u(`Cannot read config at ${this.configPath}: ${Tl(e)}`,"Repair the file and try again",void 0,{cause:e,tag:co})}readConfigFile(){try{return qe.readFileSync(this.configPath,"utf-8")}catch(e){if(e.code==="ENOENT")return;throw e}}}function El(e){let t=JSON.parse(e);if(Array.isArray(t))throw Error("Config must be an object");return Qf(t)}function Tl(e){return e instanceof Error?e.message:String(e)}var Il="0.14.0";var T="sis",uo="\uD83E\uDEA8",mt="other",nr={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},sr=50,ir=".sisyphus",Al="stones",Ol="released",ps=7;var Wr="unknown",_l="0.0.0",ye="latest",po=["bun","run","build"],Lt="main",Ll=4,Dl=8,ds="config.json";var gt={$schema:"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/sisyphus/schema.json",changelog:{append:!1,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:[...po],outputs:[],root:[]},createRelease:!1,npm:!1,npmVisibilityTimeout:0,push:!1,tags:!1},scripts:{post:{},pre:{}},single:!1,sisyphusDir:".sisyphus",stones:[],tag:"latest"};var M=Nn();import{existsSync as Ph}from"fs";import{mkdir as Sh,writeFile as Ch}from"fs/promises";import{dirname as kh}from"path";var We="ProviderRequestFailed",ft={bitbucket:"bitbucket.org",github:"github.com",gitlab:"gitlab.com"};function Je(e){return e.host??ft[e.provider]}class ht{owner;repo;remote;constructor(e){this.owner=e.owner,this.repo=e.repo,this.remote=e}get host(){return Je(this.remote)}}class ms extends ht{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 th=200,rh=404,nh=10,sh=3000,Ml=_().map((e)=>e.length>0?e:K()),ih=re(re(Hr({filename:Ml,previous_filename:Ml.or(He()),status:_()}).map((e)=>e.status==="renamed"&&e.previous_filename===void 0?K():e)));function oh(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 gs extends ht{name="github";get apiPath(){return`repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}`}get repository(){return this.isPublicHost?`${this.owner}/${this.repo}`:`${this.host}/${this.owner}/${this.repo}`}get hostArgs(){return this.isPublicHost?[]:["--hostname",this.host]}get isPublicHost(){return this.host===ft.github}async gh(e,t){try{return(await t()).stdout.toString()}catch(r){let n=r&&typeof r==="object"&&"stderr"in r?String(r.stderr).trim():"";throw new u(`Failed to ${e} on ${this.repository}: ${n||r}`,"Check gh access and retry",1,{cause:r,tag:We})}}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 --hostname ${this.host}`)}try{await Bun.$`gh auth status --hostname ${this.host}`.env({...process.env,GH_HOST:this.host}).quiet()}catch{throw new u(`GitHub CLI (gh) is not authenticated for ${this.host}`,`Run: gh auth login --hostname ${this.host}`)}}async getDefaultBranch(){return(await this.gh("read the default branch",()=>Bun.$`gh api ${this.apiPath} ${this.hostArgs} --jq .default_branch`.quiet())).trim()||Lt}async findPr(e){let t=[];if(e.head)t.push("--head",e.head);if(e.label)t.push("--label",e.label);let r=await this.gh("list pull requests",()=>Bun.$`gh pr list --repo ${this.repository} --json number,url,title,body,labels,author,headRefName,baseRefName,mergeCommit,state --limit 1 ${t}`.quiet()),[n]=JSON.parse(r);return n?this.mapPrResponse(n):null}async createPr(e){let t=await this.gh("create a pull request",()=>Bun.$`gh api ${this.apiPath}/pulls ${this.hostArgs} --method POST -f head=${e.head} -f base=${e.base} -f title=${e.title} -f body=${e.body}`.quiet()),r=JSON.parse(t).number;if(e.labels&&e.labels.length>0){let n=e.labels.flatMap((s)=>["-f",`labels[]=${s}`]);await this.gh(`label pull request #${r}`,()=>Bun.$`gh api ${this.apiPath}/issues/${r}/labels ${this.hostArgs} --method POST ${n}`.quiet())}return this.getPr(r)}async updatePr(e,t){let r=[];if(t.title)r.push("--title",t.title);if(t.body)r.push("--body",t.body);await this.gh(`update pull request #${e}`,()=>Bun.$`gh pr edit ${e} --repo ${this.repository} ${r}`.quiet())}async getPr(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e} ${this.hostArgs}`.quiet(),r=JSON.parse(t.stdout.toString());return this.mapRestApiResponse(r)}catch(t){throw new u(`Failed to fetch PR #${e}`,"Make sure the PR exists and you have access",1,{cause:t,tag:We})}}async getPrFromCurrentBranch(){try{let e=(await Bun.$`git rev-parse --abbrev-ref HEAD`.quiet()).stdout.toString().trim(),t=await Bun.$`gh pr view ${e} --repo ${this.repository} --json number,title,body,labels,author,headRefName,baseRefName,url,mergeCommit,state`.quiet(),r=JSON.parse(t.stdout.toString());return this.mapPrResponse(r)}catch(e){throw new u("No PR found for current branch","Make sure you have an open PR or provide a URL with --url",1,{cause:e,tag:We})}}async getPrCommits(e){return(await this.gh(`fetch PR #${e} commits`,()=>Bun.$`gh api ${this.apiPath}/pulls/${e}/commits ${this.hostArgs} --paginate --jq '.[].sha'`.quiet())).trim().split(`
|
|
102
|
+
`).filter(Boolean)}async getPrFiles(e){let t=await this.gh(`fetch PR #${e} files`,()=>Bun.$`gh api ${this.apiPath}/pulls/${e}/files ${this.hostArgs} --paginate --slurp`.quiet()),r=this.parsePrFiles(e,t);if(r.length>=sh)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((n)=>n.status==="renamed"&&n.previous_filename!==void 0?[n.previous_filename,n.filename]:[n.filename]))]}parsePrFiles(e,t){try{return ih(JSON.parse(t)).flat()}catch(r){throw new u(`Failed to fetch PR #${e} files on ${this.repository}: unexpected gh api response`,"Check GitHub access and retry the analysis",1,{cause:r,tag:We})}}async ensureLabelExists(e,t){try{let r=t?.description??"",n=t?.color?["--color",t.color]:[];await Bun.$`gh label create ${e} --repo ${this.repository} --description ${r} ${n} --force`.quiet()}catch{}}async getRelease(e){let t=`${this.apiPath}/releases/tags/${encodeURIComponent(e)}`,r=await Bun.$`gh api ${t} ${this.hostArgs} --include`.quiet().nothrow(),n=r.stdout.toString().replaceAll(`\r
|
|
96
103
|
`,`
|
|
97
|
-
`),[
|
|
98
|
-
|
|
99
|
-
`),o=
|
|
100
|
-
|
|
101
|
-
`))}catch{throw this.releaseReadError(e,"response was not valid JSON")}if(!Eu(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 Iu="https://gitlab.com/api/v4",Au=404,No=ve().map((e)=>e.length>0?e:de()),Ou=Gt({changes:Ze(Gt({new_path:No,old_path:No})),overflow:ko()});class Br extends Ve{name="gitlab";authHeader={};apiUrl;projectPath;constructor(e){super(e);this.apiUrl=process.env.CI_API_V4_URL??Iu,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=Ou(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(!_u(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===Au)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 _u(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 Lu={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 jo();if(!t)throw new u("Could not detect git provider","Make sure you have a git remote configured (origin)");let r=Mu(t);return await r.ensureAvailable(),r}function Mu(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 jo(){let e=await Wt();if(!e)return null;return et(e)}async function Fo(){let e=await jo();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=Du(e);if(!t)return null;let r=Bo(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 Du(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 Bo(e){if(e==="github.com")return"github";if(e==="gitlab.com")return"gitlab";if(e==="bitbucket.org")return"bitbucket";return null}function Vo(e){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")return null;let r=Bo(t.hostname.toLowerCase());if(!r)return null;let s=t.pathname.match(Lu[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 Uo}from"fs";import{readFile as Nu}from"fs/promises";import{dirname as ju,join as nn}from"path";import{fileURLToPath as Fu}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"}},Bu=nn(ju(Fu(import.meta.url)),"templates"),Go={"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)=>Uo(t))}async readTemplate(e){let t=nn(Bu,this.provider,Go[e]);return Nu(t,"utf-8")}}class Ur extends on{provider="github";outputDir=".github/workflows";getOutputPath(e){return nn(this.outputDir,Go[e])}}var Jt=".gitlab-ci-sisyphus.yml";class Gr extends on{provider="gitlab";outputDir=".";async generate(e){let t=[];t.push(`stages:
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
${
|
|
110
|
-
`)
|
|
111
|
-
|
|
112
|
-
`),
|
|
113
|
-
${
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
`)
|
|
118
|
-
|
|
119
|
-
${t}${i
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
`)[0]??""
|
|
124
|
-
`);if(!(
|
|
125
|
-
`).trim()}formatEntry(e,t,r){let
|
|
126
|
-
`)}formatRootEntry(e,t){let
|
|
127
|
-
`)}formatPackageHeader(e){let t=e.newVersion??e.version,r=this.getDate(),
|
|
104
|
+
`),[s="",...i]=n.split(`
|
|
105
|
+
|
|
106
|
+
`),o=s.match(/^HTTP\/\S+\s+(\d{3})\b/m)?.[1],a=o?Number.parseInt(o,nh):null;if(r.exitCode!==0){if(a===rh)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!==th)throw this.releaseReadError(e,a?`GitHub API returned HTTP ${a}`:"missing HTTP status");let c;try{c=JSON.parse(i.join(`
|
|
107
|
+
|
|
108
|
+
`))}catch{throw this.releaseReadError(e,"response was not valid JSON")}if(!oh(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){let t=e.prerelease?["--prerelease"]:[];await this.gh(`create release ${e.tag}`,()=>Bun.$`gh release create ${e.tag} --repo ${this.repository} --title ${e.title} --notes ${e.notes} --verify-tag ${t}`.quiet())}async deleteRelease(e){try{await Bun.$`gh release delete ${e} --repo ${this.repository} --yes`.quiet()}catch{}}mapRestApiResponse(e){return{author:e.user?.login??Wr,baseBranch:e.base?.ref??Lt,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??Wr,baseBranch:e.baseRefName??Lt,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 ah=404,ch=/Token found:\s*(\S+)/,Nl=_().map((e)=>e.length>0?e:K()),lh=Hr({changes:re(Hr({new_path:Nl,old_path:Nl})),overflow:er()});class fs extends ht{name="gitlab";authHeader={};apiUrl;projectPath;constructor(e){super(e);this.apiUrl=e.apiUrl??process.env.CI_API_V4_URL??`https://${Je(e)}/api/v4`,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||Lt}catch(e){throw this.requestFailed("read the default branch",e)}}async findPr(e){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;try{r=await this.api(`/projects/${this.projectPath}/merge_requests?${t}`)}catch(s){throw this.requestFailed("list merge requests",s)}let[n]=r;return n?this.mapMrResponse(n):null}requestFailed(e,t){let r=t instanceof Error?t.message:String(t);return new u(`Failed to ${e} on ${this.owner}/${this.repo}: ${r}`,"Check GitLab access and retry",1,{cause:t,tag:We})}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"}),n=await this.api(`/projects/${this.projectPath}/merge_requests?${r}`);if(!n[0])throw Error("No MR found");return this.mapMrResponse(n[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=lh(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(!uh(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};let e=await this.readGlabToken(new URL(this.apiUrl).hostname);if(e)return{Authorization:`Bearer ${e}`};throw new u("GitLab token not found","Set GITLAB_TOKEN environment variable or install glab CLI and run: glab auth login")}async readGlabToken(e){try{let t=await Bun.$`glab auth status --hostname ${e} --show-token`.quiet().nothrow();if(t.exitCode!==0)return;return(t.stdout.toString()+t.stderr.toString()).match(ch)?.[1]}catch{return}}async api(e,t,r=!1){let n=await fetch(`${this.apiUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...this.authHeader,...t?.headers}});if(r&&n.status===ah)return;if(!n.ok){let s=await n.text().catch(()=>"");throw Error(`GitLab API error: ${n.status} ${n.statusText}${s?` \u2014 ${s}`:""}`)}return n.json()}mapMrResponse(e){return{author:e.author?.username??Wr,baseBranch:e.target_branch??Lt,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 uh(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 jl="ProviderNotDetected",ph={github:/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/|$)/,gitlab:/^\/(.+)\/([^/]+)\/-\/merge_requests\/([1-9]\d*)(?:\/|$)/,bitbucket:/^\/([^/]+)\/([^/]+)\/pull-requests\/([1-9]\d*)(?:\/|$)/},Fl=new Set(["http:","https:"]),dh="://",mh=/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/,gh='Set "provider": { "type": "github" or "gitlab", "host": "<web host>" } in .sisyphus/config.json for GitHub Enterprise, self-managed GitLab or an SSH host alias';async function yt(e,t){let r=e?hh(e,t):await Bl(t),n=fh(r);return await n.ensureAvailable(),n}function fh(e){switch(e.provider){case"github":return new gs(e);case"gitlab":return new fs(e);case"bitbucket":return new ms(e);default:throw new u(`Unsupported provider: ${e.provider}`)}}function hh(e,t){if(t?.type!==e.provider)return e;let r=e.host??t.host,n=e.apiUrl??t.apiUrl;return{...e,...r?{host:r}:{},...n?{apiUrl:n}:{}}}async function hs(e){let t=await Vl();return t?Jr(t,e):null}async function Bl(e){let t=await Vl();if(!t)throw new u("Could not detect git provider","Make sure you have a git remote configured (origin)",1,{tag:jl});let r=Jr(t,e);if(r)return r;let n=Gl(t)?.hostname;throw new u(n?`Could not detect the git provider for origin host ${n}`:"Could not parse the origin remote URL",gh,1,{tag:jl})}async function Ul(e){return(await Bl(e)).provider}async function Vl(){try{return(await Bun.$`git remote get-url origin`.quiet()).stdout.toString().trim()||null}catch{return null}}function Jr(e,t){let r=Gl(e);if(!r)return null;let n=t?.type??Hl(r.hostname)??yh(r.hostname);if(!n)return null;let s=r.path.replace(/^\/+|\/+$/g,"").replace(/\.git$/,"").split("/").filter(Boolean),i=s.pop();if(!i||s.length===0)return null;if(n!=="gitlab"&&s.length!==1)return null;let o=t?.apiUrl;return{host:t?.host??r.webHost,owner:s.join("/"),provider:n,repo:i,...o?{apiUrl:o}:{}}}function Gl(e){if(e.includes(dh)){let s=URL.parse(e);if(!s?.hostname)return null;let i=s.hostname.toLowerCase(),o=Fl.has(s.protocol)?s.host.toLowerCase():i;return{hostname:i,path:s.pathname,webHost:o}}let t=e.match(mh),r=t?.[1]?.toLowerCase(),n=t?.[2];return r&&n?{hostname:r,path:n,webHost:r}:null}function Hl(e){if(e===ft.github)return"github";if(e===ft.gitlab)return"gitlab";if(e===ft.bitbucket)return"bitbucket";return null}function yh(e){if(process.env.CI_SERVER_HOST?.toLowerCase()===e)return"gitlab";return(process.env.GITHUB_SERVER_URL?URL.parse(process.env.GITHUB_SERVER_URL):null)?.hostname.toLowerCase()===e?"github":null}function ql(e,t){let r=URL.parse(e);if(!r||!Fl.has(r.protocol))return null;let n=r.host.toLowerCase(),s=t&&n===Je(t)?t.provider:Hl(r.hostname.toLowerCase());if(!s)return null;let[,i,o,a]=r.pathname.match(ph[s])??[],c=Number(a);if(!i||!o||!Number.isSafeInteger(c))return null;return{host:n,number:c,owner:i,provider:s,repo:o}}import{existsSync as Wl}from"fs";import{readFile as wh}from"fs/promises";import{dirname as bh,join as mo}from"path";import{fileURLToPath as Rh}from"url";var ys={"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"}},vh=mo(bh(Rh(import.meta.url)),"templates"),$h="__SISYPHUS_VERSION__",Jl={"create-stone":"sis-create-stone.yml",release:"sis-release.yml"};class go{sisyphusVersion;constructor(e){this.sisyphusVersion=e}async generate(e){let t=[];for(let r of e){let n=await this.readTemplate(r),s=this.getOutputPath(r);t.push({content:n,path:s})}return t}getExistingFiles(e){return e.map((t)=>this.getOutputPath(t)).filter((t)=>Wl(t))}async readTemplate(e){let t=mo(vh,this.provider,Jl[e]);return(await wh(t,"utf-8")).replaceAll($h,this.sisyphusVersion)}}class ws extends go{provider="github";outputDir=".github/workflows";getOutputPath(e){return mo(this.outputDir,Jl[e])}}var zr=".gitlab-ci-sisyphus.yml",bs="sisyphus";class Rs extends go{provider="gitlab";outputDir=".";async generate(e){let t=[];for(let r of e){let n=await this.readTemplate(r);t.push(n)}return[{content:t.join(`
|
|
109
|
+
`),path:zr}]}getExistingFiles(e){return Wl(zr)?[zr]:[]}getIncludeInstruction(){return`stages:
|
|
110
|
+
- build
|
|
111
|
+
- test
|
|
112
|
+
- deploy
|
|
113
|
+
- ${bs}
|
|
114
|
+
|
|
115
|
+
include:
|
|
116
|
+
- local: '${zr}'`}getOutputPath(e){return zr}}function zl(e,t){switch(e){case"github":return new ws(t);case"gitlab":return new Rs(t);default:throw Error(`CI generation is not supported for ${e}`)}}var xh={bitbucket:"Bitbucket Pipelines",github:"GitHub Actions",gitlab:"GitLab CI"},Eh=q({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:"Overwrite existing workflows without asking",type:"boolean"}}),Kl=M({name:"init",description:"Set up CI workflows for automated releases",args:Eh,prompts:!0,json:!0,examples:["sis actions init --all --dry-run","sis actions init --all --yes"],run:async(e)=>{let t=e.cli.version;if(!t)throw Error("The Sisyphus version is required to pin generated workflows");let r=await Ul(e.config.get("provider")),n=zl(r,t);v.info(`Detected ${d.bold(xh[r])} repository
|
|
117
|
+
`);let s=await Ah(e);if(s.length===0){v.info(d.dim("No workflows selected")),e.output.result({dryRun:e.args.dryRun,files:[],nextSteps:[],provider:r,sisyphusVersion:t});return}let i=n.getExistingFiles(s),o=(await n.generate(s)).map((c)=>({...c,exists:i.includes(c.path)})),a={dryRun:e.args.dryRun,files:o,nextSteps:Ih(n),provider:r,sisyphusVersion:t};if(e.args.dryRun){for(let c of o)v.info(`
|
|
118
|
+
${d.bold(c.path)}${c.exists?d.yellow(" (would overwrite)"):""}:`),v.info(d.dim(c.content));e.output.result(a);return}if(i.length>0&&!e.args.yes&&!await Th(e,i))return;for(let c of o){let l=kh(c.path);if(l!=="."&&!Ph(l))await Sh(l,{recursive:!0});await Ch(c.path,c.content,"utf-8")}te(o.map((c)=>` ${d.green("+")} ${c.path}`).join(`
|
|
119
|
+
`),d.green("CI workflows created")),v.info(`Workflows install ${d.bold(`@r5n/sisyphus@${t}`)}; run this command again to upgrade.`);for(let c of a.nextSteps)v.info(c);e.output.result(a)}});async function Th(e,t){if(!e.interactive)throw new u(`Workflows already exist: ${t.join(", ")}`,"Use --yes to overwrite existing workflows, or --dry-run to preview them",1,{tag:"WorkflowsExist"});return v.warn(`The following files already exist:
|
|
120
|
+
${t.map((r)=>` ${r}`).join(`
|
|
121
|
+
`)}`),V({initialValue:!1,message:"Overwrite existing files?"})}function Ih(e){if(e instanceof Rs)return[`Add the include and the ${bs} stage to your .gitlab-ci.yml (append ${bs} to an existing stages list):
|
|
122
|
+
${e.getIncludeInstruction()}`,"Add a GITLAB_TOKEN CI/CD variable (Personal Access Token with api + write_repository scopes); it is required for creating release merge requests. Settings \u2192 CI/CD \u2192 Variables","Commit and push these files to enable the workflows."];if(e instanceof ws)return['Enable "Allow GitHub Actions to create and approve pull requests" in Settings \u2192 Actions \u2192 General \u2192 Workflow permissions.',"Commit and push these files to enable the workflows."];return["Commit and push these files to enable the workflows."]}async function Ah(e){let t=Oh(e);if(t.length>0)return t;if(!e.interactive)throw new u("No workflows specified","Use --all or specify workflows with --create-stone, --release");return tt({initialValues:Object.keys(ys),message:"Select workflows to create",options:Object.entries(ys).map(([r,n])=>({hint:n.description,label:n.name,value:r})),required:!1})}function Oh(e){if(e.args.all)return Object.keys(ys);let t=[];if(e.args.createStone)t.push("create-stone");if(e.args.release)t.push("release");return t}import{readdir as Sv,rm as Cv,rmdir as kv}from"fs/promises";import{dirname as Dd,join as Md}from"path";var Xl={["major"]:5,["minor"]:4,["patch"]:3,["dependency"]:2,["snapshot"]:1},or={["major"]:"\uD83D\uDEA8",["minor"]:"\u2728",["patch"]:"\uD83D\uDC1B",["dependency"]:"\uD83D\uDCE6",["snapshot"]:"\uD83D\uDCF8"},ar={["major"]:d.red,["minor"]:d.yellow,["patch"]:d.green,["dependency"]:d.blue,["snapshot"]:d.magenta},st=["major","minor","patch","dependency","snapshot"];function cr(e,t){return Xl[e]>=Xl[t]?e:t}var Yl=/^(\w+)(?:\(([^)]+)\))?(!)?: (.+)$/,_h=/^BREAKING(?: CHANGE|-CHANGE):[\t ]+\S/m,Lh="%x00%H%x00%s%x00%an%x00%b",Zl=4,Ql=`
|
|
123
|
+
`,Dh=new Set(["build","chore","ci","docs","feat","fix","perf","refactor","style","test"]);class Z{hash;subject;author;body;type;scope;breaking;message;files;constructor(e){let[,,,t]=e.subject.match(Yl)??[];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||_h.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 Z.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 Z.fetchFromRange("HEAD")}static async inRange(e,t){let r=[`origin/${e}..origin/${t}`,`${e}..${t}`];for(let n of r){let s=await Z.tryFetchFromRange(n);if(s)return s}throw new u(`Commits between ${e} and ${t} are not available locally`,`Run: git fetch origin ${e} ${t}`)}static async fromHash(e){try{let[t]=await Z.readCommits(["-1",e]);return t??null}catch{return null}}static async fromMerge(e){let t=await Bun.$`git rev-parse --verify --quiet ${`${e}^2`}`.quiet().nothrow(),r=t.exitCode===0?t.stdout.toString().trim():"";if(!r)return[];try{return await Z.fetchFromRange(`${e}^1..${r}`)}catch(n){throw new u(`Failed to read the commits merged by ${e}`,"Run: git fetch --unshallow",1,{cause:n})}}static async tryFetchFromRange(e){try{return await Z.fetchFromRange(e)}catch{return null}}static async fetchFromRange(e){return Z.readCommits([e,"--no-merges"])}static async readCommits(e){let r=(await Bun.$`git log ${e} -z --format=${Lh} --name-only --root`.quiet()).stdout.toString().split("\x00"),n=[],s=0;while(s<r.length){s++;let[i,o,a,c]=r.slice(s,s+Zl);s+=Zl;let l=[];while(s<r.length&&r[s]!==""){let p=r[s++];if(p===void 0)continue;l.push(l.length===0&&p.startsWith(Ql)?p.slice(Ql.length):p)}if(!i||!o||!a)continue;n.push(Z.parse(i,o,a).withFiles(l).withBody(c?.trim()||void 0))}return n}static parse(e,t,r){let n=t.match(Yl);if(n){let[,s="",i,,o=""]=n,a=s.toLowerCase();if(a&&Dh.has(a))return new Z({author:r,files:[],hash:e,message:o,scope:i,subject:t,type:a})}return new Z({author:r,files:[],hash:e,message:t,subject:t,type:mt})}get shortHash(){return this.hash.slice(0,ps)}withFiles(e){return new Z({...this.toOptions(),files:e})}withBody(e){return new Z({...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 X=(e)=>e.length>0?e:void 0;var Mh=/^[A-Za-z][0-9A-Za-z]*$/,Nh=_().map((e)=>Mh.test(e)?e:K());function Dt(e,t="Invalid prerelease tag"){try{return Nh(e)}catch{throw new u(t,"Start with a letter and use only letters or numbers")}}var jh=/^(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-]+)*))?$/,Fh=/^(0|[1-9]\d*)$/,eu=10,fo=1,Bh=2;function De(e){let t=jh.exec(e);if(!t)return null;let[,r="0",n="0",s="0",i,o]=t,a=[r,n,s].map((l)=>Number.parseInt(l,eu)),c=i?i.split(".").map(Uh):[];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 vs(e,t){let r=De(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 $s(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 Me(e){return e.prerelease.length>0}function tu(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}function ru(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 Vh(e.prerelease,t.prerelease)}function nu(e,t){let r=Me(e);if(t==="major"){let n=r&&e.minor===0&&e.patch===0;return ho(n?e.major:e.major+fo,0,0)}if(t==="minor"){let n=r&&e.patch===0;return ho(e.major,n?e.minor:e.minor+fo,0)}return ho(e.major,e.minor,r?e.patch:e.patch+fo)}function Ps(e,t,r){return{...e,build:[],prerelease:[t,r]}}function Kr(e){return iu(e)?.tag}function su(e){return iu(e)?.counter}function iu(e){if(e.prerelease.length!==Bh)return;let[t,r]=e.prerelease;if(typeof t!=="string"||typeof r!=="number")return;return{counter:r,tag:t}}function ho(e,t,r){return{build:[],major:e,minor:t,patch:r,prerelease:[]}}function Uh(e){return Fh.test(e)?Number.parseInt(e,eu):e}function Vh(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 n=0;n<r;n+=1){let s=e[n],i=t[n];if(s===void 0)return-1;if(i===void 0)return 1;if(s===i)continue;let o=typeof s==="number",a=typeof i==="number";if(o&&a)return s<i?-1:1;if(o)return-1;if(a)return 1;return s<i?-1:1}return 0}var Gh=1,ou=0,Hh=/[.ZT:-]/g,qh=14,Wh="0.0.0",Jh=/^0\.0\.0-[0-9A-Za-z.-]+-\d{14,}$/,zh="nightly",Kh={dependency:"patch",major:"major",minor:"minor",patch:"patch"};class xe{static bump(e,t,r,n=!1){if(r!==void 0)Dt(r);if(t==="snapshot")return xe.formatSnapshot(r);let s=`apply a ${t} bump`,i=Kh[t];if(!i)throw new u(`Unknown bump type "${t}"`,"Use major, minor, patch, dependency, or snapshot");if(xe.isSnapshotVersion(e))throw new u(`Cannot ${s} to snapshot version ${e}`,"Restore the package version from its last real release before releasing it again");let o=vs(e,s),a=xe.resolveTag(o,t,r,n),c=nu(o,i),l=a===void 0?c:xe.applyPrerelease(c,o,a,e);if(ru(l,o)<=0)throw new u(`A ${t} bump would move ${e} to ${$s(l)}, which is not a later version`,"Prerelease tags must increase in semver precedence (alpha < beta < rc)");return $s(l)}static formatLabel(e,t,r,n,s){let i=s??xe.bump(t,r,n),o=or[r];return`${e}@${t} => ${i} ${o}`}static isSnapshotVersion(e){return Jh.test(e)}static resolveTag(e,t,r,n){if(r!==void 0)return r;if(n||t!=="dependency")return;let s=Kr(e);if(s===void 0&&Me(e))throw new u(`Cannot continue the prerelease of ${$s(e)}`,"Set the package version to a <tag>.<number> prerelease, or roll a graduating release to leave the channel");return s}static applyPrerelease(e,t,r,n){if(Dt(r),!tu(e,t))return Ps(e,r,ou);let s=su(t);if(Kr(t)===r&&s!==void 0)return Ps(e,r,s+Gh);if(t.prerelease[0]===r){let i=`${e.major}.${e.minor}.${e.patch}`;throw new u(`Cannot continue the "${r}" prerelease from ${n}`,`Set the package version to ${i}-${r}.<number> first`)}return Ps(e,r,ou)}static formatSnapshot(e){let t=new Date().toISOString().replace(Hh,"").slice(0,qh);return`${Wh}-${e||zh}-${t}`}}var Xh={build:[],major:0,minor:0,patch:0,prerelease:[]},Ss="workspace:",Cs=["dependencies","devDependencies","optionalDependencies","peerDependencies"];function Yh(e){let t=[];for(let r of Cs)for(let[n,s]of Object.entries(e[r]??{})){if(!s?.startsWith(Ss))continue;t.push({kind:r,name:n,specifier:s})}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||_l,workspaceDependencies:Yh(e)})}static applyStone(e,t,r=Cs){let n=[],s=new Set,i=z.graduatingPackages(e,t,new Set(r));for(let o of st)for(let a of e.getPackages(o)){let c=t.get(a);if(!c||s.has(a))continue;s.add(a),n.push(c.withBump(o,e.tag,i.has(a)))}return n}static graduatingPackages(e,t,r){let n=new Set;if(e.tag!==void 0)return n;let s=st.filter((a)=>a!=="dependency"&&a!=="snapshot");for(let a of s)for(let c of e.getPackages(a))if(z.isPrereleaseVersion(t.get(c)?.version))n.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(n.has(a.name))continue;if(!a.workspaceDependencies.some((c)=>r.has(c.kind)&&n.has(c.name)))continue;n.add(a.name),o=!0}}return n}static isPrereleaseVersion(e){return e!==void 0&&Me(De(e)??Xh)}get newVersion(){if(this._newVersion)return this._newVersion;if(!this.bump)return;return xe.bump(this.version,this.bump,this.tag)}get label(){if(!this.bump)return`${this.name}@${this.version}`;return xe.formatLabel(this.name,this.version,this.bump,this.tag,this._newVersion)}withBump(e,t,r=!1){return new z({...this.toOptions(),bump:e,newVersion:xe.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 Zh}from"crypto";var au=re(_()),Qh=_().map((e)=>e.trim().length>0?e:K()),wo=_().or(He()),ey=re(nt({body:wo,hash:_().map((e)=>e.length>0?e:K()),message:_(),packages:au,scope:wo,subject:_(),type:_()})).or(He());function yo(e,t,r,n,s){try{return n(s)}catch{throw new u(`Invalid ${t} in stone ${e}`,`Expected ${r}`)}}class O{id;message;tag;description;commits;_packages;constructor(e){this.id=e.id,this.message=e.message,this.tag=e.tag===void 0?void 0:Dt(e.tag),this.description=e.description,this.commits=e.commits,this._packages=e.packages}static create(e,t=0){let r=O.generateId(t);return O.fromData(r,e)}static fromJson(e){return O.fromData(e.id,e)}static mergeAll(e){if(e.length===0)throw Error("No stones to merge");let t=e.map((s)=>s.message).join("; "),{stone:r,errors:n}=O.merge(e,t);if(n.length>0)throw new u("Pending stones conflict and cannot be released together",n.join(`
|
|
124
|
+
`));return r}static merge(e,t){let r=new Map,n=[],s=[];for(let m of e)for(let g of st)O.collectBumps(m,g,r,n,s);let i=O.categorizeBumps(r),o=e.map((m)=>m.description).filter(Boolean).join(`
|
|
125
|
+
|
|
126
|
+
`),a=O.mergeCommits(e),c=O.resolveTag(e,s),l=`merged-${Date.now()}`,p=new O({commits:a.length>0?a:void 0,description:o||void 0,id:l,message:t,packages:i,tag:c});return{conflicts:[...new Set(n)],errors:[...new Set(s)],stone:p}}static resolveTag(e,t){let r=e.filter((i)=>!i.isEmpty),n=new Map;for(let i of r){if(!i.tag)continue;n.set(i.tag,[...n.get(i.tag)??[],i.id])}if(n.size===0)return;let s=r.filter((i)=>!i.tag).map((i)=>i.id);if(n.size>1||s.length>0){let i=[...n.entries()].map(([o,a])=>`${o}: ${a.join(", ")}`);if(s.length>0)i.push(`no tag: ${s.join(", ")}`);t.push(`Stones disagree on the prerelease tag (${i.join("; ")})`)}return[...n.keys()][0]}static mergeCommits(e){let t=new Map;for(let r of e.flatMap((n)=>n.commits??[])){let n=t.get(r.hash);if(!n){t.set(r.hash,{...r,packages:[...r.packages??[]]});continue}let s=new Set([...n.packages,...r.packages??[]]);t.set(r.hash,{...n,packages:[...s]})}return[...t.values()]}static collectBumps(e,t,r,n,s){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"){s.push(`Package ${i} is requested as both a snapshot and a ${o==="snapshot"?t:o} release`);continue}n.push(i);let a=cr(t,o);if(a!==o)r.set(i,a)}}static categorizeBumps(e){let t=new Map;for(let r of st)t.set(r,[]);for(let[r,n]of e)t.get(n)?.push(r);return t}static fromData(e,t){let r=new Map;for(let n of st){let s=t[n];try{r.set(n,s===void 0?[]:au(s))}catch{throw new u(`Invalid ${n} packages in stone ${e}`,"Each bump field must contain an array of package names")}}return new O({commits:yo(e,"commits","commit records with a packages array",ey,t.commits),description:yo(e,"description","a string",wo,t.description),id:e,message:yo(e,"message","a non-empty string",Qh,t.message),packages:r,tag:t.tag})}static generateId(e){let t=String(e+1).padStart(Ll,"0"),r=Zh().slice(0,Dl);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 O({...this.toOptions(),message:e})}withPackages(e,t){let r=new Map(this._packages);return r.set(e,t),new O({...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:X(this.dependency),description:this.description,id:this.id,major:X(this.major),message:this.message,minor:X(this.minor),patch:X(this.patch),snapshot:X(this.snapshot),tag:this.tag}}}import{readFile as ry,rm as ny,writeFile as cu}from"fs/promises";import{dirname as sy,join as iy}from"path";var ty={bitbucket:"commits",github:"commit",gitlab:"-/commit"};function bo(e){let t=`https://${Je(e)}/${e.owner}/${e.repo}`,r=ty[e.provider];return(n)=>`${t}/${r}/${n}`}class Xr{settings;cached=void 0;constructor(e){this.settings=e}async getRemoteInfo(){if(this.cached!==void 0)return this.cached;let e=await hs(this.settings);return this.cached=e?{...e,commitUrl:bo(e)}:null,this.cached}}var oy=/^#\s/,ay=/^#{1,6}\s+\[?v?\d+\.\d+\.\d+/,cy=/\r$/;function lu(e){return oy.test(e)&&!ay.test(e)}function lr(e){return new uu(e.get("changelog"),e.get("dependents").kinds,e.get("provider"))}class uu{dependencyKinds;config;originals=new Map;remoteParser;commitUrlFn=null;constructor(e,t=Cs,r){this.dependencyKinds=t;this.config=e,this.remoteParser=new Xr(r)}async generate(e,t){await this.initCommitLinks();let r=new Map(t.map((n)=>[n.name,n]));for(let n of t){let s=this.filterStonesForPackage(e,n.name),i=this.getBumpedDependencies(n,r);await this.generateForPackage(s,n,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){return[...new Set(e.workspaceDependencies.filter((n)=>this.dependencyKinds.includes(n.kind)).map((n)=>n.name))].map((n)=>t.get(n)).filter((n)=>n?.newVersion!==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 ny(e,{force:!0});else await cu(e,t,"utf-8");this.originals.clear()}async generateForPackage(e,t,r){let n=iy(sy(t.file),this.config.filename),s=this.formatEntry(e,t,r);await this.writeEntry(n,s,t.name)}async generateRoot(e,t){let r=this.config.filename,n=this.formatRootEntry(e,t);await this.writeEntry(r,n,"Changelog")}async writeEntry(e,t,r){let n=await this.readExisting(e);if(!this.originals.has(e))this.originals.set(e,n);let s=n?this.extractTitle(n,r):`# ${r}`,i=n?this.extractRest(n):"",o=this.config.append?[i,t]:[t,i];await cu(e,`${[s,...o.filter(Boolean)].join(`
|
|
127
|
+
|
|
128
|
+
`)}
|
|
129
|
+
`,"utf-8")}async readExisting(e){try{return await ry(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}firstLine(e){return(e.split(`
|
|
130
|
+
`)[0]??"").replace(cy,"")}extractTitle(e,t){let r=this.firstLine(e);return lu(r)?r:`# ${t}`}extractRest(e){let t=e.split(`
|
|
131
|
+
`);if(!lu(this.firstLine(e)))return e.trim();let r=1;while(r<t.length&&t[r]?.trim()==="")r++;return t.slice(r).join(`
|
|
132
|
+
`).trim()}formatEntry(e,t,r){let n=this.formatPackageHeader(t),s=r.length>0,i=[`## ${n}`];for(let o of e)i.push("",`### ${uo} ${o.message}`),i.push("",this.formatStoneContent(o,t.name));if(s){i.push("",`### ${this.config.sections.dependencies}`);for(let o of r)i.push(`- \`${o.name}\` ${o.version} \u2192 ${o.newVersion}`)}return i.join(`
|
|
133
|
+
`)}formatRootEntry(e,t){let n=[`## ${this.formatRootHeader(t)}`];n.push("","**Packages**");for(let s of t){let i=this.getEmoji(s),o=s.newVersion?`${s.version} \u2192 ${s.newVersion}`:s.version;n.push(`- ${i} \`${s.name}\` ${o}`)}for(let s of e)n.push("",`### ${uo} ${s.message}`),n.push(this.formatStonePackages(s)),n.push("",this.formatRootStoneContent(s));return n.join(`
|
|
134
|
+
`)}formatPackageHeader(e){let t=e.newVersion??e.version,r=this.getDate(),n=this.getEmoji(e);return this.config.packageHeader.replace("{emoji}",()=>n).replace("{version}",()=>t).replace("{date}",()=>r)}formatRootHeader(e){let t=this.getDate(),r=e.map((n)=>`${n.name}@${n.newVersion??n.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
135
|
|
|
129
136
|
`)}formatRootCommits(e,t){let r=this.formatCommits(e,t);return`<details>
|
|
130
137
|
<summary>Commits (${e.length})</summary>
|
|
131
138
|
|
|
132
139
|
${r}
|
|
133
140
|
|
|
134
|
-
</details>`}formatStonePackages(e){let t=[...e.major,...e.minor,...e.patch];if(t.length===0)return"";return`**Packages:** ${t.map((
|
|
141
|
+
</details>`}formatStonePackages(e){let t=[...e.major,...e.minor,...e.patch];if(t.length===0)return"";return`**Packages:** ${t.map((n)=>`\`${n}\``).join(" \xB7 ")}`}formatStoneContent(e,t){let r=[];if(e.description)r.push(this.formatDescription(e.description));let n=t&&e.commits?this.filterCommitsForPackage(e.commits,t):e.commits??[];if(n.length>0){let s=!this.isSectionName(e.message);r.push(this.formatCommits(n,s))}return r.join(`
|
|
135
142
|
|
|
136
143
|
`)}isSectionName(e){return Object.values(this.config.sections).includes(e)}formatDescription(e){return`<details>
|
|
137
144
|
<summary>Description</summary>
|
|
138
145
|
|
|
139
146
|
${this.convertHeadersToBold(e).split(`
|
|
140
|
-
`).map((
|
|
147
|
+
`).map((n)=>` ${n}`).join(`
|
|
141
148
|
`)}
|
|
142
|
-
</details>`}convertHeadersToBold(e){return e.replace(/^#{1,6}\s+(.+)$/gm,"**$1**")}getDate(){return new Date().toISOString().split("T")[0]??""}getEmoji(e){return e.bump
|
|
143
|
-
`);let r=this.groupCommitsByType(e),
|
|
144
|
-
`))}return
|
|
149
|
+
</details>`}convertHeadersToBold(e){return e.replace(/^#{1,6}\s+(.+)$/gm,"**$1**")}getDate(){return new Date().toISOString().split("T")[0]??""}getEmoji(e){return e.bump?or[e.bump]:"\uD83D\uDCE6"}filterCommitsForPackage(e,t){return e.filter((r)=>r.packages.includes(t))}formatCommits(e,t){if(!t)return e.map((s)=>this.formatCommitLine(s)).join(`
|
|
150
|
+
`);let r=this.groupCommitsByType(e),n=[];for(let[s,i]of r){let o=this.config.sections[s]??`${s} changes`;n.push(`#### ${o}`),n.push(i.map((a)=>this.formatCommitLine(a)).join(`
|
|
151
|
+
`))}return n.join(`
|
|
145
152
|
|
|
146
|
-
`)}groupCommitsByType(e){let t=new Map;for(let r of e){let
|
|
147
|
-
`).map((
|
|
153
|
+
`)}groupCommitsByType(e){let t=new Map;for(let r of e){let n=t.get(r.type)??[];n.push(r),t.set(r.type,n)}return Array.from(t.entries()).sort(([r],[n])=>(nr[r]??sr)-(nr[n]??sr))}formatCommitLine(e){let r=`- ${this.commitUrlFn?`[\`${e.hash}\`](${this.commitUrlFn(e.hash)})`:`\`${e.hash}\``} ${e.subject}`;if(e.body){let n=e.body.split(`
|
|
154
|
+
`).map((s)=>` ${s}`).join(`
|
|
148
155
|
`);return`${r}
|
|
149
156
|
<details>
|
|
150
157
|
<summary>Details</summary>
|
|
151
158
|
|
|
152
|
-
${
|
|
153
|
-
</details>`}return r}}import{readdir as
|
|
154
|
-
`);if(
|
|
155
|
-
`))
|
|
156
|
-
`).trim()}}catch{return null}}async
|
|
157
|
-
`),
|
|
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="^",gn="~",aa=new Map;function ee(e,t){return t.some((r)=>r===e||Ip(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 Sp(e,t,r){let s=e.slice(zr.length);if(s===la)return t!==r;if(s!==ua&&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=Tp(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?Cp(R.specifier):Sp(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 Cp(e){let t=e.slice(zr.length);return t===la||t===ua||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 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=kp(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 kp(e,t,r,s){let n=xp(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 xp(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 Tp(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(!Ep(i,t,e,r))continue;s.set(i.name,[...s.get(i.name)??[],{dependent:n,specifier:i.specifier}])}}return s}function Ep(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 Ip(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 fn,readFile as da,unlink as ga,writeFile as ha}from"fs/promises";import{dirname as Ap,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 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 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 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 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 fn(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(Ap(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 Op={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":Op[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 _p,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 _p(e.file,"utf-8");this.originals.set(e.file,r),await ba(e.file,Ht(r,{...JSON.parse(r),version:t}),"utf-8")}}var Lp=/^[\t ]+/m,Mp=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 Dp(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 Np(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(!Mp.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,Dp(n,i,t,s)];if(i.startsWith("workspace:"))return[n,Np(n,i,r,s)];return[n,i]}))}function jp(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 $a(e,t,r){let s=JSON.parse(e),n=jp(s,t,r),i=e.match(Lp)?.[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 Ed,readFile as Id,rm as qc}from"fs/promises";import{tmpdir as Ad}from"os";import{dirname as Wc,join as pi,resolve as Od}from"path";var Sa=So().map((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:de()),Bp=Sa.map(Qs({publishConfig:Sa.map(Qs({access:Co(["public","restricted"]).or(Ut())})).or(Ut())}));function Xr(e){try{return Bp(JSON.parse(e)).publishConfig?.access??"public"}catch(t){throw Error("Invalid publishConfig.access: expected public or restricted",{cause:t})}}import{rm as cm}from"fs/promises";import{isAbsolute as lm,resolve as Ua}from"path";import{createHash as Zr}from"crypto";import{constants as Ca}from"fs";import{lstat as Vp,open as Up,readlink as xa}from"fs/promises";import{isAbsolute as Gp,relative as bn,resolve as Le,sep as vn}from"path";var $n=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=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 Hp(r,i),a=Zr("sha256");for(let c of o){if(c.kind==="tracked"&&!qp(c.mode))throw new u(`Release source has unsupported Git mode ${c.mode}: ${c.path}`);let l=await Aa(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 Wp(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 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 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 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 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(`..${vn}`)||Gp(e)}async function Hp(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 qp(e){return $n.has(e)||e===kt||e===er}async function Aa(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 Vp(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 Wp(e,t,r){let s=await Up(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=bn(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 Jp,mkdir as zp,mkdtemp as Kp,rename as Yp,rm as Xp,writeFile as Zp}from"fs/promises";import{tmpdir as Qp}from"os";import{dirname as Da,join as Ma,relative as kn,resolve as He,sep as em}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,tm=100,rm=124,sm=12,nm=345,im=155,om="package/package.json",am=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=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 Yp(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=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 Fa(e,t,r){let s=await ja(e,t),n=await Kp(Ma(Qp(),"sisyphus-package-stage-"));try{for(let i of s){let o=He(n,i);await zp(Da(o),{recursive:!0}),await Jp(He(t,i),o,{errorOnExist:!0,force:!1,recursive:!1,verbatimSymlinks:!0})}return await Zp(Ma(n,"package.json"),r,"utf-8"),n}catch(i){try{await Xp(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=kn(r,He(t,o)).split(em).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,am),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):
|
|
159
|
+
${n}
|
|
160
|
+
</details>`}return r}}import{readdir as hu,readFile as yu}from"fs/promises";import{basename as hy,join as $o}from"path";var mu="*",gu="^",Ro="~",pu=new Map;function se(e,t){return t.some((r)=>r===e||fy(e,r))}function pe(e,t){let r=e.get("dependents")??gt.dependents;return{ignore:e.get("ignore")??[],kinds:r.kinds,tag:t,updateInternal:r.updateInternal}}function ly(e,t,r){let n=e.slice(Ss.length);if(n===mu)return t!==r;if(n!==gu&&n!==Ro)return!1;let s=De(t),i=De(r);if(!s||!i)return!0;if(Me(s)||Me(i))return!0;if(s.major!==i.major)return!0;if(n===Ro)return s.minor!==i.minor;if(s.major!==0)return!1;if(s.minor!==0)return s.minor!==i.minor;return s.minor!==i.minor||s.patch!==i.patch}function wt(e,t,r){let n=r.ignore??[],s=my(t,new Set(r.kinds),n),i=new Map,o=new Set,a=[];for(let c of[...e].sort((l,p)=>ur(l.name,p.name))){if(!t.has(c.name)||se(c.name,n))continue;if(o.add(c.name),du(i,c.name,c.bump))ks(a,c.name)}while(a.length>0){let c=a.shift();if(!c)continue;let l=t.get(c),p=i.get(c),m=s.get(c);if(!l||!p||!m)continue;let g=r.updateInternal==="outOfRange",h=De(l.version),f=h!==null&&Me(h),y=g&&!f?xe.bump(l.version,p,r.tag):l.version;for(let R of m){let S=f?uy(R.specifier):ly(R.specifier,l.version,y);if(g&&!S)continue;if(du(i,R.dependent,"dependency"))ks(a,R.dependent)}}return[...i.keys()].filter((c)=>!o.has(c)).sort(ur)}function uy(e){let t=e.slice(Ss.length);return t===mu||t===gu||t===Ro}function vo(e,t){if(t.length===0)return{skipped:[],stone:e};let r=[],n=e;for(let s of st){let i=e.getPackages(s),o=i.filter((a)=>!se(a,t));if(o.length===i.length)continue;r.push(...i.filter((a)=>!o.includes(a))),n=n.withPackages(s,o)}return{skipped:[...new Set(r)].sort(ur),stone:n}}function fu(e,t){if(t.length===0)return{kept:[...e],skipped:[]};let r=[],n=[];for(let s of e)if(se(s.name,t))n.push(s.name);else r.push(s);return{kept:r,skipped:n}}function pr(e){let t=new Map(e.map((p)=>[p.name,p])),r=[...t.keys()].sort(ur),n=new Map,s=new Map,i=new Map;for(let p of r){let m=new Set((t.get(p)?.workspaceDependencies??[]).filter((g)=>g.kind!=="devDependencies").map((g)=>g.name).filter((g)=>g!==p&&t.has(g)));n.set(p,m.size),i.set(p,m);for(let g of m)s.set(g,[...s.get(g)??[],p])}let o=r.filter((p)=>n.get(p)===0),a=[],c=new Set,l=[];while(c.size<r.length){if(o.length===0){let g=py(r,c,s,i);if(!g)break;l.push(g),ks(o,g)}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 g of s.get(p)??[]){if(c.has(g))continue;let h=(n.get(g)??0)-1;if(n.set(g,h),h===0)ks(o,g)}}return{cycle:l,ordered:a}}function py(e,t,r,n){let s=dy(e,t,n),i=s.size>0?e.filter((c)=>s.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 dy(e,t,r){let n=new Map,s=new Map,i=[],o=new Set,a=new Set,c=(l)=>{let p=n.size;n.set(l,p),s.set(l,p),i.push(l),o.add(l);for(let f of r.get(l)??[]){if(t.has(f))continue;if(!n.has(f))c(f),s.set(l,Math.min(s.get(l)??p,s.get(f)??p));else if(o.has(f))s.set(l,Math.min(s.get(l)??p,n.get(f)??p))}if(s.get(l)!==p)return;let m=new Set,g;do{if(g=i.pop(),g===void 0)break;o.delete(g),m.add(g)}while(g!==l);if([...m].some((f)=>[...r.get(f)??[]].some((y)=>!t.has(y)&&!m.has(y))))return;for(let f of m)a.add(f)};for(let l of e)if(!t.has(l)&&!n.has(l))c(l);return a}function my(e,t,r){let n=new Map;for(let s of[...e.keys()].sort(ur)){if(se(s,r))continue;for(let i of e.get(s)?.workspaceDependencies??[]){if(!gy(i,t,e,r))continue;n.set(i.name,[...n.get(i.name)??[],{dependent:s,specifier:i.specifier}])}}return n}function gy(e,t,r,n){if(!t.has(e.kind))return!1;if(!r.has(e.name))return!1;return!se(e.name,n)}function du(e,t,r){let n=e.get(t),s=n===void 0?r:cr(n,r);if(n!==void 0&&s===n)return!1;return e.set(t,s),!0}function ks(e,t){if(e.includes(t))return;let r=e.findIndex((n)=>ur(n,t)>0);if(r<0)e.push(t);else e.splice(r,0,t)}function ur(e,t){if(e===t)return 0;return e<t?-1:1}function fy(e,t){let r=pu.get(t);if(!r)r=new Bun.Glob(t),pu.set(t,r);return r.match(e)}var yy=".changeset",wy="config.json",xs="---",wu=0,Po=1,by=Rl().or(He()),Ry=ke((e)=>Array.isArray(e)?K():dt(Qt())(e)),vy=_();function bt(e,t){return(r)=>{if(r===void 0)return;try{return t(r)}catch{throw new Co(`${e} has an unsupported value`)}}}class Co extends Error{}var bu=re(re(_())),$y=nt({access:bt("access",Le(["restricted","public"])),baseBranch:bt("baseBranch",_()),changelog:bt("changelog",_().or(re(Qt())).or(Le([!1]))),commit:bt("commit",er().or(_()).or(re(Qt()))),fixed:bt("fixed",bu),ignore:bt("ignore",re(_())),linked:bt("linked",bu),updateInternalDependencies:bt("updateInternalDependencies",Le(["patch","minor"]))});class Mt extends Error{}function Ru(e){if(e===null)return"null";return Array.isArray(e)?"a list":`a ${typeof e}`}function Py(e){let t=e.split(`
|
|
161
|
+
`);if(t[wu]?.trim()!==xs)throw new Mt(`it does not start with a ${xs} front matter line`);let r=t.findIndex((s,i)=>i>wu&&s.trim()===xs);if(r<Po)throw new Mt(`its front matter has no closing ${xs} line`);let n;try{n=Bun.YAML.parse(t.slice(Po,r).join(`
|
|
162
|
+
`))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Mt(`its front matter is not valid YAML (${i})`)}return{frontmatter:n,summary:t.slice(r+Po).join(`
|
|
163
|
+
`).trim()}}function So(e,t){try{return e(t),!0}catch{return!1}}function Sy(e){if(So(by,e))return null;if(!So(Ry,e))throw new Mt(`its front matter must map package names to bump types, not ${Ru(e)}`);let t=Object.entries(e);if(t.length===0)return null;let r=t.filter(([,n])=>!So(vy,n));if(r.length>0){let n=r.map(([s,i])=>`${s} has ${Ru(i)} instead of a bump type`);throw new Mt(n.join("; "))}return Object.fromEntries(t)}class ko{root;constructor(e=process.cwd()){this.root=e}get changesetDir(){return $o(this.root,yy)}async exists(){try{return await hu(this.changesetDir),!0}catch{return!1}}async parse(){let e=[],t=[],r=[];for(let s of await this.findChangesetFiles()){let i=await this.parseFile(s);switch(i._tag){case"Parsed":t.push(i.changeset);break;case"Empty":r.push(i.filename);break;case"Invalid":e.push(`${i.filename}: ${i.reason}`);break}}let n=await this.parseConfig(e);return{changesets:t,config:n,empty:r,errors:e}}async findChangesetFiles(){try{return(await hu(this.changesetDir)).filter((t)=>t.endsWith(".md")&&t!=="README.md").sort().map((t)=>$o(this.changesetDir,t))}catch{return[]}}async parseFile(e){let t=hy(e);try{let{frontmatter:r,summary:n}=Py(await yu(e,"utf-8")),s=Sy(r);return s?{_tag:"Parsed",changeset:{filename:t,packages:s,summary:n}}:{_tag:"Empty",filename:t}}catch(r){if(r instanceof Mt)return{_tag:"Invalid",filename:t,reason:r.message};let n=r instanceof Error?r.message:String(r);return{_tag:"Invalid",filename:t,reason:`it cannot be read (${n})`}}}async parseConfig(e){let t=$o(this.changesetDir,wy),r;try{r=await yu(t,"utf-8")}catch(n){if(n.code==="ENOENT")return null;return e.push(`Failed to read ${t}: ${n instanceof Error?n.message:String(n)}`),null}try{return $y(JSON.parse(r))}catch(n){let s=n instanceof Co?n.message:"it must be a JSON object";return e.push(`Invalid ${t}: ${s}`),null}}toStoneData(e,t){let r=[],n=[],s=[],i=[];for(let[g,h]of Object.entries(e.packages))switch(h){case"major":r.push(g);break;case"minor":n.push(g);break;case"patch":s.push(g);break;default:i.push(`${g} uses an unsupported bump type "${h}"`)}if(i.length>0)throw new u(`Changeset ${e.filename}: ${i.join("; ")}`,"Rewrite them as major, minor, or patch before migrating");let o=t?Object.keys(e.packages).filter((g)=>!t.packages.has(g)):[];if(o.length>0)throw new u(`Changeset ${e.filename}: ${o.join(", ")} ${o.length===1?"is":"are"} not a workspace package`,"Fix the package names in the changeset before migrating");let a=[...r.map((g)=>({bump:"major",name:g})),...n.map((g)=>({bump:"minor",name:g})),...s.map((g)=>({bump:"patch",name:g}))],c=t?X(wt(a,t.packages,t.dependents)):void 0,l=e.summary.split(`
|
|
164
|
+
`),p=l[0]?.trim()||"Migrated from changeset",m=l.slice(1).join(`
|
|
165
|
+
`).trim();return{dependency:c,description:m||void 0,major:X(r),message:p,minor:X(n),patch:X(s)}}}function Es(e){let t=new Map;for(let[r,n]of e){let s=n.file.replace(/\\/g,"/"),i=s.substring(0,s.lastIndexOf("/"))||".";t.set(i,r)}return t}function Yr(e,t,r=!0){let n=new Set;for(let s of e)for(let[i,o]of t){let a=i===".",c=s.startsWith(`${i}/`);if(a?r:c)n.add(o)}return n}import{existsSync as dr}from"fs";import{mkdir as vu,readdir as xo,readFile as $u,unlink as Pu,writeFile as Su}from"fs/promises";import{dirname as Cy,join as Zr,resolve as Cu}from"path";var ku=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,xu=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/;class B{config;constructor(e){this.config=e}get sisyphusDir(){return this.config.get("sisyphusDir")||ir}get stonesPath(){return this.config.get("stonesPath")||Zr(this.sisyphusDir,Al)}get releasedPath(){return Zr(this.sisyphusDir,Ol)}getStoragePaths(){return[this.sisyphusDir,this.stonesPath]}async list(){let e=await this.listIds(),t=[];for(let r of e){let n=await this.get(r);if(n)t.push(n)}return t}async listIds(){return(await this.readStoneFiles()).filter((t)=>t.endsWith(".json")).map((t)=>this.toStoneId(t)).sort()}async get(e){let t=this.getFilePath(e);if(!dr(t))return null;let r=await $u(t,"utf-8"),n=this.parseStoneJson(r,t);return this.assertStoneId(n,e,t),O.fromJson(n)}parseStoneJson(e,t){let r;try{r=JSON.parse(e)}catch{throw new u(`Failed to parse stone file ${t}`,"Remove or fix the file")}if(typeof r!=="object"||r===null||Array.isArray(r))throw new u(`Stone file ${t} is not a JSON object`,"Remove or fix the file");return r}assertStoneId(e,t,r){if(e.id===t)return;throw new u(`Stone file ID mismatch: expected "${t}", found "${String(e.id)}"`,`Fix ${r}`)}async readStoneFiles(){try{return await xo(this.stonesPath)}catch(e){if(e.code==="ENOENT")return[];throw e}}async save(e){await this.ensureStorageExists();let t=this.getFilePath(e.id),r=JSON.stringify(e.toJson(),null,2);await Su(t,r,"utf-8")}async delete(e){let t=this.getFilePath(e);if(!dr(t))return!1;return await Pu(t),!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=O.create(e,t.length);return await this.save(r),r}async archive(e){if(e.length===0)return"";let t=this.createTimestamp(),r=Zr(this.releasedPath,t);await vu(r,{recursive:!0});for(let n of e){let s=this.getFilePath(n.id),i=Zr(r,`${n.id}.json`);if(dr(s))await Su(i,JSON.stringify(n.toJson(),null,2),"utf-8"),await Pu(s)}return t}async getReleasedStones(e,t){let r=this.getArchivePath(e);if(!dr(r))return[];let s=(await xo(r)).filter((a)=>a.endsWith(".json")).sort(),i=t?.map((a)=>`${this.validateId(a)}.json`).sort();if(i&&JSON.stringify(s)!==JSON.stringify(i))throw Error(`Released stone archive ${e} does not match currentRelease: expected ${i.join(", ")||"no stones"}, found ${s.join(", ")||"no stones"}`);let o=[];for(let a of s)try{let c=this.validateId(a.slice(0,-5)),l=Zr(r,a),p=await $u(l,"utf-8"),m=this.parseStoneJson(p,l);this.assertStoneId(m,c,l),o.push(O.fromJson(m))}catch(c){if(t)throw c;v.warn(d.dim(`Failed to parse stone "${a}": ${c}`))}return o}async listReleasedTimestamps(){if(!dr(this.releasedPath))return[];return(await xo(this.releasedPath,{withFileTypes:!0})).filter((t)=>t.isDirectory()&&xu.test(t.name)).map((t)=>t.name)}async getTrackedCommitPackages(){let e=await this.list(),t=new Map;for(let r of e.flatMap((n)=>n.commits??[])){let n=t.get(r.hash)??new Set;for(let s of r.packages)n.add(s);t.set(r.hash,n)}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(!xu.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 n=Cu(e),s=Cu(n,t);if(Cy(s)!==n)throw Error(r);return s}validateId(e){if(!ku.test(e))throw Error(`Invalid stone ID "${e}"`);return e}toStoneId(e){let t=e.slice(0,-5);if(ku.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(!dr(this.stonesPath))await vu(this.stonesPath,{recursive:!0})}}import{posix as ky,sep as xy}from"path";var Eo="!",Eu="./",Ey="node_modules",Ty="package.json";class U{static async scan(e={}){let{filter:t,single:r}=e;if(r)return U.scanRootPackage(t);let n=await U.getWorkspaces();U.validateWorkspaces(n);let s=await U.scanWorkspaces(n);return{packageNames:U.filterNames(Array.from(s.keys()),t),packages:s}}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"),n=new Map;return n.set(r.name,r),{packageNames:U.filterNames([r.name],e),packages:n}}static async scanWorkspaces(e){let t=new Map;for(let r of U.expandWorkspaces(e)){let n=await Bun.file(r).json(),s=z.fromJson(n,r),i=t.get(s.name);if(i)throw new u(`Duplicate workspace package ${s.name}: ${i.file} and ${r}`);t.set(s.name,s)}return t}static expandWorkspaces(e){let t=e.filter((n)=>n.startsWith(Eo)).map((n)=>new Bun.Glob(To(n.slice(Eo.length)))),r=new Set;for(let n of e){if(n.startsWith(Eo))continue;let s=new Bun.Glob(`${To(n)}/${Ty}`);for(let i of s.scanSync({cwd:process.cwd()})){let o=To(i.split(xy).join("/"));if(o.split("/").includes(Ey))continue;let a=ky.dirname(o);if(t.some((c)=>c.match(a)||c.match(o)))continue;r.add(o)}}return[...r]}}function To(e){return e.startsWith(Eu)?e.slice(Eu.length):e}var Iy={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch",[mt]:"patch"},Ay=/\{message\}|\{packages\}/,Oy=/[.*+?^${}()|[\]\\]/g,_y=/^- \S+@\S+(?:\n- \S+@\S+)*$/;function Ly(e){return e.replace(Oy,"\\$&")}function Dy(e){return new RegExp(`^${e.split(Ay).map(Ly).join(".+")}$`)}function My(e){return e.map((t)=>{try{return new RegExp(t,"i")}catch(r){throw new u(`Invalid regex pattern in commits.skip.messagePatterns: "${t}"`,void 0,1,{cause:r})}})}class Nt{config;stoneManager;constructor(e){this.config=e;this.stoneManager=new B(e)}async analyze(e={}){let t=this.config.get("commits")?.skip??gt.commits.skip,r={authors:t.authors,patterns:My(t.messagePatterns),releaseSubject:Dy(this.config.get("commit").message)},n=await this.getCommitsSinceLastRelease();if(n.length===0)return[];if(n=n.filter((i)=>!this.shouldSkipCommit(i,r)),n.length===0)return[];let s=await this.stoneManager.getTrackedCommitPackages();return this.groupByPackage(n,e,s)}shouldSkipCommit(e,t){if(t.authors.includes(e.author))return!0;if(t.patterns.some((r)=>r.test(e.subject)))return!0;return t.releaseSubject.test(e.subject)&&_y.test(e.body??"")}async getCommitsSinceLastRelease(){let t=this.config.get("lastStone")?.commit||void 0;if(!t)return[];return Z.since(t)}async groupByPackage(e,t,r){let{packages:n,packageNames:s}=await U.scan({filter:t.filter,single:t.single}),i=this.config.get("ignore")??[],o=new Set(s.filter((p)=>!se(p,i))),a=new Map([...n].filter(([p])=>o.has(p))),c=Es(a),l=new Map;for(let p of e){let m=Yr(p.files,c);for(let y of r.get(p.shortHash)??[])m.delete(y);if(m.size===0)continue;let g=p.breaking?"major":Iy[p.type]||"patch",h=`${p.type}${p.breaking?"!":""}`,f=l.get(h);if(!f){let y=this.getGroupMessage(p);f={bump:g,commits:[],message:y,packages:new Set},l.set(h,f)}f.commits.push(p.toInfo([...m]));for(let y of m)f.packages.add(y)}return Array.from(l.entries()).sort(([p],[m])=>(nr[p]??sr)-(nr[m]??sr)).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 n=Array.from(e.packages),s=n.map((i)=>({bump:e.bump,name:i}));return{[e.bump]:n,commits:X(e.commits),dependency:X(wt(s,t,r)),message:e.message,tag:r.tag}}}import{readFile as Ny,writeFile as Tu}from"fs/promises";class Qr{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 Tu(e,t,"utf-8");this.originals.clear()}async updatePackage(e){let t=e.newVersion;if(!t)return;vs(t,`write the new version of ${e.name}`);let r=await Ny(e.file,"utf-8");this.originals.set(e.file,r),await Tu(e.file,qr(r,{...JSON.parse(r),version:t}),"utf-8")}}var jy=/^[\t ]+/m,Fy=new Set(["*","^","~"]);class Rt extends Error{hint;_tag="PublishManifestError";constructor(e,t){super(e);this.hint=t}}function Iu(e){let t=Array.isArray(e.workspaces)?void 0:e.workspaces;return{["default"]:{...e.catalog,...t?.catalog},...e.catalogs,...t?.catalogs}}function By(e,t,r,n){let s=t.slice(8)||"default",i=Object.hasOwn(r,s)?r[s]:void 0,o=i&&Object.hasOwn(i,e)?i[e]:void 0;if(!o)throw new Rt(`Catalog "${s}" has no entry for "${e}" (required by ${n})`,"Add the entry to the root package.json catalog before publishing");return o}function Uy(e,t,r,n){let s=t.slice(10),i=Object.hasOwn(r,e)?r[e]:void 0;if(!i)throw new Rt(`Workspace package "${e}" (required by ${n}) was not found in the workspace`,"Check the dependency name against your workspaces globs");if(i.isPrivate)throw new Rt(`"${n}" 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(!Fy.has(s)){if(!s)throw new Rt(`Invalid workspace specifier "${t}" for "${e}" (required by ${n})`,"Use workspace:*, workspace:^, workspace:~, or workspace:<range>");return s}let o=i.version;if(!o)throw new Rt(`Workspace package "${e}" (required by ${n}) has no version in its package.json`,"Add a version field before publishing");return s==="*"?o:`${s}${o}`}function Io(e,t,r,n){if(!e)return e;return Object.fromEntries(Object.entries(e).map(([s,i])=>{if(i.startsWith("catalog:"))return[s,By(s,i,t,n)];if(i.startsWith("workspace:"))return[s,Uy(s,i,r,n)];return[s,i]}))}function Vy(e,t,r){let{devDependencies:n,...s}=e;return{...s,dependencies:Io(e.dependencies,t,r,e.name),optionalDependencies:Io(e.optionalDependencies,t,r,e.name),peerDependencies:Io(e.peerDependencies,t,r,e.name)}}function Au(e,t,r){let n=JSON.parse(e),s=Vy(n,t,r),i=e.match(jy)?.[0]??2;return`${JSON.stringify(s,null,i)}
|
|
166
|
+
`}function Ou(e){return Object.fromEntries(Array.from(e,(t)=>[t.name,{isPrivate:t.isPrivate,version:t.version||null}]))}function _u(e,t,r){try{return Au(e,t,r)}catch(n){throw n instanceof Rt?new u(n.message,n.hint):n}}var Hy="%an%x00%ae%x00%aI%x00%s",qy=2,Wy="feat";class Ao{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),n=this.config.get("single"),{packages:s}=await U.scan({single:n}),i=Es(s),o={isSinglePackage:n,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 Z.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){let o=r.includes(e.mergeCommitSha)?r:await this.findRebasedCommits(e.mergeCommitSha,r),a=o?await Promise.all(o.map((c)=>Z.fromHash(c))):[];if(o&&a.every((c)=>c!==null))return this.processCommits(a,t)}let n=await t.provider.getPrFiles(e.number);if(n.length===0)throw new u(`Could not determine changed files for PR #${e.number}`,"Check provider access and retry the analysis");let s=Yr(n,t.packagePaths,t.isSinglePackage);if(!e.mergeCommitSha)return{affectedPackages:s,commits:[]};let i={body:e.body||void 0,hash:e.mergeCommitSha.slice(0,ps),message:e.title,packages:[...s],subject:e.title,type:this.inferCommitType(e.title)};return{affectedPackages:s,commits:[i]}}async findRebasedCommits(e,t){if(t.length===0)return null;let r=await Bun.$`git rev-list --first-parent --no-merges ${`--max-count=${t.length}`} ${e}`.quiet().nothrow(),n=r.exitCode===0?r.stdout.toString().split(`
|
|
167
|
+
`).filter(Boolean).reverse():[];if(n.length!==t.length)return null;let[s,i]=await Promise.all([this.readIdentities(n),this.readIdentities(t)]);return s!==null&&s===i?n:null}async readIdentities(e){let t=await Bun.$`git show --no-patch --no-walk=unsorted ${`--format=${Hy}`} ${e}`.quiet().nothrow();return t.exitCode===0?t.stdout.toString():null}async analyzeMergeCommit(e,t){if(!e.mergeCommitSha)return{affectedPackages:new Set,commits:[]};let r=await Z.fromMerge(e.mergeCommitSha);return this.processCommits(r,t)}processCommits(e,t){let r=[],n=new Set;for(let s of e){let i=Yr(s.files,t.packagePaths,t.isSinglePackage);if(i.size===0)continue;r.push(s.toInfo([...i]));for(let o of i)n.add(o)}return{affectedPackages:n,commits:r}}async detectMergeMethod(e){if(!e)return"squash";if(await this.getCommitParentCount(e)===qy)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(`
|
|
168
|
+
`).filter(Boolean).length}catch{return 1}}inferCommitType(e){return e.match(/^(\w+)(?:\(.*?\))?!?:/)?.[1]??mt}async getProvider(){if(!this.provider)this.provider=await yt(void 0,this.config.get("provider"));return this.provider}async fetchFromCurrentBranch(e){let t=await e.getPrFromCurrentBranch();return this.mapPullRequest(t)}async fetchFromUrl(e,t){let r=await hs(this.config.get("provider")),n=ql(t,r??void 0);if(!n)throw new u("Invalid PR URL","Expected a PR/MR URL from GitHub, GitLab, or Bitbucket");if(n.provider!==e.name)throw new u(`PR URL is from ${n.provider}, but repository is on ${e.name}`,"Make sure the PR URL matches the repository provider");if(!r||n.host!==Je(r)||r.owner.toLowerCase()!==n.owner.toLowerCase()||r.repo.toLowerCase()!==n.repo.toLowerCase())throw new u("PR URL does not match this repository","Use a PR/MR URL from the repository configured as origin");let s=await e.getPr(n.number);return this.mapPullRequest(s)}mapPullRequest({headBranch:e,...t}){return{...t,branch:e}}inferBumpFromLabels(e){let t=this.config.get("pr").labelMapping,r=null;for(let n of e){let s=n.toLowerCase();for(let[i,o]of Object.entries(t)){if(s!==i.toLowerCase())continue;r=r?cr(r,o):o}}return r}inferBumpFromTitle(e){let t=Z.parse("",e,"");if(t.breaking)return"major";if(t.type===mt)return null;return t.type===Wy?"minor":"patch"}}import{resolve as Cb}from"path";import{createHash as Nw,randomUUID as jw}from"crypto";import{constants as Fw}from"fs";import{copyFile as Bw,link as Uw,lstat as yp,readFile as na,rename as wp,rm as bp,stat as Vw,unlink as Gw}from"fs/promises";import{extname as Hw,join as qw,resolve as Rp}from"path";import{createHash as rp,randomUUID as ww}from"crypto";import{link as bw,lstat as dn,mkdir as Fs,open as Rw,readFile as np,realpath as $t,rename as vw,rm as $w,unlink as Pw}from"fs/promises";import{dirname as ln,isAbsolute as tp,join as un,relative as sp,resolve as Ne,sep as Sw}from"path";import{createHash as Ts}from"crypto";import{constants as Lu}from"fs";import{lstat as Jy,open as zy,readlink as Mu,realpath as Ky}from"fs/promises";import{basename as Xy,dirname as Yy,isAbsolute as Zy,join as Qy,relative as Oo,resolve as it,sep as _o}from"path";var Lo=new Set(["100644","100755"]),mr="120000",en="160000",ew=/["\\\n\r\t]/g,tw={"\t":"\\t","\n":"\\n","\r":"\\r",'"':"\\\"","\\":"\\\\"},Nu=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;function tn(e){let[t,r]=new B(e).getStoragePaths();return[t,r,e.path]}async function As(e,...t){let r=await Bun.$`git rev-parse --show-toplevel`.quiet(),n=it(r.stdout.toString().trim()),s=await Promise.all([e,...t].map((a)=>sw(n,a))),i=await iw(n,s),o=Ts("sha256");for(let a of i){if(a.kind==="tracked"&&!ow(a.mode))throw new u(`Release source has unsupported Git mode ${a.mode}: ${a.path}`);let c=await Uu(n,a.path),l=await Do(c);if(o.update(a.path),o.update("\x00"),o.update(a.kind),o.update("\x00"),!l){if(a.kind==="tracked"&&a.mode===en)throw new u(`Release source gitlink is not initialized: ${a.path}`);o.update("deleted")}else if(a.kind==="untracked"||Lo.has(a.mode)){if(!l.isFile()||l.isSymbolicLink())throw new u(`Release source path is not a regular file: ${a.path}`);await aw(o,c,a.path)}else if(a.mode===mr){if(!l.isSymbolicLink())throw new u(`Release source path does not match Git mode ${mr}: ${a.path}`);o.update(Ts("sha256").update(await Mu(c,{encoding:"buffer"})).digest("hex")),o.update(mr)}else{if(!l.isDirectory()||l.isSymbolicLink())throw new u(`Release source path does not match Git mode ${en}: ${a.path}`);o.update(await Vu(n,c,a)),await rn(c),o.update(en)}o.update("\x00")}return o.digest("hex")}async function rn(e=process.cwd()){let t=await Bun.$`git rev-parse --show-toplevel`.cwd(e).quiet(),r=it(t.stdout.toString().trim());await ju(r)}async function ju(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()]),n=new Set,s=new Map,i=[];for(let a of Is(r.stdout)){let c=a.slice(0,1),l=a.slice(2);if(!c||a.slice(1,2)!==" "||!l)throw new u("Unable to parse Git index flags while validating release source");s.set(l,c)}for(let a of Is(t.stdout)){let c=Bu(a);if(c.stage!=="0")throw new u(`Release source has an unresolved index entry: ${c.path}`);if(n.has(c.path))throw new u(`Release source has duplicate index entries: ${c.path}`);if(n.add(c.path),s.get(c.path)!=="H")throw new u(`Release source index flags hide working tree changes: ${c.path}`);let l={kind:"tracked",mode:c.mode,objectId:c.objectId,path:c.path},p=await Uu(e,c.path),m=await Do(p);if(!m)throw new u(`Release source path is missing: ${c.path}`);if(Lo.has(c.mode)){if(!m.isFile()||m.isSymbolicLink())throw new u(`Release source path is not a regular file: ${c.path}`);i.push({entry:l,mode:m.mode&73?"100755":"100644"});continue}if(c.mode===mr){if(!m.isSymbolicLink())throw new u(`Release source path does not match Git mode ${mr}: ${c.path}`);let g=await Bun.$`git cat-file blob ${c.objectId}`.cwd(e).quiet(),h=await Mu(p,{encoding:"buffer"});if(!Buffer.from(g.stdout).equals(h))throw new u(`Release source symlink differs from the Git index: ${c.path}`);continue}if(c.mode!==en)throw new u(`Release source has unsupported Git mode ${c.mode}: ${c.path}`);if(!m.isDirectory()||m.isSymbolicLink())throw new u(`Release source gitlink is not initialized: ${c.path}`);await Vu(e,p,l),await ju(p)}let o=await rw(e,i.map(({entry:a})=>a.path));for(let[a,{entry:c,mode:l}]of i.entries())if(o[a]!==c.objectId||l!==c.mode)throw new u(`Release source path differs from the Git index: ${c.path}`)}async function rw(e,t){if(t.length===0)return[];let r=Buffer.from(`${t.map(nw).join(`
|
|
169
|
+
`)}
|
|
170
|
+
`),s=(await Bun.$`git hash-object --stdin-paths < ${r}`.cwd(e).quiet()).stdout.toString().split(`
|
|
171
|
+
`).filter(Boolean);if(s.length!==t.length)throw new u(`Unable to hash release source files in ${e}`);return s}function nw(e){return`"${e.replace(ew,(t)=>tw[t]??t)}"`}function Os(e,t){return Ts("sha256").update(JSON.stringify(gr({...e,stones:t}))).digest("hex")}function gr(e){if(Array.isArray(e))return e.map(gr);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,gr(r)]))}function de(e){return e===".."||e.startsWith(`..${_o}`)||Zy(e)}async function sw(e,t){let r=Oo(e,await Fu(it(e,t)));if(!r||de(r))throw new u(`Release metadata path is outside the repository: ${t}`,"Keep sisyphusDir, stonesPath and the Sisyphus config inside the repository");return r.split(_o).join("/")}async function Fu(e){let t=Yy(e);if(t===e)return e;let r=await Ky(t).catch((n)=>{if(Mo(n,"ENOENT"))return Fu(t);throw n});return Qy(r,Xy(e))}async function iw(e,t){let[r,n]=await Promise.all([Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),Bun.$`git ls-files -z --others --exclude-standard`.cwd(e).quiet()]),s=[],i=new Set;for(let o of Is(r.stdout)){let a=Bu(o);if(Du(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),s.push({kind:"tracked",mode:a.mode,objectId:a.objectId,path:a.path})}for(let o of Is(n.stdout)){if(Du(o,t))continue;if(i.has(o))throw new u(`Release source path is both tracked and untracked: ${o}`);i.add(o),s.push({kind:"untracked",path:o})}return s.sort((o,a)=>o.path<a.path?-1:o.path>a.path?1:0)}function Is(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 Bu(e){let t=e.indexOf("\t");if(t<0)throw new u("Unable to parse Git index entry while hashing release source");let[r,n,s,...i]=e.slice(0,t).split(" "),o=e.slice(t+1);if(!r||!/^[0-7]{6}$/.test(r)||!n||!Nu.test(n)||!s||i.length>0||!o)throw new u("Unable to parse Git index entry while hashing release source");return{mode:r,objectId:n,path:o,stage:s}}function Du(e,t){return t.some((r)=>e===r||e.startsWith(`${r}/`))}function ow(e){return Lo.has(e)||e===mr||e===en}async function Uu(e,t){let r=t.split("/"),n=it(e,t),s=Oo(e,n);if(r.some((o)=>!o||o==="."||o==="..")||de(s)||s.split(_o).join("/")!==t)throw new u(`Release source path escapes the repository: ${t}`);let i=e;for(let o of r.slice(0,-1)){i=it(i,o);let a=await Do(i);if(!a)break;if(!a.isDirectory()||a.isSymbolicLink())throw new u(`Release source path has an unsafe parent: ${t}`)}return n}async function Do(e){try{return await Jy(e)}catch(t){if(Mo(t,"ENOENT"))return null;throw t}}function Mo(e,t){return e instanceof Error&&"code"in e&&e.code===t}async function aw(e,t,r){let n=await zy(t,Lu.O_RDONLY|Lu.O_NOFOLLOW).catch((s)=>{if(Mo(s,"ELOOP"))throw new u(`Release source path is not a regular file: ${r}`);throw s});try{let s=await n.stat();if(!s.isFile())throw new u(`Release source path is not a regular file: ${r}`);e.update(Ts("sha256").update(await n.readFile()).digest("hex")),e.update(s.mode&73?"100755":"100644")}finally{await n.close()}}async function Vu(e,t,r){let[n,s,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=it(n.stdout.toString().trim()),c=s.stdout.toString().trim(),l=c?it(c):null,p=it(i.stdout.toString().trim()),m=it(e,o.stdout.toString().trim()),g=Oo(m,p);if(a!==t||l!==e||!g||de(g))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(!Nu.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 nn=1,fr=["planned","local-ready","external","completed"],No=["pending","started","completed"],cw=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,jt=/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/,Gu=/^sha512-[0-9A-Za-z+/]{86}==$/,Hu=/^[0-9A-Za-z][0-9A-Za-z._/-]*$/,jo=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,qu=/^(?:linux:[0-9a-f-]{36}:[0-9]+|ps:.+|windows:[0-9]+)$/i,_s=2,Wu=3,Ju=19;class b extends Error{_tag="ReleaseLedgerError"}function P(e,t){throw new b(`Invalid release ledger at ${e}: ${t}`)}function sn(e,t){if(typeof e!=="string")P(t,"must be a string");return e}function A(e,t){let r=sn(e,t);if(!r.trim())P(t,"must be nonempty");return r}function on(e,t){let r=A(e,t);if(!cw.test(r))P(t,`invalid release ID ${r}`);return r}function Ls(e){let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function ne(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function j(e){return e instanceof Error?e.message:String(e)}import{randomUUID as lw}from"crypto";import{constants as zu,readFileSync as Ku}from"fs";import{link as uw,lstat as Ft,open as Uo,readFile as Yu,rename as pw,rm as Ms,unlink as Ns}from"fs/promises";import{hostname as Zu}from"os";import{dirname as vt,join as Fo}from"path";async function cn(e){let t=Fo(e,".write.lock");for(let r=0;r<Wu;r+=1){let n=hw();if(!n)throw new b("Failed to identify the release ledger lock owner process");let s={acquiredAt:new Date().toISOString(),hostname:Zu(),ownerId:lw(),pid:process.pid,processStartedAt:n,schemaVersion:_s},i=js(e,s.ownerId,"owner");await dw(i,s);try{await uw(i,t)}catch(a){if(await Ms(i,{force:!0}),!ne(a,"EEXIST"))throw new b(`Failed to acquire release ledger lock at ${t}: ${j(a)}`);let c=await mw(t);if(!c)continue;await gw(c);continue}let o={lockPath:t,metadata:s,ownerPath:i};try{return await me(e),o}catch(a){try{await hr(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}: ${j(a)}`)}}throw new b(`Release ledger is locked by another process at ${t}: lock changed during acquisition`)}async function dw(e,t){let r;try{r=await Uo(e,"wx",384),await r.writeFile(`${JSON.stringify(t)}
|
|
172
|
+
`,"utf-8"),await r.sync()}catch(n){throw await Ms(e,{force:!0}),new b(`Failed to create release ledger lock owner: ${j(n)}`)}finally{await r?.close()}await me(vt(e))}async function mw(e){let t,r,n;try{n=await Uo(e,zu.O_RDONLY|zu.O_NOFOLLOW),t=await n.stat(),r=await n.readFile("utf-8")}catch(p){if(ne(p,"ENOENT"))return null;throw new b(`Failed to inspect release ledger lock at ${e}: ${j(p)}`)}finally{await n?.close()}if(!t.isFile())throw new b(`Release ledger is locked by another process at ${e}: lock owner is unknown`);let s=null;try{s=Bo(JSON.parse(r))}catch{s=null}if(!s)return await Ds(e,t,"lock metadata is malformed");let i=js(vt(e),s.ownerId,"owner"),o=js(vt(e),s.ownerId,"claim"),a;try{a=await Ft(i)}catch(p){if(ne(p,"ENOENT")){try{await Ft(o)}catch(m){if(ne(m,"ENOENT"))return await Ds(e,t,"stale lock ownership is incomplete");throw new b(`Failed to inspect release ledger lock claim: ${j(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: ${j(p)}`)}if(!a.isFile()||a.isSymbolicLink())return await Ds(e,t,"stale lock ownership is invalid");let c=null;try{c=Bo(JSON.parse(await Yu(i,"utf-8")))}catch{c=null}if(!c||!yw(s,c))return await Ds(e,t,"stale lock ownership is invalid");if(!await ep(e,t))return null;if(!an(t,a))return{lockPath:e,lockStat:t,metadata:s,ownerPath:i,ownerStat:a};if(s.hostname!==Zu())throw new b(`Release ledger is locked by another process at ${e}: lock owner is on an unknown host ${s.hostname} (pid ${s.pid})`);let l=fw(s);if(l==="alive")throw new b(`Release ledger is locked by another process at ${e}: lock owner is still live (pid ${s.pid} on ${s.hostname})`);if(l==="unknown")throw new b(`Release ledger is locked by another process at ${e}: lock owner liveness is unknown (pid ${s.pid} on ${s.hostname})`);return{lockPath:e,lockStat:t,metadata:s,ownerPath:i,ownerStat:a}}async function gw(e){let t=js(vt(e.lockPath),e.metadata.ownerId,"claim");if(e.ownerPath!==t)try{await pw(e.ownerPath,t),await me(vt(e.lockPath))}catch(s){if(ne(s,"ENOENT")||ne(s,"EEXIST"))return;throw new b(`Failed to claim stale release ledger lock: ${j(s)}`)}let r,n;try{[r,n]=await Promise.all([Ft(e.lockPath),Ft(t)])}catch(s){if(ne(s,"ENOENT"))return;throw new b(`Failed to verify stale release ledger lock: ${j(s)}`)}if(!an(e.lockStat,r))return;if(!an(e.ownerStat,n))return;try{await Ns(e.lockPath),await me(vt(e.lockPath)),await Ns(t),await me(vt(e.lockPath))}catch(s){if(ne(s,"ENOENT"))return;throw new b(`Failed to recover stale release ledger lock: ${j(s)}`)}}async function hr(e){let t,r;try{[t,r]=await Promise.all([Ft(e.lockPath),Ft(e.ownerPath)])}catch(s){if(ne(s,"ENOENT"))throw await Ms(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: ${j(s)}`)}if(!an(t,r))throw await Ms(e.ownerPath,{force:!0}),new b("Failed to release ledger write lock: ownership changed");let n=null;try{n=Bo(JSON.parse(await Yu(e.lockPath,"utf-8")))}catch{n=null}if(n?.ownerId!==e.metadata.ownerId)throw new b("Failed to release ledger write lock: owner identity changed");try{await Ns(e.lockPath),await Ns(e.ownerPath),await me(vt(e.lockPath))}catch(s){throw new b(`Failed to release ledger write lock: ${j(s)}`)}}function Bo(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((n)=>["acquiredAt","hostname","ownerId","pid","processStartedAt","schemaVersion"].includes(n))||t.schemaVersion!==_s||typeof t.ownerId!=="string"||!jo.test(t.ownerId)||typeof t.hostname!=="string"||!t.hostname||typeof t.pid!=="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.processStartedAt!=="string"||!qu.test(t.processStartedAt)||typeof t.acquiredAt!=="string"||!Ls(t.acquiredAt))return null;return{acquiredAt:t.acquiredAt,hostname:t.hostname,ownerId:t.ownerId,pid:t.pid,processStartedAt:t.processStartedAt,schemaVersion:_s}}function js(e,t,r){if(!jo.test(t))throw new b(`Release ledger is locked by another process at ${Fo(e,".write.lock")}: lock owner identity is malformed`);return Fo(e,`.write.lock.${t}.${r}`)}function fw(e){try{process.kill(e.pid,0)}catch(r){return ne(r,"ESRCH")?"dead":"unknown"}let t=Qu(e.pid);if(!t)return"unknown";if(t.split(":",1)[0]!==e.processStartedAt.split(":",1)[0])return"unknown";return t===e.processStartedAt?"alive":"dead"}var Xu=null;function hw(){return Xu??=Qu(process.pid),Xu}function Qu(e){if(process.platform==="linux")try{let t=Ku("/proc/sys/kernel/random/boot_id","utf-8").trim(),r=Ku(`/proc/${e}/stat`,"utf-8"),n=r.lastIndexOf(")"),s=n<0?void 0:r.slice(n+1).trim().split(/\s+/)[Ju];if(t&&s)return`linux:${t}:${s}`}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 an(e,t){return e.dev===t.dev&&e.ino===t.ino}async function ep(e,t){try{return an(t,await Ft(e))}catch(r){if(ne(r,"ENOENT"))return!1;throw new b(`Failed to verify release ledger lock at ${e}: ${j(r)}`)}}async function Ds(e,t,r){if(!await ep(e,t))return null;throw new b(`Release ledger is locked by another process at ${e}: ${r}`)}function yw(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 me(e){let t=await Uo(e,"r");try{await t.sync()}finally{await t.close()}}async function Vo(e){let t=Ne(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 n=r.stdout.toString().trim();if(!n)throw new b(`Failed to resolve repository root from ${t}: empty git output`);let s=tp(n)?Ne(n):Ne(t,n),i=await Bun.$`git rev-parse --git-path sisyphus/release`.cwd(s).quiet().nothrow();if(i.exitCode!==0)throw new b(`Failed to resolve release ledger git path from ${s}: ${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 ${s}: empty git output`);let a=tp(o)?Ne(o):Ne(s,o);return{activePath:un(a,"active.json"),artifactsRoot:un(a,"artifacts"),historyDirectory:un(a,"history"),releaseDirectory:a,removingPath:un(a,"removing.json"),repositoryRoot:s}}async function ip(e,t){let r=`${t}^{tree}`,n=await Bun.$`git rev-parse ${r}`.cwd(e).quiet().nothrow(),s=n.stdout.toString().trim();if(n.exitCode!==0||!jt.test(s))throw new b(`Cannot resolve release tree for commit ${t}`);return s}async function mn(e,t){await Fs(e.releaseDirectory,{recursive:!0}),await Pt(e.releaseDirectory,"release directory"),await Fs(e.artifactsRoot,{recursive:!0}),await Pt(e.artifactsRoot,"artifacts root"),await Fs(gn(e,t),{recursive:!0}),await op(e,t)}async function op(e,t){let r=gn(e,t);await Pt(e.releaseDirectory,"release directory"),await Pt(e.artifactsRoot,"artifacts root"),await Pt(r,`artifacts directory for release ${t}`);let n=await $t(e.releaseDirectory),s=await $t(e.artifactsRoot),i=await $t(r);return pn(n,s,"Artifacts root escapes the release directory"),pn(s,i,`Artifacts directory for release ${t} escapes the artifacts root`),i}async function ap(e){await Pt(e.releaseDirectory,"release directory"),await Fs(e.historyDirectory,{recursive:!0}),await Pt(e.historyDirectory,"history directory");let t=await $t(e.releaseDirectory),r=await $t(e.historyDirectory);pn(t,r,"History directory escapes the release directory")}async function cp(e,t){for(let[r,n]of Object.entries(e.artifacts))await Bs(t,e.id,r,n)}async function Bs(e,t,r,n){let s=Ne(e.releaseDirectory,n.path);if(await yr(e,t,s),await wr(s)!==n.integrity)throw new b(`Invalid release ledger artifact for ${r}: sha512 integrity mismatch`)}async function Us(e,t){let r=await $t(t.repositoryRoot);for(let n of e.packages){let s=Ne(t.repositoryRoot,n.file),i;try{i=await dn(s)}catch(a){throw new b(`Invalid package manifest for ${n.name} at ${n.file}: ${j(a)}`)}if(!i.isFile()||i.isSymbolicLink())throw new b(`Invalid package manifest for ${n.name} at ${n.file}: expected a regular file`);let o=await $t(s);pn(r,o,`Package manifest for ${n.name} escapes the repository: ${n.file}`)}}async function yr(e,t,r){let n=await op(e,t),s;try{s=await dn(r)}catch(o){throw new b(`Invalid release artifact at ${r}: ${j(o)}`)}if(!s.isFile()||s.isSymbolicLink())throw new b(`Invalid release artifact at ${r}: expected a regular file`);let i=await $t(r);pn(n,i,`Release artifact escapes artifacts directory: ${r}`)}async function Go(e,t,r,n){let s=`${JSON.stringify(t,null,2)}
|
|
173
|
+
`,i=un(ln(e),`.${ww()}.json.tmp`),o=await cn(ln(e));try{if(await Pt(ln(e),"release directory"),r){await Cw(e,"active release ledger");let c;try{c=JSON.parse(await np(e,"utf-8"))}catch(l){throw new b(`Failed to read active release ledger at ${e} before writing: ${j(l)}`)}if(c.updatedAt!==n)throw new b("Active release ledger changed in another process")}let a=await Rw(i,"wx",384);try{await a.writeFile(s,"utf-8"),await a.sync()}finally{await a.close()}if(r)await vw(i,e);else{try{await bw(i,e)}catch(c){if(ne(c,"EEXIST"))throw new b(`Cannot create release ledger: active ledger already exists at ${e}`);throw c}await Pw(i)}await me(ln(e))}catch(a){await Ho(i,a,`Failed to clean temporary ledger file at ${i}`)}finally{await hr(o)}}async function Ho(e,t,r){try{await $w(e,{force:!0})}catch(n){throw AggregateError([t,n],r)}throw t}async function wr(e){let t;try{t=await np(e)}catch(r){throw new b(`Failed to read release artifact at ${e}: ${j(r)}`)}return`sha512-${rp("sha512").update(t).digest("base64")}`}async function Pt(e,t){let r;try{r=await dn(e)}catch(n){throw new b(`Invalid ${t} at ${e}: ${j(n)}`)}if(!r.isDirectory()||r.isSymbolicLink())throw new b(`Invalid ${t} at ${e}: expected a real directory`)}async function Cw(e,t){let r;try{r=await dn(e)}catch(n){throw new b(`Invalid ${t} at ${e}: ${j(n)}`)}if(!r.isFile()||r.isSymbolicLink())throw new b(`Invalid ${t} at ${e}: expected a regular file`)}async function Bt(e){try{return await dn(e),!0}catch(t){if(ne(t,"ENOENT"))return!1;throw t}}function gn(e,t){return Ne(e.artifactsRoot,on(t,"id"))}function qo(e,t,r){let n=`${rp("sha256").update(r).digest("hex")}.tgz`;return Ne(gn(e,t),n)}function Vs(e,t,r){return sp(e.releaseDirectory,qo(e,t,r)).split(Sw).join("/")}function Wo(e,t){let r=Ne(e.historyDirectory,`${on(t,"id")}.json`);if(ln(r)!==Ne(e.historyDirectory))throw new b(`Invalid release history path for ID ${t}`);return r}function pn(e,t,r){let n=sp(e,t);if(!n||de(n))throw new b(r)}import{isAbsolute as lp,relative as kw,resolve as xw}from"path";function Xo(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 up(e){return e.map((t,r)=>{let n=`create.packages[${r}]`,s=t.oldVersion??t.version;if(t.oldVersion!==void 0&&t.version!==void 0&&t.oldVersion!==t.version)P(n,"oldVersion and version must match when both are provided");return dp({file:t.file,isPrivate:t.isPrivate,name:t.name,newVersion:t.newVersion,oldVersion:s},n)})}function pp(e){return e.map((t,r)=>{let n=typeof t==="object"&&t!==null&&"toJson"in t&&typeof t.toJson==="function"?t.toJson():t,s;try{s=JSON.parse(JSON.stringify(n))}catch(i){throw new b(`Invalid release ledger at create.stones[${r}]: ${j(i)}`)}return mp(s,`create.stones[${r}]`)})}function Ut(e,t){let r=ie(e,"root");if(Ee(r,["schemaVersion","id","baseCommit","createdAt","updatedAt","phase","options","packages","releaseTags","tagsReady","stones","artifacts","operations"],["expectedReleaseTree","releaseCommit"],"root"),r.schemaVersion!==nn)P("schemaVersion",`unsupported schema version ${String(r.schemaVersion)}`);let n=on(r.id,"id"),s=br(r.baseCommit,"baseCommit"),i=Gs(r.createdAt,"createdAt"),o=Gs(r.updatedAt,"updatedAt");if(Date.parse(o)<Date.parse(i))P("updatedAt","must not precede createdAt");let a=gp(r.phase,fr,"phase","release phase"),c=Tw(r.options,"options"),l=Iw(r.packages,t.repositoryRoot),p=Ew(r.releaseTags,l,c),m=St(r.tagsReady,"tagsReady");if(!c.tags&&!m)P("tagsReady","must be true when tags are disabled");let g=Aw(r.stones),h=r.expectedReleaseTree===void 0?void 0:br(r.expectedReleaseTree,"expectedReleaseTree"),f=r.releaseCommit===void 0?void 0:br(r.releaseCommit,"releaseCommit"),y=_w(r.artifacts,l,t,n),R=Lw(r.operations,l,c,i,o),S={artifacts:y,baseCommit:s,createdAt:i,id:n,operations:R,options:c,packages:l,phase:a,releaseTags:p,schemaVersion:nn,stones:g,tagsReady:m,updatedAt:o};if(h!==void 0)S.expectedReleaseTree=h;if(f!==void 0)S.releaseCommit=f;if(c.tags&&m&&!f)P("tagsReady","cannot be true before releaseCommit is recorded");if(a==="completed")Qo(S);return S}function Ew(e,t,r){if(!Array.isArray(e))P("releaseTags","must be an array");let n=e.map((i,o)=>{let a=A(i,`releaseTags[${o}]`);return Ko(`refs/tags/${a}`,`releaseTags[${o}]`),a});if(new Set(n).size!==n.length)P("releaseTags","must not contain duplicates");let s=r.tags?t.map((i)=>`${i.name}@${i.newVersion}`).sort():[];if(JSON.stringify([...n].sort())!==JSON.stringify(s))P("releaseTags","must exactly match the release package versions when tags are enabled");return n}function Tw(e,t){let r=ie(e,t);return Ee(r,["changelog","createRelease","dryRun","npm","npmTag","publishOnly","push","tags"],[],t),{changelog:St(r.changelog,`${t}.changelog`),createRelease:St(r.createRelease,`${t}.createRelease`),dryRun:ea(r.dryRun),npm:St(r.npm,`${t}.npm`),npmTag:A(r.npmTag,`${t}.npmTag`),publishOnly:St(r.publishOnly,`${t}.publishOnly`),push:St(r.push,`${t}.push`),tags:St(r.tags,`${t}.tags`)}}function Iw(e,t){if(!Array.isArray(e)||e.length===0)P("packages","must be a nonempty array");let r=new Set,n=new Set;return e.map((s,i)=>{let o=`packages[${i}]`,a=dp(s,o);if(lp(a.file))P(`${o}.file`,"must be repository-relative");if(r.has(a.name))P(o,`duplicate package name ${a.name}`);let c=xw(t,a.file),l=kw(t,c);if(!l||de(l))P(`${o}.file`,"must resolve inside the repository");if(n.has(c))P(o,`duplicate package file ${a.file}`);return r.add(a.name),n.add(c),a})}function dp(e,t){let r=ie(e,t);Ee(r,["name","file","oldVersion","newVersion","isPrivate"],[],t);let n=A(r.file,`${t}.file`);if(n.includes("\x00"))P(`${t}.file`,"must not contain a null byte");return{file:n,isPrivate:St(r.isPrivate,`${t}.isPrivate`),name:A(r.name,`${t}.name`),newVersion:A(r.newVersion,`${t}.newVersion`),oldVersion:A(r.oldVersion,`${t}.oldVersion`)}}function Aw(e){if(!Array.isArray(e))P("stones","must be an array");let t=new Set;return e.map((r,n)=>{let s=mp(r,`stones[${n}]`);if(t.has(s.id))P(`stones[${n}].id`,`duplicate stone ID ${s.id}`);return t.add(s.id),s})}function mp(e,t){let r=ie(e,t);Ee(r,["id","message"],["tag","description","commits","major","minor","patch","dependency","snapshot"],t);let n={id:A(r.id,`${t}.id`),message:A(r.message,`${t}.message`)};if(r.tag!==void 0)n.tag=A(r.tag,`${t}.tag`);if(r.description!==void 0)n.description=sn(r.description,`${t}.description`);if(r.commits!==void 0)n.commits=Ow(r.commits,`${t}.commits`);for(let s of["major","minor","patch","dependency","snapshot"])if(r[s]!==void 0)n[s]=hp(r[s],`${t}.${s}`);return n}function Ow(e,t){if(!Array.isArray(e))P(t,"must be an array");return e.map((r,n)=>{let s=`${t}[${n}]`,i=ie(r,s);return Ee(i,["hash","subject","type","message","packages"],["body","scope"],s),{...{hash:A(i.hash,`${s}.hash`),message:A(i.message,`${s}.message`),packages:hp(i.packages,`${s}.packages`),subject:A(i.subject,`${s}.subject`),type:A(i.type,`${s}.type`)},...i.body===void 0?{}:{body:sn(i.body,`${s}.body`)},...i.scope===void 0?{}:{scope:A(i.scope,`${s}.scope`)}}})}function _w(e,t,r,n){let s=ie(e,"artifacts"),i=new Map(t.map((a)=>[a.name,a])),o=ot();for(let[a,c]of Object.entries(s)){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=ie(c,p);Ee(m,["path","integrity"],[],p);let g=A(m.path,`${p}.path`);if(lp(g))P(`${p}.path`,"must be relative to the release directory");let h=Vs(r,n,a);if(g!==h)P(`${p}.path`,`must be ${h}`);let f=A(m.integrity,`${p}.integrity`);if(!Gu.test(f))P(`${p}.integrity`,"must be a sha512 SRI value");je(o,a,{integrity:f,path:g})}return o}function Lw(e,t,r,n,s){let i=ie(e,"operations");Ee(i,["npm","npmRegistries","providerReleases"],["push"],"operations");let o=new Map(t.map((y)=>[y.name,y])),a=ie(i.npm,"operations.npm"),c=ot();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=Jo(R,`operations.npm.${y}`);zo(k,n,s,`operations.npm.${y}`),je(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=ie(i.npmRegistries,"operations.npmRegistries"),m=ot();for(let[y,R]of Object.entries(p)){if(!c[y])P(`operations.npmRegistries.${y}`,"references an unknown npm operation");je(m,y,ta(R,`operations.npmRegistries.${y}`))}let g;if(i.push!==void 0){if(!r.push&&!r.tags)P("operations.push","push and tags are disabled");let y=ie(i.push,"operations.push");Ee(y,["destination","remote","refs","state"],["startedAt","completedAt"],"operations.push");let R=Yo(y,"operations.push"),S=Jo(y,"operations.push",["destination","remote","refs"]);zo(S,n,s,"operations.push"),g={...R,...S}}let h=ie(i.providerReleases,"operations.providerReleases"),f=ot();for(let[y,R]of Object.entries(h)){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=ie(R,S);Ee(k,["tag","title","notes","state"],["startedAt","completedAt"],S);let ee=Zo(k,S),G=Jo(k,S,["tag","title","notes"]);zo(G,n,s,S),je(f,y,{...ee,...G})}return{npm:c,npmRegistries:m,providerReleases:f,...g?{push:g}:{}}}function Jo(e,t,r=[]){let n=ie(e,t);Ee(n,["state",...r],["startedAt","completedAt"],t);let s=gp(n.state,No,`${t}.state`,"operation state");if(s==="pending"){if(n.startedAt!==void 0||n.completedAt!==void 0)P(t,"pending operations cannot have timestamps");return{state:s}}let i=Gs(n.startedAt,`${t}.startedAt`);if(s==="started"){if(n.completedAt!==void 0)P(t,"started operations cannot have completedAt");return{startedAt:i,state:s}}let o=Gs(n.completedAt,`${t}.completedAt`);if(Date.parse(o)<Date.parse(i))P(t,"completedAt must not precede startedAt");return{completedAt:o,startedAt:i,state:s}}function Yo(e,t){let r=ie(e,t),n=Dw(r.destination,`${t}.destination`),s=A(r.remote,`${t}.remote`);if(!Hu.test(s)||s.includes("..")||s.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=ie(c,p);Ee(m,["source","destination","oid"],[],p);let g=Ko(m.source,`${p}.source`),h=Ko(m.destination,`${p}.destination`),f=A(m.oid,`${p}.oid`);if(!jt.test(f))P(`${p}.oid`,"must be a full 40- or 64-character git object ID");if(i.has(g))P(`${p}.source`,`duplicate source ref ${g}`);if(o.has(h))P(`${p}.destination`,`duplicate destination ref ${h}`);return i.add(g),o.add(h),{destination:h,oid:f,source:g}});return{destination:n,refs:a,remote:s}}function Dw(e,t){let r=ie(e,t);Ee(r,["canonicalUrl"],["owner","provider","repo"],t);let n=A(r.canonicalUrl,`${t}.canonicalUrl`),s;try{s=new URL(n)}catch{P(`${t}.canonicalUrl`,"must be an absolute credential-free URL")}let i=s.protocol==="ssh:"||s.protocol==="git+ssh:";if(s.password||s.username&&!i||s.search||s.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:n};if(o.some((c)=>c===void 0))P(t,"provider, owner, and repo must be set together");let a=A(r.provider,`${t}.provider`);if(a!=="github"&&a!=="gitlab"&&a!=="bitbucket")P(`${t}.provider`,"must be github, gitlab, or bitbucket");return{canonicalUrl:n,owner:A(r.owner,`${t}.owner`),provider:a,repo:A(r.repo,`${t}.repo`)}}function Zo(e,t){let r=ie(e,t);return{notes:sn(r.notes,`${t}.notes`),tag:A(r.tag,`${t}.tag`),title:A(r.title,`${t}.title`)}}function Hs(e,t,r){if(!Mw(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 Qo(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 ea(e){if(e!==!1)P("options.dryRun","durable ledgers require dryRun to be false");return!1}function ta(e,t){let r=A(e,t),n;try{n=new URL(r)}catch{P(t,"must be an absolute HTTP or HTTPS URL")}if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password||n.search||n.hash)P(t,"must be a credential-free HTTP or HTTPS URL");return n.href}function zo(e,t,r,n){if(e.state==="pending")return;let s=Date.parse(e.startedAt);if(s<Date.parse(t)||s>Date.parse(r))P(`${n}.startedAt`,"must be between createdAt and updatedAt");if(e.state==="completed"){let i=Date.parse(e.completedAt);if(i<s||i>Date.parse(r))P(`${n}.completedAt`,"must be between startedAt and updatedAt")}}function Ko(e,t){let r=A(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 gp(e,t,r,n){if(typeof e!=="string"||!t.includes(e))P(r,`unknown ${n} ${String(e)}`);return e}function fp(e){return fr.includes(e)}function Mw(e){return No.includes(e)}function ie(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))P(t,"must be an object");return e}function Ee(e,t,r,n){let s=new Set([...t,...r]);for(let i of t)if(!Object.hasOwn(e,i))P(n,`missing required key ${i}`);for(let i of Object.keys(e))if(!s.has(i))P(n,`unknown key ${i}`)}function St(e,t){if(typeof e!=="boolean")P(t,"must be a boolean");return e}function Gs(e,t){let r=A(e,t);if(!Ls(r))P(t,"must be a canonical ISO timestamp");return r}function br(e,t){let r=A(e,t);if(!jt.test(r))P(t,"must be a full 40- or 64-character git object ID");return r}function hp(e,t){if(!Array.isArray(e))P(t,"must be an array");return e.map((r,n)=>A(r,`${t}[${n}]`))}function ra(e){return new Date(Math.max(Date.now(),Date.parse(e)+1)).toISOString()}function ot(){return Object.create(null)}function je(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0})}class ge{value;paths;releaseDirectory;artifactsDirectory;activePath;active=!0;constructor(e,t){this.value=e;this.paths=t;this.releaseDirectory=t.releaseDirectory,this.artifactsDirectory=gn(t,e.id),this.activePath=t.activePath}static async create(e,t=process.cwd()){let r=await Vo(t);if(await Bt(r.activePath))throw new b(`Cannot create release ledger: active ledger already exists at ${r.activePath}`);if(await Bt(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 n=new Date().toISOString(),s=await Bun.$`git rev-parse HEAD`.cwd(r.repositoryRoot).quiet().nothrow(),i=s.stdout.toString().trim();if(s.exitCode!==0||!jt.test(i))throw new b("Cannot create release ledger: failed to resolve the current commit");let o=e.options.publishOnly?await ip(r.repositoryRoot,i):void 0,a=up(e.packages),c=pp(e.stones),l=Nw("sha256").update(JSON.stringify({baseCommit:i,options:e.options,packages:a,stones:c})).digest("hex"),p=ot(),m=e.options.tags?a.map((y)=>`${y.name}@${y.newVersion}`).sort():[];if(e.options.npm){for(let y of a)if(!y.isPrivate)je(p,y.name,{state:"pending"})}let g={artifacts:ot(),baseCommit:i,createdAt:n,id:l,operations:{npm:p,npmRegistries:ot(),providerReleases:ot()},options:{changelog:e.options.changelog,createRelease:e.options.createRelease,dryRun:ea(e.options.dryRun),npm:e.options.npm,npmTag:A(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:nn,stones:c,tagsReady:!e.options.tags,updatedAt:n};if(o)g.expectedReleaseTree=o;let h=Ut(g,r);if(await Us(h,r),await mn(r,l),await Bt(r.activePath))throw new b(`Cannot create release ledger: active ledger already exists at ${r.activePath}`);let f=Wo(r,l);if(await Bt(f))throw new b(`Release ${l} is already completed at ${f}`);return await Go(r.activePath,h,!1),new ge(h,r)}static async loadActive(e=process.cwd(),t={}){let r=await Vo(e),n;try{n=await yp(r.activePath)}catch(a){if(ne(a,"ENOENT")){if(await Bt(r.removingPath))throw new b(`Release cleanup is incomplete: an interrupted removal left ${r.removingPath}; delete it and its artifacts directory to finish cleanup`);return null}throw new b(`Failed to inspect active release ledger at ${r.activePath}: ${j(a)}`)}if(!n.isFile()||n.isSymbolicLink())throw new b(`Invalid active release ledger at ${r.activePath}: expected a regular file`);let s;try{s=await na(r.activePath,"utf-8")}catch(a){if(ne(a,"ENOENT"))return null;throw new b(`Failed to read active release ledger at ${r.activePath}: ${j(a)}`)}let i;try{i=JSON.parse(s)}catch(a){throw new b(`Failed to parse active release ledger at ${r.activePath}: ${j(a)}`)}let o=Ut(i,r);if(t.verifyFiles===!1)return new ge(o,r);return await Us(o,r),await mn(r,o.id),await cp(o,r),new ge(o,r)}get data(){return Ut(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(!fp(e))throw new b(`Cannot set release phase: unknown phase ${String(e)}`);if(e===this.value.phase)return;let t=fr.indexOf(this.value.phase);if(fr.indexOf(e)<t)throw new b(`Cannot move release phase backwards from ${this.value.phase} to ${e}`);let n=structuredClone(this.value);n.phase=e,await this.persist(n)}async setReleaseCommit(e){this.assertActive("set release commit");let t=br(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=br(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 n=this.value.operations.npm[e];if(!n)throw new b(`Cannot store an artifact for unconfigured npm package ${e}`);if(n.state!=="pending")throw new b(`Cannot replace artifact for ${e} after its npm operation has started`);if(Hw(t)!==".tgz")throw new b(`Cannot store artifact for ${e}: source must be a .tgz file`);let s;try{s=await Vw(t)}catch(p){throw new b(`Cannot read source artifact for ${e} at ${t}: ${j(p)}`)}if(!s.isFile())throw new b(`Cannot store artifact for ${e}: source is not a regular file`);await mn(this.paths,this.value.id);let i=qo(this.paths,this.value.id,e),o=qw(this.artifactsDirectory,`.${jw()}.tgz.tmp`),a;try{await Bw(t,o,Fw.COPYFILE_EXCL),await me(o),await yr(this.paths,this.value.id,o),a=await wr(o);try{await Uw(o,i)}catch(p){if(!ne(p,"EEXIST"))throw p;if(await yr(this.paths,this.value.id,i),await wr(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 bp(o,{force:!0}),await me(this.artifactsDirectory),await yr(this.paths,this.value.id,i)}catch(p){await Ho(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:Vs(this.paths,this.value.id,e)},l=structuredClone(this.value);return je(l.artifacts,e,c),await this.persist(l,e),{...c}}async verifyArtifact(e){let t=this.value.artifacts[e];if(!t)throw new b(`Release artifact is not configured for ${e}`);await Bs(this.paths,this.value.id,e,t)}resolveArtifactPath(e){let t=this.value.artifacts[e];if(!t)throw new b(`Release artifact is not configured for ${e}`);return Rp(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 n=Yo({destination:t,refs:r,remote:e},"configurePush"),s=this.value.operations.push;if(s){if(JSON.stringify([s.remote,s.destination,s.refs])===JSON.stringify([n.remote,n.destination,n.refs]))return;throw new b("Cannot replace an existing push configuration")}let i=structuredClone(this.value);i.operations.push={...n,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=Zo(t,`providerReleases.${e}`),n=this.value.operations.providerReleases[e];if(n){if(n.tag===r.tag&&n.title===r.title&&n.notes===r.notes)return;throw new b(`Cannot replace provider release configuration for ${e}`)}let s=structuredClone(this.value);je(s.operations.providerReleases,e,{...r,state:"pending"}),await this.persist(s)}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 n=structuredClone(this.value);je(n.operations.npm,e,Hs(r,t,this.operationTimestamp())),await this.persist(n)}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 n=ta(t,`operations.npmRegistries.${e}`),s=this.value.operations.npmRegistries[e];if(s===n)return;if(s)throw new b(`Cannot replace npm registry for ${e}`);let i=structuredClone(this.value);je(i.operations.npmRegistries,e,n),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,...Hs(t,e,this.operationTimestamp())},await this.persist(r)}async markPushNotApplied(){this.assertActive("mark push operation not applied");let e=this.value.operations.push;if(!e)throw new b("Push operation is not configured");if(e.state==="pending")return;if(e.state==="completed")throw new b("Cannot mark a completed push operation as not applied");let t=structuredClone(this.value);t.operations.push={destination:e.destination,refs:e.refs,remote:e.remote,state:"pending"},await this.persist(t)}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 n=structuredClone(this.value);je(n.operations.providerReleases,e,{notes:r.notes,tag:r.tag,title:r.title,...Hs(r,t,this.operationTimestamp())}),await this.persist(n)}hasExternalProgress(){return Xo(this.value)}async complete(){if(this.assertActive("complete"),this.value.phase!=="completed"){let r=structuredClone(this.value);Qo(r),r.phase="completed",await this.persist(r)}let e=Wo(this.paths,this.value.id),t=await cn(this.releaseDirectory);try{let r=await yp(this.activePath);if(!r.isFile()||r.isSymbolicLink())throw new b(`Invalid active release ledger at ${this.activePath}: expected a regular file`);let n=Ut(JSON.parse(await na(this.activePath,"utf-8")),this.paths);if(n.id!==this.value.id||n.updatedAt!==this.value.updatedAt||n.phase!=="completed")throw new b("Active release ledger changed in another process");if(await ap(this.paths),await Bt(e))throw new b(`Cannot complete release ${n.id}: history ledger already exists at ${e}`);await wp(this.activePath,e),await me(this.paths.historyDirectory),await me(this.releaseDirectory)}catch(r){if(r instanceof b)throw r;throw new b(`Failed to move completed release ${this.value.id} to history: ${j(r)}`)}finally{await hr(t)}return this.active=!1,e}async remove(){this.assertActive("remove");let e=await cn(this.releaseDirectory);try{await mn(this.paths,this.value.id);let t=Ut(JSON.parse(await na(this.activePath,"utf-8")),this.paths);if(t.id!==this.value.id||t.updatedAt!==this.value.updatedAt)throw new b("Active release ledger changed in another process");if(Xo(t))throw new b(`Cannot remove release ${t.id}: an external operation has started`);await wp(this.activePath,this.paths.removingPath),await me(this.releaseDirectory),await bp(this.artifactsDirectory,{force:!0,recursive:!0}),await Gw(this.paths.removingPath),await me(this.releaseDirectory)}catch(t){if(t instanceof b)throw t;throw new b(`Failed to remove release ${this.value.id}: ${j(t)}`)}finally{await hr(e)}this.active=!1}async persist(e,t){e.updatedAt=ra(this.value.updatedAt);let r=Ut(e,this.paths);await Us(r,this.paths);for(let[n,s]of Object.entries(r.artifacts)){let i=this.value.artifacts[n];if(i?.integrity===s.integrity&&i.path===s.path)continue;if(n===t){await yr(this.paths,r.id,Rp(this.releaseDirectory,s.path));continue}await Bs(this.paths,r.id,n,s)}await Go(this.activePath,r,!0,this.value.updatedAt),this.value=r}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 ra(this.value.updatedAt)}assertActive(e){if(!this.active)throw new b(`Cannot ${e}: release ledger ${this.value.id} is no longer active`)}}import{mkdtemp as tb,rm as rb}from"fs/promises";import{tmpdir as nb}from"os";import{join as xp}from"path";import{createHash as Jw}from"crypto";import{lstat as zw,realpath as vp}from"fs/promises";import{dirname as Kw,isAbsolute as Xw,relative as $p,resolve as sa,sep as Yw}from"path";async function C(e,t){try{return await e()}catch(r){let n=qs(r),s=n?`${t}: ${n}`:t;if(r instanceof u)throw new u(s,r.hint,r.exitCode,{cause:r,tag:r._tag});throw Error(s,{cause:r})}}function qs(e){let t=Ww(e);if(t)return t;return e instanceof Error?e.message:String(e)}function Ww(e){if(e&&typeof e==="object"&&"stderr"in e){let t=e.stderr;if(t instanceof Buffer)return t.toString().trim();if(typeof t==="string")return t.trim()}return}var Zw=3,Qw=/^[RC]|^.[RC]/;function Ke(e){return`:(top,literal)${e}`}async function Q(){let t=(await C(()=>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 Ws(){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 Rr(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 ia(e){let t=e.map((o)=>Ke(o)),[r,n,s]=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=Jw("sha256");for(let o of[r.stdout,n.stdout,s.stdout])i.update(String(o.length)),i.update("\x00"),i.update(o);return i.digest("hex")}function Pp(e,t){let r=Xw(t)?sa(t):sa(e,t),n=$p(e,r);if(!n||de(n))throw new u(`Release-owned path is outside the repository: ${t}`);return n.split(Yw).join("/")}async function Sp(e,t){let r=await vp(t);for(let n of e){let s=sa(t,n),i=await zw(s).catch(()=>null);if(i?.isSymbolicLink())throw new u(`Release-owned path is a symbolic link: ${n}`);let o=i?s:Kw(s),a=await vp(o);if(de($p(r,a)))throw new u(`Release-owned path escapes the repository: ${n}`)}}async function Js(e){let t=e.map((r)=>Ke(r));await C(()=>Bun.$`git reset --quiet HEAD -- ${t}`.quiet(),"Failed to unstage release-owned files")}async function Vt(e){if((await oa(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 oa(e){return await rn(e),(await C(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all --ignore-submodules=none`.cwd(e).quiet(),"Failed to inspect release source files")).stdout}async function Cp(e,t){let r=t.map((s)=>`:(exclude,top,literal)${s}`),n=await C(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all --ignore-submodules=none -- ${":/"} ${r}`.cwd(e).quiet(),"Failed to inspect release source files");return eb(n.stdout)}function eb(e){let t=e.toString().split("\x00").filter(Boolean),r=[];for(let n=0;n<t.length;n+=1){let s=t[n]??"";if(r.push(s.slice(Zw)),Qw.test(s))n+=1}return r}async function kp(e,t,r,n){let s=[];if(e)s.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}`);s.push(`delete refs/tags/${a} ${c}`)}if(s.length===0)return;let i=await n(),o=Buffer.from(["start",...s,"prepare","commit",""].join(`
|
|
174
|
+
`));await C(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 Ep(e,t,r){let n=await tb(xp(nb(),"sisyphus-index-")),s=xp(n,"index"),i={...process.env,GIT_INDEX_FILE:s},o=t.map((a)=>Ke(a));try{await C(()=>Bun.$`git read-tree ${e}`.cwd(r).env(i).quiet(),"Failed to initialize release tree"),await C(()=>Bun.$`git add -A -- ${o}`.cwd(r).env(i).quiet(),"Failed to build release tree");let c=(await C(()=>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 rb(n,{force:!0,recursive:!0})}}async function Tp(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 Q();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 Fe(e,t)}async function Ip(e){let{baseCommit:t,releaseCommit:r}=e;if(!r||r===t)return;if(await Q()!==t)return;if(!await sb(r)||!await ib())return;await Fe(e,r),await C(()=>Bun.$`git checkout --quiet --detach ${r}`.quiet(),`Failed to check out release commit ${r} from base commit ${t}`)}async function sb(e){return(await Bun.$`git cat-file -e ${`${e}^{commit}`}`.quiet().nothrow()).exitCode===0}async function ib(){return(await C(()=>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 Fe(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 aa(t,e.baseCommit,e.id);await ca(t,e.expectedReleaseTree,e.id)}async function aa(e,t,r){let n=await C(()=>Bun.$`git rev-list --parents -n 1 ${e}`.quiet(),"Failed to resolve release commit parent"),[s,...i]=n.stdout.toString().trim().split(/\s+/);if(s===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 ca(e,t,r){let n=await la(e);if(n===t)return;let s=r?` for release ${r}`:"";throw new u(`Release commit tree${s} is ${n}, expected ${t}`,"No external operation was attempted; inspect the release commit for unrelated tracked changes")}async function la(e){let t=`${e}^{tree}`,n=(await C(()=>Bun.$`git rev-parse ${t}`.quiet(),"Failed to resolve release commit tree")).stdout.toString().trim();if(!n)throw Error(`Git returned an empty tree object ID for ${e}`);return n}import{basename as ob}from"path";var ab="-o BatchMode=yes",cb="ssh",Ap="ssh",Op="auto",lb=/\.exe$/i,ub="core.sshcommand",pb="ssh.variant",db="^(core\\.sshcommand|ssh\\.variant)$",mb=new Set(["","0","false"]);function gb(e=process.env){let t=e.CI?.trim().toLowerCase();return t!==void 0&&!mb.has(t)}function zs(e,t){return _e(e)&&!t&&!gb()}async function fb(e,t,r=process.env){let n=_p(r);if(e)return n;let s=await hb(r,t);return{...n,GCM_INTERACTIVE:"never",GIT_TERMINAL_PROMPT:"0",...s?{GIT_SSH_COMMAND:s}:{}}}async function Ct(e,t,r){let n=await fb(t.interactive,t.cwd);return C(()=>{let s=Bun.$`git ${e}`.env(n).quiet();return t.cwd?s.cwd(t.cwd):s},r)}async function hb(e,t){let r=await wb(e,t),n=e.GIT_SSH_COMMAND?.trim()||r.command;if(!n&&e.GIT_SSH)return;let s=n||cb,i=e.GIT_SSH_VARIANT?.trim().toLowerCase()||r.variant||Op;return yb(s,i)?`${s} ${ab}`:void 0}function yb(e,t){if(t===Ap)return!0;if(t!==Op)return!1;let[r=""]=e.split(/\s+/);return ob(r).replace(lb,"").toLowerCase()===Ap}async function wb(e,t){let r=Bun.$`git config --get-regexp ${db}`.env(_p(e)).quiet().nothrow(),n=await(t?r.cwd(t):r);if(n.exitCode!==0)return{};let s={};for(let i of n.stdout.toString().split(`
|
|
175
|
+
`)){let o=i.indexOf(" ");if(o<0)continue;let a=i.slice(0,o).toLowerCase(),c=i.slice(o+1).trim();if(a===ub&&c)s.command=c;if(a===pb&&c)s.variant=c.toLowerCase()}return s}function _p(e){return Object.fromEntries(Object.entries(e).filter((t)=>t[1]!==void 0))}import{resolve as bb}from"path";import{pathToFileURL as Rb}from"url";async function fn(e,t,r){let n=Jr(e,r);return{canonicalUrl:await Lp(e,t),...n?{owner:n.owner,provider:n.provider,repo:n.repo}:{}}}async function Lp(e,t){let r=null;try{r=new URL(e)}catch{r=null}if(r){let s=r.protocol==="ssh:"||r.protocol==="git+ssh:";if(r.password||r.username&&!s)throw new u("Push URL contains embedded credentials","Configure git authentication outside the remote URL");return r.search="",r.hash="",r.href}let n=e.match(/^(?:([^@/\s]+)@)?([^:/\s]+):(.+)$/);if(n?.[2]&&n[3])return`ssh://${n[1]?`${n[1]}@`:""}${n[2].toLowerCase()}/${n[3].replace(/^\/+/,"")}`;return Rb(bb(await t(),e)).href}function Gt(e,t){if(!e?.provider||!e.owner||!e.repo)return;let{owner:r,provider:n,repo:s}=e,i=Jr(e.canonicalUrl,t);return i?.provider===n&&i.owner===r&&i.repo===s?i:{owner:r,provider:n,repo:s}}async function vr(e){let r=(await C(()=>Bun.$`git remote get-url --push --all ${e}`.quiet(),`Failed to resolve push URL for ${e}`)).stdout.toString().trim().split(`
|
|
176
|
+
`).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[n]=r;if(!n)throw new u(`Push remote ${e} has no URL`);return n}async function $r(e,t){let r=await vr(e.remote);if(await Lp(r,t)!==e.destination.canonicalUrl)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 pa(e){for(let t of e){let n=(await C(()=>Bun.$`git rev-parse ${t.source}`.quiet(),`Failed to resolve ${t.source}`)).stdout.toString().trim();if(n!==t.oid)throw new u(`Release ref ${t.source} points to ${n}, expected ${t.oid}`,"Do not move release refs before the release completes")}}async function Ks(e,t){let r=await $r(e,t.repositoryRoot),n=e.refs.map((s)=>`${s.oid}:${s.destination}`);await Ct(["push","--atomic",r,...n],{interactive:t.interactive},"Failed to atomically push release refs")}async function Dp(e,t,r=e.refs){let n=await da(e,r,t),s=r.find((i)=>n.get(i.destination)!==i.oid);if(s)throw new u(`Cannot safely resume remote push: ${s.destination} is not at ${s.oid}`,"The previous push may not have completed; inspect the remote refs manually")}async function da(e,t,r){let n=await $r(e,r.repositoryRoot),s=t.map((o)=>o.destination),i=await Ct(["ls-remote","--refs",n,...s],{interactive:r.interactive},"Failed to inspect remote release refs");return new Map(i.stdout.toString().trim().split(`
|
|
177
|
+
`).filter(Boolean).map((o)=>{let[a="",c=""]=o.split("\t");return[c,a]}))}async function hn(){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 Xs(){let e=await hn();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 yn(e)}}async function yn(e){let t=e?await ua(`branch.${e}.pushRemote`):null,r=await ua("remote.pushDefault"),n=e?await ua(`branch.${e}.remote`):null,s=t??r??n;if(!s){let o=(await C(()=>Bun.$`git remote`.quiet(),"Failed to list git remotes")).stdout.toString().trim().split(`
|
|
178
|
+
`).filter(Boolean);if(o.length===1&&o[0]==="origin")s="origin"}if(!s){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 C(()=>Bun.$`git remote get-url --push ${s}`.quiet(),`Invalid push remote ${s}`),s}async function ua(e){let t=await Bun.$`git config --get ${e}`.quiet().nothrow();if(t.exitCode===1)return null;if(t.exitCode!==0){let n=t.stderr.toString().trim();throw Error(n?`Failed to read git config ${e}: ${n}`:`Failed to read git config ${e}`)}let r=t.stdout.toString().trim();if(!r)throw Error(`Git config ${e} is empty`);return r}var vb=1,ma="ReleasePushNotApplied",$b=`No release ref reached the remote. Run ${T} roll --abort to discard the release commit and tags, update the branch and roll again; or fix the remote and run ${T} roll --resume to retry the push`;async function Ys(e,t){let r=await da(e,e.refs,t),n={diverged:[],landed:[],pending:[]};for(let s of e.refs){let i=r.get(s.destination);if(i===s.oid){n.landed.push(s);continue}if(!i){n.pending.push(s);continue}if(s.destination.startsWith("refs/heads/")){if(await Sb(i,e,t),await Mp(s.oid,i)){n.landed.push(s);continue}if(await Mp(i,s.oid)){n.pending.push(s);continue}}n.diverged.push(s)}return n}async function Np(e,t,r){let n=await Ys(t,r);if(n.landed.length===0){if(await e.markPushNotApplied(),n.diverged.length>0)throw Fp(t,Pb(n.diverged));return"not-applied"}let[s]=n.diverged;if(s)throw new u(`Cannot safely resume remote push: ${s.destination} is not at ${s.oid}`,"Part of the release push reached the remote and a ref has diverged since; inspect the remote refs manually before resuming");if(n.pending.length>0)await Ks({...t,refs:n.pending},r);return await e.markPush("completed"),"completed"}async function jp(e,t,r,n){let s;try{s=await Ys(t,r)}catch(i){return AggregateError([n,i],"The release push failed and the remote refs could not be inspected afterwards")}if(s.landed.length>0)return n;return await e.markPushNotApplied(),Fp(t,`Remote ${t.remote} rejected the release push`,n)}function Fp(e,t,r){return new u(`${t}; no release ref reached ${e.remote}`,$b,1,{cause:r,tag:ma})}function Pb(e){return`Remote refs diverged from the release: ${e.map((t)=>t.destination).join(", ")}`}async function Sb(e,t,r){if((await Bun.$`git cat-file -e ${`${e}^{commit}`}`.quiet().nothrow()).exitCode===0)return;let s=await $r(t,r.repositoryRoot);await Ct(["fetch","--no-tags","--no-write-fetch-head","--no-recurse-submodules",s,e],{interactive:r.interactive},"Failed to inspect the remote branch ancestry")}async function Mp(e,t){let r=await Bun.$`git merge-base --is-ancestor ${e} ${t}`.quiet().nothrow();if(r.exitCode===0)return!0;if(r.exitCode===vb)return!1;throw Error(`Failed to inspect remote branch ancestry: ${r.stderr.toString().trim()}`)}async function Bp(e){let t=await ge.loadActive(process.cwd(),{verifyFiles:!1});if(!t)throw new u("No incomplete release found","Nothing to abort");if(await kb(t,{interactive:e.interactive,repositoryRoot:Ab}),t.hasExternalProgress())throw new u(`Release ${t.id} already performed external operations`,`Run ${T} roll --resume to reconcile; a release whose push, publication or provider release may have reached its destination cannot be aborted`);let r=t.data,n=[],s=await Eb(r),i=await Tb(r,s,n),o=await Ib(r,s,n);return await t.remove(),{commitDiscarded:i,deletedTags:o,ledger:r,warnings:n}}async function kb(e,t){let r=e.data,n=r.operations.push;if(n?.state!=="started"||xb(r))return;let s;try{s=(await Ys(n,t)).landed.length}catch(i){throw new u(`Cannot confirm whether release ${r.id} reached ${n.remote}`,`Check the connection to the remote, then run ${T} roll --abort again, or run ${T} roll --resume to continue the release`,1,{cause:i})}if(s===0)await e.markPushNotApplied()}function xb(e){return[...Object.values(e.operations.npm),...Object.values(e.operations.providerReleases)].some((r)=>r.state!=="pending")}async function Eb(e){if(e.options.publishOnly)return e.baseCommit;if(e.releaseCommit)return e.releaseCommit;if(!e.expectedReleaseTree)return;let t=await Q();if(t===e.baseCommit)return;try{return await Fe(e,t),t}catch{return}}async function Tb(e,t,r){if(e.options.publishOnly)return!1;if(!t)return r.push(`No release commit was found, so local file changes since ${e.baseCommit} were kept; restore the release files from that commit if they belong to the abandoned release`),!1;let n=await Q();if(n!==t)return r.push(`Kept release commit ${t} because HEAD moved to ${n}; remove it manually if unwanted`),!1;let s=await Bun.$`git reset --quiet --keep ${e.baseCommit}`.quiet().nothrow();if(s.exitCode===0)return!0;throw new u(`Cannot discard release commit ${t}: ${s.stderr.toString().trim()||`git reset exited with code ${s.exitCode}`}`,`Commit or stash local changes to the release files, then run ${T} roll --abort again`)}async function Ib(e,t,r){let n=[];for(let s of e.releaseTags){let i=`refs/tags/${s}`,o=await Rr(i);if(!o)continue;if(o!==t){r.push(`Kept tag ${s} because it points to ${o}, not to the release commit`);continue}await C(()=>Bun.$`git update-ref -d ${i} ${o}`.quiet(),`Failed to delete release tag ${s}`),n.push(s)}return n}async function Ab(){let e=await C(()=>Bun.$`git rev-parse --show-toplevel`.quiet(),"Failed to resolve git repository root");return Cb(e.stdout.toString().trim())}import{readFile as Ob}from"fs/promises";import{dirname as Up}from"path";var _b=/^[A-Za-z][0-9A-Za-z._-]*$/,Lb=/-\d{14,}$/,Db=/^(?:[vV]?\d+(?:\.(?:\d+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?|[xX])$/;function Vp(e){return _b.test(e)&&!Db.test(e)}function Qs(e){let t=(e||ye).trim();if(!Vp(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 Ht(e,t){let r=Qs(t),n=new Set;for(let s of e){if(s.isPrivate)continue;let i=s.newVersion??s.version,o=De(i);if(!o)throw new u(`Cannot derive an npm dist-tag for ${s.name}@${i}`,"The version is not valid SemVer; fix it before publishing");if(o.prerelease.length===0){n.add(r);continue}let a=Mb(o);if(!a||!Vp(a))throw new u(`Cannot derive an npm dist-tag for ${s.name}@${i}`,"Use a prerelease identifier that is a valid npm dist-tag (e.g. beta, rc)");n.add(a)}if(n.size<=1)return[...n][0]??r;throw new u(`Release mixes npm dist-tags (${[...n].sort().join(", ")})`,"Roll stable and prerelease packages separately, or give every prerelease the same tag")}function Mb(e){let t=Kr(e);if(t)return t;let[r]=e.prerelease;if(typeof r!=="string")return;return r.replace(Lb,"")}function Gp(e){return e.startsWith("@")?e.split("/")[0]:void 0}function Pr(e,t){let r=Gp(e);return r?[`--${r}:registry=${t}`]:[]}async function ei(e){let t=Gp(e.name);if(t){let o=await Bun.$`npm config get ${`${t}:registry`}`.cwd(Up(e.file)).quiet().nothrow();if(o.exitCode===0){let a=o.stdout.toString().trim();if(a&&a!=="undefined"&&a!=="null"){let c=Zs(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 n=(await Hp(e)).publishConfig;if(n!==void 0){if(typeof n!=="object"||n===null||Array.isArray(n))throw new u(`Invalid publishConfig in ${e.name}`,"publishConfig must be an object");let o=Reflect.get(n,"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=Zs(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 s=process.env.NPM_CONFIG_REGISTRY??process.env.npm_config_registry;if(s){let o=Zs(s);if(o)return o}let i=await Bun.$`npm config get registry`.cwd(Up(e.file)).quiet().nothrow();if(i.exitCode===0){let o=i.stdout.toString().trim();if(o&&o!=="undefined"&&o!=="null"){let a=Zs(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 Zs(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 wn(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"),n=Reflect.get(t,"version"),s=Reflect.get(t,"dist");if(typeof s!=="object"||s===null||Array.isArray(s))return;let i=Reflect.get(s,"integrity");if(typeof r!=="string"||typeof n!=="string"||typeof i!=="string")return;return{integrity:i,name:r,version:n}}async function Hp(e){let t;try{t=await Ob(e.file,"utf-8")}catch(n){throw Error(`Failed to read ${e.name}: ${qs(n)}`)}let r;try{r=JSON.parse(t)}catch(n){throw Error(`Failed to parse ${e.name}: ${qs(n)}`)}if(typeof r!=="object"||r===null||Array.isArray(r))throw Error(`Invalid ${e.name} manifest object`);return r}async function bn(e){let t=[];for(let r of e){let s=(await Hp(r)).private;if(s!==void 0&&typeof s!=="boolean")throw Error(`Failed to validate ${r.name} manifest: "private" must be a boolean`);if(s)continue;t.push(r)}return t}function ti(e){try{return JSON.parse(e)}catch{return}}function ri(e,t,r){let n=t.newVersion??t.version;return{notes:jb(Nb(e,t.name),t,r),tag:`${t.name}@${n}`,title:`${t.name} v${n}`}}function Nb(e,t){return e.filter((r)=>r.affectsPackage(t))}function jb(e,t,r){let n=[],s=t.newVersion??t.version;if(n.push(`\`${t.name}\` ${t.version} \u2192 ${s}`),e.length===0)return n.join(`
|
|
179
|
+
`);n.push(""),n.push("<details>"),n.push(`<summary>Stones (${e.length})</summary>`),n.push("");for(let i of e){if(n.push(`### ${i.message}`),n.push(""),i.description)n.push(i.description),n.push("");let o=Fb(i.commits,t.name);if(o.length>0){n.push("<details>"),n.push(`<summary>Commits (${o.length})</summary>`),n.push("");for(let a of o)n.push(Bb(a,r));n.push(""),n.push("</details>"),n.push("")}}return n.push("</details>"),n.join(`
|
|
180
|
+
`)}function Fb(e,t){if(!e)return[];return e.filter((r)=>r.packages.includes(t))}function Bb(e,t){return`- ${t?`[\`${e.hash}\`](${t(e.hash)})`:`\`${e.hash}\``} ${e.subject}`}import{realpath as sd}from"fs/promises";import{join as dR,resolve as mR}from"path";import{rm as rR}from"fs/promises";import{isAbsolute as nR,resolve as Qp}from"path";var qt={isOutput:()=>!1};function qp(e){if(e.length===0)return qt;let t=e.flatMap((r)=>{let n=r.endsWith("/")?`${r}**`:r;if(n.endsWith("**"))return[new Bun.Glob(n)];return[new Bun.Glob(n),new Bun.Glob(`${n}/**`)]});return{isOutput:(r)=>t.some((n)=>n.match(r))}}import{cp as Ub,mkdir as Vb,mkdtemp as Gb,rename as Hb,rm as qb,writeFile as Wb}from"fs/promises";import{tmpdir as Jb}from"os";import{dirname as Jp,join as Wp,relative as ha,resolve as kt,sep as zb}from"path";function ga(e){let t=JSON.parse(e),r=Array.isArray(t)?t:typeof t==="object"&&t!==null?Object.values(t):[],[n]=r;return typeof n==="object"&&n!==null&&!Array.isArray(n)?n:void 0}var ni=512,Kb=100,Xb=124,Yb=12,Zb=345,Qb=155,eR="package/package.json",tR=20;async function zp(e,t){let r=Jp(t),n=await Bun.$`npm pack --ignore-scripts --json --pack-destination ${r}`.cwd(e).quiet(),s=ga(n.stdout.toString());if(typeof s?.filename!=="string"||!s.filename||typeof s.name!=="string"||!s.name||typeof s.version!=="string"||!s.version)throw Error("npm pack did not return a valid artifact identity");let i=kt(r,s.filename);if(de(ha(r,i)))throw Error("npm pack returned an artifact outside the destination directory");if(i!==kt(t))await Hb(i,t);return{name:s.name,version:s.version}}async function Kp(e,t){let r=await Bun.$`npm pack --dry-run --ignore-scripts --json`.cwd(t).quiet(),n=ga(r.stdout.toString())?.files;if(!Array.isArray(n))throw Error(`npm pack did not return a file list for ${e.name}`);return n.map((s)=>{if(typeof s!=="object"||s===null||Array.isArray(s)||!("path"in s))throw Error(`npm pack returned an invalid file entry for ${e.name}`);let i=s.path;if(typeof i!=="string"||!i)throw Error(`npm pack returned an invalid file path for ${e.name}`);if(de(ha(t,kt(t,i))))throw new u(`Package ${e.name} includes a file outside its directory: ${i}`);return i})}async function Xp(e,t,r){let n=await Kp(e,t),s=await Gb(Wp(Jb(),"sisyphus-package-stage-"));try{for(let i of n){let o=kt(s,i);await Vb(Jp(o),{recursive:!0}),await Ub(kt(t,i),o,{errorOnExist:!0,force:!1,recursive:!1,verbatimSymlinks:!0})}return await Wb(Wp(s,"package.json"),r,"utf-8"),s}catch(i){try{await qb(s,{force:!0,recursive:!0})}catch(o){throw AggregateError([i,o],"Failed to clean staged npm package")}throw i}}async function Yp(e,t,r,n=qt){let[s,i]=await Promise.all([Kp(e,t),ii(r)]);for(let o of s){let a=ha(r,kt(t,o)).split(zb).join("/");if(!i.has(a)&&!n.isOutput(a))throw new u(`Package ${e.name} includes an untracked or ignored pre-build file: ${o}`)}}async function ya(e,t){return(await Bun.$`git ls-files --others --ignored --exclude-standard -z`.cwd(e).quiet()).stdout.toString().split("\x00").filter(Boolean).filter((n)=>!n.split("/").includes("node_modules")).map((n)=>`${t}${n}`)}async function Rn(e,t,r=qt){let[n,s]=await Promise.all([ya(e,t),Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet()]),i=n.filter((o)=>!r.isOutput(o));if(i.length>0){let o=i.slice(0,tR),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
181
|
${o.join(`
|
|
162
182
|
`)}${a>0?`
|
|
163
|
-
...and ${a} more`:""}`)}for(let{mode:o,path:a}of
|
|
183
|
+
...and ${a} more`:""}`)}for(let{mode:o,path:a}of si(s.stdout.toString()))if(o==="160000")await Rn(kt(e,a),`${t}${a}/`,r)}function si(e){return e.split("\x00").filter(Boolean).map((t)=>{let r=t.indexOf("\t"),n=r<0?[]:t.slice(0,r).split(" "),[s,,i,...o]=n,a=r<0?"":t.slice(r+1);if(!s||!i||o.length>0||!a)throw Error("Unable to parse Git index while collecting tracked package inputs");return{mode:s,path:a,stage:i}})}async function ii(e,t=""){let r=await Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),n=new Set;for(let{mode:s,stage:i,path:o}of si(r.stdout.toString())){if(i!=="0")throw new u(`Repository has an unresolved index entry: ${o}`);let a=`${t}${o}`;if(n.add(a),s!=="160000")continue;let c=await ii(kt(e,o),`${a}/`);for(let l of c)n.add(l)}return n}async function vn(e){let t=new Uint8Array(await Bun.file(e).arrayBuffer()),r=Bun.gunzipSync(t),n=new TextDecoder;for(let s=0;s+ni<=r.length;){let i=fa(r,s,Kb,n);if(!i)break;let o=fa(r,s+Zb,Qb,n),a=o?`${o}/${i}`:i,c=fa(r,s+Xb,Yb,n).trim(),l=Number.parseInt(c,8);if(!Number.isSafeInteger(l)||l<0)throw Error(`Invalid tar entry size for ${a}`);let p=s+ni,m=p+l;if(m>r.length)throw Error(`Truncated tar entry for ${a}`);if(a===eR)return n.decode(r.subarray(p,m));s=p+Math.ceil(l/ni)*ni}throw Error("Packed artifact does not contain package/package.json")}function fa(e,t,r,n){let s=e.subarray(t,t+r),i=s.indexOf(0);return n.decode(i<0?s:s.subarray(0,i))}function Zp(e,t){return JSON.stringify(gr(JSON.parse(e)))===JSON.stringify(gr(JSON.parse(t)))}var sR="160000",iR="./",oR=50;function td(e){let t=e?.command??[...po],r=e?.root??[],n=e?.outputs??[];oi(t,"release.build.command"),oi(r,"release.build.root"),oi(n,"release.build.outputs"),ed(t,"release.build.command");for(let[s,i]of r.entries())if(oi(i,`release.build.root[${s}]`),ed(i,`release.build.root[${s}]`),i.length===0)throw new u(`Invalid release.build.root[${s}]`,'Each root build command must be a non-empty array of arguments, e.g. ["bun", "run", "build:dts"]');for(let s of n)if(!s||nR(s)||s.startsWith(iR)||lR(s))throw new u(`Invalid release.build.outputs entry: ${s||"(empty)"}`,"Build output globs must be relative to the repository root, e.g. packages/*/dist/**");if(n.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:qp(n),outputs:n,root:r}}async function ai(e,t){if(t===qt)return;let r=await ii(e);for(let n of r){if(!t.isOutput(n))continue;throw new u(`Declared build output ${n} is tracked by Git`,"Add it to .gitignore, or narrow release.build.outputs so it excludes committed files")}}async function wa(e,t,r){if(r===qt)return 0;let n=0;for(let i of await ya(e,t)){if(!r.isOutput(i))continue;await rR(Qp(e,i.slice(t.length)),{force:!0}),n+=1}let s=await Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet();for(let{mode:i,path:o}of si(s.stdout.toString())){if(i!==sR)continue;n+=await wa(Qp(e,o),`${t}${o}/`,r)}return n}async function ba(e,t,r){let n=cR(e,t,r),s,i,o;try{[s,i,o]=await Promise.all([n.exited,new Response(n.stderr).text(),new Response(n.stdout).text()])}catch(a){throw n.kill(),a}if(s!==0){let a=aR([i.trim(),o.trim()].filter(Boolean).join(`
|
|
184
|
+
`),oR),c=`${e.join(" ")} exited with code ${s} in ${t}`;throw Error(`${r}: ${c}${a?`
|
|
185
|
+
${a}`:""}`)}}function aR(e,t){return e.split(`
|
|
186
|
+
`).slice(-t).join(`
|
|
187
|
+
`)}function cR(e,t,r){try{return Bun.spawn([...e],{cwd:t,stderr:"pipe",stdout:"pipe"})}catch(n){throw Error(`${r}: ${n instanceof Error?n.message:String(n)}`)}}function oi(e,t){if(Array.isArray(e))return;throw new u(`Invalid ${t}`,`${t} must be an array`)}function lR(e){if(de(e))return!0;return e.split("/").includes("..")}function ed(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 uR,join as pR}from"path";function rd(e,t,r){let n=r.map((i)=>`- ${i.name}@${i.newVersion??i.version}`).join(`
|
|
164
188
|
`);return`${e.replace("{message}",()=>t.message).replace("{packages}",()=>r.map((i)=>i.name).join(", "))}
|
|
165
189
|
|
|
166
|
-
${s}`}function Ja(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 za(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)=>hm(gm(i.file),r));if(s)n.push(r);return n}import{mkdtemp as Pm,rm as Rm}from"fs/promises";import{tmpdir as Sm}from"os";import{join as tc}from"path";import{createHash as ym}from"crypto";import{lstat as wm,realpath as Ka}from"fs/promises";import{dirname as bm,isAbsolute as vm,relative as Ya,resolve as An,sep as $m}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=fm(e);if(t)return t;return e instanceof Error?e.message:String(e)}function fm(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 Xa(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=ym("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 Za(e,t){let r=vm(t)?An(t):An(e,t),s=Ya(e,r);if(!s||oe(s))throw new u(`Release-owned path is outside the repository: ${t}`);return s.split($m).join("/")}async function Qa(e,t){let r=await Ka(t);for(let s of e){let n=An(t,s),i=await wm(n).catch(()=>null);if(i?.isSymbolicLink())throw new u(`Release-owned path is a symbolic link: ${s}`);let o=i?n:bm(n),a=await Ka(o);if(oe(Ya(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 ec(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
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
`).
|
|
173
|
-
`)
|
|
174
|
-
`)
|
|
175
|
-
`)}function od(e,t){if(!e)return[];return e.filter((r)=>r.packages.includes(t))}function ad(e,t){return`- ${t?`[\`${e.hash}\`](${t(e.hash)})`:`\`${e.hash}\``} ${e.subject}`}import{createHash as bd,randomUUID as vd}from"crypto";import{constants as $d}from"fs";import{copyFile as Pd,link as Rd,lstat as Uc,readFile as ui,rename as Gc,rm as Hc,stat as Sd,unlink as Cd}from"fs/promises";import{extname as kd,join as xd,resolve as Td}from"path";import{isAbsolute as Lc,relative as cd,resolve as ld}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 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=pd(r.options,"options"),l=md(r.packages,t.repositoryRoot),p=ud(r.releaseTags,l,c),d=Ke(r.tagsReady,"tagsReady");if(!c.tags&&!d)P("tagsReady","must be true when tags are disabled");let h=dd(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=hd(r.artifacts,l,t,s),R=fd(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")oi(S);return S}function ud(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 pd(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 md(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=ld(t,a.file),l=cd(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 dd(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=gd(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 gd(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 hd(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 fd(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"),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,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:d,providerReleases:g,...h?{push:h}:{}}}function ei(e,t,r=[]){let s=Z(e,t);ye(s,["state",...r],["startedAt","completedAt"],t);let n=Fc(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=yd(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=ri(d.source,`${p}.source`),f=ri(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 yd(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(!wd(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 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 wd(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 Vc(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 vc(r.repositoryRoot,i):void 0,a=Mc(e.packages),c=Dc(e.stones),l=bd("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: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: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=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 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 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 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(kd(t)!==".tgz")throw new b(`Cannot store artifact for ${e}: source must be a .tgz file`);let n;try{n=await Sd(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=Wn(this.paths,this.value.id,e),o=xd(this.artifactsDirectory,`.${vd()}.tgz.tmp`),a;try{await Pd(t,o,$d.COPYFILE_EXCL),await ae(o),await gr(this.paths,this.value.id,o),a=await It(o);try{await Rd(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 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 Td(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 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 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 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 ui(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(si(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 Cd(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 dr(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 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=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 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:
|
|
176
|
-
${
|
|
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 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 rc(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(za(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 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 Mn(d,a),await Dn(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 Ed(pi(Ad(),"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 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=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 ec(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 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,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 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 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 _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,pi(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=Od(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(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 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 Id(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 Tn(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 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:va(e),workspaceVersions:Pa(t.values())}}return this.publishContext}crossIrreversibleBoundary(e){this.irreversibleOperation??=e}}import{dirname as _d}from"path";var Ld=1000,Md=5000;function mi(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 di(e,t){let r=t>0?Dd(e):[];if(r.length===0)return[];let s=Date.now()+t*Ld,n=new Map,i=r;while(i.length>0){for(let a of i)n.set(a.name,await Nd(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(Md,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 Dd(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:_d(t.file),integrity:r.integrity,name:t.name,registry:s,version:t.newVersion}]:[]})}async function Nd(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(jd(s.stdout.toString()));if(!n||n.name!==e.name||n.version!==e.version)return"pending";return n.integrity===e.integrity?"visible":"mismatch"}function jd(e){try{return JSON.parse(e)}catch{return}}var Fd=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 Jc(e,t){let r=t.map((o)=>`${o.name}@${o.newVersion??o.version}`),s=r.slice(0,Fd),n=r.length-s.length,i=n>0?` +${n} more`:"";return`${e} ${s.join(", ")}${i}`}var Bd=1;function zc(e){let{ledger:t}=e,r=t?Vd(t,e.npmVisibility??[]):Gd(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:qd(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:Bd,status:e.status,stones:t?t.stones.map((i)=>i.id):e.stones.map((i)=>i.id),tags:t?t.tagsReady?[...t.releaseTags]:[]:Hd(e.packages,e.tagsEnabled),warnings:[...e.warnings??[]]};if(e.changelogFiles)n.changelogFiles=[...e.changelogFiles];if(e.error!==void 0)n.error=Wd(e.error);return n}function Vd(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:Ud(t,r.name)}))}function Ud(e,t){let r=e.find((s)=>s.name===t);return r?r.state==="visible":null}function Kc(e,t){return`${e}@${t}`}function Gd(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 Hd(e,t){if(!t)return[];return e.map((r)=>Kc(r.name,r.newVersion??r.version)).sort()}function qd(e){let t=Object.values(e?.operations.providerReleases??{});return t.length>0&&t.every((r)=>r.state==="completed")}function Wd(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",fi="sisyphus-release",Jd="Sisyphus release PR",zd="6f42c1",Xc="chore(release):",Kd=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=Kd;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]
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
${
|
|
182
|
-
`)}
|
|
183
|
-
`)
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
`);
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
`);
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
190
|
+
${n}`}function ci(e){let{author:t,email:r}=e,n=t.trim(),s=r?.trim()??"";if(!n&&!s)return[];if(!n||!/^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/.test(s))throw new u("Invalid release commit author","Set valid commit.author and commit.email");return["--author",`${n} <${s}>`]}function nd(e){let{author:t,email:r}=e,n={...process.env};if(!t)return n;if(n.GIT_COMMITTER_NAME=t,r)n.GIT_COMMITTER_EMAIL=r;return n}function li(e,t){let{filename:r,root:n}=e,s=t.map((i)=>pR(uR(i.file),r));if(n)s.push(r);return s}var ui={interactive:!1};function pi(e,t,r){return{changelogGenerator:lr(e),commitUrlFn:null,config:e,irreversibleOperation:null,ledger:null,local:{commitCreated:!1,createdCommit:null,createdTagTargets:new Map,createdTags:[],ownedPaths:null,rollbackBlockedReason:null},npm:{buildConfig:null,buildOutputsPrepared:!1,ignoredBuildInputsValidated:!1,prepared:null,publishContext:null},options:t,packageUpdater:new Qr,provider:null,repositoryRoot:null,runtime:r,stoneManager:new B(e)}}async function J(e){if(e.repositoryRoot)return e.repositoryRoot;let r=(await C(()=>Bun.$`git rev-parse --show-toplevel`.quiet(),"Failed to resolve git repository root")).stdout.toString().trim();if(!r)throw Error("Git repository root is empty");return e.repositoryRoot=mR(r),e.repositoryRoot}function di(e){return{interactive:e.runtime.interactive,repositoryRoot:()=>J(e)}}async function id(e){let t=await J(e);if(await sd(process.cwd())===await sd(t))return;throw new u(`Releases must run from the Git repository root (${t})`,void 0,1,{tag:"NotRepositoryRoot"})}function Te(e,t){if(!e.ledger)throw Error(`Cannot ${t} without an active release ledger`);return e.ledger}function Sr(e,t){e.irreversibleOperation??=t}function Cr(e){return e.irreversibleOperation!==null||e.ledger?.hasExternalProgress()===!0}function Wt(e){return e.npm.buildConfig??=td(e.config.get("release")?.build),e.npm.buildConfig}function mi(e){return e.map((t)=>`${t.name}\x00${t.file}`).join("\x00")}async function $n(e,t,r){let n=await J(e),s=e.options.changelog?li(e.config.get("changelog"),t):[],i=[...t.map((c)=>c.file),...s,dR(ir,ds),...e.stoneManager.getFilePaths(r)],o=[...new Set(i.map((c)=>Pp(n,c)))].sort(),a=e.local.ownedPaths;if(a&&(a.length!==o.length||a.some((c,l)=>c!==o[l])))throw Error("Release paths changed");return e.local.ownedPaths=o,o}function gi(e,t){if(t instanceof u&&t._tag===ma)return t;let r=e.irreversibleOperation??"an external release operation",n=new u(`Release incomplete after ${r} began`,"Local state preserved; run sis roll --resume to reconcile and continue.");return n.cause=t,n}async function Pn(e){if(e.ledger)await e.ledger.complete()}async function Ra(e){if(!e.provider){let t=e.ledger?.data.operations.push?.destination,r=e.config.get("provider");e.provider=await yt(Gt(t,r),r)}return e.provider}async function va(e){if(e.commitUrlFn!==null)return;let t=e.ledger?.data.operations.push?.destination,r=e.config.get("provider"),n=Gt(t,r);if(n){e.commitUrlFn=bo(n);return}let s=await new Xr(r).getRemoteInfo();e.commitUrlFn=s?.commitUrl??null}async function fi(e,t,r){if(e.options.dryRun)return;if(r.length===0)return;await va(e);let n=await Ra(e),s=e.ledger?.data.operations.push;if(s){let i=s.refs.filter((o)=>o.destination.startsWith("refs/tags/"));if(i.length>0)await Dp(s,di(e),i)}for(let i of r){let o=ri(t,i,e.commitUrlFn),a=De(i.newVersion??i.version);await gR(e,n,i.name,o,a!==null&&Me(a))}}async function gR(e,t,r,n,s){let i=Te(e,`create the provider release for ${n.tag}`),o=i.data.operations.providerReleases[r];if(!o)throw Error(`Provider release is not configured for ${r}`);if(o.state==="completed")return;if(o.state==="started"){await fR(e,t,r,o);return}await i.setPhase("external"),await i.markProviderRelease(r,"started"),Sr(e,`git provider release creation for ${n.tag}`),await C(()=>t.createRelease({...n,prerelease:s}),`Failed to create release for ${n.tag}`),await i.markProviderRelease(r,"completed")}async function fR(e,t,r,n){let s=await C(()=>t.getRelease(n.tag),`Failed to inspect release for ${n.tag}`);if(!s)throw new u(`Cannot safely resume provider release ${n.tag}`,"The provider does not confirm the previous creation; inspect the release manually");if(s.draft||s.tag!==n.tag||s.title!==n.title||s.notes!==n.notes)throw new u(`Cannot safely resume provider release ${n.tag}: existing release does not match`,"Do not overwrite the existing release; compare its title and notes with the release ledger");await e.ledger?.markProviderRelease(r,"completed")}function hR(e,t){let{options:r}=e;return r.npm||r.push||r.createRelease||t&&r.tags}async function od(e,t,r,n){if(e.options.dryRun||!hR(e,n))return;e.ledger=await ge.create({options:{...e.options,npmTag:e.options.npm?Ht(t,e.config.get("tag")):ye,publishOnly:n},packages:t.map((s)=>({file:s.file,isPrivate:s.isPrivate,name:s.name,newVersion:s.newVersion,version:s.version})),stones:r})}async function ad(e,t,r){let{ledger:n}=e;if(!n)return;if(e.options.npm||n.data.options.publishOnly)await Vt(await J(e));let s=await Q();await ld(e,n.data,s),await Fe(n.data,s),await n.setReleaseCommit(s),await $a(e,t,r)}async function cd(e,t){let{ledger:r}=e;if(t.releaseCommit||!r)return;let n=await Q();if(!t.expectedReleaseTree&&!t.options.publishOnly)throw new u(`Release ${t.id} stopped before its expected release tree was recorded`,`No external operation was attempted; inspect the local changes and release ledger manually; delete ${r.activePath} to abort the release`);if(!t.options.publishOnly&&n===t.baseCommit)throw new u(`Release ${t.id} stopped before its release commit was created`,`No external operation was attempted; restore the release-owned files from ${t.baseCommit} and delete ${r.activePath} to abort the release`);await ld(e,t,n),await Fe(r.data,n),await r.setReleaseCommit(n)}async function $a(e,t,r){let{ledger:n}=e;if(!n)return;let s=n.data;if(await yR(e,s),s.options.npm)for(let i of t){if(!s.operations.npm[i.name]||s.operations.npmRegistries[i.name])continue;await n.setNpmRegistry(i.name,await ei(i))}if(!s.operations.push&&(s.options.push||s.options.publishOnly&&s.options.tags))await wR(e,s);if(s.options.createRelease){await va(e);for(let i of t)await n.configureProviderRelease(i.name,ri(r,i,e.commitUrlFn));await Ra(e)}}function hi(e,t){if(!e.options.createRelease||Gt(t))return;throw new u("Push destination is not a supported git provider repository","Provider releases require GitHub, GitLab, or Bitbucket")}async function yR(e,t){if(!e.ledger||!t.options.tags)return;if(!t.releaseCommit)throw Error("Cannot reconcile release tags without a release commit");for(let r of t.releaseTags){let n=`refs/tags/${r}`,s=await Bun.$`git rev-parse --verify ${n}`.quiet().nothrow();if(s.exitCode!==0){await C(()=>Bun.$`git -c tag.gpgSign=false tag -- ${r} ${t.releaseCommit}`.quiet(),`Failed to create tag ${r}`);continue}let i=s.stdout.toString().trim();if(i!==t.releaseCommit)throw new u(`Release tag ${r} points to ${i}, expected ${t.releaseCommit}`,"Do not move release tags before the release completes")}if(!t.tagsReady)await e.ledger.markTagsReady()}async function wR(e,t){let{ledger:r}=e;if(!r||!t.releaseCommit)throw Error("Cannot configure release push without a recorded release commit");let n=t.releaseCommit,s=()=>J(e),i=e.config.get("provider"),o=t.releaseTags.map((g)=>({destination:`refs/tags/${g}`,oid:n,source:`refs/tags/${g}`}));if(t.options.publishOnly){let g=await yn(await hn()),h=await fn(await vr(g),s,i);hi(e,h),await pa(o),await r.configurePush(g,h,o);return}let{branch:a,remote:c}=await Xs(),l=await fn(await vr(c),s,i);hi(e,l);let p=`refs/heads/${a}`,m=[{destination:p,oid:n,source:p},...o];await pa(m),await r.configurePush(c,l,m)}async function ld(e,t,r){if(t.expectedReleaseTree)return;if(!e.ledger||!t.options.publishOnly||r!==t.baseCommit)throw new u(`Release ${t.id} has no recorded expected release tree`,"No external operation was attempted; inspect the release state manually");await e.ledger.setExpectedReleaseTree(await la(t.baseCommit))}function Pa(e){return`${e.name}@${e.newVersion??e.version}`}async function ud(e,t,r,n){if(e.options.dryRun)return;let s=e.config.get("commit"),i=await $n(e,r,n),o=i.map((f)=>Ke(f)),a=rd(s.message,t,r),c=ci(s),l=e.ledger?.data.baseCommit??await Q(),p=await Ws(),m,g;try{if(await C(()=>Bun.$`git add -A -- ${o}`.quiet(),"Failed to stage release files"),await Q()!==l)throw new u("Release base commit changed before commit creation","Restart the release from the intended branch");m=await Ep(l,i,await J(e)),await e.ledger?.setExpectedReleaseTree(m),g=await ia(i),await C(()=>Bun.$`git commit --only ${c} -m ${a} -- ${o}`.env(nd(s)).quiet(),"Failed to create commit"),e.local.commitCreated=!0}catch(f){throw await bR(e,i,g,f),f}let h=await Q();if(e.local.createdCommit={baseCommit:l,oid:h,ref:p},!m)throw Error("Expected release tree was not recorded before commit");if(e.ledger){await Fe(e.ledger.data,h);return}await aa(h,l),await ca(h,m)}async function bR(e,t,r,n){if(r){let s;try{s=await ia(t)}catch(i){throw e.local.rollbackBlockedReason="release files could not be verified after commit failure",AggregateError([n,i],"Commit failed and release files could not be verified")}if(s!==r)throw e.local.rollbackBlockedReason="release-owned files changed while commit hooks ran",AggregateError([n],"Commit failed after a hook changed release-owned files")}try{await Js(t)}catch(s){throw AggregateError([n,s],"Commit and index cleanup failed")}}async function pd(e,t){if(e.options.dryRun)return;let r=await Q();for(let n of t){let s=Pa(n);await C(()=>Bun.$`git -c tag.gpgSign=false tag -- ${s}`.quiet(),`Failed to create tag ${s}`),e.local.createdTags.push(s),e.local.createdTagTargets.set(s,r)}}import{mkdtemp as CR,readFile as kR,rm as yd}from"fs/promises";import{tmpdir as xR}from"os";import{dirname as ER,join as hd}from"path";var dd=Qt().map((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:K()),RR=dd.map(nt({publishConfig:dd.map(nt({access:Le(["public","restricted"]).or(He())})).or(He())}));function Sn(e){try{return RR(JSON.parse(e)).publishConfig?.access??"public"}catch(t){throw Error("Invalid publishConfig.access: expected public or restricted",{cause:t})}}import{dirname as vR}from"path";var $R=/\bE404\b/,PR=/cannot publish over|EPUBLISHCONFLICT/i;function md(e,t){let r=e.newVersion??e.version,n=`${e.name}@${r}`,s=Bun.$`npm view ${n} --json --registry ${t} ${Pr(e.name,t)}`.cwd(vR(e.file)).quiet().nothrow();return{packageSpec:n,version:r,view:s}}async function gd(e,t,r){let{packageSpec:n,version:s,view:i}=md(e,t),o=await i;if(o.exitCode!==0)return;let a=wn(ti(o.stdout.toString()));if(a?.version!==s||a.name!==e.name||a.integrity===r)return;throw new u(`${n} is already published on ${t} with a different artifact`)}async function fd(e,t,r){let n=e.data.artifacts[t.name];if(!n)throw Error(`Release artifact is missing for ${t.name}`);let s=e.data.operations.npmRegistries[t.name];if(!s)throw Error(`Npm registry is not configured for ${t.name}`);let{packageSpec:i,version:o,view:a}=md(t,s),c=await a;if(c.exitCode!==0){if(!$R.test(`${c.stdout.toString()}
|
|
191
|
+
${c.stderr.toString()}`))throw new u(`Cannot safely resume npm publication for ${i}: ${s} did not confirm whether it exists`,"Check the registry connectivity and authentication, then re-run sis roll --resume");await SR(e,t,i,s,r);return}let l;try{l=JSON.parse(c.stdout.toString())}catch{throw new u(`Cannot safely resume npm publication for ${i}`,"Registry metadata is not valid JSON")}let p=wn(l);if(!p)throw new u(`Cannot safely resume npm publication for ${i}`,"Registry metadata does not report name, version, and dist.integrity; verify the upload manually");if(p.name!==t.name||p.version!==o||p.integrity!==n.integrity)throw new u(`Cannot safely resume npm publication for ${i}: 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 SR(e,t,r,n,s){let i=e.resolveArtifactPath(t.name);if(await wr(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 s()}catch(o){if(o instanceof Error&&PR.test(o.message))throw new u(`${r} was already accepted by ${n} 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")}var TR=4;async function kr(e,t){if(e.options.dryRun)return;let r=mi(t);if(e.npm.prepared?.key===r)return;let n=Te(e,"prepare npm artifacts");e.npm.prepared=null;let s=await bn(t);if(s.length===0){e.npm.prepared={key:r,packages:[]};return}if(s.some((a)=>!n.data.artifacts[a.name]))await OR(e);let i=await CR(hd(xR(),"sisyphus-publish-")),o=[];try{for(let[a,c]of s.entries()){if(!n.data.artifacts[c.name]){let p=hd(i,`${String(a).padStart(TR,"0")}.tgz`);await C(()=>AR(e,c,p),`Failed to prepare ${c.name}`),await n.setArtifact(c.name,p)}let l=n.resolveArtifactPath(c.name);Sn(await vn(l)),await IR(n,c),o.push({artifactPath:l,pkg:c})}}finally{await yd(i,{force:!0,recursive:!0})}e.npm.prepared={key:r,packages:o}}async function IR(e,t){if(e.data.operations.npm[t.name]?.state!=="pending")return;let r=e.data.operations.npmRegistries[t.name],n=e.data.artifacts[t.name]?.integrity;if(!r||!n)return;await gd(t,r,n)}async function Ca(e,t){let r=Te(e,"bind npm artifacts to a release commit").data;if(!r.releaseCommit||!r.expectedReleaseTree||t!==r.releaseCommit)throw new u(`Publish source does not match the recorded release commit for ${r.id}`,r.releaseCommit?`Check out ${r.releaseCommit} before publishing`:"Resume the release before publishing");await Fe(r,t)}async function Sa(e,t,r,n){let s=await Q();await Ca(e,s);let i=await oa(await J(e));if(s===t&&i.length===0)return;throw new u(r,n)}async function AR(e,t,r){let n=ER(t.file),s=await J(e),i=null;try{let o=await Q();await Ca(e,o),await Vt(s),await wd(e);let a=Wt(e);if(await Yp(t,n,s,a.matcher),a.command.length>0)await ba(a.command,n,`Failed to build ${t.name}`);await Sa(e,o,`Package build changed repository source files for ${t.name}`,"This package was not packed and nothing was published; restore the build changes before retrying");let c=await kR(t.file,"utf-8"),{catalogs:l,workspaceVersions:p}=await _R(e),m=_u(c,l,p);Sn(m);let g=JSON.parse(m),h=t.newVersion??t.version;if(g.name!==t.name||g.version!==h)throw Error(`Packed manifest identity mismatch for ${t.name}: expected ${t.name}@${h}, found ${String(g.name)}@${String(g.version)}`);i=await Xp(t,n,m);let f=await zp(i,r);if(f.name!==t.name||f.version!==h)throw new u(`Packed artifact identity mismatch for ${t.name}: found ${f.name}@${f.version}`,"This package was not recorded and nothing was published");if(!Zp(m,await vn(r)))throw new u(`Packed manifest does not match the prepared manifest for ${t.name}`,"This package was not recorded and nothing was published");await Sa(e,o,`Package packing changed repository source files for ${t.name}`,"This package was not recorded and nothing was published; restore the changes before retrying")}finally{if(i)await yd(i,{force:!0,recursive:!0})}}async function wd(e){if(e.npm.ignoredBuildInputsValidated)return;await Rn(await J(e),"",Wt(e).matcher),e.npm.ignoredBuildInputsValidated=!0}async function OR(e){if(e.npm.buildOutputsPrepared)return;let t=Wt(e),r=await J(e),n=await Q();await Ca(e,n),await Vt(r),await ai(r,t.matcher),await wa(r,"",t.matcher);for(let[s,i]of t.root.entries())await ba(i,r,`Failed to run release root build command ${s}`);if(t.root.length>0)await Sa(e,n,"Root build changed repository source files","No package was packed and nothing was published; restore the build changes before retrying");await wd(e),e.npm.buildOutputsPrepared=!0}async function _R(e){if(!e.npm.publishContext){let t=await Bun.file("package.json").json(),{packages:r}=await U.scan({single:e.config.get("single")});e.npm.publishContext={catalogs:Iu(t),workspaceVersions:Ou(r.values())}}return e.npm.publishContext}import{dirname as LR}from"path";async function yi(e,t){if(e.options.dryRun)return;if(e.npm.prepared?.key!==mi(t))await kr(e,t);let r=e.npm.prepared?.packages??[];if(r.length===0)return;try{for(let n of r)await DR(e,n)}finally{e.npm.prepared=null}}async function DR(e,t){let r=Te(e,`publish ${t.pkg.name}`),n=r.data.operations.npm[t.pkg.name];if(!n)throw Error(`Npm operation is not configured for ${t.pkg.name}`);if(n.state==="completed")return;if(n.state==="started"){await fd(r,t.pkg,()=>bd(e,t));return}await r.verifyArtifact(t.pkg.name),await r.setPhase("external"),await r.markNpm(t.pkg.name,"started"),Sr(e,"npm publication"),await bd(e,t),await r.markNpm(t.pkg.name,"completed")}async function bd(e,t){let r=Te(e,`publish ${t.pkg.name}`),n=r.data.options.npmTag,s=Sn(await vn(t.artifactPath)),i=r.data.operations.npmRegistries[t.pkg.name];if(!i)throw Error(`Npm registry is not configured for ${t.pkg.name}`);let o=Pr(t.pkg.name,i);await C(()=>Bun.$`npm publish ${t.artifactPath} --tag ${n} --access ${s} --ignore-scripts --registry ${i} ${o}`.cwd(LR(t.pkg.file)).quiet(),`Failed to publish ${t.pkg.name}`)}var ka=20,Rd={publishOnly:!1};async function xa(){let e=await ge.loadActive(process.cwd(),{verifyFiles:!1});if(!e)return;throw new u(`Release ${e.id} is incomplete`,"Run sis roll --resume before starting another release")}async function vd(e,t,r,n=Rd){for(let s of Pd(e,t,r,n))await s()}async function $d(e,t,r,n=Rd){let s=[];for(let i of Pd(e,t,r,n))try{await i()}catch(o){let a=GR(o);if(!s.some((c)=>c.message===a.message&&c.hint===a.hint))s.push(a)}return s}function Pd(e,t,r,n){let{options:s}=e,i=!n.publishOnly,o=i&&s.commit!==!1,a=n.publishOnly?s.tags:s.push;return[()=>xa(),()=>id(e),o&&(async()=>void ci(e.config.get("commit"))),s.npm&&(async()=>FR(e,t)),i&&(()=>MR(e,t,r)),s.tags&&(()=>NR(t)),a&&(()=>jR(e,n)),s.npm&&(()=>BR(e,t,r,n)),s.npm&&(()=>UR(e,t)),s.npm&&(()=>VR(e,t))].filter((l)=>l!==!1)}async function MR(e,t,r){let n=await $n(e,t,r);await Sp(n,await J(e));let s=n.map((o)=>Ke(o));if((await C(()=>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:
|
|
192
|
+
${n.join(`
|
|
193
|
+
`)}`)}async function NR(e){let t=[];for(let r of e){let n=Pa(r);if(await Rr(`refs/tags/${n}`))t.push(n)}if(t.length===0)return;throw new u(`Release tags already exist: ${t.join(", ")}`,"Delete the stale tags or bump to versions that have not been released",1,{tag:"ReleaseTagExists"})}async function jR(e,t){let r=t.publishOnly?await yn(await hn()):(await Xs()).remote,n=e.config.get("provider"),s=()=>J(e),i=await fn(await vr(r),s,n);if(hi(e,i),!e.options.createRelease)return;e.provider??=await yt(Gt(i,n),n)}function FR(e,t){Ht(t,e.config.get("tag")),Wt(e)}async function BR(e,t,r,n){for(let l of await bn(t))await ei(l);let s=await J(e),i=n.publishOnly?[]:await $n(e,t,r);await rn(s);let o=await Cp(s,i);if(o.length===0)return;let a=o.slice(0,ka).join(`
|
|
194
|
+
`),c=o.length>ka?`
|
|
195
|
+
...and ${o.length-ka} more`:"";throw new u("Repository has uncommitted changes outside the release files",`Npm releases pack committed source only; commit or stash these files first:
|
|
196
|
+
${a}${c}`)}async function UR(e,t){let r=await Sd(e,t);if(!r)return;await ai(await J(e),r)}async function VR(e,t){let r=await Sd(e,t);if(!r)return;await Rn(await J(e),"",r)}async function Sd(e,t){return(await bn(t)).length===0?void 0:Wt(e).matcher}function GR(e){let t=e instanceof Error?e.message:String(e),r=e instanceof u?e.hint:void 0;return r?{hint:r,message:t}:{message:t}}async function wi(e){let t=Te(e,"push release refs"),r=t.data.operations.push;if(!r)throw Error("Release push is not configured");if(r.state==="completed")return;let n=di(e);if(await $r(r,n.repositoryRoot),r.state==="started"&&await Np(t,r,n)==="completed")return;await t.setPhase("external"),await t.markPush("started"),Sr(e,"remote push");try{await Ks(r,n)}catch(s){throw await jp(t,r,n,s)}await t.markPush("completed")}function HR(e){return e instanceof u&&e._tag!==We}async function Cd(e,t){let r=await ge.loadActive();if(!r)throw new u("No incomplete release found","Run sis roll to start a release");let n=r.data,s=pi(e,n.options,t);s.ledger=r;let i=n.packages.map((a)=>new z({file:a.file,isPrivate:a.isPrivate,name:a.name,newVersion:a.newVersion,version:a.oldVersion})),o=n.stones.map((a)=>O.fromJson(a));if(s.local.createdTags=[...n.releaseTags],n.phase==="completed")return await r.complete(),{ledger:r.data,packages:i,stones:o};try{if(await cd(s,n),await Ip(r.data),await Tp(r.data),await $a(s,i,o),n.options.npm){if(i.some((c)=>r.data.operations.npm[c.name]&&!r.data.artifacts[c.name]))await Vt(await J(s));await kr(s,i)}if(r.phase==="planned")await r.setPhase("local-ready");return await qR(s,i,o),{ledger:r.data,packages:i,stones:o}}catch(a){if(HR(a)||!Cr(s))throw a;throw gi(s,a)}}async function qR(e,t,r){let n=Te(e,"resume external operations");if(n.phase==="completed"){await Pn(e);return}if(n.data.operations.push)await wi(e);if(e.options.npm)await yi(e,t);if(e.options.createRelease)await fi(e,r,t);await Pn(e)}var Cn="Local release state and the recovery ledger were preserved";async function kd(e,t){if(Cr(e))return!1;await WR(e);let{local:r}=e;if(e.npm.prepared=null,await kp(r.createdCommit,r.createdTags,r.createdTagTargets,()=>J(e)),r.commitCreated){if(r.ownedPaths)await Js(r.ownedPaths);r.commitCreated=!1,r.createdCommit=null}if(r.createdTags=[],r.createdTagTargets.clear(),await e.changelogGenerator.rollback(),await e.packageUpdater.rollback(),t)await Ea(e);return!0}async function Ea(e){if(!e.ledger)return;await e.ledger.remove(),e.ledger=null}async function WR(e){let{local:t}=e;if(t.rollbackBlockedReason)throw new u(`Cannot roll back release because ${t.rollbackBlockedReason}`,Cn);if(t.commitCreated&&!t.createdCommit)throw new u("Cannot identify the release commit for rollback",Cn);if(t.commitCreated&&t.createdCommit){let[r,n]=await Promise.all([Q(),Ws()]);if(r!==t.createdCommit.oid||n!==t.createdCommit.ref)throw new u(`Cannot roll back release commit because HEAD changed from ${t.createdCommit.oid}`,Cn)}if(t.commitCreated&&t.ownedPaths){let r=t.ownedPaths.map((s)=>Ke(s));if((await C(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${r}`.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",Cn)}for(let r of t.createdTags){let n=t.createdTagTargets.get(r),s=await Rr(`refs/tags/${r}`);if(!n||s!==n)throw new u(`Cannot roll back release because tag ${r} changed after creation`,Cn)}}class Be{session;constructor(e,t,r=ui){this.session=pi(e,t,r)}static async assertNoActiveRelease(){await xa()}static async resume(e,t=ui){return Cd(e,t)}static async abort(e=ui){return Bp(e)}async preflight(e,t,r){await vd(this.session,e,t,r)}async inspectPreflight(e,t,r){return $d(this.session,e,t,r)}async initializeExternalRelease(e,t,r){await od(this.session,e,t,r)}async updatePackageVersions(e){if(this.session.options.dryRun)return;await this.session.packageUpdater.updateAll(e)}async generateChangelogs(e,t){if(this.session.options.dryRun)return;await this.session.changelogGenerator.generate(e,t)}async createCommit(e,t,r){await ud(this.session,e,t,r)}async createGitTags(e){await pd(this.session,e)}async finalizeExternalRelease(e,t){await ad(this.session,e,t)}async prepareNpmPublish(e){await kr(this.session,e)}async markExternalReleaseReady(){if(this.session.ledger)await this.session.ledger.setPhase("local-ready")}async pushRelease(){if(this.session.options.dryRun)return;await wi(this.session)}async publishToNpm(e){await yi(this.session,e)}async createGitRelease(e,t){await fi(this.session,e,t)}async completeRelease(){await Pn(this.session)}hasCrossedIrreversibleBoundary(){return Cr(this.session)}createIncompleteReleaseError(e){return gi(this.session,e)}async rollback(e=!0){return kd(this.session,e)}async removeReleaseLedger(){await Ea(this.session)}getLedgerSnapshot(){return this.session.ledger?.data??null}}import{dirname as JR}from"path";var zR=1000,KR=5000,XR=5000,YR="E404";function Ta(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 Ia(e,t){let r=t>0?ZR(e):[];if(r.length===0)return[];let n=Date.now()+t*zR,s=new Map,i=r;while(i.length>0){let o=await Promise.all(i.map((c)=>QR(c,n)));for(let[c,l]of i.entries()){let p=o[c];if(p)s.set(l.name,p)}i=i.filter((c)=>s.get(c.name)?.state==="pending");let a=n-Date.now();if(i.length===0||a<=0)break;await Bun.sleep(Math.min(KR,a))}return r.map(({name:o,registry:a,version:c})=>{let l=s.get(o)??{state:"pending"};return{name:o,registry:a,version:c,...l}})}function Aa(e,t){return e.filter((r)=>r.state!=="visible").map((r)=>{let n=`${r.name}@${r.version}`;if(r.state==="mismatch")return`${n} on ${r.registry} does not match the integrity of the published artifact`;if(r.state==="error")return`${n} could not be checked on ${r.registry}: ${r.detail}`;return`${n} is not visible on ${r.registry} after ${t}s; npm may still be processing or holding it`})}function ZR(e){return e.packages.flatMap((t)=>{let r=e.artifacts[t.name],n=e.operations.npmRegistries[t.name];return e.operations.npm[t.name]?.state==="completed"&&r&&n?[{cwd:JR(t.file),integrity:r.integrity,name:t.name,registry:n,version:t.newVersion}]:[]})}async function QR(e,t){let r=`${e.name}@${e.version}`,n=Math.max(t-Date.now(),XR),s=Bun.spawn(["npm","view",r,"--json","--prefer-online","--registry",e.registry,...Pr(e.name,e.registry),`--fetch-timeout=${n}`,"--fetch-retries=0"],{cwd:e.cwd,stderr:"pipe",stdin:"ignore",stdout:"pipe",timeout:n}),[i,o,a]=await Promise.all([s.exited,new Response(s.stdout).text(),new Response(s.stderr).text()]);if(s.signalCode||i!==0&&`${o}${a}`.includes(YR))return{state:"pending"};if(i!==0)return{detail:a.trim().split(`
|
|
197
|
+
`)[0]||`exit ${i}`,state:"error"};let c=wn(ti(o));if(!c||c.name!==e.name||c.version!==e.version)return{state:"pending"};return{state:c.integrity===e.integrity?"visible":"mismatch"}}var ev=6;function xr(e,t){let r=e.map((n)=>vo(n,t));return{skipped:[...new Set(r.flatMap((n)=>n.skipped))].sort(),stones:r.map((n)=>n.stone)}}function kn(e,t,r){let n=[...new Set(e.allPackages)].filter((s)=>!t.has(s)&&!se(s,r)).sort();if(n.length>0)return{kind:"unknown-packages",names:n};return{kind:"ignored-only"}}function Oa(e,t,r,n){let{stone:s}=vo(e,r),i=kn(s,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(s,t,n).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 xd(e,t){let r=t.map((o)=>`${o.name}@${o.newVersion??o.version}`),n=r.slice(0,ev),s=r.length-n.length,i=s>0?` +${s} more`:"";return`${e} ${n.join(", ")}${i}`}var tv=1;function Ed(e){let{ledger:t}=e,r=t?rv(t,e.npmVisibility??[]):sv(e.packages),n=r.filter((i)=>i.published).map((i)=>({name:i.name,version:i.newVersion})),s={baseCommit:t?.baseCommit??null,command:"roll",mode:e.mode,operations:{npmTag:t?.options.npmTag??e.npmTag,providerReleases:av(t),pushed:t?.operations.push?.state==="completed"},packages:r,published:n.length>0,publishedPackages:n,releaseCommit:e.abort?.commitDiscarded?null:t?.releaseCommit??e.releaseCommit??null,releaseId:t?.id??null,schemaVersion:tv,status:e.status,stones:t?t.stones.map((i)=>i.id):e.stones.map((i)=>i.id),tags:ov(t?t.tagsReady?[...t.releaseTags]:[]:iv(e.packages,e.tagsEnabled),e.abort),warnings:[...e.warnings??[]]};if(e.abort)s.abort={commitDiscarded:e.abort.commitDiscarded,deletedTags:[...e.abort.deletedTags]};if(e.blockers)s.blockers=e.blockers.map((i)=>({...i}));if(e.preview)s.preview={changelogs:e.preview.changelogs.map((i)=>({...i})),kept:e.preview.kept};if(e.error!==void 0)s.error=cv(e.error);return s}function rv(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((n)=>n===Td(r.name,r.newVersion))??null:null,visible:nv(t,r.name)}))}function nv(e,t){let r=e.find((n)=>n.name===t);return r?r.state==="visible":null}function Td(e,t){return`${e}@${t}`}function sv(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 iv(e,t){if(!t)return[];return e.map((r)=>Td(r.name,r.newVersion??r.version)).sort()}function ov(e,t){return t?e.filter((r)=>!t.deletedTags.includes(r)):e}function av(e){let t=Object.values(e?.operations.providerReleases??{});return t.length>0&&t.every((r)=>r.state==="completed")}function cv(e){let t=e instanceof Error?e.message:String(e),r=e instanceof u?e.hint:void 0,n=Id(e);return{...n.length>0?{causes:n}:{},...r?{hint:r}:{},message:t}}function Id(e,t=new Set){if(!(e instanceof Error)||t.has(e))return[];return t.add(e),[...e instanceof AggregateError?e.errors:[],e.cause].filter((s)=>s instanceof Error).flatMap((s)=>[s.message,...Id(s,t)])}var lv="Fix the file so it matches the schema.json shipped with @r5n/sisyphus, then run the command again",Ad="InvalidConfig";function le(e,t,r){return ke((n)=>{try{return r(n)}catch(s){if(s instanceof u)throw s;throw new u(`${e} must be ${t}`,lv,1,{tag:Ad})}})}var ce=(e)=>le(e,"a string",_()),xt=(e)=>le(e,"a boolean",er()),Ue=(e)=>le(e,"an array of strings",re(_())),xn=(e)=>ke((t)=>t===void 0?void 0:e(t)),_a=(e)=>xn(ce(e)),fe=(e,t)=>le(e,"an object",nt(t)),uv=/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d{1,5})?$/,pv=new Set(["http:","https:"]),dv=/\/+$/,mv=_().map((e)=>{let t=e.trim().toLowerCase();return uv.test(t)?t:K()}),gv=_().map((e)=>{let t=URL.parse(e);if(!t||!pv.has(t.protocol)||t.username||t.password||t.search||t.hash)return K();return t.href.replace(dv,"")}),fv=fe("provider",{apiUrl:xn(le("provider.apiUrl","an http(s) URL without credentials, query or fragment",gv)),host:xn(le("provider.host","a host name such as git.example.com, optionally with a port",mv)),type:le("provider.type",'"github" or "gitlab"',Le(["github","gitlab"]))}).map((e)=>{if(e.type!=="github"||e.apiUrl===void 0)return e;throw new u("provider.apiUrl is only used with GitLab","Remove it; gh derives the GitHub API from provider.host",1,{tag:Ad})}),hv=fe("currentRelease.packages.*",{newVersion:ce("currentRelease.packages.*.newVersion"),oldVersion:ce("currentRelease.packages.*.oldVersion")}),yv=fe("config",{$schema:ce("$schema"),changelog:fe("changelog",{append:xt("changelog.append"),filename:ce("changelog.filename"),generate:xt("changelog.generate"),packageHeader:ce("changelog.packageHeader"),root:xt("changelog.root"),rootHeader:ce("changelog.rootHeader"),sections:le("changelog.sections","an object of strings",dt(_())),template:_a("changelog.template")}),commit:fe("commit",{author:ce("commit.author"),email:_a("commit.email"),message:ce("commit.message")}),commits:fe("commits",{skip:fe("commits.skip",{authors:Ue("commits.skip.authors"),messagePatterns:Ue("commits.skip.messagePatterns")})}),currentRelease:xn(fe("currentRelease",{packages:le("currentRelease.packages","an object",dt(hv)),planHash:ce("currentRelease.planHash"),sourceHash:ce("currentRelease.sourceHash"),stoneIds:Ue("currentRelease.stoneIds"),timestamp:ce("currentRelease.timestamp")})),dependents:fe("dependents",{kinds:le("dependents.kinds","an array of dependency sections",re(Le(["dependencies","devDependencies","optionalDependencies","peerDependencies"]))),updateInternal:le("dependents.updateInternal",'"always" or "outOfRange"',Le(["always","outOfRange"]))}),ignore:Ue("ignore"),lastStone:fe("lastStone",{commit:ce("lastStone.commit"),date:ce("lastStone.date")}),plugins:Ue("plugins"),pr:fe("pr",{labelMapping:le("pr.labelMapping",'an object of "major", "minor" or "patch"',dt(Le(["major","minor","patch"]))),skip:fe("pr.skip",{authors:Ue("pr.skip.authors"),labels:Ue("pr.skip.labels"),titlePatterns:Ue("pr.skip.titlePatterns")})}),provider:xn(fv),release:fe("release",{build:fe("release.build",{command:Ue("release.build.command"),outputs:Ue("release.build.outputs"),root:le("release.build.root","an array of string arrays",re(re(_())))}),createRelease:xt("release.createRelease"),npm:xt("release.npm"),npmVisibilityTimeout:le("release.npmVisibilityTimeout","a number",bl()),push:xt("release.push"),tags:xt("release.tags")}),scripts:fe("scripts",{post:le("scripts.post","an object of strings",dt(_())),pre:le("scripts.pre","an object of strings",dt(_()))}),single:xt("single"),sisyphusDir:ce("sisyphusDir"),stones:Ue("stones"),stonesPath:_a("stonesPath"),tag:ce("tag")}),wv=`${ir}/${ds}`;function bv(e){return yv(e)}function bi(e=wv){return new lo(e,gt,{parse:bv,strict:!0})}function Od(e,t){if(e.exists())return;throw new u(`No Sisyphus config found at ${e.path}`,`Run '${t} init' in the project root first`,1,{tag:"NotInitialised"})}var Xe="sisyphus/release",La="chore(release):";function _d(e){return xd(La,e)}function Ld(e,t){return[Rv(t),vv(e),$v(t),Pv()].join(`
|
|
198
|
+
`)}function Rv(e){let t=["## Changes",""];for(let r of e){if(t.push(`### ${r.message}`,""),r.commits&&r.commits.length>0)for(let n of r.commits)t.push(`- ${n.message} (\`${n.hash}\`)`);else if(r.description)t.push(r.description);t.push("")}return t.join(`
|
|
199
|
+
`)}function vv(e){return["## Packages","",...e.map((t)=>`- \`${t.name}\` ${t.version} \u2192 ${t.newVersion}`),""].join(`
|
|
200
|
+
`)}function $v(e){return["## Stones","",...e.map((t)=>`- \`${t.id}\`: ${t.message}`),""].join(`
|
|
201
|
+
`)}function Pv(){return["---","*This PR was automatically created by [Sisyphus](https://github.com/r5n-labs/clis).*","*Merging this PR will trigger the release workflow.*"].join(`
|
|
202
|
+
`)}var Da="sisyphus-release",xv="Sisyphus release PR",Ev="6f42c1";function Tv(e=(t)=>yt(void 0,t)){return M({name:"release-pr",description:"Create or update a release PR from pending stones",args:q({dryRun:{alias:"d",default:!1,description:"Preview without making changes",type:"boolean"}}),json:!0,examples:["sis actions release-pr --dry-run","sis actions release-pr --json"],run:async(t)=>{let r=await e(t.config.get("provider")),n=t.args.dryRun,s=await Av(r,n,zs(t,!1)),i;try{let o=bi(t.config.path);i=await Iv(r,o,s,n)}catch(o){throw await Bv(s,n,o),o}await Bd(s.originalRef),t.output.result(i)}})}var jd=Tv();async function Iv(e,t,r,n){let{generated:s,packages:i,stones:o}=await Ov(t,n);if(o.length===0)return v.info(d.dim("No pending stones found, skipping release PR")),{status:"skipped"};let a=_d(i),c=Ld(i,o),l={packages:i.map((h)=>({name:h.name,newVersion:h.newVersion,version:h.version})),stones:o.map((h)=>h.id),title:a};if(v.info(`${d.bold("Release PR:")} ${a}`),v.info(`${d.dim("Packages:")} ${i.map((h)=>h.name).join(", ")}`),n)return v.info(d.yellow(`
|
|
203
|
+
[dry-run] Would create/update release PR`)),v.info(d.dim(`
|
|
204
|
+
PR Body preview:`)),v.info(c),{...l,status:"dry-run"};let p=new B(t);for(let h of s)await p.save(h);await Lv(t,o,i,r.cutCommit,r.interactive);let{pr:m,status:g}=await Dv(e,r.baseBranch,a,c);return{...l,pr:m,status:g}}async function Av(e,t,r){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 i=(await Bun.$`git branch --show-current`.quiet()).stdout.toString().trim()||(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim(),o=await e.getDefaultBranch(),a=`origin/${o}`;if(await Ct(["fetch","origin",o],{interactive:r},`Failed to fetch ${a}`),t)await C(()=>Bun.$`git checkout --detach ${a}`.quiet(),`Failed to check out ${a}`);else await C(()=>Bun.$`git checkout --no-track -B ${Xe} ${a}`.quiet(),`Failed to check out ${Xe} from ${a}`);let c=(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim(),l=(await Bun.$`git rev-parse --show-toplevel`.quiet()).stdout.toString().trim(),p=new Set(await Fd(l));return{baseBranch:o,cutCommit:c,interactive:r,originalRef:i,root:l,untracked:p}}async function Fd(e){return(await C(()=>Bun.$`git ls-files --others --exclude-standard -z`.cwd(e).quiet(),`Failed to list untracked files in ${e}`)).stdout.toString().split("\x00").filter(Boolean)}async function Ov(e,t){let n=await new B(e).list(),s=await _v(e,n.length,t),i=[...n,...s];if(i.length===0)return{generated:[],packages:[],stones:[]};let o=e.get("ignore")??[],{stones:a,skipped:c}=xr(i,o);if(c.length>0)v.warn(d.yellow(`Excluded by config.ignore: ${c.join(", ")}`));let{packages:l}=await U.scan({single:e.get("single")}),p=O.mergeAll(a),m=kn(p,l,o);if(m.kind==="unknown-packages")throw new u(`Pending stones reference unknown packages: ${m.names.join(", ")}`,"Remove or update the stale stones before creating a release PR");let{cycle:g,ordered:h}=pr(z.applyStone(p,l,pe(e).kinds));if(g.length>0)v.warn(d.yellow(`Dependency cycle between ${g.join(", ")}; publish order may not satisfy every pin`));if(h.length===0)return v.warn(d.yellow("Pending stones reference no releasable packages")),{generated:[],packages:[],stones:[]};return{generated:s,packages:h,stones:a}}async function _v(e,t,r){let s=await new Nt(e).analyze({single:e.get("single")});if(s.length===0)return[];let{packages:i}=await U.scan({single:e.get("single")});return s.map((o,a)=>{let c=O.create(Nt.buildStoneData(o,i,pe(e)),t+a);return v.info(`${d.dim(r?"[dry-run] Would generate stone:":"Generated stone:")} ${o.message}`),c})}async function Lv(e,t,r,n,s){let i=Ve();i.start("Applying release changes...");try{let o=[...await Mv(r),...await Nv(e,t,r)],a=await new B(e).archive(t);if(await Nd(o),await jv(e,t,r,a,n),await Nd(tn(e)),(await Bun.$`git diff --cached --quiet`.quiet().nothrow()).exitCode!==0)await C(()=>Bun.$`git commit -m ${`${La} prepare release`}`.quiet(),`Failed to commit the release changes on ${Xe}`);await Ct(["push","origin",Xe,"--force"],{interactive:s},`Failed to push ${Xe} to origin`),i.stop("Release branch ready")}catch(o){throw i.error("Release preparation failed"),o}}async function Dv(e,t,r,n){let s=Ve(),i=await e.findPr({head:Xe,label:Da});if(i)return s.start("Updating PR..."),await e.updatePr(i.number,{body:n,title:r}),s.stop(`PR #${i.number} updated`),v.info(`
|
|
205
|
+
${d.green("Release PR updated:")} ${i.url}`),{pr:{number:i.number,url:i.url},status:"updated"};s.start("Creating PR..."),await e.ensureLabelExists(Da,{color:Ev,description:xv});let o=await e.createPr({base:t,body:n,head:Xe,labels:[Da],title:r});return s.stop(`PR #${o.number} created`),v.info(`
|
|
206
|
+
${d.green("Release PR created:")} ${o.url}`),{pr:{number:o.number,url:o.url},status:"created"}}async function Nd(e){await C(()=>Bun.$`git --literal-pathspecs add -- ${e}`.quiet(),`Failed to stage ${e.join(", ")}`)}async function Mv(e){return await new Qr().updateAll(e),e.map((t)=>t.file)}async function Nv(e,t,r){let n=e.get("changelog");if(!n.generate)return[];return await lr(e).generate(t,r),li(n,r)}async function jv(e,t,r,n,s){let i=await As(...tn(e)),o={packages:Fv(r),sourceHash:i,stoneIds:t.map((a)=>a.id),timestamp:n};e.set("currentRelease",{...o,planHash:Os(o,t.map((a)=>a.toJson()))}),e.set("lastStone",{commit:s,date:new Date().toISOString()})}function Fv(e){let t={};for(let r of e)if(r.newVersion)t[r.name]={newVersion:r.newVersion,oldVersion:r.version};return t}async function Bv(e,t,r){try{if(!t)await Uv(e);await Bd(e.originalRef)}catch(n){throw AggregateError([r,n],"Release PR preparation failed and the original checkout could not be restored")}}async function Uv(e){if((await Bun.$`git branch --show-current`.quiet()).stdout.toString().trim()!==Xe)return;await C(()=>Bun.$`git reset --hard --quiet HEAD`.quiet(),`Failed to discard changes on ${Xe}`);let r=(await Fd(e.root)).filter((n)=>!e.untracked.has(n));for(let n of r)await Vv(e.root,n)}async function Vv(e,t){await Cv(Md(e,t),{force:!0});let r=Dd(t);while(r!=="."){let n=Md(e,r),s=await Sv(n).catch(()=>null);if(s===null||s.length>0)return;await kv(n),r=Dd(r)}}async function Bd(e){try{await Bun.$`git checkout ${e}`.quiet()}catch(t){let r=(await Bun.$`git branch --show-current`.quiet().nothrow()).stdout.toString().trim();throw new u(`Failed to restore ${e}; the checkout is still on ${r||"a detached HEAD"}`,`Run 'git checkout ${e}' once the conflict is resolved`,1,{cause:t,tag:"ReleaseBranchRestoreFailed"})}}var Ud=M({name:"actions",description:"CI/CD integration",subcommands:[Kl,jd]});var Vd="0.0.0",Gd=M({name:"check",description:"Show workspace packages, pending stones and the combined release",args:q({config:{alias:"c",default:!1,description:"Include config in output",type:"boolean"}}),json:!0,examples:["sis check","sis check --json"],run:async(e)=>{let t=e.config.get("single"),r=e.config.get("ignore")??[],n=await U.scan({single:t}),i=(t?null:await U.scan({single:!0}))?.packages.values().next().value??n.packages.values().next().value,o=await new B(e.config).list(),a={ignore:r,kinds:pe(e.config).kinds,packages:n.packages},c={config:e.args.config?e.config.getAll():void 0,packages:n.packageNames.filter((l)=>!se(l,r)).map((l)=>({name:l,version:n.packages.get(l)?.version??Vd})),release:Hv(o,a),root:{name:i?.name??"",version:i?.version??Vd},stones:o.map((l)=>Gv(l,a))};e.output.result(c,qv)}});function Gv(e,t){let r=Oa(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}}function Hv(e,t){if(e.length===0)return{errors:[],packages:[],releasable:!1};let{stones:r}=xr(e,t.ignore),n=O.merge(r,r.map((o)=>o.message).join("; "));if(n.errors.length>0)return{errors:["Pending stones conflict and cannot be released together",...n.errors],packages:[],releasable:!1};let s=Oa(n.stone,t.packages,t.ignore,t.kinds);if(s.kind==="invalid")return{errors:[s.message],packages:[],releasable:!1};let i=s.packages.filter((o)=>!se(o.name,t.ignore));return{errors:[],packages:i,releasable:i.length>0}}function qv(e){let t=[`${d.bold(d.green("Root package:"))} ${d.cyan(e.root.name)}${d.dim(`@${e.root.version}`)}`,[d.bold(d.green("Packages:")),...e.packages.map((r)=>` ${d.dim("\u2022")} ${d.cyan(r.name)}${d.dim(`@${r.version}`)}`)].join(`
|
|
207
|
+
`)];if(e.stones.length>0)t.push(`${d.bold(d.green("Stones:"))}
|
|
208
|
+
|
|
209
|
+
${e.stones.map(Wv).join(`
|
|
210
|
+
|
|
211
|
+
`)}`),t.push(Jv(e.release));if(e.config)t.push(`${d.bold(d.green("Config:"))}
|
|
212
|
+
${d.dim(JSON.stringify(e.config,null,2))}`);return t.push(d.green("Sisyphus check complete.")),t.join(`
|
|
213
|
+
|
|
214
|
+
`)}function Wv(e){let t=[`${d.bold("Stone:")} ${d.cyan(e.id)}`];if(e.tag)t.push(`${d.dim("Tag:")} ${e.tag}`);if(t.push(`${d.dim("Message:")} ${e.message}`,d.bold("Packages:")),e.invalid)return t.push(` ${d.yellow(`invalid: ${e.invalid}`)}`),t.join(`
|
|
215
|
+
`);return t.push(...e.packages.map(Hd)),t.join(`
|
|
216
|
+
`)}function Jv(e){let t=d.bold(d.green("Combined release:"));if(e.errors.length>0)return[t,...e.errors.map((r)=>` ${d.yellow(r)}`)].join(`
|
|
217
|
+
`);if(!e.releasable)return`${t}
|
|
218
|
+
${d.dim("No releasable packages")}`;return[t,...e.packages.map(Hd)].join(`
|
|
219
|
+
`)}function Hd(e){let t=ar[e.bump];return` ${or[e.bump]} ${d.cyan(e.name)}@${t(e.newVersion)} ${d.dim(`(${e.bump})`)}`}var zv=q({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:{default:!1,description:"Reset an existing config to the defaults (requires --force)",type:"boolean"},force:{alias:"f",default:!1,description:"Merge the given values into an 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"}}),qd="ConfigExists",Jd=M({name:"init",description:"Initialise the Sisyphus config or edit it",args:zv,prompts:!0,json:!0,examples:["sis init","sis init --npm --tags --push","sis init --npm --force","sis init --default --force"],run:async(e)=>{let{default:t,force:r,...n}=e.args,s=Object.values(n).some((l)=>l!==void 0),i=e.config.exists();if(t){if(s)throw new N("--default cannot be combined with setting flags","Reset first, then apply the settings");if(i&&!r)throw new u(`Config already exists at ${e.config.path}`,"Pass --default --force to reset it",1,{tag:qd});let l=i?Kv(e.config.getAll()):{};return e.config.save({...structuredClone(gt),...l}),Ma(e,i?"reset":"created",await Wd(e.config))}let o=e.interactive&&!s;if(i&&!r&&!o){if(!s)return Ma(e,"unchanged",e.config.get("lastStone"));throw new u(`Config already exists at ${e.config.path}`,"Pass --force to merge these values into it",1,{tag:qd})}let a=e.config.getAll(),c=o?await Zv(a):n;return e.config.save(Ot({...a},Xv(c))),Ma(e,i?"updated":"created",await Wd(e.config))}});function Kv(e){let{currentRelease:t,lastStone:r,stones:n}=e;return{...t&&{currentRelease:t},lastStone:r,stones:n}}function Xv(e){let t=(o)=>Object.fromEntries(Object.entries(o).filter(([,a])=>a!==void 0)),r=(o)=>Object.keys(o).length>0,n=t({author:e.commitAuthor,email:e.commitEmail,message:e.commitMessage}),s=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(n)&&{commit:n},...r(s)&&{changelog:s},...r(i)&&{release:i}}}async function Wd(e){let t=e.get("lastStone");if(t?.commit)return t;let r=await Bun.$`git rev-parse HEAD`.quiet().nothrow(),n=r.exitCode===0?r.stdout.toString().trim():"";if(!n)return t;let s={commit:n,date:new Date().toISOString()};return e.set("lastStone",s),s}function Ma(e,t,r){let n={lastStone:r,path:e.config.path,status:t};e.output.result(n,()=>Yv(n,e.cli.version))}function Yv(e,t){if(e.status==="unchanged")return d.yellow(`Config already exists at ${e.path}. Pass setting flags with --force to change it, or use -i to edit it.`);return`${`${d.magenta(`${d.bold("Sisyphus ")}${d.underline(d.italic(`v${t??"unknown"}`))}`)}${d.green(" is set up to roll stones.")}`}
|
|
220
|
+
|
|
221
|
+
You can now start by creating a new stone by running ${d.green(T)}${d.blue(" version")}
|
|
197
222
|
and following the prompts.
|
|
198
223
|
|
|
199
|
-
After you finished, you can release it by running ${
|
|
200
|
-
|
|
201
|
-
${r.join(`
|
|
202
|
-
|
|
203
|
-
`);
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
Run ${
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
`))}
|
|
212
|
-
|
|
213
|
-
${
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
Run ${
|
|
218
|
-
Run ${
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
`))r.
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
`)
|
|
228
|
-
`))
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
224
|
+
After you finished, you can release it by running ${d.green(T)}${d.blue(" roll")}`}async function Zv(e){let t=await Xn({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?ve({initialValue:e.commit?.author??"",message:"Commit author",placeholder:"r5n-bot"}):void 0,commitEmail:({results:{configureCommit:r}})=>r?ve({initialValue:e.commit?.email??"",message:"Commit author email",placeholder:"r5n-bot@users.noreply.github.com"}):void 0,commitMessage:({results:{configureCommit:r}})=>r?ve({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:()=>ve({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 Re}});return{changelog:t.changelog,commitAuthor:Na(t.commitAuthor),commitEmail:Na(t.commitEmail),commitMessage:Na(t.commitMessage),createRelease:t.createRelease,npm:t.npm,push:t.push,rootChangelog:Qv(t.rootChangelog),single:t.single,tag:t.tag,tags:t.tags}}function Na(e){return typeof e==="string"?e:void 0}function Qv(e){return typeof e==="boolean"?e:void 0}var zd=60,Xd=M({name:"migrate",description:"Migrate from changesets to sisyphus",args:q({dryRun:{alias:"d",default:!1,description:"Preview migration without making changes",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}}),json:!0,examples:["sis migrate --dry-run","sis migrate --yes"],run:async(e)=>{let t=new ko;if(!await t.exists())throw new u("No .changeset directory found","This command migrates existing changesets to sisyphus stones");let{changesets:r,config:n,empty:s,errors:i}=await e$(t);if(o$(r),s.length>0)v.info(d.dim(`Skipping empty changesets without package bumps: ${s.join(", ")}`));if(n)a$(n);if(i.length>0)throw new u(`Cannot migrate changesets:
|
|
225
|
+
${i.join(`
|
|
226
|
+
`)}`,"Fix or remove these changeset files; no stones were created",1,{tag:"InvalidChangeset"});let o=new B(e.config),a=t$(t,r),c=await o.list(),l=a.filter((h)=>!r$(h.data,c)),p=a.filter((h)=>!l.includes(h)).map((h)=>h.filename);if(p.length>0)v.info(d.dim(`Already migrated to pending stones: ${p.join(", ")}`));let m=l.map((h)=>h.filename);if(e.args.dryRun){te("No changes made",d.yellow("Dry run")),e.output.result({alreadyMigrated:p,created:[],dryRun:!0,planned:m,skipped:s});return}if(l.length===0){te("Every changeset already has a pending stone",d.yellow("Nothing to migrate")),e.output.result({alreadyMigrated:p,created:[],dryRun:!1,planned:[],skipped:s});return}if(!e.args.yes&&!_e(e))throw new u("Non-interactive migration requires --yes","Use --yes to migrate or --dry-run to preview without changes");if(!e.args.yes&&!await V({initialValue:!0,message:`Migrate ${l.length} changeset(s) to stones?`}))return;let g=await n$(o,l);if(n)s$(e.config,n);i$(g),e.output.result({alreadyMigrated:p,created:g,dryRun:!1,planned:m,skipped:s})}});async function e$(e){let t=Ve();t.start("Analyzing changesets...");let r=await e.parse();if(r.changesets.length===0&&r.errors.length===0){t.stop("No changesets found");let n=r.empty.length>0?`Every changeset is empty: ${r.empty.join(", ")}`:void 0;throw new u("No changeset files to migrate",n,1,{tag:"NoChangesets"})}if(r.errors.length>0)return t.error(`Found ${r.errors.length} changeset(s) that cannot be parsed`),r;return t.stop(`Found ${d.bold(String(r.changesets.length))} changeset(s)`),r}function t$(e,t){let r=[],n=[];for(let s of t)try{r.push({data:e.toStoneData(s),filename:s.filename})}catch(i){if(!(i instanceof u))throw i;n.push(i.message)}if(n.length>0)throw new u(`Cannot migrate changesets:
|
|
227
|
+
${n.join(`
|
|
228
|
+
`)}`,"Rewrite them as major, minor, or patch before migrating; no stones were created");return r}function Kd(e){let t=(r)=>[...r??[]].sort();return JSON.stringify([e.message,e.description??"",t(e.major),t(e.minor),t(e.patch)])}function r$(e,t){let r=Kd(e);return t.some((n)=>Kd({description:n.description,major:n.major,message:n.message,minor:n.minor,patch:n.patch})===r)}async function n$(e,t){let r=Ve();r.start("Creating stones...");let n=[];for(let s of t){let i=await e.create(s.data);n.push(i.id)}return r.stop(`Created ${d.bold(String(n.length))} stone(s)`),n}function s$(e,t){let r=Ve();r.start("Migrating config..."),c$(e,t),r.stop("Config migrated")}function i$(e){let t=e.map((r)=>` ${d.dim("-")} ${r}`).join(`
|
|
229
|
+
`);te(`${t}
|
|
230
|
+
|
|
231
|
+
Run ${d.green(`${T} stone list`)} to view stones
|
|
232
|
+
Run ${d.green(`${T} roll --preview`)} to see what will be released
|
|
233
|
+
Remove ${d.green(".changeset/")} once you have checked the stones`,d.green("Migration complete"))}function o$(e){for(let t of e){let r=Object.entries(t.packages).map(([s,i])=>{let o=i==="major"?d.red:i==="minor"?d.yellow:d.green;return`${s} ${d.dim("(")}${o(i)}${d.dim(")")}`}).join(", "),n=t.summary.length>zd?`${t.summary.slice(0,zd)}...`:t.summary;v.info(`${d.dim(t.filename)}
|
|
234
|
+
${d.dim("Packages:")} ${r}
|
|
235
|
+
${d.dim("Message:")} ${n||d.dim("(empty)")}`)}}function a$(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 n of t)if(n.check())r[n.category].items.push(d.dim(n.format()));for(let n of[r.migrate,r.info,r.unsupported])if(n.items.length>0)te(n.items.join(`
|
|
236
|
+
`),n.color(n.title))}function c$(e,t){if(t.ignore?.length){let r=e.get("ignore")??[],n=[...new Set([...r,...t.ignore])];e.set("ignore",n)}if(t.commit===!0){let r=e.get("commit")??{},n=e.get("release")??{};e.set("commit",{...r,author:r.author??"Sisyphus"}),e.set("release",{...n,push:!0})}if(t.access==="public"){let r=e.get("release")??{};e.set("release",{...r,npm:!0})}if(t.changelog===!1){let r=e.get("changelog")??{};e.set("changelog",{...r,generate:!1})}}var Yd=100,l$=q({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"}});function u$(e,t){if(!e)return;let r=new Set(t),n=e.map((s)=>({...s,packages:s.packages.filter((i)=>r.has(i))})).filter((s)=>s.packages.length>0);return n.length>0?n:void 0}var Zd=M({name:"pr",description:"Create a stone from a Pull Request",args:l$,prompts:!0,json:!0,examples:["sis pr -u https://github.com/org/repo/pull/123 -y","sis pr -u https://github.com/org/repo/pull/123 -y --json"],run:async(e)=>{let r=await new Ao(e.config).analyze(e.args.url),n={number:r.pr.number,title:r.pr.title,url:r.pr.url};p$(r.pr);let s=(f)=>{v.info(d.dim(`Skipping: ${f.message}`)),e.output.result({pr:n,reason:f,status:"skipped"})},i=d$(e.config,r.pr);if(i)return s(i);if(r.packages.size===0){if(r.pr.merged&&!e.args.packages)return s({code:"no-affected-packages",message:"no workspace packages affected (only root files or files outside packages changed)"});throw new u("No packages affected by this PR","The PR only modifies root files or files outside packages")}let o=await m$(e,r.suggestedBump,r.pr.labels),a=await f$(e,r.packages);if(a.length===0)throw new u("No packages selected");let c=e.config.get("ignore")??[];if(e.args.packages){let f=a.filter((y)=>se(y,c));if(f.length>0)throw new u(`Packages are excluded by config.ignore: ${f.join(", ")}`,"Remove them from ignore before releasing them")}let l=a.filter((f)=>!se(f,c));if(l.length===0)return s({code:"ignored-only",message:"every affected package is excluded by config.ignore"});let{packages:p}=await U.scan({single:e.config.get("single")}),m=`[#${r.pr.number}](${r.pr.url})`,g=h$({allPackages:p,bump:o,commits:r.commits,dependents:pe(e.config),description:r.pr.body||void 0,message:e.args.message??`${r.pr.title} (${m})`,packages:l});if(y$(g,e.args.dryRun),e.args.dryRun){e.output.result({pr:n,status:"dry-run",stone:g});return}if(!e.args.yes&&e.interactive&&!await V({initialValue:!0,message:"Create this stone?"})){e.output.result({pr:n,status:"declined",stone:g});return}let h=await new B(e.config).create(g);te(`Run ${d.green(`${T} roll`)} to release packages
|
|
237
|
+
or create another stone with ${d.green(`${T} version`)}`,`Stone ${d.bold(h.id)} ${d.green("created")}`),e.output.result({pr:n,status:"created",stone:g,stoneId:h.id})}});function p$(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(", ")}`)}function d$(e,t){let r=e.get("pr").skip;for(let n of t.labels)if(r.labels.some((s)=>s.toLowerCase()===n.toLowerCase()))return{code:"skip-label",message:`label "${n}" is in skip list`};if(r.authors.some((n)=>n.toLowerCase()===t.author.toLowerCase()))return{code:"skip-author",message:`author "${t.author}" is in skip list`};for(let n of r.titlePatterns)try{if(new RegExp(n,"i").test(t.title))return{code:"skip-title",message:`title matches skip pattern "${n}"`}}catch{v.warn(d.yellow(`Invalid regex pattern in pr.skip.titlePatterns: "${n}"`))}return null}async function m$(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 ${g$(t,r,e.config)})`),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 At({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"}]})}function g$(e,t,r){let n=r.get("pr").labelMapping;for(let s of t){let i=s.toLowerCase();for(let[o,a]of Object.entries(n))if(i===o.toLowerCase()&&a===e)return`label: ${s}`}return"title"}async function f$(e,t){let r=Array.from(t);if(e.args.packages){let n=e.args.packages.split(",").map((i)=>i.trim()).filter(Boolean),s=n.filter((i)=>!t.has(i));if(s.length>0)throw new u(`Packages not affected by this PR: ${s.join(", ")}`,`Affected packages: ${r.join(", ")}`);return n}if(r.length===1||e.args.yes||!e.interactive)return v.info(`${d.dim("Affected packages:")} ${r.map((n)=>d.bold(n)).join(", ")}`),r;return tt({initialValues:r,message:"Select packages to include",options:r.map((n)=>({label:n,value:n})),required:!0})}function h$(e){let{allPackages:t,bump:r,commits:n,dependents:s,description:i,message:o,packages:a}=e,c={commits:u$(n,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=X(wt(a.map((l)=>({bump:r,name:l})),t,s)),c}function y$(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 n=e.description.length>Yd?`${e.description.slice(0,Yd)}...`:e.description;r.push(` ${d.dim("Description:")} ${n}`)}v.step(r.join(`
|
|
238
|
+
`))}import{readFile as S$}from"fs/promises";import{dirname as C$,join as k$}from"path";var Qd=q({abort:{default:!1,description:"Discard the incomplete release commit and tags 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:"Check and preview the release without making changes",type:"boolean"},keep:{default:!1,description:"Keep the changelog files written by --preview",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:"Write the changelogs, report them, then revert them unless --keep is passed",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:"Consent to the release without a confirmation prompt",type:"boolean"}}),w$=1,b$="Pass --yes to consent to the release, or use --dry-run to preview it";function Et(e){return{interactive:zs(e,e.args.yes)}}function em(e){return{ctx:e,emitted:!1,npmVisibilityTimeout:0,report:{mode:"release",npmTag:ye,packages:[],stones:[]},warnings:[]}}function Er(e){if(e){let r=()=>{return};return{info:r,note:r,start:r,step:r,stop:r,warn:r}}let t=Ve();return{info:(r)=>v.info(r),note:(r,n)=>te(r,n),start:(r)=>t.start(r),step:(r)=>v.step(r),stop:(r)=>t.stop(r),warn:(r)=>v.warn(r)}}function Ae(e,t){if(e.warnings.push(t),!e.ctx.json)v.warn(d.yellow(t))}function R$(e,t,r={}){let{ctx:n,report:s}=e;return Ed({ledger:s.ledger??null,mode:s.mode,npmTag:s.npmTag,npmVisibility:s.npmVisibility,packages:s.packages,releaseCommit:s.releaseCommit,status:t,stones:s.stones,tagsEnabled:s.tagsEnabled??n.args.tags??(n.config.failure?!1:n.config.get("release").tags),warnings:e.warnings,...r})}function Ie(e,t,r={}){e.emitted=!0,e.ctx.output.result(R$(e,t,r))}function Ri(e,t,r){if(r.length===0){t.info(d.yellow("Dry run complete - no changes made")),Ie(e,"planned");return}let n=r.map((s)=>` ${s.message}${s.hint?`
|
|
239
|
+
${d.dim(s.hint)}`:""}`);return t.warn(`Dry run blocked - the release would stop before changing anything:
|
|
240
|
+
${n.join(`
|
|
241
|
+
`)}`),Ie(e,"blocked",{blockers:r}),w$}async function vi(e,t){if(e.args.yes)return!0;if(!_e(e)){let r=e.json?"--json":"A non-interactive release";throw new N(`${r} requires --yes`,b$)}return V({initialValue:!0,message:t})}function $i(e,t,r){if(!r)return ye;let n=e.ctx.config.get("tag");try{return Ht(t,n)}catch(s){return Ae(e,`Npm publication would fail: ${s instanceof Error?s.message:String(s)}`),Qs(n)}}import{rm as v$}from"fs/promises";async function rm(e,t,r,n,s,i){let{config:o}=e.ctx,a=new Be(o,i,Et(e.ctx)),c={...o.get("lastStone")},l=o.path,p=await Bun.file(l).exists()?await Bun.file(l).text():null,m=new B(o),g=new Map;for(let y of s){let R=m.getFilePath(y.id);if(await Bun.file(R).exists())g.set(R,await Bun.file(R).text())}let h=await tm();await a.preflight(n,s);let f=t;try{if(await a.initializeExternalRelease(n,s,!1),e.report.ledger=a.getLedgerSnapshot()??void 0,f.start("Updating package versions..."),await a.updatePackageVersions(n),f.stop("Package versions updated"),i.changelog)f.start("Generating changelogs..."),await a.generateChangelogs(s,n),f.stop("Changelogs generated");for(let y of s)await m.delete(y.id);if(i.commit)f.start("Creating release commit..."),o.set("lastStone",{commit:h,date:new Date().toISOString()}),await a.createCommit(r,n,s),e.report.releaseCommit=await tm(),f.stop("Release commit created");if(i.tags)f.start("Creating git tags..."),await a.createGitTags(n),f.stop("Git tags created");if(await a.finalizeExternalRelease(n,s),i.npm)f.start("Preparing NPM packages..."),await a.prepareNpmPublish(n),f.stop("NPM packages prepared");if(await a.markExternalReleaseReady(),i.push)f.start("Pushing to remote..."),await a.pushRelease(),f.stop("Pushed to remote");if(i.npm)f.start("Publishing to NPM..."),await a.publishToNpm(n),f.stop("Published to NPM");if(i.createRelease)f.start("Creating release..."),await a.createGitRelease(s,n),f.stop("Release created");await a.completeRelease(),e.report.ledger=a.getLedgerSnapshot()??e.report.ledger,await Pi(e,f),f.note(`Released ${d.bold(String(n.length))} package(s)
|
|
242
|
+
Run ${d.green(`${T} check`)} to verify`,d.green("Release complete")),Ie(e,"completed")}catch(y){if(e.report.ledger=a.getLedgerSnapshot()??e.report.ledger,a.hasCrossedIrreversibleBoundary())throw f.stop("Release incomplete, local state preserved"),a.createIncompleteReleaseError(y);f.stop("Release failed, rolling back...");try{await a.rollback(!1)}catch(R){throw AggregateError([y,R],"Release failed and rollback could not be completed; local release state was preserved")}try{o.set("lastStone",c);for(let R of s)await m.save(R);for(let[R,S]of g)await Bun.write(R,S);if(p===null)await v$(l,{force:!0});else await Bun.write(l,p)}catch(R){throw AggregateError([y,R],"Release failed and local metadata could not be restored; local release state was preserved")}try{await a.removeReleaseLedger()}catch(R){throw AggregateError([y,R],"Release failed and the recovery ledger could not be removed; remove it before the next roll")}throw e.report.ledger=void 0,e.report.releaseCommit=void 0,y}}async function Pi(e,t){let r=e.report.ledger;if(!r?.options.npm||e.npmVisibilityTimeout===0)return;t.start("Checking npm registry visibility...");try{e.report.npmVisibility=await Ia(r,e.npmVisibilityTimeout),t.stop("Npm registry visibility checked")}catch(n){t.stop("Npm registry visibility check failed"),Ae(e,`Could not check npm registry visibility: ${n instanceof Error?n.message:String(n)}`);return}for(let n of Aa(e.report.npmVisibility,e.npmVisibilityTimeout))Ae(e,n)}async function tm(){let e=await Bun.$`git rev-parse HEAD`.quiet().nothrow();return e.exitCode===0?e.stdout.toString().trim():""}var nm=/\d{14}$/,Tr="Recreate the release PR before publishing";function ja(e){return e.filter(([t])=>t).map(([,t])=>t)}function sm(e){let{args:t}=e;if(t.abort){let n=ja([[t.changelog!==void 0,"--changelog"],[t.createRelease!==void 0,"--create-release"],[t.dryRun!==void 0,"--dry-run"],[t.keep,"--keep"],[t.noCommit,"--no-commit"],[t.npm!==void 0,"--npm"],[t.preview,"--preview"],[t.publishOnly,"--publish-only"],[t.push!==void 0,"--push"],[t.resume,"--resume"],[t.tags!==void 0,"--tags"]]);if(n.length>0)throw new u(`--abort cannot be combined with ${n.join(", ")}`,"Abort discards the incomplete release recorded in the recovery ledger");return}if(t.resume){let n=ja([[t.changelog!==void 0,"--changelog"],[t.createRelease!==void 0,"--create-release"],[t.dryRun!==void 0,"--dry-run"],[t.keep,"--keep"],[t.noCommit,"--no-commit"],[t.npm!==void 0,"--npm"],[t.preview,"--preview"],[t.publishOnly,"--publish-only"],[t.push!==void 0,"--push"],[t.tags!==void 0,"--tags"]]);if(n.length>0)throw new u(`--resume cannot be combined with ${n.join(", ")}`,"Resume uses the operation settings recorded in the active release ledger");return}if(t.keep&&!t.preview)throw new u("--keep requires --preview","Pass --preview --keep to write the changelogs and keep them");if(t.preview&&t.dryRun)throw new u("--preview cannot be combined with --dry-run","Preview writes the changelog files and reverts them unless --keep is passed");if(!t.publishOnly)return;let r=ja([[t.changelog!==void 0,"--changelog"],[t.noCommit,"--no-commit"],[t.preview,"--preview"],[t.push!==void 0,"--push"]]);if(r.length>0)throw new u(`--publish-only cannot be combined with ${r.join(", ")}`,"Publish-only supports --create-release, --dry-run, --npm, --tags, and --yes")}async function im(e){let{ctx:t}=e;await Be.assertNoActiveRelease();let r=t.config.get("currentRelease");if(!r)throw new u("No currentRelease found in config",`Run \`${T} actions release-pr\` first to prepare a release`);if(await As(...tn(t.config))!==r.sourceHash)throw new u("Current checkout does not match the prepared release source",Tr);let s=await new B(t.config).getReleasedStones(r.timestamp,r.stoneIds).catch((y)=>{throw new u(y instanceof Error?y.message:String(y),Tr)});if(s.length===0)throw new u("No archived stones found for currentRelease",Tr);if(Os({packages:r.packages,sourceHash:r.sourceHash,stoneIds:r.stoneIds,timestamp:r.timestamp},s.map((y)=>y.toJson()))!==r.planHash)throw new u("Prepared release plan has changed",Tr);let o=Object.entries(r.packages);if(o.length===0)throw new u("No packages in currentRelease","The release config appears to be empty");let{packages:a}=await U.scan({single:t.config.get("single")}),c=[];for(let[y,{oldVersion:R,newVersion:S}]of o){let k=a.get(y);if(!k)throw new u(`Package ${y} from currentRelease is missing from the workspace`);if(k.version!==S)throw new u(`Package ${y} is at ${k.version}, but currentRelease expects ${S}`,"Check out the exact release commit before publishing");c.push(k.withVersions(R,S))}P$(t,s,r.packages,c);let l=Er(t.json),{cycle:p,ordered:m}=pr(c);if(p.length>0)Ae(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: ${r.timestamp}`)),l.info(d.dim(`Stones: ${r.stoneIds.join(", ")}`)),l.info(""),l.info(d.bold("Packages to publish:"));for(let y of m)l.info(` ${y.name}@${y.newVersion??y.version}`);l.info("");let g=t.config.get("release"),h={createRelease:t.args.createRelease??g.createRelease,dryRun:t.args.dryRun??!1,npm:t.args.npm??g.npm,tags:t.args.tags??g.tags};if(l.info(d.dim(`Operations: npm=${h.npm} tags=${h.tags} createRelease=${h.createRelease}`)),e.report={mode:"publish-only",npmTag:ye,packages:m,stones:s,tagsEnabled:h.tags},e.report.npmTag=$i(e,m,h.npm),h.createRelease&&!h.tags)throw new u("Provider releases require pushed git tags","Enable --tags so the provider cannot create an implicit tag");if(!h.npm&&!h.tags&&!h.createRelease)throw new u("Nothing to publish: npm, tags, and provider release are all disabled","Enable --npm, --tags, or --create-release");let f=new Be(t.config,{...h,changelog:!1,push:!1},Et(t));if(h.dryRun){l.info(d.yellow("[dry-run] Would publish packages"));let y=await f.inspectPreflight(m,s,{publishOnly:!0});return Ri(e,l,y)}if(!await vi(t,"Proceed with publishing?"))return;await $$(e,l,f,m,s,h);return}async function $$(e,t,r,n,s,i){let o=t;await r.preflight(n,s,{publishOnly:!0});try{if(await r.initializeExternalRelease(n,s,!0),e.report.ledger=r.getLedgerSnapshot()??void 0,i.tags)o.start("Creating git tags..."),await r.createGitTags(n),o.stop("Git tags created");if(await r.finalizeExternalRelease(n,s),i.npm)o.start("Preparing NPM packages..."),await r.prepareNpmPublish(n),o.stop("NPM packages prepared");if(await r.markExternalReleaseReady(),i.tags)o.start("Pushing git tags..."),await r.pushRelease(),o.stop("Git tags pushed");if(i.npm)o.start("Publishing to NPM..."),await r.publishToNpm(n),o.stop("Published to NPM");if(i.createRelease)o.start("Creating release..."),await r.createGitRelease(s,n),o.stop("Release created");await r.completeRelease(),e.report.ledger=r.getLedgerSnapshot()??e.report.ledger,await Pi(e,o),o.note(`Published ${d.bold(String(n.length))} package(s)
|
|
243
|
+
Run ${d.green(`${T} check`)} to verify`,d.green("Publish complete")),Ie(e,"completed")}catch(a){if(e.report.ledger=r.getLedgerSnapshot()??e.report.ledger,r.hasCrossedIrreversibleBoundary())throw o.stop("Publish incomplete, local state preserved"),r.createIncompleteReleaseError(a);o.stop("Publish failed");try{await r.rollback()}catch(c){throw AggregateError([a,c],"Publish failed and rollback could not be completed; local release state was preserved")}throw e.report.ledger=void 0,a}}async function om(e){let t=await Be.abort(Et(e.ctx)),{commitDiscarded:r,deletedTags:n}=t;e.report={ledger:t.ledger,mode:"abort",npmTag:ye,packages:[],stones:[]};for(let s of t.warnings)Ae(e,s);if(!e.ctx.json){let s=[r?"the release commit":void 0,n.length>0?`tags ${n.join(", ")}`:void 0].filter((i)=>i!==void 0);v.info(s.length>0?`Release ${t.ledger.id} abandoned; discarded ${s.join(" and ")}`:`Release ${t.ledger.id} abandoned`)}Ie(e,"aborted",{abort:{commitDiscarded:r,deletedTags:n}})}async function am(e){let{ctx:t}=e,{ledger:r,packages:n,stones:s}=await Be.resume(t.config,Et(t));if(e.report={ledger:r??void 0,mode:"resume",npmTag:r?.options.npmTag??ye,packages:n,stones:s,tagsEnabled:r?.options.tags??!1},await Pi(e,Er(t.json)),!t.json)te(`Released ${d.bold(String(n.length))} package(s)
|
|
244
|
+
Run ${d.green(`${T} check`)} to verify`,d.green("Release resumed"));Ie(e,"completed")}function P$(e,t,r,n){let s=O.mergeAll(t),i=Object.keys(r).sort(),o=[...new Set(s.allPackages)].sort();if(JSON.stringify(i)!==JSON.stringify(o))throw new u("Archived stones do not match currentRelease packages",Tr);let a=z.applyStone(s,new Map(n.map((c)=>[c.name,c])),pe(e.config).kinds);for(let c of a){let l=r[c.name]?.newVersion,p=c.bump==="snapshot"?c.newVersion?.replace(nm,""):c.newVersion,m=c.bump==="snapshot"?l?.replace(nm,""):l;if(p!==m)throw new u(`Archived stones do not produce ${c.name}@${l??"missing"}`,Tr)}}var x$="Pending stones reference only ignored packages",cm=M({name:"roll",description:"Execute a release from pending stones",args:Qd,json:!0,examples:["sis roll --dry-run","sis roll --npm --tags --push --yes","sis roll --json --yes","sis roll --resume --json"],run:async(e)=>{let t=em(e);try{return await E$(t)}catch(r){if(e.json&&!t.emitted)t.report.ledger??=(await ge.loadActive().catch(()=>null))?.data,Ie(t,"failed",{error:r});throw r}}});async function E$(e){let{ctx:t}=e;if(sm(t),t.args.abort){e.report.mode="abort",await om(e);return}if(e.npmVisibilityTimeout=Ta(t.config.get("release").npmVisibilityTimeout),t.args.resume){e.report.mode="resume",await am(e);return}if(t.args.publishOnly)return e.report.mode="publish-only",im(e);await Be.assertNoActiveRelease();let r=L$(t),n=await new B(t.config).list();if(n.length===0)throw new u("No pending stones found",`Create a stone with ${d.green(`${T} version`)} first`);let{packages:s}=await U.scan({single:t.config.get("single")}),i=t.config.get("ignore")??[],{skipped:o,stones:a}=xr(n,i);if(o.length>0)Ae(e,`Excluded by config.ignore: ${o.join(", ")}`);let c=O.mergeAll(a),l=kn(c,s,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=T$(e,z.applyStone(c,s,pe(t.config).kinds)),m=r.dryRun?"dry-run":t.args.preview?"preview":"release";if(p.length===0){Ae(e,x$),e.report={mode:m,npmTag:ye,packages:[],stones:n,tagsEnabled:r.tags},Ie(e,"planned");return}if(e.report={mode:m,npmTag:ye,packages:p,stones:n,tagsEnabled:r.tags},e.report.npmTag=$i(e,p,r.npm),t.args.preview){await I$(e,n,p);return}let g=Er(t.json);if(D$(g,c,p,r),r.dryRun){let h=new Be(t.config,r,Et(t));return Ri(e,g,await h.inspectPreflight(p,n))}if(!await vi(t,"Proceed with release?"))return;await rm(e,g,c,p,n,r);return}function T$(e,t){let{kept:r,skipped:n}=fu(t,e.ctx.config.get("ignore")??[]);if(n.length>0)Ae(e,`Excluded by config.ignore: ${n.join(", ")}`);let{cycle:s,ordered:i}=pr(r);if(s.length>0)Ae(e,`Dependency cycle between ${s.join(", ")}; publish order may not satisfy every pin`);return i}async function I$(e,t,r){let{ctx:n}=e,s=n.config.get("changelog"),i=lr(n.config),o=Er(n.json);o.start("Generating changelog preview..."),await i.generate(t,r),o.stop("Changelog preview generated");let a=r.map((l)=>k$(C$(l.file),s.filename));if(s.root)a.push(s.filename);let c=await A$(n,o,a).catch(async(l)=>{throw await i.rollback(),o.info(d.dim("Changes reverted")),l});if(c.kept)o.info(d.yellow("Changes kept"));else await i.rollback(),o.info(d.dim("Changes reverted"));Ie(e,"previewed",{preview:c})}async function A$(e,t,r){let n=[];for(let s of r){let i=await O$(s);if(i!==null)n.push({content:i,file:s})}return t.info(`
|
|
245
|
+
Preview files written:
|
|
246
|
+
${r.map((s)=>d.dim(` ${s}`)).join(`
|
|
247
|
+
`)}`),t.info(""),{changelogs:n,kept:await _$(e)}}async function O$(e){try{return await S$(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function _$(e){if(e.args.keep)return!0;if(e.args.yes||!_e(e))return!1;return!await V({initialValue:!0,message:"Revert changes?"})}function L$(e){let t=e.config.get("release"),r=e.config.get("changelog"),n=!e.args.noCommit;if(!n){let i=[e.args.createRelease?"--create-release":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(`--no-commit cannot be combined with ${i.join(", ")}`,"Tags, pushes, and provider releases require the release commit")}let s={changelog:e.args.changelog??r.generate,commit:n,createRelease:n?e.args.createRelease??t.createRelease:!1,dryRun:e.args.dryRun??!1,npm:e.args.npm??t.npm,push:n?e.args.push??t.push:!1,tags:n?e.args.tags??t.tags:!1};if(s.createRelease&&(!s.tags||!s.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(!s.commit&&s.npm)throw new u("Npm publication requires a release commit","Remove --no-commit so package artifacts are bound to committed source");return s}function D$(e,t,r,n){let s=[];if(n.dryRun)s.push(d.bold(d.yellow("[dry-run]")));if(s.push(`${d.bold("Release:")} ${t.message}`),t.tag)s.push(`${d.dim("Tag:")} ${t.tag}`);s.push("",d.bold("Packages:"));for(let i of r)s.push(` ${i.label}`);s.push("",d.dim(`Changelog: ${n.changelog?"yes":"no"}`),d.dim(`Git tags: ${n.tags?"yes":"no"}`),d.dim(`NPM publish: ${n.npm?"yes":"no"}`),d.dim(`Push to remote: ${n.push?"yes":"no"}`),d.dim(`Create release: ${n.createRelease?"yes":"no"}`)),e.step(s.join(`
|
|
248
|
+
`))}function Ye(e){return Od(e,T),new B(e)}async function Ir(e,t,r,n){if(n)return M$(e,r);if(!t)throw new u("Stone ID is required",`Usage: ${T} stone ${e} <id>`);let s=await r.get(t);if(!s)throw new u(`Stone '${t}' not found`,`Run '${T} stone list' to see available stones`,1,{tag:"StoneNotFound"});return s}async function M$(e,t){let r=await t.list();if(r.length===0)throw new u("No pending stones found");let n=r.map((s)=>({label:`${s.id} - ${s.message}`,value:s}));return At({message:`Select a stone to ${e}`,options:n})}var lm=M({name:"delete",description:"Delete a pending stone",positionals:$e({id:{description:"Stone ID to delete"}}),prompts:!0,json:!0,examples:["sis stone delete 0001-abcdefgh","sis stone delete 0001-abcdefgh --json"],run:async(e)=>{let t=Ye(e.config),r=await Ir("delete",e.positionals.id,t,e.interactive);if(e.interactive&&!await V({initialValue:!1,message:`Delete stone '${r.id}'?`}))return;await t.delete(r.id),v.success(`Stone '${d.bold(r.id)}' deleted`),e.output.result({deleted:!0,id:r.id})}});var um=M({name:"edit",description:"Edit a pending stone",args:q({message:{alias:"m",description:"New commit message",type:"string"}}),positionals:$e({id:{description:"Stone ID to edit"}}),prompts:!0,json:!0,examples:['sis stone edit 0001-abcdefgh -m "fix: clearer message"'],run:async(e)=>{let t=Ye(e.config),r=await Ir("edit",e.positionals.id,t,e.interactive),n=await N$(e.args.message,e.interactive,r.message);await t.save(r.withMessage(n)),v.success(`Updated commit message for stone '${d.bold(r.id)}'`),e.output.result({id:r.id,message:n})}});async function N$(e,t,r){if(e)return e;if(!t)throw new u("--message is required in non-interactive mode");return ve({initialValue:r,message:"Commit message",placeholder:r})}var pm=M({name:"list",description:"List all pending stones",args:q({verbose:{alias:"v",default:!1,description:"Show detailed info",type:"boolean"}}),json:!0,examples:["sis stone list","sis stone list --json"],run:async(e)=>{let t=Ye(e.config),r=await t.list(),n=r.map((s)=>({path:t.getFilePath(s.id),...s.toJson()}));e.output.result(n,()=>j$(r,e.args.verbose))}});function j$(e,t){if(e.length===0)return"No pending stones found";return`${`Found ${d.bold(String(e.length))} pending stone${e.length>1?"s":""}`}
|
|
249
|
+
|
|
250
|
+
${e.map((n)=>F$(n,t)).join(`
|
|
251
|
+
|
|
252
|
+
`)}`}function F$(e,t){let r=[`${d.dim("-")} ${d.bold(e.id)}`,` ${d.dim("Message:")} ${e.message}`];if(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 n of e.description.split(`
|
|
253
|
+
`))r.push(` ${d.dim(n)}`)}return r.join(`
|
|
254
|
+
`)}var Fa=2,dm=M({name:"merge",description:"Merge multiple stones into one",args:q({delete:{default:!1,description:"Delete original stones after merge",type:"boolean"},message:{alias:"m",description:"Commit message for merged stone",type:"string"}}),positionals:$e({ids:{description:"Stone IDs to merge (at least 2)",variadic:!0}}),prompts:!0,json:!0,examples:['sis stone merge 0001-aaaaaaaa 0002-bbbbbbbb -m "feat: combined" --delete'],run:async(e)=>{let t=Ye(e.config),r=await B$(t,e.positionals.ids,e.interactive),n=await U$(e.args.message,e.interactive),{stone:s,conflicts:i,errors:o}=O.merge(r,n);if(o.length>0)throw new u("Selected stones cannot be merged",o.join(`
|
|
255
|
+
`));await t.save(s);let a=await V$(e.args.delete,e.interactive);if(a)await t.deleteMany(r.map((c)=>c.id));H$(s.id,i),e.output.result({conflicts:i,deleted:a,id:s.id,mergedFrom:r.map((c)=>c.id)})}});async function B$(e,t,r){let n=await e.list();if(n.length<Fa)throw new u("Need at least 2 stones to merge");if(r)return G$(n);if(t.length<Fa)throw new u("Need at least 2 stone IDs",`Usage: ${T} stone merge <id1> <id2> [...] -m "message"`);let s=n.filter((i)=>t.includes(i.id));if(s.length!==t.length){let i=s.map((a)=>a.id),o=t.filter((a)=>!i.includes(a));throw new u(`Stone(s) not found: ${o.join(", ")}`)}return s}async function U$(e,t){if(e)return e;if(!t)throw new u("--message is required in non-interactive mode");return ve({message:"Commit message for merged stone",placeholder:"feat: combined changes"})}async function V$(e,t){if(e)return!0;return t?V({initialValue:!1,message:"Delete original stones?"}):!1}async function G$(e){let t=e.map((n)=>({label:`${n.id} - ${n.message}`,value:n})),r=await tt({message:"Select stones to merge (at least 2)",options:t,required:!0});if(r.length<Fa)throw new u("Need to select at least 2 stones");return r}function H$(e,t){if(v.success(`Created merged stone: ${d.bold(e)}`),t.length===0)return;te(`Resolved ${t.length} package conflict(s) using highest bump type:
|
|
256
|
+
`+t.map((r)=>` ${d.dim("-")} ${r}`).join(`
|
|
257
|
+
`),d.yellow("Conflicts resolved"))}var q$=40,mm=M({name:"show",description:"Show details of a specific stone",positionals:$e({id:{description:"Stone ID to display"}}),prompts:!0,json:!0,examples:["sis stone show 0001-abcdefgh","sis stone show 0001-abcdefgh --json"],run:async(e)=>{let t=Ye(e.config),r=await Ir("show",e.positionals.id,t,e.interactive),n=t.getFilePath(r.id);e.output.result({path:n,...r.toJson()},()=>W$(r,n))}});function W$(e,t){let r=[d.bold(`Stone: ${e.id}`),d.dim(`Path: ${t}`),d.dim("-".repeat(q$)),"",`${d.dim("Message:")} ${e.message}`];if(e.tag)r.push(`${d.dim("Tag:")} ${d.cyan(e.tag)}`);if(e.description)r.push(`${d.dim("Description:")} ${e.description}`);r.push("");let n=[{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:s,packages:i}of n)if(i.length>0)r.push(`${ar[s](s)}: ${i.join(", ")}`);return r.join(`
|
|
258
|
+
`)}var gm=M({name:"stone",description:"Manage version stones",subcommands:[pm,mm,lm,um,dm]});var J$=$e({message:{description:"Stone message (commit message)"},description:{description:"Stone description (optional details)"}}),z$=q({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"}}),fm=M({name:"version",description:"Create a new version stone",args:z$,positionals:J$,prompts:!0,json:!0,examples:["sis version",'sis version --bump minor --all --message "feat: update everything" --yes','sis version --minor @org/core --patch @org/utils --message "feat: update core" --yes --json',"sis version --from-commits --dry-run"],run:async(e)=>{let t=K$(e);if(Z$(e,t),!e.args.fromCommits)Q$(e,t);let r=e.args.fromCommits?await iP(e,t):e.interactive&&!t.hasManualSelection?await eP(e,t):await tP(e,t);e.output.result({dryRun:e.args.dryRun,stones:r})}});function K$(e){let t=e.args.major!==void 0||e.args.minor!==void 0||e.args.patch!==void 0,r={major:Ba(e.args.major,"--major"),minor:Ba(e.args.minor,"--minor"),patch:Ba(e.args.patch,"--patch")};Y$(r);let n=e.positionals.message!==void 0,s=e.args.message!==void 0;if(n&&s)throw new u("Message cannot be provided both positionally and with --message");let i=n?e.positionals.message:e.args.message,o=Si(e.args.bump,"--bump"),a=Si(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:Si(i,"Message"),packageSelection:r,packageSelectionSupplied:t,tag:X$(e.args.tag)}}function Si(e,t){if(e===void 0)return;let r=e.trim();if(!r)throw new u(`${t} cannot be empty`);return r}function X$(e){let t=Si(e,"--tag");if(t===void 0)return;return Dt(t,"--tag must be a supported prerelease identifier")}function Ba(e,t){if(e===void 0)return[];let r=e.split(",").map((n)=>n.trim());if(r.some((n)=>!n))throw new u(`${t} must contain one or more non-empty package names`);return[...new Set(r)]}function Y$(e){let t=new Map,r=[["major",e.major],["minor",e.minor],["patch",e.patch]];for(let[n,s]of r)for(let i of s){let o=t.get(i);if(o)throw new u(`Package "${i}" cannot be assigned to both --${o} and --${n}`);t.set(i,n)}}function Z$(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")}function Q$(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 function Ua(e,t){let r=await U.scan({filter:t,single:e.config.get("single")}),n=e.config.get("ignore")??[],s=r.packageNames.filter((i)=>!se(i,n));if(s.length===0)throw new u("No packages found matching the criteria");return{packageNames:s,packages:r.packages}}async function eP(e,t){let{packages:r,packageNames:n}=await Ua(e,t.filter),s=await oP(r,n,t.tag),i=t.message??await hm(),o=t.description??await lP(),a=ym({ctx:e,description:o,message:i,packages:r,selection:s,tag:t.tag});return wm(e,a,r)}async function tP(e,t){let r=t.message??(e.interactive?await hm():void 0);if(!r)throw new u("Message is required",'Pass --message "..." or a positional message');let{packages:n,packageNames:s}=await Ua(e,t.filter),i=rP(e,t,s);sP(i,n,s,e.config.get("ignore")??[],t.filter);let o=ym({ctx:e,description:t.description,message:r,packages:n,selection:i,tag:t.tag});return wm(e,o,n)}function rP(e,t,r){let n=t.bump;if(!n)return nP(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 s=[...r];if(n==="major")return{major:s,minor:[],patch:[]};if(n==="minor")return{major:[],minor:s,patch:[]};return{major:[],minor:[],patch:s}}function nP(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}function sP(e,t,r,n,s){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)=>se(p,n));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 "${s}": ${l.join(", ")}`)}async function iP(e,t){if(!e.config.get("lastStone")?.commit)throw new u("No release baseline recorded",`Set lastStone.commit (run ${T} init in an existing repo, or complete one release) before using --fromCommits`);let n=await new Nt(e.config).analyze({filter:t.filter,single:e.config.get("single")});if(n.length===0)return v.info("No conventional commits found since last release"),[];let{packages:s}=await Ua(e,t.filter);v.info(`Found ${d.bold(String(n.length))} commit group(s) to process`);let i=new B(e.config),o=[];for(let a of n){let c=Nt.buildStoneData(a,s,pe(e.config,t.tag));if(e.args.dryRun)bm(e,c,s),o.push({...c});else{let l=await i.create(c);o.push({...c,id:l.id}),v.success(`Created stone: ${d.bold(l.id)}`)}}if(!e.args.dryRun&&o.length>0)te(`Created ${d.bold(String(o.length))} stone(s) from commits.
|
|
259
|
+
Run ${d.green(`${T} check`)} to see what will be released.`,d.green("Success"));return o}async function oP(e,t,r){let n=[],s={major:[],minor:[],patch:[]};for(let i of["major","minor","patch"]){let o=t.filter((c)=>!n.includes(c));if(o.length===0)break;let a=await aP(i,o,e,r);if(n.push(...a),i==="major")s.major=a;else if(i==="minor")s.minor=a;else s.patch=a}if(n.length===0)throw new u("No packages selected");return s}async function aP(e,t,r,n){let s=ar[e],i=t.map((o)=>{let a=r.get(o);return{label:a?cP(a,e,n):o,value:o}});return tt({message:`Select packages for ${d.bold(s(e))} bump`,options:i,required:!1})}function cP(e,t,r){try{return e.withBump(t,r).label}catch(n){if(n instanceof u)return e.name;throw n}}async function hm(){return(await ve({message:"Stone message (used as commit message)",placeholder:"feat: add new feature",validate:(t)=>t?.trim()?void 0:"Message is required"})).trim()}async function lP(){return(await ve({message:"Description (optional, press enter to skip)",placeholder:"Additional details about this change..."}))?.trim()||void 0}function ym(e){let{ctx:t,selection:r,message:n,packages:s,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=wt(a,s,pe(t.config,i));return{dependency:X(c),description:o,major:X(r.major),message:n,minor:X(r.minor),patch:X(r.patch),tag:i}}async function wm(e,t,r){if(bm(e,t,r),e.args.dryRun)return[{...t}];if(!e.args.yes&&e.interactive&&!await V({initialValue:!0,message:"Create this stone?"}))return[];let n=await new B(e.config).create(t);return te(`Run ${d.green(`${T} roll`)} to release packages
|
|
260
|
+
or create another stone with ${d.green(`${T} version`)}`,`Stone ${d.bold(n.id)} ${d.green("created")}`),[{...t,id:n.id}]}function bm(e,t,r){let n=[];if(e.args.dryRun)n.push(d.bold(d.yellow("[dry-run]")));if(n.push(`${d.dim("Stone:")} ${d.bold(t.message)}`),t.tag)n.push(`${d.dim("Tag:")} ${t.tag}`);for(let s of uP(e,t,r))n.push(` ${s}`);v.step(n.join(`
|
|
261
|
+
`))}function uP(e,t,r){let n=O.create(t);try{return z.applyStone(n,r,pe(e.config).kinds).map((s)=>s.label)}catch(s){if(s instanceof u)return n.allPackages.filter((i)=>r.has(i));throw s}}var pP=[Ud,Gd,Jd,Xd,Zd,cm,gm,fm];function Rm(e=bi()){return no({bin:T,commands:pP,config:e,description:"Monorepo versioning and releases from reviewable stones",interactive:{clearOnStart:!0,exitLabel:"Give Up",goodbyeMessage:"The boulder rolls back down...",promptMessage:"Choose your boulder:"},name:"SISYPHUS",version:Il})}Rm().main();
|