@r5n/sisyphus 0.14.0 → 0.15.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.
Files changed (2) hide show
  1. package/dist/cli.js +181 -175
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,261 +1,267 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
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(`
3
+ class Re extends Error{_tag="Cancel";constructor(e="Operation cancelled"){super(e)}}function q(e){return e}function xi(e){return e==null?[]:Array.isArray(e)?e:[e]}function Lm(e,t,n,r){var s,i=e[t],o=~r.string.indexOf(t)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~r.boolean.indexOf(t)?n==="false"?!1:n==="true"||(e._.push((s=+n,s*0===0)?s:n),!!n):(s=+n,s*0===0)?s:n;e[t]=i==null?o:Array.isArray(i)?i.concat(o):[i,o]}function Ei(e,t){e=e||[],t=t||{};var n,r,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=xi(t.string),t.boolean=xi(t.boolean),g)for(n in t.alias){r=t.alias[n]=xi(t.alias[n]);for(c=0;c<r.length;c++)(t.alias[r[c]]=r.concat(n)).splice(c,1)}for(c=t.boolean.length;c-- >0;){r=t.alias[t.boolean[c]]||[];for(l=r.length;l-- >0;)t.boolean.push(r[l])}for(c=t.string.length;c-- >0;){r=t.alias[t.string[c]]||[];for(l=r.length;l-- >0;)t.string.push(r[l])}if(f){for(n in t.default)if(i=typeof t.default[n],r=t.alias[n]=t.alias[n]||[],t[i]!==void 0){t[i].push(n);for(c=0;c<r.length;c++)t[i].push(r[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]),r=l===2?[i]:i;for(p=0;p<r.length;p++){if(i=r[p],h&&!~y.indexOf(i))return t.unknown("-".repeat(l)+i);Lm(a,i,p+1<r.length||o,t)}}}if(f){for(n in t.default)if(a[n]===void 0)a[n]=t.default[n]}if(g)for(n in a){r=t.alias[n]||[];while(r.length>0)a[r.shift()]=a[n]}return a}var he=0,On=1,za=2,Ka=255;function Tr(e){return Number.isInteger(e)&&e>=0&&e<=255}class u extends Error{hint;exitCode;_tag;constructor(e,t,n=1,r={}){super(e,"cause"in r?{cause:r.cause}:void 0);this.hint=t;this.exitCode=n;this._tag=r.tag??"Exit"}}class N extends u{constructor(e,t,n={}){super(e,t,2,{...n,tag:n.tag??"UsageError"})}}var Ya=1,Dm=2,Ar="--",Za="-",at="no-",Mm=new Set(["false","true"]),Dn=/^--([^=]+)(?:=(.*))?$/s,Mn=/^-([^-=][^=]*)(?:=(.*))?$/s,Ai=/^(?:---|-no-|-_|-[^-=][^=]*_)/,Nm="_",_n="\x00";function _e(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Xt(e){let t={alias:{},boolean:[],default:{},string:[]};for(let[n,r]of Object.entries(e)){if(r.type==="boolean")t.boolean.push(n);else t.string.push(n);if(r.alias)t.alias[r.alias]=n;let s=_e(n);if(s!==n)t.alias[s]=n;if(r.default!==void 0)t.default[n]=r.default}return t}function Ir(e,t){let n={};for(let[o,a]of Object.entries(t.alias))n[a]=[...n[a]??[],o];let{_:r,...s}=Ei(Dr(e,jm),{alias:n,boolean:[...t.boolean],default:{...t.default},string:[...t.string]}),i=Object.entries(s).map(([o,a])=>[Ti(o),Ti(a)]);return{...Object.fromEntries(i),_:r.map(Ti)}}function jm(e){if(e===Za)return`${_n}${e}`;let t=Dn.exec(e);if(Ai.test(e)||Fm(t?.[1]))return`--${_n}${e}`;return(t?t[2]:Mn.exec(e)?.[2])===""?`${e}${_n}`:e}function Fm(e){if(e===void 0)return!1;let t=e.startsWith(at)?e.slice(at.length):e;return t===Nm||t in Object.prototype}function Ti(e){return typeof e==="string"&&e.startsWith(_n)?e.slice(_n.length):e}function Ln(e,t){return Object.hasOwn(t.alias,e)?t.alias[e]??e:e}function Kt(e,t){if(Object.hasOwn(t,e))return`--${_e(e)}`;let n=Object.entries(t).find(([,r])=>r.alias===e)?.[0];if(n)return`--${_e(n)}`;return e.length===Ya?`-${e}`:`--${e}`}function Or(e,t,n,r){let{alias:s}=Xt(t),i=Object.keys(e).find((o)=>!Object.hasOwn(t,o)&&!Object.hasOwn(s,o));if(i!==void 0)throw new N(`Unknown option: ${Bm(i,r)}`,n)}function Bm(e,t){if(e.startsWith("-"))return e;let n=t.indexOf(Ar);for(let r of n<0?t:t.slice(0,n)){let s=Dn.exec(r)?.[1];if(s===e||r===`--${at}${e}`)return`--${s}`;if(s===void 0&&Mn.exec(r)?.[1]?.includes(e))return`-${e}`}return Kt(e,{})}function Qa(e,t){for(let[r,s]of Object.entries(e))if(Array.isArray(s))throw new N(`${Kt(r,t)} can only be provided once`);let n={...e};for(let[r,s]of Object.entries(t)){let i=e[r];if(i===void 0)continue;if(s.type==="string"&&typeof i==="boolean")throw ec(Kt(r,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=Kt(r,t);throw new N(`Invalid number for ${a}: "${i}"`,`Use ${a}=<number> with a finite numeric value`)}n[r]=o}return n}function ec(e){return new N(`${e} needs a value`,`Use ${e}=<value>`)}function _r(e,t){let n=Xt(t),r=_i([...e],n),s=Ir(r,n)._[0],i=s===void 0?-1:r.indexOf(s);return{before:i>=0?e.slice(0,i):[...e],command:s,restArgs:i>=0?e.slice(i+1):[]}}function tc(e,t){let n=Xt(t);for(let r=0;r<e.length;r+=1){let s=e[r]??"";if(s===Ar)return-1;if(s===Za||!s.startsWith("-"))return r;if(Um(s,n,t))r+=1}return-1}function Um(e,t,n){if(e.startsWith(`--${at}`))return!1;let r=Dn.exec(e),s=r??Mn.exec(e);if(!s||s[2]!==void 0)return!1;let i=r?s[1]??"":s[1]?.at(-1)??"",o=n[Ln(i,t)]?.type;return o==="string"||o==="number"}function Oi(e,t,n=t){let r=Xt(t),{before:s,command:i,restArgs:o}=_r(e,t),a=Xt(n);Ii(s,r,t,!0),Ii(e,a,n,!0);let{_:c,...l}=Ir(nc(s,r,t),r);Or(l,t,"Place command options after the command name",s);let{_:p,...m}=Ir(_i(o,a),a),g=Qa({...Xa(l,t,r),...Xa(m,n,a)},t);return{command:i,flags:g,restArgs:o}}function Xa(e,t,n){return Object.fromEntries(Object.entries(e).filter(([r])=>Object.hasOwn(t,r)||Object.hasOwn(n.alias,r)))}function Lr(e,t){return Object.fromEntries(Object.keys(t).flatMap((n)=>{let r=e[n];return r===void 0?[]:[[n,r]]}))}function Nn(e,t={}){let n=Xt(t),r=Gm(e,n);Ii(r,n,t);let s=Ir(nc(r,n,t),n),{_:i,...o}=s;return{args:Qa(o,t),rawPositionals:i.map(String)}}function Ii(e,t,n,r=!1){let s=new Set;for(let i of e){if(i===Ar)break;let o=i.match(/^-+/)?.[0];if(!o||Ai.test(i))continue;let a=i.slice(o.length),c=a.split("=",Ya)[0]??"",l=a.startsWith(at)?[a.slice(at.length)]:o.length===Dm?[c]:[...c];for(let p of l){let m=Ln(p,t);if(r&&!Object.hasOwn(n,m))continue;if(s.has(m))throw new N(`${Kt(m,n)} can only be provided once`);s.add(m)}}}function Dr(e,t){let n=e.indexOf(Ar);return e.map((r,s)=>n>=0&&s>=n?r:t(r,e[s+1]))}function _i(e,t){return Dr(e,(n)=>{let r=Dn.exec(n)??Mn.exec(n);if(!r||r[2]!==void 0||n.startsWith(`--${at}`))return n;let s=n.startsWith("--")?r[1]??"":r[1]?.at(-1)??"";return t.boolean.includes(Ln(s,t))?`${n}=true`:n})}function nc(e,t,n){let r=(o)=>n[Ln(o,t)]?.type,s=(o)=>o!==void 0&&!o.startsWith("-"),i=Dr(e,(o,a)=>{let c=Dn.exec(o),l=c?null:Mn.exec(o);if(o.startsWith(`--${at}`)||Ai.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=r(h),y=g===p.length-1,R=Kt(Ln(h,t),n),S=!y||m===void 0&&!s(a);if(f==="string"&&(S||m===""))throw ec(R);if(f==="number"&&S)throw new N(`${R} needs a value`,`Use ${R}=<number>`);if(f==="boolean"&&y&&m!==void 0&&!Mm.has(m))throw new N(`Invalid value for ${R}: "${m}"`,`Use ${R}=true or ${R}=false`)}return o});return _i(i,t)}function Gm(e,t){return Dr(e,(n)=>n.replace(/^--(no-[^=]+)(=.*)?$/,(r,s,i)=>{let o=t.alias[s];return o&&t.boolean.includes(o)?`--${o}${i??""}`:r}))}function Mr(e,t){let n={},r=Object.entries(t);for(let[s,[i,o]]of r.entries())n[i]=o.variadic?e.slice(s):e[s];return n}function Nr(e,t){for(let[n,r]of Object.entries(t)){if(!r.required)continue;let s=e[n];if(Array.isArray(s)?s.length===0:!s)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}function rc(e,t){let n=Object.values(t);if(n.some((r)=>r.variadic))return;return e[n.length]}var Vm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Hm=new Set(["help","json"]),qm=/^[a-zA-Z0-9]$/,Wm=new Set(["h","j"]);function jr(){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 Jm(t),Object.freeze(t)}}function Fr(e,t){let n=Li(t.map((r)=>r.name));if(n!==void 0)throw Error(`${e} has more than one command named "${n}"`)}function Jm(e){let t=`Command "${e.name}"`;if(!Vm.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(Hm.has(_e(p)))throw Error(`${t} cannot define the option "${p}": --${_e(p)} is a global flag`);if(m.alias!==void 0&&Wm.has(m.alias))throw Error(`${t} cannot give "${p}" the alias -${m.alias}: it belongs to a global flag`)}let n=Object.keys(e.args).map(_e),r=Li(n);if(r!==void 0)throw Error(`${t} has more than one option named --${r}`);let s=Object.values(e.args).flatMap((p)=>p.alias??[]),i=s.find((p)=>!qm.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)=>n.includes(p));if(o!==void 0)throw Error(`${t} uses the alias -${o}, which is also an option's name`);let a=Li(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`);Fr(t,e.subcommands)}function Li(e){return e.find((t,n)=>e.indexOf(t)!==n)}function Pe(e){return e}import{Console as rg}from"console";import{Writable as sg}from"stream";import{format as ig,stripVTControlCharacters as og}from"util";var ct={active:!1};var zm=new Set(["0","false"]);function jn(e){if(process.env.NO_COLOR)return!1;let t=process.env.FORCE_COLOR;if(t!==void 0)return!zm.has(t);return e?.isTTY===!0}var Km=jn(process.stdout),oc=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Xm=["bold","dim","italic","underline","reset"],ac={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Ym={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"},Zm={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"},sc={"\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 Br(e){return(t)=>Km&&!ct.active?`${e}${t}${ac.reset}`:t}function Qm(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32&&n!==27)return!1}return!0}function ic({bright:e=!1,color:t}){let n=Bun.color(t,"ansi"),r=typeof n==="string"&&n.length>0&&Qm(n)?n:Ym[t];if(!r)return"";return e&&r in sc?sc[r]:r}var eg=oc.reduce((e,t)=>{let n=ic({color:t});if(n)e[t]=Br(n);let r=ic({bright:!0,color:t});if(r)e[`${t}Bright`]=Br(r);return e},{}),tg=Xm.reduce((e,t)=>(e[t]=Br(ac[t]),e),{}),ng=oc.reduce((e,t)=>{let n=Zm[t];if(n){let r=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[r]=Br(n)}return e},{}),d={...eg,...tg,...ng};var ag=2,uc=["clear","count","countReset","debug","dir","dirxml","group","groupCollapsed","groupEnd","info","log","table"],cg=[...uc,"trace","write"],lg=1,ug="EPIPE",pg="EIO",W={closedStreams:new Set,documentWritten:!1,jsonRuns:0,outputGuarded:!1,restoreStdout:void 0,sealed:!1,stdoutClosed:!1,stdoutWrite:void 0};function Fn(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Le(e){return Fn()&&!ct.active&&e?.json!==!0}function pc(){return ct.active}function lt(e){let t=JSON.stringify(e??null,null,ag);if(t===void 0)throw TypeError("JSON cannot represent the value");return`${t}
4
+ `}function dc(){return W.documentWritten}function mc(){W.sealed=!0}function Qe(e){if(W.documentWritten=!0,W.sealed||W.stdoutClosed)return;let t=W.stdoutWrite??process.stdout.write;try{t.call(process.stdout,e)}catch(n){if(!Ur(n,process.stdout))throw n;W.stdoutClosed=!0}}function gc(){if(W.outputGuarded)return;W.outputGuarded=!0,process.stdout.write=cc(process.stdout.write,!0),console.write=cc(console.write,0),process.stdout.on("error",(e)=>{if(!Ur(e,process.stdout))throw e;W.stdoutClosed=!0}),process.stderr.on("error",(e)=>{if(!Ur(e,process.stderr))throw e});for(let e of[process.stdout,process.stderr])e.once("close",()=>W.closedStreams.add(e))}function cc(e,t){let n=(r)=>{let s=r.at(-1);if(typeof s==="function")queueMicrotask(()=>s());return t};return function(...s){if(W.stdoutClosed)return n(s);try{return e.apply(this,s)}catch(i){if(!Ur(i,process.stdout))throw i;return W.stdoutClosed=!0,n(s)}}}function Ur(e,t){if(!(e instanceof Error))return!1;let n=Reflect.get(e,"code");return n===ug||n===pg&&t.isTTY===!0}function Gr(){let e=jn(process.stderr);return new sg({decodeStrings:!1,write(t,n,r){process.stderr.write(e?t:og(t)),r()}})}async function fc(e,t){if(!e)return t();W.jsonRuns+=1,W.restoreStdout??=dg(),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 hc(e){let t=Promise.all([W.stdoutClosed?void 0:lc(process.stdout),lc(process.stderr)]);await(e===void 0?t:Promise.race([t,Bun.sleep(e)]))}function lc(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 dg(){let e=process.stdout.write,t=new rg({stderr:process.stderr,stdout:process.stderr}),n=Object.fromEntries(cg.map((s)=>[s,console[s]])),r=Object.fromEntries(uc.map((s)=>[s,t[s].bind(t)]));return W.stdoutWrite=e,process.stdout.write=process.stderr.write.bind(process.stderr),Object.assign(console,r,{trace:mg(t),write:gg}),()=>{process.stdout.write=e,Object.assign(console,n),W.stdoutWrite=void 0}}function mg(e){let t=(...n)=>{let r={};Error.captureStackTrace(r,t);let s=r.stack?.split(`
5
+ `).slice(lg)??[];e.error([`Trace: ${ig(...n)}`,...s].join(`
6
+ `))};return t}function gg(...e){let t=Buffer.concat(e.map(fg));return process.stderr.write(t),t.byteLength}function fg(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 ve={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"}},Yt={help:ve.help,json:ve.json},At="help",Vr={[he]:"success",[On]:"failure",[za]:"usage error"};import{stripVTControlCharacters as Yi}from"util";import{styleText as Tg}from"util";import{stdout as Ac,stdin as Ig}from"process";import Ag from"readline";var yc=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let n=0;e.lastIndex=0;while(e.test(t))n+=1;return t.length-n}})(),wc=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,bc=(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 hg=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,yg=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Rc=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,wg=/\t{1,1000}/y,$c=/[\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,bg=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Rg=/\p{M}+/gu,$g={limit:1/0,ellipsis:""},Pc=(e,t={},n={})=>{let r=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?Pc(s,$g,n).width:0),o=0,a=n.controlWidth??0,c=n.tabWidth??8,l=n.emojiWidth??2,p=2,m=n.regularWidth??1,g=n.wideWidth??2,h=[[bg,m],[hg,0],[yg,a],[wg,c],[$c,l],[Rc,g]],f=0,y=0,R=e.length,S=0,k=!1,ee=R,V=Math.max(0,r-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(Rg,"")){let be=we.codePointAt(0)||0;if(wc(be))x=2;else if(bc(be))x=g;else x=m;if(H+x>V)ee=Math.min(ee,Math.max(L,f)+S);if(H+x>r){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,Ja]=h[D];if(be.lastIndex=y,be.test(e)){if(S=be===Rc?yc(e.slice(y,be.lastIndex)):be===$c?1:be.lastIndex-y,x=S*Ja,H+x>V)ee=Math.min(ee,y+Math.floor((V-H)/Ja));if(H+x>r){k=!0;break e}H+=x,L=f,Y=y,y=f=be.lastIndex;continue e}}y+=1}return{width:k?V:H,index:k?ee:R,truncated:k,ellipsed:k&&r>=i}},vc=Pc;var Pg={limit:1/0,ellipsis:"",ellipsisWidth:0},vg=(e,t={})=>vc(e,Pg,t).width,oe=vg;var Hr="\x1B",Ec="\x9B",Sg=39,Mi="\x07",Tc="[",Cg="]",Ic="m",Ni=`${Cg}8;;`,Sc=new RegExp(`(?:\\${Tc}(?<code>\\d+)m|\\${Ni}(?<uri>.*)${Mi})`,"y"),Cc=(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},kc=(e)=>`${Hr}${Tc}${e}${Ic}`,xc=(e)=>`${Hr}${Ni}${e}${Mi}`,Di=(e,t,n)=>{let r=t[Symbol.iterator](),s=!1,i=!1,o=e.at(-1),a=o===void 0?0:oe(o),c=r.next(),l=r.next(),p=0;while(!c.done){let m=c.value,g=oe(m);if(a+g<=n)e[e.length-1]+=m;else e.push(m),a=0;if(m===Hr||m===Ec)s=!0,i=t.startsWith(Ni,p+1);if(s){if(i){if(m===Mi)s=!1,i=!1}else if(m===Ic)s=!1}else if(a+=g,a===n&&!l.done)e.push(""),a=0;c=l,l=r.next(),p+=m.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},kg=(e)=>{let t=e.split(" "),n=t.length;while(n){if(oe(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},xg=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",s,i,o=e.split(" "),a=[""],c=0;for(let m=0;m<o.length;m++){let g=o[m];if(n.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&&(n.wordWrap===!1||n.trim===!1))a.push(""),c=0;if(c||n.trim===!1)a[a.length-1]+=" ",c++}let h=oe(g);if(n.hard&&h>t){let f=t-c,y=1+Math.floor((h-f-1)/t);if(Math.floor((h-1)/t)<y)a.push("");Di(a,g,t),c=oe(a.at(-1)??"");continue}if(c+h>t&&c&&h){if(n.wordWrap===!1&&c<t){Di(a,g,t),c=oe(a.at(-1)??"");continue}a.push(""),c=0}if(c+h>t&&n.wordWrap===!1){Di(a,g,t),c=oe(a.at(-1)??"");continue}a[a.length-1]+=g,c+=h}if(n.trim!==!1)a=a.map((m)=>kg(m));let l=a.join(`
7
+ `),p=!1;for(let m=0;m<l.length;m++){let g=l[m];if(r+=g,!p){if(p=g>="\uD800"&&g<="\uDBFF",p)continue}else p=!1;if(g===Hr||g===Ec){Sc.lastIndex=m+1;let f=Sc.exec(l)?.groups;if(f?.code!==void 0){let y=Number.parseFloat(f.code);s=y===Sg?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)r+=xc("");let h=s?Cc(s):void 0;if(s&&h)r+=kc(h)}else if(g===`
9
+ `){if(s&&Cc(s))r+=kc(s);if(i)r+=xc(i)}}return r},Eg=/\r?\n/;function ut(e,t,n){return String(e).normalize().split(Eg).map((r)=>xg(r,t,n)).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 n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"};var Bn={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?Se.up():"");if(e)t+=Se.left;return t}};function Ot(e,t,n){if(!n.some((o)=>!o.disabled))return e;let r=e+t,s=Math.max(n.length-1,0),i=r<0?s:r>s?0:r;return n[i]?.disabled?Ot(i,t<0?-1:1,n):i}var Og=["up","down","left","right","space","enter","cancel"],_g=["January","February","March","April","May","June","July","August","September","October","November","December"],ae={actions:new Set(Og),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:[..._g],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 Oc(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 _c(e,t){if(typeof e=="string")return ae.aliases.get(e)===t;for(let n of e)if(n!==void 0&&_c(n,t))return!0;return!1}function Lg(e,t){if(e===t)return;let n=e.split(`
11
+ `),r=t.split(`
12
+ `),s=Math.max(n.length,r.length),i=[];for(let o=0;o<s;o++)n[o]!==r[o]&&i.push(o);return{lines:i,numLinesBefore:n.length,numLinesAfter:r.length,numLines:s}}var AS=globalThis.process.platform.startsWith("win"),Wr=Symbol("clack:cancel");function Un(e){return e===Wr}function qr(e,t){let n=e;n.isTTY&&n.setRawMode(t)}var Zt=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,ji=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function et(e,t,n,r=n,s=n,i){let o=Zt(e??Ac),a=oe(n);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?`${r}${m}`:l===p.length-1?`${s}${m}`:`${n}${m}`}).join(`
14
+ `)}function Lc(e,t){if("~standard"in e){let n=e["~standard"].validate(t);return n instanceof Promise?n.then((r)=>r.issues?.at(0)?.message):n.issues?.at(0)?.message}return e(t)}var Jr=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return Oc(this.opts.accessible)}constructor(t,n=!0){let{input:r=Ig,output:s=Ac,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=n,this._abortSignal=o,this.input=r,this.output=s}unsubscribe(){this._subscribers.clear()}setSubscriber(t,n){let r=this._subscribers.get(t)??[];r.push(n),this._subscribers.set(t,r)}on(t,n){this.setSubscriber(t,{cb:n})}once(t,n){this.setSubscriber(t,{cb:n,once:!0})}emit(t,...n){let r=this._subscribers.get(t)??[],s=[];for(let i of r)i.cb(...n),i.once&&s.push(()=>r.splice(r.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(Wr);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Ag.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),qr(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),qr(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Se.show),this.output.off("resize",this.render),qr(this.input,!1),t(Wr)})})}_isActionKey(t,n){return t==="\t"}_shouldSubmit(t,n){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,n){this.userInput=t??"",this.emit("userInput",this.userInput),n&&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,n){if(this.state!=="validating"){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(t,n)&&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"),n?.name&&(!this._track&&ae.aliases.has(n.name)&&this.emit("cursor",ae.aliases.get(n.name)),ae.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,n),n?.name==="return"&&this._shouldSubmit(t,n)){if(this.opts.validate){let r=Lc(this.opts.validate,this.value),s;r instanceof Promise?(this.state="validating",this.render(),s=await r):s=r,s&&(this.error=s instanceof Error?s.message:s,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}_c([t,n?.name,n?.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
+ `),qr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=ut(this._prevFrame,Zt(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)??"",Zt(this.output),{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Se.hide);else{let n=Lg(this._prevFrame,t),r=ji(this.output);if(this.restoreCursor(),n){let s=Math.max(0,n.numLinesAfter-r),i=Math.max(0,n.numLinesBefore-r),o=n.lines.find((a)=>a>=s);if(o===void 0){this._prevFrame=t;return}if(n.lines.length===1){this.output.write(Se.move(0,o-i)),this.output.write(Bn.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(n.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(Bn.down());let a=t.split(`
18
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)}
19
+ `)),this._prevFrame=t;return}}this.output.write(Bn.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};class Fi extends Jr{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 Bi extends Jr{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?Ot(t,1,this.options):t,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert(),r.name===void 0&&n==="\u3000"&&this.toggleValue()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=Ot(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ot(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Dc=class extends Jr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let t=this._selectedValue;this.value=t===void 0?void 0:t.value}constructor(t){super(t,!1),this.options=t.options;let n=this.options.findIndex(({value:s})=>s===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?Ot(r,1,this.options):r,this.changeValue(),this.on("cursor",(s)=>{switch(s){case"left":case"up":this.cursor=Ot(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Ot(this.cursor,1,this.options);break}this.changeValue()})}};class Ui extends Jr{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${Tg("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",(t)=>{this._setValue(t)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as w,stripVTControlCharacters as VS}from"util";import Ce from"process";function Dg(){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 Hi=Dg(),Uc=()=>process.env.CI==="true";var F=(e,t)=>Hi?e:t,Mc=F("\u25C6","*"),qi=F("\u25A0","x"),Wi=F("\u25B2","x"),Vn=F("\u25C7","o"),Mg=F("\u250C","T"),E=F("\u2502","|"),tt=F("\u2514","\u2014"),zS=F("\u2510","T"),KS=F("\u2518","\u2014"),Gi=F("\u25CF",">"),Kr=F("\u25CB"," "),Ng=F("\u25FB","[\u2022]"),Nc=F("\u25FC","[+]"),jc=F("\u25FB","[ ]"),XS=F("\u25AA","\u2022"),Fc=F("\u2500","-"),jg=F("\u256E","+"),Fg=F("\u251C","+"),Bg=F("\u256F","+"),Ug=F("\u2570","+"),YS=F("\u256D","+"),Gg=F("\u25CF","\u2022"),Vg=F("\u25C6","*"),Hg=F("\u25B2","!"),qg=F("\u25A0","x"),Xr=(e)=>{switch(e){case"initial":case"active":return w("cyan",Mc);case"cancel":return w("red",qi);case"error":return w("yellow",Wi);case"submit":return w("green",Vn);case"validating":return w("dim",Mc)}},Gc=(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 Vc(e,t,n){let r=n?`${w("cyan",E)} `:"",s=et(e,t.join(" \u2022 "),r).split(`
20
+ `);return n&&s.push(w("cyan",tt)),s}var Bc=(e,t,n,r,s,i=!1)=>{let o=t,a=0;if(i)for(let c=r-1;c>=n;c--){let l=e[c];if(l&&(o-=l.length),a++,o<=s)break}else for(let c=n;c<r;c++){let l=e[c];if(l&&(o-=l.length),a++,o<=s)break}return{lineCount:o,removals:a}},Vi=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:s=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=Zt(r)-i,c=ji(r),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?n(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=()=>Bc(R,H,0,x,D),be=()=>Bc(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 V=[];h&&V.push(l);for(let L of R)for(let Y of L)V.push(Y);return f&&V.push(l),V};var Hc=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new Fi({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??ae.withGuide,s=`${Xr(this.state)} `,i=r?`${w("gray",E)} `:"",o=et(e.output,e.message,i,s),a=`${r?`${w("gray",E)}
22
22
  `:""}${o}
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?`
23
+ `,c=this.value?t:n;switch(this.state){case"submit":{let l=r?`${w("gray",E)} `:"";return`${a}${l}${w("dim",c)}`}case"cancel":{let l=r?`${w("gray",E)} `:"";return`${a}${l}${w(["strikethrough","dim"],c)}${r?`
24
+ ${w("gray",E)}`:""}`}default:{let l=r?`${w("cyan",E)} `:"",p=r?w("cyan",tt):"";return`${a}${l}${this.value?`${w("green",Gi)} ${t}`:`${w("dim",Kr)} ${w("dim",t)}`}${e.vertical?r?`
25
25
  ${w("cyan",E)} `:`
26
- `:` ${w("dim","/")} `}${this.value?`${w("dim",zn)} ${w("dim",r)}`:`${w("green",Bi)} ${r}`}
26
+ `:` ${w("dim","/")} `}${this.value?`${w("dim",Kr)} ${w("dim",n)}`:`${w("green",Gi)} ${n}`}
27
27
  ${p}
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(`
29
- `).map((r)=>t(r)).join(`
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
+ `}}}}).prompt()};var Yr=async(e,t)=>{let n={},r=Object.keys(e);for(let s of r){let i=e[s],o=await i({results:n})?.catch((a)=>{throw a});if(typeof t?.onCancel=="function"&&Un(o)){n[s]="canceled",t.onCancel({results:n});continue}n[s]=o}return n},Wg=[`${w("dim","\u2191/\u2193")} to navigate`,`${w("dim","Space:")} select`,`${w("dim","Enter:")} confirm`],Gn=(e,t)=>e.split(`
29
+ `).map((n)=>t(n)).join(`
30
+ `),qc=(e)=>{let t=(s,i)=>{let o=s.label??String(s.value);return i==="disabled"?`${w("gray",jc)} ${Gn(o,(a)=>w(["strikethrough","gray"],a))}${s.hint?` ${w("dim",`(${s.hint??"disabled"})`)}`:""}`:i==="active"?`${w("cyan",Ng)} ${o}${s.hint?` ${w("dim",`(${s.hint})`)}`:""}`:i==="selected"?`${w("green",Nc)} ${Gn(o,(a)=>w("dim",a))}${s.hint?` ${w("dim",`(${s.hint})`)}`:""}`:i==="cancelled"?`${Gn(o,(a)=>w(["strikethrough","dim"],a))}`:i==="active-selected"?`${w("green",Nc)} ${o}${s.hint?` ${w("dim",`(${s.hint})`)}`:""}`:i==="submitted"?`${Gn(o,(a)=>w("dim",a))}`:`${w("dim",jc)} ${Gn(o,(a)=>w("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new Bi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(s){if(n&&(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=et(e.output,e.message,s?`${Gc(this.state)} `:"",`${Xr(this.state)} `),o=`${s?`${w("gray",E)}
32
32
  `:""}${i}
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?`
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=et(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=et(e.output,l,s?`${w("gray",E)} `:"");return`${o}${p}${s?`
34
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(`
35
+ `).map((h,f)=>f===0?`${s?`${w("yellow",tt)} `:""}${w("yellow",h)}`:` ${h}`).join(`
36
36
  `),m=o.split(`
37
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(`
38
+ `).length+1;return`${o}${l}${Vi({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:m+g,style:c}).join(`
39
39
  ${l}`)}
40
40
  ${p}
41
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(`
42
+ `).length,m=r?Vc(e.output,Wg,s):s?[w("cyan",tt)]:[],g=m.join(`
43
+ `),h=m.length+1;return`${o}${l}${Vi({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:l.length,rowPadding:p+h,style:c}).join(`
44
44
  ${l}`)}
45
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(`
46
+ `}}}}).prompt()};var ue={message:(e=[],{symbol:t=w("gray",E),secondarySymbol:n=w("gray",E),output:r=process.stdout,spacing:s=1,withGuide:i}={})=>{let o=[],a=i??ae.withGuide,c=a?n:"",l=a?`${t} `:"",p=a?`${n} `:"";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?n:"")}r.write(`${o.join(`
48
48
  `)}
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}
49
+ `)},info:(e,t)=>{ue.message(e,{...t,symbol:w("blue",Gg)})},success:(e,t)=>{ue.message(e,{...t,symbol:w("green",Vg)})},step:(e,t)=>{ue.message(e,{...t,symbol:w("green",Vn)})},warn:(e,t)=>{ue.message(e,{...t,symbol:w("yellow",Hg)})},warning:(e,t)=>{ue.warn(e,t)},error:(e,t)=>{ue.message(e,{...t,symbol:w("red",qg)})}};var Wc=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??ae.withGuide?`${w("gray",Mg)} `:"";n.write(`${r}${e}
50
+ `)},Jc=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??ae.withGuide?`${w("gray",E)}
51
+ ${w("gray",tt)} `:"";n.write(`${r}${e}
52
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(`
53
+ `)};var Jg=(e)=>e,zg=(e,t,n)=>{let r={hard:!0,trim:!1},s=ut(e,t,r).split(`
54
+ `),i=s.reduce((c,l)=>Math.max(oe(l),c),0),o=s.map(n).reduce((c,l)=>Math.max(oe(l),c),0),a=t-(o-i);return ut(e,a,r)},zc=(e="",t="",n)=>{let r=n?.output??Ce.stdout,s=n?.withGuide??ae.withGuide,i=n?.format??Jg,o=["",...zg(e,Zt(r)-6,i).split(`
55
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
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)}
57
+ `:"",m=s?Fg:Ug;r.write(`${p}${w("green",Vn)} ${w("reset",t)} ${w("gray",Fc.repeat(Math.max(c-a-1,1))+jg)}
58
58
  ${l}
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(`
59
+ ${w("gray",m+Fc.repeat(c+2)+Bg)}
60
+ `)};var ZS={light:F("\u2500","-"),heavy:F("\u2501","="),block:F("\u2588","#")};var Kg=[`${w("dim","\u2191/\u2193")} to navigate`,`${w("dim","Enter:")} confirm`],zr=(e,t)=>e.includes(`
61
61
  `)?e.split(`
62
- `).map((r)=>t(r)).join(`
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)}
62
+ `).map((n)=>t(n)).join(`
63
+ `):t(e),Kc=(e)=>{let t=(r,s)=>{if(r===void 0)return"";let i=r.label??String(r.value);switch(s){case"disabled":return`${w("gray",Kr)} ${zr(i,(o)=>w("gray",o))}${r.hint?` ${w("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${zr(i,(o)=>w("dim",o))}`;case"active":return`${w("green",Gi)} ${i}${r.hint?` ${w("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${zr(i,(o)=>w(["strikethrough","dim"],o))}`;default:return`${w("dim",Kr)} ${zr(i,(o)=>w("dim",o))}`}},n=e.showInstructions??!0;return new Dc({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??ae.withGuide,s=`${Xr(this.state)} `,i=`${Gc(this.state)} `,o=et(e.output,e.message,i,s),a=`${r?`${w("gray",E)}
64
64
  `:""}${o}
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(`
65
+ `;switch(this.state){case"submit":{let c=r?`${w("gray",E)} `:"",l=et(e.output,t(this.options[this.cursor],"selected"),c);return`${a}${l}`}case"cancel":{let c=r?`${w("gray",E)} `:"",l=et(e.output,t(this.options[this.cursor],"cancelled"),c);return`${a}${l}${r?`
66
+ ${w("gray",E)}`:""}`}default:{let c=r?`${w("cyan",E)} `:"",l=a.split(`
67
+ `).length,p=n?Vc(e.output,Kg,r):r?[w("cyan",tt)]:[],m=p.join(`
68
+ `),g=p.length+1;return`${a}${c}${Vi({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(`
69
69
  ${c}`)}
70
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}
71
+ `}}}}).prompt()};var QS=`${w("gray",E)} `;var Xc=(e)=>new Ui({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,n=`${`${t?`${w("gray",E)}
72
+ `:""}${Xr(this.state)} `}${e.message}
73
+ `,r=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:r,i=this.value??"";switch(this.state){case"validating":{let o=t?`${w("cyan",E)} `:"",a=t?w("cyan",tt):"",c=w("dim",s),l=w("dim","Validating...");return`${n}${o}${c}
74
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()}
75
+ `}case"error":{let o=this.error?` ${w("yellow",this.error)}`:"",a=t?`${w("yellow",E)} `:"",c=t?w("yellow",tt):"";return`${n.trim()}
76
76
  ${a}${s}
77
77
  ${c}${o}
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}
78
+ `}case"submit":{let o=i?`${t?" ":""}${w("dim",i)}`:"",a=t?w("gray",E):"";return`${n}${a}${o}`}case"cancel":{let o=i?` ${w(["strikethrough","dim"],i)}`:"",a=t?w("gray",E):"";return`${n}${a}${o}${i.trim()?`
79
+ ${a}`:""}`}default:{let o=t?`${w("cyan",E)} `:"",a=t?w("cyan",tt):"";return`${n}${o}${s}
80
80
  ${a}
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&ee;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(`
81
+ `}}}}).prompt();function Yc(e=process.stdin){return e.readableEnded||e.destroyed}async function Zc({edits:e,input:t=process.stdin,signal:n},r){let s=new AbortController,i=()=>s.abort(),o=(c,l)=>{if(l.sequence==="\x04"&&(!e||t.isPaused()))i()},a=r(n?AbortSignal.any([s.signal,n]):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 Yg}from"util";var Ji=Hi?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],Zg=80,Qg=8,ef=3,tf="...",zi="\r\x1B[K",nf=80,rf=/\s*\n\s*/g,Hn=new Set;function el(){for(let e of[...Hn])e.error()}function tl({output:e=process.stdout}={}){let t=e.isTTY===!0&&!Uc(),n=jn(e),r="",s=0,i=!1,o,a=(h)=>{e.write(t||n?h:Yg(h))},c=()=>{let h=d.magenta(Ji[s%Ji.length]??""),f=".".repeat(Math.floor(s/Qg)%(ef+1)),y=`${h} ${r.replace(rf," ")}${f}`;a(`${zi}${Bun.sliceAnsi(y,0,(e.columns||nf)-1)}`),s+=1},l=()=>t?c():a(`${d.magenta(Ji[0]??"")} ${r}${tf}
82
+ `),p=()=>(clearInterval(o),Hn.delete(g)),m=(h,f)=>{if(p())a(`${t?zi:""}${h} ${f}
83
+ `)},g={cancel(h=r){i=Hn.has(g)||i,m(d.red(qi),h)},clear(){if(p()&&t)a(zi)},error(h=r){m(d.red(Wi),h)},get isCancelled(){return i},message(h=r){let f=Qc(h);if(f===r)return;if(r=f,Hn.has(g)&&!t)l()},start(h=""){if(g.clear(),i=!1,r=Qc(h),s=0,Hn.add(g),a(`${d.gray(E)}
84
+ `),l(),!t)return;o=setInterval(c,Zg),o.unref()},stop(h=r){m(d.green(Vn),h)}};return g}function Qc(e){return e.replace(/\.+$/,"")}var sf="Pass the value as an argument or option instead";function of(e){if(Un(e))throw new Re;return e}function af(e){if(Le())return;throw new N(`Cannot prompt for ${e} without a terminal`,sf)}async function Zr(e,t,{edits:n=!1,hint:r}){if(af(t.message),Yc(t.input))throw new Re;return lf(r),of(await Zc({...t,edits:n},(s)=>e({...t,signal:s})))}function cf(e){return e.map((t)=>t.key?`${d.bold(t.key)} ${d.dim(t.text)}`:d.dim(t.text)).join(d.dim(" \xB7 "))}function lf(e){ue.info(cf(e))}var Qr={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 G(e){return Zr(Hc,e,{hint:Qr.confirm})}async function $e(e){return Zr(Xc,e,{edits:!0,hint:Qr.text})}async function _t(e){return Zr(Kc,{showInstructions:!1,...e},{hint:Qr.select})}async function nt(e){return Zr(qc,{showInstructions:!1,...e},{hint:Qr.multiselect})}function en(e){return pc()&&e.output===void 0?{...e,output:process.stderr}:e}function Qt(e){return(t,n={})=>e(t,en(n))}var P={error:Qt(ue.error),info:Qt(ue.info),message:(e,t={})=>ue.message(e,en(t)),step:Qt(ue.step),success:Qt(ue.success),warn:Qt(ue.warn),warning:Qt(ue.warning)};function Ki(e,t={}){Wc(e,en(t))}function Xi(e,t={}){Jc(e,en(t))}function te(e,t,n={}){zc(e,t,en(n))}function Ve(e={}){return tl(en(e))}import{inspect as uf}from"util";var pf=4;function es(e,t=[]){if(t.length>=pf)return[];let n=e instanceof AggregateError?e.errors:[],r=[...t,e];return[...n,...e.cause!==void 0?[e.cause]:[]].filter((i)=>!r.includes(i)).flatMap((i)=>[{hint:ns(i),message:ts(i)},...i instanceof Error?es(i,r):[]])}function ts(e){return rs(e instanceof Error?e.message||e.name:e)}function ns(e){return e instanceof u&&e.hint!==void 0?rs(e.hint):void 0}function rs(e){return typeof e==="string"?e:uf(e,{breakLength:Number.POSITIVE_INFINITY})}var df="Error",mf=27,gf=new RegExp(`${String.fromCharCode(mf)}\\[[\\d;]*m`,"g"),ff=9,hf=10,yf=31,wf=127,bf=159,Rf=16,$f=4;function pt(e,{json:t}){if(el(),Sf(e),t)Qe(lt({error:Pf(e)}));return nl(e)}function Pf(e){let t=nl(e),n=Yi(ts(e));if(!(e instanceof Error))return{_tag:df,message:n,exitCode:t,causes:[]};let r=ns(e);return{_tag:vf(e),message:n,hint:r===void 0?void 0:Yi(r),exitCode:t,causes:es(e).map((s)=>Yi(s.message))}}function nl(e){if(e instanceof Re)return he;if(e instanceof u)return Tr(e.exitCode)?e.exitCode:On;return On}function vf(e){let t=Reflect.get(e,"_tag");return typeof t==="string"?t:rs(e.name)}function Sf(e){if(e instanceof Re)return;let t=Gr(),n=ss(ts(e));if(e instanceof u){let r=ns(e);if(P.warn(d.yellow(n),{output:t}),r)P.info(d.dim(ss(r)),{output:t})}else P.error(d.red(n),{output:t});if(!(e instanceof Error))return;for(let r of es(e))if(P.info(d.dim(`caused by: ${ss(r.message)}`),{output:t}),r.hint)P.info(d.dim(` ${ss(r.hint)}`),{output:t})}function ss(e){return Array.from(e.replace(gf,""),(t)=>{let n=t.charCodeAt(0);return n<=yf&&n!==ff&&n!==hf||n>=wf&&n<=bf?`\\u${n.toString(Rf).padStart($f,"0")}`:t}).join("")}var Cf=500,kf="The command stopped before it finished because nothing was left for it to wait for";function rl({json:e}){let t={ending:void 0,failed:!1,settled:!1},n=(s,i)=>(t.ending??=xf(s,i),t.ending),r=(s)=>{if(t.failed||t.ending)return;t.failed=!0;let i=pt(s,{json:e&&!dc()});mc(),n(i,t.settled?void 0:Cf)};return process.on("uncaughtException",r),process.on("unhandledRejection",r),process.on("beforeExit",()=>{if(!t.settled)r(Error(kf))}),{exit:(s)=>n(s),settle(){t.settled=!0}}}async function xf(e,t){process.exitCode=e,await hc(t),process.exit(e)}var rt=new Uint32Array(65536),Ef=(e,t)=>{let n=e.length,r=t.length,s=1<<n-1,i=-1,o=0,a=n,c=n;while(c--)rt[e.charCodeAt(c)]|=1<<c;for(c=0;c<r;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=n;while(c--)rt[e.charCodeAt(c)]=0;return a},Tf=(e,t)=>{let n=t.length,r=e.length,s=[],i=[],o=Math.ceil(n/32),a=Math.ceil(r/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,r)+R;for(let k=R;k<S;k++)rt[e.charCodeAt(k)]|=1<<k;for(let k=0;k<n;k++){let ee=rt[t.charCodeAt(k)],V=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^V)i[k/32|0]^=1<<k;if(D>>>31^L)s[k/32|0]^=1<<k;x=x<<1|V,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,r-m)+m;for(let f=m;f<g;f++)rt[e.charCodeAt(f)]|=1<<f;let h=r;for(let f=0;f<n;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,V=l|~(ee|p),L=p&ee;if(h+=V>>>r-1&1,h-=L>>>r-1&1,V>>>31^R)i[f/32|0]^=1<<f;if(L>>>31^S)s[f/32|0]^=1<<f;V=V<<1|R,L=L<<1|S,p=L|~(k|V),l=V&k}for(let f=m;f<g;f++)rt[e.charCodeAt(f)]=0;return h},If=(e,t)=>{if(e.length<t.length){let n=t;t=e,e=n}if(t.length===0)return e.length;if(e.length<=32)return Ef(e,t);return Tf(e,t)},sl=(e,t)=>{let n=1/0,r=0;for(let s=0;s<t.length;s++){let i=If(e,t[s]);if(i<n)n=i,r=s}return t[r]};function is(e,t,n){let r=t.length>0?sl(e,[...t]):void 0,s=`Run "${n} --help" for usage.`;return new N(`Unknown command: ${e}`,r?`Did you mean "${r}"? ${s}`:s)}function Lt(e,t){if(Array.isArray(t))return[...t];if(!il(e)||!il(t))return t;return Object.fromEntries([...Object.entries(e),...Object.entries(t).map(([n,r])=>[n,Lt(Object.hasOwn(e,n)?e[n]:void 0,r)])])}function il(e){if(e===null||typeof e!=="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ol(e,t){return{name:e.name,bin:e.bin,version:e.version,description:e.description,exitCodes:{...Vr},options:al(ve),commands:t.map((n)=>os(n,`${e.bin} ${n.name}`))}}function os(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(([n,r])=>({name:n,required:r.required??!1,variadic:r.variadic??!1,description:r.description??""})),options:al(e.args),examples:[...e.examples],commands:e.subcommands.map((n)=>os(n,`${t} ${n.name}`))}}function al(e){return Object.entries(e).map(([t,n])=>({name:t,flag:`--${_e(t)}`,...n.alias?{alias:`-${n.alias}`}:{},type:n.type,...n.default===void 0?{}:{default:n.default},...n.displayDefault===void 0?{}:{displayDefault:n.displayDefault},description:n.description??""}))}import{stripVTControlCharacters as cl}from"util";var Af=2,Of="0.0.0",_f=(e)=>e,I={arg:d.magenta,cmd:d.cyan,default:d.bold,desc:_f,flag:d.green,header:(e)=>d.bold(d.yellow(e)),hint:d.dim,name:(e)=>d.bold(d.cyan(e)),placeholder:d.magenta};function ll(e){return`${I.name(e.name)} ${I.hint(e.version??Of)}`}function ul(e,t){let n=`${I.name(e.name)}${e.version?` ${I.hint(`v${e.version}`)}`:""}`;return dl([[n,...e.description?[I.desc(e.description)]:[]],He("Usage:",[` ${I.cmd(e.bin)} ${I.placeholder("[command]")} ${I.placeholder("[options]")}`]),He("Commands:",ml(t)),He("Options:",fl(ve)),He("Exit codes:",gl()),[`${I.hint("Run")} ${I.cmd(`${e.bin} <command> --help`)} ${I.hint("for command details.")}`]])}function pl(e,t){let n=e.json?{...e.args,json:ve.json}:e.args,r=[...e.subcommands.length>0?[` ${I.cmd(t)} ${I.placeholder("<command>")} ${I.placeholder("[options]")}`]:[],...e.run?[` ${Lf(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 dl([[I.name(t),I.desc(e.description)],He("Usage:",r),He("Commands:",ml(e.subcommands)),He("Arguments:",Mf(e.positionals)),He("Options:",fl(n)),He("Examples:",e.examples.map((s)=>` ${I.cmd(s)}`)),He("Exit codes:",gl())])}function Lf(e,t){let n=Df(e.positionals);return e.passthrough?[I.cmd(t),I.placeholder("[options]"),I.placeholder("[--]"),...n]:[I.cmd(t),...n,I.placeholder("[options]")]}function He(e,t){return t.length>0?[I.header(e),...t]:[]}function dl(e){return e.filter((t)=>t.length>0).map((t)=>t.join(`
85
85
  `)).join(`
86
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
87
+ `)}function ml(e){return as(e.map((t)=>[` ${I.cmd(t.name)}`,I.desc(t.description)]))}function gl(){return as(Object.entries(Vr).map(([e,t])=>[` ${e}`,t]))}function Zi(e,t){return t.variadic?`${e}...`:e}function Df(e){return Object.entries(e).map(([t,n])=>n.required?I.arg(`<${Zi(t,n)}>`):I.arg(`[${Zi(t,n)}]`))}function Mf(e){return as(Object.entries(e).map(([t,n])=>[` ${I.arg(Zi(t,n))}`,`${I.desc(n.description??"")}${n.required?"":I.hint(" (optional)")}`]))}function fl(e){return as(Object.entries(e).map(([t,n])=>{let r=n.alias?`${I.flag(`-${n.alias}`)}, `:" ",s=n.type==="boolean"?"":` ${I.placeholder(`<${n.type==="number"?"number":"value"}>`)}`,i=Nf(n),o=i===void 0?"":` (default: ${I.default(i)})`;return[` ${r}${I.flag(`--${_e(t)}`)}${s}`,`${I.desc(n.description??"")}${o}`]}))}function Nf(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 as(e){let t=Math.max(0,...e.map(([n])=>cl(n).length));return e.map(([n,r])=>`${n}${" ".repeat(t-cl(n).length+Af)}${r}`)}function cs(e){let t=!1;return{emitted:()=>t,json:e,result(n,r){if(t)throw Error("ctx.output.result was called more than once; a command emits one result");let s=jf(e,n,r);if(t=!0,s!==void 0)Qe(s)}}}function jf(e,t,n){if(e)return lt(t);return n?`${n(t)}
88
+ `:void 0}function ls(e,t,n){return{args:t.args,cli:e.info,config:e.config,interactive:t.interactive,json:t.json,output:n,positionals:t.positionals}}async function us(e,t,n,r){let s=await fc(n.json,async()=>{let i=await e.run?.(n);return typeof i==="number"?Ff(t,i):he});if(n.json&&!r.emitted())throw Error(`${t} finished in JSON mode without calling ctx.output.result`);return s}function Ff(e,t){if(Tr(t))return t;throw Error(`${e} returned ${t}, which is not an exit code from ${he} to ${Ka}`)}var Qi="__exit__",hl="__run__",Bf="Back",Uf="Return to previous menu";async function yl(e,t){if(t)throw new N("Interactive mode cannot be combined with --json","Pass a command and its arguments instead");if(!Fn())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 n=e.info.version?` v${e.info.version}`:"";Ki(d.bgCyan(d.black(` ${e.info.name}${n} `)));let r={commands:e.commands,message:e.interactive.promptMessage,path:e.info.bin,root:!0};return await wl(e,new Map,r),Xi(e.interactive.goodbyeMessage),he}async function wl(e,t,n){while(!0){let r=await Gf(e,t,n);if(r===void 0)return;if(t.set(n.path,r),r===hl&&n.owner){await bl(e,n.owner,n.path);continue}let s=n.commands.find((i)=>i.name===r);if(s)await Vf(e,t,s,`${n.path} ${r}`)}}async function Gf(e,t,n){let r=n.root?{hint:e.interactive.exitHint,label:e.interactive.exitLabel,value:Qi}:{hint:Uf,label:Bf,value:Qi};try{let s=await _t({initialValue:t.get(n.path),message:n.message,options:[...n.owner?[{hint:n.owner.description,label:n.owner.name,value:hl}]:[],...n.commands.map((i)=>({hint:i.description,label:i.name,value:i.name})),r]});return s===Qi?void 0:s}catch(s){if(s instanceof Re)return;throw s}}async function Vf(e,t,n,r){if(n.subcommands.length===0)return bl(e,n,r);return wl(e,t,{commands:n.subcommands,message:`${n.name}:`,path:r,root:!1,...n.run?{owner:n}:{}})}async function bl(e,t,n){try{await Hf(e,t,n)}catch(r){if(r instanceof Re)return;if(!(r instanceof u))throw r;pt(r,{json:!1})}}async function Hf(e,t,n){let{args:r}=Nn([],t.args),s=Mr([],t.positionals),i=t.prompts?null:Nr(s,t.positionals);if(i)throw new N(i,`Run "${n} --help" for usage.`);let o=cs(!1),a={args:Lr(r,t.args),interactive:t.prompts,json:!1,positionals:s};await us(t,n,ls(e,a,o),o)}var qf="--",Wf=/^(?:--json(?:=true)?|-[^-=]*j[^-=]*(?:=true)?)$/,Jf=/^(?:--no-(?:help|json)|(?:--(?:help|json)|-[hj]+)(?:=(?:true|false))?)$/;async function eo(e,t){try{return await zf(e,t)}catch(n){return{code:pt(n,{json:no(t)}),menu:!1}}}function to(e,t){let{command:n,restArgs:r}=_r(t,ve),s=n===void 0||n===At?void 0:Pl(e,n,r);if(!s||s instanceof N||!s.command.passthrough)return{operands:[],options:[...t]};let i=tc(s.tokens,{...s.command.args,...Yt}),o=i<0?[]:s.tokens.slice(i);return{operands:o,options:t.slice(0,t.length-o.length)}}async function zf(e,{options:t,operands:n}){let{command:r,flags:s,restArgs:i}=Oi(t,ve,Yt),o=s.json===!0,a={code:he,menu:!1};if(r===void 0){if(s.interactive&&!s.help&&!s.version)return{code:await yl(e,o),menu:!0};return Qe(s.version&&!s.help?Xf(e,o):Rl(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(r===At)return Qe(Yf(e,i,o)),a;let l=Zf(e,r,i);if(s.help)return Qe(ro(l.command,l.path,o)),a;return{code:await Qf(e,l,n,o),menu:!1}}function no({options:e}){let{before:t,restArgs:n}=_r(e,ve);return[t,n].some((r)=>Kf(r).some((s)=>Wf.test(s)))}function Kf(e){let t=e.indexOf(qf);return t<0?e:e.slice(0,t)}function Xf({info:e},t){return t?lt({name:e.name,bin:e.bin,version:e.version}):`${ll(e)}
89
+ `}function Rl(e,t){return t?lt(ol(e.info,e.commands)):`${ul(e.info,e.commands)}
90
+ `}function ro(e,t,n){return n?lt(os(e,t)):`${pl(e,t)}
91
+ `}function Yf(e,t,n){let{args:r,rawPositionals:s}=Nn(t,Yt);if(Or(r,Yt,`Run "${e.info.bin} ${At} [command]" for usage.`,t),s.length===0)return Rl(e,n);let{command:i,path:o}=$l(e.commands,s,e.info.bin);return ro(i,o,n)}function $l(e,t,n){let[r="",...s]=t,i=e.find((a)=>a.name===r);if(!i)throw is(r,so(e),n);let o=`${n} ${r}`;return s.length===0?{command:i,path:o}:$l(i.subcommands,s,o)}function so(e){return e.map((t)=>t.name)}function Zf(e,t,n){let r=Pl(e,t,n);if(r instanceof N)throw r;return r}function Pl(e,t,n){let r=e.commands.find((s)=>s.name===t);if(!r)return is(t,so(e.commands),e.info.bin);return vl({command:r,path:`${e.info.bin} ${t}`,tokens:n})}function vl(e){let{command:t,path:n,tokens:r}=e;if(t.subcommands.length===0)return e;let s=r.findIndex((a)=>!Jf.test(a)),i=r[s];if(i===void 0||i.startsWith("-"))return e;let o=t.subcommands.find((a)=>a.name===i);if(o)return vl({command:o,path:`${n} ${i}`,tokens:r.toSpliced(s,1)});if(t.run&&Object.keys(t.positionals).length>0)return e;return is(i,so(t.subcommands),n)}async function Qf(e,{command:t,path:n,tokens:r},s,i){let o=`Run "${n} --help" for usage.`,a={...t.args,...Yt},c=Nn(r,a),{args:l}=c,p=[...c.rawPositionals,...s];if(t.strict)Or(l,a,o,r);if(i&&!t.json)throw new N(`${n} does not support --json`,o);let m=t.strict?rc(p,t.positionals):void 0;if(m!==void 0)throw new N(`Unexpected argument: ${m}`,o);if(!t.run)return Qe(ro(t,n,i)),he;let g=Mr(p,t.positionals),h=Nr(g,t.positionals);if(h)throw new N(h,o);let f=t.prompts&&p.length===0&&Fn()&&!i,y={args:Lr(l,t.args),interactive:f,json:i,positionals:g},R=cs(i);try{return await us(t,n,ls(e,y,R),R)}catch(S){return pt(S,{json:i&&!R.emitted()})}}var eh={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",promptMessage:"What would you like to do?"};function io(e){let t=`CLI "${e.name}"`;if(Fr(t,e.commands),e.commands.some((r)=>r.name===At))throw Error(`${t} cannot define a command named "${At}": the framework provides it`);let n={commands:e.commands,config:e.config,info:{bin:e.bin??e.name,description:e.description,name:e.name,version:e.version},interactive:{...eh,...e.interactive}};return{async main(r=process.argv.slice(2)){gc();let s=to(n,r),i=rl({json:no(s)}),o=await eo(n,s);if(i.settle(),o.code===he&&!o.menu)return;await i.exit(o.code)},async run(r=process.argv.slice(2)){return(await eo(n,to(n,r))).code}}}import We from"fs";import lo from"path";var ke=(e)=>(e.map=(t)=>ke((n)=>t(e(n))),e.or=(t)=>ke((n)=>{try{return e(n)}catch(r){return t(n)}}),e),K=()=>"bad banditype"();var tn=()=>ke((e)=>e),De=(e)=>ke((t)=>e.includes(t)?t:K()),ps=(e)=>ke((t)=>typeof t===typeof e?t:K()),_=()=>ps(""),Sl=()=>ps(0),nn=()=>ps(!0);var qe=()=>ps(),Cl=()=>ke((e)=>e===null?e:K()),rn=(e)=>ke((t)=>t instanceof e?t:K()),dt=(e)=>rn(Object).map((t)=>{let n={};for(let r in t){let s=e(t[r]);s!==void 0&&(n[r]=s)}return n}),qn=(e)=>rn(Object).map((t)=>{let n={};for(let r in e){let s=e[r](t[r]);s!==void 0&&(n[r]=s)}return n}),st=(e)=>rn(Object).map((t)=>{let n={...t};for(let r in e){let s=e[r](t[r]);s!==void 0&&(n[r]=s)}return n}),ne=(e)=>rn(Array).map((t)=>t.map(e));import sn from"fs";var th=".lock",nh=".break",kl=10,rh=1e4,sh=5000;function xl(e,t){let n=`${e}${th}`,r=crypto.randomUUID();ih(n,r);try{return t()}finally{El(n,r)}}function ih(e,t){let n=Date.now()+rh;while(!Tl(e,t)){if(Date.now()>n)throw Error(`timed out waiting for ${e}, which another process holds`);if(oo(e))oh(e,t);else Bun.sleepSync(kl)}}function El(e,t){if(ah(e)===t)sn.rmSync(e,{force:!0})}function oh(e,t){let n=`${e}${nh}`;if(!Tl(n,t)){if(oo(n))sn.rmSync(n,{force:!0});else Bun.sleepSync(kl);return}try{if(oo(e))sn.rmSync(e,{force:!0})}finally{El(n,t)}}function Tl(e,t){try{return sn.writeFileSync(e,t,{flag:"wx"}),!0}catch(n){if(Il(n)==="EEXIST")return!1;throw n}}function oo(e){let t=sn.statSync(e,{throwIfNoEntry:!1})?.mtimeMs;return t!==void 0&&Date.now()-t>sh}function ah(e){try{return sn.readFileSync(e,"utf8")}catch(t){if(Il(t)==="ENOENT")return;throw t}}function Il(e){return e instanceof Error?Reflect.get(e,"code"):void 0}import ao from"fs";import Dt from"path";var ch="..",lh=40;function Ol(e){let{root:t}=Dt.parse(Dt.resolve(e)),n=Al(Dt.resolve(e)),r=t,s=0;for(let i=n.shift();i!==void 0;i=n.shift()){if(i===ch){r=Dt.dirname(ao.realpathSync(r));continue}let o=Dt.join(r,i);if(!ao.lstatSync(o,{throwIfNoEntry:!1})?.isSymbolicLink()){r=o;continue}if(s+=1,s>lh)throw Error(`too many symbolic links in ${e}`);let a=ao.readlinkSync(o);if(Dt.isAbsolute(a))r=t;n.unshift(...Al(a))}return r}function Al(e){return e.split(Dt.sep).filter((t)=>t!==""&&t!==".")}function Wn(e,t){JSON.parse(e);let n=JSON.parse(JSON.stringify(t)),r=uh(e),s=e.match(/^[\t ]+(?=\S)/m)?.[0]??" ",i=e.includes(`\r
92
92
  `)?`\r
93
93
  `:`
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(`
94
+ `,o=/\s/.test(e[r.start+1]??"")||r.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
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(`
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],V=ee?e.slice(f.node.end,ee.start):`,${S.includes(`
97
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(`
98
+ `))});return`${g?"[":"{"}${S}${H.join(V)}${k}${g?"]":"}"}`}function c(l,p,m){if(!m)return co(l,o);let g=e.lastIndexOf(`
99
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
100
+ `,i+h)}return e.slice(0,r.start)+a(r,n)+e.slice(r.end)}function co(e,t){if(Array.isArray(e))return`[${e.map((s)=>co(s,t)).join(`,${t}`)}]`;if(e===null||typeof e!=="object")return JSON.stringify(e);let n=Object.entries(e);if(n.length===0)return"{}";let r=n.map(([s,i])=>`${JSON.stringify(s)}:${t}${co(i,t)}`);return`{${t}${r.join(`,${t}`)}${t}}`}function uh(e){let t=e.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),n=t.next().value;function r(){if(!n)throw Error("Unexpected end of JSON");let i=n;return n=t.next().value,i}function s(){let i=r(),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(n&&n[0]!==c){let p=n.index,m=a?JSON.parse(r()[0]):String(o.length);if(a)r();if(o.push({key:m,node:s(),start:p}),n?.[0]===",")r()}let l=r().index+1;return{end:l,entries:o,start:i.index,value:JSON.parse(e.slice(i.index,l))}}return s()}var ph=2,uo="ConfigError",dh=rn(Object);class po{loaded;configPath;defaultConfig;options;constructor(e,t,n={}){this.configPath=lo.resolve(e),this.defaultConfig=t,this.options=n}get path(){return this.configPath}get failure(){return this.state().failure}get(e){return this.current()[e]}set(e,t){let n=this.writable();this.update((r)=>({...r,[e]:t})),n.config={...n.config,[e]:t}}delete(e){let t=this.writable();this.update((n)=>(delete n[e],n)),delete t.config[e]}exists(){return We.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:uo})}readStored(){try{let e=this.readConfigFile();if(e===void 0)return structuredClone(this.defaultConfig);return Lt(structuredClone(this.defaultConfig),_l(e))}catch(e){throw this.unreadable(e)}}update(e){try{let t=this.savePath();xl(t,()=>this.write(t,e(this.readStored())))}catch(t){throw t instanceof u?t:this.saveFailure(t)}}savePath(){let e=this.exists()?We.realpathSync(this.configPath):Ol(this.configPath);return We.mkdirSync(lo.dirname(e),{recursive:!0}),e}write(e,t){let n=`${e}.${crypto.randomUUID()}.tmp`;try{let r=this.exists()?We.statSync(this.configPath).mode:void 0,s=this.exists()?Wn(We.readFileSync(this.configPath,"utf-8"),t):`${JSON.stringify(t,null,ph)}
101
+ `;if(We.writeFileSync(n,s,{flag:"wx",mode:r}),r!==void 0)We.chmodSync(n,r);We.renameSync(n,e)}finally{We.rmSync(n,{force:!0})}}saveFailure(e){return new u(`Cannot save config at ${this.configPath}: ${Ll(e)}`,`Check that ${lo.dirname(this.configPath)} is writable and that no other process is saving the file`,void 0,{cause:e,tag:uo})}load(){let{parse:e,strict:t}=this.options;try{let n=this.readConfigFile();if(n===void 0)return{config:structuredClone(this.defaultConfig)};let r=Lt(structuredClone(this.defaultConfig),_l(n));return{config:e?e(r):r}}catch(n){if(t)return{config:structuredClone(this.defaultConfig),failure:this.loadFailure(n)};return P.warn(d.yellow(`Config file corrupted at ${this.configPath}. Using defaults.`),{output:Gr()}),{config:structuredClone(this.defaultConfig),error:n}}}loadFailure(e){return new u(`Cannot read config at ${this.configPath}: ${Ll(e)}`,"Repair the file and try again",void 0,{cause:e,tag:uo})}readConfigFile(){try{return We.readFileSync(this.configPath,"utf-8")}catch(e){if(e.code==="ENOENT")return;throw e}}}function _l(e){let t=JSON.parse(e);if(Array.isArray(t))throw Error("Config must be an object");return dh(t)}function Ll(e){return e instanceof Error?e.message:String(e)}var Dl="0.15.0";var T="sis",mo="\uD83E\uDEA8",mt="other",gt={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},ft=50,on=".sisyphus",Ml="stones",Nl="released",ds=7;var Jn="unknown",jl="0.0.0",ye="latest",go=["bun","run","build"],Mt="main",Fl=4,Bl=8,ms="config.json";var ht={$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): {versions}"},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:[...go],outputs:[],root:[]},createRelease:!1,npm:!1,npmVisibilityTimeout:0,push:!1,tags:!1},scripts:{post:{},pre:{}},single:!1,sisyphusDir:".sisyphus",stones:[],tag:"latest"};var M=jr();import{existsSync as Mh}from"fs";import{mkdir as Nh,writeFile as jh}from"fs/promises";import{dirname as Fh}from"path";var Je="ProviderRequestFailed",yt={bitbucket:"bitbucket.org",github:"github.com",gitlab:"gitlab.com"};function ze(e){return e.host??yt[e.provider]}class wt{owner;repo;remote;constructor(e){this.owner=e.owner,this.repo=e.repo,this.remote=e}get host(){return ze(this.remote)}}class gs extends wt{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 gh=200,fh=404,hh=10,yh=3000,Ul=_().map((e)=>e.length>0?e:K()),wh=ne(ne(qn({filename:Ul,previous_filename:Ul.or(qe()),status:_()}).map((e)=>e.status==="renamed"&&e.previous_filename===void 0?K():e)));function bh(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 fs extends wt{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===yt.github}async gh(e,t){try{return(await t()).stdout.toString()}catch(n){let r=n&&typeof n==="object"&&"stderr"in n?String(n.stderr).trim():"";throw new u(`Failed to ${e} on ${this.repository}: ${r||n}`,"Check gh access and retry",1,{cause:n,tag:Je})}}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()||Mt}async findPr(e){let t=[];if(e.head)t.push("--head",e.head);if(e.label)t.push("--label",e.label);let n=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()),[r]=JSON.parse(n);return r?this.mapPrResponse(r):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()),n=JSON.parse(t).number;if(e.labels&&e.labels.length>0){let r=e.labels.flatMap((s)=>["-f",`labels[]=${s}`]);await this.gh(`label pull request #${n}`,()=>Bun.$`gh api ${this.apiPath}/issues/${n}/labels ${this.hostArgs} --method POST ${r}`.quiet())}return this.getPr(n)}async updatePr(e,t){let n=[];if(t.title)n.push("--title",t.title);if(t.body)n.push("--body",t.body);await this.gh(`update pull request #${e}`,()=>Bun.$`gh pr edit ${e} --repo ${this.repository} ${n}`.quiet())}async getPr(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e} ${this.hostArgs}`.quiet(),n=JSON.parse(t.stdout.toString());return this.mapRestApiResponse(n)}catch(t){throw new u(`Failed to fetch PR #${e}`,"Make sure the PR exists and you have access",1,{cause:t,tag:Je})}}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(),n=JSON.parse(t.stdout.toString());return this.mapPrResponse(n)}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:Je})}}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()),n=this.parsePrFiles(e,t);if(n.length>=yh)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(n.flatMap((r)=>r.status==="renamed"&&r.previous_filename!==void 0?[r.previous_filename,r.filename]:[r.filename]))]}parsePrFiles(e,t){try{return wh(JSON.parse(t)).flat()}catch(n){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:n,tag:Je})}}async ensureLabelExists(e,t){try{let n=t?.description??"",r=t?.color?["--color",t.color]:[];await Bun.$`gh label create ${e} --repo ${this.repository} --description ${n} ${r} --force`.quiet()}catch{}}async getRelease(e){let t=`${this.apiPath}/releases/tags/${encodeURIComponent(e)}`,n=await Bun.$`gh api ${t} ${this.hostArgs} --include`.quiet().nothrow(),r=n.stdout.toString().replaceAll(`\r
103
103
  `,`
104
- `),[s="",...i]=n.split(`
104
+ `),[s="",...i]=r.split(`
105
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(`
106
+ `),o=s.match(/^HTTP\/\S+\s+(\d{3})\b/m)?.[1],a=o?Number.parseInt(o,hh):null;if(n.exitCode!==0){if(a===fh)return null;let l=a?`GitHub API returned HTTP ${a}`:`gh api failed with exit code ${n.exitCode}; check authentication and network connectivity`;throw this.releaseReadError(e,l)}if(a!==gh)throw this.releaseReadError(e,a?`GitHub API returned HTTP ${a}`:"missing HTTP status");let c;try{c=JSON.parse(i.join(`
107
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:
108
+ `))}catch{throw this.releaseReadError(e,"response was not valid JSON")}if(!bh(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??Jn,baseBranch:e.base?.ref??Mt,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??Jn,baseBranch:e.baseRefName??Mt,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 Rh=404,$h=/Token found:\s*(\S+)/,Gl=_().map((e)=>e.length>0?e:K()),Ph=qn({changes:ne(qn({new_path:Gl,old_path:Gl})),overflow:nn()});class hs extends wt{name="gitlab";authHeader={};apiUrl;projectPath;constructor(e){super(e);this.apiUrl=e.apiUrl??process.env.CI_API_V4_URL??`https://${ze(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||Mt}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 n;try{n=await this.api(`/projects/${this.projectPath}/merge_requests?${t}`)}catch(s){throw this.requestFailed("list merge requests",s)}let[r]=n;return r?this.mapMrResponse(r):null}requestFailed(e,t){let n=t instanceof Error?t.message:String(t);return new u(`Failed to ${e} on ${this.owner}/${this.repo}: ${n}`,"Check GitLab access and retry",1,{cause:t,tag:Je})}async createPr(e){let t={description:e.body,source_branch:e.head,target_branch:e.base,title:e.title};if(e.labels?.length)t.labels=e.labels.join(",");let n=await this.api(`/projects/${this.projectPath}/merge_requests`,{body:JSON.stringify(t),method:"POST"});return this.mapMrResponse(n)}async updatePr(e,t){let n={};if(t.title)n.title=t.title;if(t.body)n.description=t.body;await this.api(`/projects/${this.projectPath}/merge_requests/${e}`,{body:JSON.stringify(n),method:"PUT"})}async getPr(e){try{let t=await this.api(`/projects/${this.projectPath}/merge_requests/${e}`);return this.mapMrResponse(t)}catch{throw new 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(),n=new URLSearchParams({per_page:"1",source_branch:t,state:"opened"}),r=await this.api(`/projects/${this.projectPath}/merge_requests?${n}`);if(!r[0])throw Error("No MR found");return this.mapMrResponse(r[0])}catch{throw new 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((n)=>n.id)}catch{return[]}}async getPrFiles(e){try{let t=Ph(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((n)=>[n.old_path,n.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 n={name:e};if(t?.description)n.description=t.description;if(t?.color)n.color=`#${t.color}`;await this.api(`/projects/${this.projectPath}/labels`,{body:JSON.stringify(n),method:"POST"})}catch{}}async getRelease(e){let t=await this.api(`/projects/${this.projectPath}/releases/${encodeURIComponent(e)}`,void 0,!0);if(t===void 0)return null;if(!vh(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($h)?.[1]}catch{return}}async api(e,t,n=!1){let r=await fetch(`${this.apiUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...this.authHeader,...t?.headers}});if(n&&r.status===Rh)return;if(!r.ok){let s=await r.text().catch(()=>"");throw Error(`GitLab API error: ${r.status} ${r.statusText}${s?` \u2014 ${s}`:""}`)}return r.json()}mapMrResponse(e){return{author:e.author?.username??Jn,baseBranch:e.target_branch??Mt,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 vh(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 Vl="ProviderNotDetected",Sh={github:/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/|$)/,gitlab:/^\/(.+)\/([^/]+)\/-\/merge_requests\/([1-9]\d*)(?:\/|$)/,bitbucket:/^\/([^/]+)\/([^/]+)\/pull-requests\/([1-9]\d*)(?:\/|$)/},Hl=new Set(["http:","https:"]),Ch="://",kh=/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/,xh='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 bt(e,t){let n=e?Th(e,t):await ql(t),r=Eh(n);return await r.ensureAvailable(),r}function Eh(e){switch(e.provider){case"github":return new fs(e);case"gitlab":return new hs(e);case"bitbucket":return new gs(e);default:throw new u(`Unsupported provider: ${e.provider}`)}}function Th(e,t){if(t?.type!==e.provider)return e;let n=e.host??t.host,r=e.apiUrl??t.apiUrl;return{...e,...n?{host:n}:{},...r?{apiUrl:r}:{}}}async function ys(e){let t=await Jl();return t?zn(t,e):null}async function ql(e){let t=await Jl();if(!t)throw new u("Could not detect git provider","Make sure you have a git remote configured (origin)",1,{tag:Vl});let n=zn(t,e);if(n)return n;let r=zl(t)?.hostname;throw new u(r?`Could not detect the git provider for origin host ${r}`:"Could not parse the origin remote URL",xh,1,{tag:Vl})}async function Wl(e){return(await ql(e)).provider}async function Jl(){try{return(await Bun.$`git remote get-url origin`.quiet()).stdout.toString().trim()||null}catch{return null}}function zn(e,t){let n=zl(e);if(!n)return null;let r=t?.type??Kl(n.hostname)??Ih(n.hostname);if(!r)return null;let s=n.path.replace(/^\/+|\/+$/g,"").replace(/\.git$/,"").split("/").filter(Boolean),i=s.pop();if(!i||s.length===0)return null;if(r!=="gitlab"&&s.length!==1)return null;let o=t?.apiUrl;return{host:t?.host??n.webHost,owner:s.join("/"),provider:r,repo:i,...o?{apiUrl:o}:{}}}function zl(e){if(e.includes(Ch)){let s=URL.parse(e);if(!s?.hostname)return null;let i=s.hostname.toLowerCase(),o=Hl.has(s.protocol)?s.host.toLowerCase():i;return{hostname:i,path:s.pathname,webHost:o}}let t=e.match(kh),n=t?.[1]?.toLowerCase(),r=t?.[2];return n&&r?{hostname:n,path:r,webHost:n}:null}function Kl(e){if(e===yt.github)return"github";if(e===yt.gitlab)return"gitlab";if(e===yt.bitbucket)return"bitbucket";return null}function Ih(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 Xl(e,t){let n=URL.parse(e);if(!n||!Hl.has(n.protocol))return null;let r=n.host.toLowerCase(),s=t&&r===ze(t)?t.provider:Kl(n.hostname.toLowerCase());if(!s)return null;let[,i,o,a]=n.pathname.match(Sh[s])??[],c=Number(a);if(!i||!o||!Number.isSafeInteger(c))return null;return{host:r,number:c,owner:i,provider:s,repo:o}}import{existsSync as Yl}from"fs";import{readFile as Ah}from"fs/promises";import{dirname as Oh,join as fo}from"path";import{fileURLToPath as _h}from"url";var ws={"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"}},Lh=fo(Oh(_h(import.meta.url)),"templates"),Dh="__SISYPHUS_VERSION__",Zl={"create-stone":"sis-create-stone.yml",release:"sis-release.yml"};class ho{sisyphusVersion;constructor(e){this.sisyphusVersion=e}async generate(e){let t=[];for(let n of e){let r=await this.readTemplate(n),s=this.getOutputPath(n);t.push({content:r,path:s})}return t}getExistingFiles(e){return e.map((t)=>this.getOutputPath(t)).filter((t)=>Yl(t))}async readTemplate(e){let t=fo(Lh,this.provider,Zl[e]);return(await Ah(t,"utf-8")).replaceAll(Dh,this.sisyphusVersion)}}class bs extends ho{provider="github";outputDir=".github/workflows";getOutputPath(e){return fo(this.outputDir,Zl[e])}}var Kn=".gitlab-ci-sisyphus.yml",Rs="sisyphus";class $s extends ho{provider="gitlab";outputDir=".";async generate(e){let t=[];for(let n of e){let r=await this.readTemplate(n);t.push(r)}return[{content:t.join(`
109
+ `),path:Kn}]}getExistingFiles(e){return Yl(Kn)?[Kn]:[]}getIncludeInstruction(){return`stages:
110
110
  - build
111
111
  - test
112
112
  - deploy
113
- - ${bs}
113
+ - ${Rs}
114
114
 
115
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(`
116
+ - local: '${Kn}'`}getOutputPath(e){return Kn}}function Ql(e,t){switch(e){case"github":return new bs(t);case"gitlab":return new $s(t);default:throw Error(`CI generation is not supported for ${e}`)}}var Bh={bitbucket:"Bitbucket Pipelines",github:"GitHub Actions",gitlab:"GitLab CI"},Uh=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"}}),eu=M({name:"init",description:"Set up CI workflows for automated releases",args:Uh,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 n=await Wl(e.config.get("provider")),r=Ql(n,t);P.info(`Detected ${d.bold(Bh[n])} repository
117
+ `);let s=await Hh(e);if(s.length===0){P.info(d.dim("No workflows selected")),e.output.result({dryRun:e.args.dryRun,files:[],nextSteps:[],provider:n,sisyphusVersion:t});return}let i=r.getExistingFiles(s),o=(await r.generate(s)).map((c)=>({...c,exists:i.includes(c.path)})),a={dryRun:e.args.dryRun,files:o,nextSteps:Vh(r),provider:n,sisyphusVersion:t};if(e.args.dryRun){for(let c of o)P.info(`
118
+ ${d.bold(c.path)}${c.exists?d.yellow(" (would overwrite)"):""}:`),P.info(d.dim(c.content));e.output.result(a);return}if(i.length>0&&!e.args.yes&&!await Gh(e,i))return;for(let c of o){let l=Fh(c.path);if(l!=="."&&!Mh(l))await Nh(l,{recursive:!0});await jh(c.path,c.content,"utf-8")}te(o.map((c)=>` ${d.green("+")} ${c.path}`).join(`
119
+ `),d.green("CI workflows created")),P.info(`Workflows install ${d.bold(`@r5n/sisyphus@${t}`)}; run this command again to upgrade.`);for(let c of a.nextSteps)P.info(c);e.output.result(a)}});async function Gh(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 P.warn(`The following files already exist:
120
+ ${t.map((n)=>` ${n}`).join(`
121
+ `)}`),G({initialValue:!1,message:"Overwrite existing files?"})}function Vh(e){if(e instanceof $s)return[`Add the include and the ${Rs} stage to your .gitlab-ci.yml (append ${Rs} 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 bs)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 Hh(e){let t=qh(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 nt({initialValues:Object.keys(ws),message:"Select workflows to create",options:Object.entries(ws).map(([n,r])=>({hint:r.description,label:r.name,value:n})),required:!1})}function qh(e){if(e.args.all)return Object.keys(ws);let t=[];if(e.args.createStone)t.push("create-stone");if(e.args.release)t.push("release");return t}import{readdir as sP,rm as iP,rmdir as oP}from"fs/promises";import{dirname as zd,join as Kd}from"path";var tu={["major"]:5,["minor"]:4,["patch"]:3,["dependency"]:2,["snapshot"]:1},an={["major"]:"\uD83D\uDEA8",["minor"]:"\u2728",["patch"]:"\uD83D\uDC1B",["dependency"]:"\uD83D\uDCE6",["snapshot"]:"\uD83D\uDCF8"},cn={["major"]:d.red,["minor"]:d.yellow,["patch"]:d.green,["dependency"]:d.blue,["snapshot"]:d.magenta},xe=["major","minor","patch","dependency","snapshot"];function ln(e,t){return tu[e]>=tu[t]?e:t}var nu=/^(\w+)(?:\(([^)]+)\))?(!)?: (.+)$/,iu=/^BREAKING(?: CHANGE|-CHANGE):[\t ]+\S/m,Wh=/^\w+(?:\([^)]+\))?!: /,Jh=/^BREAKING(?: CHANGE|-CHANGE):[\t ]+(\S[\s\S]*?)(?=\n[\t ]*\n|(?![\s\S]))/gm,zh=/\s+/g,Kh="%x00%H%x00%s%x00%an%x00%b",ru=4,su=`
123
+ `,Xh=new Set(["build","chore","ci","docs","feat","fix","perf","refactor","style","test"]);function yo(e){return Wh.test(e.subject)||iu.test(e.body??"")}function ou(e){if(!e)return[];return[...e.matchAll(Jh)].map((t)=>(t[1]??"").replace(zh," ").trim()).filter((t)=>t.length>0)}class Z{hash;subject;author;body;type;scope;breaking;message;files;constructor(e){let[,,,t]=e.subject.match(nu)??[];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||iu.test(e.body??""),this.message=e.message,this.files=e.files}static async since(e){if(e!==void 0)try{let n=(await Bun.$`git rev-parse --verify --end-of-options ${`${e}^{commit}`}`.quiet()).stdout.toString().trim();return await Z.fetchFromRange(`${n}..HEAD`)}catch(t){let n=new u(`Failed to read commits since ${e}`,"Fetch the missing commit or correct the configured baseline before creating stones");throw n.cause=t,n}return Z.fetchFromRange("HEAD")}static async inRange(e,t){let n=[`origin/${e}..origin/${t}`,`${e}..${t}`];for(let r of n){let s=await Z.tryFetchFromRange(r);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(),n=t.exitCode===0?t.stdout.toString().trim():"";if(!n)return[];try{return await Z.fetchFromRange(`${e}^1..${n}`)}catch(r){throw new u(`Failed to read the commits merged by ${e}`,"Run: git fetch --unshallow",1,{cause:r})}}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 n=(await Bun.$`git log ${e} -z --format=${Kh} --name-only --root`.quiet()).stdout.toString().split("\x00"),r=[],s=0;while(s<n.length){s++;let[i,o,a,c]=n.slice(s,s+ru);s+=ru;let l=[];while(s<n.length&&n[s]!==""){let p=n[s++];if(p===void 0)continue;l.push(l.length===0&&p.startsWith(su)?p.slice(su.length):p)}if(!i||!o||!a)continue;r.push(Z.parse(i,o,a).withFiles(l).withBody(c?.trim()||void 0))}return r}static parse(e,t,n){let r=t.match(nu);if(r){let[,s="",i,,o=""]=r,a=s.toLowerCase();if(a&&Xh.has(a))return new Z({author:n,files:[],hash:e,message:o,scope:i,subject:t,type:a})}return new Z({author:n,files:[],hash:e,message:t,subject:t,type:mt})}get shortHash(){return this.hash.slice(0,ds)}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 Yh=/^[A-Za-z][0-9A-Za-z]*$/,Zh=_().map((e)=>Yh.test(e)?e:K());function Nt(e,t="Invalid prerelease tag"){try{return Zh(e)}catch{throw new u(t,"Start with a letter and use only letters or numbers")}}var Qh=/^(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-]+)*))?$/,ey=/^(0|[1-9]\d*)$/,au=10,wo=1,ty=2;function Me(e){let t=Qh.exec(e);if(!t)return null;let[,n="0",r="0",s="0",i,o]=t,a=[n,r,s].map((l)=>Number.parseInt(l,au)),c=i?i.split(".").map(ny):[];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 Ps(e,t){let n=Me(e);if(n)return n;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 vs(e){let t=e.prerelease.length>0?`-${e.prerelease.join(".")}`:"",n=e.build.length>0?`+${e.build.join(".")}`:"";return`${e.major}.${e.minor}.${e.patch}${t}${n}`}function Ne(e){return e.prerelease.length>0}function cu(e,t){return e.major===t.major&&e.minor===t.minor&&e.patch===t.patch}function lu(e,t){let n=e.major-t.major||e.minor-t.minor||e.patch-t.patch;if(n!==0)return n<0?-1:1;return ry(e.prerelease,t.prerelease)}function uu(e,t){let n=Ne(e);if(t==="major"){let r=n&&e.minor===0&&e.patch===0;return bo(r?e.major:e.major+wo,0,0)}if(t==="minor"){let r=n&&e.patch===0;return bo(e.major,r?e.minor:e.minor+wo,0)}return bo(e.major,e.minor,n?e.patch:e.patch+wo)}function Ss(e,t,n){return{...e,build:[],prerelease:[t,n]}}function Xn(e){return du(e)?.tag}function pu(e){return du(e)?.counter}function du(e){if(e.prerelease.length!==ty)return;let[t,n]=e.prerelease;if(typeof t!=="string"||typeof n!=="number")return;return{counter:n,tag:t}}function bo(e,t,n){return{build:[],major:e,minor:t,patch:n,prerelease:[]}}function ny(e){return ey.test(e)?Number.parseInt(e,au):e}function ry(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return 1;if(t.length===0)return-1;let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1){let s=e[r],i=t[r];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 sy=1,mu=0,iy=/[.ZT:-]/g,oy=14,ay="0.0.0",cy=/^0\.0\.0-[0-9A-Za-z.-]+-\d{14,}$/,ly="nightly",uy={dependency:"patch",major:"major",minor:"minor",patch:"patch"};class Ee{static bump(e,t,n,r=!1){if(n!==void 0)Nt(n);if(t==="snapshot")return Ee.formatSnapshot(n);let s=`apply a ${t} bump`,i=uy[t];if(!i)throw new u(`Unknown bump type "${t}"`,"Use major, minor, patch, dependency, or snapshot");if(Ee.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=Ps(e,s),a=Ee.resolveTag(o,t,n,r),c=uu(o,i),l=a===void 0?c:Ee.applyPrerelease(c,o,a,e);if(lu(l,o)<=0)throw new u(`A ${t} bump would move ${e} to ${vs(l)}, which is not a later version`,"Prerelease tags must increase in semver precedence (alpha < beta < rc)");return vs(l)}static formatLabel(e,t,n,r,s){let i=s??Ee.bump(t,n,r),o=an[n];return`${e}@${t} => ${i} ${o}`}static isSnapshotVersion(e){return cy.test(e)}static resolveTag(e,t,n,r){if(n!==void 0)return n;if(r||t!=="dependency")return;let s=Xn(e);if(s===void 0&&Ne(e))throw new u(`Cannot continue the prerelease of ${vs(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,n,r){if(Nt(n),!cu(e,t))return Ss(e,n,mu);let s=pu(t);if(Xn(t)===n&&s!==void 0)return Ss(e,n,s+sy);if(t.prerelease[0]===n){let i=`${e.major}.${e.minor}.${e.patch}`;throw new u(`Cannot continue the "${n}" prerelease from ${r}`,`Set the package version to ${i}-${n}.<number> first`)}return Ss(e,n,mu)}static formatSnapshot(e){let t=new Date().toISOString().replace(iy,"").slice(0,oy);return`${ay}-${e||ly}-${t}`}}var py={build:[],major:0,minor:0,patch:0,prerelease:[]},Cs="workspace:",ks=["dependencies","devDependencies","optionalDependencies","peerDependencies"];function dy(e){let t=[];for(let n of ks)for(let[r,s]of Object.entries(e[n]??{})){if(!s?.startsWith(Cs))continue;t.push({kind:n,name:r,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||jl,workspaceDependencies:dy(e)})}static applyStone(e,t,n=ks){let r=[],s=new Set,i=z.graduatingPackages(e,t,new Set(n));for(let o of xe)for(let a of e.getPackages(o)){let c=t.get(a);if(!c||s.has(a))continue;s.add(a),r.push(c.withBump(o,e.tag,i.has(a)))}return r}static graduatingPackages(e,t,n){let r=new Set;if(e.tag!==void 0)return r;let s=xe.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))r.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(r.has(a.name))continue;if(!a.workspaceDependencies.some((c)=>n.has(c.kind)&&r.has(c.name)))continue;r.add(a.name),o=!0}}return r}static isPrereleaseVersion(e){return e!==void 0&&Ne(Me(e)??py)}get newVersion(){if(this._newVersion)return this._newVersion;if(!this.bump)return;return Ee.bump(this.version,this.bump,this.tag)}get label(){if(!this.bump)return`${this.name}@${this.version}`;return Ee.formatLabel(this.name,this.version,this.bump,this.tag,this._newVersion)}withBump(e,t,n=!1){return new z({...this.toOptions(),bump:e,newVersion:Ee.bump(this.version,e,t,n),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 my}from"crypto";var gu=ne(_()),gy=_().map((e)=>e.trim().length>0?e:K()),$o=_().or(qe()),fy=ne(st({body:$o,hash:_().map((e)=>e.length>0?e:K()),message:_(),packages:gu,scope:$o,subject:_(),type:_()})).or(qe());function Ro(e,t,n,r,s){try{return r(s)}catch{throw new u(`Invalid ${t} in stone ${e}`,`Expected ${n}`)}}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:Nt(e.tag),this.description=e.description,this.commits=e.commits,this._packages=e.packages}static create(e,t=0){let n=O.generateId(t);return O.fromData(n,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:n,errors:r}=O.merge(e,t);if(r.length>0)throw new u("Pending stones conflict and cannot be released together",r.join(`
124
+ `));return n}static merge(e,t){let n=new Map,r=[],s=[];for(let m of e)for(let g of xe)O.collectBumps(m,g,n,r,s);let i=O.categorizeBumps(n),o=e.map((m)=>m.description).filter(Boolean).join(`
125
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(`
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(r)],errors:[...new Set(s)],stone:p}}static resolveTag(e,t){let n=e.filter((i)=>!i.isEmpty),r=new Map;for(let i of n){if(!i.tag)continue;r.set(i.tag,[...r.get(i.tag)??[],i.id])}if(r.size===0)return;let s=n.filter((i)=>!i.tag).map((i)=>i.id);if(r.size>1||s.length>0){let i=[...r.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[...r.keys()][0]}static mergeCommits(e){let t=new Map;for(let n of e.flatMap((r)=>r.commits??[])){let r=t.get(n.hash);if(!r){t.set(n.hash,{...n,packages:[...n.packages??[]]});continue}let s=new Set([...r.packages,...n.packages??[]]);t.set(n.hash,{...r,packages:[...s]})}return[...t.values()]}static collectBumps(e,t,n,r,s){for(let i of e.getPackages(t)){let o=n.get(i);if(!o){n.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}r.push(i);let a=ln(t,o);if(a!==o)n.set(i,a)}}static categorizeBumps(e){let t=new Map;for(let n of xe)t.set(n,[]);for(let[n,r]of e)t.get(r)?.push(n);return t}static fromData(e,t){let n=new Map;for(let r of xe){let s=t[r];try{n.set(r,s===void 0?[]:gu(s))}catch{throw new u(`Invalid ${r} packages in stone ${e}`,"Each bump field must contain an array of package names")}}return new O({commits:Ro(e,"commits","commit records with a packages array",fy,t.commits),description:Ro(e,"description","a string",$o,t.description),id:e,message:Ro(e,"message","a non-empty string",gy,t.message),packages:n,tag:t.tag})}static generateId(e){let t=String(e+1).padStart(Fl,"0"),n=my().slice(0,Bl);return`${t}-${n}`}get major(){return this._packages.get("major")??[]}get minor(){return this._packages.get("minor")??[]}get patch(){return this._packages.get("patch")??[]}get dependency(){return this._packages.get("dependency")??[]}get snapshot(){return this._packages.get("snapshot")??[]}get allPackages(){let e=[];for(let t of this._packages.values())e.push(...t);return e}get isEmpty(){return this.allPackages.length===0}affectsPackage(e){return this.allPackages.includes(e)}getPackages(e){return this._packages.get(e)??[]}withMessage(e){return new O({...this.toOptions(),message:e})}withPackages(e,t){let n=new Map(this._packages);return n.set(e,t),new O({...this.toOptions(),packages:n})}toOptions(){return{commits:this.commits,description:this.description,id:this.id,message:this.message,packages:new Map(this._packages),tag:this.tag}}toJson(){return{commits:this.commits&&this.commits.length>0?this.commits:void 0,dependency: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 yy,rm as wy,writeFile as fu}from"fs/promises";import{dirname as by,join as Ry}from"path";var hy={bitbucket:"commits",github:"commit",gitlab:"-/commit"};function Po(e){let t=`https://${ze(e)}/${e.owner}/${e.repo}`,n=hy[e.provider];return(r)=>`${t}/${n}/${r}`}class Yn{settings;cached=void 0;constructor(e){this.settings=e}async getRemoteInfo(){if(this.cached!==void 0)return this.cached;let e=await ys(this.settings);return this.cached=e?{...e,commitUrl:Po(e)}:null,this.cached}}var $y=/^#\s/,Py=/^#{1,6}\s+\[?v?\d+\.\d+\.\d+/,vy=/\r$/;function hu(e){return $y.test(e)&&!Py.test(e)}function un(e){return new yu(e.get("changelog"),e.get("dependents").kinds,e.get("provider"))}class yu{dependencyKinds;config;originals=new Map;remoteParser;commitUrlFn=null;constructor(e,t=ks,n){this.dependencyKinds=t;this.config=e,this.remoteParser=new Yn(n)}async generate(e,t){await this.initCommitLinks();let n=new Map(t.map((r)=>[r.name,r]));for(let r of t){let s=this.filterStonesForPackage(e,r.name),i=this.getBumpedDependencies(r,n);await this.generateForPackage(s,r,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((r)=>this.dependencyKinds.includes(r.kind)).map((r)=>r.name))].map((r)=>t.get(r)).filter((r)=>r?.newVersion!==void 0)}filterStonesForPackage(e,t){return e.filter((n)=>this.hasDirectChanges(n,t))}hasDirectChanges(e,t){return e.major.includes(t)||e.minor.includes(t)||e.patch.includes(t)}async rollback(){for(let[e,t]of this.originals)if(t===null)await wy(e,{force:!0});else await fu(e,t,"utf-8");this.originals.clear()}async generateForPackage(e,t,n){let r=Ry(by(t.file),this.config.filename),s=this.formatEntry(e,t,n);await this.writeEntry(r,s,t.name)}async generateRoot(e,t){let n=this.config.filename,r=this.formatRootEntry(e,t);await this.writeEntry(n,r,"Changelog")}async writeEntry(e,t,n){let r=await this.readExisting(e);if(!this.originals.has(e))this.originals.set(e,r);let s=r?this.extractTitle(r,n):`# ${n}`,i=r?this.extractRest(r):"",o=this.config.append?[i,t]:[t,i];await fu(e,`${[s,...o.filter(Boolean)].join(`
127
127
 
128
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(`
129
+ `,"utf-8")}async readExisting(e){try{return await yy(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}firstLine(e){return(e.split(`
130
+ `)[0]??"").replace(vy,"")}extractTitle(e,t){let n=this.firstLine(e);return hu(n)?n:`# ${t}`}extractRest(e){let t=e.split(`
131
+ `);if(!hu(this.firstLine(e)))return e.trim();let n=1;while(n<t.length&&t[n]?.trim()==="")n++;return t.slice(n).join(`
132
+ `).trim()}formatEntry(e,t,n){let r=this.formatPackageHeader(t),s=n.length>0,i=[`## ${r}`];for(let o of e)i.push("",`### ${mo} ${o.message}`),i.push("",this.formatStoneContent(o,t.name));if(s){i.push("",`### ${this.config.sections.dependencies}`);for(let o of n)i.push(`- \`${o.name}\` ${o.version} \u2192 ${o.newVersion}`)}return i.join(`
133
+ `)}formatRootEntry(e,t){let r=[`## ${this.formatRootHeader(t)}`];r.push("","**Packages**");for(let s of t){let i=this.getEmoji(s),o=s.newVersion?`${s.version} \u2192 ${s.newVersion}`:s.version;r.push(`- ${i} \`${s.name}\` ${o}`)}for(let s of e)r.push("",`### ${mo} ${s.message}`),r.push(this.formatStonePackages(s)),r.push("",this.formatRootStoneContent(s));return r.join(`
134
+ `)}formatPackageHeader(e){let t=e.newVersion??e.version,n=this.getDate(),r=this.getEmoji(e);return this.config.packageHeader.replace("{emoji}",()=>r).replace("{version}",()=>t).replace("{date}",()=>n)}formatRootHeader(e){let t=this.getDate(),n=e.map((r)=>`${r.name}@${r.newVersion??r.version}`).join(", ");return this.config.rootHeader.replace("{date}",()=>t).replace("{packages}",()=>n)}formatRootStoneContent(e){let t=[];if(e.description)t.push(this.formatDescription(e.description));if(e.commits?.length){let n=!this.isSectionName(e.message);t.push(this.formatRootCommits(e.commits,n))}return t.join(`
135
135
 
136
- `)}formatRootCommits(e,t){let r=this.formatCommits(e,t);return`<details>
136
+ `)}formatRootCommits(e,t){let n=this.formatCommits(e,t);return`<details>
137
137
  <summary>Commits (${e.length})</summary>
138
138
 
139
- ${r}
139
+ ${n}
140
140
 
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(`
141
+ </details>`}formatStonePackages(e){let t=[...e.major,...e.minor,...e.patch];if(t.length===0)return"";return`**Packages:** ${t.map((r)=>`\`${r}\``).join(" \xB7 ")}`}formatStoneContent(e,t){let n=[];if(e.description)n.push(this.formatDescription(e.description));let r=t&&e.commits?this.filterCommitsForPackage(e.commits,t):e.commits??[];if(r.length>0){let s=!this.isSectionName(e.message);n.push(this.formatCommits(r,s))}return n.join(`
142
142
 
143
143
  `)}isSectionName(e){return Object.values(this.config.sections).includes(e)}formatDescription(e){return`<details>
144
144
  <summary>Description</summary>
145
145
 
146
146
  ${this.convertHeadersToBold(e).split(`
147
- `).map((n)=>` ${n}`).join(`
147
+ `).map((r)=>` ${r}`).join(`
148
148
  `)}
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(`
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?an[e.bump]:"\uD83D\uDCE6"}filterCommitsForPackage(e,t){return e.filter((n)=>n.packages.includes(t))}formatCommits(e,t){if(!t)return e.map((s)=>this.formatCommitLine(s)).join(`
150
+ `);let n=this.groupCommitsByType(e),r=[];for(let[s,i]of n){let o=this.config.sections[s]??`${s} changes`;r.push(`#### ${o}`),r.push(i.map((a)=>this.formatCommitLine(a)).join(`
151
+ `))}return r.join(`
152
152
 
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(`
153
+ `)}groupCommitsByType(e){let t=new Map;for(let n of e){let r=t.get(n.type)??[];r.push(n),t.set(n.type,r)}return Array.from(t.entries()).sort(([n],[r])=>(gt[n]??ft)-(gt[r]??ft))}formatCommitLine(e){let n=`- ${this.commitUrlFn?`[\`${e.hash}\`](${this.commitUrlFn(e.hash)})`:`\`${e.hash}\``} ${e.subject}`;if(e.body){let r=e.body.split(`
154
154
  `).map((s)=>` ${s}`).join(`
155
- `);return`${r}
155
+ `);return`${n}
156
156
  <details>
157
157
  <summary>Details</summary>
158
158
 
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(`
159
+ ${r}
160
+ </details>`}return n}}import{readdir as vu,readFile as Su}from"fs/promises";import{basename as Ay,join as Co}from"path";var Ru="*",$u="^",vo="~",wu=new Map;function se(e,t){return t.some((n)=>n===e||Iy(e,n))}function pe(e,t){let n=e.get("dependents")??ht.dependents;return{ignore:e.get("ignore")??[],kinds:n.kinds,tag:t,updateInternal:n.updateInternal}}function Sy(e,t,n){let r=e.slice(Cs.length);if(r===Ru)return t!==n;if(r!==$u&&r!==vo)return!1;let s=Me(t),i=Me(n);if(!s||!i)return!0;if(Ne(s)||Ne(i))return!0;if(s.major!==i.major)return!0;if(r===vo)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 Rt(e,t,n){let r=n.ignore??[],s=Ey(t,new Set(n.kinds),r),i=new Map,o=new Set,a=[];for(let c of[...e].sort((l,p)=>pn(l.name,p.name))){if(!t.has(c.name)||se(c.name,r))continue;if(o.add(c.name),bu(i,c.name,c.bump))xs(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=n.updateInternal==="outOfRange",h=Me(l.version),f=h!==null&&Ne(h),y=g&&!f?Ee.bump(l.version,p,n.tag):l.version;for(let R of m){let S=f?Cy(R.specifier):Sy(R.specifier,l.version,y);if(g&&!S)continue;if(bu(i,R.dependent,"dependency"))xs(a,R.dependent)}}return[...i.keys()].filter((c)=>!o.has(c)).sort(pn)}function Cy(e){let t=e.slice(Cs.length);return t===Ru||t===$u||t===vo}function So(e,t){if(t.length===0)return{skipped:[],stone:e};let n=[],r=e;for(let s of xe){let i=e.getPackages(s),o=i.filter((a)=>!se(a,t));if(o.length===i.length)continue;n.push(...i.filter((a)=>!o.includes(a))),r=r.withPackages(s,o)}return{skipped:[...new Set(n)].sort(pn),stone:r}}function Pu(e,t){if(t.length===0)return{kept:[...e],skipped:[]};let n=[],r=[];for(let s of e)if(se(s.name,t))r.push(s.name);else n.push(s);return{kept:n,skipped:r}}function dn(e){let t=new Map(e.map((p)=>[p.name,p])),n=[...t.keys()].sort(pn),r=new Map,s=new Map,i=new Map;for(let p of n){let m=new Set((t.get(p)?.workspaceDependencies??[]).filter((g)=>g.kind!=="devDependencies").map((g)=>g.name).filter((g)=>g!==p&&t.has(g)));r.set(p,m.size),i.set(p,m);for(let g of m)s.set(g,[...s.get(g)??[],p])}let o=n.filter((p)=>r.get(p)===0),a=[],c=new Set,l=[];while(c.size<n.length){if(o.length===0){let g=ky(n,c,s,i);if(!g)break;l.push(g),xs(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=(r.get(g)??0)-1;if(r.set(g,h),h===0)xs(o,g)}}return{cycle:l,ordered:a}}function ky(e,t,n,r){let s=xy(e,t,r),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=(n.get(c)??[]).filter((p)=>!t.has(p)).length;if(l<=a)continue;o=c,a=l}return o}function xy(e,t,n){let r=new Map,s=new Map,i=[],o=new Set,a=new Set,c=(l)=>{let p=r.size;r.set(l,p),s.set(l,p),i.push(l),o.add(l);for(let f of n.get(l)??[]){if(t.has(f))continue;if(!r.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,r.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)=>[...n.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)&&!r.has(l))c(l);return a}function Ey(e,t,n){let r=new Map;for(let s of[...e.keys()].sort(pn)){if(se(s,n))continue;for(let i of e.get(s)?.workspaceDependencies??[]){if(!Ty(i,t,e,n))continue;r.set(i.name,[...r.get(i.name)??[],{dependent:s,specifier:i.specifier}])}}return r}function Ty(e,t,n,r){if(!t.has(e.kind))return!1;if(!n.has(e.name))return!1;return!se(e.name,r)}function bu(e,t,n){let r=e.get(t),s=r===void 0?n:ln(r,n);if(r!==void 0&&s===r)return!1;return e.set(t,s),!0}function xs(e,t){if(e.includes(t))return;let n=e.findIndex((r)=>pn(r,t)>0);if(n<0)e.push(t);else e.splice(n,0,t)}function pn(e,t){if(e===t)return 0;return e<t?-1:1}function Iy(e,t){let n=wu.get(t);if(!n)n=new Bun.Glob(t),wu.set(t,n);return n.match(e)}var Oy=".changeset",_y="config.json",Es="---",Cu=0,ko=1,Ly=Cl().or(qe()),Dy=ke((e)=>Array.isArray(e)?K():dt(tn())(e)),My=_();function $t(e,t){return(n)=>{if(n===void 0)return;try{return t(n)}catch{throw new Eo(`${e} has an unsupported value`)}}}class Eo extends Error{}var ku=ne(ne(_())),Ny=st({access:$t("access",De(["restricted","public"])),baseBranch:$t("baseBranch",_()),changelog:$t("changelog",_().or(ne(tn())).or(De([!1]))),commit:$t("commit",nn().or(_()).or(ne(tn()))),fixed:$t("fixed",ku),ignore:$t("ignore",ne(_())),linked:$t("linked",ku),updateInternalDependencies:$t("updateInternalDependencies",De(["patch","minor"]))});class jt extends Error{}function xu(e){if(e===null)return"null";return Array.isArray(e)?"a list":`a ${typeof e}`}function jy(e){let t=e.split(`
161
+ `);if(t[Cu]?.trim()!==Es)throw new jt(`it does not start with a ${Es} front matter line`);let n=t.findIndex((s,i)=>i>Cu&&s.trim()===Es);if(n<ko)throw new jt(`its front matter has no closing ${Es} line`);let r;try{r=Bun.YAML.parse(t.slice(ko,n).join(`
162
+ `))}catch(s){let i=s instanceof Error?s.message:String(s);throw new jt(`its front matter is not valid YAML (${i})`)}return{frontmatter:r,summary:t.slice(n+ko).join(`
163
+ `).trim()}}function xo(e,t){try{return e(t),!0}catch{return!1}}function Fy(e){if(xo(Ly,e))return null;if(!xo(Dy,e))throw new jt(`its front matter must map package names to bump types, not ${xu(e)}`);let t=Object.entries(e);if(t.length===0)return null;let n=t.filter(([,r])=>!xo(My,r));if(n.length>0){let r=n.map(([s,i])=>`${s} has ${xu(i)} instead of a bump type`);throw new jt(r.join("; "))}return Object.fromEntries(t)}class To{root;constructor(e=process.cwd()){this.root=e}get changesetDir(){return Co(this.root,Oy)}async exists(){try{return await vu(this.changesetDir),!0}catch{return!1}}async parse(){let e=[],t=[],n=[];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":n.push(i.filename);break;case"Invalid":e.push(`${i.filename}: ${i.reason}`);break}}let r=await this.parseConfig(e);return{changesets:t,config:r,empty:n,errors:e}}async findChangesetFiles(){try{return(await vu(this.changesetDir)).filter((t)=>t.endsWith(".md")&&t!=="README.md").sort().map((t)=>Co(this.changesetDir,t))}catch{return[]}}async parseFile(e){let t=Ay(e);try{let{frontmatter:n,summary:r}=jy(await Su(e,"utf-8")),s=Fy(n);return s?{_tag:"Parsed",changeset:{filename:t,packages:s,summary:r}}:{_tag:"Empty",filename:t}}catch(n){if(n instanceof jt)return{_tag:"Invalid",filename:t,reason:n.message};let r=n instanceof Error?n.message:String(n);return{_tag:"Invalid",filename:t,reason:`it cannot be read (${r})`}}}async parseConfig(e){let t=Co(this.changesetDir,_y),n;try{n=await Su(t,"utf-8")}catch(r){if(r.code==="ENOENT")return null;return e.push(`Failed to read ${t}: ${r instanceof Error?r.message:String(r)}`),null}try{return Ny(JSON.parse(n))}catch(r){let s=r instanceof Eo?r.message:"it must be a JSON object";return e.push(`Invalid ${t}: ${s}`),null}}toStoneData(e,t){let n=[],r=[],s=[],i=[];for(let[g,h]of Object.entries(e.packages))switch(h){case"major":n.push(g);break;case"minor":r.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=[...n.map((g)=>({bump:"major",name:g})),...r.map((g)=>({bump:"minor",name:g})),...s.map((g)=>({bump:"patch",name:g}))],c=t?X(Rt(a,t.packages,t.dependents)):void 0,l=e.summary.split(`
164
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(`
165
+ `).trim();return{dependency:c,description:m||void 0,major:X(n),message:p,minor:X(r),patch:X(s)}}}function Ts(e){let t=new Map;for(let[n,r]of e){let s=r.file.replace(/\\/g,"/"),i=s.substring(0,s.lastIndexOf("/"))||".";t.set(i,n)}return t}function Zn(e,t,n=!0){let r=new Set;for(let s of e)for(let[i,o]of t){let a=i===".",c=s.startsWith(`${i}/`);if(a?n:c)r.add(o)}return r}import{existsSync as mn}from"fs";import{mkdir as Eu,readdir as Io,readFile as Tu,unlink as Iu,writeFile as Au}from"fs/promises";import{dirname as By,join as Qn,resolve as Ou}from"path";var _u=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,Lu=/^\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")||on}get stonesPath(){return this.config.get("stonesPath")||Qn(this.sisyphusDir,Ml)}get releasedPath(){return Qn(this.sisyphusDir,Nl)}getStoragePaths(){return[this.sisyphusDir,this.stonesPath]}async list(){let e=await this.listIds(),t=[];for(let n of e){let r=await this.get(n);if(r)t.push(r)}return t}async listIds(){return(await this.readStoneFiles()).filter((t)=>t.endsWith(".json")).map((t)=>this.toStoneId(t)).sort()}async get(e){let t=this.getFilePath(e);if(!mn(t))return null;let n=await Tu(t,"utf-8"),r=this.parseStoneJson(n,t);return this.assertStoneId(r,e,t),O.fromJson(r)}parseStoneJson(e,t){let n;try{n=JSON.parse(e)}catch{throw new u(`Failed to parse stone file ${t}`,"Remove or fix the file")}if(typeof n!=="object"||n===null||Array.isArray(n))throw new u(`Stone file ${t} is not a JSON object`,"Remove or fix the file");return n}assertStoneId(e,t,n){if(e.id===t)return;throw new u(`Stone file ID mismatch: expected "${t}", found "${String(e.id)}"`,`Fix ${n}`)}async readStoneFiles(){try{return await Io(this.stonesPath)}catch(e){if(e.code==="ENOENT")return[];throw e}}async save(e){await this.ensureStorageExists();let t=this.getFilePath(e.id),n=JSON.stringify(e.toJson(),null,2);await Au(t,n,"utf-8")}async delete(e){let t=this.getFilePath(e);if(!mn(t))return!1;return await Iu(t),!0}async deleteMany(e){let t=0;for(let n of e)if(await this.delete(n))t++;return t}async create(e){let t=await this.listIds(),n=O.create(e,t.length);return await this.save(n),n}async archive(e){if(e.length===0)return"";let t=this.createTimestamp(),n=Qn(this.releasedPath,t);await Eu(n,{recursive:!0});for(let r of e){let s=this.getFilePath(r.id),i=Qn(n,`${r.id}.json`);if(mn(s))await Au(i,JSON.stringify(r.toJson(),null,2),"utf-8"),await Iu(s)}return t}async getReleasedStones(e,t){let n=this.getArchivePath(e);if(!mn(n))return[];let s=(await Io(n)).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=Qn(n,a),p=await Tu(l,"utf-8"),m=this.parseStoneJson(p,l);this.assertStoneId(m,c,l),o.push(O.fromJson(m))}catch(c){if(t)throw c;P.warn(d.dim(`Failed to parse stone "${a}": ${c}`))}return o}async listReleasedTimestamps(){if(!mn(this.releasedPath))return[];return(await Io(this.releasedPath,{withFileTypes:!0})).filter((t)=>t.isDirectory()&&Lu.test(t.name)).map((t)=>t.name)}async getTrackedCommitPackages(){let e=await this.list(),t=new Map;for(let n of e.flatMap((r)=>r.commits??[])){let r=t.get(n.hash)??new Set;for(let s of n.packages)r.add(s);t.set(n.hash,r)}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(!Lu.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,n){let r=Ou(e),s=Ou(r,t);if(By(s)!==r)throw Error(n);return s}validateId(e){if(!_u.test(e))throw Error(`Invalid stone ID "${e}"`);return e}toStoneId(e){let t=e.slice(0,-5);if(_u.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(!mn(this.stonesPath))await Eu(this.stonesPath,{recursive:!0})}}import{posix as Uy,sep as Gy}from"path";var Ao="!",Du="./",Vy="node_modules",Hy="package.json";class U{static async scan(e={}){let{filter:t,single:n}=e;if(n)return U.scanRootPackage(t);let r=await U.getWorkspaces();U.validateWorkspaces(r);let s=await U.scanWorkspaces(r);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((n)=>n.includes(t))}static async scanRootPackage(e){let t=await Bun.file("package.json").json(),n=z.fromJson(t,"package.json"),r=new Map;return r.set(n.name,n),{packageNames:U.filterNames([n.name],e),packages:r}}static async scanWorkspaces(e){let t=new Map;for(let n of U.expandWorkspaces(e)){let r=await Bun.file(n).json(),s=z.fromJson(r,n),i=t.get(s.name);if(i)throw new u(`Duplicate workspace package ${s.name}: ${i.file} and ${n}`);t.set(s.name,s)}return t}static expandWorkspaces(e){let t=e.filter((r)=>r.startsWith(Ao)).map((r)=>new Bun.Glob(Oo(r.slice(Ao.length)))),n=new Set;for(let r of e){if(r.startsWith(Ao))continue;let s=new Bun.Glob(`${Oo(r)}/${Hy}`);for(let i of s.scanSync({cwd:process.cwd()})){let o=Oo(i.split(Gy).join("/"));if(o.split("/").includes(Vy))continue;let a=Uy.dirname(o);if(t.some((c)=>c.match(a)||c.match(o)))continue;n.add(o)}}return[...n]}}function Oo(e){return e.startsWith(Du)?e.slice(Du.length):e}var qy={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch",[mt]:"patch"},Wy=/\{message\}|\{packages\}|\{versions\}/,Jy=/[.*+?^${}()|[\]\\]/g,zy=/^- \S+@\S+(?:\n- \S+@\S+)*(?:\n\n[\s\S]*)?$/;function Ky(e){return e.replace(Jy,"\\$&")}function Xy(e){return new RegExp(`^${e.split(Wy).map(Ky).join(".+")}$`)}function Yy(e){return e.map((t)=>{try{return new RegExp(t,"i")}catch(n){throw new u(`Invalid regex pattern in commits.skip.messagePatterns: "${t}"`,void 0,1,{cause:n})}})}class Ft{config;stoneManager;constructor(e){this.config=e;this.stoneManager=new B(e)}async analyze(e={}){let t=this.config.get("commits")?.skip??ht.commits.skip,n={authors:t.authors,patterns:Yy(t.messagePatterns),releaseSubject:Xy(this.config.get("commit").message)},r=await this.getCommitsSinceLastRelease();if(r.length===0)return[];if(r=r.filter((i)=>!this.shouldSkipCommit(i,n)),r.length===0)return[];let s=await this.stoneManager.getTrackedCommitPackages();return this.groupByPackage(r,e,s)}shouldSkipCommit(e,t){if(t.authors.includes(e.author))return!0;if(t.patterns.some((n)=>n.test(e.subject)))return!0;return t.releaseSubject.test(e.subject)&&zy.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,n){let{packages:r,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([...r].filter(([p])=>o.has(p))),c=Ts(a),l=new Map;for(let p of e){let m=Zn(p.files,c);for(let y of n.get(p.shortHash)??[])m.delete(y);if(m.size===0)continue;let g=p.breaking?"major":qy[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])=>(gt[p]??ft)-(gt[m]??ft)).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,n){let r=Array.from(e.packages),s=r.map((i)=>({bump:e.bump,name:i}));return{[e.bump]:r,commits:X(e.commits),dependency:X(Rt(s,t,n)),message:e.message,tag:n.tag}}}import{readFile as Zy,writeFile as Mu}from"fs/promises";class er{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 Mu(e,t,"utf-8");this.originals.clear()}async updatePackage(e){let t=e.newVersion;if(!t)return;Ps(t,`write the new version of ${e.name}`);let n=await Zy(e.file,"utf-8");this.originals.set(e.file,n),await Mu(e.file,Wn(n,{...JSON.parse(n),version:t}),"utf-8")}}var Qy=/^[\t ]+/m,ew=new Set(["*","^","~"]);class Pt extends Error{hint;_tag="PublishManifestError";constructor(e,t){super(e);this.hint=t}}function Nu(e){let t=Array.isArray(e.workspaces)?void 0:e.workspaces;return{["default"]:{...e.catalog,...t?.catalog},...e.catalogs,...t?.catalogs}}function tw(e,t,n,r){let s=t.slice(8)||"default",i=Object.hasOwn(n,s)?n[s]:void 0,o=i&&Object.hasOwn(i,e)?i[e]:void 0;if(!o)throw new Pt(`Catalog "${s}" has no entry for "${e}" (required by ${r})`,"Add the entry to the root package.json catalog before publishing");return o}function nw(e,t,n,r){let s=t.slice(10),i=Object.hasOwn(n,e)?n[e]:void 0;if(!i)throw new Pt(`Workspace package "${e}" (required by ${r}) was not found in the workspace`,"Check the dependency name against your workspaces globs");if(i.isPrivate)throw new Pt(`"${r}" 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(!ew.has(s)){if(!s)throw new Pt(`Invalid workspace specifier "${t}" for "${e}" (required by ${r})`,"Use workspace:*, workspace:^, workspace:~, or workspace:<range>");return s}let o=i.version;if(!o)throw new Pt(`Workspace package "${e}" (required by ${r}) has no version in its package.json`,"Add a version field before publishing");return s==="*"?o:`${s}${o}`}function _o(e,t,n,r){if(!e)return e;return Object.fromEntries(Object.entries(e).map(([s,i])=>{if(i.startsWith("catalog:"))return[s,tw(s,i,t,r)];if(i.startsWith("workspace:"))return[s,nw(s,i,n,r)];return[s,i]}))}function rw(e,t,n){let{devDependencies:r,...s}=e;return{...s,dependencies:_o(e.dependencies,t,n,e.name),optionalDependencies:_o(e.optionalDependencies,t,n,e.name),peerDependencies:_o(e.peerDependencies,t,n,e.name)}}function ju(e,t,n){let r=JSON.parse(e),s=rw(r,t,n),i=e.match(Qy)?.[0]??2;return`${JSON.stringify(s,null,i)}
166
+ `}function Fu(e){return Object.fromEntries(Array.from(e,(t)=>[t.name,{isPrivate:t.isPrivate,version:t.version||null}]))}function Bu(e,t,n){try{return ju(e,t,n)}catch(r){throw r instanceof Pt?new u(r.message,r.hint):r}}var iw="%an%x00%ae%x00%aI%x00%s",ow=2,aw="feat";class Lo{config;provider=null;constructor(e){this.config=e}async analyze(e){let t=await this.getProvider(),n=e?await this.fetchFromUrl(t,e):await this.fetchFromCurrentBranch(t),r=this.config.get("single"),{packages:s}=await U.scan({single:r}),i=Ts(s),o={isSinglePackage:r,packagePaths:i,provider:t},{commits:a,affectedPackages:c}=n.merged?await this.analyzeAfterMerge(n,o):await this.analyzeBeforeMerge(n,o),l=this.inferBumpFromLabels(n.labels)??this.inferBumpFromTitle(n.title);return{commits:a,packages:c,pr:n,suggestedBump:l}}async analyzeBeforeMerge(e,t){let n=await Z.inRange(e.baseBranch,e.branch);return this.processCommits(n,t)}async analyzeAfterMerge(e,t){if(await this.detectMergeMethod(e.mergeCommitSha)==="squash")return this.analyzeSquashMerge(e,t);return this.analyzeMergeCommit(e,t)}async analyzeSquashMerge(e,t){let n=await t.provider.getPrCommits(e.number);if(e.mergeCommitSha){let o=n.includes(e.mergeCommitSha)?n:await this.findRebasedCommits(e.mergeCommitSha,n),a=o?await Promise.all(o.map((c)=>Z.fromHash(c))):[];if(o&&a.every((c)=>c!==null))return this.processCommits(a,t)}let r=await t.provider.getPrFiles(e.number);if(r.length===0)throw new u(`Could not determine changed files for PR #${e.number}`,"Check provider access and retry the analysis");let s=Zn(r,t.packagePaths,t.isSinglePackage);if(!e.mergeCommitSha)return{affectedPackages:s,commits:[]};let i={body:e.body||void 0,hash:e.mergeCommitSha.slice(0,ds),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 n=await Bun.$`git rev-list --first-parent --no-merges ${`--max-count=${t.length}`} ${e}`.quiet().nothrow(),r=n.exitCode===0?n.stdout.toString().split(`
167
+ `).filter(Boolean).reverse():[];if(r.length!==t.length)return null;let[s,i]=await Promise.all([this.readIdentities(r),this.readIdentities(t)]);return s!==null&&s===i?r:null}async readIdentities(e){let t=await Bun.$`git show --no-patch --no-walk=unsorted ${`--format=${iw}`} ${e}`.quiet().nothrow();return t.exitCode===0?t.stdout.toString():null}async analyzeMergeCommit(e,t){if(!e.mergeCommitSha)return{affectedPackages:new Set,commits:[]};let n=await Z.fromMerge(e.mergeCommitSha);return this.processCommits(n,t)}processCommits(e,t){let n=[],r=new Set;for(let s of e){let i=Zn(s.files,t.packagePaths,t.isSinglePackage);if(i.size===0)continue;n.push(s.toInfo([...i]));for(let o of i)r.add(o)}return{affectedPackages:r,commits:n}}async detectMergeMethod(e){if(!e)return"squash";if(await this.getCommitParentCount(e)===ow)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 bt(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 n=await ys(this.config.get("provider")),r=Xl(t,n??void 0);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");if(!n||r.host!==ze(n)||n.owner.toLowerCase()!==r.owner.toLowerCase()||n.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 s=await e.getPr(r.number);return this.mapPullRequest(s)}mapPullRequest({headBranch:e,...t}){return{...t,branch:e}}inferBumpFromLabels(e){let t=this.config.get("pr").labelMapping,n=null;for(let r of e){let s=r.toLowerCase();for(let[i,o]of Object.entries(t)){if(s!==i.toLowerCase())continue;n=n?ln(n,o):o}}return n}inferBumpFromTitle(e){let t=Z.parse("",e,"");if(t.breaking)return"major";if(t.type===mt)return null;return t.type===aw?"minor":"patch"}}import{resolve as Bb}from"path";import{createHash as Zw,randomUUID as Qw}from"crypto";import{constants as eb}from"fs";import{copyFile as tb,link as nb,lstat as Sp,readFile as oa,rename as Cp,rm as kp,stat as rb,unlink as sb}from"fs/promises";import{extname as ib,join as ob,resolve as xp}from"path";import{createHash as lp,randomUUID as _w}from"crypto";import{link as Lw,lstat as dr,mkdir as Bs,open as Dw,readFile as up,realpath as St,rename as Mw,rm as Nw,unlink as jw}from"fs/promises";import{dirname as lr,isAbsolute as cp,join as ur,relative as pp,resolve as je,sep as Fw}from"path";import{createHash as Is}from"crypto";import{constants as Uu}from"fs";import{lstat as cw,open as lw,readlink as Vu,realpath as uw}from"fs/promises";import{basename as pw,dirname as dw,isAbsolute as mw,join as gw,relative as Do,resolve as it,sep as Mo}from"path";var No=new Set(["100644","100755"]),gn="120000",tr="160000",fw=/["\\\n\r\t]/g,hw={"\t":"\\t","\n":"\\n","\r":"\\r",'"':"\\\"","\\":"\\\\"},Hu=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;function nr(e){let[t,n]=new B(e).getStoragePaths();return[t,n,e.path]}async function Os(e,...t){let n=await Bun.$`git rev-parse --show-toplevel`.quiet(),r=it(n.stdout.toString().trim()),s=await Promise.all([e,...t].map((a)=>bw(r,a))),i=await Rw(r,s),o=Is("sha256");for(let a of i){if(a.kind==="tracked"&&!$w(a.mode))throw new u(`Release source has unsupported Git mode ${a.mode}: ${a.path}`);let c=await zu(r,a.path),l=await jo(c);if(o.update(a.path),o.update("\x00"),o.update(a.kind),o.update("\x00"),!l){if(a.kind==="tracked"&&a.mode===tr)throw new u(`Release source gitlink is not initialized: ${a.path}`);o.update("deleted")}else if(a.kind==="untracked"||No.has(a.mode)){if(!l.isFile()||l.isSymbolicLink())throw new u(`Release source path is not a regular file: ${a.path}`);await Pw(o,c,a.path)}else if(a.mode===gn){if(!l.isSymbolicLink())throw new u(`Release source path does not match Git mode ${gn}: ${a.path}`);o.update(Is("sha256").update(await Vu(c,{encoding:"buffer"})).digest("hex")),o.update(gn)}else{if(!l.isDirectory()||l.isSymbolicLink())throw new u(`Release source path does not match Git mode ${tr}: ${a.path}`);o.update(await Ku(r,c,a)),await rr(c),o.update(tr)}o.update("\x00")}return o.digest("hex")}async function rr(e=process.cwd()){let t=await Bun.$`git rev-parse --show-toplevel`.cwd(e).quiet(),n=it(t.stdout.toString().trim());await qu(n)}async function qu(e){let[t,n]=await Promise.all([Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),Bun.$`git ls-files -v -z --cached`.cwd(e).quiet()]),r=new Set,s=new Map,i=[];for(let a of As(n.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 As(t.stdout)){let c=Ju(a);if(c.stage!=="0")throw new u(`Release source has an unresolved index entry: ${c.path}`);if(r.has(c.path))throw new u(`Release source has duplicate index entries: ${c.path}`);if(r.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 zu(e,c.path),m=await jo(p);if(!m)throw new u(`Release source path is missing: ${c.path}`);if(No.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===gn){if(!m.isSymbolicLink())throw new u(`Release source path does not match Git mode ${gn}: ${c.path}`);let g=await Bun.$`git cat-file blob ${c.objectId}`.cwd(e).quiet(),h=await Vu(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!==tr)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 Ku(e,p,l),await qu(p)}let o=await yw(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 yw(e,t){if(t.length===0)return[];let n=Buffer.from(`${t.map(ww).join(`
169
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):
170
+ `),s=(await Bun.$`git hash-object --stdin-paths < ${n}`.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 ww(e){return`"${e.replace(fw,(t)=>hw[t]??t)}"`}function _s(e,t){return Is("sha256").update(JSON.stringify(fn({...e,stones:t}))).digest("hex")}function fn(e){if(Array.isArray(e))return e.map(fn);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>[t,fn(n)]))}function de(e){return e===".."||e.startsWith(`..${Mo}`)||mw(e)}async function bw(e,t){let n=Do(e,await Wu(it(e,t)));if(!n||de(n))throw new u(`Release metadata path is outside the repository: ${t}`,"Keep sisyphusDir, stonesPath and the Sisyphus config inside the repository");return n.split(Mo).join("/")}async function Wu(e){let t=dw(e);if(t===e)return e;let n=await uw(t).catch((r)=>{if(Fo(r,"ENOENT"))return Wu(t);throw r});return gw(n,pw(e))}async function Rw(e,t){let[n,r]=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 As(n.stdout)){let a=Ju(o);if(Gu(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 As(r.stdout)){if(Gu(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 As(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 Ju(e){let t=e.indexOf("\t");if(t<0)throw new u("Unable to parse Git index entry while hashing release source");let[n,r,s,...i]=e.slice(0,t).split(" "),o=e.slice(t+1);if(!n||!/^[0-7]{6}$/.test(n)||!r||!Hu.test(r)||!s||i.length>0||!o)throw new u("Unable to parse Git index entry while hashing release source");return{mode:n,objectId:r,path:o,stage:s}}function Gu(e,t){return t.some((n)=>e===n||e.startsWith(`${n}/`))}function $w(e){return No.has(e)||e===gn||e===tr}async function zu(e,t){let n=t.split("/"),r=it(e,t),s=Do(e,r);if(n.some((o)=>!o||o==="."||o==="..")||de(s)||s.split(Mo).join("/")!==t)throw new u(`Release source path escapes the repository: ${t}`);let i=e;for(let o of n.slice(0,-1)){i=it(i,o);let a=await jo(i);if(!a)break;if(!a.isDirectory()||a.isSymbolicLink())throw new u(`Release source path has an unsafe parent: ${t}`)}return r}async function jo(e){try{return await cw(e)}catch(t){if(Fo(t,"ENOENT"))return null;throw t}}function Fo(e,t){return e instanceof Error&&"code"in e&&e.code===t}async function Pw(e,t,n){let r=await lw(t,Uu.O_RDONLY|Uu.O_NOFOLLOW).catch((s)=>{if(Fo(s,"ELOOP"))throw new u(`Release source path is not a regular file: ${n}`);throw s});try{let s=await r.stat();if(!s.isFile())throw new u(`Release source path is not a regular file: ${n}`);e.update(Is("sha256").update(await r.readFile()).digest("hex")),e.update(s.mode&73?"100755":"100644")}finally{await r.close()}}async function Ku(e,t,n){let[r,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(r.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=Do(m,p);if(a!==t||l!==e||!g||de(g))throw new u(`Release source gitlink is not initialized: ${n.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: ${n.path}`,"Commit or discard submodule changes before releasing");let y=(await Bun.$`git rev-parse --verify HEAD`.cwd(t).quiet()).stdout.toString().trim();if(!Hu.test(y))throw new u(`Release source gitlink has an invalid object ID: ${n.path}`);if(y!==n.objectId)throw new u(`Release source gitlink does not match the recorded commit: ${n.path}`,"Check out the submodule commit recorded by the repository before releasing");return n.objectId}var sr=1,hn=["planned","local-ready","external","completed"],Bo=["pending","started","completed"],vw=/^[0-9A-Za-z][0-9A-Za-z_-]*$/,Bt=/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/,Xu=/^sha512-[0-9A-Za-z+/]{86}==$/,Yu=/^[0-9A-Za-z][0-9A-Za-z._/-]*$/,Uo=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Zu=/^(?:linux:[0-9a-f-]{36}:[0-9]+|ps:.+|windows:[0-9]+)$/i,Ls=2,Qu=3,ep=19;class b extends Error{_tag="ReleaseLedgerError"}function v(e,t){throw new b(`Invalid release ledger at ${e}: ${t}`)}function ir(e,t){if(typeof e!=="string")v(t,"must be a string");return e}function A(e,t){let n=ir(e,t);if(!n.trim())v(t,"must be nonempty");return n}function or(e,t){let n=A(e,t);if(!vw.test(n))v(t,`invalid release ID ${n}`);return n}function Ds(e){let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function re(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 Sw}from"crypto";import{constants as tp,readFileSync as np}from"fs";import{link as Cw,lstat as Ut,open as Ho,readFile as sp,rename as kw,rm as Ns,unlink as js}from"fs/promises";import{hostname as ip}from"os";import{dirname as vt,join as Go}from"path";async function cr(e){let t=Go(e,".write.lock");for(let n=0;n<Qu;n+=1){let r=Aw();if(!r)throw new b("Failed to identify the release ledger lock owner process");let s={acquiredAt:new Date().toISOString(),hostname:ip(),ownerId:Sw(),pid:process.pid,processStartedAt:r,schemaVersion:Ls},i=Fs(e,s.ownerId,"owner");await xw(i,s);try{await Cw(i,t)}catch(a){if(await Ns(i,{force:!0}),!re(a,"EEXIST"))throw new b(`Failed to acquire release ledger lock at ${t}: ${j(a)}`);let c=await Ew(t);if(!c)continue;await Tw(c);continue}let o={lockPath:t,metadata:s,ownerPath:i};try{return await me(e),o}catch(a){try{await yn(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 xw(e,t){let n;try{n=await Ho(e,"wx",384),await n.writeFile(`${JSON.stringify(t)}
172
+ `,"utf-8"),await n.sync()}catch(r){throw await Ns(e,{force:!0}),new b(`Failed to create release ledger lock owner: ${j(r)}`)}finally{await n?.close()}await me(vt(e))}async function Ew(e){let t,n,r;try{r=await Ho(e,tp.O_RDONLY|tp.O_NOFOLLOW),t=await r.stat(),n=await r.readFile("utf-8")}catch(p){if(re(p,"ENOENT"))return null;throw new b(`Failed to inspect release ledger lock at ${e}: ${j(p)}`)}finally{await r?.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=Vo(JSON.parse(n))}catch{s=null}if(!s)return await Ms(e,t,"lock metadata is malformed");let i=Fs(vt(e),s.ownerId,"owner"),o=Fs(vt(e),s.ownerId,"claim"),a;try{a=await Ut(i)}catch(p){if(re(p,"ENOENT")){try{await Ut(o)}catch(m){if(re(m,"ENOENT"))return await Ms(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 Ms(e,t,"stale lock ownership is invalid");let c=null;try{c=Vo(JSON.parse(await sp(i,"utf-8")))}catch{c=null}if(!c||!Ow(s,c))return await Ms(e,t,"stale lock ownership is invalid");if(!await ap(e,t))return null;if(!ar(t,a))return{lockPath:e,lockStat:t,metadata:s,ownerPath:i,ownerStat:a};if(s.hostname!==ip())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=Iw(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 Tw(e){let t=Fs(vt(e.lockPath),e.metadata.ownerId,"claim");if(e.ownerPath!==t)try{await kw(e.ownerPath,t),await me(vt(e.lockPath))}catch(s){if(re(s,"ENOENT")||re(s,"EEXIST"))return;throw new b(`Failed to claim stale release ledger lock: ${j(s)}`)}let n,r;try{[n,r]=await Promise.all([Ut(e.lockPath),Ut(t)])}catch(s){if(re(s,"ENOENT"))return;throw new b(`Failed to verify stale release ledger lock: ${j(s)}`)}if(!ar(e.lockStat,n))return;if(!ar(e.ownerStat,r))return;try{await js(e.lockPath),await me(vt(e.lockPath)),await js(t),await me(vt(e.lockPath))}catch(s){if(re(s,"ENOENT"))return;throw new b(`Failed to recover stale release ledger lock: ${j(s)}`)}}async function yn(e){let t,n;try{[t,n]=await Promise.all([Ut(e.lockPath),Ut(e.ownerPath)])}catch(s){if(re(s,"ENOENT"))throw await Ns(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(!ar(t,n))throw await Ns(e.ownerPath,{force:!0}),new b("Failed to release ledger write lock: ownership changed");let r=null;try{r=Vo(JSON.parse(await sp(e.lockPath,"utf-8")))}catch{r=null}if(r?.ownerId!==e.metadata.ownerId)throw new b("Failed to release ledger write lock: owner identity changed");try{await js(e.lockPath),await js(e.ownerPath),await me(vt(e.lockPath))}catch(s){throw new b(`Failed to release ledger write lock: ${j(s)}`)}}function Vo(e){if(typeof e!=="object"||e===null||Array.isArray(e))return null;let t=e,n=Object.keys(t);if(n.length!==6||!n.every((r)=>["acquiredAt","hostname","ownerId","pid","processStartedAt","schemaVersion"].includes(r))||t.schemaVersion!==Ls||typeof t.ownerId!=="string"||!Uo.test(t.ownerId)||typeof t.hostname!=="string"||!t.hostname||typeof t.pid!=="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.processStartedAt!=="string"||!Zu.test(t.processStartedAt)||typeof t.acquiredAt!=="string"||!Ds(t.acquiredAt))return null;return{acquiredAt:t.acquiredAt,hostname:t.hostname,ownerId:t.ownerId,pid:t.pid,processStartedAt:t.processStartedAt,schemaVersion:Ls}}function Fs(e,t,n){if(!Uo.test(t))throw new b(`Release ledger is locked by another process at ${Go(e,".write.lock")}: lock owner identity is malformed`);return Go(e,`.write.lock.${t}.${n}`)}function Iw(e){try{process.kill(e.pid,0)}catch(n){return re(n,"ESRCH")?"dead":"unknown"}let t=op(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 rp=null;function Aw(){return rp??=op(process.pid),rp}function op(e){if(process.platform==="linux")try{let t=np("/proc/sys/kernel/random/boot_id","utf-8").trim(),n=np(`/proc/${e}/stat`,"utf-8"),r=n.lastIndexOf(")"),s=r<0?void 0:n.slice(r+1).trim().split(/\s+/)[ep];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"}),n=t.stdout.toString().trim();if(t.exitCode===0&&/^[0-9]+$/.test(n))return`windows:${n}`}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 n=t.stdout.toString().trim().replace(/\s+/g," ");return n?`ps:${n}`:null}catch{return null}}function ar(e,t){return e.dev===t.dev&&e.ino===t.ino}async function ap(e,t){try{return ar(t,await Ut(e))}catch(n){if(re(n,"ENOENT"))return!1;throw new b(`Failed to verify release ledger lock at ${e}: ${j(n)}`)}}async function Ms(e,t,n){if(!await ap(e,t))return null;throw new b(`Release ledger is locked by another process at ${e}: ${n}`)}function Ow(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 Ho(e,"r");try{await t.sync()}finally{await t.close()}}async function qo(e){let t=je(e),n=await Bun.$`git rev-parse --show-toplevel`.cwd(t).quiet().nothrow();if(n.exitCode!==0)throw new b(`Failed to resolve repository root from ${t}: ${n.stderr.toString().trim()||"git exited unsuccessfully"}`);let r=n.stdout.toString().trim();if(!r)throw new b(`Failed to resolve repository root from ${t}: empty git output`);let s=cp(r)?je(r):je(t,r),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=cp(o)?je(o):je(s,o);return{activePath:ur(a,"active.json"),artifactsRoot:ur(a,"artifacts"),historyDirectory:ur(a,"history"),releaseDirectory:a,removingPath:ur(a,"removing.json"),repositoryRoot:s}}async function dp(e,t){let n=`${t}^{tree}`,r=await Bun.$`git rev-parse ${n}`.cwd(e).quiet().nothrow(),s=r.stdout.toString().trim();if(r.exitCode!==0||!Bt.test(s))throw new b(`Cannot resolve release tree for commit ${t}`);return s}async function mr(e,t){await Bs(e.releaseDirectory,{recursive:!0}),await Ct(e.releaseDirectory,"release directory"),await Bs(e.artifactsRoot,{recursive:!0}),await Ct(e.artifactsRoot,"artifacts root"),await Bs(gr(e,t),{recursive:!0}),await mp(e,t)}async function mp(e,t){let n=gr(e,t);await Ct(e.releaseDirectory,"release directory"),await Ct(e.artifactsRoot,"artifacts root"),await Ct(n,`artifacts directory for release ${t}`);let r=await St(e.releaseDirectory),s=await St(e.artifactsRoot),i=await St(n);return pr(r,s,"Artifacts root escapes the release directory"),pr(s,i,`Artifacts directory for release ${t} escapes the artifacts root`),i}async function gp(e){await Ct(e.releaseDirectory,"release directory"),await Bs(e.historyDirectory,{recursive:!0}),await Ct(e.historyDirectory,"history directory");let t=await St(e.releaseDirectory),n=await St(e.historyDirectory);pr(t,n,"History directory escapes the release directory")}async function fp(e,t){for(let[n,r]of Object.entries(e.artifacts))await Us(t,e.id,n,r)}async function Us(e,t,n,r){let s=je(e.releaseDirectory,r.path);if(await wn(e,t,s),await bn(s)!==r.integrity)throw new b(`Invalid release ledger artifact for ${n}: sha512 integrity mismatch`)}async function Gs(e,t){let n=await St(t.repositoryRoot);for(let r of e.packages){let s=je(t.repositoryRoot,r.file),i;try{i=await dr(s)}catch(a){throw new b(`Invalid package manifest for ${r.name} at ${r.file}: ${j(a)}`)}if(!i.isFile()||i.isSymbolicLink())throw new b(`Invalid package manifest for ${r.name} at ${r.file}: expected a regular file`);let o=await St(s);pr(n,o,`Package manifest for ${r.name} escapes the repository: ${r.file}`)}}async function wn(e,t,n){let r=await mp(e,t),s;try{s=await dr(n)}catch(o){throw new b(`Invalid release artifact at ${n}: ${j(o)}`)}if(!s.isFile()||s.isSymbolicLink())throw new b(`Invalid release artifact at ${n}: expected a regular file`);let i=await St(n);pr(r,i,`Release artifact escapes artifacts directory: ${n}`)}async function Wo(e,t,n,r){let s=`${JSON.stringify(t,null,2)}
173
+ `,i=ur(lr(e),`.${_w()}.json.tmp`),o=await cr(lr(e));try{if(await Ct(lr(e),"release directory"),n){await Bw(e,"active release ledger");let c;try{c=JSON.parse(await up(e,"utf-8"))}catch(l){throw new b(`Failed to read active release ledger at ${e} before writing: ${j(l)}`)}if(c.updatedAt!==r)throw new b("Active release ledger changed in another process")}let a=await Dw(i,"wx",384);try{await a.writeFile(s,"utf-8"),await a.sync()}finally{await a.close()}if(n)await Mw(i,e);else{try{await Lw(i,e)}catch(c){if(re(c,"EEXIST"))throw new b(`Cannot create release ledger: active ledger already exists at ${e}`);throw c}await jw(i)}await me(lr(e))}catch(a){await Jo(i,a,`Failed to clean temporary ledger file at ${i}`)}finally{await yn(o)}}async function Jo(e,t,n){try{await Nw(e,{force:!0})}catch(r){throw AggregateError([t,r],n)}throw t}async function bn(e){let t;try{t=await up(e)}catch(n){throw new b(`Failed to read release artifact at ${e}: ${j(n)}`)}return`sha512-${lp("sha512").update(t).digest("base64")}`}async function Ct(e,t){let n;try{n=await dr(e)}catch(r){throw new b(`Invalid ${t} at ${e}: ${j(r)}`)}if(!n.isDirectory()||n.isSymbolicLink())throw new b(`Invalid ${t} at ${e}: expected a real directory`)}async function Bw(e,t){let n;try{n=await dr(e)}catch(r){throw new b(`Invalid ${t} at ${e}: ${j(r)}`)}if(!n.isFile()||n.isSymbolicLink())throw new b(`Invalid ${t} at ${e}: expected a regular file`)}async function Gt(e){try{return await dr(e),!0}catch(t){if(re(t,"ENOENT"))return!1;throw t}}function gr(e,t){return je(e.artifactsRoot,or(t,"id"))}function zo(e,t,n){let r=`${lp("sha256").update(n).digest("hex")}.tgz`;return je(gr(e,t),r)}function Vs(e,t,n){return pp(e.releaseDirectory,zo(e,t,n)).split(Fw).join("/")}function Ko(e,t){let n=je(e.historyDirectory,`${or(t,"id")}.json`);if(lr(n)!==je(e.historyDirectory))throw new b(`Invalid release history path for ID ${t}`);return n}function pr(e,t,n){let r=pp(e,t);if(!r||de(r))throw new b(n)}import{isAbsolute as hp,relative as Uw,resolve as Gw}from"path";function Qo(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 yp(e){return e.map((t,n)=>{let r=`create.packages[${n}]`,s=t.oldVersion??t.version;if(t.oldVersion!==void 0&&t.version!==void 0&&t.oldVersion!==t.version)v(r,"oldVersion and version must match when both are provided");return bp({file:t.file,isPrivate:t.isPrivate,name:t.name,newVersion:t.newVersion,oldVersion:s},r)})}function wp(e){return e.map((t,n)=>{let r=typeof t==="object"&&t!==null&&"toJson"in t&&typeof t.toJson==="function"?t.toJson():t,s;try{s=JSON.parse(JSON.stringify(r))}catch(i){throw new b(`Invalid release ledger at create.stones[${n}]: ${j(i)}`)}return Rp(s,`create.stones[${n}]`)})}function Vt(e,t){let n=ie(e,"root");if(Te(n,["schemaVersion","id","baseCommit","createdAt","updatedAt","phase","options","packages","releaseTags","tagsReady","stones","artifacts","operations"],["expectedReleaseTree","releaseCommit"],"root"),n.schemaVersion!==sr)v("schemaVersion",`unsupported schema version ${String(n.schemaVersion)}`);let r=or(n.id,"id"),s=Rn(n.baseCommit,"baseCommit"),i=Hs(n.createdAt,"createdAt"),o=Hs(n.updatedAt,"updatedAt");if(Date.parse(o)<Date.parse(i))v("updatedAt","must not precede createdAt");let a=$p(n.phase,hn,"phase","release phase"),c=Hw(n.options,"options"),l=qw(n.packages,t.repositoryRoot),p=Vw(n.releaseTags,l,c),m=kt(n.tagsReady,"tagsReady");if(!c.tags&&!m)v("tagsReady","must be true when tags are disabled");let g=Ww(n.stones),h=n.expectedReleaseTree===void 0?void 0:Rn(n.expectedReleaseTree,"expectedReleaseTree"),f=n.releaseCommit===void 0?void 0:Rn(n.releaseCommit,"releaseCommit"),y=zw(n.artifacts,l,t,r),R=Kw(n.operations,l,c,i,o),S={artifacts:y,baseCommit:s,createdAt:i,id:r,operations:R,options:c,packages:l,phase:a,releaseTags:p,schemaVersion:sr,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)v("tagsReady","cannot be true before releaseCommit is recorded");if(a==="completed")na(S);return S}function Vw(e,t,n){if(!Array.isArray(e))v("releaseTags","must be an array");let r=e.map((i,o)=>{let a=A(i,`releaseTags[${o}]`);return Zo(`refs/tags/${a}`,`releaseTags[${o}]`),a});if(new Set(r).size!==r.length)v("releaseTags","must not contain duplicates");let s=n.tags?t.map((i)=>`${i.name}@${i.newVersion}`).sort():[];if(JSON.stringify([...r].sort())!==JSON.stringify(s))v("releaseTags","must exactly match the release package versions when tags are enabled");return r}function Hw(e,t){let n=ie(e,t);return Te(n,["changelog","createRelease","dryRun","npm","npmTag","publishOnly","push","tags"],[],t),{changelog:kt(n.changelog,`${t}.changelog`),createRelease:kt(n.createRelease,`${t}.createRelease`),dryRun:ra(n.dryRun),npm:kt(n.npm,`${t}.npm`),npmTag:A(n.npmTag,`${t}.npmTag`),publishOnly:kt(n.publishOnly,`${t}.publishOnly`),push:kt(n.push,`${t}.push`),tags:kt(n.tags,`${t}.tags`)}}function qw(e,t){if(!Array.isArray(e)||e.length===0)v("packages","must be a nonempty array");let n=new Set,r=new Set;return e.map((s,i)=>{let o=`packages[${i}]`,a=bp(s,o);if(hp(a.file))v(`${o}.file`,"must be repository-relative");if(n.has(a.name))v(o,`duplicate package name ${a.name}`);let c=Gw(t,a.file),l=Uw(t,c);if(!l||de(l))v(`${o}.file`,"must resolve inside the repository");if(r.has(c))v(o,`duplicate package file ${a.file}`);return n.add(a.name),r.add(c),a})}function bp(e,t){let n=ie(e,t);Te(n,["name","file","oldVersion","newVersion","isPrivate"],[],t);let r=A(n.file,`${t}.file`);if(r.includes("\x00"))v(`${t}.file`,"must not contain a null byte");return{file:r,isPrivate:kt(n.isPrivate,`${t}.isPrivate`),name:A(n.name,`${t}.name`),newVersion:A(n.newVersion,`${t}.newVersion`),oldVersion:A(n.oldVersion,`${t}.oldVersion`)}}function Ww(e){if(!Array.isArray(e))v("stones","must be an array");let t=new Set;return e.map((n,r)=>{let s=Rp(n,`stones[${r}]`);if(t.has(s.id))v(`stones[${r}].id`,`duplicate stone ID ${s.id}`);return t.add(s.id),s})}function Rp(e,t){let n=ie(e,t);Te(n,["id","message"],["tag","description","commits","major","minor","patch","dependency","snapshot"],t);let r={id:A(n.id,`${t}.id`),message:A(n.message,`${t}.message`)};if(n.tag!==void 0)r.tag=A(n.tag,`${t}.tag`);if(n.description!==void 0)r.description=ir(n.description,`${t}.description`);if(n.commits!==void 0)r.commits=Jw(n.commits,`${t}.commits`);for(let s of["major","minor","patch","dependency","snapshot"])if(n[s]!==void 0)r[s]=vp(n[s],`${t}.${s}`);return r}function Jw(e,t){if(!Array.isArray(e))v(t,"must be an array");return e.map((n,r)=>{let s=`${t}[${r}]`,i=ie(n,s);return Te(i,["hash","subject","type","message","packages"],["body","scope"],s),{...{hash:A(i.hash,`${s}.hash`),message:A(i.message,`${s}.message`),packages:vp(i.packages,`${s}.packages`),subject:A(i.subject,`${s}.subject`),type:A(i.type,`${s}.type`)},...i.body===void 0?{}:{body:ir(i.body,`${s}.body`)},...i.scope===void 0?{}:{scope:A(i.scope,`${s}.scope`)}}})}function zw(e,t,n,r){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)v(`artifacts.${a}`,"references an unknown package");if(l.isPrivate)v(`artifacts.${a}`,"private packages cannot have artifacts");let p=`artifacts.${a}`,m=ie(c,p);Te(m,["path","integrity"],[],p);let g=A(m.path,`${p}.path`);if(hp(g))v(`${p}.path`,"must be relative to the release directory");let h=Vs(n,r,a);if(g!==h)v(`${p}.path`,`must be ${h}`);let f=A(m.integrity,`${p}.integrity`);if(!Xu.test(f))v(`${p}.integrity`,"must be a sha512 SRI value");Fe(o,a,{integrity:f,path:g})}return o}function Kw(e,t,n,r,s){let i=ie(e,"operations");Te(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)v(`operations.npm.${y}`,"references an unknown package");if(S.isPrivate)v(`operations.npm.${y}`,"private packages cannot have npm operations");if(!n.npm)v(`operations.npm.${y}`,"npm is disabled");let k=Xo(R,`operations.npm.${y}`);Yo(k,r,s,`operations.npm.${y}`),Fe(c,y,k)}let l=n.npm?t.filter((y)=>!y.isPrivate).map((y)=>y.name):[];for(let y of l)if(!c[y])v("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])v(`operations.npmRegistries.${y}`,"references an unknown npm operation");Fe(m,y,sa(R,`operations.npmRegistries.${y}`))}let g;if(i.push!==void 0){if(!n.push&&!n.tags)v("operations.push","push and tags are disabled");let y=ie(i.push,"operations.push");Te(y,["destination","remote","refs","state"],["startedAt","completedAt"],"operations.push");let R=ea(y,"operations.push"),S=Xo(y,"operations.push",["destination","remote","refs"]);Yo(S,r,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))v(`operations.providerReleases.${y}`,"references an unknown package");if(!n.createRelease)v(`operations.providerReleases.${y}`,"createRelease is disabled");let S=`operations.providerReleases.${y}`,k=ie(R,S);Te(k,["tag","title","notes","state"],["startedAt","completedAt"],S);let ee=ta(k,S),V=Xo(k,S,["tag","title","notes"]);Yo(V,r,s,S),Fe(f,y,{...ee,...V})}return{npm:c,npmRegistries:m,providerReleases:f,...g?{push:g}:{}}}function Xo(e,t,n=[]){let r=ie(e,t);Te(r,["state",...n],["startedAt","completedAt"],t);let s=$p(r.state,Bo,`${t}.state`,"operation state");if(s==="pending"){if(r.startedAt!==void 0||r.completedAt!==void 0)v(t,"pending operations cannot have timestamps");return{state:s}}let i=Hs(r.startedAt,`${t}.startedAt`);if(s==="started"){if(r.completedAt!==void 0)v(t,"started operations cannot have completedAt");return{startedAt:i,state:s}}let o=Hs(r.completedAt,`${t}.completedAt`);if(Date.parse(o)<Date.parse(i))v(t,"completedAt must not precede startedAt");return{completedAt:o,startedAt:i,state:s}}function ea(e,t){let n=ie(e,t),r=Xw(n.destination,`${t}.destination`),s=A(n.remote,`${t}.remote`);if(!Yu.test(s)||s.includes("..")||s.includes("//"))v(`${t}.remote`,"must be a git remote name, not a URL or credential-bearing value");if(!Array.isArray(n.refs)||n.refs.length===0)v(`${t}.refs`,"must be a nonempty array");let i=new Set,o=new Set,a=n.refs.map((c,l)=>{let p=`${t}.refs[${l}]`,m=ie(c,p);Te(m,["source","destination","oid"],[],p);let g=Zo(m.source,`${p}.source`),h=Zo(m.destination,`${p}.destination`),f=A(m.oid,`${p}.oid`);if(!Bt.test(f))v(`${p}.oid`,"must be a full 40- or 64-character git object ID");if(i.has(g))v(`${p}.source`,`duplicate source ref ${g}`);if(o.has(h))v(`${p}.destination`,`duplicate destination ref ${h}`);return i.add(g),o.add(h),{destination:h,oid:f,source:g}});return{destination:r,refs:a,remote:s}}function Xw(e,t){let n=ie(e,t);Te(n,["canonicalUrl"],["owner","provider","repo"],t);let r=A(n.canonicalUrl,`${t}.canonicalUrl`),s;try{s=new URL(r)}catch{v(`${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)v(`${t}.canonicalUrl`,"must not contain credentials, query parameters, or fragments");let o=[n.provider,n.owner,n.repo];if(o.every((c)=>c===void 0))return{canonicalUrl:r};if(o.some((c)=>c===void 0))v(t,"provider, owner, and repo must be set together");let a=A(n.provider,`${t}.provider`);if(a!=="github"&&a!=="gitlab"&&a!=="bitbucket")v(`${t}.provider`,"must be github, gitlab, or bitbucket");return{canonicalUrl:r,owner:A(n.owner,`${t}.owner`),provider:a,repo:A(n.repo,`${t}.repo`)}}function ta(e,t){let n=ie(e,t);return{notes:ir(n.notes,`${t}.notes`),tag:A(n.tag,`${t}.tag`),title:A(n.title,`${t}.title`)}}function qs(e,t,n){if(!Yw(t))throw new b(`Unknown release operation state ${String(t)}`);if(e.state===t)return e;if(e.state==="pending"&&t==="started")return{startedAt:n,state:t};if(e.state==="started"&&t==="completed")return{completedAt:n,startedAt:e.startedAt,state:t};throw new b(`Invalid release operation transition from ${e.state} to ${t}`)}function na(e){if(!e.tagsReady)throw new b(`Cannot complete release ${e.id}: local release tags are not ready`);for(let[t,n]of Object.entries(e.operations.npm)){if(n.state!=="completed")throw new b(`Cannot complete release ${e.id}: npm operation for ${t} is ${n.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 n=e.operations.providerReleases[t.name];if(!n)throw new b(`Cannot complete release ${e.id}: provider release for ${t.name} is not configured`);if(n.state!=="completed")throw new b(`Cannot complete release ${e.id}: provider release for ${t.name} is ${n.state}`)}}function ra(e){if(e!==!1)v("options.dryRun","durable ledgers require dryRun to be false");return!1}function sa(e,t){let n=A(e,t),r;try{r=new URL(n)}catch{v(t,"must be an absolute HTTP or HTTPS URL")}if(r.protocol!=="http:"&&r.protocol!=="https:"||r.username||r.password||r.search||r.hash)v(t,"must be a credential-free HTTP or HTTPS URL");return r.href}function Yo(e,t,n,r){if(e.state==="pending")return;let s=Date.parse(e.startedAt);if(s<Date.parse(t)||s>Date.parse(n))v(`${r}.startedAt`,"must be between createdAt and updatedAt");if(e.state==="completed"){let i=Date.parse(e.completedAt);if(i<s||i>Date.parse(n))v(`${r}.completedAt`,"must be between startedAt and updatedAt")}}function Zo(e,t){let n=A(e,t);if(!n.startsWith("refs/")||n.includes("..")||n.includes("//")||/[\s~^:?*[\\]/.test(n))v(t,"must be an exact full git ref");return n}function $p(e,t,n,r){if(typeof e!=="string"||!t.includes(e))v(n,`unknown ${r} ${String(e)}`);return e}function Pp(e){return hn.includes(e)}function Yw(e){return Bo.includes(e)}function ie(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))v(t,"must be an object");return e}function Te(e,t,n,r){let s=new Set([...t,...n]);for(let i of t)if(!Object.hasOwn(e,i))v(r,`missing required key ${i}`);for(let i of Object.keys(e))if(!s.has(i))v(r,`unknown key ${i}`)}function kt(e,t){if(typeof e!=="boolean")v(t,"must be a boolean");return e}function Hs(e,t){let n=A(e,t);if(!Ds(n))v(t,"must be a canonical ISO timestamp");return n}function Rn(e,t){let n=A(e,t);if(!Bt.test(n))v(t,"must be a full 40- or 64-character git object ID");return n}function vp(e,t){if(!Array.isArray(e))v(t,"must be an array");return e.map((n,r)=>A(n,`${t}[${r}]`))}function ia(e){return new Date(Math.max(Date.now(),Date.parse(e)+1)).toISOString()}function ot(){return Object.create(null)}function Fe(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,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=gr(t,e.id),this.activePath=t.activePath}static async create(e,t=process.cwd()){let n=await qo(t);if(await Gt(n.activePath))throw new b(`Cannot create release ledger: active ledger already exists at ${n.activePath}`);if(await Gt(n.removingPath))throw new b(`Cannot create release ledger: an interrupted removal left ${n.removingPath}; delete it and its artifacts directory to finish cleanup`);let r=new Date().toISOString(),s=await Bun.$`git rev-parse HEAD`.cwd(n.repositoryRoot).quiet().nothrow(),i=s.stdout.toString().trim();if(s.exitCode!==0||!Bt.test(i))throw new b("Cannot create release ledger: failed to resolve the current commit");let o=e.options.publishOnly?await dp(n.repositoryRoot,i):void 0,a=yp(e.packages),c=wp(e.stones),l=Zw("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)Fe(p,y.name,{state:"pending"})}let g={artifacts:ot(),baseCommit:i,createdAt:r,id:l,operations:{npm:p,npmRegistries:ot(),providerReleases:ot()},options:{changelog:e.options.changelog,createRelease:e.options.createRelease,dryRun:ra(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:sr,stones:c,tagsReady:!e.options.tags,updatedAt:r};if(o)g.expectedReleaseTree=o;let h=Vt(g,n);if(await Gs(h,n),await mr(n,l),await Gt(n.activePath))throw new b(`Cannot create release ledger: active ledger already exists at ${n.activePath}`);let f=Ko(n,l);if(await Gt(f))throw new b(`Release ${l} is already completed at ${f}`);return await Wo(n.activePath,h,!1),new ge(h,n)}static async loadActive(e=process.cwd(),t={}){let n=await qo(e),r;try{r=await Sp(n.activePath)}catch(a){if(re(a,"ENOENT")){if(await Gt(n.removingPath))throw new b(`Release cleanup is incomplete: an interrupted removal left ${n.removingPath}; delete it and its artifacts directory to finish cleanup`);return null}throw new b(`Failed to inspect active release ledger at ${n.activePath}: ${j(a)}`)}if(!r.isFile()||r.isSymbolicLink())throw new b(`Invalid active release ledger at ${n.activePath}: expected a regular file`);let s;try{s=await oa(n.activePath,"utf-8")}catch(a){if(re(a,"ENOENT"))return null;throw new b(`Failed to read active release ledger at ${n.activePath}: ${j(a)}`)}let i;try{i=JSON.parse(s)}catch(a){throw new b(`Failed to parse active release ledger at ${n.activePath}: ${j(a)}`)}let o=Vt(i,n);if(t.verifyFiles===!1)return new ge(o,n);return await Gs(o,n),await mr(n,o.id),await fp(o,n),new ge(o,n)}get data(){return Vt(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(!Pp(e))throw new b(`Cannot set release phase: unknown phase ${String(e)}`);if(e===this.value.phase)return;let t=hn.indexOf(this.value.phase);if(hn.indexOf(e)<t)throw new b(`Cannot move release phase backwards from ${this.value.phase} to ${e}`);let r=structuredClone(this.value);r.phase=e,await this.persist(r)}async setReleaseCommit(e){this.assertActive("set release commit");let t=Rn(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 n=structuredClone(this.value);n.releaseCommit=t,await this.persist(n)}async setExpectedReleaseTree(e){this.assertActive("set expected release tree");let t=Rn(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 n=structuredClone(this.value);n.expectedReleaseTree=t,await this.persist(n)}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 r=this.value.operations.npm[e];if(!r)throw new b(`Cannot store an artifact for unconfigured npm package ${e}`);if(r.state!=="pending")throw new b(`Cannot replace artifact for ${e} after its npm operation has started`);if(ib(t)!==".tgz")throw new b(`Cannot store artifact for ${e}: source must be a .tgz file`);let s;try{s=await rb(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 mr(this.paths,this.value.id);let i=zo(this.paths,this.value.id,e),o=ob(this.artifactsDirectory,`.${Qw()}.tgz.tmp`),a;try{await tb(t,o,eb.COPYFILE_EXCL),await me(o),await wn(this.paths,this.value.id,o),a=await bn(o);try{await nb(o,i)}catch(p){if(!re(p,"EEXIST"))throw p;if(await wn(this.paths,this.value.id,i),await bn(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 kp(o,{force:!0}),await me(this.artifactsDirectory),await wn(this.paths,this.value.id,i)}catch(p){await Jo(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 Fe(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 Us(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 xp(this.releaseDirectory,t.path)}async configurePush(e,t,n){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 r=ea({destination:t,refs:n,remote:e},"configurePush"),s=this.value.operations.push;if(s){if(JSON.stringify([s.remote,s.destination,s.refs])===JSON.stringify([r.remote,r.destination,r.refs]))return;throw new b("Cannot replace an existing push configuration")}let i=structuredClone(this.value);i.operations.push={...r,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 n=ta(t,`providerReleases.${e}`),r=this.value.operations.providerReleases[e];if(r){if(r.tag===n.tag&&r.title===n.title&&r.notes===n.notes)return;throw new b(`Cannot replace provider release configuration for ${e}`)}let s=structuredClone(this.value);Fe(s.operations.providerReleases,e,{...n,state:"pending"}),await this.persist(s)}async markNpm(e,t){this.assertActive("mark npm operation");let n=this.value.operations.npm[e];if(!n)throw new b(`Npm operation is not configured for package ${e}`);if(n.state===t)return;if(t==="started"&&!this.value.artifacts[e])throw new b(`Cannot start npm operation for ${e} without a durable artifact`);let r=structuredClone(this.value);Fe(r.operations.npm,e,qs(n,t,this.operationTimestamp())),await this.persist(r)}async setNpmRegistry(e,t){this.assertActive("set npm registry");let n=this.value.operations.npm[e];if(!n)throw new b(`Npm operation is not configured for package ${e}`);if(n.state!=="pending")throw new b(`Cannot change npm registry for ${e} after publication has started`);let r=sa(t,`operations.npmRegistries.${e}`),s=this.value.operations.npmRegistries[e];if(s===r)return;if(s)throw new b(`Cannot replace npm registry for ${e}`);let i=structuredClone(this.value);Fe(i.operations.npmRegistries,e,r),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 n=structuredClone(this.value);n.operations.push={destination:t.destination,refs:t.refs,remote:t.remote,...qs(t,e,this.operationTimestamp())},await this.persist(n)}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 n=this.value.operations.providerReleases[e];if(!n)throw new b(`Provider release is not configured for package ${e}`);if(n.state===t)return;let r=structuredClone(this.value);Fe(r.operations.providerReleases,e,{notes:n.notes,tag:n.tag,title:n.title,...qs(n,t,this.operationTimestamp())}),await this.persist(r)}hasExternalProgress(){return Qo(this.value)}async complete(){if(this.assertActive("complete"),this.value.phase!=="completed"){let n=structuredClone(this.value);na(n),n.phase="completed",await this.persist(n)}let e=Ko(this.paths,this.value.id),t=await cr(this.releaseDirectory);try{let n=await Sp(this.activePath);if(!n.isFile()||n.isSymbolicLink())throw new b(`Invalid active release ledger at ${this.activePath}: expected a regular file`);let r=Vt(JSON.parse(await oa(this.activePath,"utf-8")),this.paths);if(r.id!==this.value.id||r.updatedAt!==this.value.updatedAt||r.phase!=="completed")throw new b("Active release ledger changed in another process");if(await gp(this.paths),await Gt(e))throw new b(`Cannot complete release ${r.id}: history ledger already exists at ${e}`);await Cp(this.activePath,e),await me(this.paths.historyDirectory),await me(this.releaseDirectory)}catch(n){if(n instanceof b)throw n;throw new b(`Failed to move completed release ${this.value.id} to history: ${j(n)}`)}finally{await yn(t)}return this.active=!1,e}async remove(){this.assertActive("remove");let e=await cr(this.releaseDirectory);try{await mr(this.paths,this.value.id);let t=Vt(JSON.parse(await oa(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(Qo(t))throw new b(`Cannot remove release ${t.id}: an external operation has started`);await Cp(this.activePath,this.paths.removingPath),await me(this.releaseDirectory),await kp(this.artifactsDirectory,{force:!0,recursive:!0}),await sb(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 yn(e)}this.active=!1}async persist(e,t){e.updatedAt=ia(this.value.updatedAt);let n=Vt(e,this.paths);await Gs(n,this.paths);for(let[r,s]of Object.entries(n.artifacts)){let i=this.value.artifacts[r];if(i?.integrity===s.integrity&&i.path===s.path)continue;if(r===t){await wn(this.paths,n.id,xp(this.releaseDirectory,s.path));continue}await Us(this.paths,n.id,r,s)}await Wo(this.activePath,n,!0,this.value.updatedAt),this.value=n}getPackage(e){let t=this.value.packages.find((n)=>n.name===e);if(!t)throw new b(`Unknown release package ${e}`);return t}operationTimestamp(){return ia(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 hb,rm as yb}from"fs/promises";import{tmpdir as wb}from"os";import{join as Lp}from"path";import{createHash as cb}from"crypto";import{lstat as lb,realpath as Ep}from"fs/promises";import{dirname as ub,isAbsolute as pb,relative as Tp,resolve as aa,sep as db}from"path";async function C(e,t){try{return await e()}catch(n){let r=Ws(n),s=r?`${t}: ${r}`:t;if(n instanceof u)throw new u(s,n.hint,n.exitCode,{cause:n,tag:n._tag});throw Error(s,{cause:n})}}function Ws(e){let t=ab(e);if(t)return t;return e instanceof Error?e.message:String(e)}function ab(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 mb=3,gb=/^[RC]|^.[RC]/;function Xe(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 Js(){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 $n(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 ca(e){let t=e.map((o)=>Xe(o)),[n,r,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=cb("sha256");for(let o of[n.stdout,r.stdout,s.stdout])i.update(String(o.length)),i.update("\x00"),i.update(o);return i.digest("hex")}function Ip(e,t){let n=pb(t)?aa(t):aa(e,t),r=Tp(e,n);if(!r||de(r))throw new u(`Release-owned path is outside the repository: ${t}`);return r.split(db).join("/")}async function Ap(e,t){let n=await Ep(t);for(let r of e){let s=aa(t,r),i=await lb(s).catch(()=>null);if(i?.isSymbolicLink())throw new u(`Release-owned path is a symbolic link: ${r}`);let o=i?s:ub(s),a=await Ep(o);if(de(Tp(n,a)))throw new u(`Release-owned path escapes the repository: ${r}`)}}async function zs(e){let t=e.map((n)=>Xe(n));await C(()=>Bun.$`git reset --quiet HEAD -- ${t}`.quiet(),"Failed to unstage release-owned files")}async function Ht(e){if((await la(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 la(e){return await rr(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 Op(e,t){let n=t.map((s)=>`:(exclude,top,literal)${s}`),r=await C(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all --ignore-submodules=none -- ${":/"} ${n}`.cwd(e).quiet(),"Failed to inspect release source files");return fb(r.stdout)}function fb(e){let t=e.toString().split("\x00").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let s=t[r]??"";if(n.push(s.slice(mb)),gb.test(s))r+=1}return n}async function _p(e,t,n,r){let s=[];if(e)s.push(`update ${e.ref??"HEAD"} ${e.baseCommit} ${e.oid}`);for(let a of t){let c=n.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 r(),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 Dp(e,t,n){let r=await hb(Lp(wb(),"sisyphus-index-")),s=Lp(r,"index"),i={...process.env,GIT_INDEX_FILE:s},o=t.map((a)=>Xe(a));try{await C(()=>Bun.$`git read-tree ${e}`.cwd(n).env(i).quiet(),"Failed to initialize release tree"),await C(()=>Bun.$`git add -A -- ${o}`.cwd(n).env(i).quiet(),"Failed to build release tree");let c=(await C(()=>Bun.$`git write-tree`.cwd(n).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 yb(r,{force:!0,recursive:!0})}}async function Mp(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 Be(e,t)}async function Np(e){let{baseCommit:t,releaseCommit:n}=e;if(!n||n===t)return;if(await Q()!==t)return;if(!await bb(n)||!await Rb())return;await Be(e,n),await C(()=>Bun.$`git checkout --quiet --detach ${n}`.quiet(),`Failed to check out release commit ${n} from base commit ${t}`)}async function bb(e){return(await Bun.$`git cat-file -e ${`${e}^{commit}`}`.quiet().nothrow()).exitCode===0}async function Rb(){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 Be(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 ua(t,e.baseCommit,e.id);await pa(t,e.expectedReleaseTree,e.id)}async function ua(e,t,n){let r=await C(()=>Bun.$`git rev-list --parents -n 1 ${e}`.quiet(),"Failed to resolve release commit parent"),[s,...i]=r.stdout.toString().trim().split(/\s+/);if(s===e&&i.length===1&&i[0]===t)return;let o=n?` for release ${n}`:"";throw new u(`Release commit parent${o} does not match ${t}`,"No external operation was attempted; inspect the release commit ancestry")}async function pa(e,t,n){let r=await da(e);if(r===t)return;let s=n?` for release ${n}`:"";throw new u(`Release commit tree${s} is ${r}, expected ${t}`,"No external operation was attempted; inspect the release commit for unrelated tracked changes")}async function da(e){let t=`${e}^{tree}`,r=(await C(()=>Bun.$`git rev-parse ${t}`.quiet(),"Failed to resolve release commit tree")).stdout.toString().trim();if(!r)throw Error(`Git returned an empty tree object ID for ${e}`);return r}import{basename as $b}from"path";var Pb="-o BatchMode=yes",vb="ssh",jp="ssh",Fp="auto",Sb=/\.exe$/i,Cb="core.sshcommand",kb="ssh.variant",xb="^(core\\.sshcommand|ssh\\.variant)$",Eb=new Set(["","0","false"]);function Tb(e=process.env){let t=e.CI?.trim().toLowerCase();return t!==void 0&&!Eb.has(t)}function Ks(e,t){return Le(e)&&!t&&!Tb()}async function Ib(e,t,n=process.env){let r=Bp(n);if(e)return r;let s=await Ab(n,t);return{...r,GCM_INTERACTIVE:"never",GIT_TERMINAL_PROMPT:"0",...s?{GIT_SSH_COMMAND:s}:{}}}async function xt(e,t,n){let r=await Ib(t.interactive,t.cwd);return C(()=>{let s=Bun.$`git ${e}`.env(r).quiet();return t.cwd?s.cwd(t.cwd):s},n)}async function Ab(e,t){let n=await _b(e,t),r=e.GIT_SSH_COMMAND?.trim()||n.command;if(!r&&e.GIT_SSH)return;let s=r||vb,i=e.GIT_SSH_VARIANT?.trim().toLowerCase()||n.variant||Fp;return Ob(s,i)?`${s} ${Pb}`:void 0}function Ob(e,t){if(t===jp)return!0;if(t!==Fp)return!1;let[n=""]=e.split(/\s+/);return $b(n).replace(Sb,"").toLowerCase()===jp}async function _b(e,t){let n=Bun.$`git config --get-regexp ${xb}`.env(Bp(e)).quiet().nothrow(),r=await(t?n.cwd(t):n);if(r.exitCode!==0)return{};let s={};for(let i of r.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===Cb&&c)s.command=c;if(a===kb&&c)s.variant=c.toLowerCase()}return s}function Bp(e){return Object.fromEntries(Object.entries(e).filter((t)=>t[1]!==void 0))}import{resolve as Lb}from"path";import{pathToFileURL as Db}from"url";async function fr(e,t,n){let r=zn(e,n);return{canonicalUrl:await Up(e,t),...r?{owner:r.owner,provider:r.provider,repo:r.repo}:{}}}async function Up(e,t){let n=null;try{n=new URL(e)}catch{n=null}if(n){let s=n.protocol==="ssh:"||n.protocol==="git+ssh:";if(n.password||n.username&&!s)throw new u("Push URL contains embedded credentials","Configure git authentication outside the remote URL");return n.search="",n.hash="",n.href}let r=e.match(/^(?:([^@/\s]+)@)?([^:/\s]+):(.+)$/);if(r?.[2]&&r[3])return`ssh://${r[1]?`${r[1]}@`:""}${r[2].toLowerCase()}/${r[3].replace(/^\/+/,"")}`;return Db(Lb(await t(),e)).href}function qt(e,t){if(!e?.provider||!e.owner||!e.repo)return;let{owner:n,provider:r,repo:s}=e,i=zn(e.canonicalUrl,t);return i?.provider===r&&i.owner===n&&i.repo===s?i:{owner:n,provider:r,repo:s}}async function Pn(e){let n=(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(n.length!==1)throw new u(`Push remote ${e} must have exactly one push URL, found ${n.length}`,"Remove additional push URLs before starting or resuming a release");let[r]=n;if(!r)throw new u(`Push remote ${e} has no URL`);return r}async function vn(e,t){let n=await Pn(e.remote);if(await Up(n,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 n}async function ga(e){for(let t of e){let r=(await C(()=>Bun.$`git rev-parse ${t.source}`.quiet(),`Failed to resolve ${t.source}`)).stdout.toString().trim();if(r!==t.oid)throw new u(`Release ref ${t.source} points to ${r}, expected ${t.oid}`,"Do not move release refs before the release completes")}}async function Xs(e,t){let n=await vn(e,t.repositoryRoot),r=e.refs.map((s)=>`${s.oid}:${s.destination}`);await xt(["push","--atomic",n,...r],{interactive:t.interactive},"Failed to atomically push release refs")}async function Gp(e,t,n=e.refs){let r=await fa(e,n,t),s=n.find((i)=>r.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 fa(e,t,n){let r=await vn(e,n.repositoryRoot),s=t.map((o)=>o.destination),i=await xt(["ls-remote","--refs",r,...s],{interactive:n.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 hr(){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 Ys(){let e=await hr();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 yr(e)}}async function yr(e){let t=e?await ma(`branch.${e}.pushRemote`):null,n=await ma("remote.pushDefault"),r=e?await ma(`branch.${e}.remote`):null,s=t??n??r;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 ma(e){let t=await Bun.$`git config --get ${e}`.quiet().nothrow();if(t.exitCode===1)return null;if(t.exitCode!==0){let r=t.stderr.toString().trim();throw Error(r?`Failed to read git config ${e}: ${r}`:`Failed to read git config ${e}`)}let n=t.stdout.toString().trim();if(!n)throw Error(`Git config ${e} is empty`);return n}var Mb=1,ha="ReleasePushNotApplied",Nb=`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 Zs(e,t){let n=await fa(e,e.refs,t),r={diverged:[],landed:[],pending:[]};for(let s of e.refs){let i=n.get(s.destination);if(i===s.oid){r.landed.push(s);continue}if(!i){r.pending.push(s);continue}if(s.destination.startsWith("refs/heads/")){if(await Fb(i,e,t),await Vp(s.oid,i)){r.landed.push(s);continue}if(await Vp(i,s.oid)){r.pending.push(s);continue}}r.diverged.push(s)}return r}async function Hp(e,t,n){let r=await Zs(t,n);if(r.landed.length===0){if(await e.markPushNotApplied(),r.diverged.length>0)throw Wp(t,jb(r.diverged));return"not-applied"}let[s]=r.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(r.pending.length>0)await Xs({...t,refs:r.pending},n);return await e.markPush("completed"),"completed"}async function qp(e,t,n,r){let s;try{s=await Zs(t,n)}catch(i){return AggregateError([r,i],"The release push failed and the remote refs could not be inspected afterwards")}if(s.landed.length>0)return r;return await e.markPushNotApplied(),Wp(t,`Remote ${t.remote} rejected the release push`,r)}function Wp(e,t,n){return new u(`${t}; no release ref reached ${e.remote}`,Nb,1,{cause:n,tag:ha})}function jb(e){return`Remote refs diverged from the release: ${e.map((t)=>t.destination).join(", ")}`}async function Fb(e,t,n){if((await Bun.$`git cat-file -e ${`${e}^{commit}`}`.quiet().nothrow()).exitCode===0)return;let s=await vn(t,n.repositoryRoot);await xt(["fetch","--no-tags","--no-write-fetch-head","--no-recurse-submodules",s,e],{interactive:n.interactive},"Failed to inspect the remote branch ancestry")}async function Vp(e,t){let n=await Bun.$`git merge-base --is-ancestor ${e} ${t}`.quiet().nothrow();if(n.exitCode===0)return!0;if(n.exitCode===Mb)return!1;throw Error(`Failed to inspect remote branch ancestry: ${n.stderr.toString().trim()}`)}async function Jp(e){let t=await ge.loadActive(process.cwd(),{verifyFiles:!1});if(!t)throw new u("No incomplete release found","Nothing to abort");if(await Ub(t,{interactive:e.interactive,repositoryRoot:Wb}),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 n=t.data,r=[],s=await Vb(n),i=await Hb(n,s,r),o=await qb(n,s,r);return await t.remove(),{commitDiscarded:i,deletedTags:o,ledger:n,warnings:r}}async function Ub(e,t){let n=e.data,r=n.operations.push;if(r?.state!=="started"||Gb(n))return;let s;try{s=(await Zs(r,t)).landed.length}catch(i){throw new u(`Cannot confirm whether release ${n.id} reached ${r.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 Gb(e){return[...Object.values(e.operations.npm),...Object.values(e.operations.providerReleases)].some((n)=>n.state!=="pending")}async function Vb(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 Be(e,t),t}catch{return}}async function Hb(e,t,n){if(e.options.publishOnly)return!1;if(!t)return n.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 r=await Q();if(r!==t)return n.push(`Kept release commit ${t} because HEAD moved to ${r}; 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 qb(e,t,n){let r=[];for(let s of e.releaseTags){let i=`refs/tags/${s}`,o=await $n(i);if(!o)continue;if(o!==t){n.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}`),r.push(s)}return r}async function Wb(){let e=await C(()=>Bun.$`git rev-parse --show-toplevel`.quiet(),"Failed to resolve git repository root");return Bb(e.stdout.toString().trim())}import{readFile as Jb}from"fs/promises";import{dirname as zp}from"path";var zb=/^[A-Za-z][0-9A-Za-z._-]*$/,Kb=/-\d{14,}$/,Xb=/^(?:[vV]?\d+(?:\.(?:\d+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?|[xX])$/;function Kp(e){return zb.test(e)&&!Xb.test(e)}function ei(e){let t=(e||ye).trim();if(!Kp(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 Wt(e,t){let n=ei(t),r=new Set;for(let s of e){if(s.isPrivate)continue;let i=s.newVersion??s.version,o=Me(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){r.add(n);continue}let a=Yb(o);if(!a||!Kp(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)");r.add(a)}if(r.size<=1)return[...r][0]??n;throw new u(`Release mixes npm dist-tags (${[...r].sort().join(", ")})`,"Roll stable and prerelease packages separately, or give every prerelease the same tag")}function Yb(e){let t=Xn(e);if(t)return t;let[n]=e.prerelease;if(typeof n!=="string")return;return n.replace(Kb,"")}function Xp(e){return e.startsWith("@")?e.split("/")[0]:void 0}function Sn(e,t){let n=Xp(e);return n?[`--${n}:registry=${t}`]:[]}async function ti(e){let t=Xp(e.name);if(t){let o=await Bun.$`npm config get ${`${t}:registry`}`.cwd(zp(e.file)).quiet().nothrow();if(o.exitCode===0){let a=o.stdout.toString().trim();if(a&&a!=="undefined"&&a!=="null"){let c=Qs(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 r=(await Yp(e)).publishConfig;if(r!==void 0){if(typeof r!=="object"||r===null||Array.isArray(r))throw new u(`Invalid publishConfig in ${e.name}`,"publishConfig must be an object");let o=Reflect.get(r,"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=Qs(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=Qs(s);if(o)return o}let i=await Bun.$`npm config get registry`.cwd(zp(e.file)).quiet().nothrow();if(i.exitCode===0){let o=i.stdout.toString().trim();if(o&&o!=="undefined"&&o!=="null"){let a=Qs(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 Qs(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 wr(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 n=Reflect.get(t,"name"),r=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 n!=="string"||typeof r!=="string"||typeof i!=="string")return;return{integrity:i,name:n,version:r}}async function Yp(e){let t;try{t=await Jb(e.file,"utf-8")}catch(r){throw Error(`Failed to read ${e.name}: ${Ws(r)}`)}let n;try{n=JSON.parse(t)}catch(r){throw Error(`Failed to parse ${e.name}: ${Ws(r)}`)}if(typeof n!=="object"||n===null||Array.isArray(n))throw Error(`Invalid ${e.name} manifest object`);return n}async function br(e){let t=[];for(let n of e){let s=(await Yp(n)).private;if(s!==void 0&&typeof s!=="boolean")throw Error(`Failed to validate ${n.name} manifest: "private" must be a boolean`);if(s)continue;t.push(n)}return t}function ni(e){try{return JSON.parse(e)}catch{return}}function ri(e,t,n){let r=t.newVersion??t.version;return{notes:Qb(Zb(e,t.name),t,n),tag:`${t.name}@${r}`,title:`${t.name} v${r}`}}function Zb(e,t){return e.filter((n)=>n.affectsPackage(t))}function Qb(e,t,n){let r=[],s=t.newVersion??t.version;if(r.push(`\`${t.name}\` ${t.version} \u2192 ${s}`),e.length===0)return r.join(`
179
+ `);r.push(""),r.push("<details>"),r.push(`<summary>Stones (${e.length})</summary>`),r.push("");for(let i of e){if(r.push(`### ${i.message}`),r.push(""),i.description)r.push(i.description),r.push("");let o=eR(i.commits,t.name);if(o.length>0){r.push("<details>"),r.push(`<summary>Commits (${o.length})</summary>`),r.push("");for(let a of o)r.push(tR(a,n));r.push(""),r.push("</details>"),r.push("")}}return r.push("</details>"),r.join(`
180
+ `)}function eR(e,t){if(!e)return[];return e.filter((n)=>n.packages.includes(t))}function tR(e,t){return`- ${t?`[\`${e.hash}\`](${t(e.hash)})`:`\`${e.hash}\``} ${e.subject}`}import{realpath as yd}from"fs/promises";import{join as HR,resolve as qR}from"path";import{rm as yR}from"fs/promises";import{isAbsolute as wR,resolve as od}from"path";var Jt={isOutput:()=>!1};function Zp(e){if(e.length===0)return Jt;let t=e.flatMap((n)=>{let r=n.endsWith("/")?`${n}**`:n;if(r.endsWith("**"))return[new Bun.Glob(r)];return[new Bun.Glob(r),new Bun.Glob(`${r}/**`)]});return{isOutput:(n)=>t.some((r)=>r.match(n))}}import{cp as nR,mkdir as rR,mkdtemp as sR,rename as iR,rm as oR,writeFile as aR}from"fs/promises";import{tmpdir as cR}from"os";import{dirname as ed,join as Qp,relative as ba,resolve as Et,sep as lR}from"path";function ya(e){let t=JSON.parse(e),n=Array.isArray(t)?t:typeof t==="object"&&t!==null?Object.values(t):[],[r]=n;return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}var si=512,uR=100,pR=124,dR=12,mR=345,gR=155,fR="package/package.json",hR=20;async function td(e,t){let n=ed(t),r=await Bun.$`npm pack --ignore-scripts --json --pack-destination ${n}`.cwd(e).quiet(),s=ya(r.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=Et(n,s.filename);if(de(ba(n,i)))throw Error("npm pack returned an artifact outside the destination directory");if(i!==Et(t))await iR(i,t);return{name:s.name,version:s.version}}async function nd(e,t){let n=await Bun.$`npm pack --dry-run --ignore-scripts --json`.cwd(t).quiet(),r=ya(n.stdout.toString())?.files;if(!Array.isArray(r))throw Error(`npm pack did not return a file list for ${e.name}`);return r.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(ba(t,Et(t,i))))throw new u(`Package ${e.name} includes a file outside its directory: ${i}`);return i})}async function rd(e,t,n){let r=await nd(e,t),s=await sR(Qp(cR(),"sisyphus-package-stage-"));try{for(let i of r){let o=Et(s,i);await rR(ed(o),{recursive:!0}),await nR(Et(t,i),o,{errorOnExist:!0,force:!1,recursive:!1,verbatimSymlinks:!0})}return await aR(Qp(s,"package.json"),n,"utf-8"),s}catch(i){try{await oR(s,{force:!0,recursive:!0})}catch(o){throw AggregateError([i,o],"Failed to clean staged npm package")}throw i}}async function sd(e,t,n,r=Jt){let[s,i]=await Promise.all([nd(e,t),oi(n)]);for(let o of s){let a=ba(n,Et(t,o)).split(lR).join("/");if(!i.has(a)&&!r.isOutput(a))throw new u(`Package ${e.name} includes an untracked or ignored pre-build file: ${o}`)}}async function Ra(e,t){return(await Bun.$`git ls-files --others --ignored --exclude-standard -z`.cwd(e).quiet()).stdout.toString().split("\x00").filter(Boolean).filter((r)=>!r.split("/").includes("node_modules")).map((r)=>`${t}${r}`)}async function Rr(e,t,n=Jt){let[r,s]=await Promise.all([Ra(e,t),Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet()]),i=r.filter((o)=>!n.isOutput(o));if(i.length>0){let o=i.slice(0,hR),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):
181
181
  ${o.join(`
182
182
  `)}${a>0?`
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(`
183
+ ...and ${a} more`:""}`)}for(let{mode:o,path:a}of ii(s.stdout.toString()))if(o==="160000")await Rr(Et(e,a),`${t}${a}/`,n)}function ii(e){return e.split("\x00").filter(Boolean).map((t)=>{let n=t.indexOf("\t"),r=n<0?[]:t.slice(0,n).split(" "),[s,,i,...o]=r,a=n<0?"":t.slice(n+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 oi(e,t=""){let n=await Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet(),r=new Set;for(let{mode:s,stage:i,path:o}of ii(n.stdout.toString())){if(i!=="0")throw new u(`Repository has an unresolved index entry: ${o}`);let a=`${t}${o}`;if(r.add(a),s!=="160000")continue;let c=await oi(Et(e,o),`${a}/`);for(let l of c)r.add(l)}return r}async function $r(e){let t=new Uint8Array(await Bun.file(e).arrayBuffer()),n=Bun.gunzipSync(t),r=new TextDecoder;for(let s=0;s+si<=n.length;){let i=wa(n,s,uR,r);if(!i)break;let o=wa(n,s+mR,gR,r),a=o?`${o}/${i}`:i,c=wa(n,s+pR,dR,r).trim(),l=Number.parseInt(c,8);if(!Number.isSafeInteger(l)||l<0)throw Error(`Invalid tar entry size for ${a}`);let p=s+si,m=p+l;if(m>n.length)throw Error(`Truncated tar entry for ${a}`);if(a===fR)return r.decode(n.subarray(p,m));s=p+Math.ceil(l/si)*si}throw Error("Packed artifact does not contain package/package.json")}function wa(e,t,n,r){let s=e.subarray(t,t+n),i=s.indexOf(0);return r.decode(i<0?s:s.subarray(0,i))}function id(e,t){return JSON.stringify(fn(JSON.parse(e)))===JSON.stringify(fn(JSON.parse(t)))}var bR="160000",RR="./",$R=50;function cd(e){let t=e?.command??[...go],n=e?.root??[],r=e?.outputs??[];ai(t,"release.build.command"),ai(n,"release.build.root"),ai(r,"release.build.outputs"),ad(t,"release.build.command");for(let[s,i]of n.entries())if(ai(i,`release.build.root[${s}]`),ad(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 r)if(!s||wR(s)||s.startsWith(RR)||SR(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(r.length>0&&t.length===0&&n.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:Zp(r),outputs:r,root:n}}async function ci(e,t){if(t===Jt)return;let n=await oi(e);for(let r of n){if(!t.isOutput(r))continue;throw new u(`Declared build output ${r} is tracked by Git`,"Add it to .gitignore, or narrow release.build.outputs so it excludes committed files")}}async function $a(e,t,n){if(n===Jt)return 0;let r=0;for(let i of await Ra(e,t)){if(!n.isOutput(i))continue;await yR(od(e,i.slice(t.length)),{force:!0}),r+=1}let s=await Bun.$`git ls-files --stage -z --cached`.cwd(e).quiet();for(let{mode:i,path:o}of ii(s.stdout.toString())){if(i!==bR)continue;r+=await $a(od(e,o),`${t}${o}/`,n)}return r}async function Pa(e,t,n){let r=vR(e,t,n),s,i,o;try{[s,i,o]=await Promise.all([r.exited,new Response(r.stderr).text(),new Response(r.stdout).text()])}catch(a){throw r.kill(),a}if(s!==0){let a=PR([i.trim(),o.trim()].filter(Boolean).join(`
184
+ `),$R),c=`${e.join(" ")} exited with code ${s} in ${t}`;throw Error(`${n}: ${c}${a?`
185
+ ${a}`:""}`)}}function PR(e,t){return e.split(`
186
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(`
188
- `);return`${e.replace("{message}",()=>t.message).replace("{packages}",()=>r.map((i)=>i.name).join(", "))}
187
+ `)}function vR(e,t,n){try{return Bun.spawn([...e],{cwd:t,stderr:"pipe",stdout:"pipe"})}catch(r){throw Error(`${n}: ${r instanceof Error?r.message:String(r)}`)}}function ai(e,t){if(Array.isArray(e))return;throw new u(`Invalid ${t}`,`${t} must be an array`)}function SR(e){if(de(e))return!0;return e.split("/").includes("..")}function ad(e,t){for(let n of e){if(typeof n==="string"&&n.length>0)continue;throw new u(`Invalid ${t}`,"Every build command argument must be a non-empty string")}}import{dirname as GR,join as VR}from"path";var CR=3,kR=3,xR=3,ld=240,ER=-1,ud="\u2026",TR=/^@[^/]+\//;function md(e){return[...e].sort((t,n)=>Number(t.isPrivate)-Number(n.isPrivate)||pd(t)-pd(n))}function pd({bump:e}){return e===void 0?xe.length:xe.indexOf(e)}function va(e,t=CR){let n=md(e).map((i)=>`${i.name}@${i.newVersion??i.version}`),r=n.slice(0,t),s=n.length-r.length;return`${r.join(", ")}${s>0?` +${s} more`:""}`}function gd(e,t,n){return e.replace("{message}",()=>t).replace("{packages}",()=>n.map((r)=>r.name).join(", ")).replace("{versions}",()=>va(n))}function Pr(e,t,n){let r=new Set(t.map((a)=>a.name)),s=IR(e,r),i=AR(e,r),o=i.length>0?[{breaking:!1,changes:i,heading:n.other}]:[];return{groups:[...OR(s,n),...o],packages:md(t).map((a)=>MR(a,e,s,t))}}function IR(e,t){let n=new Map;for(let r of e.flatMap((s)=>s.commits??[])){let s=r.packages.filter((a)=>t.has(a));if(s.length===0)continue;let i=n.get(r.hash),o=new Set([...i?.packages??[],...s]);n.set(r.hash,{...i??r,packages:[...o]})}return[...n.values()]}function AR(e,t){return e.filter((n)=>(n.commits?.length??0)===0).flatMap((n)=>{let r=[...n.major,...n.minor,...n.patch].filter((s)=>t.has(s));return r.length===0?[]:[{message:n.message,notes:[],packages:r}]})}function OR(e,t){let n=new Map;for(let r of e){let s=yo(r),i=s?"breaking":r.type,o=s?t.breaking:_R(r.type,t),a=n.get(i)??{breaking:s,changes:[],heading:o};a.changes.push(LR(r,s)),n.set(i,a)}return[...n.entries()].sort(([r],[s])=>dd(r)-dd(s)).map(([,r])=>r)}function _R(e,t){return t[e]??`${e} changes`}function dd(e){return e==="breaking"?ER:gt[e]??ft}function LR(e,t){return{hash:e.hash,message:e.message,notes:t?ou(e.body).map(DR):[],packages:e.packages,scope:e.scope}}function DR(e){return e.length>ld?`${e.slice(0,ld-ud.length).trimEnd()}${ud}`:e}function MR(e,t,n,r){return{bump:e.bump,from:e.version,isPrivate:e.isPrivate,name:e.name,reason:NR(e,t,n,r),to:e.newVersion??e.version}}function NR(e,t,n,r){let s=n.filter((l)=>l.packages.includes(e.name)),i=t.filter((l)=>(l.commits?.length??0)===0&&[...l.major,...l.minor,...l.patch].includes(e.name)),o=s.length+i.length;if(o>0)return jR(o,s.filter((l)=>yo(l)).length);let a=new Set(r.map((l)=>l.name)),c=[...new Set(e.workspaceDependencies.map((l)=>l.name))].filter((l)=>a.has(l));return c.length===0?"dependency bump":FR(c)}function jR(e,t){let n=`${e} ${e===1?"change":"changes"}`;return t>0?`${n}, ${t} breaking`:n}function FR(e){let t=e.slice(0,kR),n=e.length-t.length;return`updated ${t.join(", ")}${n>0?` +${n} more`:""}`}function Sa({message:e,packages:t,scope:n}){if(n)return`${n}: ${e}`;let r=t.slice(0,xR).map(BR),s=t.length-r.length;return r.length===0?e:`${e} [${r.join(", ")}${s>0?` +${s}`:""}]`}function BR(e){return e.replace(TR,"")}function li(e){let t=e.packages.map((r)=>`- ${r.name}@${r.to}`).join(`
188
+ `),n=e.groups.map(UR);return[t,...n].join(`
189
+
190
+ `)}function UR(e){let t=e.changes.flatMap((n)=>[`- ${Sa(n)}`,...n.notes.map((r)=>` ${r}`)]);return[e.heading,...t].join(`
191
+ `)}function fd(e,t,n,r,s){let i=gd(e.message,n.message,s),o=Pr(r,s,t.sections);return`${i}
192
+
193
+ ${li(o)}`}function ui(e){let{author:t,email:n}=e,r=t.trim(),s=n?.trim()??"";if(!r&&!s)return[];if(!r||!/^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/.test(s))throw new u("Invalid release commit author","Set valid commit.author and commit.email");return["--author",`${r} <${s}>`]}function hd(e){let{author:t,email:n}=e,r={...process.env};if(!t)return r;if(r.GIT_COMMITTER_NAME=t,n)r.GIT_COMMITTER_EMAIL=n;return r}function pi(e,t){let{filename:n,root:r}=e,s=t.map((i)=>VR(GR(i.file),n));if(r)s.push(n);return s}var di={interactive:!1};function mi(e,t,n){return{changelogGenerator:un(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 er,provider:null,repositoryRoot:null,runtime:n,stoneManager:new B(e)}}async function J(e){if(e.repositoryRoot)return e.repositoryRoot;let n=(await C(()=>Bun.$`git rev-parse --show-toplevel`.quiet(),"Failed to resolve git repository root")).stdout.toString().trim();if(!n)throw Error("Git repository root is empty");return e.repositoryRoot=qR(n),e.repositoryRoot}function gi(e){return{interactive:e.runtime.interactive,repositoryRoot:()=>J(e)}}async function wd(e){let t=await J(e);if(await yd(process.cwd())===await yd(t))return;throw new u(`Releases must run from the Git repository root (${t})`,void 0,1,{tag:"NotRepositoryRoot"})}function Ie(e,t){if(!e.ledger)throw Error(`Cannot ${t} without an active release ledger`);return e.ledger}function Cn(e,t){e.irreversibleOperation??=t}function kn(e){return e.irreversibleOperation!==null||e.ledger?.hasExternalProgress()===!0}function zt(e){return e.npm.buildConfig??=cd(e.config.get("release")?.build),e.npm.buildConfig}function fi(e){return e.map((t)=>`${t.name}\x00${t.file}`).join("\x00")}async function vr(e,t,n){let r=await J(e),s=e.options.changelog?pi(e.config.get("changelog"),t):[],i=[...t.map((c)=>c.file),...s,HR(on,ms),...e.stoneManager.getFilePaths(n)],o=[...new Set(i.map((c)=>Ip(r,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 hi(e,t){if(t instanceof u&&t._tag===ha)return t;let n=e.irreversibleOperation??"an external release operation",r=new u(`Release incomplete after ${n} began`,"Local state preserved; run sis roll --resume to reconcile and continue.");return r.cause=t,r}async function Sr(e){if(e.ledger)await e.ledger.complete()}async function Ca(e){if(!e.provider){let t=e.ledger?.data.operations.push?.destination,n=e.config.get("provider");e.provider=await bt(qt(t,n),n)}return e.provider}async function ka(e){if(e.commitUrlFn!==null)return;let t=e.ledger?.data.operations.push?.destination,n=e.config.get("provider"),r=qt(t,n);if(r){e.commitUrlFn=Po(r);return}let s=await new Yn(n).getRemoteInfo();e.commitUrlFn=s?.commitUrl??null}async function yi(e,t,n){if(e.options.dryRun)return;if(n.length===0)return;await ka(e);let r=await Ca(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 Gp(s,gi(e),i)}for(let i of n){let o=ri(t,i,e.commitUrlFn),a=Me(i.newVersion??i.version);await WR(e,r,i.name,o,a!==null&&Ne(a))}}async function WR(e,t,n,r,s){let i=Ie(e,`create the provider release for ${r.tag}`),o=i.data.operations.providerReleases[n];if(!o)throw Error(`Provider release is not configured for ${n}`);if(o.state==="completed")return;if(o.state==="started"){await JR(e,t,n,o);return}await i.setPhase("external"),await i.markProviderRelease(n,"started"),Cn(e,`git provider release creation for ${r.tag}`),await C(()=>t.createRelease({...r,prerelease:s}),`Failed to create release for ${r.tag}`),await i.markProviderRelease(n,"completed")}async function JR(e,t,n,r){let s=await C(()=>t.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 e.ledger?.markProviderRelease(n,"completed")}function zR(e,t){let{options:n}=e;return n.npm||n.push||n.createRelease||t&&n.tags}async function bd(e,t,n,r){if(e.options.dryRun||!zR(e,r))return;e.ledger=await ge.create({options:{...e.options,npmTag:e.options.npm?Wt(t,e.config.get("tag")):ye,publishOnly:r},packages:t.map((s)=>({file:s.file,isPrivate:s.isPrivate,name:s.name,newVersion:s.newVersion,version:s.version})),stones:n})}async function Rd(e,t,n){let{ledger:r}=e;if(!r)return;if(e.options.npm||r.data.options.publishOnly)await Ht(await J(e));let s=await Q();await Pd(e,r.data,s),await Be(r.data,s),await r.setReleaseCommit(s),await xa(e,t,n)}async function $d(e,t){let{ledger:n}=e;if(t.releaseCommit||!n)return;let r=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 ${n.activePath} to abort the release`);if(!t.options.publishOnly&&r===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 ${n.activePath} to abort the release`);await Pd(e,t,r),await Be(n.data,r),await n.setReleaseCommit(r)}async function xa(e,t,n){let{ledger:r}=e;if(!r)return;let s=r.data;if(await KR(e,s),s.options.npm)for(let i of t){if(!s.operations.npm[i.name]||s.operations.npmRegistries[i.name])continue;await r.setNpmRegistry(i.name,await ti(i))}if(!s.operations.push&&(s.options.push||s.options.publishOnly&&s.options.tags))await XR(e,s);if(s.options.createRelease){await ka(e);for(let i of t)await r.configureProviderRelease(i.name,ri(n,i,e.commitUrlFn));await Ca(e)}}function wi(e,t){if(!e.options.createRelease||qt(t))return;throw new u("Push destination is not a supported git provider repository","Provider releases require GitHub, GitLab, or Bitbucket")}async function KR(e,t){if(!e.ledger||!t.options.tags)return;if(!t.releaseCommit)throw Error("Cannot reconcile release tags without a release commit");for(let n of t.releaseTags){let r=`refs/tags/${n}`,s=await Bun.$`git rev-parse --verify ${r}`.quiet().nothrow();if(s.exitCode!==0){await C(()=>Bun.$`git -c tag.gpgSign=false tag -- ${n} ${t.releaseCommit}`.quiet(),`Failed to create tag ${n}`);continue}let i=s.stdout.toString().trim();if(i!==t.releaseCommit)throw new u(`Release tag ${n} points to ${i}, expected ${t.releaseCommit}`,"Do not move release tags before the release completes")}if(!t.tagsReady)await e.ledger.markTagsReady()}async function XR(e,t){let{ledger:n}=e;if(!n||!t.releaseCommit)throw Error("Cannot configure release push without a recorded release commit");let r=t.releaseCommit,s=()=>J(e),i=e.config.get("provider"),o=t.releaseTags.map((g)=>({destination:`refs/tags/${g}`,oid:r,source:`refs/tags/${g}`}));if(t.options.publishOnly){let g=await yr(await hr()),h=await fr(await Pn(g),s,i);wi(e,h),await ga(o),await n.configurePush(g,h,o);return}let{branch:a,remote:c}=await Ys(),l=await fr(await Pn(c),s,i);wi(e,l);let p=`refs/heads/${a}`,m=[{destination:p,oid:r,source:p},...o];await ga(m),await n.configurePush(c,l,m)}async function Pd(e,t,n){if(t.expectedReleaseTree)return;if(!e.ledger||!t.options.publishOnly||n!==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 da(t.baseCommit))}function Ea(e){return`${e.name}@${e.newVersion??e.version}`}async function vd(e,t,n,r){if(e.options.dryRun)return;let s=e.config.get("commit"),i=await vr(e,n,r),o=i.map((f)=>Xe(f)),a=fd(s,e.config.get("changelog"),t,r,n),c=ui(s),l=e.ledger?.data.baseCommit??await Q(),p=await Js(),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 Dp(l,i,await J(e)),await e.ledger?.setExpectedReleaseTree(m),g=await ca(i),await C(()=>Bun.$`git commit --only ${c} -m ${a} -- ${o}`.env(hd(s)).quiet(),"Failed to create commit"),e.local.commitCreated=!0}catch(f){throw await YR(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 Be(e.ledger.data,h);return}await ua(h,l),await pa(h,m)}async function YR(e,t,n,r){if(n){let s;try{s=await ca(t)}catch(i){throw e.local.rollbackBlockedReason="release files could not be verified after commit failure",AggregateError([r,i],"Commit failed and release files could not be verified")}if(s!==n)throw e.local.rollbackBlockedReason="release-owned files changed while commit hooks ran",AggregateError([r],"Commit failed after a hook changed release-owned files")}try{await zs(t)}catch(s){throw AggregateError([r,s],"Commit and index cleanup failed")}}async function Sd(e,t){if(e.options.dryRun)return;let n=await Q();for(let r of t){let s=Ea(r);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,n)}}import{mkdtemp as r$,readFile as s$,rm as Id}from"fs/promises";import{tmpdir as i$}from"os";import{dirname as o$,join as Td}from"path";var Cd=tn().map((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)?e:K()),ZR=Cd.map(st({publishConfig:Cd.map(st({access:De(["public","restricted"]).or(qe())})).or(qe())}));function Cr(e){try{return ZR(JSON.parse(e)).publishConfig?.access??"public"}catch(t){throw Error("Invalid publishConfig.access: expected public or restricted",{cause:t})}}import{dirname as QR}from"path";var e$=/\bE404\b/,t$=/cannot publish over|EPUBLISHCONFLICT/i;function kd(e,t){let n=e.newVersion??e.version,r=`${e.name}@${n}`,s=Bun.$`npm view ${r} --json --registry ${t} ${Sn(e.name,t)}`.cwd(QR(e.file)).quiet().nothrow();return{packageSpec:r,version:n,view:s}}async function xd(e,t,n){let{packageSpec:r,version:s,view:i}=kd(e,t),o=await i;if(o.exitCode!==0)return;let a=wr(ni(o.stdout.toString()));if(a?.version!==s||a.name!==e.name||a.integrity===n)return;throw new u(`${r} is already published on ${t} with a different artifact`)}async function Ed(e,t,n){let r=e.data.artifacts[t.name];if(!r)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}=kd(t,s),c=await a;if(c.exitCode!==0){if(!e$.test(`${c.stdout.toString()}
194
+ ${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 n$(e,t,i,s,n);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=wr(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!==r.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 n$(e,t,n,r,s){let i=e.resolveArtifactPath(t.name);if(await bn(i)!==e.data.artifacts[t.name]?.integrity)throw new u(`Cannot safely republish ${n}: 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&&t$.test(o.message))throw new u(`${n} was already accepted by ${r} 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 a$=4;async function xn(e,t){if(e.options.dryRun)return;let n=fi(t);if(e.npm.prepared?.key===n)return;let r=Ie(e,"prepare npm artifacts");e.npm.prepared=null;let s=await br(t);if(s.length===0){e.npm.prepared={key:n,packages:[]};return}if(s.some((a)=>!r.data.artifacts[a.name]))await u$(e);let i=await r$(Td(i$(),"sisyphus-publish-")),o=[];try{for(let[a,c]of s.entries()){if(!r.data.artifacts[c.name]){let p=Td(i,`${String(a).padStart(a$,"0")}.tgz`);await C(()=>l$(e,c,p),`Failed to prepare ${c.name}`),await r.setArtifact(c.name,p)}let l=r.resolveArtifactPath(c.name);Cr(await $r(l)),await c$(r,c),o.push({artifactPath:l,pkg:c})}}finally{await Id(i,{force:!0,recursive:!0})}e.npm.prepared={key:n,packages:o}}async function c$(e,t){if(e.data.operations.npm[t.name]?.state!=="pending")return;let n=e.data.operations.npmRegistries[t.name],r=e.data.artifacts[t.name]?.integrity;if(!n||!r)return;await xd(t,n,r)}async function Ia(e,t){let n=Ie(e,"bind npm artifacts to a release commit").data;if(!n.releaseCommit||!n.expectedReleaseTree||t!==n.releaseCommit)throw new u(`Publish source does not match the recorded release commit for ${n.id}`,n.releaseCommit?`Check out ${n.releaseCommit} before publishing`:"Resume the release before publishing");await Be(n,t)}async function Ta(e,t,n,r){let s=await Q();await Ia(e,s);let i=await la(await J(e));if(s===t&&i.length===0)return;throw new u(n,r)}async function l$(e,t,n){let r=o$(t.file),s=await J(e),i=null;try{let o=await Q();await Ia(e,o),await Ht(s),await Ad(e);let a=zt(e);if(await sd(t,r,s,a.matcher),a.command.length>0)await Pa(a.command,r,`Failed to build ${t.name}`);await Ta(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 s$(t.file,"utf-8"),{catalogs:l,workspaceVersions:p}=await p$(e),m=Bu(c,l,p);Cr(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 rd(t,r,m);let f=await td(i,n);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(!id(m,await $r(n)))throw new u(`Packed manifest does not match the prepared manifest for ${t.name}`,"This package was not recorded and nothing was published");await Ta(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 Id(i,{force:!0,recursive:!0})}}async function Ad(e){if(e.npm.ignoredBuildInputsValidated)return;await Rr(await J(e),"",zt(e).matcher),e.npm.ignoredBuildInputsValidated=!0}async function u$(e){if(e.npm.buildOutputsPrepared)return;let t=zt(e),n=await J(e),r=await Q();await Ia(e,r),await Ht(n),await ci(n,t.matcher),await $a(n,"",t.matcher);for(let[s,i]of t.root.entries())await Pa(i,n,`Failed to run release root build command ${s}`);if(t.root.length>0)await Ta(e,r,"Root build changed repository source files","No package was packed and nothing was published; restore the build changes before retrying");await Ad(e),e.npm.buildOutputsPrepared=!0}async function p$(e){if(!e.npm.publishContext){let t=await Bun.file("package.json").json(),{packages:n}=await U.scan({single:e.config.get("single")});e.npm.publishContext={catalogs:Nu(t),workspaceVersions:Fu(n.values())}}return e.npm.publishContext}import{dirname as d$}from"path";async function bi(e,t){if(e.options.dryRun)return;if(e.npm.prepared?.key!==fi(t))await xn(e,t);let n=e.npm.prepared?.packages??[];if(n.length===0)return;try{for(let r of n)await m$(e,r)}finally{e.npm.prepared=null}}async function m$(e,t){let n=Ie(e,`publish ${t.pkg.name}`),r=n.data.operations.npm[t.pkg.name];if(!r)throw Error(`Npm operation is not configured for ${t.pkg.name}`);if(r.state==="completed")return;if(r.state==="started"){await Ed(n,t.pkg,()=>Od(e,t));return}await n.verifyArtifact(t.pkg.name),await n.setPhase("external"),await n.markNpm(t.pkg.name,"started"),Cn(e,"npm publication"),await Od(e,t),await n.markNpm(t.pkg.name,"completed")}async function Od(e,t){let n=Ie(e,`publish ${t.pkg.name}`),r=n.data.options.npmTag,s=Cr(await $r(t.artifactPath)),i=n.data.operations.npmRegistries[t.pkg.name];if(!i)throw Error(`Npm registry is not configured for ${t.pkg.name}`);let o=Sn(t.pkg.name,i);await C(()=>Bun.$`npm publish ${t.artifactPath} --tag ${r} --access ${s} --ignore-scripts --registry ${i} ${o}`.cwd(d$(t.pkg.file)).quiet(),`Failed to publish ${t.pkg.name}`)}var Aa=20,_d={publishOnly:!1};async function Oa(){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 Ld(e,t,n,r=_d){for(let s of Md(e,t,n,r))await s()}async function Dd(e,t,n,r=_d){let s=[];for(let i of Md(e,t,n,r))try{await i()}catch(o){let a=$$(o);if(!s.some((c)=>c.message===a.message&&c.hint===a.hint))s.push(a)}return s}function Md(e,t,n,r){let{options:s}=e,i=!r.publishOnly,o=i&&s.commit!==!1,a=r.publishOnly?s.tags:s.push;return[()=>Oa(),()=>wd(e),o&&(async()=>void ui(e.config.get("commit"))),s.npm&&(async()=>y$(e,t)),i&&(()=>g$(e,t,n)),s.tags&&(()=>f$(t)),a&&(()=>h$(e,r)),s.npm&&(()=>w$(e,t,n,r)),s.npm&&(()=>b$(e,t)),s.npm&&(()=>R$(e,t))].filter((l)=>l!==!1)}async function g$(e,t,n){let r=await vr(e,t,n);await Ap(r,await J(e));let s=r.map((o)=>Xe(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:
195
+ ${r.join(`
196
+ `)}`)}async function f$(e){let t=[];for(let n of e){let r=Ea(n);if(await $n(`refs/tags/${r}`))t.push(r)}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 h$(e,t){let n=t.publishOnly?await yr(await hr()):(await Ys()).remote,r=e.config.get("provider"),s=()=>J(e),i=await fr(await Pn(n),s,r);if(wi(e,i),!e.options.createRelease)return;e.provider??=await bt(qt(i,r),r)}function y$(e,t){Wt(t,e.config.get("tag")),zt(e)}async function w$(e,t,n,r){for(let l of await br(t))await ti(l);let s=await J(e),i=r.publishOnly?[]:await vr(e,t,n);await rr(s);let o=await Op(s,i);if(o.length===0)return;let a=o.slice(0,Aa).join(`
197
+ `),c=o.length>Aa?`
198
+ ...and ${o.length-Aa} more`:"";throw new u("Repository has uncommitted changes outside the release files",`Npm releases pack committed source only; commit or stash these files first:
199
+ ${a}${c}`)}async function b$(e,t){let n=await Nd(e,t);if(!n)return;await ci(await J(e),n)}async function R$(e,t){let n=await Nd(e,t);if(!n)return;await Rr(await J(e),"",n)}async function Nd(e,t){return(await br(t)).length===0?void 0:zt(e).matcher}function $$(e){let t=e instanceof Error?e.message:String(e),n=e instanceof u?e.hint:void 0;return n?{hint:n,message:t}:{message:t}}async function Ri(e){let t=Ie(e,"push release refs"),n=t.data.operations.push;if(!n)throw Error("Release push is not configured");if(n.state==="completed")return;let r=gi(e);if(await vn(n,r.repositoryRoot),n.state==="started"&&await Hp(t,n,r)==="completed")return;await t.setPhase("external"),await t.markPush("started"),Cn(e,"remote push");try{await Xs(n,r)}catch(s){throw await qp(t,n,r,s)}await t.markPush("completed")}function P$(e){return e instanceof u&&e._tag!==Je}async function jd(e,t){let n=await ge.loadActive();if(!n)throw new u("No incomplete release found","Run sis roll to start a release");let r=n.data,s=mi(e,r.options,t);s.ledger=n;let i=r.packages.map((a)=>new z({file:a.file,isPrivate:a.isPrivate,name:a.name,newVersion:a.newVersion,version:a.oldVersion})),o=r.stones.map((a)=>O.fromJson(a));if(s.local.createdTags=[...r.releaseTags],r.phase==="completed")return await n.complete(),{ledger:n.data,packages:i,stones:o};try{if(await $d(s,r),await Np(n.data),await Mp(n.data),await xa(s,i,o),r.options.npm){if(i.some((c)=>n.data.operations.npm[c.name]&&!n.data.artifacts[c.name]))await Ht(await J(s));await xn(s,i)}if(n.phase==="planned")await n.setPhase("local-ready");return await v$(s,i,o),{ledger:n.data,packages:i,stones:o}}catch(a){if(P$(a)||!kn(s))throw a;throw hi(s,a)}}async function v$(e,t,n){let r=Ie(e,"resume external operations");if(r.phase==="completed"){await Sr(e);return}if(r.data.operations.push)await Ri(e);if(e.options.npm)await bi(e,t);if(e.options.createRelease)await yi(e,n,t);await Sr(e)}var kr="Local release state and the recovery ledger were preserved";async function Fd(e,t){if(kn(e))return!1;await S$(e);let{local:n}=e;if(e.npm.prepared=null,await _p(n.createdCommit,n.createdTags,n.createdTagTargets,()=>J(e)),n.commitCreated){if(n.ownedPaths)await zs(n.ownedPaths);n.commitCreated=!1,n.createdCommit=null}if(n.createdTags=[],n.createdTagTargets.clear(),await e.changelogGenerator.rollback(),await e.packageUpdater.rollback(),t)await _a(e);return!0}async function _a(e){if(!e.ledger)return;await e.ledger.remove(),e.ledger=null}async function S$(e){let{local:t}=e;if(t.rollbackBlockedReason)throw new u(`Cannot roll back release because ${t.rollbackBlockedReason}`,kr);if(t.commitCreated&&!t.createdCommit)throw new u("Cannot identify the release commit for rollback",kr);if(t.commitCreated&&t.createdCommit){let[n,r]=await Promise.all([Q(),Js()]);if(n!==t.createdCommit.oid||r!==t.createdCommit.ref)throw new u(`Cannot roll back release commit because HEAD changed from ${t.createdCommit.oid}`,kr)}if(t.commitCreated&&t.ownedPaths){let n=t.ownedPaths.map((s)=>Xe(s));if((await C(()=>Bun.$`git status --porcelain=v1 -z --untracked-files=all -- ${n}`.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",kr)}for(let n of t.createdTags){let r=t.createdTagTargets.get(n),s=await $n(`refs/tags/${n}`);if(!r||s!==r)throw new u(`Cannot roll back release because tag ${n} changed after creation`,kr)}}class Ue{session;constructor(e,t,n=di){this.session=mi(e,t,n)}static async assertNoActiveRelease(){await Oa()}static async resume(e,t=di){return jd(e,t)}static async abort(e=di){return Jp(e)}async preflight(e,t,n){await Ld(this.session,e,t,n)}async inspectPreflight(e,t,n){return Dd(this.session,e,t,n)}async initializeExternalRelease(e,t,n){await bd(this.session,e,t,n)}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,n){await vd(this.session,e,t,n)}async createGitTags(e){await Sd(this.session,e)}async finalizeExternalRelease(e,t){await Rd(this.session,e,t)}async prepareNpmPublish(e){await xn(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 Ri(this.session)}async publishToNpm(e){await bi(this.session,e)}async createGitRelease(e,t){await yi(this.session,e,t)}async completeRelease(){await Sr(this.session)}hasCrossedIrreversibleBoundary(){return kn(this.session)}createIncompleteReleaseError(e){return hi(this.session,e)}async rollback(e=!0){return Fd(this.session,e)}async removeReleaseLedger(){await _a(this.session)}getLedgerSnapshot(){return this.session.ledger?.data??null}}import{dirname as C$}from"path";var k$=1000,x$=5000,E$=5000,T$="E404";function La(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 Da(e,t){let n=t>0?I$(e):[];if(n.length===0)return[];let r=Date.now()+t*k$,s=new Map,i=n;while(i.length>0){let o=await Promise.all(i.map((c)=>A$(c,r)));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=r-Date.now();if(i.length===0||a<=0)break;await Bun.sleep(Math.min(x$,a))}return n.map(({name:o,registry:a,version:c})=>{let l=s.get(o)??{state:"pending"};return{name:o,registry:a,version:c,...l}})}function Ma(e,t){return e.filter((n)=>n.state!=="visible").map((n)=>{let r=`${n.name}@${n.version}`;if(n.state==="mismatch")return`${r} on ${n.registry} does not match the integrity of the published artifact`;if(n.state==="error")return`${r} could not be checked on ${n.registry}: ${n.detail}`;return`${r} is not visible on ${n.registry} after ${t}s; npm may still be processing or holding it`})}function I$(e){return e.packages.flatMap((t)=>{let n=e.artifacts[t.name],r=e.operations.npmRegistries[t.name];return e.operations.npm[t.name]?.state==="completed"&&n&&r?[{cwd:C$(t.file),integrity:n.integrity,name:t.name,registry:r,version:t.newVersion}]:[]})}async function A$(e,t){let n=`${e.name}@${e.version}`,r=Math.max(t-Date.now(),E$),s=Bun.spawn(["npm","view",n,"--json","--prefer-online","--registry",e.registry,...Sn(e.name,e.registry),`--fetch-timeout=${r}`,"--fetch-retries=0"],{cwd:e.cwd,stderr:"pipe",stdin:"ignore",stdout:"pipe",timeout:r}),[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(T$))return{state:"pending"};if(i!==0)return{detail:a.trim().split(`
200
+ `)[0]||`exit ${i}`,state:"error"};let c=wr(ni(o));if(!c||c.name!==e.name||c.version!==e.version)return{state:"pending"};return{state:c.integrity===e.integrity?"visible":"mismatch"}}function En(e,t){let n=e.map((r)=>So(r,t));return{skipped:[...new Set(n.flatMap((r)=>r.skipped))].sort(),stones:n.map((r)=>r.stone)}}function xr(e,t,n){let r=[...new Set(e.allPackages)].filter((s)=>!t.has(s)&&!se(s,n)).sort();if(r.length>0)return{kind:"unknown-packages",names:r};return{kind:"ignored-only"}}function Na(e,t,n,r){let{stone:s}=So(e,n),i=xr(s,t,n);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,r).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 Bd(e,t){return`${e} ${va(t)}`}var O$=1;function Ud(e){let{ledger:t}=e,n=t?_$(t,e.npmVisibility??[]):D$(e.packages),r=n.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:j$(t),pushed:t?.operations.push?.state==="completed"},packages:n,published:r.length>0,publishedPackages:r,releaseCommit:e.abort?.commitDiscarded?null:t?.releaseCommit??e.releaseCommit??null,releaseId:t?.id??null,schemaVersion:O$,status:e.status,stones:t?t.stones.map((i)=>i.id):e.stones.map((i)=>i.id),tags:N$(t?t.tagsReady?[...t.releaseTags]:[]:M$(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=F$(e.error);return s}function _$(e,t){return e.packages.map((n)=>({integrity:e.artifacts[n.name]?.integrity??null,name:n.name,newVersion:n.newVersion,oldVersion:n.oldVersion,private:n.isPrivate,published:e.operations.npm[n.name]?.state==="completed",registry:e.operations.npmRegistries[n.name]??null,tag:e.tagsReady?e.releaseTags.find((r)=>r===Gd(n.name,n.newVersion))??null:null,visible:L$(t,n.name)}))}function L$(e,t){let n=e.find((r)=>r.name===t);return n?n.state==="visible":null}function Gd(e,t){return`${e}@${t}`}function D$(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 M$(e,t){if(!t)return[];return e.map((n)=>Gd(n.name,n.newVersion??n.version)).sort()}function N$(e,t){return t?e.filter((n)=>!t.deletedTags.includes(n)):e}function j$(e){let t=Object.values(e?.operations.providerReleases??{});return t.length>0&&t.every((n)=>n.state==="completed")}function F$(e){let t=e instanceof Error?e.message:String(e),n=e instanceof u?e.hint:void 0,r=Vd(e);return{...r.length>0?{causes:r}:{},...n?{hint:n}:{},message:t}}function Vd(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,...Vd(s,t)])}var B$="Fix the file so it matches the schema.json shipped with @r5n/sisyphus, then run the command again",Hd="InvalidConfig";function le(e,t,n){return ke((r)=>{try{return n(r)}catch(s){if(s instanceof u)throw s;throw new u(`${e} must be ${t}`,B$,1,{tag:Hd})}})}var ce=(e)=>le(e,"a string",_()),Tt=(e)=>le(e,"a boolean",nn()),Ge=(e)=>le(e,"an array of strings",ne(_())),Er=(e)=>ke((t)=>t===void 0?void 0:e(t)),ja=(e)=>Er(ce(e)),fe=(e,t)=>le(e,"an object",st(t)),U$=/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d{1,5})?$/,G$=new Set(["http:","https:"]),V$=/\/+$/,H$=_().map((e)=>{let t=e.trim().toLowerCase();return U$.test(t)?t:K()}),q$=_().map((e)=>{let t=URL.parse(e);if(!t||!G$.has(t.protocol)||t.username||t.password||t.search||t.hash)return K();return t.href.replace(V$,"")}),W$=fe("provider",{apiUrl:Er(le("provider.apiUrl","an http(s) URL without credentials, query or fragment",q$)),host:Er(le("provider.host","a host name such as git.example.com, optionally with a port",H$)),type:le("provider.type",'"github" or "gitlab"',De(["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:Hd})}),J$=fe("currentRelease.packages.*",{newVersion:ce("currentRelease.packages.*.newVersion"),oldVersion:ce("currentRelease.packages.*.oldVersion")}),z$=fe("config",{$schema:ce("$schema"),changelog:fe("changelog",{append:Tt("changelog.append"),filename:ce("changelog.filename"),generate:Tt("changelog.generate"),packageHeader:ce("changelog.packageHeader"),root:Tt("changelog.root"),rootHeader:ce("changelog.rootHeader"),sections:le("changelog.sections","an object of strings",dt(_())),template:ja("changelog.template")}),commit:fe("commit",{author:ce("commit.author"),email:ja("commit.email"),message:ce("commit.message")}),commits:fe("commits",{skip:fe("commits.skip",{authors:Ge("commits.skip.authors"),messagePatterns:Ge("commits.skip.messagePatterns")})}),currentRelease:Er(fe("currentRelease",{packages:le("currentRelease.packages","an object",dt(J$)),planHash:ce("currentRelease.planHash"),sourceHash:ce("currentRelease.sourceHash"),stoneIds:Ge("currentRelease.stoneIds"),timestamp:ce("currentRelease.timestamp")})),dependents:fe("dependents",{kinds:le("dependents.kinds","an array of dependency sections",ne(De(["dependencies","devDependencies","optionalDependencies","peerDependencies"]))),updateInternal:le("dependents.updateInternal",'"always" or "outOfRange"',De(["always","outOfRange"]))}),ignore:Ge("ignore"),lastStone:fe("lastStone",{commit:ce("lastStone.commit"),date:ce("lastStone.date")}),plugins:Ge("plugins"),pr:fe("pr",{labelMapping:le("pr.labelMapping",'an object of "major", "minor" or "patch"',dt(De(["major","minor","patch"]))),skip:fe("pr.skip",{authors:Ge("pr.skip.authors"),labels:Ge("pr.skip.labels"),titlePatterns:Ge("pr.skip.titlePatterns")})}),provider:Er(W$),release:fe("release",{build:fe("release.build",{command:Ge("release.build.command"),outputs:Ge("release.build.outputs"),root:le("release.build.root","an array of string arrays",ne(ne(_())))}),createRelease:Tt("release.createRelease"),npm:Tt("release.npm"),npmVisibilityTimeout:le("release.npmVisibilityTimeout","a number",Sl()),push:Tt("release.push"),tags:Tt("release.tags")}),scripts:fe("scripts",{post:le("scripts.post","an object of strings",dt(_())),pre:le("scripts.pre","an object of strings",dt(_()))}),single:Tt("single"),sisyphusDir:ce("sisyphusDir"),stones:Ge("stones"),stonesPath:ja("stonesPath"),tag:ce("tag")}),K$=`${on}/${ms}`;function X$(e){return z$(e)}function $i(e=K$){return new po(e,ht,{parse:X$,strict:!0})}function qd(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 Ye="sisyphus/release",Y$="chore(release):";function Fa(e){return Bd(Y$,e)}function Wd(e,t,n){let r=Pr(t,e,n.sections);return`${Fa(e)}
189
201
 
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(`
202
+ ${li(r)}`}function Jd(e,t,n){let r=Pr(t,e,n.sections);return[Z$(r),...r.groups.map(eP),tP(n.release),nP(t),rP()].join(`
203
+ `)}function Z$({packages:e}){return["## Release plan","","| Package | Version | Bump | Why |","| --- | --- | --- | --- |",...e.map(Q$),""].join(`
204
+ `)}function Q$(e){return`| ${e.isPrivate?`\`${e.name}\` (private)`:`\`${e.name}\``} | ${e.from} \u2192 ${e.to} | ${e.bump??"none"} | ${e.reason} |`}function eP(e){let t=e.changes.flatMap((n)=>[`- ${Sa(n)}${n.hash?` \u2014 \`${n.hash}\``:""}`,...n.notes.map((r)=>` - ${r}`)]);return[`## ${e.heading}`,"",...t,""].join(`
205
+ `)}function tP(e){let t=[e.tags?"Every released package is tagged at the merge commit as `name@version`.":null,e.npm?"Public packages are built, packed and published to npm in dependency order; private packages are tagged but never published.":null,e.createRelease?"A release is created on the provider for each package.":null].filter((r)=>r!==null);return["## When this merges","","The merge starts the release workflow. It does not add commits to the base branch.","",...t.length>0?t.map((r)=>`- ${r}`):["- The release workflow runs for the versions above."],""].join(`
206
+ `)}function nP(e){return["<details>",`<summary>Stones (${e.length})</summary>`,"",...e.map((t)=>`- \`${t.id}\`: ${t.message}`),"","</details>",""].join(`
207
+ `)}function rP(){return["---","*This PR was automatically created by [Sisyphus](https://github.com/r5n-labs/clis).*","*Merging this PR will trigger the release workflow.*"].join(`
208
+ `)}var Ba="sisyphus-release",aP="Sisyphus release PR",cP="6f42c1";function lP(e=(t)=>bt(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 n=await e(t.config.get("provider")),r=t.args.dryRun,s=await pP(n,r,Ks(t,!1)),i;try{let o=$i(t.config.path);i=await uP(n,o,s,r)}catch(o){throw await RP(s,r,o),o}await Qd(s.originalRef),t.output.result(i)}})}var Yd=lP();async function uP(e,t,n,r){let{generated:s,packages:i,stones:o}=await dP(t,r);if(o.length===0)return P.info(d.dim("No pending stones found, skipping release PR")),{status:"skipped"};let a={release:t.get("release"),sections:t.get("changelog").sections},c=Fa(i),l=Jd(i,o,a),p={packages:i.map((f)=>({name:f.name,newVersion:f.newVersion,version:f.version})),stones:o.map((f)=>f.id),title:c};if(P.info(`${d.bold("Release PR:")} ${c}`),P.info(`${d.dim("Packages:")} ${i.map((f)=>f.name).join(", ")}`),r)return P.info(d.yellow(`
209
+ [dry-run] Would create/update release PR`)),P.info(d.dim(`
210
+ PR Body preview:`)),P.info(l),{...p,status:"dry-run"};let m=new B(t);for(let f of s)await m.save(f);await gP(t,o,i,n,Wd(i,o,a));let{pr:g,status:h}=await fP(e,n.baseBranch,c,l);return{...p,pr:g,status:h}}async function pP(e,t,n){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 xt(["fetch","origin",o],{interactive:n},`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 ${Ye} ${a}`.quiet(),`Failed to check out ${Ye} 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 Zd(l));return{baseBranch:o,cutCommit:c,interactive:n,originalRef:i,root:l,untracked:p}}async function Zd(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 dP(e,t){let r=await new B(e).list(),s=await mP(e,r.length,t),i=[...r,...s];if(i.length===0)return{generated:[],packages:[],stones:[]};let o=e.get("ignore")??[],{stones:a,skipped:c}=En(i,o);if(c.length>0)P.warn(d.yellow(`Excluded by config.ignore: ${c.join(", ")}`));let{packages:l}=await U.scan({single:e.get("single")}),p=O.mergeAll(a),m=xr(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}=dn(z.applyStone(p,l,pe(e).kinds));if(g.length>0)P.warn(d.yellow(`Dependency cycle between ${g.join(", ")}; publish order may not satisfy every pin`));if(h.length===0)return P.warn(d.yellow("Pending stones reference no releasable packages")),{generated:[],packages:[],stones:[]};return{generated:s,packages:h,stones:a}}async function mP(e,t,n){let s=await new Ft(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(Ft.buildStoneData(o,i,pe(e)),t+a);return P.info(`${d.dim(n?"[dry-run] Would generate stone:":"Generated stone:")} ${o.message}`),c})}async function gP(e,t,n,r,s){let{cutCommit:i,interactive:o}=r,a=Ve();a.start("Applying release changes...");try{let c=[...await hP(n),...await yP(e,t,n)],l=await new B(e).archive(t);if(await Xd(c),await wP(e,t,n,l,i),await Xd(nr(e)),(await Bun.$`git diff --cached --quiet`.quiet().nothrow()).exitCode!==0)await C(()=>Bun.$`git commit -m ${s}`.quiet(),`Failed to commit the release changes on ${Ye}`);await xt(["push","origin",Ye,"--force"],{interactive:o},`Failed to push ${Ye} to origin`),a.stop("Release branch ready")}catch(c){throw a.error("Release preparation failed"),c}}async function fP(e,t,n,r){let s=Ve(),i=await e.findPr({head:Ye,label:Ba});if(i)return s.start("Updating PR..."),await e.updatePr(i.number,{body:r,title:n}),s.stop(`PR #${i.number} updated`),P.info(`
211
+ ${d.green("Release PR updated:")} ${i.url}`),{pr:{number:i.number,url:i.url},status:"updated"};s.start("Creating PR..."),await e.ensureLabelExists(Ba,{color:cP,description:aP});let o=await e.createPr({base:t,body:r,head:Ye,labels:[Ba],title:n});return s.stop(`PR #${o.number} created`),P.info(`
212
+ ${d.green("Release PR created:")} ${o.url}`),{pr:{number:o.number,url:o.url},status:"created"}}async function Xd(e){await C(()=>Bun.$`git --literal-pathspecs add -- ${e}`.quiet(),`Failed to stage ${e.join(", ")}`)}async function hP(e){return await new er().updateAll(e),e.map((t)=>t.file)}async function yP(e,t,n){let r=e.get("changelog");if(!r.generate)return[];return await un(e).generate(t,n),pi(r,n)}async function wP(e,t,n,r,s){let i=await Os(...nr(e)),o={packages:bP(n),sourceHash:i,stoneIds:t.map((a)=>a.id),timestamp:r};e.set("currentRelease",{...o,planHash:_s(o,t.map((a)=>a.toJson()))}),e.set("lastStone",{commit:s,date:new Date().toISOString()})}function bP(e){let t={};for(let n of e)if(n.newVersion)t[n.name]={newVersion:n.newVersion,oldVersion:n.version};return t}async function RP(e,t,n){try{if(!t)await $P(e);await Qd(e.originalRef)}catch(r){throw AggregateError([n,r],"Release PR preparation failed and the original checkout could not be restored")}}async function $P(e){if((await Bun.$`git branch --show-current`.quiet()).stdout.toString().trim()!==Ye)return;await C(()=>Bun.$`git reset --hard --quiet HEAD`.quiet(),`Failed to discard changes on ${Ye}`);let n=(await Zd(e.root)).filter((r)=>!e.untracked.has(r));for(let r of n)await PP(e.root,r)}async function PP(e,t){await iP(Kd(e,t),{force:!0});let n=zd(t);while(n!=="."){let r=Kd(e,n),s=await sP(r).catch(()=>null);if(s===null||s.length>0)return;await oP(r),n=zd(n)}}async function Qd(e){try{await Bun.$`git checkout ${e}`.quiet()}catch(t){let n=(await Bun.$`git branch --show-current`.quiet().nothrow()).stdout.toString().trim();throw new u(`Failed to restore ${e}; the checkout is still on ${n||"a detached HEAD"}`,`Run 'git checkout ${e}' once the conflict is resolved`,1,{cause:t,tag:"ReleaseBranchRestoreFailed"})}}var em=M({name:"actions",description:"CI/CD integration",subcommands:[eu,Yd]});var tm="0.0.0",nm=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"),n=e.config.get("ignore")??[],r=await U.scan({single:t}),i=(t?null:await U.scan({single:!0}))?.packages.values().next().value??r.packages.values().next().value,o=await new B(e.config).list(),a={ignore:n,kinds:pe(e.config).kinds,packages:r.packages},c={config:e.args.config?e.config.getAll():void 0,packages:r.packageNames.filter((l)=>!se(l,n)).map((l)=>({name:l,version:r.packages.get(l)?.version??tm})),release:SP(o,a),root:{name:i?.name??"",version:i?.version??tm},stones:o.map((l)=>vP(l,a))};e.output.result(c,CP)}});function vP(e,t){let n=Na(e,t.packages,t.ignore,t.kinds);if(n.kind==="invalid")return{id:e.id,invalid:n.message,message:e.message,packages:[],tag:e.tag};return{id:e.id,message:e.message,packages:n.packages,tag:e.tag}}function SP(e,t){if(e.length===0)return{errors:[],packages:[],releasable:!1};let{stones:n}=En(e,t.ignore),r=O.merge(n,n.map((o)=>o.message).join("; "));if(r.errors.length>0)return{errors:["Pending stones conflict and cannot be released together",...r.errors],packages:[],releasable:!1};let s=Na(r.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 CP(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((n)=>` ${d.dim("\u2022")} ${d.cyan(n.name)}${d.dim(`@${n.version}`)}`)].join(`
207
213
  `)];if(e.stones.length>0)t.push(`${d.bold(d.green("Stones:"))}
208
214
 
209
- ${e.stones.map(Wv).join(`
215
+ ${e.stones.map(kP).join(`
210
216
 
211
- `)}`),t.push(Jv(e.release));if(e.config)t.push(`${d.bold(d.green("Config:"))}
217
+ `)}`),t.push(xP(e.release));if(e.config)t.push(`${d.bold(d.green("Config:"))}
212
218
  ${d.dim(JSON.stringify(e.config,null,2))}`);return t.push(d.green("Sisyphus check complete.")),t.join(`
213
219
 
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(`
220
+ `)}function kP(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(`
221
+ `);return t.push(...e.packages.map(rm)),t.join(`
222
+ `)}function xP(e){let t=d.bold(d.green("Combined release:"));if(e.errors.length>0)return[t,...e.errors.map((n)=>` ${d.yellow(n)}`)].join(`
217
223
  `);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.")}`}
224
+ ${d.dim("No releasable packages")}`;return[t,...e.packages.map(rm)].join(`
225
+ `)}function rm(e){let t=cn[e.bump];return` ${an[e.bump]} ${d.cyan(e.name)}@${t(e.newVersion)} ${d.dim(`(${e.bump})`)}`}var EP=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"}}),sm="ConfigExists",om=M({name:"init",description:"Initialise the Sisyphus config or edit it",args:EP,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:n,...r}=e.args,s=Object.values(r).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&&!n)throw new u(`Config already exists at ${e.config.path}`,"Pass --default --force to reset it",1,{tag:sm});let l=i?TP(e.config.getAll()):{};return e.config.save({...structuredClone(ht),...l}),Ua(e,i?"reset":"created",await im(e.config))}let o=e.interactive&&!s;if(i&&!n&&!o){if(!s)return Ua(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:sm})}let a=e.config.getAll(),c=o?await OP(a):r;return e.config.save(Lt({...a},IP(c))),Ua(e,i?"updated":"created",await im(e.config))}});function TP(e){let{currentRelease:t,lastStone:n,stones:r}=e;return{...t&&{currentRelease:t},lastStone:n,stones:r}}function IP(e){let t=(o)=>Object.fromEntries(Object.entries(o).filter(([,a])=>a!==void 0)),n=(o)=>Object.keys(o).length>0,r=t({author:e.commitAuthor,email:e.commitEmail,message:e.commitMessage}),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}),...n(r)&&{commit:r},...n(s)&&{changelog:s},...n(i)&&{release:i}}}async function im(e){let t=e.get("lastStone");if(t?.commit)return t;let n=await Bun.$`git rev-parse HEAD`.quiet().nothrow(),r=n.exitCode===0?n.stdout.toString().trim():"";if(!r)return t;let s={commit:r,date:new Date().toISOString()};return e.set("lastStone",s),s}function Ua(e,t,n){let r={lastStone:n,path:e.config.path,status:t};e.output.result(r,()=>AP(r,e.cli.version))}function AP(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
226
 
221
227
  You can now start by creating a new stone by running ${d.green(T)}${d.blue(" version")}
222
228
  and following the prompts.
223
229
 
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:
230
+ After you finished, you can release it by running ${d.green(T)}${d.blue(" roll")}`}async function OP(e){let t=await Yr({changelog:()=>G({active:"Yes, generate changelog",inactive:"Skip changelog",initialValue:e.changelog?.generate??!0,message:"Generate changelog for release?"}),configureCommit:()=>G({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:n}})=>n?$e({initialValue:e.commit?.author??"",message:"Commit author",placeholder:"r5n-bot"}):void 0,commitEmail:({results:{configureCommit:n}})=>n?$e({initialValue:e.commit?.email??"",message:"Commit author email",placeholder:"r5n-bot@users.noreply.github.com"}):void 0,commitMessage:({results:{configureCommit:n}})=>n?$e({initialValue:e.commit?.message??"",message:"Commit message",placeholder:"release: <packageName@version>"}):void 0,createRelease:()=>G({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:()=>G({active:"Yes, publish packages to NPM",inactive:"Skip NPM release",initialValue:e.release?.npm??!1,message:"Publish packages to NPM when releasing packages?"}),push:()=>G({active:"Yes, push to remote",inactive:"No, keep local",initialValue:e.release?.push??!1,message:"Should `roll` command push commits and tags to remote?"}),rootChangelog:({results:{changelog:n}})=>n?G({active:"Yes, generate combined changelog",inactive:"Skip root changelog",initialValue:e.changelog?.root??!1,message:"Generate combined changelog for monorepo?"}):void 0,single:()=>G({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:()=>$e({initialValue:e.tag??"latest",message:"Tag used when versioning packages. Leave `latest` if you are not sure.",placeholder:"latest"}),tags:()=>G({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:Ga(t.commitAuthor),commitEmail:Ga(t.commitEmail),commitMessage:Ga(t.commitMessage),createRelease:t.createRelease,npm:t.npm,push:t.push,rootChangelog:_P(t.rootChangelog),single:t.single,tag:t.tag,tags:t.tags}}function Ga(e){return typeof e==="string"?e:void 0}function _P(e){return typeof e==="boolean"?e:void 0}var am=60,lm=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 To;if(!await t.exists())throw new u("No .changeset directory found","This command migrates existing changesets to sisyphus stones");let{changesets:n,config:r,empty:s,errors:i}=await LP(t);if(BP(n),s.length>0)P.info(d.dim(`Skipping empty changesets without package bumps: ${s.join(", ")}`));if(r)UP(r);if(i.length>0)throw new u(`Cannot migrate changesets:
225
231
  ${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(`
232
+ `)}`,"Fix or remove these changeset files; no stones were created",1,{tag:"InvalidChangeset"});let o=new B(e.config),a=DP(t,n),c=await o.list(),l=a.filter((h)=>!MP(h.data,c)),p=a.filter((h)=>!l.includes(h)).map((h)=>h.filename);if(p.length>0)P.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&&!Le(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 G({initialValue:!0,message:`Migrate ${l.length} changeset(s) to stones?`}))return;let g=await NP(o,l);if(r)jP(e.config,r);FP(g),e.output.result({alreadyMigrated:p,created:g,dryRun:!1,planned:m,skipped:s})}});async function LP(e){let t=Ve();t.start("Analyzing changesets...");let n=await e.parse();if(n.changesets.length===0&&n.errors.length===0){t.stop("No changesets found");let r=n.empty.length>0?`Every changeset is empty: ${n.empty.join(", ")}`:void 0;throw new u("No changeset files to migrate",r,1,{tag:"NoChangesets"})}if(n.errors.length>0)return t.error(`Found ${n.errors.length} changeset(s) that cannot be parsed`),n;return t.stop(`Found ${d.bold(String(n.changesets.length))} changeset(s)`),n}function DP(e,t){let n=[],r=[];for(let s of t)try{n.push({data:e.toStoneData(s),filename:s.filename})}catch(i){if(!(i instanceof u))throw i;r.push(i.message)}if(r.length>0)throw new u(`Cannot migrate changesets:
233
+ ${r.join(`
234
+ `)}`,"Rewrite them as major, minor, or patch before migrating; no stones were created");return n}function cm(e){let t=(n)=>[...n??[]].sort();return JSON.stringify([e.message,e.description??"",t(e.major),t(e.minor),t(e.patch)])}function MP(e,t){let n=cm(e);return t.some((r)=>cm({description:r.description,major:r.major,message:r.message,minor:r.minor,patch:r.patch})===n)}async function NP(e,t){let n=Ve();n.start("Creating stones...");let r=[];for(let s of t){let i=await e.create(s.data);r.push(i.id)}return n.stop(`Created ${d.bold(String(r.length))} stone(s)`),r}function jP(e,t){let n=Ve();n.start("Migrating config..."),GP(e,t),n.stop("Config migrated")}function FP(e){let t=e.map((n)=>` ${d.dim("-")} ${n}`).join(`
229
235
  `);te(`${t}
230
236
 
231
237
  Run ${d.green(`${T} stone list`)} to view stones
232
238
  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
+ Remove ${d.green(".changeset/")} once you have checked the stones`,d.green("Migration complete"))}function BP(e){for(let t of e){let n=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(", "),r=t.summary.length>am?`${t.summary.slice(0,am)}...`:t.summary;P.info(`${d.dim(t.filename)}
240
+ ${d.dim("Packages:")} ${n}
241
+ ${d.dim("Message:")} ${r||d.dim("(empty)")}`)}}function UP(e){let t=[{category:"migrate",check:()=>(e.ignore?.length??0)>0,format:()=>`ignore: ${e.ignore?.join(", ")}`},{category:"migrate",check:()=>e.commit===!0,format:()=>"commit: enabled (will enable commit & push)"},{category:"migrate",check:()=>e.access==="public",format:()=>"access: public (will enable npm publishing)"},{category:"migrate",check:()=>e.changelog===!1,format:()=>"changelog: disabled"},{category:"info",check:()=>!!e.baseBranch&&e.baseBranch!=="master",format:()=>`baseBranch: ${e.baseBranch}`},{category:"info",check:()=>!!e.updateInternalDependencies,format:()=>`updateInternalDependencies: ${e.updateInternalDependencies}`},{category:"info",check:()=>Array.isArray(e.changelog)||typeof e.changelog==="string",format:()=>`changelog: ${Array.isArray(e.changelog)?e.changelog[0]:e.changelog}`},{category:"info",check:()=>Array.isArray(e.commit)||typeof e.commit==="string",format:()=>`commit: ${Array.isArray(e.commit)?e.commit[0]:e.commit}`},{category:"unsupported",check:()=>(e.linked?.length??0)>0,format:()=>`linked: ${e.linked?.length} group(s)`},{category:"unsupported",check:()=>(e.fixed?.length??0)>0,format:()=>`fixed: ${e.fixed?.length} group(s)`}],n={info:{color: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 r of t)if(r.check())n[r.category].items.push(d.dim(r.format()));for(let r of[n.migrate,n.info,n.unsupported])if(r.items.length>0)te(r.items.join(`
242
+ `),r.color(r.title))}function GP(e,t){if(t.ignore?.length){let n=e.get("ignore")??[],r=[...new Set([...n,...t.ignore])];e.set("ignore",r)}if(t.commit===!0){let n=e.get("commit")??{},r=e.get("release")??{};e.set("commit",{...n,author:n.author??"Sisyphus"}),e.set("release",{...r,push:!0})}if(t.access==="public"){let n=e.get("release")??{};e.set("release",{...n,npm:!0})}if(t.changelog===!1){let n=e.get("changelog")??{};e.set("changelog",{...n,generate:!1})}}var um=100,VP=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 HP(e,t){if(!e)return;let n=new Set(t),r=e.map((s)=>({...s,packages:s.packages.filter((i)=>n.has(i))})).filter((s)=>s.packages.length>0);return r.length>0?r:void 0}var pm=M({name:"pr",description:"Create a stone from a Pull Request",args:VP,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 n=await new Lo(e.config).analyze(e.args.url),r={number:n.pr.number,title:n.pr.title,url:n.pr.url};qP(n.pr);let s=(f)=>{P.info(d.dim(`Skipping: ${f.message}`)),e.output.result({pr:r,reason:f,status:"skipped"})},i=WP(e.config,n.pr);if(i)return s(i);if(n.packages.size===0){if(n.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 JP(e,n.suggestedBump,n.pr.labels),a=await KP(e,n.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=`[#${n.pr.number}](${n.pr.url})`,g=XP({allPackages:p,bump:o,commits:n.commits,dependents:pe(e.config),description:n.pr.body||void 0,message:e.args.message??`${n.pr.title} (${m})`,packages:l});if(YP(g,e.args.dryRun),e.args.dryRun){e.output.result({pr:r,status:"dry-run",stone:g});return}if(!e.args.yes&&e.interactive&&!await G({initialValue:!0,message:"Create this stone?"})){e.output.result({pr:r,status:"declined",stone:g});return}let h=await new B(e.config).create(g);te(`Run ${d.green(`${T} roll`)} to release packages
243
+ or create another stone with ${d.green(`${T} version`)}`,`Stone ${d.bold(h.id)} ${d.green("created")}`),e.output.result({pr:r,status:"created",stone:g,stoneId:h.id})}});function qP(e){if(P.info(`PR #${d.bold(String(e.number))}: ${e.title}`),P.info(`${d.dim("Author:")} ${e.author}`),P.info(`${d.dim("Branch:")} ${e.branch}`),e.labels.length>0)P.info(`${d.dim("Labels:")} ${e.labels.map((t)=>d.cyan(t)).join(", ")}`)}function WP(e,t){let n=e.get("pr").skip;for(let r of t.labels)if(n.labels.some((s)=>s.toLowerCase()===r.toLowerCase()))return{code:"skip-label",message:`label "${r}" is in skip list`};if(n.authors.some((r)=>r.toLowerCase()===t.author.toLowerCase()))return{code:"skip-author",message:`author "${t.author}" is in skip list`};for(let r of n.titlePatterns)try{if(new RegExp(r,"i").test(t.title))return{code:"skip-title",message:`title matches skip pattern "${r}"`}}catch{P.warn(d.yellow(`Invalid regex pattern in pr.skip.titlePatterns: "${r}"`))}return null}async function JP(e,t,n){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 P.info(`${d.dim("Detected bump:")} ${d.bold(t)} (from ${zP(t,n,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 _t({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 zP(e,t,n){let r=n.get("pr").labelMapping;for(let s of t){let i=s.toLowerCase();for(let[o,a]of Object.entries(r))if(i===o.toLowerCase()&&a===e)return`label: ${s}`}return"title"}async function KP(e,t){let n=Array.from(t);if(e.args.packages){let r=e.args.packages.split(",").map((i)=>i.trim()).filter(Boolean),s=r.filter((i)=>!t.has(i));if(s.length>0)throw new u(`Packages not affected by this PR: ${s.join(", ")}`,`Affected packages: ${n.join(", ")}`);return r}if(n.length===1||e.args.yes||!e.interactive)return P.info(`${d.dim("Affected packages:")} ${n.map((r)=>d.bold(r)).join(", ")}`),n;return nt({initialValues:n,message:"Select packages to include",options:n.map((r)=>({label:r,value:r})),required:!0})}function XP(e){let{allPackages:t,bump:n,commits:r,dependents:s,description:i,message:o,packages:a}=e,c={commits:HP(r,a),description:i,message:o};if(n==="major")c.major=a;else if(n==="minor")c.minor=a;else c.patch=a;return c.dependency=X(Rt(a.map((l)=>({bump:n,name:l})),t,s)),c}function YP(e,t){let n=[];if(t)n.push(d.bold(d.yellow("[dry-run]")));if(n.push(`${d.dim("Stone:")} ${d.bold(e.message)}`),e.major?.length)n.push(` ${d.red("major")}: ${e.major.join(", ")}`);if(e.minor?.length)n.push(` ${d.yellow("minor")}: ${e.minor.join(", ")}`);if(e.patch?.length)n.push(` ${d.green("patch")}: ${e.patch.join(", ")}`);if(e.commits?.length)n.push(` ${d.dim(`${e.commits.length} commit(s)`)}`);if(e.description){let r=e.description.length>um?`${e.description.slice(0,um)}...`:e.description;n.push(` ${d.dim("Description:")} ${r}`)}P.step(n.join(`
244
+ `))}import{readFile as sv}from"fs/promises";import{dirname as iv,join as ov}from"path";var dm=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"}}),ZP=1,QP="Pass --yes to consent to the release, or use --dry-run to preview it";function It(e){return{interactive:Ks(e,e.args.yes)}}function mm(e){return{ctx:e,emitted:!1,npmVisibilityTimeout:0,report:{mode:"release",npmTag:ye,packages:[],stones:[]},warnings:[]}}function Tn(e){if(e){let n=()=>{return};return{info:n,note:n,start:n,step:n,stop:n,warn:n}}let t=Ve();return{info:(n)=>P.info(n),note:(n,r)=>te(n,r),start:(n)=>t.start(n),step:(n)=>P.step(n),stop:(n)=>t.stop(n),warn:(n)=>P.warn(n)}}function Oe(e,t){if(e.warnings.push(t),!e.ctx.json)P.warn(d.yellow(t))}function ev(e,t,n={}){let{ctx:r,report:s}=e;return Ud({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??r.args.tags??(r.config.failure?!1:r.config.get("release").tags),warnings:e.warnings,...n})}function Ae(e,t,n={}){e.emitted=!0,e.ctx.output.result(ev(e,t,n))}function Pi(e,t,n){if(n.length===0){t.info(d.yellow("Dry run complete - no changes made")),Ae(e,"planned");return}let r=n.map((s)=>` ${s.message}${s.hint?`
239
245
  ${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(`
246
+ ${r.join(`
247
+ `)}`),Ae(e,"blocked",{blockers:n}),ZP}async function vi(e,t){if(e.args.yes)return!0;if(!Le(e)){let n=e.json?"--json":"A non-interactive release";throw new N(`${n} requires --yes`,QP)}return G({initialValue:!0,message:t})}function Si(e,t,n){if(!n)return ye;let r=e.ctx.config.get("tag");try{return Wt(t,r)}catch(s){return Oe(e,`Npm publication would fail: ${s instanceof Error?s.message:String(s)}`),ei(r)}}import{rm as tv}from"fs/promises";async function fm(e,t,n,r,s,i){let{config:o}=e.ctx,a=new Ue(o,i,It(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 gm();await a.preflight(r,s);let f=t;try{if(await a.initializeExternalRelease(r,s,!1),e.report.ledger=a.getLedgerSnapshot()??void 0,f.start("Updating package versions..."),await a.updatePackageVersions(r),f.stop("Package versions updated"),i.changelog)f.start("Generating changelogs..."),await a.generateChangelogs(s,r),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(n,r,s),e.report.releaseCommit=await gm(),f.stop("Release commit created");if(i.tags)f.start("Creating git tags..."),await a.createGitTags(r),f.stop("Git tags created");if(await a.finalizeExternalRelease(r,s),i.npm)f.start("Preparing NPM packages..."),await a.prepareNpmPublish(r),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(r),f.stop("Published to NPM");if(i.createRelease)f.start("Creating release..."),await a.createGitRelease(s,r),f.stop("Release created");await a.completeRelease(),e.report.ledger=a.getLedgerSnapshot()??e.report.ledger,await Ci(e,f),f.note(`Released ${d.bold(String(r.length))} package(s)
248
+ Run ${d.green(`${T} check`)} to verify`,d.green("Release complete")),Ae(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 tv(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 Ci(e,t){let n=e.report.ledger;if(!n?.options.npm||e.npmVisibilityTimeout===0)return;t.start("Checking npm registry visibility...");try{e.report.npmVisibility=await Da(n,e.npmVisibilityTimeout),t.stop("Npm registry visibility checked")}catch(r){t.stop("Npm registry visibility check failed"),Oe(e,`Could not check npm registry visibility: ${r instanceof Error?r.message:String(r)}`);return}for(let r of Ma(e.report.npmVisibility,e.npmVisibilityTimeout))Oe(e,r)}async function gm(){let e=await Bun.$`git rev-parse HEAD`.quiet().nothrow();return e.exitCode===0?e.stdout.toString().trim():""}var hm=/\d{14}$/,In="Recreate the release PR before publishing";function Va(e){return e.filter(([t])=>t).map(([,t])=>t)}function ym(e){let{args:t}=e;if(t.abort){let r=Va([[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(r.length>0)throw new u(`--abort cannot be combined with ${r.join(", ")}`,"Abort discards the incomplete release recorded in the recovery ledger");return}if(t.resume){let r=Va([[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(r.length>0)throw new u(`--resume cannot be combined with ${r.join(", ")}`,"Resume uses the operation settings recorded in the active release ledger");return}if(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 n=Va([[t.changelog!==void 0,"--changelog"],[t.noCommit,"--no-commit"],[t.preview,"--preview"],[t.push!==void 0,"--push"]]);if(n.length>0)throw new u(`--publish-only cannot be combined with ${n.join(", ")}`,"Publish-only supports --create-release, --dry-run, --npm, --tags, and --yes")}async function wm(e){let{ctx:t}=e;await Ue.assertNoActiveRelease();let n=t.config.get("currentRelease");if(!n)throw new u("No currentRelease found in config",`Run \`${T} actions release-pr\` first to prepare a release`);if(await Os(...nr(t.config))!==n.sourceHash)throw new u("Current checkout does not match the prepared release source",In);let s=await new B(t.config).getReleasedStones(n.timestamp,n.stoneIds).catch((y)=>{throw new u(y instanceof Error?y.message:String(y),In)});if(s.length===0)throw new u("No archived stones found for currentRelease",In);if(_s({packages:n.packages,sourceHash:n.sourceHash,stoneIds:n.stoneIds,timestamp:n.timestamp},s.map((y)=>y.toJson()))!==n.planHash)throw new u("Prepared release plan has changed",In);let o=Object.entries(n.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))}rv(t,s,n.packages,c);let l=Tn(t.json),{cycle:p,ordered:m}=dn(c);if(p.length>0)Oe(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: ${n.timestamp}`)),l.info(d.dim(`Stones: ${n.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=Si(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 Ue(t.config,{...h,changelog:!1,push:!1},It(t));if(h.dryRun){l.info(d.yellow("[dry-run] Would publish packages"));let y=await f.inspectPreflight(m,s,{publishOnly:!0});return Pi(e,l,y)}if(!await vi(t,"Proceed with publishing?"))return;await nv(e,l,f,m,s,h);return}async function nv(e,t,n,r,s,i){let o=t;await n.preflight(r,s,{publishOnly:!0});try{if(await n.initializeExternalRelease(r,s,!0),e.report.ledger=n.getLedgerSnapshot()??void 0,i.tags)o.start("Creating git tags..."),await n.createGitTags(r),o.stop("Git tags created");if(await n.finalizeExternalRelease(r,s),i.npm)o.start("Preparing NPM packages..."),await n.prepareNpmPublish(r),o.stop("NPM packages prepared");if(await n.markExternalReleaseReady(),i.tags)o.start("Pushing git tags..."),await n.pushRelease(),o.stop("Git tags pushed");if(i.npm)o.start("Publishing to NPM..."),await n.publishToNpm(r),o.stop("Published to NPM");if(i.createRelease)o.start("Creating release..."),await n.createGitRelease(s,r),o.stop("Release created");await n.completeRelease(),e.report.ledger=n.getLedgerSnapshot()??e.report.ledger,await Ci(e,o),o.note(`Published ${d.bold(String(r.length))} package(s)
249
+ Run ${d.green(`${T} check`)} to verify`,d.green("Publish complete")),Ae(e,"completed")}catch(a){if(e.report.ledger=n.getLedgerSnapshot()??e.report.ledger,n.hasCrossedIrreversibleBoundary())throw o.stop("Publish incomplete, local state preserved"),n.createIncompleteReleaseError(a);o.stop("Publish failed");try{await n.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 bm(e){let t=await Ue.abort(It(e.ctx)),{commitDiscarded:n,deletedTags:r}=t;e.report={ledger:t.ledger,mode:"abort",npmTag:ye,packages:[],stones:[]};for(let s of t.warnings)Oe(e,s);if(!e.ctx.json){let s=[n?"the release commit":void 0,r.length>0?`tags ${r.join(", ")}`:void 0].filter((i)=>i!==void 0);P.info(s.length>0?`Release ${t.ledger.id} abandoned; discarded ${s.join(" and ")}`:`Release ${t.ledger.id} abandoned`)}Ae(e,"aborted",{abort:{commitDiscarded:n,deletedTags:r}})}async function Rm(e){let{ctx:t}=e,{ledger:n,packages:r,stones:s}=await Ue.resume(t.config,It(t));if(e.report={ledger:n??void 0,mode:"resume",npmTag:n?.options.npmTag??ye,packages:r,stones:s,tagsEnabled:n?.options.tags??!1},await Ci(e,Tn(t.json)),!t.json)te(`Released ${d.bold(String(r.length))} package(s)
250
+ Run ${d.green(`${T} check`)} to verify`,d.green("Release resumed"));Ae(e,"completed")}function rv(e,t,n,r){let s=O.mergeAll(t),i=Object.keys(n).sort(),o=[...new Set(s.allPackages)].sort();if(JSON.stringify(i)!==JSON.stringify(o))throw new u("Archived stones do not match currentRelease packages",In);let a=z.applyStone(s,new Map(r.map((c)=>[c.name,c])),pe(e.config).kinds);for(let c of a){let l=n[c.name]?.newVersion,p=c.bump==="snapshot"?c.newVersion?.replace(hm,""):c.newVersion,m=c.bump==="snapshot"?l?.replace(hm,""):l;if(p!==m)throw new u(`Archived stones do not produce ${c.name}@${l??"missing"}`,In)}}var av="Pending stones reference only ignored packages",$m=M({name:"roll",description:"Execute a release from pending stones",args:dm,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=mm(e);try{return await cv(t)}catch(n){if(e.json&&!t.emitted)t.report.ledger??=(await ge.loadActive().catch(()=>null))?.data,Ae(t,"failed",{error:n});throw n}}});async function cv(e){let{ctx:t}=e;if(ym(t),t.args.abort){e.report.mode="abort",await bm(e);return}if(e.npmVisibilityTimeout=La(t.config.get("release").npmVisibilityTimeout),t.args.resume){e.report.mode="resume",await Rm(e);return}if(t.args.publishOnly)return e.report.mode="publish-only",wm(e);await Ue.assertNoActiveRelease();let n=gv(t),r=await new B(t.config).list();if(r.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}=En(r,i);if(o.length>0)Oe(e,`Excluded by config.ignore: ${o.join(", ")}`);let c=O.mergeAll(a),l=xr(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=lv(e,z.applyStone(c,s,pe(t.config).kinds)),m=n.dryRun?"dry-run":t.args.preview?"preview":"release";if(p.length===0){Oe(e,av),e.report={mode:m,npmTag:ye,packages:[],stones:r,tagsEnabled:n.tags},Ae(e,"planned");return}if(e.report={mode:m,npmTag:ye,packages:p,stones:r,tagsEnabled:n.tags},e.report.npmTag=Si(e,p,n.npm),t.args.preview){await uv(e,r,p);return}let g=Tn(t.json);if(fv(g,c,p,n),n.dryRun){let h=new Ue(t.config,n,It(t));return Pi(e,g,await h.inspectPreflight(p,r))}if(!await vi(t,"Proceed with release?"))return;await fm(e,g,c,p,r,n);return}function lv(e,t){let{kept:n,skipped:r}=Pu(t,e.ctx.config.get("ignore")??[]);if(r.length>0)Oe(e,`Excluded by config.ignore: ${r.join(", ")}`);let{cycle:s,ordered:i}=dn(n);if(s.length>0)Oe(e,`Dependency cycle between ${s.join(", ")}; publish order may not satisfy every pin`);return i}async function uv(e,t,n){let{ctx:r}=e,s=r.config.get("changelog"),i=un(r.config),o=Tn(r.json);o.start("Generating changelog preview..."),await i.generate(t,n),o.stop("Changelog preview generated");let a=n.map((l)=>ov(iv(l.file),s.filename));if(s.root)a.push(s.filename);let c=await pv(r,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"));Ae(e,"previewed",{preview:c})}async function pv(e,t,n){let r=[];for(let s of n){let i=await dv(s);if(i!==null)r.push({content:i,file:s})}return t.info(`
245
251
  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":""}`}
252
+ ${n.map((s)=>d.dim(` ${s}`)).join(`
253
+ `)}`),t.info(""),{changelogs:r,kept:await mv(e)}}async function dv(e){try{return await sv(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function mv(e){if(e.args.keep)return!0;if(e.args.yes||!Le(e))return!1;return!await G({initialValue:!0,message:"Revert changes?"})}function gv(e){let t=e.config.get("release"),n=e.config.get("changelog"),r=!e.args.noCommit;if(!r){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??n.generate,commit:r,createRelease:r?e.args.createRelease??t.createRelease:!1,dryRun:e.args.dryRun??!1,npm:e.args.npm??t.npm,push:r?e.args.push??t.push:!1,tags:r?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 fv(e,t,n,r){let s=[];if(r.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 n)s.push(` ${i.label}`);s.push("",d.dim(`Changelog: ${r.changelog?"yes":"no"}`),d.dim(`Git tags: ${r.tags?"yes":"no"}`),d.dim(`NPM publish: ${r.npm?"yes":"no"}`),d.dim(`Push to remote: ${r.push?"yes":"no"}`),d.dim(`Create release: ${r.createRelease?"yes":"no"}`)),e.step(s.join(`
254
+ `))}function Ze(e){return qd(e,T),new B(e)}async function An(e,t,n,r){if(r)return hv(e,n);if(!t)throw new u("Stone ID is required",`Usage: ${T} stone ${e} <id>`);let s=await n.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 hv(e,t){let n=await t.list();if(n.length===0)throw new u("No pending stones found");let r=n.map((s)=>({label:`${s.id} - ${s.message}`,value:s}));return _t({message:`Select a stone to ${e}`,options:r})}var Pm=M({name:"delete",description:"Delete a pending stone",positionals:Pe({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=Ze(e.config),n=await An("delete",e.positionals.id,t,e.interactive);if(e.interactive&&!await G({initialValue:!1,message:`Delete stone '${n.id}'?`}))return;await t.delete(n.id),P.success(`Stone '${d.bold(n.id)}' deleted`),e.output.result({deleted:!0,id:n.id})}});var vm=M({name:"edit",description:"Edit a pending stone",args:q({message:{alias:"m",description:"New commit message",type:"string"}}),positionals:Pe({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=Ze(e.config),n=await An("edit",e.positionals.id,t,e.interactive),r=await yv(e.args.message,e.interactive,n.message);await t.save(n.withMessage(r)),P.success(`Updated commit message for stone '${d.bold(n.id)}'`),e.output.result({id:n.id,message:r})}});async function yv(e,t,n){if(e)return e;if(!t)throw new u("--message is required in non-interactive mode");return $e({initialValue:n,message:"Commit message",placeholder:n})}var Sm=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=Ze(e.config),n=await t.list(),r=n.map((s)=>({path:t.getFilePath(s.id),...s.toJson()}));e.output.result(r,()=>wv(n,e.args.verbose))}});function wv(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
255
 
250
- ${e.map((n)=>F$(n,t)).join(`
256
+ ${e.map((r)=>bv(r,t)).join(`
251
257
 
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();
258
+ `)}`}function bv(e,t){let n=[`${d.dim("-")} ${d.bold(e.id)}`,` ${d.dim("Message:")} ${e.message}`];if(e.tag)n.push(` ${d.dim("Tag:")} ${d.cyan(e.tag)}`);if(e.major.length)n.push(` ${d.red("Major:")} ${e.major.join(", ")}`);if(e.minor.length)n.push(` ${d.yellow("Minor:")} ${e.minor.join(", ")}`);if(e.patch.length)n.push(` ${d.green("Patch:")} ${e.patch.join(", ")}`);if(t&&e.description){n.push(` ${d.dim("Description:")}`);for(let r of e.description.split(`
259
+ `))n.push(` ${d.dim(r)}`)}return n.join(`
260
+ `)}var Ha=2,Cm=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:Pe({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=Ze(e.config),n=await Rv(t,e.positionals.ids,e.interactive),r=await $v(e.args.message,e.interactive),{stone:s,conflicts:i,errors:o}=O.merge(n,r);if(o.length>0)throw new u("Selected stones cannot be merged",o.join(`
261
+ `));await t.save(s);let a=await Pv(e.args.delete,e.interactive);if(a)await t.deleteMany(n.map((c)=>c.id));Sv(s.id,i),e.output.result({conflicts:i,deleted:a,id:s.id,mergedFrom:n.map((c)=>c.id)})}});async function Rv(e,t,n){let r=await e.list();if(r.length<Ha)throw new u("Need at least 2 stones to merge");if(n)return vv(r);if(t.length<Ha)throw new u("Need at least 2 stone IDs",`Usage: ${T} stone merge <id1> <id2> [...] -m "message"`);let s=r.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 $v(e,t){if(e)return e;if(!t)throw new u("--message is required in non-interactive mode");return $e({message:"Commit message for merged stone",placeholder:"feat: combined changes"})}async function Pv(e,t){if(e)return!0;return t?G({initialValue:!1,message:"Delete original stones?"}):!1}async function vv(e){let t=e.map((r)=>({label:`${r.id} - ${r.message}`,value:r})),n=await nt({message:"Select stones to merge (at least 2)",options:t,required:!0});if(n.length<Ha)throw new u("Need to select at least 2 stones");return n}function Sv(e,t){if(P.success(`Created merged stone: ${d.bold(e)}`),t.length===0)return;te(`Resolved ${t.length} package conflict(s) using highest bump type:
262
+ `+t.map((n)=>` ${d.dim("-")} ${n}`).join(`
263
+ `),d.yellow("Conflicts resolved"))}var Cv=40,km=M({name:"show",description:"Show details of a specific stone",positionals:Pe({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=Ze(e.config),n=await An("show",e.positionals.id,t,e.interactive),r=t.getFilePath(n.id);e.output.result({path:r,...n.toJson()},()=>kv(n,r))}});function kv(e,t){let n=[d.bold(`Stone: ${e.id}`),d.dim(`Path: ${t}`),d.dim("-".repeat(Cv)),"",`${d.dim("Message:")} ${e.message}`];if(e.tag)n.push(`${d.dim("Tag:")} ${d.cyan(e.tag)}`);if(e.description)n.push(`${d.dim("Description:")} ${e.description}`);n.push("");let r=[{bump:"major",packages:e.major},{bump:"minor",packages:e.minor},{bump:"patch",packages:e.patch},{bump:"dependency",packages:e.dependency},{bump:"snapshot",packages:e.snapshot}];for(let{bump:s,packages:i}of r)if(i.length>0)n.push(`${cn[s](s)}: ${i.join(", ")}`);return n.join(`
264
+ `)}var xm=M({name:"stone",description:"Manage version stones",subcommands:[Sm,km,Pm,vm,Cm]});var xv=Pe({message:{description:"Stone message (commit message)"},description:{description:"Stone description (optional details)"}}),Ev=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"}}),Em=M({name:"version",description:"Create a new version stone",args:Ev,positionals:xv,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=Tv(e);if(Ov(e,t),!e.args.fromCommits)_v(e,t);let n=e.args.fromCommits?await Fv(e,t):e.interactive&&!t.hasManualSelection?await Lv(e,t):await Dv(e,t);e.output.result({dryRun:e.args.dryRun,stones:n})}});function Tv(e){let t=e.args.major!==void 0||e.args.minor!==void 0||e.args.patch!==void 0,n={major:qa(e.args.major,"--major"),minor:qa(e.args.minor,"--minor"),patch:qa(e.args.patch,"--patch")};Av(n);let r=e.positionals.message!==void 0,s=e.args.message!==void 0;if(r&&s)throw new u("Message cannot be provided both positionally and with --message");let i=r?e.positionals.message:e.args.message,o=ki(e.args.bump,"--bump"),a=ki(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:ki(i,"Message"),packageSelection:n,packageSelectionSupplied:t,tag:Iv(e.args.tag)}}function ki(e,t){if(e===void 0)return;let n=e.trim();if(!n)throw new u(`${t} cannot be empty`);return n}function Iv(e){let t=ki(e,"--tag");if(t===void 0)return;return Nt(t,"--tag must be a supported prerelease identifier")}function qa(e,t){if(e===void 0)return[];let n=e.split(",").map((r)=>r.trim());if(n.some((r)=>!r))throw new u(`${t} must contain one or more non-empty package names`);return[...new Set(n)]}function Av(e){let t=new Map,n=[["major",e.major],["minor",e.minor],["patch",e.patch]];for(let[r,s]of n)for(let i of s){let o=t.get(i);if(o)throw new u(`Package "${i}" cannot be assigned to both --${o} and --${r}`);t.set(i,r)}}function Ov(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 _v(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 Wa(e,t){let n=await U.scan({filter:t,single:e.config.get("single")}),r=e.config.get("ignore")??[],s=n.packageNames.filter((i)=>!se(i,r));if(s.length===0)throw new u("No packages found matching the criteria");return{packageNames:s,packages:n.packages}}async function Lv(e,t){let{packages:n,packageNames:r}=await Wa(e,t.filter),s=await Bv(n,r,t.tag),i=t.message??await Tm(),o=t.description??await Vv(),a=Im({ctx:e,description:o,message:i,packages:n,selection:s,tag:t.tag});return Am(e,a,n)}async function Dv(e,t){let n=t.message??(e.interactive?await Tm():void 0);if(!n)throw new u("Message is required",'Pass --message "..." or a positional message');let{packages:r,packageNames:s}=await Wa(e,t.filter),i=Mv(e,t,s);jv(i,r,s,e.config.get("ignore")??[],t.filter);let o=Im({ctx:e,description:t.description,message:n,packages:r,selection:i,tag:t.tag});return Am(e,o,r)}function Mv(e,t,n){let r=t.bump;if(!r)return Nv(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=[...n];if(r==="major")return{major:s,minor:[],patch:[]};if(r==="minor")return{major:[],minor:s,patch:[]};return{major:[],minor:[],patch:s}}function Nv(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 jv(e,t,n,r,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,r));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(n),l=i.filter((p)=>!c.has(p));if(l.length>0)throw new u(`Packages do not match --filter "${s}": ${l.join(", ")}`)}async function Fv(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 r=await new Ft(e.config).analyze({filter:t.filter,single:e.config.get("single")});if(r.length===0)return P.info("No conventional commits found since last release"),[];let{packages:s}=await Wa(e,t.filter);P.info(`Found ${d.bold(String(r.length))} commit group(s) to process`);let i=new B(e.config),o=[];for(let a of r){let c=Ft.buildStoneData(a,s,pe(e.config,t.tag));if(e.args.dryRun)Om(e,c,s),o.push({...c});else{let l=await i.create(c);o.push({...c,id:l.id}),P.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.
265
+ Run ${d.green(`${T} check`)} to see what will be released.`,d.green("Success"));return o}async function Bv(e,t,n){let r=[],s={major:[],minor:[],patch:[]};for(let i of["major","minor","patch"]){let o=t.filter((c)=>!r.includes(c));if(o.length===0)break;let a=await Uv(i,o,e,n);if(r.push(...a),i==="major")s.major=a;else if(i==="minor")s.minor=a;else s.patch=a}if(r.length===0)throw new u("No packages selected");return s}async function Uv(e,t,n,r){let s=cn[e],i=t.map((o)=>{let a=n.get(o);return{label:a?Gv(a,e,r):o,value:o}});return nt({message:`Select packages for ${d.bold(s(e))} bump`,options:i,required:!1})}function Gv(e,t,n){try{return e.withBump(t,n).label}catch(r){if(r instanceof u)return e.name;throw r}}async function Tm(){return(await $e({message:"Stone message (used as commit message)",placeholder:"feat: add new feature",validate:(t)=>t?.trim()?void 0:"Message is required"})).trim()}async function Vv(){return(await $e({message:"Description (optional, press enter to skip)",placeholder:"Additional details about this change..."}))?.trim()||void 0}function Im(e){let{ctx:t,selection:n,message:r,packages:s,tag:i,description:o}=e,a=[...n.major.map((l)=>({bump:"major",name:l})),...n.minor.map((l)=>({bump:"minor",name:l})),...n.patch.map((l)=>({bump:"patch",name:l}))],c=Rt(a,s,pe(t.config,i));return{dependency:X(c),description:o,major:X(n.major),message:r,minor:X(n.minor),patch:X(n.patch),tag:i}}async function Am(e,t,n){if(Om(e,t,n),e.args.dryRun)return[{...t}];if(!e.args.yes&&e.interactive&&!await G({initialValue:!0,message:"Create this stone?"}))return[];let r=await new B(e.config).create(t);return te(`Run ${d.green(`${T} roll`)} to release packages
266
+ or create another stone with ${d.green(`${T} version`)}`,`Stone ${d.bold(r.id)} ${d.green("created")}`),[{...t,id:r.id}]}function Om(e,t,n){let r=[];if(e.args.dryRun)r.push(d.bold(d.yellow("[dry-run]")));if(r.push(`${d.dim("Stone:")} ${d.bold(t.message)}`),t.tag)r.push(`${d.dim("Tag:")} ${t.tag}`);for(let s of Hv(e,t,n))r.push(` ${s}`);P.step(r.join(`
267
+ `))}function Hv(e,t,n){let r=O.create(t);try{return z.applyStone(r,n,pe(e.config).kinds).map((s)=>s.label)}catch(s){if(s instanceof u)return r.allPackages.filter((i)=>n.has(i));throw s}}var qv=[em,nm,om,lm,pm,$m,xm,Em];function _m(e=$i()){return io({bin:T,commands:qv,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:Dl})}_m().main();