@r5n/sisyphus 0.4.7 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -201
- package/README.md +147 -365
- package/dist/cli.js +201 -219
- package/dist/templates/github/sis-create-stone.yml +88 -0
- package/dist/templates/github/sis-release.yml +30 -0
- package/dist/templates/gitlab/sis-create-stone.yml +49 -0
- package/dist/templates/gitlab/sis-release.yml +13 -0
- package/package.json +6 -12
- package/schema.json +0 -112
package/dist/cli.js
CHANGED
|
@@ -1,227 +1,209 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
`).
|
|
5
|
-
`)
|
|
6
|
-
`)
|
|
7
|
-
`),i=
|
|
8
|
-
`),s=
|
|
9
|
-
`),
|
|
10
|
-
`).length
|
|
11
|
-
`)
|
|
12
|
-
`).
|
|
13
|
-
`)
|
|
14
|
-
`)
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
`,`
|
|
18
|
-
|
|
19
|
-
`).
|
|
20
|
-
`)
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
`)
|
|
32
|
-
`)
|
|
33
|
-
${
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
${
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
`).
|
|
41
|
-
|
|
42
|
-
${
|
|
43
|
-
|
|
44
|
-
`
|
|
45
|
-
${e}`
|
|
46
|
-
${
|
|
47
|
-
|
|
48
|
-
`)
|
|
49
|
-
`).
|
|
50
|
-
`);i.write(`${b.default.gray(T)}
|
|
51
|
-
${b.default.green(mo)} ${b.default.reset(o)} ${b.default.gray(ii.repeat(Math.max(a-e-1,1))+Lt)}
|
|
52
|
-
${c}
|
|
53
|
-
${b.default.gray(Dt+ii.repeat(a+2)+Nt)}
|
|
54
|
-
`)},se,Sn=({indicator:n="dots",onCancel:o,output:r=process.stdout,cancelMessage:i,errorMessage:s,frames:t=sr?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:e=sr?80:120,signal:a,...c}={})=>{let u=Tt(),m,g,d=!1,w=!1,p="",f,h=performance.now(),x=co(r),S=c?.styleFrame??se,I=(k)=>{let Q=k>1?s??ln.messages.error:i??ln.messages.cancel;w=k===1,d&&(On(Q,k),w&&typeof o=="function"&&o())},j=()=>I(2),R=()=>I(1),P=()=>{process.on("uncaughtExceptionMonitor",j),process.on("unhandledRejection",j),process.on("SIGINT",R),process.on("SIGTERM",R),process.on("exit",I),a&&a.addEventListener("abort",R)},v=()=>{process.removeListener("uncaughtExceptionMonitor",j),process.removeListener("unhandledRejection",j),process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R),process.removeListener("exit",I),a&&a.removeEventListener("abort",R)},E=()=>{if(f===void 0)return;u&&r.write(`
|
|
55
|
-
`);let k=zn(f,x,{hard:!0,trim:!1}).split(`
|
|
56
|
-
`);k.length>1&&r.write(qn.cursor.up(k.length-1)),r.write(qn.cursor.to(0)),r.write(qn.erase.down())},H=(k)=>k.replace(/\.+$/,""),z=(k)=>{let Q=(performance.now()-k)/1000,rn=Math.floor(Q/60),_n=Math.floor(Q%60);return rn>0?`[${rn}m ${_n}s]`:`[${_n}s]`},W=(k="")=>{d=!0,m=Xr({output:r}),p=H(k),h=performance.now(),r.write(`${b.default.gray(T)}
|
|
57
|
-
`);let Q=0,rn=0;P(),g=setInterval(()=>{if(u&&p===f)return;E(),f=p;let _n=S(t[Q]),no;if(u)no=`${_n} ${p}...`;else if(n==="timer")no=`${_n} ${p} ${z(h)}`;else{let Ks=".".repeat(Math.floor(rn)).slice(0,3);no=`${_n} ${p}${Ks}`}let Fs=zn(no,x,{hard:!0,trim:!1});r.write(Fs),Q=Q+1<t.length?Q+1:0,rn=rn<4?rn+0.125:0},e)},On=(k="",Q=0)=>{if(!d)return;d=!1,clearInterval(g),E();let rn=Q===0?b.default.green(mo):Q===1?b.default.red(ai):b.default.red(ci);p=k??p,n==="timer"?r.write(`${rn} ${p} ${z(h)}
|
|
58
|
-
`):r.write(`${rn} ${p}
|
|
59
|
-
`),v(),m()};return{start:W,stop:On,message:(k="")=>{p=H(k??p)},get isCancelled(){return w}}},Eu,nn=(n)=>{let o=(r,i)=>{let s=r.label??String(r.value);switch(i){case"disabled":return`${b.default.gray(fo)} ${b.default.gray(s)}${r.hint?` ${b.default.dim(`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${b.default.dim(s)}`;case"active":return`${b.default.green(tr)} ${s}${r.hint?` ${b.default.dim(`(${r.hint})`)}`:""}`;case"cancelled":return`${b.default.strikethrough(b.default.dim(s))}`;default:return`${b.default.dim(fo)} ${b.default.dim(s)}`}};return new Qo({options:n.options,signal:n.signal,input:n.input,output:n.output,initialValue:n.initialValue,render(){let r=`${b.default.gray(T)}
|
|
60
|
-
${go(this.state)} ${n.message}
|
|
61
|
-
`;switch(this.state){case"submit":return`${r}${b.default.gray(T)} ${o(this.options[this.cursor],"selected")}`;case"cancel":return`${r}${b.default.gray(T)} ${o(this.options[this.cursor],"cancelled")}
|
|
62
|
-
${b.default.gray(T)}`;default:{let i=`${b.default.cyan(T)} `;return`${r}${i}${er({output:n.output,cursor:this.cursor,options:this.options,maxItems:n.maxItems,columnPadding:i.length,style:(s,t)=>o(s,s.disabled?"disabled":t?"active":"inactive")}).join(`
|
|
63
|
-
${i}`)}
|
|
64
|
-
${b.default.cyan(mn)}
|
|
65
|
-
`}}}}).prompt()},Cu,J=(n)=>new Vo({validate:n.validate,placeholder:n.placeholder,defaultValue:n.defaultValue,initialValue:n.initialValue,output:n.output,signal:n.signal,input:n.input,render(){let o=`${b.default.gray(T)}
|
|
66
|
-
${go(this.state)} ${n.message}
|
|
67
|
-
`,r=n.placeholder?b.default.inverse(n.placeholder[0])+b.default.dim(n.placeholder.slice(1)):b.default.inverse(b.default.hidden("_")),i=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"error":{let t=this.error?` ${b.default.yellow(this.error)}`:"";return`${o.trim()}
|
|
68
|
-
${b.default.yellow(T)} ${i}
|
|
69
|
-
${b.default.yellow(mn)}${t}
|
|
70
|
-
`}case"submit":{let t=s?` ${b.default.dim(s)}`:"";return`${o}${b.default.gray(T)}${t}`}case"cancel":{let t=s?` ${b.default.strikethrough(b.default.dim(s))}`:"";return`${o}${b.default.gray(T)}${t}${s.trim()?`
|
|
71
|
-
${b.default.gray(T)}`:""}`}default:return`${o}${b.default.cyan(T)} ${i}
|
|
72
|
-
${b.default.cyan(mn)}
|
|
73
|
-
`}}}).prompt();var N=A(()=>{nr();nr();b=bn(Uo(),1),qn=bn(zo(),1);sr=_t(),Bt=M("\u25C6","*"),ai=M("\u25A0","x"),ci=M("\u25B2","x"),mo=M("\u25C7","o"),At=M("\u250C","T"),T=M("\u2502","|"),mn=M("\u2514","\u2014"),$u=M("\u2510","T"),Su=M("\u2518","\u2014"),tr=M("\u25CF",">"),fo=M("\u25CB"," "),Mt=M("\u25FB","[\u2022]"),oi=M("\u25FC","[+]"),ri=M("\u25FB","[ ]"),vu=M("\u25AA","\u2022"),ii=M("\u2500","-"),Lt=M("\u256E","+"),Dt=M("\u251C","+"),Nt=M("\u256F","+"),ju=M("\u2570","+"),Ru=M("\u256D","+"),Gt=M("\u25CF","\u2022"),Ht=M("\u25C6","*"),Ut=M("\u25B2","!"),qt=M("\u25A0","x"),or=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,uo=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,po=/\t{1,1000}/y,rr=/[\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,lo=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Yt=/\p{M}+/gu,Wt={limit:1/0,ellipsis:""},Ft={limit:1/0,ellipsis:"",ellipsisWidth:0},cr=`${Xt}8;;`,si=new RegExp(`(?:\\${li}(?<code>\\d+)m|\\${cr}(?<uri>.*)${ar})`,"y");$={message:(n=[],{symbol:o=b.default.gray(T),secondarySymbol:r=b.default.gray(T),output:i=process.stdout,spacing:s=1}={})=>{let t=[];for(let a=0;a<s;a++)t.push(`${r}`);let e=Array.isArray(n)?n:n.split(`
|
|
74
|
-
`);if(e.length>0){let[a,...c]=e;a.length>0?t.push(`${o} ${a}`):t.push(o);for(let u of c)u.length>0?t.push(`${r} ${u}`):t.push(r)}i.write(`${t.join(`
|
|
75
|
-
`)}
|
|
76
|
-
`)},info:(n,o)=>{$.message(n,{...o,symbol:b.default.blue(Gt)})},success:(n,o)=>{$.message(n,{...o,symbol:b.default.green(Ht)})},step:(n,o)=>{$.message(n,{...o,symbol:b.default.green(mo)})},warn:(n,o)=>{$.message(n,{...o,symbol:b.default.yellow(Ut)})},warning:(n,o)=>{$.warn(n,o)},error:(n,o)=>{$.message(n,{...o,symbol:b.default.red(qt)})}},se=b.default.magenta,Eu={light:M("\u2500","-"),heavy:M("\u2501","="),block:M("\u2588","#")},Cu=`${b.default.gray(T)} `});function gi(n,o){let r=te[n]||"Unknown error";return o?`${r}: ${o}`:r}var te;var pr=A(()=>{te={"core.auth.failed":"Authentication failed","core.auth.invalid_token":"Token is invalid or expired","core.fs.cannot_read":"Cannot read file","core.fs.cannot_write":"Cannot write to file","core.fs.directory_not_found":"Directory not found","core.fs.file_not_found":"File not found","core.git.dirty_working_dir":"Working directory has uncommitted changes","core.git.no_commits":"No commits found","core.git.not_repository":"Not a git repository","core.git.operation_failed":"Git operation failed","core.invalid_argument":"Invalid argument","core.invalid_config":"Invalid configuration","core.network.request_failed":"Network request failed","core.operation_cancelled":"Operation cancelled","core.operation_failed":"Operation failed","core.permission_denied":"Permission denied"}});function hi(n={}){let{errorPrefix:o="\u2717"}=n;return function(i){if(sn(i))Tn.info("Operation cancelled"),process.exit(0);if(i instanceof K){if(Tn.error(`${o} ${i.message}`),i.code)Tn.error(` Error code: ${i.code}`)}else if(i instanceof Error)Tn.error(`${o} ${i.message}`);else Tn.error(`${o} An unexpected error occurred`),Tn.error(String(i));process.exit(1)}}var Tn,K;var di=A(()=>{N();_();pr();Tn=C({prefix:"cli-core"}).child("error");K=class K extends Error{code;context;constructor(n,o,r){let i=n.includes(".")&&!n.includes(" ")?gi(n,r):n;super(i);this.code=o;this.context=r;this.name="CLIError"}}});var pn,ee=(n,o)=>{let r=n.length,i=o.length,s=1<<r-1,t=-1,e=0,a=r,c=r;while(c--)pn[n.charCodeAt(c)]|=1<<c;for(c=0;c<i;c++){let u=pn[o.charCodeAt(c)],m=u|e;if(u|=(u&t)+t^t,e|=~(u|t),t&=u,e&s)a++;if(t&s)a--;e=e<<1|1,t=t<<1|~(m|e),e&=m}c=r;while(c--)pn[n.charCodeAt(c)]=0;return a},ae=(n,o)=>{let r=o.length,i=n.length,s=[],t=[],e=Math.ceil(r/32),a=Math.ceil(i/32);for(let p=0;p<e;p++)t[p]=-1,s[p]=0;let c=0;for(;c<a-1;c++){let p=0,f=-1,h=c*32,x=Math.min(32,i)+h;for(let S=h;S<x;S++)pn[n.charCodeAt(S)]|=1<<S;for(let S=0;S<r;S++){let I=pn[o.charCodeAt(S)],j=t[S/32|0]>>>S&1,R=s[S/32|0]>>>S&1,P=I|p,v=((I|R)&f)+f^f|I|R,E=p|~(v|f),H=f&v;if(E>>>31^j)t[S/32|0]^=1<<S;if(H>>>31^R)s[S/32|0]^=1<<S;E=E<<1|j,H=H<<1|R,f=H|~(P|E),p=E&P}for(let S=h;S<x;S++)pn[n.charCodeAt(S)]=0}let u=0,m=-1,g=c*32,d=Math.min(32,i-g)+g;for(let p=g;p<d;p++)pn[n.charCodeAt(p)]|=1<<p;let w=i;for(let p=0;p<r;p++){let f=pn[o.charCodeAt(p)],h=t[p/32|0]>>>p&1,x=s[p/32|0]>>>p&1,S=f|u,I=((f|x)&m)+m^m|f|x,j=u|~(I|m),R=m&I;if(w+=j>>>i-1&1,w-=R>>>i-1&1,j>>>31^h)t[p/32|0]^=1<<p;if(R>>>31^x)s[p/32|0]^=1<<p;j=j<<1|h,R=R<<1|x,m=R|~(S|j),u=j&S}for(let p=g;p<d;p++)pn[n.charCodeAt(p)]=0;return w},yi=(n,o)=>{if(n.length<o.length){let r=o;o=n,n=r}if(o.length===0)return n.length;if(n.length<=32)return ee(n,o);return ae(n,o)};var bi=A(()=>{pn=new Uint32Array(65536)});function yo(n,o,r=pe){let i=o.map((t)=>({distance:yi(n.toLowerCase(),t.toLowerCase()),option:t})),s=Math.max(ue,n.length*ce);return i.filter(({distance:t})=>t<=s).sort((t,e)=>t.distance-e.distance).slice(0,r).map(({option:t})=>t)}function bo(n,o){return o[n.toLowerCase()]||null}var ce=0.5,ue=3,pe=3;var wi=A(()=>{bi()});async function lr(n,o={}){let{fallback:r,logLevel:i="warn",message:s="Operation failed gracefully"}=o;try{return await n()}catch(t){let e=t instanceof Error?t.message:String(t);if(xi[i](`${s}: ${e}`),r)try{await r()}catch(a){xi.error(`Fallback also failed: ${a instanceof Error?a.message:String(a)}`)}return}}var xi;var $i=A(()=>{_();xi=C({prefix:"cli-core"}).child("graceful")});function wo(n){let o=[];if(o.push(l.bold(`${n.name} - ${n.description}`)),o.push(""),o.push(l.bold("USAGE")),o.push(` ${n.usage}`),o.push(""),n.options?.length){o.push(l.bold("OPTIONS"));for(let r of n.options){let i=[r.description];if(r.default!==void 0)i.push(l.dim(`(default: ${r.default})`));if(r.required)i.push(l.error("(required)"));o.push(` ${l.flag(r.flags.padEnd(26))} ${i.join(" ")}`)}o.push("")}if(n.examples?.length){o.push(l.bold("EXAMPLES"));for(let r of n.examples)o.push(l.dim(` # ${r.description}`)),o.push(` ${l.value(r.command)}`),o.push("")}if(n.notes?.length){o.push(l.bold("NOTES"));for(let r of n.notes)o.push(` - ${r}`);o.push("")}if(n.sections?.length)for(let r of n.sections){o.push(l.bold(r.title));for(let i of r.content)o.push(` ${i}`);o.push("")}if(o[o.length-1]==="")o.pop();return o.join(`
|
|
77
|
-
`)}function xo(n,o,r,i){let s=[];s.push(l.bold(n)),s.push(""),s.push(l.bold("USAGE")),s.push(` ${o}`),s.push(""),s.push(l.bold("COMMANDS"));let t=Math.max(...r.map((e)=>e.name.length));for(let e of r)s.push(` ${l.command(e.name.padEnd(t+2))} ${e.description}`);if(i)s.push(""),s.push(i);return s.join(`
|
|
78
|
-
`)}var Si=A(()=>{Go()});var vi=A(()=>{_()});var ji=A(()=>{N()});async function Ri(n,o={}){let r={...le,...o},i=Error("Operation failed");for(let s=1;s<=r.maxAttempts;s++)try{return await n()}catch(t){if(i=t instanceof Error?t:Error(String(t)),!r.retryableErrors.some((c)=>i.message.toLowerCase().includes(c.toLowerCase()))||s===r.maxAttempts)throw i;r.onRetry(s,i);let a=Math.min(r.initialDelay*r.backoffMultiplier**(s-1),r.maxDelay);await new Promise((c)=>setTimeout(c,a))}throw i}var le;var Ei=A(()=>{_();le={backoffMultiplier:2,initialDelay:1000,maxAttempts:3,maxDelay:30000,onRetry:(n,o)=>{No.warn(`Retry attempt ${n}: ${o.message}`)},retryableErrors:["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","rate limit","429","503","502","504","npm ERR!","EPUBLISHCONFLICT"]}});var Ci=()=>{};import{existsSync as fe}from"fs";import{readFile as me}from"fs/promises";import{homedir as ge}from"os";import{join as Pi}from"path";async function ye(){try{if(fe(fr)){let n=await me(fr,"utf-8");return JSON.parse(n)}}catch{}return{}}async function be(n){try{await Bun.write(fr,JSON.stringify(n,null,2))}catch{}}async function we(n){try{let o=await fetch(`https://registry.npmjs.org/${n}/latest`,{signal:AbortSignal.timeout(5000)});if(!o.ok)return null;return(await o.json()).version}catch{return null}}function Ii(n,o){let r=n.split(".").map(Number),i=o.split(".").map(Number);for(let s=0;s<Math.max(r.length,i.length);s++){let t=r[s]||0,e=i[s]||0;if(t>e)return 1;if(t<e)return-1}return 0}async function xe(n){let{packageName:o,currentVersion:r,checkInterval:i=he,silent:s=!1}=n;if(process.env.CI||process.env.CONTINUOUS_INTEGRATION||process.env.R5N_NO_UPDATE_CHECK==="1")return null;try{let t=await ye(),e=t[o],a=Date.now();if(e&&a-e.lastChecked<i)return{currentVersion:r,lastChecked:e.lastChecked,latestVersion:e.latestVersion,name:o,updateAvailable:Ii(e.latestVersion,r)>0};let c=await we(o);if(!c)return null;if(t[o]={lastChecked:a,latestVersion:c},!s)be(t).catch(()=>{});return{currentVersion:r,lastChecked:a,latestVersion:c,name:o,updateAvailable:Ii(c,r)>0}}catch{return null}}function Oi(n,o){xe({currentVersion:o,packageName:n}).then((r)=>{if(r?.updateAvailable)console.error(`
|
|
79
|
-
\u26A0\uFE0F Update available: ${r.latestVersion} (current: ${r.currentVersion})`),console.error(` Run: bun install -g ${n}
|
|
80
|
-
`)}).catch(()=>{})}var he=86400000,de,fr;var _i=A(()=>{de=Pi(ge(),".r5n","cache"),fr=Pi(de,"update-check.json")});var Bn=(n)=>{return n.map=(o)=>Bn((r)=>o(n(r))),n.or=(o)=>Bn((r)=>{try{return n(r)}catch(i){return o(r)}}),n},mr=()=>"bad banditype"(),gr=(n)=>Bn((o)=>typeof o===typeof n?o:mr()),en=()=>gr(""),hr=()=>gr(!0),kn=()=>gr(),Ti=(n)=>Bn((o)=>o instanceof n?o:mr()),an=(n)=>Ti(Object).map((o)=>{let r={};for(let i in n){let s=n[i](o[i]);s!==void 0&&(r[i]=s)}return r}),Jn=(n)=>Ti(Array).map((o)=>o.map(n));var Bi=()=>{};function $o(n,o){return Bn((r)=>{try{return n(r)}catch{try{return o(r)}catch{throw Error("No matching schema in union")}}})}function gn(n,o){return(r)=>{if(r===void 0)return o;return n(r)}}function Ai(n){return{parse(o){try{return n(o)}catch(r){throw Error(r instanceof Error?r.message:"Validation failed")}},safeParse(o){try{return{data:n(o),success:!0}}catch(r){return{error:r instanceof Error?r:Error("Validation failed"),success:!1}}},validator:n}}var Mi=A(()=>{Bi()});var L=A(()=>{Go();di();pr();wi();$i();Si();vi();ji();Ei();Ci();_i();Mi()});var dr=()=>$o(kn(),en()),So=(n)=>gn(dr(),n),hn=(n)=>gn($o(kn(),hr()),n),An=(n)=>$o(kn(),n),Se,ve,je,Re,Ee,yr;var Di=A(()=>{L();Se=an({commit:en(),date:en()}),ve=an({author:So("r5n-bot"),email:dr(),message:So("release(\uD83C\uDF89): <packageName@version>")}),je=an({commitAndPush:hn(!1),github:hn(!1),npm:hn(!1),tags:hn(!1)}),Re=an({append:hn(!0),filename:So("CHANGELOG.md"),generate:hn(!0),root:hn(!1),template:dr()}),Ee=an({post:An(an({})),pre:An(an({}))}),yr=Ai(an({$schema:gn(en(),"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/cli/sisyphus/schema.json"),changelog:An(Re),commit:An(ve),configPath:So(".sisyphus"),ignore:gn(Jn(en()),[]),lastStone:Se,plugins:gn(Jn(en()),[]),release:An(je),scripts:An(Ee),single:hn(!1),stones:gn(Jn(en()),[]),tag:gn(en(),"latest")}))});var Mn=()=>{};function jn(n){let o=n.match(/^([~^]?)(\d+)\.(\d+)\.(\d+)(.*)$/);if(!o)return null;let[,r="",i="0",s="0",t="0"]=o;return{major:Number.parseInt(i,10),minor:Number.parseInt(s,10),patch:Number.parseInt(t,10),prefix:r||"",version:`${i}.${s}.${t}`}}function br(n,o){let r=jn(n),i=jn(o);if(!r||!i)return!1;if(!i.prefix)return r.version===i.version;if(i.prefix==="^"){if(i.major>0)return r.major===i.major&&(r.minor>i.minor||r.minor===i.minor&&r.patch>=i.patch);if(i.minor>0)return r.major===0&&r.minor===i.minor&&r.patch>=i.patch;return r.major===0&&r.minor===0&&r.patch===i.patch}if(i.prefix==="~")return r.major===i.major&&r.minor===i.minor&&r.patch>=i.patch;return!1}function wr(n,o,r){let i=jn(n),s=jn(o);if(!i||!s)return Ce.warn(`Could not parse version constraint: ${n} -> ${o}`),o;if(r?.preserveConstraintType&&i.prefix)return`${i.prefix}${o}`;if(s.major>i.major)return s.major===0?o:`^${o}`;if(s.minor>i.minor)return i.prefix==="^"?`^${o}`:o;return i.prefix?`${i.prefix}${o}`:o}function Ni(n){let o=jn(n);return o?o.version:n}function Gi(n,o){return!br(o,n)}function Hi(n,o,r){let i={...n};for(let[s,t]of Object.entries(o))if(s in i&&i[s])i[s]=wr(i[s],t,r);return i}var Ce;var Ui=A(()=>{_();Ce=C({prefix:"sisyphus"}).child("version-constraints")});var jr={};Gn(jr,{versionBumper:()=>X,updateVersionConstraint:()=>wr,updateSisyphusConfig:()=>vr,updateDependencyVersions:()=>Hi,satisfiesConstraint:()=>br,parseVersionConstraint:()=>jn,lineSplitter:()=>xr,isInteractive:()=>$r,isBreakingChange:()=>Gi,handleCancel:()=>Ln,getStones:()=>on,getSisyphusConfig:()=>O,getPackages:()=>U,getPackageUpdateLabel:()=>Yn,getMinimumVersion:()=>Ni,ensureDryRunInTest:()=>Sr,bumpTypeOrder:()=>Rn,bumpTypeAnnotation:()=>En,SNAPSHOT_DATE_REGEX:()=>zi,SNAPSHOT_DATE_LENGTH:()=>ki,ISO_DATE_SEPARATOR:()=>qi,DEFAULT_SNAPSHOT_TAG:()=>Ji});var{$:vo}=globalThis.Bun;function $r({stream:n=process.stdout}={}){return Boolean(n?.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}function Ln(n){if(typeof n==="function")n();else mi(n||"Operation cancelled by user");process.exit(0)}function Sr(n){return n}async function O({overwrite:n,tag:o,dryRun:r,silent:i,configPath:s=".sisyphus",...t}={}){let e=s.startsWith("/")?`${s}/config.json`:`./${s}/config.json`,c=await Bun.file(e).exists(),u=c&&n,m=s.includes("/.sisyphus-test-"),g="";if(!m){if(g=Bun.spawnSync(["git","rev-parse","HEAD"]).stdout.toString().trim(),g.length===0)throw Error("Couldn't find git repository. Have you initialized git repository?")}else g="test-commit-hash";let d;if(c)try{let f=await Bun.file(e).json(),h=yr.safeParse(f);if(!h.success)throw jo.error("Configuration validation failed:",f,h),h.error instanceof Error?Error(`Invalid configuration file: ${h.error.message}`):h.error;d=h.data}catch(f){if(f instanceof Error)throw Error(`Invalid configuration file: ${f.message}`);throw Error("Failed to parse configuration file")}else d=yr.parse({$schema:"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/cli/sisyphus/schema.json",ignore:[],lastStone:{commit:g,date:new Date().toISOString().split(qi)[0]||""},plugins:[],stones:[],tag:o||"latest"});let w={...d,...t},p=`${JSON.stringify(w,null,2)}
|
|
81
|
-
`;if(r){if(!i)jo.info(`${y.bold(y.yellow("[dry-run]"))}
|
|
82
|
-
${y.italic(".sisyphus/config.json")}:
|
|
83
|
-
${p}`);return{...d,...t}}if(u)try{await vo`rm -rf ${s}`.quiet()}catch{}if(c&&!n)return w;return await vo`mkdir -p ${s}`.quiet(),await Bun.write(e,p),w}async function vr({dryRun:n,silent:o,configPath:r,...i}){let s=await O({configPath:r}),t=`./${r||s.configPath||".sisyphus"}/config.json`,e=`${JSON.stringify({...s,...i},null,2)}
|
|
84
|
-
`;if(n){if(!o)jo.info(`${y.bold(y.yellow("[dry-run]"))}
|
|
85
|
-
${y.italic(t)} would be updated to
|
|
86
|
-
${e}`);return}await Bun.write(t,e),B(`${y.green("Sisyphus config updated!")}`)}function Yn({name:n,version:o,bump:r,tag:i}){return`${n}@${o} => ${y.green(X({bump:r,tag:i,version:o}))} ${En[r]}`}function Ie({baseVersion:n,bump:o}){let[r="0",i="0",s="0"]=n.split(".");switch(o){case"major":return`${Number.parseInt(r,10)+1}.0.0`;case"minor":return`${r}.${Number.parseInt(i,10)+1}.0`;case"dependency":case"patch":return`${r}.${i}.${Number.parseInt(s,10)+1}`;default:return`${r}.${i}.${s}`}}function X({version:n="",bump:o,tag:r}){let[i="0.0.0",s=""]=n.split("-"),[t="",e="0"]=s.split(".");if(o==="snapshot"){let a=new Date().toISOString().replace(zi,"").slice(0,ki);return`0.0.0-${r||Ji}-${a}`}if(r&&!o){let a=r===t?Number.parseInt(e,10)+1:1;return`${i}-${r}.${a}`}if(r||o==="dependency"&&t){let a=r===t?Number.parseInt(e,10)+1:1;return`${i}-${r||t}.${a}`}return Ie({baseVersion:i,bump:o})}async function on({dryRun:n,silent:o,configPath:r,testModeEnabled:i}={}){let s=i,t=await O({configPath:r,dryRun:n,silent:o}),e=s&&r?`${r}/stones`:`./${r||t.configPath||".sisyphus"}/stones`;try{let c=(await vo`ls ${e} 2>/dev/null || true`.quiet()).stdout.toString().trim();if(!c)return[];return c.split(`
|
|
87
|
-
`).filter(Boolean).map((m)=>m.replace(".md",""))}catch(a){if(!n)await vo`mkdir -p ${e}`.quiet();return[]}}async function U({filter:n,single:o,includePrivate:r}={}){let i=process.cwd(),s=await Bun.file("package.json").json();if(o)return Oe(s);let t=s?.workspaces,e=Array.isArray(t)?t:t?.packages||[];if(e.length===0)throw Error(`Seems like package.json doesn't have \`workspaces\` field or it's empty. Are you sure you are in the root of the workspace? (cwd: ${i})
|
|
88
|
-
|
|
89
|
-
If you want to run Sisyphus in single-mode/root package, use --single flag or set \`"single": true\` in .sisyphus/config.json.`);let{packages:a,privatePackageCount:c}=await Pe({cwd:i,includePrivate:r,workspaces:e}),u=Object.keys(a);return{packageNames:n?u.filter((m)=>m.includes(n)):u,packages:a,privatePackageCount:c}}async function Pe({workspaces:n,cwd:o,includePrivate:r}){let i={},s={},t=0;for(let e of n){let a=new Bun.Glob(`${e}/package.json`).scanSync({cwd:o});for(let c of a){let{name:u,version:m,private:g,dependencies:d={},devDependencies:w={}}=await Bun.file(c).json();if(g&&!r){jo.debug(`Skipping private package: ${u}`),t++;continue}let f=Object.entries({...d,...w}).map(([h,x])=>x.startsWith("workspace")?h:"").filter(Boolean);for(let h of f)if(s[h]||=[],!s[h].includes(u))s[h].push(u);i[u]={bump:"dependency",dependencyOf:[],file:c,name:u,version:m||"0.0.0"}}}for(let[e,a]of Object.entries(s))if(i[e])i[e].dependencyOf=a;return{packages:i,privatePackageCount:t}}function Oe({name:n,version:o}){return{packageNames:[n],packages:{[n]:{bump:"dependency",dependencyOf:[],file:"package.json",name:n,version:o||"0.0.0"}},privatePackageCount:0}}var jo,xr="***",qi=".",zi,ki=14,Ji="nightly",Rn,En;var G=A(()=>{N();_();Di();Mn();Ui();jo=C({prefix:"sisyphus"}).child("helpers"),zi=/[.ZT:-]/g,Rn=["dependency","patch","minor","major","snapshot"],En={dependency:"\uD83D\uDCE6",patch:"\uD83D\uDC1B",minor:"\u2728",major:"\uD83D\uDEA8",snapshot:"\uD83D\uDCF8"}});var ns={};Gn(ns,{validateGitWorkingDirectory:()=>Ve,validateGitRepository:()=>na,getCurrentGitCommit:()=>oa});var{$:Eo}=globalThis.Bun;async function Ve(){try{let{exitCode:n}=await Eo`git diff --quiet`.nothrow(),{exitCode:o}=await Eo`git diff --cached --quiet`.nothrow();if(n!==0||o!==0)throw new K("Git working directory has uncommitted changes. Please commit or stash your changes before running this command.","GIT_DIRTY_WORKING_DIR")}catch(n){if(n instanceof K)throw n;throw new K("Failed to validate git working directory. Are you in a git repository?","GIT_VALIDATION_FAILED")}}async function na(){try{await Eo`git rev-parse --git-dir`.quiet()}catch{throw new K("Not a git repository. Please initialize git repository first with 'git init'.","NOT_GIT_REPO")}}async function oa(){try{let o=(await Eo`git rev-parse HEAD`.quiet()).stdout.toString().trim();if(!o)throw new K("Could not get current git commit","GIT_NO_COMMIT");return o}catch(n){if(n instanceof K)throw n;throw new K("Failed to get current git commit","GIT_COMMIT_FAILED")}}var os=A(()=>{L()});var is={};Gn(is,{updateLockfile:()=>ia,detectPackageManager:()=>rs});import{existsSync as Co}from"fs";var{$:ra}=globalThis.Bun;async function rs(n=process.cwd()){if(Co(`${n}/bun.lock`))return"bun";if(Co(`${n}/pnpm-lock.yaml`))return"pnpm";if(Co(`${n}/yarn.lock`))return"yarn";if(Co(`${n}/package-lock.json`))return"npm";return null}async function ia(n={}){let{cwd:o=process.cwd(),dryRun:r=!1}=n,i=await rs(o);if(!i){Fn.warn("No lockfile detected, skipping lockfile update");return}if(r){Fn.info(`[dry-run] Would run: ${i} install`);return}Fn.info(`Updating lockfile with ${i}...`);try{await ra`${i} install`.cwd(o).quiet(),Fn.info("Lockfile updated successfully")}catch(s){throw Fn.error(`Failed to update lockfile: ${s instanceof Error?s.message:String(s)}`),s}}var Fn;var ss=A(()=>{_();Fn=C({prefix:"lockfile-updater"})});var es={};Gn(es,{createStoneParser:()=>pa,StoneParseError:()=>Z});function ta(n,o){let r=o[0];if(!r)throw new Z("Stone file is empty",n);let i=r.replace(/^#+\s*/,"").trim();if(!i)throw new Z("Stone message cannot be empty",n);return i}function ea(n){let o=n.find((r)=>r.trim().startsWith("_")&&r.trim().endsWith("_"));return o?o.replace(/_/g,"").trim():void 0}function ts(n){return n.split("|").map((o)=>o.trim()).filter(Boolean)}function aa(n,o){let r=n.toLowerCase().trim(),i={dependency:"dependency",major:"major",minor:"minor",patch:"patch",snapshot:"snapshot"},s=i[r];if(!s)throw new Z(`Invalid bump type "${n}". Must be one of: ${Object.keys(i).join(", ")}`,o);return s}function ca(n,o,r){let i=o.findIndex((u)=>{let m=u.trim();return m.includes("|")&&/:\s*-+\s*:/.test(m)});if(i===-1)throw new Z("Missing table separator (e.g., | :---: |)",n);let s=o[i-1],t=o[i+1];if(!s)throw new Z("Missing table header line",n);if(!t)throw new Z("Missing table data line",n);let e=ts(s),a=ts(t);if(e.length===0)throw new Z("Table header is empty",n);if(e.length!==a.length)throw new Z(`Table column mismatch: ${e.length} headers, ${a.length} data cells`,n);let c=[];for(let u=0;u<e.length;u++){let m=aa(e[u]||"",n),g=a[u]||"";if(!g)continue;let d=g.split(",").map((w)=>w.trim()).filter(Boolean);for(let w of d){let p=r[w];if(!p){sa.warn(`Package "${w}" in stone "${n}" not found in workspace, skipping`);continue}c.push({...p,bump:m})}}if(c.length===0)throw new Z("No valid packages found in stone",n);return c}function ua(n,o,r){let i=o.split(`
|
|
90
|
-
`),s=ta(n,i),t=ea(i),e=ca(n,i,r);return{message:s,name:n,packages:e,tag:t}}function pa(n){return async(o,r)=>{let i=`${n}/${o}.md`;try{let s=await Bun.file(i).text();return ua(o,s,r)}catch(s){if(s instanceof Z)throw s;throw new Z("Could not read stone file",o,s)}}}var sa,Z;var as=A(()=>{_();sa=C({prefix:"stone-parser"});Z=class Z extends Error{stoneName;cause;constructor(n,o,r){super(`Failed to parse stone "${o}": ${n}`);this.stoneName=o;this.cause=r;this.name="StoneParseError"}}});var cs={};Gn(cs,{createFileTransaction:()=>la});function la(){let n={changes:new Map,committed:!1};return{clear:()=>{if(n.committed)throw Error("Cannot clear committed transaction");n.changes.clear()},commit:async()=>{if(n.committed)throw Error("Transaction already committed");if(n.changes.size===0){dn.info("No changes to commit"),n.committed=!0;return}dn.info(`Committing ${n.changes.size} file changes`);let e=new Map;try{for(let[a]of n.changes)try{let c=await Bun.file(a).text();e.set(a,c)}catch{dn.debug(`File ${a} does not exist, creating new file`)}for(let a of n.changes.values())await Bun.write(a.path,a.content),dn.debug(`Wrote ${a.path}`);n.committed=!0,dn.info("Transaction committed successfully")}catch(a){dn.error("Transaction failed, attempting rollback");for(let[c,u]of e)try{await Bun.write(c,u),dn.debug(`Restored ${c} from backup`)}catch(m){dn.error(`Failed to restore ${c}: ${m}`)}throw Error(`Transaction failed: ${a instanceof Error?a.message:String(a)}`)}},getQueuedChanges:()=>{return Array.from(n.changes.entries()).map(([e,a])=>({content:a.content,path:e}))},hasChanges:()=>{return n.changes.size>0},queue:(e,a)=>{if(n.committed)throw Error("Cannot queue changes after transaction is committed");n.changes.set(e,{content:a,path:e})}}}var dn;var us=A(()=>{_();dn=C({prefix:"file-transaction"})});L();_();var vn="0.4.7";L();L();var Li=hi({errorPrefix:"\u2717"});N();L();_();G();import{parseArgs as _e}from"util";var Wi=C({prefix:"changeset"}),Yi=".changesets";async function Fi(){let n=await Ge();un("\uD83D\uDE80 Create a new changeset");try{let{packages:o,packageNames:r}=await U({includePrivate:!1});if(r.length===0)throw new K("No public packages found","NO_PUBLIC_PACKAGES");let i=r.map((t)=>({name:t,version:o[t]?.version||"0.0.0"})),s=await Te(i,n.all);if(s.changes.length===0){q("\u274C No packages selected");return}if(n.dryRun){Me(s),q("\u2728 Dry run complete - no files created");return}await Le(s),q("\u2728 Changeset created successfully!")}catch(o){throw Wi.error("Failed to create changeset:",o),o}}async function Te(n,o){let r=await Be(n,o);if(r.length===0)return{changes:[],summary:""};let i=[];for(let a of r){let c=await Ae(a);if(c)i.push({packageName:a.name,versionType:c})}let s=await J({message:"Write a summary for this change",placeholder:"Fixed critical bug in authentication flow",validate:(a)=>{if(!a||a.trim().length===0)return"Summary is required";if(a.length>100)return"Summary should be less than 100 characters";return}});if(typeof s==="symbol")throw new K("Changeset creation cancelled","CANCELLED");let t=await D({initialValue:!1,message:"Do you want to add a longer description?"}),e;if(t){let a=await J({message:"Write a detailed description (optional)",placeholder:"This change fixes the issue where users could not..."});if(typeof a!=="symbol"&&a.trim().length>0)e=a}return{changes:i,description:e,summary:s}}async function Be(n,o){if(o)return n;let r=n.map((s)=>({hint:s.version,label:s.name,value:s})),i=await $n({message:"Which packages have changed?",options:r,required:!1});if(typeof i==="symbol")throw new K("Package selection cancelled","CANCELLED");return i}async function Ae(n){let o=await nn({message:`How should ${n.name} be updated?`,options:[{hint:"Bug fixes and small changes",label:"Patch",value:"patch"},{hint:"New features, backwards compatible",label:"Minor",value:"minor"},{hint:"Breaking changes",label:"Major",value:"major"},{hint:"Don't update this package",label:"Skip",value:"skip"}]});if(typeof o==="symbol")throw new K("Version selection cancelled","CANCELLED");return o==="skip"?null:o}function Me(n){if(console.log(`
|
|
91
|
-
\uD83D\uDCC4 Changeset Preview:`),console.log("\u2500".repeat(50)),console.log(`Summary: ${n.summary}`),n.description)console.log(`
|
|
92
|
-
Description:
|
|
93
|
-
${n.description}`);console.log(`
|
|
94
|
-
Changes:`);for(let o of n.changes)console.log(` ${o.packageName}: ${o.versionType}`);console.log("\u2500".repeat(50))}async function Le(n){let o=await import("fs/promises"),r=await import("path");await o.mkdir(Yi,{recursive:!0});let s=`${De()}.md`,t=r.join(Yi,s),e=Ne(n);await o.writeFile(t,e,"utf-8"),Wi.info(`Created changeset: ${s}`)}function De(){let n=Date.now().toString(36),o=Math.random().toString(36).substring(2,8);return`${n}-${o}`}function Ne(n){let o=[];o.push("---");for(let r of n.changes)o.push(`"${r.packageName}": ${r.versionType}`);if(o.push("---"),o.push(""),o.push(n.summary),n.description)o.push(""),o.push(n.description);return o.push(""),o.join(`
|
|
95
|
-
`)}async function Ge(){let{values:n}=_e({allowPositionals:!0,args:Bun.argv,options:{all:{default:!1,short:"a",type:"boolean"},dryRun:{default:!1,short:"d",type:"boolean"}},strict:!0});return{all:n.all,dryRun:n.dryRun}}N();L();_();G();N();_();G();import{parseArgs as fa}from"util";var{$:Y}=globalThis.Bun;L();_();G();var Wn=C({prefix:"sisyphus"}).child("changelog");async function Xi({changelogRoot:n,commit:o,dryRun:r=!1,stones:i}){let s=[""],{lastStone:{commit:t=""}}=await O(),e=He({stones:i});for(let[a,{bump:c,path:u,changelog:m}]of e.entries()){let g=[...m,Ki({commit:o,lastCommit:t})],d=await Bun.file(u).exists(),[w,...p]=d?(await Bun.file(u).text()).split(`
|
|
96
|
-
`):[`# ${a}`],f=[w,...g,...p];if(r)Wn.info(`${y.bold(y.yellow("[dry-run]"))}
|
|
97
|
-
${f.join(`
|
|
98
|
-
`)}`);else if(!await lr(async()=>{return Wn.info(`Writing changelog to ${u}`),await Bun.write(u,`${f.join(`
|
|
99
|
-
`).trimEnd()}
|
|
100
|
-
`),!0},{logLevel:"error",message:`Failed to write changelog to ${u}`}))continue;let[h="",,,x=""]=m;if(!s.includes(x))s.unshift(x);s.push(`### ${En[c]} ${a}@${h.slice(7)}`)}if(n){let a=Bun.file("CHANGELOG.md"),c=await a.exists(),[u,...m]=c?(await a.text()).split(`
|
|
101
|
-
`):["# Changelog"],g=[u,"",...s,...m,Ki({commit:o,lastCommit:t,root:!0})];if(r)Wn.info(`${y.bold(y.yellow("[dry-run]"))}
|
|
102
|
-
Root changelog:
|
|
103
|
-
${g.join(`
|
|
104
|
-
`)}`);else await lr(async()=>{Wn.info(`Writing root changelog to ${a.name}`),await Bun.write(a,g.join(`
|
|
105
|
-
`))},{logLevel:"error",message:"Failed to write root changelog"})}}function He({stones:n}){let o=new Map;for(let{tag:r,packages:i,message:s}of n)for(let{file:t,name:e,version:a,bump:c}of i){let u=X({bump:c,tag:r,version:a}),{bump:m,path:g,changelog:d}=o.get(e)??{bump:c,changelog:[],path:t.replace("package.json","CHANGELOG.md")},[w="",,,p=""]=d,f=[w.replace("### ","")||"0.0.0",u].sort(Bun.semver.order)[1];o.set(e,{bump:m,changelog:[`### ${En[c]} ${f}`,"",d.length>0?"__Stones:__":"__Stone:__",`_${s}${p?`, ${p.replace(/_/g,"")}_`:"_"}`],path:g})}return o}var Rr="#@!";function Ki({root:n,lastCommit:o,commit:r}){let i=(()=>{try{return Bun.spawnSync(["git","remote","get-url","origin"]).stdout.toString().trim().split(":")[1]?.replaceAll(".git","")||""}catch{return""}})(),t=(()=>{try{return Bun.spawnSync(["git","log",`--pretty=format:%H${Rr}%s${Rr}%cn`,`${o}..${r}`]).stdout.toString()}catch{return Wn.warn("Could not get git commit history"),""}})().split(`
|
|
106
|
-
`).map((e)=>{if(e.length===0)return;let[a="",c="",u=""]=e.split(Rr);return`- ${i?`[${a.slice(0,7)} ${c}](https://github.com/${i}/commit/${a})`:c} (by [@${u}](https://github.com/${u}))`}).filter(Boolean);return t.length>0?`
|
|
107
|
-
<details><summary>${t.length} ${n?"Commits in this release":"Commits since last stone"}:</summary>
|
|
108
|
-
${t.join(`
|
|
2
|
+
// @bun
|
|
3
|
+
var zr=Object.create;var{getPrototypeOf:Yr,defineProperty:kn,getOwnPropertyNames:Kr}=Object;var Zr=Object.prototype.hasOwnProperty;function Tr(e){return this[e]}var Qr,_r,Cn=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?Qr??=new WeakMap:_r??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?zr(Yr(e)):{};let o=t||!e||!e.__esModule?kn(n,"default",{value:e,enumerable:!0}):n;for(let a of Kr(e))if(!Zr.call(o,a))kn(o,a,{get:Tr.bind(e,a),enumerable:!0});if(r)i.set(e,o);return o};var Xr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var It=Xr((Io,Un)=>{var Mt={to(e,t){if(!t)return`\x1B[${e+1}G`;return`\x1B[${t+1};${e+1}H`},move(e,t){let n="";if(e<0)n+=`\x1B[${-e}D`;else if(e>0)n+=`\x1B[${e}C`;if(t<0)n+=`\x1B[${-t}A`;else if(t>0)n+=`\x1B[${t}B`;return n},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},ui={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},hi={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let n=0;n<e;n++)t+=this.line+(n<e-1?Mt.up():"");if(e)t+=Mt.left;return t}};Un.exports={cursor:Mt,scroll:ui,erase:hi,beep:"\x07"}});class te extends Error{constructor(e="Operation cancelled"){super(e)}}class d extends Error{hint;constructor(e,t){super(e);this.hint=t}}import{styleText as Qe}from"util";import{stdout as Et,stdin as Hn}from"process";import*as le from"readline";import fi from"readline";var $n=(()=>{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}})(),Rn=(e)=>{return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510},Sn=(e)=>{return e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141};var ei=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ti=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Mn=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,ni=/\t{1,1000}/y,In=/[\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,ri=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ii=/\p{M}+/gu,si={limit:1/0,ellipsis:""},Fn=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?Fn(i,si,n).width:0),o=0,a=n.controlWidth??0,g=n.tabWidth??8,m=n.emojiWidth??2,u=2,f=n.regularWidth??1,y=n.wideWidth??2,b=[[ri,f],[ei,0],[ti,a],[ni,g],[In,m],[Mn,y]],h=0,P=0,j=e.length,B=0,k=!1,H=j,L=Math.max(0,r-s),C=0,x=0,O=0,E=0;e:while(!0){if(x>C||P>=j&&P>h){let G=e.slice(C,x)||e.slice(h,P);B=0;for(let ne of G.replaceAll(ii,"")){let z=ne.codePointAt(0)||0;if(Rn(z))E=2;else if(Sn(z))E=y;else E=f;if(O+E>L)H=Math.min(H,Math.max(C,h)+B);if(O+E>r){k=!0;break e}B+=ne.length,O+=E}C=x=0}if(P>=j)break e;for(let G=0,ne=b.length;G<ne;G++){let[z,Ve]=b[G];if(z.lastIndex=P,z.test(e)){if(B=z===Mn?$n(e.slice(P,z.lastIndex)):z===In?1:z.lastIndex-P,E=B*Ve,O+E>L)H=Math.min(H,P+Math.floor((L-O)/Ve));if(O+E>r){k=!0;break e}O+=E,C=h,x=P,P=h=z.lastIndex;continue e}}P+=1}return{width:k?L:O,index:k?H:j,truncated:k,ellipsed:k&&r>=s}},Dn=Fn;var oi={limit:1/0,ellipsis:"",ellipsisWidth:0},ai=(e,t={})=>{return Dn(e,oi,t).width},Y=ai;var Ye="\x1B",An="\x9B",ci=39,Rt="\x07",Nn="[",gi="]",Bn="m",St=`${gi}8;;`,jn=new RegExp(`(?:\\${Nn}(?<code>\\d+)m|\\${St}(?<uri>.*)${Rt})`,"y"),En=(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},Ln=(e)=>`${Ye}${Nn}${e}${Bn}`,On=(e)=>`${Ye}${St}${e}${Rt}`,$t=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,s=!1,o=e.at(-1),a=o===void 0?0:Y(o),g=r.next(),m=r.next(),u=0;while(!g.done){let f=g.value,y=Y(f);if(a+y<=n)e[e.length-1]+=f;else e.push(f),a=0;if(f===Ye||f===An)i=!0,s=t.startsWith(St,u+1);if(i){if(s){if(f===Rt)i=!1,s=!1}else if(f===Bn)i=!1}else if(a+=y,a===n&&!m.done)e.push(""),a=0;g=m,m=r.next(),u+=f.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},mi=(e)=>{let t=e.split(" "),n=t.length;while(n){if(Y(t[n-1]))break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},pi=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",i,s,o=e.split(" "),a=[""],g=0;for(let f=0;f<o.length;f++){let y=o[f];if(n.trim!==!1){let h=a.at(-1)??"",P=h.trimStart();if(h.length!==P.length)a[a.length-1]=P,g=Y(P)}if(f!==0){if(g>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),g=0;if(g||n.trim===!1)a[a.length-1]+=" ",g++}let b=Y(y);if(n.hard&&b>t){let h=t-g,P=1+Math.floor((b-h-1)/t);if(Math.floor((b-1)/t)<P)a.push("");$t(a,y,t),g=Y(a.at(-1)??"");continue}if(g+b>t&&g&&b){if(n.wordWrap===!1&&g<t){$t(a,y,t),g=Y(a.at(-1)??"");continue}a.push(""),g=0}if(g+b>t&&n.wordWrap===!1){$t(a,y,t),g=Y(a.at(-1)??"");continue}a[a.length-1]+=y,g+=b}if(n.trim!==!1)a=a.map((f)=>mi(f));let m=a.join(`
|
|
4
|
+
`),u=!1;for(let f=0;f<m.length;f++){let y=m[f];if(r+=y,!u){if(u=y>="\uD800"&&y<="\uDBFF",u)continue}else u=!1;if(y===Ye||y===An){jn.lastIndex=f+1;let h=jn.exec(m)?.groups;if(h?.code!==void 0){let P=Number.parseFloat(h.code);i=P===ci?void 0:P}else if(h?.uri!==void 0)s=h.uri.length===0?void 0:h.uri}if(m[f+1]===`
|
|
5
|
+
`){if(s)r+=On("");let b=i?En(i):void 0;if(i&&b)r+=Ln(b)}else if(y===`
|
|
6
|
+
`){if(i&&En(i))r+=Ln(i);if(s)r+=On(s)}}return r},li=/\r?\n/;function re(e,t,n){return String(e).normalize().split(li).map((r)=>pi(r,t,n)).join(`
|
|
7
|
+
`)}var V=Cn(It(),1);import{ReadStream as Gn}from"tty";function oe(e,t,n){if(!n.some((o)=>!o.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),s=r<0?i:r>i?0:r;return n[s]?.disabled?oe(s,t<0?-1:1,n):s}function Ke(e,t,n,r){let i=r.split(`
|
|
8
|
+
`),s=0,o=e;for(let g of i){if(o<=g.length)break;o-=g.length+1,s++}for(s=Math.max(0,Math.min(i.length-1,s+n)),o=Math.min(o,i[s].length)+t;o<0&&s>0;)s--,o+=i[s].length+1;for(;o>i[s].length&&s<i.length-1;)o-=i[s].length+1,s++;o=Math.max(0,Math.min(i[s].length,o));let a=0;for(let g=0;g<s;g++)a+=i[g].length+1;return a+o}var di=["up","down","left","right","space","enter","cancel"],yi=["January","February","March","April","May","June","July","August","September","October","November","December"],W={actions:new Set(di),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...yi],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:(e)=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:(e)=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function Lt(e,t){if(typeof e=="string")return W.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Lt(n,t))return!0;return!1}function bi(e,t){if(e===t)return;let n=e.split(`
|
|
9
|
+
`),r=t.split(`
|
|
10
|
+
`),i=Math.max(n.length,r.length),s=[];for(let o=0;o<i;o++)n[o]!==r[o]&&s.push(o);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}var Pi=globalThis.process.platform.startsWith("win"),Dt=Symbol("clack:cancel");function Ae(e){return e===Dt}function Ze(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Wn({input:e=Hn,output:t=Et,overwrite:n=!0,hideCursor:r=!0}={}){let i=le.createInterface({input:e,output:t,prompt:"",tabSize:1});le.emitKeypressEvents(e,i),e instanceof Gn&&e.isTTY&&e.setRawMode(!0);let s=(o,{name:a,sequence:g})=>{let m=String(o);if(Lt([m,a,g],"cancel")){r&&t.write(V.cursor.show),process.exit(0);return}if(!n)return;le.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{le.clearLine(t,1,()=>{e.once("keypress",s)})})};return r&&t.write(V.cursor.hide),e.once("keypress",s),()=>{e.off("keypress",s),r&&t.write(V.cursor.show),e instanceof Gn&&e.isTTY&&!Pi&&e.setRawMode(!1),i.terminal=!1,i.close()}}var Ne=(e)=>("columns"in e)&&typeof e.columns=="number"?e.columns:80,Ot=(e)=>("rows"in e)&&typeof e.rows=="number"?e.rows:20;function ue(e,t,n,r=n,i=n,s){let o=Ne(e??Et);return re(t,o-n.length,{hard:!0,trim:!1}).split(`
|
|
11
|
+
`).map((a,g,m)=>{let u=s?s(a,g):a;return g===0?`${r}${u}`:g===m.length-1?`${i}${u}`:`${n}${u}`}).join(`
|
|
12
|
+
`)}function Jn(e,t){if("~standard"in e){let n=e["~standard"].validate(t);if(n instanceof Promise)throw TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return n.issues?.at(0)?.message}return e(t)}class ae{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,t=!0){let{input:n=Hn,output:r=Et,render:i,signal:s,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=s,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let i of n)i.cb(...t),i.once&&r.push(()=>n.splice(n.indexOf(i),1));for(let i of r)i()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Dt);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=fi.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),Ze(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(V.cursor.show),this.output.off("resize",this.render),Ze(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(V.cursor.show),this.output.off("resize",this.render),Ze(this.input,!1),e(Dt)})})}_isActionKey(e,t){return e==="\t"}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,t){this.userInput=e??"",this.emit("userInput",this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,t){if(this._track&&t.name!=="return"&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),t?.name&&(!this._track&&W.aliases.has(t.name)&&this.emit("cursor",W.aliases.get(t.name)),W.actions.has(t.name)&&this.emit("cursor",t.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,t),t?.name==="return"&&this._shouldSubmit(e,t)){if(this.opts.validate){let n=Jn(this.opts.validate,this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Lt([e,t?.name,t?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
13
|
+
`),Ze(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=re(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
14
|
+
`).length-1;this.output.write(V.cursor.move(-999,e*-1))}render(){let e=re(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(V.cursor.hide);else{let t=bi(this._prevFrame,e),n=Ot(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),s=t.lines.find((o)=>o>=r);if(s===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(V.cursor.move(0,s-i)),this.output.write(V.erase.lines(1));let o=e.split(`
|
|
15
|
+
`);this.output.write(o[s]),this._prevFrame=e,this.output.write(V.cursor.move(0,o.length-s-1));return}else if(t.lines.length>1){if(r<i)s=r;else{let a=s-i;a>0&&this.output.write(V.cursor.move(0,a))}this.output.write(V.erase.down());let o=e.split(`
|
|
16
|
+
`).slice(s);this.output.write(o.join(`
|
|
17
|
+
`)),this._prevFrame=e;return}}this.output.write(V.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}}function wi(e,t){if(e===void 0||t.length===0)return 0;let n=t.findIndex((r)=>r.value===e);return n!==-1?n:0}function vi(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function ki(e,t){if(t)return e?t:t[0]}var Ci=class extends ae{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#t=0;#i="";#e;#s;#a;get cursor(){return this.#t}get userInputWithCursor(){if(!this.userInput)return Qe(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let t=this.userInput.slice(0,this.cursor),n=this.userInput.slice(this.cursor,this.cursor+1),r=this.userInput.slice(this.cursor+1);return`${t}${Qe("inverse",n)}${r}`}get options(){return typeof this.#s=="function"?this.#s():this.#s}constructor(t){super(t),this.#s=t.options,this.#a=t.placeholder;let n=this.options;this.filteredOptions=[...n],this.multiple=t.multiple===!0,this.#e=typeof t.options=="function"?t.filter:t.filter??vi;let r;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?r=t.initialValue:r=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(r=[this.options[0]?.value]),r)for(let i of r){let s=n.findIndex((o)=>o.value===i);s!==-1&&(this.toggleSelected(i),this.#t=s)}this.focusedValue=this.options[this.#t]?.value,this.on("key",(i,s)=>this.#n(i,s)),this.on("userInput",(i)=>this.#r(i))}_isActionKey(t,n){return t==="\t"||this.multiple&&this.isNavigating&&n.name==="space"&&t!==void 0&&t!==""}#n(t,n){let r=n.name==="up",i=n.name==="down",s=n.name==="return",o=this.userInput===""||this.userInput==="\t",a=this.#a,g=this.options,m=a!==void 0&&a!==""&&g.some((u)=>!u.disabled&&(this.#e?this.#e(a,u):!0));if(n.name==="tab"&&o&&m){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(a,!0),this.isNavigating=!1;return}r||i?(this.#t=oe(this.#t,r?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#t]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):s?this.value=ki(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(n.name==="tab"||this.isNavigating&&n.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter((n)=>n!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#r(t){if(t!==this.#i){this.#i=t;let n=this.options;t&&this.#e?this.filteredOptions=n.filter((s)=>this.#e?.(t,s)):this.filteredOptions=[...n];let r=wi(this.focusedValue,this.filteredOptions);this.#t=oe(r,0,this.filteredOptions);let i=this.filteredOptions[this.#t];i&&!i.disabled?this.focusedValue=i.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class At extends ae{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(t)=>{this.output.write(V.cursor.move(0,-1)),this.value=t,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var $i={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function xn(e){return[...e].map((t)=>$i[t])}function Ri(e){let t=new Intl.DateTimeFormat(e,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),n=[],r="/";for(let i of t)i.type==="literal"?r=i.value.trim()||i.value:(i.type==="year"||i.type==="month"||i.type==="day")&&n.push({type:i.type,len:i.type==="year"?4:2});return{segments:n,separator:r}}function Ft(e){return Number.parseInt((e||"0").replace(/_/g,"0"),10)||0}function Te(e){return{year:Ft(e.year),month:Ft(e.month),day:Ft(e.day)}}function jt(e,t){return new Date(e||2001,t||1,0).getDate()}function Vn(e){let{year:t,month:n,day:r}=Te(e);if(!t||t<0||t>9999||!n||n<1||n>12||!r||r<1)return;let i=new Date(Date.UTC(t,n-1,r));if(!(i.getUTCFullYear()!==t||i.getUTCMonth()!==n-1||i.getUTCDate()!==r))return{year:t,month:n,day:r}}function qn(e){let t=Vn(e);return t?new Date(Date.UTC(t.year,t.month-1,t.day)):void 0}function Si(e,t,n,r){let i=n?{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate()}:null,s=r?{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}:null;return e==="year"?{min:i?.year??1,max:s?.year??9999}:e==="month"?{min:i&&t.year===i.year?i.month:1,max:s&&t.year===s.year?s.month:12}:{min:i&&t.year===i.year&&t.month===i.month?i.day:1,max:s&&t.year===s.year&&t.month===s.month?s.day:jt(t.year,t.month)}}class zn extends ae{#t;#i;#e;#s;#a;#n={segmentIndex:0,positionInSegment:0};#r=!0;#o=null;inlineError="";get segmentCursor(){return{...this.#n}}get segmentValues(){return{...this.#e}}get segments(){return this.#t}get separator(){return this.#i}get formattedValue(){return this.#p(this.#e)}#p(e){return this.#t.map((t)=>e[t.type]).join(this.#i)}#c(){this._setUserInput(this.#p(this.#e)),this._setValue(qn(this.#e)??void 0)}constructor(e){let t=e.format?{segments:xn(e.format),separator:e.separator??"/"}:Ri(e.locale),n=e.separator??t.separator,r=e.format?xn(e.format):t.segments,i=e.initialValue??e.defaultValue,s=i?{year:String(i.getUTCFullYear()).padStart(4,"0"),month:String(i.getUTCMonth()+1).padStart(2,"0"),day:String(i.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},o=r.map((a)=>s[a.type]).join(n);super({...e,initialUserInput:o},!1),this.#t=r,this.#i=n,this.#e=s,this.#s=e.minDate,this.#a=e.maxDate,this.#c(),this.on("cursor",(a)=>this.#h(a)),this.on("key",(a,g)=>this.#f(a,g)),this.on("finalize",()=>this.#d(e))}#g(){let e=Math.max(0,Math.min(this.#n.segmentIndex,this.#t.length-1)),t=this.#t[e];if(t)return this.#n.positionInSegment=Math.max(0,Math.min(this.#n.positionInSegment,t.len-1)),{segment:t,index:e}}#m(e){this.inlineError="",this.#o=null;let t=this.#g();t&&(this.#n.segmentIndex=Math.max(0,Math.min(this.#t.length-1,t.index+e)),this.#n.positionInSegment=0,this.#r=!0)}#l(e){let t=this.#g();if(!t)return;let{segment:n}=t,r=this.#e[n.type],i=!r||r.replace(/_/g,"")==="",s=Number.parseInt((r||"0").replace(/_/g,"0"),10)||0,o=Si(n.type,Te(this.#e),this.#s,this.#a),a;i?a=e===1?o.min:o.max:a=Math.max(Math.min(o.max,s+e),o.min),this.#e={...this.#e,[n.type]:a.toString().padStart(n.len,"0")},this.#r=!0,this.#o=null,this.#c()}#h(e){if(e)switch(e){case"right":return this.#m(1);case"left":return this.#m(-1);case"up":return this.#l(1);case"down":return this.#l(-1)}}#f(e,t){if(t?.name==="backspace"||t?.sequence==="\x7F"||t?.sequence==="\b"||e==="\x7F"||e==="\b"){this.inlineError="";let n=this.#g();if(!n)return;if(!this.#e[n.segment.type].replace(/_/g,"")){this.#m(-1);return}this.#e[n.segment.type]="_".repeat(n.segment.len),this.#r=!0,this.#n.positionInSegment=0,this.#c();return}if(t?.name==="tab"){this.inlineError="";let n=this.#g();if(!n)return;let r=t.shift?-1:1,i=n.index+r;i>=0&&i<this.#t.length&&(this.#n.segmentIndex=i,this.#n.positionInSegment=0,this.#r=!0);return}if(e&&/^[0-9]$/.test(e)){let n=this.#g();if(!n)return;let{segment:r}=n,i=!this.#e[r.type].replace(/_/g,"");if(this.#r&&this.#o!==null&&!i){let y=this.#o+e,b={...this.#e,[r.type]:y},h=this.#u(b,r);if(h){this.inlineError=h,this.#o=null,this.#r=!1;return}this.inlineError="",this.#e[r.type]=y,this.#o=null,this.#r=!1,this.#c(),n.index<this.#t.length-1&&(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0);return}this.#r&&!i&&(this.#e[r.type]="_".repeat(r.len),this.#n.positionInSegment=0),this.#r=!1,this.#o=null;let s=this.#e[r.type],o=s.indexOf("_"),a=o>=0?o:Math.min(this.#n.positionInSegment,r.len-1);if(a<0||a>=r.len)return;let g=s.slice(0,a)+e+s.slice(a+1),m=!1;if(a===0&&s==="__"&&(r.type==="month"||r.type==="day")){let y=Number.parseInt(e,10);g=`0${e}`,m=y<=(r.type==="month"?1:2)}if(r.type==="year"&&(g=(s.replace(/_/g,"")+e).padStart(r.len,"_")),!g.includes("_")){let y={...this.#e,[r.type]:g},b=this.#u(y,r);if(b){this.inlineError=b;return}}this.inlineError="",this.#e[r.type]=g;let u=g.includes("_")?void 0:Vn(this.#e);if(u){let{year:y,month:b}=u,h=jt(y,b);this.#e={year:String(Math.max(0,Math.min(9999,y))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,b))).padStart(2,"0"),day:String(Math.max(1,Math.min(h,u.day))).padStart(2,"0")}}this.#c();let f=g.indexOf("_");m?(this.#r=!0,this.#o=e):f>=0?this.#n.positionInSegment=f:o>=0&&n.index<this.#t.length-1?(this.#n.segmentIndex=n.index+1,this.#n.positionInSegment=0,this.#r=!0):this.#n.positionInSegment=Math.min(a+1,r.len-1)}}#u(e,t){let{month:n,day:r}=Te(e);if(t.type==="month"&&(n<0||n>12))return W.date.messages.invalidMonth;if(t.type==="day"&&(r<0||r>31))return W.date.messages.invalidDay(31,"any month")}#d(e){let{year:t,month:n,day:r}=Te(this.#e);if(t&&n&&r){let i=jt(t,n);this.#e={...this.#e,day:String(Math.min(r,i)).padStart(2,"0")}}this.value=qn(this.#e)??e.defaultValue??void 0}}var Mi=class extends ae{options;cursor=0;#t;getGroupItems(t){return this.options.filter((n)=>n.group===t)}isGroupSelected(t){let n=this.getGroupItems(t),r=this.value;return r===void 0?!1:n.every((i)=>r.includes(i.value))}toggleValue(){let t=this.options[this.cursor];if(t!==void 0)if(this.value===void 0&&(this.value=[]),t.group===!0){let n=t.value,r=this.getGroupItems(n);this.isGroupSelected(n)?this.value=this.value.filter((i)=>r.findIndex((s)=>s.value===i)===-1):this.value=[...this.value,...r.map((i)=>i.value)],this.value=Array.from(new Set(this.value))}else{let n=this.value.includes(t.value);this.value=n?this.value.filter((r)=>r!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:n}=t;this.#t=t.selectableGroups!==!1,this.options=Object.entries(n).flatMap(([r,i])=>[{value:r,group:!0,label:r},...i.map((s)=>({...s,group:r}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:r})=>r===t.cursorAt),this.#t?0:1),this.on("cursor",(r)=>{switch(r){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let i=this.options[this.cursor]?.group===!0;!this.#t&&i&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Ii=new Set(["up","down","left","right"]);class Yn extends ae{#t=!1;#i;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${e}\u2588`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return n===`
|
|
18
|
+
`?`${t}\u2588
|
|
19
|
+
${r}`:`${t}${Qe("inverse",n)}${r}`}get cursor(){return this._cursor}#e(e){if(this.userInput.length===0){this._setUserInput(e);return}this._setUserInput(this.userInput.slice(0,this.cursor)+e+this.userInput.slice(this.cursor))}#s(e){let t=this.value??"";switch(e){case"up":this._cursor=Ke(this._cursor,0,-1,t);return;case"down":this._cursor=Ke(this._cursor,0,1,t);return;case"left":this._cursor=Ke(this._cursor,-1,0,t);return;case"right":this._cursor=Ke(this._cursor,1,0,t);return}}_shouldSubmit(e,t){if(this.#i)return this.focused==="submit"?!0:(this.#e(`
|
|
20
|
+
`),this._cursor++,!1);let n=this.#t;return this.#t=!0,n&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
21
|
+
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#e(`
|
|
22
|
+
`),this._cursor++,!1)}constructor(e){let t=e.initialUserInput??e.initialValue;super({...e,initialUserInput:t},!1),t!==void 0&&(this._cursor=t.length),this.#i=e.showSubmit??!1,this.on("key",(n,r)=>{if(r?.name&&Ii.has(r.name)){this.#t=!1,this.#s(r.name);return}if(n==="\t"&&this.#i){this.focused=this.focused==="editor"?"submit":"editor";return}if(r?.name!=="return"){if(this.#t=!1,r?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(r?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}n&&(this.#i&&this.focused==="submit"&&(this.focused="editor"),this.#e(n??""),this._cursor++)}}),this.on("userInput",(n)=>{this._setValue(n)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}}class Nt extends ae{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((e)=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,t=this.value!==void 0&&this.value.length===e.length;this.value=t?[]:e.map((n)=>n.value)}toggleInvert(){let e=this.value;if(!e)return;let t=this._enabledOptions.filter((n)=>!e.includes(n.value));this.value=t.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter((t)=>t!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let t=Math.max(this.options.findIndex(({value:n})=>n===e.cursorAt),0);this.cursor=this.options[t]?.disabled?oe(t,1,this.options):t,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=oe(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=oe(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Kn=class extends ae{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let t=this._selectedValue;this.value=t===void 0?void 0:t.value}constructor(t){super(t,!1),this.options=t.options;let n=this.options.findIndex(({value:i})=>i===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?oe(r,1,this.options):r,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=oe(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=oe(this.cursor,1,this.options);break}this.changeValue()})}};class Bt extends ae{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),n=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${Qe("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 p,stripVTControlCharacters as xo}from"util";import Q from"process";var Ue=Cn(It(),1);function Fi(){if(Q.platform!=="win32")return Q.env.TERM!=="linux";return Boolean(Q.env.CI)||Boolean(Q.env.WT_SESSION)||Boolean(Q.env.TERMINUS_SUBLIME)||Q.env.ConEmuTask==="{cmd::Cmder}"||Q.env.TERM_PROGRAM==="Terminus-Sublime"||Q.env.TERM_PROGRAM==="vscode"||Q.env.TERM==="xterm-256color"||Q.env.TERM==="alacritty"||Q.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Ut=Fi(),Di=()=>process.env.CI==="true";var M=(e,t)=>Ut?e:t,ji=M("\u25C6","*"),Xn=M("\u25A0","x"),er=M("\u25B2","x"),et=M("\u25C7","o"),Ei=M("\u250C","T"),v=M("\u2502","|"),he=M("\u2514","\u2014"),Jo=M("\u2510","T"),Vo=M("\u2518","\u2014"),Gt=M("\u25CF",">"),Xe=M("\u25CB"," "),Li=M("\u25FB","[\u2022]"),Zn=M("\u25FC","[+]"),Tn=M("\u25FB","[ ]"),zo=M("\u25AA","\u2022"),Qn=M("\u2500","-"),Oi=M("\u256E","+"),Ai=M("\u251C","+"),Ni=M("\u256F","+"),Bi=M("\u2570","+"),Yo=M("\u256D","+"),Ui=M("\u25CF","\u2022"),Gi=M("\u25C6","*"),xi=M("\u25B2","!"),qi=M("\u25A0","x"),tt=(e)=>{switch(e){case"initial":case"active":return p("cyan",ji);case"cancel":return p("red",Xn);case"error":return p("yellow",er);case"submit":return p("green",et)}},tr=(e)=>{switch(e){case"initial":case"active":return p("cyan",v);case"cancel":return p("red",v);case"error":return p("yellow",v);case"submit":return p("green",v)}};function nr(e,t){let n=[`${t?`${p("cyan",v)} `:""}${e.join(" \u2022 ")}`];return t&&n.push(p("cyan",he)),n}var _n=(e,t,n,r,i,s=!1)=>{let o=t,a=0;if(s)for(let g=r-1;g>=n;g--){let m=e[g];if(m&&(o-=m.length),a++,o<=i)break}else for(let g=n;g<r;g++){let m=e[g];if(m&&(o-=m.length),a++,o<=i)break}return{lineCount:o,removals:a}},xt=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:o=4})=>{let a=Ne(r)-s,g=Ot(r),m=p("dim","..."),u=Math.max(g-o,0),f=Math.max(Math.min(i,u),5),y=0;e>=f-3&&(y=Math.max(Math.min(e-f+3,t.length-f),0));let b=f<t.length&&y>0,h=f<t.length&&y+f<t.length,P=Math.min(y+f,t.length),j=[],B=0;b&&B++,h&&B++;let k=y+(b?1:0),H=P-(h?1:0);for(let C=k;C<H;C++){let x=t[C],O=x?n(x,C===e):"",E=re(O,a,{hard:!0,trim:!1}).split(`
|
|
23
|
+
`);j.push(E),B+=E.length}if(B>u){let C=0,x=0,O=B,E=e-k,G=u,ne=()=>_n(j,O,0,E,G),z=()=>_n(j,O,E+1,j.length,G,!0);b?({lineCount:O,removals:C}=ne(),O>G&&(h||(G-=1),{lineCount:O,removals:x}=z())):(h||(G-=1),{lineCount:O,removals:x}=z(),O>G&&(G-=1,{lineCount:O,removals:C}=ne())),C>0&&(b=!0,j.splice(0,C)),x>0&&(h=!0,j.splice(j.length-x,x))}let L=[];b&&L.push(m);for(let C of j)for(let x of C)L.push(x);return h&&L.push(m),L};var rr=(e)=>{let t=e.active??"Yes",n=e.inactive??"No";return new At({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??W.withGuide,i=`${tt(this.state)} `,s=r?`${p("gray",v)} `:"",o=ue(e.output,e.message,s,i),a=`${r?`${p("gray",v)}
|
|
24
|
+
`:""}${o}
|
|
25
|
+
`,g=this.value?t:n;switch(this.state){case"submit":{let m=r?`${p("gray",v)} `:"";return`${a}${m}${p("dim",g)}`}case"cancel":{let m=r?`${p("gray",v)} `:"";return`${a}${m}${p(["strikethrough","dim"],g)}${r?`
|
|
26
|
+
${p("gray",v)}`:""}`}default:{let m=r?`${p("cyan",v)} `:"",u=r?p("cyan",he):"";return`${a}${m}${this.value?`${p("green",Gt)} ${t}`:`${p("dim",Xe)} ${p("dim",t)}`}${e.vertical?r?`
|
|
27
|
+
${p("cyan",v)} `:`
|
|
28
|
+
`:` ${p("dim","/")} `}${this.value?`${p("dim",Xe)} ${p("dim",n)}`:`${p("green",Gt)} ${n}`}
|
|
29
|
+
${u}
|
|
30
|
+
`}}}}).prompt()};var nt=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let s=e[i],o=await s({results:n})?.catch((a)=>{throw a});if(typeof t?.onCancel=="function"&&Ae(o)){n[i]="canceled",t.onCancel({results:n});continue}n[i]=o}return n},Hi=[`${p("dim","\u2191/\u2193")} to navigate`,`${p("dim","Space:")} select`,`${p("dim","Enter:")} confirm`],Be=(e,t)=>e.split(`
|
|
31
|
+
`).map((n)=>t(n)).join(`
|
|
32
|
+
`),ir=(e)=>{let t=(i,s)=>{let o=i.label??String(i.value);return s==="disabled"?`${p("gray",Tn)} ${Be(o,(a)=>p(["strikethrough","gray"],a))}${i.hint?` ${p("dim",`(${i.hint??"disabled"})`)}`:""}`:s==="active"?`${p("cyan",Li)} ${o}${i.hint?` ${p("dim",`(${i.hint})`)}`:""}`:s==="selected"?`${p("green",Zn)} ${Be(o,(a)=>p("dim",a))}${i.hint?` ${p("dim",`(${i.hint})`)}`:""}`:s==="cancelled"?`${Be(o,(a)=>p(["strikethrough","dim"],a))}`:s==="active-selected"?`${p("green",Zn)} ${o}${i.hint?` ${p("dim",`(${i.hint})`)}`:""}`:s==="submitted"?`${Be(o,(a)=>p("dim",a))}`:`${p("dim",Tn)} ${Be(o,(a)=>p("dim",a))}`},n=e.required??!0,r=e.showInstructions??!0;return new Nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,validate(i){if(n&&(i===void 0||i.length===0))return`Please select at least one option.
|
|
33
|
+
${p("reset",p("dim",`Press ${p(["gray","bgWhite","inverse"]," space ")} to select, ${p("gray",p("bgWhite",p("inverse"," enter ")))} to submit`))}`},render(){let i=e.withGuide??W.withGuide,s=ue(e.output,e.message,i?`${tr(this.state)} `:"",`${tt(this.state)} `),o=`${i?`${p("gray",v)}
|
|
34
|
+
`:""}${s}
|
|
35
|
+
`,a=this.value??[],g=(m,u)=>{if(m.disabled)return t(m,"disabled");let f=a.includes(m.value);return u&&f?t(m,"active-selected"):f?t(m,"selected"):t(m,u?"active":"inactive")};switch(this.state){case"submit":{let m=this.options.filter(({value:f})=>a.includes(f)).map((f)=>t(f,"submitted")).join(p("dim",", "))||p("dim","none"),u=ue(e.output,m,i?`${p("gray",v)} `:"");return`${o}${u}`}case"cancel":{let m=this.options.filter(({value:f})=>a.includes(f)).map((f)=>t(f,"cancelled")).join(p("dim",", "));if(m.trim()==="")return`${o}${p("gray",v)}`;let u=ue(e.output,m,i?`${p("gray",v)} `:"");return`${o}${u}${i?`
|
|
36
|
+
${p("gray",v)}`:""}`}case"error":{let m=i?`${p("yellow",v)} `:"",u=this.error.split(`
|
|
37
|
+
`).map((b,h)=>h===0?`${i?`${p("yellow",he)} `:""}${p("yellow",b)}`:` ${b}`).join(`
|
|
38
|
+
`),f=o.split(`
|
|
39
|
+
`).length,y=u.split(`
|
|
40
|
+
`).length+1;return`${o}${m}${xt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:m.length,rowPadding:f+y,style:g}).join(`
|
|
41
|
+
${m}`)}
|
|
42
|
+
${u}
|
|
43
|
+
`}default:{let m=i?`${p("cyan",v)} `:"",u=o.split(`
|
|
44
|
+
`).length,f=r?nr(Hi,i):i?[p("cyan",he)]:[],y=f.join(`
|
|
45
|
+
`),b=f.length+1;return`${o}${m}${xt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:m.length,rowPadding:u+b,style:g}).join(`
|
|
46
|
+
${m}`)}
|
|
47
|
+
${y}
|
|
48
|
+
`}}}}).prompt()};var l={message:(e=[],{symbol:t=p("gray",v),secondarySymbol:n=p("gray",v),output:r=process.stdout,spacing:i=1,withGuide:s}={})=>{let o=[],a=s??W.withGuide,g=a?n:"",m=a?`${t} `:"",u=a?`${n} `:"";for(let y=0;y<i;y++)o.push(g);let f=Array.isArray(e)?e:e.split(`
|
|
49
|
+
`);if(f.length>0){let[y,...b]=f;y.length>0?o.push(`${m}${y}`):o.push(a?t:"");for(let h of b)h.length>0?o.push(`${u}${h}`):o.push(a?n:"")}r.write(`${o.join(`
|
|
109
50
|
`)}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
${
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
`);
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
${
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
`)
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
`)}`).
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
${
|
|
133
|
-
|
|
134
|
-
|
|
51
|
+
`)},info:(e,t)=>{l.message(e,{...t,symbol:p("blue",Ui)})},success:(e,t)=>{l.message(e,{...t,symbol:p("green",Gi)})},step:(e,t)=>{l.message(e,{...t,symbol:p("green",et)})},warn:(e,t)=>{l.message(e,{...t,symbol:p("yellow",xi)})},warning:(e,t)=>{l.warn(e,t)},error:(e,t)=>{l.message(e,{...t,symbol:p("red",qi)})}};var rt=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??W.withGuide?`${p("gray",Ei)} `:"";n.write(`${r}${e}
|
|
52
|
+
`)},it=(e="",t)=>{let n=t?.output??process.stdout,r=t?.withGuide??W.withGuide?`${p("gray",v)}
|
|
53
|
+
${p("gray",he)} `:"";n.write(`${r}${e}
|
|
54
|
+
|
|
55
|
+
`)};var Wi=(e)=>e,Ji=(e,t,n)=>{let r={hard:!0,trim:!1},i=re(e,t,r).split(`
|
|
56
|
+
`),s=i.reduce((g,m)=>Math.max(Y(m),g),0),o=i.map(n).reduce((g,m)=>Math.max(Y(m),g),0),a=t-(o-s);return re(e,a,r)},N=(e="",t="",n)=>{let r=n?.output??Q.stdout,i=n?.withGuide??W.withGuide,s=n?.format??Wi,o=["",...Ji(e,Ne(r)-6,s).split(`
|
|
57
|
+
`).map(s),""],a=Y(t),g=Math.max(o.reduce((y,b)=>{let h=Y(b);return h>y?h:y},0),a)+2,m=o.map((y)=>`${p("gray",v)} ${y}${" ".repeat(g-Y(y))}${p("gray",v)}`).join(`
|
|
58
|
+
`),u=i?`${p("gray",v)}
|
|
59
|
+
`:"",f=i?Ai:Bi;r.write(`${u}${p("green",et)} ${p("reset",t)} ${p("gray",Qn.repeat(Math.max(g-a-1,1))+Oi)}
|
|
60
|
+
${m}
|
|
61
|
+
${p("gray",f+Qn.repeat(g+2)+Ni)}
|
|
62
|
+
`)};var Vi=(e)=>p("magenta",e),K=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:i,frames:s=Ut?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Ut?80:120,signal:a,...g}={})=>{let m=Di(),u,f,y=!1,b=!1,h="",P,j=performance.now(),B=Ne(n),k=g?.styleFrame??Vi,H=(U)=>{let T=U>1?i??W.messages.error:r??W.messages.cancel;b=U===1,y&&(Oe(T,U),b&&typeof t=="function"&&t())},L=()=>H(2),C=()=>H(1),x=()=>{process.on("uncaughtExceptionMonitor",L),process.on("unhandledRejection",L),process.on("SIGINT",C),process.on("SIGTERM",C),process.on("exit",H),a&&a.addEventListener("abort",C)},O=()=>{process.removeListener("uncaughtExceptionMonitor",L),process.removeListener("unhandledRejection",L),process.removeListener("SIGINT",C),process.removeListener("SIGTERM",C),process.removeListener("exit",H),a&&a.removeEventListener("abort",C)},E=()=>{if(P===void 0)return;m&&n.write(`
|
|
63
|
+
`);let U=re(P,B,{hard:!0,trim:!1}).split(`
|
|
64
|
+
`);U.length>1&&n.write(Ue.cursor.up(U.length-1)),n.write(Ue.cursor.to(0)),n.write(Ue.erase.down())},G=(U)=>U.replace(/\.+$/,""),ne=(U)=>{let T=(performance.now()-U)/1000,ie=Math.floor(T/60),se=Math.floor(T%60);return ie>0?`[${ie}m ${se}s]`:`[${se}s]`},z=g.withGuide??W.withGuide,Ve=(U="")=>{y=!0,u=Wn({output:n}),h=G(U),j=performance.now(),z&&n.write(`${p("gray",v)}
|
|
65
|
+
`);let T=0,ie=0;x(),f=setInterval(()=>{if(m&&h===P)return;E(),P=h;let se=k(s[T]),ze;if(m)ze=`${se} ${h}...`;else if(e==="timer")ze=`${se} ${h} ${ne(j)}`;else{let Vr=".".repeat(Math.floor(ie)).slice(0,3);ze=`${se} ${h}${Vr}`}let Jr=re(ze,B,{hard:!0,trim:!1});n.write(Jr),T=T+1<s.length?T+1:0,ie=ie<4?ie+0.125:0},o)},Oe=(U="",T=0,ie=!1)=>{if(!y)return;y=!1,clearInterval(f),E();let se=T===0?p("green",et):T===1?p("red",Xn):p("red",er);h=U??h,ie||(e==="timer"?n.write(`${se} ${h} ${ne(j)}
|
|
66
|
+
`):n.write(`${se} ${h}
|
|
67
|
+
`)),O(),u()};return{start:Ve,stop:(U="")=>Oe(U,0),message:(U="")=>{h=G(U??h)},cancel:(U="")=>Oe(U,1),error:(U="")=>Oe(U,2),clear:()=>Oe("",0,!0),get isCancelled(){return b}}},Ko={light:M("\u2500","-"),heavy:M("\u2501","="),block:M("\u2588","#")};var zi=[`${p("dim","\u2191/\u2193")} to navigate`,`${p("dim","Enter:")} confirm`],_e=(e,t)=>e.includes(`
|
|
68
|
+
`)?e.split(`
|
|
69
|
+
`).map((n)=>t(n)).join(`
|
|
70
|
+
`):t(e),sr=(e)=>{let t=(r,i)=>{if(r===void 0)return"";let s=r.label??String(r.value);switch(i){case"disabled":return`${p("gray",Xe)} ${_e(s,(o)=>p("gray",o))}${r.hint?` ${p("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${_e(s,(o)=>p("dim",o))}`;case"active":return`${p("green",Gt)} ${s}${r.hint?` ${p("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${_e(s,(o)=>p(["strikethrough","dim"],o))}`;default:return`${p("dim",Xe)} ${_e(s,(o)=>p("dim",o))}`}},n=e.showInstructions??!0;return new Kn({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??W.withGuide,i=`${tt(this.state)} `,s=`${tr(this.state)} `,o=ue(e.output,e.message,s,i),a=`${r?`${p("gray",v)}
|
|
71
|
+
`:""}${o}
|
|
72
|
+
`;switch(this.state){case"submit":{let g=r?`${p("gray",v)} `:"",m=ue(e.output,t(this.options[this.cursor],"selected"),g);return`${a}${m}`}case"cancel":{let g=r?`${p("gray",v)} `:"",m=ue(e.output,t(this.options[this.cursor],"cancelled"),g);return`${a}${m}${r?`
|
|
73
|
+
${p("gray",v)}`:""}`}default:{let g=r?`${p("cyan",v)} `:"",m=a.split(`
|
|
74
|
+
`).length,u=n?nr(zi,r):r?[p("cyan",he)]:[],f=u.join(`
|
|
75
|
+
`),y=u.length+1;return`${a}${g}${xt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:g.length,rowPadding:m+y,style:(b,h)=>t(b,b.disabled?"disabled":h?"active":"inactive")}).join(`
|
|
76
|
+
${g}`)}
|
|
77
|
+
${f}
|
|
78
|
+
`}}}}).prompt()};var Zo=`${p("gray",v)} `;var or=(e)=>new Bt({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??W.withGuide,n=`${`${t?`${p("gray",v)}
|
|
79
|
+
`:""}${tt(this.state)} `}${e.message}
|
|
80
|
+
`,r=e.placeholder&&e.placeholder.length>0?p("inverse",e.placeholder[0])+p("dim",e.placeholder.slice(1)):p(["inverse","hidden"],"_"),i=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"error":{let o=this.error?` ${p("yellow",this.error)}`:"",a=t?`${p("yellow",v)} `:"",g=t?p("yellow",he):"";return`${n.trim()}
|
|
81
|
+
${a}${i}
|
|
82
|
+
${g}${o}
|
|
83
|
+
`}case"submit":{let o=s?` ${p("dim",s)}`:"",a=t?p("gray",v):"";return`${n}${a}${o}`}case"cancel":{let o=s?` ${p(["strikethrough","dim"],s)}`:"",a=t?p("gray",v):"";return`${n}${a}${o}${s.trim()?`
|
|
84
|
+
${a}`:""}`}default:{let o=t?`${p("cyan",v)} `:"",a=t?p("cyan",he):"";return`${n}${o}${i}
|
|
85
|
+
${a}
|
|
86
|
+
`}}}}).prompt();var Ki=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),gr=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Zi=["bold","dim","italic","underline","reset"],mr={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Ti={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"},Qi={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"},ar={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};function st(e){return(t)=>Ki?`${e}${t}${mr.reset}`:t}function _i(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32&&n!==27)return!1}return!0}function cr({bright:e=!1,color:t}){let n=Bun.color(t,"ansi"),r=typeof n==="string"&&n.length>0&&_i(n)?n:Ti[t];if(!r)return"";return e&&r in ar?ar[r]:r}var Xi=gr.reduce((e,t)=>{let n=cr({color:t});if(n)e[t]=st(n);let r=cr({bright:!0,color:t});if(r)e[`${t}Bright`]=st(r);return e},{}),es=Zi.reduce((e,t)=>{return e[t]=st(mr[t]),e},{}),ts=gr.reduce((e,t)=>{let n=Qi[t];if(n){let r=`bg${t.charAt(0).toUpperCase()}${t.slice(1)}`;e[r]=st(n)}return e},{}),c={...Xi,...es,...ts};function ot(e){if(Ae(e))throw new te;return e}function rs(e){return e.map((t)=>t.key?`${c.bold(t.key)} ${c.dim(t.text)}`:c.dim(t.text)).join(c.dim(" \xB7 "))}function at(e){l.info(rs(e))}var ct={confirm:[{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],multiselect:[{key:"\u2191\u2193",text:"navigate"},{key:"Space",text:"toggle"},{key:"a",text:"all"},{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],select:[{key:"\u2191\u2193",text:"navigate"},{key:"Enter",text:"select"},{key:"Esc",text:"cancel"}],text:[{key:"Enter",text:"submit"},{key:"Esc",text:"cancel"}]};async function F(e){return at(ct.confirm),ot(await rr(e))}async function Z(e){return at(ct.text),ot(await or(e))}async function ye(e){return at(ct.select),ot(await sr({showInstructions:!1,...e}))}async function ce(e){return at(ct.multiselect),ot(await ir({showInstructions:!1,...e}))}var w={arg:c.magenta,cmd:c.cyan,default:c.blue,desc:c.white,flag:c.green,header:(e)=>c.bold(c.yellow(e)),hint:c.dim,name:(e)=>c.bold(c.cyan(e)),placeholder:c.magenta};class qt{metadata;commands;globalArgs;constructor(e,t,n){this.metadata=e;this.commands=t;this.globalArgs=n}version(){return`${w.name(this.metadata.name)} ${w.hint(this.metadata.version??"0.0.0")}`}global(){let e=[],{name:t,bin:n,version:r,description:i}=this.metadata;if(e.push(""),e.push(`${w.name(t)}${r?` ${w.hint(`v${r}`)}`:""}`),i)e.push(w.desc(i));e.push(""),e.push(w.header("Usage:")),e.push(` ${w.cmd(n)} ${w.placeholder("[command]")} ${w.hint("[options]")}`),e.push(""),e.push(w.header("Commands:"));let s=Array.from(this.commands.values()).map((o)=>[` ${w.cmd(o.name)}`,w.desc(o.description)]);return e.push(...this.formatColumns(s)),e.push(""),e.push(w.header("Options:")),e.push(...this.formatArgDefs(this.globalArgs)),e.push(""),e.push(w.hint(`Run "${n} <command> --help" for command-specific options.`)),e.push(""),e.join(`
|
|
87
|
+
`)}command(e,t){let n=[],r=t??this.metadata.bin,i=`${w.cmd(r)} ${w.cmd(e.name)}`;n.push(""),n.push(`${w.name(e.name)} ${w.hint("-")} ${w.desc(e.description)}`),n.push(""),n.push(w.header("Usage:"));let s=this.formatPositionalUsage(e.positionals);if(e.hasSubcommands())n.push(` ${i} ${w.placeholder("<subcommand>")} ${w.hint("[options]")}`);else{let g=[i];if(s)g.push(s);g.push(w.hint("[options]")),n.push(` ${g.join(" ")}`)}if(e.prompts)n.push(` ${i} ${w.hint("- runs interactively")}`);if(n.push(""),e.hasSubcommands()){n.push(w.header("Subcommands:"));let g=e.getSubcommands().map((m)=>[` ${w.cmd(m.name)}`,w.desc(m.description)]);n.push(...this.formatColumns(g)),n.push("")}if(Object.entries(e.positionals).length>0)n.push(w.header("Arguments:")),n.push(...this.formatPositionalDefs(e.positionals)),n.push("");if(Object.entries(e.args).length>0)n.push(w.header("Options:")),n.push(...this.formatArgDefs(e.args)),n.push("");return n.join(`
|
|
88
|
+
`)}formatPositionalUsage(e){return Object.entries(e).map(([t,n])=>{let r=n.variadic?`${t}...`:t;return n.required?w.arg(`<${r}>`):w.arg(`[${r}]`)}).join(" ")}formatPositionalDefs(e){let t=Object.entries(e).map(([n,r])=>{let i=r.variadic?`${n}...`:n,s=w.desc(r.description??""),o=r.required?"":w.hint(" (optional)");return[` ${w.arg(i)}`,`${s}${o}`]});return this.formatColumns(t)}formatArgDefs(e){let t=[];for(let[n,r]of Object.entries(e)){let s=`${r.alias?`${w.flag(`-${r.alias}`)}, `:" "}${w.flag(`--${n}`)}`,o=w.desc(r.description??""),a=r.default!==void 0?w.hint(` (default: ${w.default(this.formatDefault(r))})`):"";t.push([` ${s}`,`${o}${a}`])}return this.formatColumns(t)}formatDefault(e){if(e.type==="string")return`"${e.default}"`;return String(e.default)}formatColumns(e){if(e.length===0)return[];let t=Math.max(...e.map(([r])=>this.stripAnsi(r).length)),n=2;return e.map(([r,i])=>{let s=t-this.stripAnsi(r).length+n;return`${r}${" ".repeat(s)}${i}`})}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}}var ge=new Uint32Array(65536),is=(e,t)=>{let n=e.length,r=t.length,i=1<<n-1,s=-1,o=0,a=n,g=n;while(g--)ge[e.charCodeAt(g)]|=1<<g;for(g=0;g<r;g++){let m=ge[t.charCodeAt(g)],u=m|o;if(m|=(m&s)+s^s,o|=~(m|s),s&=m,o&i)a++;if(s&i)a--;o=o<<1|1,s=s<<1|~(u|o),o&=u}g=n;while(g--)ge[e.charCodeAt(g)]=0;return a},ss=(e,t)=>{let n=t.length,r=e.length,i=[],s=[],o=Math.ceil(n/32),a=Math.ceil(r/32);for(let h=0;h<o;h++)s[h]=-1,i[h]=0;let g=0;for(;g<a-1;g++){let h=0,P=-1,j=g*32,B=Math.min(32,r)+j;for(let k=j;k<B;k++)ge[e.charCodeAt(k)]|=1<<k;for(let k=0;k<n;k++){let H=ge[t.charCodeAt(k)],L=s[k/32|0]>>>k&1,C=i[k/32|0]>>>k&1,x=H|h,O=((H|C)&P)+P^P|H|C,E=h|~(O|P),G=P&O;if(E>>>31^L)s[k/32|0]^=1<<k;if(G>>>31^C)i[k/32|0]^=1<<k;E=E<<1|L,G=G<<1|C,P=G|~(x|E),h=E&x}for(let k=j;k<B;k++)ge[e.charCodeAt(k)]=0}let m=0,u=-1,f=g*32,y=Math.min(32,r-f)+f;for(let h=f;h<y;h++)ge[e.charCodeAt(h)]|=1<<h;let b=r;for(let h=0;h<n;h++){let P=ge[t.charCodeAt(h)],j=s[h/32|0]>>>h&1,B=i[h/32|0]>>>h&1,k=P|m,H=((P|B)&u)+u^u|P|B,L=m|~(H|u),C=u&H;if(b+=L>>>r-1&1,b-=C>>>r-1&1,L>>>31^j)s[h/32|0]^=1<<h;if(C>>>31^B)i[h/32|0]^=1<<h;L=L<<1|j,C=C<<1|B,u=C|~(k|L),m=L&k}for(let h=f;h<y;h++)ge[e.charCodeAt(h)]=0;return b},os=(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 is(e,t);return ss(e,t)},pr=(e,t)=>{let n=1/0,r=0;for(let i=0;i<t.length;i++){let s=os(e,t[i]);if(s<n)n=s,r=i}return t[r]};function gt(e,t,n,r){let i=pr(t,n);if(console.error(c.red(`Unknown ${e}: ${t}`)),i)console.error(c.yellow(`Did you mean "${i}"?`));console.error(`
|
|
89
|
+
Run "${r} --help" for usage.`),process.exit(1)}function be(e,t){let n=(i)=>i&&typeof i==="object";if(!n(e)||!n(t))return t;let r={...e};for(let i of Object.keys(t)){let s=r[i],o=t[i];if(Array.isArray(s)&&Array.isArray(o))r[i]=[...o];else if(n(s)&&n(o))r[i]=be(s,o);else r[i]=o}return r}function Ht(e){return e==null?[]:Array.isArray(e)?e:[e]}function as(e,t,n,r){var i,s=e[t],o=~r.string.indexOf(t)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~r.boolean.indexOf(t)?n==="false"?!1:n==="true"||(e._.push((i=+n,i*0===0)?i:n),!!n):(i=+n,i*0===0)?i:n;e[t]=s==null?o:Array.isArray(s)?s.concat(o):[s,o]}function mt(e,t){e=e||[],t=t||{};var n,r,i,s,o,a={_:[]},g=0,m=0,u=0,f=e.length;let y=t.alias!==void 0,b=t.unknown!==void 0,h=t.default!==void 0;if(t.alias=t.alias||{},t.string=Ht(t.string),t.boolean=Ht(t.boolean),y)for(n in t.alias){r=t.alias[n]=Ht(t.alias[n]);for(g=0;g<r.length;g++)(t.alias[r[g]]=r.concat(n)).splice(g,1)}for(g=t.boolean.length;g-- >0;){r=t.alias[t.boolean[g]]||[];for(m=r.length;m-- >0;)t.boolean.push(r[m])}for(g=t.string.length;g-- >0;){r=t.alias[t.string[g]]||[];for(m=r.length;m-- >0;)t.string.push(r[m])}if(h){for(n in t.default)if(s=typeof t.default[n],r=t.alias[n]=t.alias[n]||[],t[s]!==void 0){t[s].push(n);for(g=0;g<r.length;g++)t[s].push(r[g])}}let P=b?Object.keys(t.alias):[];for(g=0;g<f;g++){if(i=e[g],i==="--"){a._=a._.concat(e.slice(++g));break}for(m=0;m<i.length;m++)if(i.charCodeAt(m)!==45)break;if(m===0)a._.push(i);else if(i.substring(m,m+3)==="no-"){if(s=i.substring(m+3),b&&!~P.indexOf(s))return t.unknown(i);a[s]=!1}else{for(u=m+1;u<i.length;u++)if(i.charCodeAt(u)===61)break;s=i.substring(m,u),o=i.substring(++u)||(g+1===f||(""+e[g+1]).charCodeAt(0)===45||e[++g]),r=m===2?[s]:s;for(u=0;u<r.length;u++){if(s=r[u],b&&!~P.indexOf(s))return t.unknown("-".repeat(m)+s);as(a,s,u+1<r.length||o,t)}}}if(h){for(n in t.default)if(a[n]===void 0)a[n]=t.default[n]}if(y)for(n in a){r=t.alias[n]||[];while(r.length>0)a[r.shift()]=a[n]}return a}function cs(e){return e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function lr(e){let t={alias:{},boolean:[],default:{},string:[]};for(let[n,r]of Object.entries(e)){if(r.type==="boolean")t.boolean.push(n);else t.string.push(n);if(r.alias)t.alias[r.alias]=n;let i=cs(n);if(i!==n)t.alias[i]=n;if(r.default!==void 0)t.default[n]=r.default}return t}function ur(e,t){let n={...e};for(let[r,i]of Object.entries(t)){if(i.type!=="number")continue;let s=e[r];if(s===void 0||typeof s==="boolean")continue;let o=Number(s);if(Number.isNaN(o))throw Error(`Invalid number for --${r}: "${s}"`);n[r]=o}return n}function hr(e,t){let n=lr(t),r=mt(e,n),i=r._[0],s=i?e.indexOf(i):-1,{_:o,...a}=r,g=ur(a,t);return{command:i,flags:g,restArgs:s>=0?e.slice(s+1):[]}}function Wt(e,t={}){let n=lr(t),r=mt(e,n),{_:i,...s}=r;return{args:ur(s,t),rawPositionals:i}}function Jt(e,t){let n={},r=Object.entries(t);for(let[i,[s,o]]of r.entries())n[s]=o.variadic?e.slice(i):e[i];return n}function fr(e,t){for(let[n,r]of Object.entries(t)){if(!r.required)continue;let i=e[n];if(Array.isArray(i)?i.length===0:!i)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}var Vt="__exit__";class Re{command;env;prefix;options;constructor(e,t,n,r={}){this.command=e;this.env=t;this.prefix=n;this.options=r}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(e,t){if(t)await this.routeInteractive();else await this.routeDirect(e)}async routeDirect(e){let[t,...n]=e;if(t&&this.command.hasSubcommands()){let r=this.command.getSubcommand(t);if(r){await this.handleSubcommandRoute(r,n);return}if(!t.startsWith("-")){this.handleUnknownSubcommand(t);return}}await this.executeCommand(e)}handleUnknownSubcommand(e){let t=this.command.getSubcommands().map((n)=>n.name);gt("subcommand",e,t,this.commandPath)}async handleSubcommandRoute(e,t){await new Re(e,this.env,this.commandPath).route(t,!1)}async executeCommand(e){if(this.isHelpRequest(e)){this.printHelp(this.command);return}if(this.command.hasSubcommands()&&!this.command.execute){this.printHelp(this.command);return}if(!this.command.execute)return;let{args:n,rawPositionals:r}=Wt(e,this.command.args),i=Jt(r,this.command.positionals),s=fr(i,this.command.positionals);if(s)l.error(s),console.error(`
|
|
90
|
+
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&r.length===0,a=this.buildContext(i,n,o);await this.command.execute(a)}async routeInteractive(){if(!this.command.hasSubcommands()){await this.executeInteractive();return}await this.runSubcommandMenu()}async executeInteractive(){let{args:e}=Wt([],this.command.args),t=Jt([],this.command.positionals),n=this.buildContext(t,e,!0);await this.command.execute?.(n)}async runSubcommandMenu(){while(!0){let e=await this.promptSubcommandSelectionOrBack();if(e===null)return;if(e===Vt){this.options.onExit?.();return}let t=this.command.getSubcommand(e);if(t)await this.executeSubcommand(t)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(e){if(e instanceof te){if(this.options.isRoot)this.options.onExit?.();return null}throw e}}async executeSubcommand(e){try{await new Re(e,this.env,this.commandPath).route([],!0)}catch(t){if(t instanceof te)return;if(t instanceof d){if(l.warn(c.yellow(t.message)),t.hint)l.info(c.dim(t.hint));return}throw t}}promptSubcommandSelection(){let{isRoot:e}=this.options,t=e?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Vt}:{hint:"Return to previous menu",label:"Back",value:Vt};return ye({message:e?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,options:[...this.command.getSubcommands().map((n)=>({hint:n.description,label:n.name,value:n.name})),t]})}buildContext(e,t,n){return{...this.env,args:t,interactive:n,positionals:e}}isHelpRequest(e){return e.includes("--help")||e.includes("-h")}printHelp(e){let t=e===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(e,t))}}var gs={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"};class zt{commands=new Map;metadata;configManager;help;bin;globalArgs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Enable interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};constructor(e,t){this.configManager=e,this.metadata={...gs,...t},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new qt({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(e){for(let t of e)t.init?.(),this.commands.set(t.name,t)}async run(e=process.argv.slice(2)){let{command:t,flags:n,restArgs:r}=hr(e,this.globalArgs);if(n.version&&!t)return console.log(this.help.version());if(n.interactive&&!t)return this.runInteractive();if(!t)return console.log(this.help.global());if(t==="help")return this.printHelpFor(r[0]);await this.runDirect(t,r,!!n.help)}printHelpFor(e){if(!e)return console.log(this.help.global());let t=this.commands.get(e);if(!t)return this.handleUnknownCommand(e);console.log(this.help.command(t))}async runInteractive(){this.showIntro();let e=this.createVirtualRootCommand(),t={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},n=new Re(e,t,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await n.route([],!0)}catch(r){this.handleError(r)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(e)=>this.commands.get(e),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){it(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(e,t,n){let r=this.commands.get(e);if(!r)return this.handleUnknownCommand(e);let i=t.length>0&&!t[0]?.startsWith("-");if(n&&!i)return console.log(this.help.command(r));try{let s={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new Re(r,s,this.bin).route(t,!1)}catch(s){this.handleError(s)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let e=this.metadata.version?` v${this.metadata.version}`:"";rt(`${c.bgCyan(c.black(` ${this.metadata.name}${e} `))}`)}handleUnknownCommand(e){let t=Array.from(this.commands.keys());gt("command",e,t,this.bin)}handleError(e){if(this.metadata.onError?.(e))return;if(e instanceof te)process.exit(0);if(e instanceof d){if(l.warn(c.yellow(e.message)),e.hint)l.info(c.dim(e.hint));process.exit(0)}if(e instanceof Error)l.error(c.red(e.message)),process.exit(1);console.error(c.red("Error:"),e),process.exit(1)}}class Ge{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(e){for(let t of e)t.init?.(),this.subcommands.set(t.name,t)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(e){return this.subcommands.get(e)}getSubcommands(){return Array.from(this.subcommands.values())}}function D(e){return e}function _(e){return e}import Se from"fs";import dr from"path";class Yt{config;configPath;defaultConfig;constructor(e,t){this.configPath=dr.resolve(e),this.defaultConfig=t,this.config=this.loadConfig()}get(e){return this.config[e]}set(e,t){this.config[e]=t,this.save()}delete(e){delete this.config[e],this.save()}exists(){return Se.existsSync(this.configPath)}getAll(){return be({},this.config)}save(e){if(e)this.config={...e};this.ensureDirectoryExists();try{Se.writeFileSync(this.configPath,JSON.stringify(this.config,null,2))}catch(t){console.error(`Failed to save config to ${this.configPath}:`,t)}}ensureDirectoryExists(){let e=dr.dirname(this.configPath);if(!Se.existsSync(e))try{Se.mkdirSync(e,{recursive:!0})}catch(t){console.error(`Failed to create config directory at ${e}:`,t)}}loadConfig(){if(!Se.existsSync(this.configPath))return{...this.defaultConfig};try{let e=Se.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return be({...this.defaultConfig},t)}catch{return console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),{...this.defaultConfig}}}}var yr="0.5.1";class I extends Ge{}import{existsSync as Cs}from"fs";import{mkdir as $s,writeFile as Rs}from"fs/promises";import{dirname as Ss}from"path";class fe{owner;repo;constructor(e){this.owner=e.owner,this.repo=e.repo}}class pt extends fe{name="bitbucket";notImplemented(){throw new d("Bitbucket is not supported yet","Bitbucket support is coming soon")}async ensureAvailable(){this.notImplemented()}async getDefaultBranch(){this.notImplemented()}async findPr(e){this.notImplemented()}async createPr(e){this.notImplemented()}async updatePr(e,t){this.notImplemented()}async getPr(e){this.notImplemented()}async getPrFromCurrentBranch(){this.notImplemented()}async getPrCommits(e){this.notImplemented()}async getPrFiles(e){this.notImplemented()}async ensureLabelExists(e,t){this.notImplemented()}async createRelease(e){this.notImplemented()}async deleteRelease(e){this.notImplemented()}}var A="sis",Kt="\uD83E\uDEA8",de="other",Me={build:23,chore:25,ci:24,docs:20,feat:10,"feat!":0,fix:11,"fix!":1,perf:12,refactor:13,style:21,test:22,["other"]:100},Ie=50,lt=".sisyphus",br="stones",Pr="released",ut=7,wr="unknown",xe="unknown",vr="0.0.0",kr="latest",me="main",Cr=4,$r=8,Rr="config.json";var Fe={$schema:"https://raw.githubusercontent.com/r5n-labs/clis/refs/heads/develop/packages/sisyphus/schema.json",changelog:{append:!0,filename:"CHANGELOG.md",generate:!0,packageHeader:"{emoji} {version} ({date})",root:!1,rootHeader:"{date} - {packages}",sections:{breaking:"Breaking changes",build:"Build",chore:"Chores",ci:"CI",dependencies:"Dependency updates",docs:"Documentation",feat:"Features",fix:"Bug fixes",other:"Other changes",perf:"Performance",refactor:"Refactoring",style:"Styling",test:"Tests"}},commit:{author:"r5n-bot",message:"chore(release): {message}"},commits:{skip:{authors:["r5n-bot[bot]"],messagePatterns:["^chore\\(release\\):","^chore: add stone"]}},ignore:[],lastStone:{commit:"",date:""},plugins:[],pr:{labelMapping:{breaking:"major","breaking-change":"major",bug:"patch",chore:"patch",docs:"patch",enhancement:"minor",feature:"minor",fix:"patch"},skip:{authors:["r5n-bot[bot]"],labels:["sisyphus-release","skip-stone"],titlePatterns:["^chore\\(release\\):"]}},release:{createRelease:!1,npm:!1,push:!1,tags:!1},scripts:{post:{},pre:{}},single:!1,sisyphusDir:".sisyphus",stones:[],tag:"latest"};class ht extends fe{name="github";get apiPath(){return`repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}`}async ensureAvailable(){try{await Bun.$`which gh`.quiet()}catch{throw new d("GitHub CLI (gh) is not installed","Install from https://cli.github.com and run: gh auth login")}try{await Bun.$`gh auth status`.quiet()}catch{throw new d("GitHub CLI (gh) is not authenticated","Run: gh auth login")}}async getDefaultBranch(){try{return(await Bun.$`gh repo view --json defaultBranchRef --jq .defaultBranchRef.name`.quiet()).stdout.toString().trim()||me}catch{return me}}async findPr(e){try{let t=[];if(e.head)t.push("--head",e.head);if(e.label)t.push("--label",e.label);let n=await Bun.$`gh pr list --json number,url,title,body,labels,author,headRefName,baseRefName,mergeCommit,state --limit 1 ${t}`.quiet(),r=JSON.parse(n.stdout.toString());if(!r[0])return null;return this.mapPrResponse(r[0])}catch{return null}}async createPr(e){let t=await Bun.$`gh api ${this.apiPath}/pulls --method POST -f head=${e.head} -f base=${e.base} -f title=${e.title} -f body=${e.body}`,r=JSON.parse(t.stdout.toString()).number;if(e.labels&&e.labels.length>0){let i=e.labels.flatMap((s)=>["-f",`labels[]=${s}`]);await Bun.$`gh api ${this.apiPath}/issues/${r}/labels --method POST ${i}`}return this.getPr(r)}async updatePr(e,t){let n=[];if(t.title)n.push("--title",t.title);if(t.body)n.push("--body",t.body);await Bun.$`gh pr edit ${e} ${n}`}async getPr(e){try{let t=await Bun.$`gh api ${this.apiPath}/pulls/${e}`.quiet(),n=JSON.parse(t.stdout.toString());return this.mapRestApiResponse(n)}catch{throw new d(`Failed to fetch PR #${e}`,"Make sure the PR exists and you have access")}}async getPrFromCurrentBranch(){try{let e=await Bun.$`gh pr view --json number,title,body,labels,author,headRefName,baseRefName,url,mergeCommit,state`.quiet(),t=JSON.parse(e.stdout.toString());return this.mapPrResponse(t)}catch{throw new d("No PR found for current branch","Make sure you have an open PR or provide a URL with --url")}}async getPrCommits(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/commits --jq '.[].sha'`.quiet()).stdout.toString().trim().split(`
|
|
91
|
+
`).filter(Boolean)}catch{return[]}}async getPrFiles(e){try{return(await Bun.$`gh api ${this.apiPath}/pulls/${e}/files --jq '.[].filename'`.quiet()).stdout.toString().trim().split(`
|
|
92
|
+
`).filter(Boolean)}catch{return[]}}async ensureLabelExists(e,t){try{let n=t?.description??"",r=t?.color?["--color",t.color]:[];await Bun.$`gh label create ${e} --description ${n} ${r} --force`.quiet()}catch{}}async createRelease(e){await Bun.$`gh release create ${e.tag} --title ${e.title} --notes ${e.notes}`}async deleteRelease(e){try{await Bun.$`gh release delete ${e} --yes`.quiet()}catch{}}mapRestApiResponse(e){return{author:e.user?.login??xe,baseBranch:e.base?.ref??me,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??xe,baseBranch:e.baseRefName??me,body:e.body??"",headBranch:e.headRefName??"",labels:e.labels?.map((t)=>t.name)??[],mergeCommitSha:e.mergeCommit?.oid??null,merged:e.state==="MERGED",number:e.number,title:e.title,url:e.url}}}var ps="https://gitlab.com/api/v4";class ft extends fe{name="gitlab";authHeader={};apiUrl;projectPath;constructor(e){super(e);this.apiUrl=process.env.CI_API_V4_URL??ps,this.projectPath=encodeURIComponent(`${this.owner}/${this.repo}`)}async ensureAvailable(){this.authHeader=await this.resolveAuth()}async getDefaultBranch(){try{return(await this.api(`/projects/${this.projectPath}`)).default_branch||me}catch{return me}}async findPr(e){try{let t=new URLSearchParams({per_page:"1",state:"opened"});if(e.head)t.set("source_branch",e.head);if(e.label)t.set("labels",e.label);let n=await this.api(`/projects/${this.projectPath}/merge_requests?${t}`);if(!n[0])return null;return this.mapMrResponse(n[0])}catch{return null}}async createPr(e){let t={description:e.body,source_branch:e.head,target_branch:e.base,title:e.title};if(e.labels?.length)t.labels=e.labels.join(",");let n=await this.api(`/projects/${this.projectPath}/merge_requests`,{body:JSON.stringify(t),method:"POST"});return this.mapMrResponse(n)}async updatePr(e,t){let n={};if(t.title)n.title=t.title;if(t.body)n.description=t.body;await this.api(`/projects/${this.projectPath}/merge_requests/${e}`,{body:JSON.stringify(n),method:"PUT"})}async getPr(e){try{let t=await this.api(`/projects/${this.projectPath}/merge_requests/${e}`);return this.mapMrResponse(t)}catch{throw new d(`Failed to fetch MR !${e}`,"Make sure the MR exists and you have access")}}async getPrFromCurrentBranch(){try{let t=(await Bun.$`git rev-parse --abbrev-ref HEAD`.quiet()).stdout.toString().trim(),n=new URLSearchParams({per_page:"1",source_branch:t,state:"opened"}),r=await this.api(`/projects/${this.projectPath}/merge_requests?${n}`);if(!r[0])throw Error("No MR found");return this.mapMrResponse(r[0])}catch{throw new d("No MR found for current branch","Make sure you have an open MR or provide a URL with --url")}}async getPrCommits(e){try{return(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/commits`)).map((n)=>n.id)}catch{return[]}}async getPrFiles(e){try{return(await this.api(`/projects/${this.projectPath}/merge_requests/${e}/changes`)).changes?.map((n)=>n.new_path)??[]}catch{return[]}}async ensureLabelExists(e,t){try{let n={name:e};if(t?.description)n.description=t.description;if(t?.color)n.color=`#${t.color}`;await this.api(`/projects/${this.projectPath}/labels`,{body:JSON.stringify(n),method:"POST"})}catch{}}async createRelease(e){await this.api(`/projects/${this.projectPath}/releases`,{body:JSON.stringify({description:e.notes,name:e.title,tag_name:e.tag}),method:"POST"})}async deleteRelease(e){try{await this.api(`/projects/${this.projectPath}/releases/${encodeURIComponent(e)}`,{method:"DELETE"})}catch{}}async resolveAuth(){if(process.env.GITLAB_TOKEN)return{"PRIVATE-TOKEN":process.env.GITLAB_TOKEN};if(process.env.CI_JOB_TOKEN)return{"JOB-TOKEN":process.env.CI_JOB_TOKEN};try{let e=await Bun.$`glab auth status --show-token`.quiet(),n=(e.stdout.toString()+e.stderr.toString()).match(/Token found:\s*(\S+)/);if(n?.[1])return{Authorization:`Bearer ${n[1]}`}}catch{}throw new d("GitLab token not found","Set GITLAB_TOKEN environment variable or install glab CLI and run: glab auth login")}async api(e,t){let n=await fetch(`${this.apiUrl}${e}`,{...t,headers:{"Content-Type":"application/json",...this.authHeader,...t?.headers}});if(!n.ok){let r=await n.text().catch(()=>"");throw Error(`GitLab API error: ${n.status} ${n.statusText}${r?` \u2014 ${r}`:""}`)}return n.json()}mapMrResponse(e){return{author:e.author?.username??xe,baseBranch:e.target_branch??me,body:e.description??"",headBranch:e.source_branch??"",labels:e.labels??[],mergeCommitSha:e.merge_commit_sha,merged:e.state==="merged",number:e.iid,title:e.title,url:e.web_url}}}var ls=/github\.com[:/]([^/]+)\/([^/.]+)/,us=/gitlab\.com[:/]([^/]+)\/([^/.]+)/,hs=/bitbucket\.org[:/]([^/]+)\/([^/.]+)/,fs=/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/,ds=/gitlab\.com\/([^/]+)\/([^/]+)\/-\/merge_requests\/(\d+)/,ys=/bitbucket\.org\/([^/]+)\/([^/]+)\/pull-requests\/(\d+)/;async function De(){let e=await Sr();if(!e)throw new d("Could not detect git provider","Make sure you have a git remote configured (origin)");let t=bs(e);return await t.ensureAvailable(),t}function bs(e){switch(e.provider){case"github":return new ht(e);case"gitlab":return new ft(e);case"bitbucket":return new pt(e);default:throw new d(`Unsupported provider: ${e.provider}`)}}async function Sr(){let e=await Zt();if(!e)return null;return Tt(e)}async function Mr(){let e=await Sr();if(!e)throw new d("Could not detect git provider","Make sure you have a git remote configured (origin)");return e.provider}async function Zt(){try{return(await Bun.$`git remote get-url origin`.quiet()).stdout.toString().trim()||null}catch{return null}}function Tt(e){let t=[[ls,"github"],[us,"gitlab"],[hs,"bitbucket"]];for(let[n,r]of t){let i=e.match(n);if(!i)continue;let[,s,o]=i;if(s&&o)return{owner:s,provider:r,repo:o}}return null}function Qt(e){let t=[[fs,"github"],[ds,"gitlab"],[ys,"bitbucket"]];for(let[n,r]of t){let i=e.match(n);if(!i)continue;let[,s,o,a]=i;if(s&&o&&a)return{number:Number.parseInt(a,10),owner:s,provider:r,repo:o}}return null}import{existsSync as Ir}from"fs";import{readFile as Ps}from"fs/promises";import{dirname as ws,join as _t}from"path";import{fileURLToPath as vs}from"url";var dt={"create-stone":{description:"When a PR is merged, create stone and update release PR",name:"Handle PR merge (stone + release PR)"},release:{description:"When the release PR is merged, publish packages",name:"Publish release"}},ks=_t(ws(vs(import.meta.url)),"templates"),Fr={"create-stone":"sis-create-stone.yml",release:"sis-release.yml"};class Xt{async generate(e){let t=[];for(let n of e){let r=await this.readTemplate(n),i=this.getOutputPath(n);t.push({content:r,path:i})}return t}getExistingFiles(e){return e.map((t)=>this.getOutputPath(t)).filter((t)=>Ir(t))}async readTemplate(e){let t=_t(ks,this.provider,Fr[e]);return Ps(t,"utf-8")}}class yt extends Xt{provider="github";outputDir=".github/workflows";getOutputPath(e){return _t(this.outputDir,Fr[e])}}var qe=".gitlab-ci-sisyphus.yml";class bt extends Xt{provider="gitlab";outputDir=".";async generate(e){let t=[];t.push(`stages:
|
|
93
|
+
- sisyphus
|
|
94
|
+
`);for(let n of e){let r=await this.readTemplate(n);t.push(r)}return[{content:t.join(`
|
|
95
|
+
`),path:qe}]}getExistingFiles(e){return Ir(qe)?[qe]:[]}getIncludeInstruction(){return`include:
|
|
96
|
+
- local: '${qe}'`}getOutputPath(e){return qe}}function Dr(e){switch(e){case"github":return new yt;case"gitlab":return new bt;default:throw Error(`CI generation is not supported for ${e}`)}}var Ms={bitbucket:"Bitbucket Pipelines",github:"GitHub Actions",gitlab:"GitLab CI"},Is=D({all:{alias:"a",default:!1,description:"Install all workflows",type:"boolean"},createStone:{default:!1,description:"Install create-stone workflow",type:"boolean"},dryRun:{alias:"d",default:!1,description:"Preview without writing files",type:"boolean"},release:{default:!1,description:"Install release workflow",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class en extends I{name="init";description="Set up CI workflows for automated releases";args=Is;prompts=!0;async execute(e){let t=await Mr(),n=Dr(t);l.info(`Detected ${c.bold(Ms[t])} repository
|
|
97
|
+
`);let r=await this.selectWorkflows(e);if(r.length===0){l.info(c.dim("No workflows selected"));return}let i=n.getExistingFiles(r);if(i.length>0&&!e.args.yes){if(!e.interactive)throw new d(`Workflows already exist: ${i.join(", ")}`,"Use --yes to overwrite existing workflows");if(l.warn(`The following files already exist:
|
|
98
|
+
${i.map((a)=>` ${a}`).join(`
|
|
99
|
+
`)}`),!await F({initialValue:!1,message:"Overwrite existing files?"}))return}let s=await n.generate(r);if(e.args.dryRun){for(let o of s)l.info(`
|
|
100
|
+
${c.bold(o.path)}:`),l.info(c.dim(o.content));return}for(let o of s){let a=Ss(o.path);if(a!=="."&&!Cs(a))await $s(a,{recursive:!0});await Rs(o.path,o.content,"utf-8")}if(N(s.map((o)=>` ${c.green("+")} ${o.path}`).join(`
|
|
101
|
+
`),c.green("CI workflows created")),n instanceof bt)l.info(`
|
|
102
|
+
Add this to your ${c.bold(".gitlab-ci.yml")}:
|
|
103
|
+
`),l.info(c.cyan(n.getIncludeInstruction())),l.info(""),l.info(`${c.yellow("Note:")} Add a ${c.bold("GITLAB_TOKEN")} CI/CD variable (Personal Access Token with ${c.bold("api")} + ${c.bold("write_repository")} scopes)`),l.info(c.dim("Required for creating release PRs. Settings \u2192 CI/CD \u2192 Variables")),l.info("");if(n instanceof yt)l.info(`
|
|
104
|
+
${c.yellow("Note:")} Enable ${c.bold('"Allow GitHub Actions to create and approve pull requests"')}`),l.info(c.dim("Settings \u2192 Actions \u2192 General \u2192 Workflow permissions")),l.info("");l.info(c.dim("Commit and push these files to enable the workflows."))}async selectWorkflows(e){let t=this.getWorkflowsFromFlags(e);if(t.length>0)return t;if(!e.interactive)throw new d("No workflows specified","Use --all or specify workflows with --createStone, --release");return ce({initialValues:Object.keys(dt),message:"Select workflows to create",options:Object.entries(dt).map(([n,r])=>({hint:r.description,label:r.name,value:n})),required:!1})}getWorkflowsFromFlags(e){if(e.args.all)return Object.keys(dt);let t=[];if(e.args.createStone)t.push("create-stone");if(e.args.release)t.push("release");return t}}var pe;((s)=>{s.Major="major";s.Minor="minor";s.Patch="patch";s.Dependency="dependency";s.Snapshot="snapshot"})(pe||={});var jr={["major"]:5,["minor"]:4,["patch"]:3,["dependency"]:2,["snapshot"]:1},je={["major"]:"\uD83D\uDEA8",["minor"]:"\u2728",["patch"]:"\uD83D\uDC1B",["dependency"]:"\uD83D\uDCE6",["snapshot"]:"\uD83D\uDCF8"},Ee={["major"]:c.red,["minor"]:c.yellow,["patch"]:c.green,["dependency"]:c.blue,["snapshot"]:c.magenta},Pe=["major","minor","patch","dependency","snapshot"];function Fs(e,t){return jr[e]-jr[t]}function Er(e,t){return Fs(e,t)>=0?e:t}function Lr(e){return Object.values(pe).includes(e)}var Ds=/^(\w+)(?:\(([^)]+)\))?(!)?: (.+)$/,tn="\x1F",js=new Set(["build","chore","ci","docs","feat","fix","perf","refactor","style","test"]);class q{hash;subject;author;body;type;scope;breaking;message;files;constructor(e){this.hash=e.hash,this.subject=e.subject,this.author=e.author,this.body=e.body,this.type=e.type,this.scope=e.scope,this.breaking=e.breaking,this.message=e.message,this.files=e.files}static async since(e){if(e){let t=await q.tryFetchFromRange(`${e}..HEAD`);if(t)return t}return q.fetchFromRange("HEAD")}static async inRange(e,t){let n=[`origin/${e}..origin/${t}`,`${e}..${t}`];for(let r of n){let i=await q.tryFetchFromRange(r);if(i)return i}return[]}static async fromHash(e){try{let n=(await Bun.$`git log -1 --pretty=format:"%H%x1f%s%x1f%an" ${e}`.quiet()).stdout.toString().trim();if(!n)return null;let r=n.split(tn);if(r.length<3)return null;let[i,s,o]=r;if(!i||!s||!o)return null;return q.hydrate(i,s,o)}catch{return null}}static async fromMerge(e){try{let n=(await Bun.$`git rev-parse ${e}^2`.quiet()).stdout.toString().trim();if(!n)return[];return q.fetchFromRange(`${e}^1..${n}`)}catch{return[]}}static async tryFetchFromRange(e){try{return await q.fetchFromRange(e)}catch{return null}}static async fetchFromRange(e){let r=(await Bun.$`git log ${e} --pretty=format:${"%x00%H%x1f%s%x1f%an%x1f%b%x00"} --name-only --no-merges`.quiet()).stdout.toString().trim();if(!r)return[];let i=r.split("\x00").filter(Boolean),s=[];for(let o=0;o<i.length;o+=2){let a=i[o];if(!a)continue;let g=a.split(tn);if(g.length<3)continue;let[m,u,f]=g;if(!m||!u||!f)continue;let y=g.slice(3).join(tn).trim()||void 0,b=(i[o+1]??"").split(`
|
|
105
|
+
`).filter(Boolean);s.push(q.parse(m,u,f).withFiles(b).withBody(y))}return s}static async hydrate(e,t,n){let r=await q.getFiles(e),i=await q.getBody(e);return q.parse(e,t,n).withFiles(r).withBody(i)}static async getFiles(e){return(await Bun.$`git diff-tree --no-commit-id --name-only -r ${e}`.quiet()).stdout.toString().trim().split(`
|
|
106
|
+
`).filter(Boolean)}static async getBody(e){return(await Bun.$`git log -1 --pretty=format:"%b" ${e}`.quiet()).stdout.toString().trim()||void 0}static parse(e,t,n){let r=t.match(Ds);if(r){let[,i="",s,o,a=""]=r;if(i&&js.has(i))return new q({author:n,breaking:!!o,files:[],hash:e,message:a,scope:s,subject:t,type:i})}return new q({author:n,breaking:!1,files:[],hash:e,message:t,subject:t,type:de})}get shortHash(){return this.hash.slice(0,ut)}get isConventional(){return this.type!==de}withFiles(e){return new q({...this.toOptions(),files:e})}withBody(e){return new q({...this.toOptions(),body:e})}toInfo(e){return{body:this.body,hash:this.shortHash,message:this.message,packages:e,scope:this.scope,subject:this.subject,type:this.type}}toOptions(){return{author:this.author,body:this.body,breaking:this.breaking,files:this.files,hash:this.hash,message:this.message,scope:this.scope,subject:this.subject,type:this.type}}}var J=(e)=>e.length>0?e:void 0;var Pt=1,Es=1,wt=10,Ls=/[.ZT:-]/g,Os=14,As="nightly";class X{static bump(e,t,n){let[r="0.0.0",i=""]=e.split("-"),[s="",o="0"]=i.split(".");if(t==="snapshot")return X.formatSnapshot(n);if(n&&t!=="dependency")return X.formatTagged(r,n,s,o);if(t==="dependency"&&s)return X.formatTagged(r,s,s,o);return X.bumpBase(r,t)}static formatLabel(e,t,n,r){let i=X.bump(t,n,r),s=je[n];return`${e}@${t} => ${i} ${s}`}static formatSnapshot(e){let t=new Date().toISOString().replace(Ls,"").slice(0,Os);return`0.0.0-${e||As}-${t}`}static formatTagged(e,t,n,r){let i=t===n?Number.parseInt(r,wt)+Pt:Es;return`${e}-${t}.${i}`}static bumpBase(e,t){let[n="0",r="0",i="0"]=e.split("."),s=Number.parseInt(n,wt),o=Number.parseInt(r,wt),a=Number.parseInt(i,wt);switch(t){case"major":return`${s+Pt}.0.0`;case"minor":return`${s}.${o+Pt}.0`;case"dependency":case"patch":return`${s}.${o}.${a+Pt}`;default:return`${s}.${o}.${a}`}}}class ee{name;version;file;dependencyOf;bump;tag;isPrivate;_newVersion;constructor(e){this.name=e.name,this.version=e.version,this.file=e.file,this.dependencyOf=e.dependencyOf??[],this.bump=e.bump,this.tag=e.tag,this.isPrivate=e.isPrivate??!1,this._newVersion=e.newVersion}static fromJson(e,t){return new ee({file:t,isPrivate:e.private??!1,name:e.name,version:e.version||vr})}static applyStone(e,t){let n=[];for(let r of Pe)for(let i of e.getPackages(r)){let s=t.get(i);if(s)n.push(s.withBump(r,e.tag))}return n}get newVersion(){if(this._newVersion)return this._newVersion;if(!this.bump)return;return X.bump(this.version,this.bump,this.tag)}get label(){if(!this.bump)return`${this.name}@${this.version}`;return X.formatLabel(this.name,this.version,this.bump,this.tag)}withDependencyOf(e){return new ee({...this.toOptions(),dependencyOf:e})}withBump(e,t){return new ee({...this.toOptions(),bump:e,newVersion:void 0,tag:t})}withVersions(e,t){return new ee({...this.toOptions(),newVersion:t,version:e})}toOptions(){return{bump:this.bump,dependencyOf:this.dependencyOf,file:this.file,isPrivate:this.isPrivate,name:this.name,newVersion:this._newVersion,tag:this.tag,version:this.version}}}import{randomUUID as Ns}from"crypto";class R{id;message;tag;description;commits;_packages;constructor(e){this.id=e.id,this.message=e.message,this.tag=e.tag,this.description=e.description,this.commits=e.commits,this._packages=e.packages}static create(e,t=0){let n=R.generateId(t);return R.fromData(n,e)}static fromJson(e){return R.fromData(e.id,e)}static mergeAll(e){let[t,...n]=e;if(!t)throw Error("No stones to merge");if(n.length===0)return t;let r=e.map((i)=>i.message).join("; ");return R.merge(e,r).stone}static merge(e,t){let n=new Map,r=[];for(let u of e)R.collectBumps(u,"major",n,r),R.collectBumps(u,"minor",n,r),R.collectBumps(u,"patch",n,r),R.collectBumps(u,"dependency",n,r);let i=R.categorizeBumps(n),s=e.map((u)=>u.description).filter(Boolean).join(`
|
|
107
|
+
|
|
108
|
+
`),o=e.flatMap((u)=>u.commits??[]),a=[...new Set(e.map((u)=>u.tag).filter(Boolean))],g=`merged-${Date.now()}`,m=new R({commits:o.length>0?o:void 0,description:s||void 0,id:g,message:t,packages:i,tag:a[0]});return{conflicts:[...new Set(r)],stone:m}}static collectBumps(e,t,n,r){for(let i of e.getPackages(t)){let s=n.get(i);if(!s){n.set(i,t);continue}if(s===t)continue;r.push(i);let o=Er(t,s);if(o!==s)n.set(i,o)}}static categorizeBumps(e){let t=new Map;for(let n of Pe)t.set(n,[]);for(let[n,r]of e)t.get(r)?.push(n);return t}static fromData(e,t){let n=new Map;return n.set("major",t.major??[]),n.set("minor",t.minor??[]),n.set("patch",t.patch??[]),n.set("dependency",t.dependency??[]),n.set("snapshot",t.snapshot??[]),new R({commits:t.commits,description:t.description,id:e,message:t.message,packages:n,tag:t.tag})}static generateId(e){let t=String(e+1).padStart(Cr,"0"),n=Ns().slice(0,$r);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 R({...this.toOptions(),message:e})}withTag(e){return new R({...this.toOptions(),tag:e})}withDescription(e){return new R({...this.toOptions(),description:e})}withCommits(e){return new R({...this.toOptions(),commits:e})}withPackages(e,t){let n=new Map(this._packages);return n.set(e,t),new R({...this.toOptions(),packages:n})}toOptions(){return{commits:this.commits,description:this.description,id:this.id,message:this.message,packages:new Map(this._packages),tag:this.tag}}toJson(){return{commits:this.commits&&this.commits.length>0?this.commits:void 0,dependency:J(this.dependency),description:this.description,id:this.id,major:J(this.major),message:this.message,minor:J(this.minor),patch:J(this.patch),snapshot:J(this.snapshot),tag:this.tag}}}import{readFile as Gs,rm as xs,writeFile as Or}from"fs/promises";import{dirname as qs,join as Hs}from"path";var Bs={bitbucket:"commits",github:"commit",gitlab:"-/commit"},Us={bitbucket:"bitbucket.org",github:"github.com",gitlab:"gitlab.com"};class He{cached=void 0;async getRemoteInfo(){if(this.cached!==void 0)return this.cached;let e=await Zt();if(!e)return this.cached=null,null;let t=Tt(e);if(!t)return this.cached=null,null;let n=Us[t.provider],r=Bs[t.provider],i=`https://${n}/${t.owner}/${t.repo}`;return this.cached={...t,commitUrl:(s)=>`${i}/${r}/${s}`},this.cached}}class we{config;originals=new Map;remoteParser=new He;commitUrlFn=null;constructor(e){this.config=e}async generate(e,t){await this.initCommitLinks();let n=new Map(t.map((r)=>[r.name,r]));for(let r of t){let i=this.filterStonesForPackage(e,r.name),s=this.getBumpedDependencies(e,r.name,n);await this.generateForPackage(i,r,s)}if(this.config.root)await this.generateRoot(e,t)}async initCommitLinks(){let e=await this.remoteParser.getRemoteInfo();this.commitUrlFn=e?.commitUrl??null}getBumpedDependencies(e,t,n){let r=new Set;for(let i of e){if(!i.dependency.includes(t))continue;for(let s of[...i.major,...i.minor,...i.patch])r.add(s)}return[...r].map((i)=>n.get(i)).filter((i)=>i!==void 0)}filterStonesForPackage(e,t){return e.filter((n)=>this.hasDirectChanges(n,t))}hasDirectChanges(e,t){return e.major.includes(t)||e.minor.includes(t)||e.patch.includes(t)}async rollback(){for(let[e,t]of this.originals)if(t===null)await xs(e,{force:!0});else await Or(e,t,"utf-8");this.originals.clear()}async generateForPackage(e,t,n){let r=Hs(qs(t.file),this.config.filename),i=this.formatEntry(e,t,n);await this.prependToChangelog(r,i,t.name)}async generateRoot(e,t){let n=this.config.filename,r=this.formatRootEntry(e,t);await this.prependToChangelog(n,r,"Changelog")}async prependToChangelog(e,t,n){let r=await this.readExisting(e);this.originals.set(e,r);let i=r?this.extractTitle(r):`# ${n}`,s=r?this.extractRest(r):"",o=`${i}
|
|
109
|
+
|
|
110
|
+
${t}${s?`
|
|
111
|
+
|
|
112
|
+
${s}`:""}
|
|
113
|
+
`;await Or(e,o,"utf-8")}async readExisting(e){try{return await Gs(e,"utf-8")}catch{return null}}extractTitle(e){let t=e.split(`
|
|
114
|
+
`)[0]??"";return t.startsWith("#")?t:"# Changelog"}extractRest(e){let t=e.split(`
|
|
115
|
+
`);if(!(t[0]??"").startsWith("#"))return e;let r=1;while(r<t.length&&t[r]?.trim()==="")r++;return t.slice(r).join(`
|
|
116
|
+
`).trim()}formatEntry(e,t,n){let r=this.formatPackageHeader(t),i=n.length>0,s=[`## ${r}`];for(let o of e)s.push("",`### ${Kt} ${o.message}`),s.push("",this.formatStoneContent(o,t.name));if(i){s.push("",`### ${this.config.sections.dependencies}`);for(let o of n)s.push(`- \`${o.name}\` ${o.version} \u2192 ${o.newVersion}`)}return s.join(`
|
|
117
|
+
`)}formatRootEntry(e,t){let r=[`## ${this.formatRootHeader(t)}`];r.push("","**Packages**");for(let i of t){let s=this.getEmoji(i),o=i.newVersion?`${i.version} \u2192 ${i.newVersion}`:i.version;r.push(`- ${s} \`${i.name}\` ${o}`)}for(let i of e)r.push("",`### ${Kt} ${i.message}`),r.push(this.formatStonePackages(i)),r.push("",this.formatRootStoneContent(i));return r.join(`
|
|
118
|
+
`)}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(`
|
|
119
|
+
|
|
120
|
+
`)}formatRootCommits(e,t){let n=this.formatCommits(e,t);return`<details>
|
|
121
|
+
<summary>Commits (${e.length})</summary>
|
|
122
|
+
|
|
123
|
+
${n}
|
|
124
|
+
|
|
125
|
+
</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 i=!this.isSectionName(e.message);n.push(this.formatCommits(r,i))}return n.join(`
|
|
126
|
+
|
|
127
|
+
`)}isSectionName(e){return Object.values(this.config.sections).includes(e)}formatDescription(e){return`<details>
|
|
128
|
+
<summary>Description</summary>
|
|
129
|
+
|
|
130
|
+
${this.convertHeadersToBold(e).split(`
|
|
131
|
+
`).map((r)=>` ${r}`).join(`
|
|
135
132
|
`)}
|
|
133
|
+
</details>`}convertHeadersToBold(e){return e.replace(/^#{1,6}\s+(.+)$/gm,"**$1**")}getDate(){return new Date().toISOString().split("T")[0]??""}getEmoji(e){return e.bump?je[e.bump]:"\uD83D\uDCE6"}filterCommitsForPackage(e,t){return e.filter((n)=>n.packages.includes(t))}formatCommits(e,t){if(!t)return e.map((i)=>this.formatCommitLine(i)).join(`
|
|
134
|
+
`);let n=this.groupCommitsByType(e),r=[];for(let[i,s]of n){let o=this.config.sections[i]??`${i} changes`;r.push(`#### ${o}`),r.push(s.map((a)=>this.formatCommitLine(a)).join(`
|
|
135
|
+
`))}return r.join(`
|
|
136
|
+
|
|
137
|
+
`)}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])=>(Me[n]??Ie)-(Me[r]??Ie))}formatCommitLine(e){let n=`- ${this.commitUrlFn?`[\`${e.hash}\`](${this.commitUrlFn(e.hash)})`:`\`${e.hash}\``} ${e.subject}`;if(e.body){let r=e.body.split(`
|
|
138
|
+
`).map((i)=>` ${i}`).join(`
|
|
139
|
+
`);return`${n}
|
|
140
|
+
<details>
|
|
141
|
+
<summary>Details</summary>
|
|
142
|
+
|
|
143
|
+
${r}
|
|
144
|
+
</details>`}return n}}import{readdir as Ar,readFile as Nr}from"fs/promises";import{join as nn}from"path";var Ws=".changeset",Js="config.json";class rn{root;constructor(e=process.cwd()){this.root=e}get changesetDir(){return nn(this.root,Ws)}async exists(){try{return await Ar(this.changesetDir),!0}catch{return!1}}async parse(){let e=[],t=[],n=await this.findChangesetFiles();for(let i of n){let s=await this.parseFile(i);if(s)t.push(s);else e.push(`Failed to parse: ${i}`)}let r=await this.parseConfig();return{changesets:t,config:r,errors:e}}async findChangesetFiles(){try{return(await Ar(this.changesetDir)).filter((t)=>t.endsWith(".md")&&t!=="README.md").map((t)=>nn(this.changesetDir,t))}catch{return[]}}async parseFile(e){try{let n=(await Nr(e,"utf-8")).split(`
|
|
145
|
+
`),r=!1,i=[],s=[];for(let g of n)if(g.trim()==="---")r=!r;else if(r)i.push(g);else if(i.length>0)s.push(g);let o={};for(let g of i){let m=g.match(/^"(.+)":\s*(major|minor|patch)$/);if(m?.[1]&&m[2])o[m[1]]=m[2]}if(Object.keys(o).length===0)return null;return{filename:e.split("/").pop()??"",packages:o,summary:s.join(`
|
|
146
|
+
`).trim()}}catch{return null}}async parseConfig(){try{let e=nn(this.changesetDir,Js),t=await Nr(e,"utf-8");return JSON.parse(t)}catch{return null}}toStoneData(e){let t=[],n=[],r=[];for(let[a,g]of Object.entries(e.packages))switch(g){case"major":t.push(a);break;case"minor":n.push(a);break;case"patch":r.push(a);break}let i=e.summary.split(`
|
|
147
|
+
`),s=i[0]?.trim()||"Migrated from changeset";return{description:i.slice(1).join(`
|
|
148
|
+
`).trim()||void 0,major:J(t),message:s,minor:J(n),patch:J(r)}}}function vt(e){let t=new Map;for(let[n,r]of e){let i=r.file.replace(/\\/g,"/"),s=i.substring(0,i.lastIndexOf("/"))||".";t.set(s,n)}return t}function Le(e,t){let n=new Set;for(let r of e){let i=t.get(r);if(i?.dependencyOf){for(let s of i.dependencyOf)if(!e.includes(s))n.add(s)}}return Array.from(n)}function We(e,t,n=!0){let r=new Set;for(let i of e)for(let[s,o]of t){let a=s===".",g=i.startsWith(`${s}/`);if(a?n:g)r.add(o)}return r}import{existsSync as ve}from"fs";import{mkdir as Br,readdir as sn,readFile as Ur,rename as Vs,unlink as zs,writeFile as Ys}from"fs/promises";import{join as ke}from"path";class ${config;constructor(e){this.config=e}get sisyphusDir(){return this.config.get("sisyphusDir")||lt}get stonesPath(){return this.config.get("stonesPath")||ke(this.sisyphusDir,br)}get releasedPath(){return ke(this.sisyphusDir,Pr)}async list(){let e=await this.listIds(),t=[];for(let n of e){let r=await this.get(n);if(r)t.push(r)}return t}async listIds(){return await this.ensureStorageExists(),(await sn(this.stonesPath)).filter((t)=>t.endsWith(".json")).map((t)=>t.replace(".json","")).sort()}async get(e){let t=this.getFilePath(e);if(!ve(t))return null;try{let n=await Ur(t,"utf-8"),r=JSON.parse(n);return R.fromJson(r)}catch{return null}}async exists(e){return ve(this.getFilePath(e))}async save(e){await this.ensureStorageExists();let t=this.getFilePath(e.id),n=JSON.stringify(e.toJson(),null,2);await Ys(t,n,"utf-8"),this.addToConfigStones(e.id)}async delete(e){let t=this.getFilePath(e);if(!ve(t))return!1;return await zs(t),this.removeFromConfigStones(e),!0}async deleteMany(e){let t=0;for(let n of e)if(await this.delete(n))t++;return t}async create(e){let t=await this.listIds(),n=R.create(e,t.length);return await this.save(n),n}async count(){return(await this.listIds()).length}async archive(e){if(e.length===0)return"";let t=this.createTimestamp(),n=ke(this.releasedPath,t);await Br(n,{recursive:!0});for(let r of e){let i=this.getFilePath(r.id),s=ke(n,`${r.id}.json`);if(ve(i))await Vs(i,s),this.removeFromConfigStones(r.id)}return t}async getReleasedStones(e){let t=ke(this.releasedPath,e);if(!ve(t))return[];let n=await sn(t),r=[];for(let i of n){if(!i.endsWith(".json"))continue;try{let s=await Ur(ke(t,i),"utf-8"),o=JSON.parse(s);r.push(R.fromJson(o))}catch(s){l.warn(c.dim(`Failed to parse stone "${i}": ${s}`))}}return r}async listReleasedTimestamps(){if(!ve(this.releasedPath))return[];return(await sn(this.releasedPath,{withFileTypes:!0})).filter((t)=>t.isDirectory()).map((t)=>t.name)}async getAllTrackedCommitHashes(){let t=(await this.list()).flatMap((n)=>n.commits??[]).map((n)=>n.hash);return new Set(t)}async listAllStones(){let e=await this.list(),t=await this.listReleasedTimestamps(),n=await Promise.all(t.map((r)=>this.getReleasedStones(r)));return[...e,...n.flat()]}getFilePath(e){return ke(this.stonesPath,`${e}.json`)}createTimestamp(){return new Date().toISOString().replace(/[:.]/g,"-")}async ensureStorageExists(){if(!ve(this.stonesPath))await Br(this.stonesPath,{recursive:!0})}addToConfigStones(e){let t=this.config.getAll();if(!t.stones.includes(e))this.config.set("stones",[...t.stones,e])}removeFromConfigStones(e){let t=this.config.getAll(),n=t.stones.filter((r)=>r!==e);if(n.length!==t.stones.length)this.config.set("stones",n)}}class S{static async scan(e={}){let{filter:t,single:n}=e;if(n)return S.scanRootPackage();let r=await S.getWorkspaces();S.validateWorkspaces(r);let i=await S.scanWorkspaces(r);return{packageNames:S.filterNames(Array.from(i.keys()),t),packages:i}}static async getWorkspaces(){try{let t=(await Bun.file("package.json").json())?.workspaces;if(Array.isArray(t))return t;return t?.packages||[]}catch{throw new d("Could not read package.json","Ensure you're in a project root directory.")}}static validateWorkspaces(e){if(e.length===0)throw new d("No workspaces found in package.json.","Use --single flag or set `single: true` in config for single-package mode.")}static filterNames(e,t){if(!t)return e;return e.filter((n)=>n.includes(t))}static async scanRootPackage(){let e=await Bun.file("package.json").json(),t=ee.fromJson(e,"package.json"),n=new Map;return n.set(t.name,t),{packageNames:[t.name],packages:n}}static async scanWorkspaces(e){let t=new Map,n=new Map;for(let r of e){let i=new Bun.Glob(`${r}/package.json`).scanSync({cwd:process.cwd()});for(let s of i){let o=await S.processPackageFile(s,n);if(o)t.set(o.name,o)}}return S.linkDependencies(t,n),t}static async processPackageFile(e,t){let n=await Bun.file(e).json(),r=ee.fromJson(n,e);return S.trackDependencies(r.name,n,t),r}static trackDependencies(e,t,n){let r={...t.dependencies,...t.devDependencies};for(let[i,s]of Object.entries(r)){if(!s?.startsWith("workspace"))continue;let o=n.get(i)||[];if(!o.includes(e))n.set(i,[...o,e])}}static linkDependencies(e,t){for(let[n,r]of t){let i=e.get(n);if(i)e.set(n,i.withDependencyOf(r))}}}var Ks={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch",[de]:"patch"};class Ce{config;stoneManager;constructor(e){this.config=e;this.stoneManager=new $(e)}async analyze(e={}){let t=await this.getCommitsSinceLastRelease();if(t.length===0)return[];let n=await this.stoneManager.getAllTrackedCommitHashes();if(n.size>0){if(t=t.filter((i)=>!n.has(i.shortHash)),t.length===0)return[]}let r=this.config.get("commits")?.skip??Fe.commits.skip;if(t=t.filter((i)=>!this.shouldSkipCommit(i,r)),t.length===0)return[];return this.groupByPackage(t,e)}shouldSkipCommit(e,t){if(t.authors.includes(e.author))return!0;for(let n of t.messagePatterns)try{if(new RegExp(n,"i").test(e.subject))return!0}catch{l.warn(c.yellow(`Invalid regex pattern in commits.skip.messagePatterns: "${n}"`))}return!1}get commitCount(){return this.getCommitsSinceLastRelease().then((e)=>e.length)}async getCommitsSinceLastRelease(){let t=this.config.get("lastStone")?.commit||void 0;if(!t)return[];return q.since(t)}async groupByPackage(e,t){let{packages:n}=await S.scan({filter:t.filter,single:t.single}),r=vt(n),i=new Map;for(let s of e){let o=We(s.files,r);if(o.size===0)continue;let a=s.breaking?"major":Ks[s.type]||"patch",g=`${s.type}${s.breaking?"!":""}`,m=i.get(g);if(!m){let u=this.getGroupMessage(s);m={bump:a,commits:[],message:u,packages:new Set},i.set(g,m)}m.commits.push(s.toInfo([...o]));for(let u of o)m.packages.add(u)}return Array.from(i.entries()).filter(([,s])=>s.packages.size>0).sort(([s],[o])=>(Me[s]??Ie)-(Me[o]??Ie)).map(([,s])=>s)}getGroupMessage(e){let t=this.config.get("changelog").sections;if(e.breaking)return t.breaking;return t[e.type]??`${e.type} updates`}static buildStoneData(e,t,n){let r=Array.from(e.packages),i=e.commits.length>0?e.commits:void 0,s=Le(r,t);return{[e.bump]:r,commits:i,dependency:s.length>0?s:void 0,message:e.message,tag:n}}}import{readFile as Zs,writeFile as Gr}from"fs/promises";class Je{originals=new Map;async updateAll(e){this.originals.clear();for(let t of e)await this.updatePackage(t)}async rollback(){for(let[e,t]of this.originals)await Gr(e,t,"utf-8");this.originals.clear()}async updatePackage(e){let t=e.newVersion;if(!t)return;let n=await Zs(e.file,"utf-8");this.originals.set(e.file,n);let r=JSON.parse(n);r.version=t;let i=this.detectIndent(n),s=`${JSON.stringify(r,null,i)}
|
|
149
|
+
`;await Gr(e.file,s,"utf-8")}detectIndent(e){let t=e.match(/^[\t ]+/m);return t?t[0]:2}}class on{config;provider=null;constructor(e){this.config=e}async analyze(e){let t=await this.getProvider(),n=e?await this.fetchFromUrl(t,e):await this.fetchFromCurrentBranch(t),r=this.config.get("single"),{packages:i}=await S.scan({single:r}),s=vt(i),o={isSinglePackage:r,packagePaths:s,provider:t,url:e},{commits:a,affectedPackages:g}=n.merged?await this.analyzeAfterMerge(n,o):await this.analyzeBeforeMerge(n,o),m=this.inferBumpFromLabels(n.labels)??this.inferBumpFromTitle(n.title);return{commits:a,packages:g,pr:n,suggestedBump:m}}async analyzeBeforeMerge(e,t){let n=await q.inRange(e.baseBranch,e.branch);return this.processCommits(n,t)}async analyzeAfterMerge(e,t){if(await this.detectMergeMethod(e.mergeCommitSha)==="squash")return this.analyzeSquashMerge(e,t);return this.analyzeMergeCommit(e,t)}async analyzeSquashMerge(e,t){let n=t.url?await this.fetchFilesFromApi(t.provider,t.url):await this.getFilesFromCommit(e.mergeCommitSha),r=We(n,t.packagePaths,t.isSinglePackage),i={body:e.body||void 0,hash:e.mergeCommitSha?.slice(0,ut)??wr,message:e.title,packages:[...r],subject:e.title,type:this.inferCommitType(e.title)};return{affectedPackages:r,commits:[i]}}async analyzeMergeCommit(e,t){if(!e.mergeCommitSha)return{affectedPackages:new Set,commits:[]};let n=await q.fromMerge(e.mergeCommitSha);return this.processCommits(n,t)}processCommits(e,t){let n=[],r=new Set;for(let i of e){let s=We(i.files,t.packagePaths,t.isSinglePackage);if(s.size===0)continue;n.push(i.toInfo([...s]));for(let o of s)r.add(o)}return{affectedPackages:r,commits:n}}async detectMergeMethod(e){if(!e)return"squash";if(await this.getCommitParentCount(e)===2)return"merge";return"squash"}async getCommitParentCount(e){try{let t=await Bun.$`git rev-parse ${e}^@`.quiet().nothrow();if(t.exitCode!==0)return 1;return t.stdout.toString().trim().split(`
|
|
150
|
+
`).filter(Boolean).length}catch{return 1}}inferCommitType(e){return e.match(/^(\w+)(?:\(.*?\))?!?:/)?.[1]??de}async getProvider(){if(!this.provider)this.provider=await De();return this.provider}async fetchFilesFromApi(e,t){let n=Qt(t);if(!n)return[];return e.getPrFiles(n.number)}async fetchFromCurrentBranch(e){let t=await e.getPrFromCurrentBranch();return this.mapPullRequest(t)}async fetchFromUrl(e,t){let n=Qt(t);if(!n)throw new d("Invalid PR URL","Expected a PR/MR URL from GitHub, GitLab, or Bitbucket");if(n.provider!==e.name)throw new d(`PR URL is from ${n.provider}, but repository is on ${e.name}`,"Make sure the PR URL matches the repository provider");let r=await e.getPr(n.number);return this.mapPullRequest(r)}mapPullRequest({headBranch:e,...t}){return{...t,branch:e}}inferBumpFromLabels(e){let t=this.config.get("pr").labelMapping;for(let n of e){let r=n.toLowerCase();for(let[i,s]of Object.entries(t))if(r===i.toLowerCase())return s}return null}inferBumpFromTitle(e){let t=e.toLowerCase();if(t.includes("breaking")||e.includes("!:"))return"major";if(t.includes("feat")||t.includes("feature"))return"minor";if(t.includes("fix")||t.includes("bug"))return"patch";return null}async getFilesFromCommit(e){if(!e)return[];try{return(await Bun.$`git diff-tree --no-commit-id --name-only -r ${e}`.quiet()).stdout.toString().trim().split(`
|
|
151
|
+
`).filter(Boolean)}catch{return[]}}}import{dirname as xr,join as Ts}from"path";class kt{config;packageUpdater=new Je;changelogGenerator;remoteParser=new He;provider=null;commitUrlFn=null;options;createdTags=[];createdReleases=[];commitCreated=!1;pushedToRemote=!1;constructor(e,t){this.config=e;this.options=t,this.changelogGenerator=new we(this.config.get("changelog"))}async getProvider(){if(!this.provider)this.provider=await De();return this.provider}async initCommitLinks(){if(this.commitUrlFn!==null)return;let e=await this.remoteParser.getRemoteInfo();this.commitUrlFn=e?.commitUrl??null}async preflight(e){if(this.options.dryRun)return;if(await this.hasStagedChanges())throw new d("You have staged changes","Commit or stash them before running roll");let n=await this.getDirtyPackageFiles(e);if(n.length>0)throw new d("Package files have uncommitted changes",`Commit or stash changes in:
|
|
152
|
+
${n.join(`
|
|
153
|
+
`)}`)}async updatePackageVersions(e){if(this.options.dryRun)return;await this.packageUpdater.updateAll(e)}async generateChangelogs(e,t){if(this.options.dryRun)return;await this.changelogGenerator.generate(e,t)}async createCommit(e,t){if(this.options.dryRun)return;let n=t.map((g)=>g.file),r=this.getChangelogFiles(t),i=this.config.get("sisyphusDir"),s=[...n,...r,i],o=this.formatCommitMessage(e,t),a=this.getCommitAuthorArg();await this.run(()=>Bun.$`git add -A -- ${s}`.quiet(),"Failed to stage files"),await this.run(()=>Bun.$`git commit ${a} -m ${o}`.quiet(),"Failed to create commit"),this.commitCreated=!0}getCommitAuthorArg(){let{author:e,email:t}=this.config.get("commit");if(!e)return[];return["--author",t?`${e} <${t}>`:e]}getChangelogFiles(e){let t=this.config.get("changelog").filename,n=e.map((r)=>Ts(xr(r.file),t));if(this.config.get("changelog").root)n.push(t);return n}async createGitTags(e){if(this.options.dryRun)return;for(let t of e){let n=t.newVersion??t.version,r=`${t.name}@${n}`;await this.run(()=>Bun.$`git tag ${r}`.quiet(),`Failed to create tag ${r}`),this.createdTags.push(r)}}async publishToNpm(e){if(this.options.dryRun)return;for(let t of e){if(t.isPrivate){l.info(c.dim(`Skipping ${t.name} (private)`));continue}await this.publishPackage(t)}}async pushToRemote(){if(this.options.dryRun)return;if(await this.run(()=>Bun.$`git push`.quiet(),"Failed to push commits"),this.createdTags.length>0)await this.pushTags();this.pushedToRemote=!0}async pushTags(){if(this.options.dryRun)return;if(this.createdTags.length===0)return;await this.run(()=>Bun.$`git push --tags`.quiet(),"Failed to push tags")}async createGitRelease(e,t){if(this.options.dryRun)return;await this.initCommitLinks();let n=await this.getProvider();for(let r of t){let i=r.newVersion??r.version,s=`${r.name}@${i}`,o=`${r.name} v${i}`,a=this.filterStonesForPackage(e,r.name),g=this.formatReleaseNotes(a,r);await this.run(()=>n.createRelease({notes:g,tag:s,title:o}),`Failed to create release for ${s}`),this.createdReleases.push(s)}}filterStonesForPackage(e,t){return e.filter((n)=>n.affectsPackage(t))}formatReleaseNotes(e,t){let n=[],r=t.newVersion??t.version;if(n.push(`\`${t.name}\` ${t.version} \u2192 ${r}`),e.length===0)return n.join(`
|
|
154
|
+
`);n.push(""),n.push("<details>"),n.push(`<summary>Stones (${e.length})</summary>`),n.push("");for(let i of e){if(n.push(`### ${i.message}`),n.push(""),i.description)n.push(i.description),n.push("");let s=this.filterCommitsForPackage(i.commits,t.name);if(s.length>0){n.push("<details>"),n.push(`<summary>Commits (${s.length})</summary>`),n.push("");for(let o of s)n.push(this.formatCommitLine(o));n.push(""),n.push("</details>"),n.push("")}}return n.push("</details>"),n.join(`
|
|
155
|
+
`)}filterCommitsForPackage(e,t){if(!e)return[];return e.filter((n)=>n.packages.includes(t))}formatCommitLine(e){return`- ${this.commitUrlFn?`[\`${e.hash}\`](${this.commitUrlFn(e.hash)})`:`\`${e.hash}\``} ${e.subject}`}async rollback(){if(this.createdReleases.length>0){let e=await this.getProvider();for(let t of this.createdReleases)await e.deleteRelease(t)}if(this.createdReleases=[],this.pushedToRemote)for(let e of this.createdTags)try{await Bun.$`git push origin --delete ${e}`.quiet()}catch(t){l.warn(c.dim(`Failed to delete remote tag "${e}": ${t}`))}for(let e of this.createdTags)try{await Bun.$`git tag -d ${e}`.quiet()}catch(t){l.warn(c.dim(`Failed to delete local tag "${e}": ${t}`))}if(this.createdTags=[],this.commitCreated){try{await Bun.$`git reset HEAD~1`.quiet()}catch(e){l.warn(c.dim(`Failed to reset commit: ${e}`))}this.commitCreated=!1}await this.changelogGenerator.rollback(),await this.packageUpdater.rollback()}async publishPackage(e){let t=this.config.get("tag")||kr,n=xr(e.file);await this.run(()=>Bun.$`bun run build`.cwd(n).quiet(),`Failed to build ${e.name}`),await this.run(()=>Bun.$`npm publish --tag ${t} --access public`.cwd(n).quiet(),`Failed to publish ${e.name}`)}formatCommitMessage(e,t){let n=this.config.get("commit").message,r=t.map((s)=>`- ${s.name}@${s.newVersion??s.version}`).join(`
|
|
156
|
+
`);return`${n.replace("{message}",()=>e.message).replace("{packages}",()=>t.map((s)=>s.name).join(", "))}
|
|
157
|
+
|
|
158
|
+
${r}`}async hasStagedChanges(){try{return(await Bun.$`git diff --cached --name-only`.quiet()).stdout.toString().trim().length>0}catch{return!1}}async getDirtyPackageFiles(e){let t=[];for(let n of e)try{if((await Bun.$`git status --porcelain ${n.file}`.quiet()).stdout.toString().trim().length>0)t.push(n.file)}catch{}return t}async run(e,t){try{await e()}catch(n){let r=this.getStderr(n)??(n instanceof Error?n.message:void 0);throw Error(r?`${t}: ${r}`:t)}}getStderr(e){if(e&&typeof e==="object"&&"stderr"in e){let t=e.stderr;if(t instanceof Buffer)return t.toString().trim();if(typeof t==="string")return t.trim()}return}}var Ct="sisyphus/release",an="sisyphus-release",Qs="Sisyphus release PR",_s="6f42c1",qr="chore(release):",Xs=D({dryRun:{alias:"d",default:!1,description:"Preview without making changes",type:"boolean"}});class cn extends I{name="release-pr";description="Create or update a release PR from pending stones";args=Xs;provider=null;async getProvider(){if(!this.provider)this.provider=await De();return this.provider}async execute(e){let t=await this.checkoutReleaseBranch();try{let{stones:n,packages:r}=await this.collectReleaseData(e);if(n.length===0){l.info(c.dim("No pending stones found, skipping release PR"));return}let i=this.buildPrTitle(r),s=this.buildPrBody(r,n);if(l.info(`${c.bold("Release PR:")} ${i}`),l.info(`${c.dim("Packages:")} ${r.map((o)=>o.name).join(", ")}`),e.args.dryRun){l.info(c.yellow(`
|
|
159
|
+
[dry-run] Would create/update release PR`)),l.info(c.dim(`
|
|
160
|
+
PR Body preview:`)),l.info(s);return}await this.commitAndPushChanges(e,n,r),await this.createOrUpdatePr(i,s)}finally{await this.restoreMainBranch(t)}}async checkoutReleaseBranch(){let t=await(await this.getProvider()).getDefaultBranch();return await Bun.$`git fetch origin ${t}`,await this.stashChanges(),await Bun.$`git checkout -B ${Ct} origin/${t}`,t}async collectReleaseData(e){let t=new $(e.config),n=await this.generateStonesFromCommits(e,t,e.args.dryRun),r=await t.list(),i=e.args.dryRun?[...r,...n]:r;if(i.length===0)return{packages:[],stones:[]};let{packages:s}=await S.scan({single:e.config.get("single")}),o=R.mergeAll(i),a=ee.applyStone(o,s);if(a.length===0)throw new d("No packages to update","Stones don't reference any known packages");return{packages:a,stones:i}}async commitAndPushChanges(e,t,n){let r=K();r.start("Applying release changes...");let i=await this.applyReleaseChanges(e,t,n);for(let o of i)await Bun.$`git add ${o}`.nothrow();if((await Bun.$`git diff --cached --quiet`.nothrow()).exitCode!==0)await Bun.$`git commit -m ${`${qr} prepare release`}`;await Bun.$`git push origin ${Ct} --force`,r.stop("Release branch ready")}async createOrUpdatePr(e,t){let n=K(),r=await this.findExistingReleasePr();if(r)n.start("Updating PR..."),await this.updatePr(r.number,e,t),n.stop(`PR #${r.number} updated`),l.info(`
|
|
161
|
+
${c.green("Release PR updated:")} ${r.url}`);else{n.start("Creating PR...");let i=await this.createPr(e,t);n.stop(`PR #${i.number} created`),l.info(`
|
|
162
|
+
${c.green("Release PR created:")} ${i.url}`)}}buildPrTitle(e){let t=e.map((n)=>`${n.name}@${n.newVersion}`).join(", ");return`${qr} ${t}`}buildPrBody(e,t){return[this.buildChangesSection(t),this.buildPackagesSection(e),this.buildStonesSection(t),this.buildFooter()].join(`
|
|
163
|
+
`)}buildChangesSection(e){let t=["## Changes",""];for(let n of e){if(t.push(`### ${n.message}`,""),n.commits&&n.commits.length>0)for(let r of n.commits)t.push(`- ${r.message} (\`${r.hash}\`)`);else if(n.description)t.push(n.description);t.push("")}return t.join(`
|
|
164
|
+
`)}buildPackagesSection(e){let t=["## Packages",""];for(let n of e)t.push(`- \`${n.name}\` ${n.version} \u2192 ${n.newVersion}`);return t.push(""),t.join(`
|
|
165
|
+
`)}buildStonesSection(e){let t=["## Stones",""];for(let n of e)t.push(`- \`${n.id}\`: ${n.message}`);return t.push(""),t.join(`
|
|
166
|
+
`)}buildFooter(){return["---","*This PR was automatically created by [Sisyphus](https://github.com/r5n-labs/clis).*","*Merging this PR will trigger the release workflow.*"].join(`
|
|
167
|
+
`)}async findExistingReleasePr(){let t=await(await this.getProvider()).findPr({head:Ct,label:an});return t?{number:t.number,url:t.url}:null}async generateStonesFromCommits(e,t,n){let i=await new Ce(e.config).analyze({single:e.config.get("single")});if(i.length===0)return[];let{packages:s}=await S.scan({single:e.config.get("single")}),o=[];for(let[a,g]of i.entries()){let m=Ce.buildStoneData(g,s);if(n)l.info(`${c.dim("[dry-run] Would generate stone:")} ${g.message}`),o.push(R.create(m,a));else{let u=await t.create(m);o.push(u),l.info(`${c.dim("Generated stone:")} ${u.id}`)}}return o}async findNewestCommitHash(e){let t=e.flatMap((r)=>r.commits??[]).map((r)=>r.hash);if(t.length===0)return null;return(await Bun.$`git log -1 --format=%H ${t}`.quiet().nothrow()).stdout.toString().trim()||null}async stashChanges(){await Bun.$`git stash --include-untracked`.nothrow()}async applyReleaseChanges(e,t,n){let r=[];return r.push(...await this.updatePackages(n)),r.push(...await this.generateChangelogs(e,t,n)),r.push(...await this.archiveStonesAndUpdateConfig(e,t,n)),r}async updatePackages(e){return await new Je().updateAll(e),e.map((n)=>n.file)}async generateChangelogs(e,t,n){let r=e.config.get("changelog");if(!r.generate)return[];return await new we(r).generate(t,n),[r.filename,`**/${r.filename}`]}async archiveStonesAndUpdateConfig(e,t,n){let i=await new $(e.config).archive(t),s=this.buildPackageVersions(n);return e.config.set("currentRelease",{packages:s,stoneIds:t.map((o)=>o.id),timestamp:i}),await this.updateLastStone(e,t),[e.config.get("sisyphusDir")]}buildPackageVersions(e){let t={};for(let n of e)if(n.newVersion)t[n.name]={newVersion:n.newVersion,oldVersion:n.version};return t}async updateLastStone(e,t){let n=await this.findNewestCommitHash(t);if(n)e.config.set("lastStone",{commit:n,date:new Date().toISOString()})}async createPr(e,t){let n=await this.getProvider(),r=await n.getDefaultBranch();await n.ensureLabelExists(an,{color:_s,description:Qs});let i=await n.createPr({base:r,body:t,head:Ct,labels:[an],title:e});return{number:i.number,url:i.url}}async updatePr(e,t,n){await(await this.getProvider()).updatePr(e,{body:n,title:t})}async restoreMainBranch(e){try{await Bun.$`git checkout ${e}`.quiet()}catch(t){l.warn(c.dim(`Failed to restore branch: ${t}`))}}}class gn extends I{name="actions";description="CI/CD integration";init(){this.registerSubcommands([new en,new cn])}}var eo=D({config:{alias:"c",default:!1,description:"Include config in output",type:"boolean"},json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}});class mn extends I{name="check";description="Show workspace packages and pending stones";args=eo;async execute(e){let t=await this.gatherData(e);if(e.args.json)this.printJson(t);else this.printFormatted(t)}async gatherData(e){let t=e.config.get("single"),{packages:n,packageNames:r}=await S.scan({single:t}),s=(t?null:await S.scan({single:!0}))?.packages.values().next().value??n.values().next().value,a=await new $(e.config).list();return{config:e.args.config?e.config.getAll():void 0,packageNames:r,packages:n,root:s,stones:a}}printJson(e){let t={config:e.config,packages:e.packageNames.map((n)=>({name:n,version:e.packages.get(n)?.version??"0.0.0"})),root:{name:e.root?.name??"",version:e.root?.version??"0.0.0"},stones:e.stones.map((n)=>this.stoneToJson(n,e.packages))};console.log(JSON.stringify(t,null,2))}stoneToJson(e,t){let n=[];for(let r of Pe)for(let i of e.getPackages(r)){let o=t.get(i)?.version??"0.0.0";n.push({bump:r,name:i,newVersion:X.bump(o,r,e.tag),version:o})}return{id:e.id,message:e.message,packages:n,tag:e.tag}}printFormatted(e){if(this.printRootInfo(e.root),this.printPackages(e),e.stones.length>0)this.printStones(e.stones,e.packages);if(e.config)this.printConfig(e.config);N(c.green("Sisyphus check complete."))}printConfig(e){let t=c.dim(JSON.stringify(e,null,2));l.step(`${c.bold(c.green("Config:"))}
|
|
168
|
+
${t}`)}printRootInfo(e){if(!e)return;let t=e.version?c.dim(`@${e.version}`):"";l.step(`${c.bold(c.green("Root package:"))} ${c.cyan(e.name)}${t}`)}printPackages(e){let t=[`${c.bold(c.green("Packages:"))}`];for(let n of e.packageNames){let r=e.packages.get(n),i=r?.version?c.dim(`@${r.version}`):"";t.push(` ${c.dim("\u2022")} ${c.cyan(n)}${i}`)}l.step(t.join(`
|
|
169
|
+
`))}printStones(e,t){let n=e.map((r)=>this.formatStone(r,t)).join(`
|
|
136
170
|
|
|
137
|
-
${d}`),B(l.success("Sisyphus check complete."))}}N();L();_();G();import{parseArgs as ha}from"util";var ms=C({prefix:"sisyphus"}).child("graph");function da(){let{values:n}=ha({args:process.argv.slice(3),options:{depth:{short:"d",type:"string"},filter:{short:"f",type:"string"},json:{short:"j",type:"boolean"},"show-versions":{short:"v",type:"boolean"}}});return{depth:n.depth?Number.parseInt(n.depth,10):void 0,filter:n.filter,json:n.json,showVersions:n["show-versions"]}}async function gs(){try{let n=da(),{packages:o}=await U(),r=ya(o);if(n.json){let s=Array.from(r.values());console.log(JSON.stringify(s,null,2));return}let i=r;if(n.filter)i=wa(r,n.filter,n.depth);xa(i,n.showVersions)}catch(n){ms.error("Failed to generate dependency graph:",n),process.exit(1)}}function ya(n){let o=new Map;for(let[r,i]of Object.entries(n))o.set(r,{dependencies:[],dependents:i.dependencyOf||[],level:0,name:r,version:i.version});for(let r of o.values())for(let i of r.dependents){let s=o.get(i);if(s)s.dependencies.push(r.name)}return ba(o),o}function ba(n){let o=Array.from(n.values()).filter((s)=>s.dependencies.length===0),r=new Set,i=o.map((s)=>({level:0,node:s}));while(i.length>0){let s=i.shift();if(!s)continue;let{node:t,level:e}=s;if(r.has(t.name))continue;r.add(t.name),t.level=e;for(let a of t.dependents){let c=n.get(a);if(c&&!r.has(a))i.push({level:e+1,node:c})}}}function wa(n,o,r){let i=new Map,s=Array.from(n.values()).find((a)=>a.name.includes(o));if(!s)return ms.warn(`No packages found matching filter: ${o}`),i;let t=[{currentDepth:0,node:s}],e=new Set;while(t.length>0){let a=t.shift();if(!a)continue;let{node:c,currentDepth:u}=a;if(e.has(c.name))continue;if(r!==void 0&&u>r)continue;if(e.add(c.name),i.set(c.name,c),!r||u<r)for(let m of[...c.dependencies,...c.dependents]){let g=n.get(m);if(g&&!e.has(m))t.push({currentDepth:u+1,node:g})}}return i}function xa(n,o){let r=Array.from(n.values()),i=Math.max(...r.map((t)=>t.level));$.info(`Package Dependency Graph (${n.size} packages)`),console.log();for(let t=0;t<=i;t++){let e=r.filter((a)=>a.level===t);if(e.length===0)continue;console.log(l.dim(`Level ${t}:`));for(let a of e){let u=o?` ${l.dim(`(${a.version})`)}`:"";if(console.log(` ${l.value(a.name)}${u}`),a.dependents.length>0){let m=a.dependents.map((g)=>{return n.get(g)?l.success(g):l.dim(g)}).join(", ");console.log(` ${l.dim("\u2192")} ${m}`)}}console.log()}let s=$a(n);if(s.length>0){console.log(l.warning("\u26A0\uFE0F Circular dependencies detected:"));for(let t of s)console.log(` ${t.join(" \u2192 ")} \u2192 ${t[0]}`);console.log()}}function $a(n){let o=[],r=new Set,i=new Set;function s(t,e){if(i.has(t)){let c=e.indexOf(t);if(c!==-1){let u=e.slice(c),m=[...u].sort().join(",");if(!o.some((g)=>[...g].sort().join(",")===m))o.push(u)}return}if(r.has(t))return;r.add(t),i.add(t);let a=n.get(t);if(a)for(let c of a.dependencies)s(c,[...e,c]);i.delete(t)}for(let t of n.keys())if(!r.has(t))s(t,[t]);return o}L();var hs={changeset:{description:"Create a new changeset interactively",examples:[{command:"sisyphus changeset",description:"Create changeset interactively"},{command:"sisyphus changeset --all",description:"Pre-select all packages"},{command:"sisyphus changeset --dry-run",description:"Preview without creating file"}],name:"sisyphus changeset",notes:["Changesets are stored in .changesets directory","Each changeset describes version bumps for one or more packages","Use semantic versioning: patch for fixes, minor for features, major for breaking changes"],options:[{description:"Select all packages",flags:"-a, --all",type:"boolean"},{description:"Preview without creating file",flags:"-d, --dry-run",type:"boolean"}],usage:"sisyphus changeset [options]"},check:{description:"Check current state and pending changes",examples:[{command:"sisyphus check",description:"Show pending stones and current state"},{command:"sisyphus check --verbose",description:"Show detailed change information"},{command:"sisyphus check --json",description:"Output in JSON format"},{command:"sisyphus check --include-private",description:"Include private packages"}],name:"sisyphus check",options:[{description:"Show detailed information",flags:"-v, --verbose",type:"boolean"},{description:"Output in JSON format",flags:"-j, --json",type:"boolean"},{description:"Show debug information",flags:"-d, --debug",type:"boolean"},{description:"Include private packages in the output",flags:"--include-private",type:"boolean"}],usage:"sisyphus check [options]"},graph:{description:"Visualize monorepo package dependencies",examples:[{command:"sisyphus graph",description:"Show full dependency graph"},{command:"sisyphus graph --filter @org/core",description:"Focus on specific package and its connections"},{command:"sisyphus graph --depth 1",description:"Limit depth to direct dependencies only"},{command:"sisyphus graph --show-versions",description:"Show with version numbers"},{command:"sisyphus graph --json > dependencies.json",description:"Export as JSON for further processing"}],name:"sisyphus graph",options:[{description:"Output in JSON format",flags:"-j, --json",type:"boolean"},{description:"Filter to specific package",flags:"-f, --filter",type:"string"},{description:"Limit depth of dependency tree",flags:"-d, --depth",type:"number"},{description:"Display package versions",flags:"-v, --show-versions",type:"boolean"}],usage:"sisyphus graph [options]"},init:{description:"Initialize Sisyphus in your project",examples:[{command:"sisyphus init",description:"Initialize Sisyphus interactively"},{command:"sisyphus init --force",description:"Reinitialize configuration"}],name:"sisyphus init",options:[{description:"Overwrite existing configuration",flags:"-f, --force",type:"boolean"}],usage:"sisyphus init [options]"},insights:{description:"Monorepo health analysis and insights",examples:[{command:"sisyphus insights",description:"Show overall monorepo health"},{command:"sisyphus insights --package @myorg/core",description:"Analyze specific package"},{command:"sisyphus insights --json",description:"Export insights as JSON"},{command:"sisyphus insights --include-private",description:"Include private packages in analysis"}],name:"sisyphus insights",options:[{description:"Analyze specific package",flags:"-p, --package",type:"string"},{description:"Output in JSON format",flags:"-j, --json",type:"boolean"},{description:"Include private packages in analysis",flags:"--include-private",type:"boolean"}],sections:[{content:[" - Package change frequency and staleness"," - Dependency health and circular dependencies"," - Release velocity and patterns"," - High-impact packages (many dependents)"," - Version mismatch detection"],title:"METRICS"}],usage:"sisyphus insights [options]"},metrics:{description:"View release metrics and statistics",examples:[{command:"sisyphus metrics",description:"Show metrics for last 30 days"},{command:"sisyphus metrics --days 90",description:"Show metrics for last 90 days"},{command:"sisyphus metrics --detailed",description:"Show detailed metrics"},{command:"sisyphus metrics --package @org/core",description:"Filter to specific package"},{command:"sisyphus metrics --json > metrics.json",description:"Export as JSON"}],name:"sisyphus metrics",options:[{description:"Output in JSON format",flags:"-j, --json",type:"boolean"},{description:"Number of days to analyze",flags:"-d, --days",type:"number"},{description:"Filter to specific package",flags:"-p, --package",type:"string"},{description:"Show detailed package metrics",flags:"-v, --detailed",type:"boolean"}],usage:"sisyphus metrics [options]"},migrate:{description:"Migrate from changesets, lerna, or standard-version",examples:[{command:"sisyphus migrate",description:"Auto-detect and migrate from changesets"},{command:"sisyphus migrate --clean",description:"Migrate and clean up changesets"},{command:"sisyphus migrate --dry-run",description:"Preview migration without making changes"}],name:"sisyphus migrate",notes:["Automatically detects changesets in .changeset directory","Converts YAML frontmatter to stone format","Preserves commit messages and summaries","Creates sequentially numbered stones"],options:[{description:"Source format (auto-detect if not specified)",flags:"-s, --source",type:"string"},{description:"Remove source files after migration",flags:"-c, --clean",type:"boolean"},{description:"Preview migration without changes",flags:"-d, --dry-run",type:"boolean"}],usage:"sisyphus migrate [options]"},pr:{description:"Create a stone from a pull/merge request",examples:[{command:"sisyphus pr",description:"Create stone from current branch's PR (requires gh CLI)"},{command:"sisyphus pr --url https://github.com/owner/repo/pull/123",description:"Create stone from specific GitHub PR"},{command:"sisyphus pr --url https://gitlab.com/owner/repo/-/merge_requests/123",description:"Create stone from GitLab MR"},{command:"sisyphus pr --dryRun",description:"Preview without creating stone"}],name:"sisyphus pr",notes:["Automatically detects bump type from PR labels and title","Labels: breaking-change \u2192 major, feature \u2192 minor, bug/fix \u2192 patch","Determines affected packages from changed files","Requires GitHub CLI (gh) for GitHub integration"],options:[{description:"PR/MR URL to process",flags:"-u, --url",type:"string"},{description:"Force GitHub mode",flags:"--github",type:"boolean"},{description:"Force GitLab mode",flags:"--gitlab",type:"boolean"},{description:"Preview changes without creating stone",flags:"-d, --dryRun",type:"boolean"},{description:"Skip confirmation prompt",flags:"-y, --yes",type:"boolean"}],usage:"sisyphus pr [options]"},prerelease:{description:"Manage prerelease versions (alpha, beta, rc)",examples:[{command:"sisyphus prerelease --type beta",description:"Create a new beta prerelease"},{command:"sisyphus prerelease --promote",description:"Promote prereleases (interactive UI)"},{command:'sisyphus prerelease --type alpha --filter "@org/core"',description:"Create alpha for specific packages"},{command:"sisyphus prerelease --type beta --bump minor --yes",description:"Non-interactive prerelease creation"}],name:"sisyphus prerelease",notes:["Use --promote to advance versions (alpha \u2192 beta \u2192 rc \u2192 stable)","RC and Next are treated as equivalent, both graduate to stable","You can skip tiers (e.g., alpha \u2192 rc or alpha \u2192 stable)"],options:[{description:"Prerelease type (alpha/beta/rc/etc)",flags:"-t, --type",type:"string"},{description:"Bump type (major/minor/patch)",flags:"-b, --bump",type:"string"},{description:"Promote existing prereleases",flags:"-p, --promote",type:"boolean"},{description:"Filter packages",flags:"-f, --filter",type:"string"},{description:"Preview changes",flags:"-d, --dryRun",type:"boolean"},{description:"Skip confirmation",flags:"-y, --yes",type:"boolean"}],usage:"sisyphus prerelease [options]"},preview:{description:"Preview what versions will be after rolling stones",examples:[{command:"sisyphus preview",description:"Preview release changes"},{command:"sisyphus preview --verbose",description:"Show detailed preview"},{command:"sisyphus preview --json",description:"Get preview as JSON"},{command:"sisyphus preview --include-private",description:"Include private packages in preview"}],name:"sisyphus preview",options:[{description:"Output in JSON format",flags:"-j, --json",type:"boolean"},{description:"Show additional information",flags:"-v, --verbose",type:"boolean"},{description:"Include private packages in preview",flags:"--include-private",type:"boolean"}],usage:"sisyphus preview [options]"},roll:{description:"Roll the stones and release packages",examples:[{command:"sisyphus roll",description:"Release packages with accumulated changes"},{command:"sisyphus roll --dry-run",description:"Preview release without publishing"},{command:"sisyphus roll --tag next",description:"Release with 'next' tag"}],name:"sisyphus roll",options:[{description:"Preview changes without releasing",flags:"-d, --dry-run",type:"boolean"},{description:"NPM dist-tag to use",flags:"-t, --tag",type:"string"}],usage:"sisyphus roll [options]"},solo:{description:"Single maintainer workflow (version + roll)",examples:[{command:"sisyphus solo",description:"Analyze commits and release immediately"},{command:"sisyphus solo --dry-run",description:"Preview what would be released"},{command:"sisyphus solo --tag next",description:"Release with 'next' tag"}],name:"sisyphus solo",notes:["Combines 'version --from-commits' and 'roll' in one command","Perfect for single maintainer projects","Skips stone accumulation phase","Uses conventional commits for version determination"],options:[{description:"NPM dist-tag to use",flags:"-t, --tag",type:"string"},{description:"Preview without releasing",flags:"-d, --dry-run",type:"boolean"}],usage:"sisyphus solo [options]"},stone:{description:"Manage pending stones",examples:[{command:"sisyphus stone list",description:"List all pending stones"},{command:"sisyphus stone delete stone-123",description:"Delete a specific stone"},{command:"sisyphus stone show stone-123",description:"Show stone details"},{command:"sisyphus stone merge",description:"Merge stones interactively"}],name:"sisyphus stone",notes:["Use 'sisyphus stone <command> --help' for more information about a command."],sections:[{content:[" list View all pending stones with details"," delete <id> Remove a specific stone by ID"," show <id> Display full content of a stone"," edit <id> Modify stone content or versions"," merge Combine stones with conflict resolution"],title:"COMMANDS"}],usage:"sisyphus stone <command> [options]"},version:{description:"Create a new version stone for next release",examples:[{command:"sisyphus version",description:"Create version stone interactively"},{command:"sisyphus version --from-commits",description:"Generate stones from conventional commits"},{command:"sisyphus version --dryRun",description:"Preview version changes"},{command:"sisyphus version --bump minor --filter @org/core",description:"Create with specific bump"},{command:"sisyphus version --include-private",description:"Include private packages in versioning"}],name:"sisyphus version",options:[{description:"Bump type (major/minor/patch)",flags:"-b, --bump",type:"string"},{description:"Preview changes without creating stone",flags:"-d, --dryRun",type:"boolean"},{description:"Filter packages",flags:"-f, --filter",type:"string"},{description:"Generate from conventional commits",flags:"--from-commits",type:"boolean"},{description:"Include private packages in versioning",flags:"--include-private",type:"boolean"},{description:"Create snapshot versions",flags:"-s, --snapshot",type:"boolean"},{description:"Release tag",flags:"-t, --tag",type:"string"},{description:"Skip confirmation prompt",flags:"-y, --yes",type:"boolean"}],usage:"sisyphus version [options]"}};function Io(n){if(n&&hs[n]){console.log(wo(hs[n]));return}let o=[{description:"Initialize Sisyphus in your project",name:"init"},{description:"Check current state and pending changes",name:"check"},{description:"Create a new changeset interactively",name:"changeset"},{description:"Visualize monorepo package dependencies",name:"graph"},{description:"Analyze monorepo health and dependencies",name:"insights"},{description:"View release metrics and statistics",name:"metrics"},{description:"Migrate from changesets/lerna/standard-version",name:"migrate"},{description:"Create stones from pull requests",name:"pr"},{description:"Manage prerelease versions (alpha, beta, rc)",name:"prerelease"},{description:"Preview what versions will be after rolling",name:"preview"},{description:"Roll the stones and release packages",name:"roll"},{description:"Single-step release (version + roll)",name:"solo"},{description:"Manage pending stones (list, delete, edit, merge)",name:"stone"},{description:"Create a new version stone for next release",name:"version"},{description:"Show this help message",name:"help"}];console.log(xo(`Sisyphus@${vn} - The rock-solid versioning system`,"sisyphus <command> [options]",o,"Use sisyphus <command> --help for more information about a command."))}N();_();import{parseArgs as va}from"util";N();_();G();Mn();async function ds({single:n,tag:o,ignore:r}){let i=await ur({commitAndPush:()=>D({active:"Yes, commit and push the release",inactive:"Skip commit",initialValue:!1,message:"Should `roll` command commit and push the release?"}),commitConfig:()=>D({active:"Yes, configure commit",inactive:"Skip commit config",initialValue:!1,message:"Configure commit for release? Default commit message is `release(\uD83C\uDF89): <packageName@version>`"}),commitAuthor:({results:{commitConfig:s}})=>s?J({message:"Commit author",placeholder:"r5n-bot"}):void 0,commitEmail:({results:{commitConfig:s}})=>s?J({message:"Commit author email",placeholder:"r5n-bot@users.noreply.github.com"}):void 0,commitMessage:({results:{commitConfig:s}})=>s?J({message:"Commit message",placeholder:"release(\uD83C\uDF89): <packageName@version>"}):void 0,generateChangelog:()=>D({active:"Yes, Generate changelog",inactive:"Skip changelog",initialValue:!0,message:"Generate changelog for release?"}),releaseOnGitHub:()=>D({active:"Yes, create a GitHub release",inactive:"Skip GitHub release",initialValue:!1,message:"Create a release on GitHub when releasing packages?"}),releaseOnNPM:()=>D({active:"Yes, publish packages to NPM",inactive:"Skip NPM release",initialValue:!1,message:"Publish packages to NPM when releasing packages?"}),releaseTags:()=>D({active:"Yes, create tags for the release",inactive:"Skip tags",initialValue:!1,message:"Create tags for the release?"}),rootChangelog:({results:{generateChangelog:s}})=>s?D({active:"Yes, generate combined changelog",inactive:"Skip root changelog",initialValue:!0,message:"Generate combined changelog for monorepo?"}):void 0,single:()=>D({active:"Yes, setup for root package",inactive:"No, setup for monorepo workspace packages",initialValue:n,message:"Setup Sisyphus for only root package?"}),tag:()=>J({initialValue:o,message:"Tag used when versioning packages. Leave `latest` if you are not sure or want to release packages with latest tag.",placeholder:"latest"})},{onCancel:()=>Ln()});return{commitAndPush:!!i.commitAndPush,commitAuthor:i.commitAuthor||"",commitConfig:!!i.commitConfig,commitEmail:i.commitEmail||"",commitMessage:i.commitMessage||"",generateChangelog:i.generateChangelog,releaseOnGitHub:!!i.releaseOnGitHub,releaseOnNPM:!!i.releaseOnNPM,releaseTags:!!i.releaseTags,rootChangelog:!!i.rootChangelog,single:i.single,tag:i.tag}}async function ys({bump:n,packages:o,packageNames:r,tag:i}){let s=Sa({packageNames:r,packages:o,tag:i}),t=`
|
|
138
|
-
- ${y.dim(y.italic(`Press ${y.underline(y.bold(y.whiteBright("a")))} to select/unselect all, ${y.underline(y.bold(y.whiteBright("SPACE")))} to select/unselect, ${y.underline(y.bold(y.whiteBright("ARROWS")))} to move, ${y.underline(y.bold(y.whiteBright("ENTER")))} to confirm`))}
|
|
139
|
-
`,e=n?[n]:["major","minor","patch"];$.info(t);let{message:a,majorPackages:c,minorPackages:u,patchPackages:m}=await ur({majorPackages:()=>e.includes("major")?s({bump:"major"}):void 0,minorPackages:({results:{majorPackages:g}})=>e.includes("minor")?s({bump:"minor",filterPackages:g||[]}):void 0,patchPackages:({results:{majorPackages:g,minorPackages:d}})=>e.includes("patch")?s({bump:"patch",filterPackages:(g||[]).concat(d||[])}):void 0,message:()=>J({message:`Name of the stone. ${y.dim(y.italic("Default prefix or message can be configured in config."))}`,placeholder:"New feature"})},{onCancel:()=>Ln()});return{majorPackages:c||[],message:a,minorPackages:u||[],patchPackages:m||[]}}function Sa({packageNames:n,tag:o,packages:r}){return({bump:i,filterPackages:s=[]})=>{let t=n.filter((a)=>!s?.includes(a)).map((a)=>({label:Yn({bump:i,name:a,tag:o,version:r[a]?.version||"0.0.0"}),value:a})),e={major:y.red,minor:y.yellow,patch:y.green};return t.length>0?$n({initialValues:void 0,message:`Select packages for ${y.bold(e[i](i))} bump.`,options:t,required:!1}):void 0}}G();async function bs(){let{values:{nonInteractive:n,overwrite:o,tag:r,single:i,ignore:s}}=va({allowPositionals:!0,args:Bun.argv,options:{ignore:{default:[],multiple:!0,short:"i",type:"string"},nonInteractive:{default:!1,short:"n",type:"boolean"},overwrite:{default:!1,short:"o",type:"boolean"},single:{default:!1,short:"s",type:"boolean"},tag:{default:"latest",short:"t",type:"string"}},strict:!0});if(n)await O({ignore:s,overwrite:o,single:i,tag:r});else{let{commitAndPush:t,commitAuthor:e,commitConfig:a,commitEmail:c,commitMessage:u,generateChangelog:m,releaseOnGitHub:g,releaseOnNPM:d,releaseTags:w,rootChangelog:p,single:f,tag:h}=await ds({ignore:s,single:i,tag:r}),x={ignore:s,single:f,tag:h};if(a)x.commit={author:e,email:c,message:u};if(g||d||t)x.release={commitAndPush:t,github:g,npm:d,tags:w};if(m)x.changelog={generate:m,root:p};await O({overwrite:o,...x})}B(`${y.magenta(`${y.bold("Sisyphus ")}${y.underline(y.italic(`v${vn}`))}`)}${y.green(" is setup to roll stones.")}
|
|
171
|
+
`);l.step(`${c.bold(c.green("Stones:"))}
|
|
140
172
|
|
|
141
|
-
|
|
173
|
+
${n}`)}formatStone(e,t){let n=[];if(n.push(`${c.bold("Stone:")} ${c.cyan(e.id)}`),e.tag)n.push(`${c.dim("Tag:")} ${e.tag}`);n.push(`${c.dim("Message:")} ${e.message}`),n.push(`${c.bold("Packages:")}`);for(let r of Pe){let i=e.getPackages(r);if(i.length===0)continue;for(let s of i){let a=t.get(s)?.version??"0.0.0",g=X.bump(a,r,e.tag),m=Ee[r],u=je[r];n.push(` ${u} ${c.cyan(s)}@${m(g)} ${c.dim(`(${r})`)}`)}}return n.join(`
|
|
174
|
+
`)}}var to=D({changelog:{description:"Generate changelog for releases",type:"boolean"},commitAuthor:{description:"Commit author name",type:"string"},commitEmail:{description:"Commit author email",type:"string"},commitMessage:{description:"Commit message template",type:"string"},createRelease:{description:"Create a release on git provider",type:"boolean"},default:{alias:"d",default:!1,description:"Reset to default config",type:"boolean"},force:{alias:"f",default:!1,description:"Overwrite existing config",type:"boolean"},npm:{description:"Publish to NPM on release",type:"boolean"},push:{description:"Push commits and tags to remote on release",type:"boolean"},rootChangelog:{description:"Generate combined changelog for monorepo",type:"boolean"},single:{alias:"s",description:"Setup for single package (not monorepo)",type:"boolean"},tag:{alias:"t",description:"Default release tag",type:"string"},tags:{description:"Create git tags on release",type:"boolean"}});class pn extends I{name="init";description="Initializes Sisyphus config or edits it";args=to;async execute(e){let{default:t,force:n}=e.args;if(t){e.config.save(Fe),await this.setLastStoneToHead(e),this.displaySuccessNote(e.cli.version);return}if(!e.interactive&&e.config.exists()&&!n){N(c.yellow("Config already exists. Use --force to replace."));return}let r=e.config.getAll(),{default:i,force:s,...o}=e.args,a=e.interactive?await this.runInitForm(r):o,g=this.mapValuesToConfig(a),m=be({...r},g);e.config.save(m),await this.setLastStoneToHead(e),this.displaySuccessNote(e.cli.version)}mapValuesToConfig(e){let t=(o)=>Object.fromEntries(Object.entries(o).filter(([,a])=>a!==void 0)),n=(o)=>Object.keys(o).length>0,r=t({author:e.commitAuthor,email:e.commitEmail,message:e.commitMessage}),i=t({generate:e.changelog,root:e.rootChangelog}),s=t({createRelease:e.createRelease,npm:e.npm,push:e.push,tags:e.tags});return{...t({single:e.single,tag:e.tag}),...n(r)&&{commit:r},...n(i)&&{changelog:i},...n(s)&&{release:s}}}async runInitForm(e){let t=await nt({changelog:()=>F({active:"Yes, generate changelog",inactive:"Skip changelog",initialValue:e.changelog?.generate??!0,message:"Generate changelog for release?"}),commitAuthor:({results:{configureCommit:n}})=>n?Z({initialValue:e.commit?.author??"",message:"Commit author",placeholder:"r5n-bot"}):void 0,commitEmail:({results:{configureCommit:n}})=>n?Z({initialValue:e.commit?.email??"",message:"Commit author email",placeholder:"r5n-bot@users.noreply.github.com"}):void 0,commitMessage:({results:{configureCommit:n}})=>n?Z({initialValue:e.commit?.message??"",message:"Commit message",placeholder:"release: <packageName@version>"}):void 0,configureCommit:()=>F({active:"Yes, configure commit",inactive:"Skip commit config",initialValue:!!(e.commit?.author||e.commit?.email||e.commit?.message),message:"Configure commit for release? Default commit message is `release: <packageName@version>`"}),createRelease:()=>F({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:()=>F({active:"Yes, publish packages to NPM",inactive:"Skip NPM release",initialValue:e.release?.npm??!1,message:"Publish packages to NPM when releasing packages?"}),push:()=>F({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?F({active:"Yes, generate combined changelog",inactive:"Skip root changelog",initialValue:e.changelog?.root??!1,message:"Generate combined changelog for monorepo?"}):void 0,single:()=>F({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:()=>Z({initialValue:e.tag??"latest",message:"Tag used when versioning packages. Leave `latest` if you are not sure.",placeholder:"latest"}),tags:()=>F({active:"Yes, create tags for the release",inactive:"Skip tags",initialValue:e.release?.tags??!1,message:"Create tags for the release?"})},{onCancel:()=>{throw new te}});return{changelog:t.changelog,commitAuthor:t.commitAuthor,commitEmail:t.commitEmail,commitMessage:t.commitMessage,createRelease:t.createRelease,npm:t.npm,push:t.push,rootChangelog:t.rootChangelog,single:t.single,tag:t.tag,tags:t.tags}}async setLastStoneToHead(e){try{let n=(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim();if(n)e.config.set("lastStone",{commit:n,date:new Date().toISOString()})}catch{}}displaySuccessNote(e){N(`${c.magenta(`${c.bold("Sisyphus ")}${c.underline(c.italic(`v${e??"unknown"}`))}`)}${c.green(" is setup to roll stones.")}
|
|
175
|
+
|
|
176
|
+
You can now start by creating a new stone by running ${c.green(A)}${c.blue(" version")}
|
|
142
177
|
and following the prompts.
|
|
143
178
|
|
|
144
|
-
After you finished, you can release it by running ${
|
|
145
|
-
`)}
|
|
146
|
-
|
|
147
|
-
`+`\uD83D\uDCC8 Most Changed: ${l.value(i.mostChanged.name)} (${i.mostChanged.commits} commits)
|
|
148
|
-
`+`\uD83D\uDC0C Stale Packages: ${i.stalePackages.length>0?l.warning(String(i.stalePackages.length)):l.success("0")}
|
|
149
|
-
`+`\uD83C\uDFAF High Impact Changes: ${l.value(String(i.highImpactPackages))}
|
|
150
|
-
`+`\uD83D\uDE80 Release Velocity: ${l.value(i.releaseVelocity)}`,l.bold("\uD83D\uDCCA Monorepo Health Report")),i.dependencyIssues.length>0)B(i.dependencyIssues.map((s)=>`${l.dim("\u2022")} ${s}`).join(`
|
|
151
|
-
`),l.warning("\u26A0\uFE0F Dependency Issues"));if(i.stalePackages.length>0)B(i.stalePackages.map((s)=>`${l.dim("\u2022")} ${s.name} - ${s.daysSinceUpdate} days since last update`).join(`
|
|
152
|
-
`),l.warning("\uD83D\uDC0C Stale Packages"));q(l.success("Analysis complete"))}async function Ea(n,o){let r={};for(let[s,t]of Object.entries(o.packages))try{let e=await Bun.file(t.file).json();r[s]={...t,packageJson:e}}catch(e){Er.warn(`Failed to load package.json for ${s}:`,e),r[s]={...t,packageJson:{dependencies:{},devDependencies:{}}}}let i=await Ia(n,r);if(B(`Current: ${l.value(i.version)}
|
|
153
|
-
Path: ${l.dim(i.path)}
|
|
154
|
-
Dependencies: ${l.value(String(i.dependencies))}
|
|
155
|
-
Dependents: ${l.value(String(i.dependents))} internal${i.externalDependents?`, ${l.info(i.externalDependents)} external`:""}
|
|
156
|
-
Last Modified: ${l.dim(i.lastModified||"Unknown")}
|
|
157
|
-
Change Frequency: ${l.value(i.changeFrequency||"Low")}
|
|
158
|
-
Breaking Changes: ${l.value(String(i.breakingChanges))} in last year`,l.bold(`\uD83D\uDCE6 ${n.name}`)),i.dependencyTree.length>0)B($s(i.dependencyTree),l.info("\uD83C\uDF33 Dependency Tree"));if(i.internalDependents.length>0)B(i.internalDependents.map((s)=>`${l.dim("\u2022")} ${s}`).join(`
|
|
159
|
-
`),l.info("\uD83D\uDC65 Used By"));q(l.success("Analysis complete"))}async function Ca(n,o){let r=await Pa(n),i=await Oa(n),s=await _a(),t=Ta(n),e=Ba(n,o);return{circularDeps:t.length,dependencyIssues:e,highImpactPackages:n.filter((a)=>a.dependencyOf?.length>5).length,mostChanged:r,releaseVelocity:s,stalePackages:i,totalPackages:n.length}}async function Ia(n,o){let r=await Aa(n.file),i=await Ma(n.file),s=await La(n.name),t=Object.keys(n.packageJson?.dependencies||{}).length,e=Object.values(o).filter((c)=>c.dependencyOf?.includes(n.name)).map((c)=>c.name),a=xs(n,o,3);return{breakingChanges:s,changeFrequency:i,dependencies:t,dependencyTree:a,dependents:e.length,externalDependents:await Da(n.name),internalDependents:e,lastModified:r,name:n.name,path:n.file,version:n.version||n.packageJson?.version||"0.0.0"}}async function Pa(n){let o={commits:0,name:"None"};for(let r of n)try{let i=r.file.substring(0,r.file.lastIndexOf("/")),s=await Cn`cd ${i} && git rev-list --count HEAD -- .`.text(),t=Number.parseInt(s.trim(),10);if(t>o.commits)o={commits:t,name:r.name}}catch{}return o}async function Oa(n,o=180){let r=[];for(let i of n)try{let s=i.file.substring(0,i.file.lastIndexOf("/")),t=await Cn`cd ${s} && git log -1 --format=%ct -- .`.text(),e=Number.parseInt(t.trim(),10),a=Math.floor((Date.now()/1000-e)/86400);if(a>o)r.push({daysSinceUpdate:a,name:i.name})}catch{}return r}async function _a(){try{let o=(await Cn`git tag -l "v*" --sort=-creatordate | head -10`.text()).trim().split(`
|
|
160
|
-
`).filter(Boolean);if(o.length<2)return"N/A";let r=[];for(let t of o.slice(0,5)){let e=await Cn`git log -1 --format=%ct ${t}`.text();r.push(Number.parseInt(e.trim(),10))}let i=0;for(let t=1;t<r.length;t++){let e=r[t-1],a=r[t];if(e&&a)i+=(e-a)/86400}let s=Math.round(i/(r.length-1));if(s<7)return`${s} days (rapid)`;if(s<14)return`${s} days (fast)`;if(s<30)return`${s} days (regular)`;return`${s} days (slow)`}catch{return"N/A"}}function Ta(n){return[]}function Ba(n,o){let r=[],i=new Map;for(let s of n){let t={...s.packageJson?.dependencies||{},...s.packageJson?.devDependencies||{}};for(let[e,a]of Object.entries(t)){if(!i.has(e))i.set(e,new Set);i.get(e)?.add(a)}}for(let[s,t]of i)if(t.size>1)r.push(`${s} has ${t.size} different versions across packages`);return r}async function Aa(n){try{let o=n.substring(0,n.lastIndexOf("/")),r=await Cn`cd ${o} && git log -1 --format=%ct -- .`.text();return new Date(Number.parseInt(r.trim(),10)*1000).toLocaleDateString()}catch{return"Unknown"}}async function Ma(n){try{let o=n.substring(0,n.lastIndexOf("/")),r=await Cn`cd ${o} && git rev-list --count HEAD --since="6 months ago" -- .`.text(),i=Number.parseInt(r.trim(),10);if(i>50)return"High";if(i>20)return"Medium";if(i>5)return"Low";return"Very Low"}catch{return"Unknown"}}async function La(n){try{let o=await Cn`git log --grep="BREAKING" --grep="breaking change" -i --oneline -- "*${n}*" | wc -l`.text();return Number.parseInt(o.trim(),10)}catch{return 0}}async function Da(n){return""}function xs(n,o,r,i=0){if(i>=r)return[];let s=[],t=Object.keys(n.packageJson?.dependencies||{});for(let e of t)if(o[e])s.push({children:xs(o[e],o,r,i+1),name:e,version:o[e].version});return s}function $s(n,o=""){let r="";for(let i=0;i<n.length;i++){let s=i===n.length-1,t=s?"\u2514\u2500":"\u251C\u2500",e=o+(s?" ":"\u2502 ");if(r+=`${o}${t} ${n[i].name}@${n[i].version}
|
|
161
|
-
`,n[i].children?.length>0)r+=$s(n[i].children,e)}return r.trimEnd()}N();L();_();G();import{parseArgs as Na}from"util";var{$:Ga}=globalThis.Bun;var Ss=C({prefix:"sisyphus"}).child("metrics");function Ha(){let{values:n}=Na({args:process.argv.slice(3),options:{days:{short:"d",type:"string"},detailed:{short:"v",type:"boolean"},json:{short:"j",type:"boolean"},package:{short:"p",type:"string"}}});return{days:n.days?Number.parseInt(n.days,10):30,detailed:n.detailed,json:n.json,package:n.package}}async function vs(){try{let n=Ha(),{packages:o}=await U(),r=await Ua(n.days||30),i=await qa(o,r,n.package);if(n.json){console.log(JSON.stringify({packageMetrics:i,releases:r},null,2));return}if(za(r,i,n),n.detailed)ka(i,n)}catch(n){Ss.error("Failed to generate metrics:",n),process.exit(1)}}async function Ua(n){let o=new Date;o.setDate(o.getDate()-n);try{let r=await Ga`git log --tags --simplify-by-decoration --pretty="format:%ci %h %d" --since="${o.toISOString()}"`.text(),i=[],s=r.trim().split(`
|
|
162
|
-
`).filter(Boolean);for(let t of s){let e=t.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) ([a-f0-9]+) \(tag: ([^)]+)\)/);if(e){let[,a="",c="",u=""]=e,m=new Date(a),g=u.match(/@[^@]+@[\d.]+(-\w+\.\d+)?/g);if(g){let d={},w=[];for(let p of g){let[f,h]=p.split("@").filter(Boolean);if(f&&h)w.push(`@${f}`),d[`@${f}`]={from:"unknown",to:h}}i.push({commitHash:c,date:m,packages:w,tag:u,versions:d})}}}return i}catch{return Ss.warn("Could not fetch git history, using empty release history"),[]}}async function qa(n,o,r){let i=new Map;for(let[s]of Object.entries(n)){if(r&&!s.includes(r))continue;i.set(s,{majorReleases:0,minorReleases:0,name:s,patchReleases:0,releaseFrequency:"Never",totalReleases:0,versionHistory:[]})}for(let s of o)for(let t of s.packages){let e=i.get(t);if(!e)continue;e.totalReleases++,e.lastRelease=s.date;let a=s.versions[t];if(a?.to){e.versionHistory.push({date:s.date,version:a.to});let c=a.to.match(/(\d+)\.(\d+)\.(\d+)/);if(c){let[,,u,m]=c;if(m!=="0")e.patchReleases++;else if(u!=="0")e.minorReleases++;else e.majorReleases++}}}for(let s of i.values())if(s.totalReleases>1&&s.versionHistory.length>1){let t=s.versionHistory[s.versionHistory.length-1]?.date?.getTime()||0,e=s.versionHistory[0]?.date?.getTime()||0,a=Math.floor((e-t)/86400000),c=Math.floor(a/(s.totalReleases-1));if(c===0)s.releaseFrequency="Daily";else if(c<=7)s.releaseFrequency=`Every ${c} days`;else if(c<=30)s.releaseFrequency=`Every ${Math.floor(c/7)} weeks`;else s.releaseFrequency=`Every ${Math.floor(c/30)} months`}else if(s.totalReleases===1)s.releaseFrequency="Single release";return Array.from(i.values()).sort((s,t)=>t.totalReleases-s.totalReleases)}function za(n,o,r){let i=n.length,s=o.filter((a)=>a.totalReleases>0).length,t=o.length;if($.info(`Release Metrics - Last ${r.days} days`),console.log(),console.log(l.bold("\uD83D\uDCCA Overview")),console.log(` Total releases: ${l.value(String(i))}`),console.log(` Active packages: ${l.value(`${s}/${t}`)}`),n.length>0){let[a]=n;console.log(` Last release: ${l.dim(Cr(a?.date))}`)}console.log();let e=o.filter((a)=>a.totalReleases>0).slice(0,5);if(e.length>0){console.log(l.bold("\uD83C\uDFC6 Most Active Packages"));for(let a of e){let c="\u2588".repeat(Math.min(20,a.totalReleases)),u=a.lastRelease?` (${js(a.lastRelease)})`:"";console.log(` ${l.value(a.name.padEnd(25))} ${l.dim(c)} ${a.totalReleases} releases${l.dim(u)}`)}console.log()}if(n.length>0){console.log(l.bold("\uD83D\uDCC5 Recent Releases"));let a=n.slice(0,5);for(let c of a){let u=c.packages.slice(0,3).join(", "),m=c.packages.length>3?` +${c.packages.length-3} more`:"";console.log(` ${l.dim(Cr(c.date))} - ${u}${l.dim(m)}`)}console.log()}}function ka(n,o){console.log(l.bold("\uD83D\uDCE6 Package Details")),console.log();for(let r of n){if(r.totalReleases===0)continue;if(console.log(`${l.bold(r.name)}`),console.log(` Releases: ${r.totalReleases} (${r.majorReleases} major, ${r.minorReleases} minor, ${r.patchReleases} patch)`),console.log(` Frequency: ${r.releaseFrequency}`),console.log(` Last release: ${r.lastRelease?Cr(r.lastRelease):"Never"}`),r.versionHistory.length>0){console.log(" Recent versions:");let i=r.versionHistory.slice(0,3);for(let{version:s,date:t}of i)console.log(` ${l.value(s)} - ${l.dim(js(t))}`)}console.log()}}function Cr(n){if(!n)return"Never";return n.toLocaleDateString("en-US",{day:"numeric",hour:"2-digit",minute:"2-digit",month:"short",year:"numeric"})}function js(n){let r=new Date().getTime()-n.getTime(),i=Math.floor(r/86400000);if(i===0)return"today";if(i===1)return"yesterday";if(i<7)return`${i} days ago`;if(i<30)return`${Math.floor(i/7)} weeks ago`;if(i<365)return`${Math.floor(i/30)} months ago`;return`${Math.floor(i/365)} years ago`}N();L();G();import{randomUUID as Ja}from"crypto";import{join as In,relative as Ya}from"path";var{$:Ir}=globalThis.Bun;var Pr=C({prefix:"sisyphus:migrate"});async function Rs(){let n=Pr.child("run");un(`${l.command("sisyphus migrate")} - Migrate from changesets to stones`);let o=process.cwd(),r=In(o,".changeset");if(!await Bun.file(r).exists())n.warn("No .changeset directory found"),q(l.error("No changesets found to migrate")),process.exit(1);let i=Sn();i.start("Analyzing changesets...");try{let s=await Wa(r);if(s.length===0){i.stop("No changesets found"),q(l.warning("No changesets to migrate"));return}i.stop(`Found ${l.value(String(s.length))} changeset(s)`);let t=[];for(let w of s){let p=await Fa(w);if(p){t.push(p);let f=Ya(o,w);B(`${l.dim("File:")} ${f}
|
|
163
|
-
${l.dim("Packages:")} ${Object.entries(p.packages).map(([h,x])=>`${h} (${x})`).join(", ")}
|
|
164
|
-
${l.dim("Summary:")} ${p.summary.slice(0,80)}${p.summary.length>80?"...":""}`,l.info("Changeset found"))}}if(t.length===0){q(l.warning("No valid changesets found to migrate"));return}if(!await D({initialValue:!0,message:`Migrate ${t.length} changeset(s) to stones?`})){q(l.dim("Migration cancelled"));return}i.start("Migrating changesets to stones...");let a=In(o,".sisyphus"),c=In(a,"stones");if(!await Bun.file(a).exists())await Ir`mkdir -p ${c}`,await Bun.write(In(a,"config.json"),JSON.stringify({stones:[]},null,2));else if(!await Bun.file(c).exists())await Ir`mkdir -p ${c}`;let m=(await on()).length,g=[];for(let w of t){m++;let p=`${String(m).padStart(4,"0")}-${Ja().slice(0,8)}`,f=Ka(w),h=In(c,`${p}.md`);await Bun.write(h,f.content),g.push(p),n.info(`Created stone: ${p}`)}if(i.stop(`Created ${l.value(String(g.length))} stone(s)`),g.length>0){let w=In(a,"config.json"),p=await Bun.file(w).json();p.stones=[...p.stones||[],...g],await Bun.write(w,JSON.stringify(p,null,2))}if(await D({initialValue:!0,message:"Remove .changeset directory?"}))i.start("Cleaning up changesets..."),await Ir`rm -rf ${r}`,i.stop("Changesets cleaned up"),n.info("Removed .changeset directory");q(l.success("Migration completed successfully!"))}catch(s){i.stop("Migration failed"),n.error("Migration failed",s),q(l.error(`Migration failed: ${s}`)),process.exit(1)}}async function Wa(n){let o=[];try{let r=await Array.fromAsync(new Bun.Glob("*.md").scan(n));for(let i of r)if(i!=="README.md")o.push(In(n,i))}catch(r){Pr.error("Failed to scan changeset directory",r)}return o}async function Fa(n){try{let r=(await Bun.file(n).text()).split(`
|
|
165
|
-
`),i=!1,s=[],t=[];for(let c of r)if(c.trim()==="---")if(!i)i=!0;else i=!1;else if(i)s.push(c);else if(!i&&s.length>0)t.push(c);let e={};for(let c of s){let u=c.match(/^"(.+)":\s*(major|minor|patch)$/);if(u){if(u[1]&&u[2])e[u[1]]=u[2]}}let a=t.join(`
|
|
166
|
-
`).trim();if(Object.keys(e).length===0)return null;return{packages:e,summary:a}}catch(o){return Pr.error(`Failed to parse changeset: ${n}`,o),null}}function Ka(n){let o=[],r=[],i=[];for(let[m,g]of Object.entries(n.packages)){let d=m.startsWith("@")?m:`@${m}`;switch(g){case"major":o.push(d);break;case"minor":r.push(d);break;case"patch":i.push(d);break}}let s=n.summary.split(`
|
|
167
|
-
`)[0],e=`### ${s||"Migrated from changesets"}
|
|
168
|
-
|
|
169
|
-
`;if(n.summary&&n.summary!==s){let m=n.summary.split(`
|
|
170
|
-
`).slice(1).join(`
|
|
171
|
-
`).trim();if(m)e+=`${m}
|
|
172
|
-
|
|
173
|
-
`}e+=`***
|
|
174
|
-
|
|
175
|
-
`;let a=[],c=[],u=[];if(o.length>0)a.push("major"),c.push(o.join(", ")),u.push(":---:");if(r.length>0)a.push("minor"),c.push(r.join(", ")),u.push(":---:");if(i.length>0)a.push("patch"),c.push(i.join(", ")),u.push(":---:");return e+=`| ${a.join(" | ")} |
|
|
176
|
-
`,e+=`| ${u.join(" | ")} |
|
|
177
|
-
`,e+=`| ${c.join(" | ")} |
|
|
178
|
-
`,{content:e}}N();L();_();G();import{parseArgs as Va}from"util";G();Mn();import{randomUUID as Xa}from"crypto";var Za=["major","minor","patch","dependency","snapshot"];function Qa({message:n,tag:o,packages:r}){let i=r.reduce((t,e)=>{return t[e.bump]=t[e.bump]||[],t[e.bump].push(e.name),t},{}),s=Za.filter((t)=>i[t]?.length>0);return[`### ${n}`,o?`_${o}_`:"",xr,"",`| ${s.join(" | ")} |`,`| ${s.map(()=>":---:").join(" | ")} |`,`| ${s.map((t)=>i[t]?.join(", ")||"").join(" | ")} |`,""]}function Pn(n){let o=n.split(`
|
|
179
|
-
`).filter((t)=>t.trim()),r={commitMessage:"",dependency:[],description:"",major:[],minor:[],patch:[],snapshot:[],tag:""},i=o.findIndex((t)=>t.includes("---"));if(o[0]?.startsWith("###"))r.commitMessage=o[0].replace(/^#+\s*/,"");if(i>1){let t=[];for(let e=1;e<i;e++){let a=o[e];if(a?.startsWith("_")&&a.endsWith("_"))r.tag=a.slice(1,-1);else if(a)t.push(a)}r.description=t.join(`
|
|
180
|
-
`).trim()}let s=o.findIndex((t)=>t.includes("|")&&!t.includes("---"));if(s!==-1&&o[s]){let e=o[s].split("|").map((c)=>c.trim()).filter((c)=>c),a=o[s+2];if(a){let c=a.split("|").map((u)=>u.trim()).filter((u)=>u);e.forEach((u,m)=>{let g=c[m]?.split(",").map((w)=>w.trim()).filter((w)=>w)||[],d=u.toLowerCase();if(d==="major")r.major=g;else if(d==="minor")r.minor=g;else if(d==="patch")r.patch=g;else if(d==="dependency")r.dependency=g;else if(d==="snapshot")r.snapshot=g})}}return r}async function yn({majorPackages:n,message:o,minorPackages:r,packages:i,patchPackages:s,tag:t,configPath:e}){let c=`${`${(await on({configPath:e})).length+1}`.padStart(4,"0")}-${Xa().slice(0,8)}`,u=[...n,...r,...s],m=u.flatMap((p)=>i[p]?.dependencyOf||[]),d=[{packages:n,type:"major"},{packages:r,type:"minor"},{packages:s,type:"patch"},{packages:m.filter((p)=>!u.includes(p)),type:"dependency"}].flatMap(({packages:p,type:f})=>p.map((h)=>{let x=i[h];if(!x)throw Error(`Package ${h} not found`);return{...x,bump:f,tag:t}})).filter(Boolean),w=Qa({message:o,packages:d,tag:t});return{packages:d,stoneContent:w,stoneName:c}}var Xn=C({prefix:"sisyphus"}).child("pr"),nc=/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/,oc=/gitlab\.com\/(.+)\/-\/merge_requests\/(\d+)/,rc={"breaking-change":"major",bug:"patch",chore:"patch",documentation:"patch",enhancement:"minor",feature:"minor",fix:"patch"};function ic(){let{values:n}=Va({args:process.argv.slice(3),options:{dryRun:{short:"d",type:"boolean"},github:{type:"boolean"},gitlab:{type:"boolean"},url:{short:"u",type:"string"},yes:{short:"y",type:"boolean"}}});return n}async function Es(){try{let n=ic(),{packages:o,packageNames:r}=await U(),i;if(n.url)i=await sc(n.url);else i=await tc(n);if(!i){$.error("Could not determine PR information. Please provide a PR URL with --url");return}if($.info(`Processing PR #${i.number}: ${i.title}`),console.log(),console.log(` Author: ${l.value(i.author)}`),console.log(` Branch: ${l.value(i.branch)}`),i.labels.length>0)console.log(` Labels: ${i.labels.map((f)=>l.dim(f)).join(", ")}`);console.log();let s;for(let f of i.labels){let h=f.toLowerCase();for(let[x,S]of Object.entries(rc))if(h.includes(x)){if(s=S,S==="major")break}if(s==="major")break}if(!s){let f=i.title.toLowerCase();if(f.includes("breaking")||f.includes("!:"))s="major";else if(f.includes("feat")||f.includes("feature"))s="minor";else if(f.includes("fix")||f.includes("bug"))s="patch"}if(!s&&!n.yes){let f=await J({message:"Could not determine bump type from PR. What type of change is this? (major/minor/patch)",placeholder:"patch"});if(!f||!["major","minor","patch"].includes(f)){$.info("Invalid bump type. Cancelled.");return}s=f}else if(!s)s="patch";$.info(`Detected bump type: ${l.bold(s)}`);let t=await cc(i.branch),e=await uc(t,o,r);if(e.length===0){$.warn("No packages affected by this PR");return}console.log(),console.log(l.bold("Affected packages:"));for(let f of e){let h=o[f];if(!h)continue;let x=h.version,S=pc(x,s);console.log(` ${l.value(f)}: ${x} \u2192 ${l.success(S)}`)}console.log();let a=`${i.title} (#${i.number})`,c;if(!n.yes){let f=await J({initialValue:a,message:"Commit message for this stone",placeholder:a});if(!f){$.info("Cancelled");return}c=f}else c=a;let u=s==="major"?e:[],m=s==="minor"?e:[],g=s==="patch"?e:[],{stoneContent:d,stoneName:w}=await yn({majorPackages:u,message:c,minorPackages:m,packages:o,patchPackages:g,tag:void 0});if(n.dryRun){$.info("Dry run - no changes made"),console.log(l.dim("Stone content:")),console.log(d.join(`
|
|
181
|
-
`));return}if(!n.yes){if(!await D({initialValue:!0,message:"Create stone from this PR?"})){$.info("Cancelled");return}}let p=await O();p.stones.push(w),await Bun.write(`.sisyphus/stones/${w}.md`,d.join(`
|
|
182
|
-
`)),await Bun.write(".sisyphus/config.json",`${JSON.stringify(p,null,2)}
|
|
183
|
-
`),$.success(`Created stone from PR: ${l.bold(w)}`),$.info(`Review the stone with ${l.value(`sisyphus stone show ${w}`)}`)}catch(n){Xn.error("Failed to process PR:",n),process.exit(1)}}async function sc(n){let o=n.match(nc);if(o){let[,i="",s="",t=""]=o;return await ec(i,s,t)}let r=n.match(oc);if(r){let[,i="",s=""]=r;return await ac(i,s)}throw Error("Unsupported PR URL format")}async function tc(n){try{if((await Bun.$`git remote get-url origin`.text()).includes("github.com")||n.github)try{let r=await Bun.$`gh pr view --json number,title,body,labels,author,headRefName`.json();return{author:r.author?.login||"unknown",branch:r.headRefName,description:r.body||"",labels:r.labels?.map((i)=>i.name)||[],number:String(r.number),title:r.title}}catch{Xn.debug("GitHub CLI not available or no PR found")}return null}catch(o){return Xn.debug("Could not detect current PR:",o),null}}async function ec(n,o,r){try{let i=await Bun.$`gh api repos/${n}/${o}/pulls/${r}`.json();return{author:i.user?.login||"unknown",branch:i.head.ref,description:i.body||"",labels:i.labels?.map((s)=>s.name)||[],number:String(i.number),title:i.title}}catch(i){throw Error(`Failed to fetch GitHub PR: ${i}`)}}async function ac(n,o){throw Error("GitLab integration requires API token configuration")}async function cc(n){try{let r=(await Bun.$`git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@'`.text()).trim()||"main";return(n?await Bun.$`git diff --name-only ${r}...${n}`.text():await Bun.$`git diff --name-only ${r}...HEAD`.text()).trim().split(`
|
|
184
|
-
`).filter(Boolean)}catch(o){return Xn.warn("Could not get changed files, using current uncommitted changes"),(await Bun.$`git status --porcelain`.text()).trim().split(`
|
|
185
|
-
`).map((i)=>i.substring(3)).filter(Boolean)}}async function uc(n,o,r){let i=new Set,s=new Map;for(let[t,e]of Object.entries(o))if(e.relativePath)s.set(e.relativePath,t);for(let t of n)for(let[e,a]of s)if(t.startsWith(`${e}/`))i.add(a);if(i.size===0&&n.length>0){if(n.filter((e)=>!e.includes("/")||e.startsWith(".")).length>0)return Xn.info("Root files changed, considering all packages affected"),r}return Array.from(i)}function pc(n,o){let r=n.split("."),i=Number.parseInt(r[0]||"0",10),s=Number.parseInt(r[1]||"0",10),t=Number.parseInt(r[2]||"0",10);switch(o){case"major":return`${i+1}.0.0`;case"minor":return`${i}.${s+1}.0`;case"patch":return`${i}.${s}.${t+1}`;default:return n}}N();L();_();G();Mn();import{parseArgs as lc}from"util";var fc=C({prefix:"sisyphus"}).child("prerelease"),mc=["alpha","beta","rc","canary","dev","next"];function gc(){let{values:n}=lc({args:process.argv.slice(3),options:{bump:{short:"b",type:"string"},dryRun:{short:"d",type:"boolean"},filter:{short:"f",type:"string"},promote:{short:"p",type:"boolean"},type:{short:"t",type:"string"},yes:{short:"y",type:"boolean"}}});return n}async function Cs(){try{let n=gc(),{packages:o,packageNames:r}=await U({filter:n.filter});if(n.promote)await dc(n,o,r);else await hc(n,o,r)}catch(n){fc.error("Prerelease operation failed:",n),process.exit(1)}}async function hc(n,o,r){let i=n.type||await nn({message:"Select prerelease type",options:mc.map((h)=>({hint:yc(h),label:h,value:h}))});if(!i||typeof i!=="string"){$.info("Cancelled");return}let s=n.filter,t=s?r.filter((h)=>h.includes(s)):r;if(t.length===0){$.error(`No packages found matching filter: ${n.filter}`);return}let e=n.filter?t:await bc(t,o);if(e.length===0){$.info("No packages selected");return}let a;if(n.bump){let x={major:"major",minor:"minor",patch:"patch"}[n.bump.toLowerCase()];if(!x){$.error(`Invalid bump type: ${n.bump}. Must be major, minor, or patch.`);return}a=x}else{let h=await nn({message:"What type of change is this prerelease for?",options:[{label:"Major - Breaking changes",value:"major"},{label:"Minor - New features",value:"minor"},{label:"Patch - Bug fixes",value:"patch"}]});if(!h){$.info("Cancelled");return}a=h}let c=`chore: prepare ${i} release`,u;if(n.yes)u=c;else{let h=await J({message:"Commit message for this prerelease",placeholder:c});if(!h||typeof h!=="string"){$.info("Cancelled");return}u=h}let m=[],g=[],d=[];for(let h of e)switch(a){case"major":m.push(h);break;case"minor":g.push(h);break;case"patch":d.push(h);break}let{stoneContent:w,stoneName:p}=await yn({majorPackages:m,message:u,minorPackages:g,packages:o,patchPackages:d,tag:i});$.step("Preview of prerelease changes:"),console.log();for(let h of e){let x=o[h],S=X({bump:a,tag:i,version:x.version});console.log(` ${l.value(h)}: ${x.version} \u2192 ${l.bold(S)}`)}if(console.log(),n.dryRun){$.info("Dry run - no changes made"),console.log(l.dim("Stone content:")),console.log(w.join(`
|
|
186
|
-
`));return}if(!n.yes){if(!await D({initialValue:!0,message:"Create this prerelease stone?"})){$.info("Cancelled");return}}let f=await O();f.stones.push(p),await Bun.write(`.sisyphus/stones/${p}.md`,w.join(`
|
|
187
|
-
`)),await Bun.write(".sisyphus/config.json",`${JSON.stringify(f,null,2)}
|
|
188
|
-
`),$.success(`Created ${i} prerelease stone: ${l.bold(p)}`),$.info(`Run ${l.value("sisyphus roll")} to publish the prerelease`)}async function dc(n,o,r){let i=r.filter((p)=>{return o[p].version.includes("-")});if(i.length===0){$.info("No packages with prerelease versions found");return}$.info(`Found ${l.bold(String(i.length))} packages with prerelease versions`),console.log();let s=new Map;for(let p of i){let h=o[p].version.match(/-(\w+)\./);if(h){let x=h[1];if(!s.has(x))s.set(x,[]);s.get(x)?.push(p)}}for(let[p,f]of s){console.log(`${l.bold(p)} packages:`);for(let h of f)console.log(` ${l.value(h)}: ${o[h].version}`);console.log()}let t=Array.from(s.keys()),e=[];if(t.includes("alpha"))e.push({label:"Promote alpha \u2192 beta",value:"alpha-to-beta"},{label:"Promote alpha \u2192 rc",value:"alpha-to-rc"},{label:"Promote alpha \u2192 stable",value:"alpha-to-stable"});if(t.includes("beta"))e.push({label:"Promote beta \u2192 rc",value:"beta-to-rc"},{label:"Promote beta \u2192 stable",value:"beta-to-stable"});if(t.includes("rc")||t.includes("next"))e.push({label:"Graduate to stable release",value:"to-stable"});e.push({label:"Increment current prerelease version",value:"increment"});let a=await nn({message:"How would you like to promote these prereleases?",options:e});if(!a){$.info("Cancelled");return}let c,u=i,m;switch(a){case"alpha-to-beta":c="beta",u=s.get("alpha")||[],m="chore: promote alpha to beta";break;case"alpha-to-rc":c="rc",u=s.get("alpha")||[],m="chore: promote alpha to rc";break;case"alpha-to-stable":c=void 0,u=s.get("alpha")||[],m="chore: promote alpha to stable release";break;case"beta-to-rc":c="rc",u=s.get("beta")||[],m="chore: promote beta to rc";break;case"beta-to-stable":c=void 0,u=s.get("beta")||[],m="chore: promote beta to stable release";break;case"to-stable":c=void 0,u=[...s.get("rc")||[],...s.get("next")||[]],m="chore: graduate to stable release";break;case"increment":if(t.length>1){let p=await nn({message:"Which prerelease type would you like to increment?",options:t.map((f)=>({label:f,value:f}))});if(!p){$.info("Cancelled");return}c=p,u=s.get(c)||[]}else c=t[0],u=c?s.get(c)||[]:[];m=`chore: increment ${c} version`;break;default:$.error("Unknown promotion strategy");return}if(u.length===0){$.info("No packages to promote");return}$.step("Preview of promotion:"),console.log();for(let p of u){let f=o[p].version,h;if(c===void 0)h=f.split("-")[0];else if(a==="increment")h=X({bump:"patch",tag:c,version:f});else h=`${f.split("-")[0]}-${c}.0`;console.log(` ${l.value(p)}: ${f} \u2192 ${l.bold(h)}`)}if(console.log(),!n.yes){if(!await D({initialValue:!0,message:"Continue with this promotion?"})){$.info("Cancelled");return}}let{stoneContent:g,stoneName:d}=await yn({majorPackages:[],message:m,minorPackages:[],packages:o,patchPackages:u,tag:c});if(n.dryRun){$.info("Dry run - no changes made"),console.log(g.join(`
|
|
189
|
-
`));return}let w=await O();w.stones.push(d),await Bun.write(`.sisyphus/stones/${d}.md`,g.join(`
|
|
190
|
-
`)),await Bun.write(".sisyphus/config.json",`${JSON.stringify(w,null,2)}
|
|
191
|
-
`),$.success(`Created promotion stone: ${l.bold(d)}`),$.info(`Run ${l.value("sisyphus roll")} to publish the promotion`)}function yc(n){switch(n){case"alpha":return"Early development, unstable";case"beta":return"Feature complete, testing";case"rc":return"Release candidate, final testing";case"canary":return"Latest commit builds";case"dev":return"Development builds";case"next":return"Next version preview";default:return""}}async function bc(n,o){if(await nn({message:"Select packages for prerelease",options:[{label:"All packages",value:"all"},{label:"Select specific packages",value:"select"}]})==="all")return n;$.info("Select packages (space to select, enter to confirm)");let i=[];for(let s of n)if(await D({initialValue:!1,message:`Include ${s} (${o[s].version})?`}))i.push(s);return i}N();L();_();G();import{parseArgs as wc}from"util";var xc=C({prefix:"sisyphus"}).child("preview");async function Is(){let{values:n}=wc({args:process.argv.slice(3),options:{"include-private":{type:"boolean"},json:{short:"j",type:"boolean"},verbose:{short:"v",type:"boolean"}}}),{json:o,verbose:r,"include-private":i=!1}=n;try{let s=await O(),t=await Kn();if(t.length===0){if(o)console.log(JSON.stringify({message:"No pending stones found"}));else $.info("No pending stones found. Nothing to preview.");return}let{packages:e}=await U({includePrivate:Boolean(i)}),a={},c=[];for(let{tag:m,packages:g,message:d}of t){c.push(d);for(let w of g){if(!a[w.name])a[w.name]={...w};let p=a[w.name];if(!p)continue;if(m)p.tag=m;p.bump=Rn.indexOf(w.bump)>Rn.indexOf(p.bump)?w.bump:p.bump,a[w.name]=p}}let u=Object.entries(a).map(([m,g])=>{let d=e[m]?.version||"0.0.0",[w="0",p="0",f="0"]=d.split("."),h=d;switch(g.bump){case"major":h=`${Number.parseInt(w,10)+1}.0.0`;break;case"minor":h=`${w}.${Number.parseInt(p,10)+1}.0`;break;case"patch":case"dependency":h=`${w}.${p}.${Number.parseInt(f,10)+1}`;break;case"snapshot":{let x=new Date().toISOString().replace(/[.ZT:-]/g,"").slice(0,14);h=`0.0.0-${g.tag||"nightly"}-${x}`;break}}if(g.tag&&g.bump!=="snapshot")h=`${h}-${g.tag}.0`;return{bump:g.bump,currentVersion:d,name:m,newVersion:h,tag:g.tag}});if(o){console.log(JSON.stringify({messages:c,stones:t.length,updates:u},null,2));return}$.info(`Preview of release with ${l.bold(String(t.length))} stone${t.length>1?"s":""}`),console.log(),console.log(l.bold("Commit Messages:")),c.forEach((m)=>{console.log(` ${l.bullet("\u2022")} ${m}`)}),console.log(),console.log(l.bold("Version Updates:"));for(let m of u){let g=m.bump==="major"?l.error:m.bump==="minor"?l.warning:l.success;console.log(` ${l.value(m.name)}`),console.log(` ${l.dim("Current:")} ${m.currentVersion}`),console.log(` ${l.dim("New:")} ${l.bold(m.newVersion)}`),console.log(` ${l.dim("Bump:")} ${g(m.bump)}${m.tag?` (${l.value(m.tag)})`:""}`),console.log()}if(r)console.log(l.bold("Additional Information:")),console.log(` ${l.dim("Config path:")} ${s.configPath||".sisyphus"}`),console.log(` ${l.dim("Total packages:")} ${Object.keys(e).length}`),console.log(` ${l.dim("Packages to update:")} ${u.length}`)}catch(s){xc.error("Failed to preview release:",s),process.exit(1)}}N();L();G();import{parseArgs as $c}from"util";var{$:Po}=globalThis.Bun;var Sc=C({prefix:"sisyphus:solo"});async function Ps(){let{values:n}=$c({args:process.argv.slice(3),options:{"dry-run":{short:"d",type:"boolean"},tag:{short:"t",type:"string"}}}),{"dry-run":o,tag:r}=n;un(`${l.command("sisyphus solo")} - Single maintainer workflow`);let i=Sn();i.start("Creating version from commits and rolling immediately...");try{let s=await Po`git describe --tags --abbrev=0 2>/dev/null || echo ""`.text(),t=await Po`git rev-list ${s?`${s.trim()}..HEAD`:"HEAD"} --count`.text();if(Number.parseInt(t.trim(),10)===0){i.stop("No commits to release"),q(l.dim("Already up to date"));return}i.message("Analyzing commits...");let e=["bunx","@r5n/sisyphus","version","--from-commits","--yes"];if(o)e.push("--dry-run");if(await Po`${e}`,((await O()).stones||[]).length===0&&!o){i.stop("No releasable changes found"),q(l.dim("No version bumps needed"));return}i.message(o?"Previewing release...":"Rolling stones...");let u=["bunx","@r5n/sisyphus","roll"];if(o)u.push("--dry-run");if(r)u.push("--tag",r);await Po`${u}`,i.stop("Release complete!"),q(l.success("Published successfully"))}catch(s){i.stop("Solo release failed"),Sc.error("Failed to complete solo workflow",s),q(l.error(`Solo release failed: ${s}`)),process.exit(1)}}L();_();N();L();_();G();import{existsSync as vc}from"fs";import{unlink as jc}from"fs/promises";import{join as Rc}from"path";import{parseArgs as Ec}from"util";var Zn=C({prefix:"sisyphus"}).child("stone:delete");async function Os(n){if(!n)Zn.error("Stone ID is required"),Zn.error("Usage: sisyphus stone delete <id>"),process.exit(1);let{values:o}=Ec({args:process.argv.slice(5),options:{force:{short:"f",type:"boolean"}}}),{force:r}=o;try{let s=(await O()).stonesPath||".sisyphus/stones",t=Rc(s,`${n}.md`);if(!vc(t))Zn.error(`Stone '${n}' not found`),Zn.info("Run 'sisyphus stone list' to see available stones"),process.exit(1);if(!r){if(!await D({initialValue:!1,message:`Delete stone '${n}'?`})){$.info("Deletion cancelled");return}}await jc(t),$.success(`Stone '${l.bold(n)}' deleted`)}catch(i){Zn.error(`Failed to delete stone '${n}':`,i),process.exit(1)}}N();L();_();G();import{existsSync as Cc}from"fs";import{readFile as Ic,writeFile as Pc}from"fs/promises";import{join as Oc}from"path";import{parseArgs as _c}from"util";var Dn=C({prefix:"sisyphus"}).child("stone:edit");async function _s(n){if(!n)Dn.error("Stone ID is required"),Dn.error("Usage: sisyphus stone edit <id>"),process.exit(1);let{values:o}=_c({args:process.argv.slice(5),options:{interactive:{short:"i",type:"boolean"},message:{short:"m",type:"string"}}}),{message:r,interactive:i}=o;try{let t=(await O()).stonesPath||".sisyphus/stones",e=Oc(t,`${n}.md`);if(!Cc(e))Dn.error(`Stone '${n}' not found`),Dn.info("Run 'sisyphus stone list' to see available stones"),process.exit(1);let a=await Ic(e,"utf-8");if(r){let c=a.split(`
|
|
192
|
-
`);c[0]=`### ${r}`,await Pc(e,c.join(`
|
|
193
|
-
`)),$.success(`Updated commit message for stone '${l.bold(n)}'`);return}if(i){$.info("Interactive stone editing coming soon"),$.info("For now, you can manually edit:"),$.info(l.dim(e));return}Dn.error("Please specify --message or --interactive"),process.exit(1)}catch(s){Dn.error(`Failed to edit stone '${n}':`,s),process.exit(1)}}L();var Ts={delete:{description:"Remove a specific stone before rolling",examples:[{command:"sisyphus stone delete stone-123",description:"Delete a stone by ID"},{command:"sisyphus stone delete stone-123 --force",description:"Delete without confirmation"}],name:"sisyphus stone delete",options:[{description:"Skip confirmation prompt",flags:"-f, --force",type:"boolean"}],usage:"sisyphus stone delete <id> [options]"},edit:{description:"Modify stone content or version bumps",examples:[{command:"sisyphus stone edit stone-123 --interactive",description:"Edit stone interactively"},{command:'sisyphus stone edit stone-123 --message "feat: better description"',description:"Update commit message"}],name:"sisyphus stone edit",options:[{description:"New commit message",flags:"-m, --message",type:"string"},{description:"Edit in interactive mode",flags:"-i, --interactive",type:"boolean"}],usage:"sisyphus stone edit <id> [options]"},list:{description:"View all pending stones with details",examples:[{command:"sisyphus stone list",description:"List all pending stones"},{command:"sisyphus stone list --verbose",description:"Show full stone content"},{command:"sisyphus stone list --json",description:"Output as JSON for scripting"}],name:"sisyphus stone list",options:[{description:"Output in JSON format",flags:"-j, --json",type:"boolean"},{description:"Show full stone content",flags:"-v, --verbose",type:"boolean"}],usage:"sisyphus stone list [options]"},merge:{description:"Combine multiple stones with smart conflict resolution",examples:[{command:"sisyphus stone merge",description:"Merge stones interactively"},{command:"sisyphus stone merge --ids stone-123 stone-456",description:"Merge specific stones"},{command:"sisyphus stone merge --strategy highest",description:"Merge with automatic conflict resolution"},{command:'sisyphus stone merge --strategy interactive --message "feat: combined changes"',description:"Merge with interactive conflict resolution"}],name:"sisyphus stone merge",notes:["Detects when same package has different bump types across stones","Default strategy uses highest bump type (major > minor > patch)","Interactive strategy lets you choose resolution for each conflict"],options:[{description:"Stone IDs to merge (multiple)",flags:"-i, --ids",type:"string"},{description:"Commit message for merged stone",flags:"-m, --message",type:"string"},{description:"Skip confirmation",flags:"-f, --force",type:"boolean"},{description:"Conflict resolution (highest/interactive)",flags:"-s, --strategy",type:"string"}],usage:"sisyphus stone merge [options]"},show:{description:"Display full content of a specific stone",examples:[{command:"sisyphus stone show stone-123",description:"Show stone content"},{command:"sisyphus stone show stone-123 --json",description:"Output as JSON"}],name:"sisyphus stone show",options:[{description:"Output in JSON format",flags:"-j, --json",type:"boolean"}],usage:"sisyphus stone show <id> [options]"}};function Oo(n){if(n&&Ts[n]){console.log(wo(Ts[n]));return}console.log(xo("Sisyphus Stone Management","sisyphus stone <command> [options]",[{description:"View all pending stones with details",name:"list"},{description:"Remove a specific stone by ID",name:"delete"},{description:"Display full content of a stone",name:"show"},{description:"Modify stone content or versions",name:"edit"},{description:"Combine multiple stones into one",name:"merge"},{description:"Show this help message",name:"help"}],"Use sisyphus stone <command> --help for more information about a command."))}N();L();_();G();import{readFile as Tc}from"fs/promises";import{join as Bc}from"path";import{parseArgs as Ac}from"util";var Bs=C({prefix:"sisyphus"}).child("stone:list");async function As(){let{values:n}=Ac({args:process.argv.slice(4),options:{json:{short:"j",type:"boolean"},verbose:{short:"v",type:"boolean"}}}),{json:o,verbose:r}=n;try{let s=(await O()).stonesPath||".sisyphus/stones",t=await on();if(t.length===0){if(o)console.log(JSON.stringify([]));else $.info("No pending stones found");return}let e=[];for(let a of t){let c=Bc(s,`${a}.md`);try{let u=await Tc(c,"utf-8"),m=Pn(u);e.push({id:a,path:c,...m})}catch(u){Bs.warn(`Failed to read stone ${a}:`,u)}}if(o){console.log(JSON.stringify(e,null,2));return}$.info(`Found ${l.bold(String(e.length))} pending stone${e.length>1?"s":""}`),console.log();for(let[a,c]of e.entries()){if(console.log(`${l.bullet("\u2022")} ${l.bold(c.id)}`),console.log(` ${l.dim("Message:")} ${c.commitMessage}`),c.tag)console.log(` ${l.dim("Tag:")} ${l.value(c.tag)}`);if(c.major.length>0)console.log(` ${l.error("Major:")} ${c.major.join(", ")}`);if(c.minor.length>0)console.log(` ${l.warning("Minor:")} ${c.minor.join(", ")}`);if(c.patch.length>0)console.log(` ${l.success("Patch:")} ${c.patch.join(", ")}`);if(r&&c.description)console.log(` ${l.dim("Description:")}`),c.description.split(`
|
|
194
|
-
`).forEach((u)=>{console.log(` ${l.dim(u)}`)});if(a<e.length-1)console.log()}}catch(i){Bs.error("Failed to list stones:",i),process.exit(1)}}N();L();_();G();import{readFile as Ns,unlink as Gs,writeFile as Mc}from"fs/promises";import{join as Or}from"path";import{parseArgs as Lc}from"util";N();L();Mn();var _o={major:4,minor:3,patch:2,dependency:1,snapshot:5};function Ms(n){let o=new Map;for(let i of n){for(let s of i.major){let t={bumpType:"major",name:s,stoneId:i.id,tag:i.tag};o.set(s,[...o.get(s)||[],t])}for(let s of i.minor){let t={bumpType:"minor",name:s,stoneId:i.id,tag:i.tag};o.set(s,[...o.get(s)||[],t])}for(let s of i.patch){let t={bumpType:"patch",name:s,stoneId:i.id,tag:i.tag};o.set(s,[...o.get(s)||[],t])}}let r=[];for(let[i,s]of o)if(s.length>1){let t=new Set(s.map((a)=>a.bumpType)),e=new Set(s.map((a)=>a.tag).filter(Boolean));if(t.size>1||e.size>1)r.push({conflicts:s,packageName:i})}return r}async function Ls(n,o="highest"){let r=[];for(let i of n){if(o==="highest"){let s=i.conflicts.reduce((t,e)=>_o[e.bumpType]>_o[t.bumpType]?e:t);i.resolution={chosenBumpType:s.bumpType,chosenStoneId:s.stoneId,reason:"Highest bump type selected"}}else{let s=i.conflicts.map((e)=>({label:`${e.bumpType} from ${e.stoneId}${e.tag?` (${e.tag})`:""}`,value:e}));console.log(`
|
|
195
|
-
${l.warning("Conflict detected")} for ${l.value(i.packageName)}:`);for(let e of i.conflicts)console.log(` ${l.dim("\u2022")} ${e.bumpType} from ${e.stoneId}${e.tag?` (${e.tag})`:""}`);let t=await nn({message:"How should this conflict be resolved?",options:[{label:"Use highest bump type",value:"highest"},...s]});if(t&&t==="highest"){let e=i.conflicts.reduce((a,c)=>_o[c.bumpType]>_o[a.bumpType]?c:a);i.resolution={chosenBumpType:e.bumpType,chosenStoneId:e.stoneId,reason:"Highest bump type selected"}}else if(t&&typeof t==="object"){let e=t;i.resolution={chosenBumpType:e.bumpType,chosenStoneId:e.stoneId,reason:"Manually selected"}}}r.push(i)}return r}function Ds(n,o){let r={major:new Set,minor:new Set,patch:new Set,tags:{}},i=new Map;for(let s of o)if(s.resolution){let{chosenBumpType:t}=s.resolution,e=s.conflicts.find((a)=>a.stoneId===s.resolution?.chosenStoneId);i.set(s.packageName,{bumpType:t,tag:e?.tag})}for(let s of n){for(let t of s.major){let e=i.get(t);if(e){switch(e.bumpType){case"major":r.major.add(t);break;case"minor":r.minor.add(t);break;case"patch":r.patch.add(t);break}if(e.tag)r.tags[t]=e.tag}else r.major.add(t)}for(let t of s.minor)if(!i.has(t))r.minor.add(t);for(let t of s.patch)if(!i.has(t))r.patch.add(t)}return{major:Array.from(r.major),minor:Array.from(r.minor),patch:Array.from(r.patch),tags:r.tags}}var Hs=C({prefix:"sisyphus"}).child("stone:merge");async function Us(n){let{values:o}=Lc({allowPositionals:!0,args:process.argv.slice(4),options:{force:{short:"f",type:"boolean"},ids:{multiple:!0,short:"i",type:"string"},message:{short:"m",type:"string"},strategy:{short:"s",type:"string"}}}),{ids:r,message:i,force:s,strategy:t}=o;try{let a=(await O()).stonesPath||".sisyphus/stones",c=await on();if(c.length<2){$.info("Need at least 2 stones to merge");return}let u=[];if(r&&r.length>=2){for(let j of r)if(c.includes(j)){let R=Or(a,`${j}.md`),P=await Ns(R,"utf-8"),v=Pn(P);u.push({id:j,path:R,...v})}if(u.length<2)Hs.error("Could not find all specified stones"),process.exit(1)}else{let j=[];for(let P of c){let v=Or(a,`${P}.md`),E=await Ns(v,"utf-8"),H=Pn(E);j.push({label:`${P} - ${H.commitMessage}`,value:{id:P,path:v,...H}})}let R=await $n({message:"Select stones to merge",options:j,required:!0});if(!R||Array.isArray(R)&&R.length<2){$.info("Need to select at least 2 stones");return}u=R}let m=i||await J({message:"Commit message for merged stone",placeholder:"feat: combined changes"});if(!m||typeof m!=="string"){$.info("Merge cancelled");return}let g=Ms(u),d;if(g.length>0){B(`Found ${l.value(String(g.length))} package conflict(s):
|
|
196
|
-
`+g.map((P)=>` ${l.dim("\u2022")} ${P.packageName}`).join(`
|
|
197
|
-
`),l.warning("Conflicts detected"));let R=await Ls(g,t==="highest"||t==="interactive"?t:"highest");if(d=Ds(u,R),R.length>0){let P=R.filter((v)=>v.resolution).map((v)=>` ${l.dim("\u2022")} ${v.packageName}: ${v.resolution?.chosenBumpType} (${v.resolution?.reason})`).join(`
|
|
198
|
-
`);B(P,l.success("Conflicts resolved"))}}else{let j={major:[],minor:[],patch:[]};for(let R of u)j.major.push(...R.major),j.minor.push(...R.minor),j.patch.push(...R.patch);d={major:[...new Set(j.major)],minor:[...new Set(j.minor)],patch:[...new Set(j.patch)],tags:{}}}let w=[];for(let j of u)if(j.description)w.push(j.description);let f=`merged-${Date.now()}`,h=Or(a,`${f}.md`),x=`### ${m}
|
|
199
|
-
`,S=[...new Set(Object.values(d.tags))];if(S.length===1)x+=`_${S[0]}_
|
|
200
|
-
`;if(w.length>0)x+=`
|
|
201
|
-
${w.join(`
|
|
179
|
+
After you finished, you can release it by running ${c.green(A)}${c.blue(" roll")}
|
|
180
|
+
`)}}var no=D({dryRun:{alias:"d",default:!1,description:"Preview migration without making changes",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class ln extends I{name="migrate";description="Migrate from changesets to sisyphus";args=no;parser=new rn;async execute(e){if(!await this.parser.exists())throw new d("No .changeset directory found","This command migrates existing changesets to sisyphus stones");let{changesets:t,config:n}=await this.analyzeChangesets();if(this.displayPreview(t,n),e.args.dryRun){N("No changes made",c.yellow("Dry run"));return}if(!e.args.yes&&!await this.confirmMigration(t.length))return;let r=await this.createStones(e,t);await this.applyConfigMigration(e,n),this.displaySuccess(r)}async analyzeChangesets(){let e=K();e.start("Analyzing changesets...");let t=await this.parser.parse();if(t.errors.length>0){e.error("Found issues while parsing");for(let n of t.errors)l.warn(c.yellow(n))}if(t.changesets.length===0)throw e.stop("No changesets found"),new d("No changeset files to migrate");return e.stop(`Found ${c.bold(String(t.changesets.length))} changeset(s)`),t}displayPreview(e,t){if(this.displayChangesets(e),t)this.displayConfigMapping(t)}async confirmMigration(e){return F({initialValue:!0,message:`Migrate ${e} changeset(s) to stones?`})}async createStones(e,t){let n=K();n.start("Creating stones...");let r=new $(e.config),i=[];for(let s of t){let o=this.parser.toStoneData(s),a=await r.create(o);i.push(a.id)}return n.stop(`Created ${c.bold(String(i.length))} stone(s)`),i}async applyConfigMigration(e,t){if(!t)return;let n=K();n.start("Migrating config..."),this.migrateConfig(e,t),n.stop("Config migrated")}displaySuccess(e){let t=e.map((n)=>` ${c.dim("-")} ${n}`).join(`
|
|
181
|
+
`);N(`${t}
|
|
202
182
|
|
|
203
|
-
`)}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
`,
|
|
209
|
-
|
|
210
|
-
`
|
|
211
|
-
|
|
212
|
-
`).
|
|
213
|
-
`)),await
|
|
214
|
-
`)}
|
|
215
|
-
`)):""}${
|
|
216
|
-
|
|
217
|
-
`)
|
|
218
|
-
|
|
219
|
-
${
|
|
220
|
-
`)
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
${
|
|
224
|
-
`)}
|
|
225
|
-
`)),t
|
|
226
|
-
`)
|
|
227
|
-
|
|
183
|
+
Run ${c.green(`${A} stone list`)} to view stones
|
|
184
|
+
Run ${c.green(`${A} preview`)} to see what will be released`,c.green("Migration complete"))}displayChangesets(e){for(let t of e){let n=Object.entries(t.packages).map(([i,s])=>{let o=s==="major"?c.red:s==="minor"?c.yellow:c.green;return`${i} ${c.dim("(")}${o(s)}${c.dim(")")}`}).join(", "),r=t.summary.length>60?`${t.summary.slice(0,60)}...`:t.summary;l.info(`${c.dim(t.filename)}
|
|
185
|
+
${c.dim("Packages:")} ${n}
|
|
186
|
+
${c.dim("Message:")} ${r||c.dim("(empty)")}`)}}displayConfigMapping(e){let t=[{category:"migrate",check:()=>(e.ignore?.length??0)>0,format:()=>`ignore: ${e.ignore?.join(", ")}`},{category:"migrate",check:()=>e.commit===!0,format:()=>"commit: enabled (will enable commit & push)"},{category:"migrate",check:()=>e.access==="public",format:()=>"access: public (will enable npm publishing)"},{category:"migrate",check:()=>e.changelog===!1,format:()=>"changelog: disabled"},{category:"info",check:()=>!!e.baseBranch&&e.baseBranch!=="master",format:()=>`baseBranch: ${e.baseBranch}`},{category:"info",check:()=>!!e.updateInternalDependencies,format:()=>`updateInternalDependencies: ${e.updateInternalDependencies}`},{category:"info",check:()=>Array.isArray(e.changelog)||typeof e.changelog==="string",format:()=>`changelog: ${Array.isArray(e.changelog)?e.changelog[0]:e.changelog}`},{category:"info",check:()=>Array.isArray(e.commit)||typeof e.commit==="string",format:()=>`commit: ${Array.isArray(e.commit)?e.commit[0]:e.commit}`},{category:"unsupported",check:()=>(e.linked?.length??0)>0,format:()=>`linked: ${e.linked?.length} group(s)`},{category:"unsupported",check:()=>(e.fixed?.length??0)>0,format:()=>`fixed: ${e.fixed?.length} group(s)`}],n={info:{color:c.blue,items:[],title:"Info (not migrated)"},migrate:{color:c.green,items:[],title:"Will migrate"},unsupported:{color:c.yellow,items:[],title:"Not yet supported"}};for(let r of t)if(r.check())n[r.category].items.push(c.dim(r.format()));for(let r of[n.migrate,n.info,n.unsupported])if(r.items.length>0)N(r.items.join(`
|
|
187
|
+
`),r.color(r.title))}migrateConfig(e,t){if(t.ignore?.length){let n=e.config.get("ignore")??[],r=[...new Set([...n,...t.ignore])];e.config.set("ignore",r)}if(t.commit===!0){let n=e.config.get("commit")??{},r=e.config.get("release")??{};e.config.set("commit",{...n,author:n.author??"Sisyphus"}),e.config.set("release",{...r,push:!0})}if(t.access==="public"){let n=e.config.get("release")??{};e.config.set("release",{...n,npm:!0})}if(t.changelog===!1){let n=e.config.get("changelog")??{};e.config.set("changelog",{...n,generate:!1})}}}var Hr=100,ro=D({bump:{alias:"b",description:"Explicit bump type (major/minor/patch)",type:"string"},dryRun:{alias:"d",default:!1,description:"Preview without writing",type:"boolean"},message:{alias:"m",description:"Override stone message",type:"string"},packages:{alias:"p",description:"Filter packages (comma-separated)",type:"string"},url:{alias:"u",description:"PR URL",type:"string"},yes:{alias:"y",default:!1,description:"Skip confirmations",type:"boolean"}});class un extends I{name="pr";description="Create a stone from a Pull Request";args=ro;prompts=!0;async execute(e){let n=await new on(e.config).analyze(e.args.url);this.displayPrSummary(n.pr);let r=this.shouldSkipPr(e,n.pr);if(r){l.info(c.dim(`Skipping: ${r}`));return}if(n.packages.size===0)throw new d("No packages affected by this PR","The PR only modifies root files or files outside packages");let i=await this.determineBumpType(e,n.suggestedBump,n.pr.labels),s=await this.determinePackages(e,n.packages);if(s.length===0)throw new d("No packages selected");let{packages:o}=await S.scan({single:e.config.get("single")}),a=`[#${n.pr.number}](${n.pr.url})`,g=e.args.message??`${n.pr.title} (${a})`,m=n.pr.body||void 0,u=this.buildStoneData({allPackages:o,bump:i,commits:n.commits,description:m,message:g,packages:s});if(this.logPreview(u,e.args.dryRun),e.args.dryRun)return;if(!e.args.yes&&e.interactive){if(!await F({initialValue:!0,message:"Create this stone?"}))return}let y=await new $(e.config).create(u);N(`Run ${c.green(`${A} roll`)} to release packages
|
|
188
|
+
or create another stone with ${c.green(`${A} version`)}`,`Stone ${c.bold(y.id)} ${c.green("created")}`)}displayPrSummary(e){if(l.info(`PR #${c.bold(String(e.number))}: ${e.title}`),l.info(`${c.dim("Author:")} ${e.author}`),l.info(`${c.dim("Branch:")} ${e.branch}`),e.labels.length>0)l.info(`${c.dim("Labels:")} ${e.labels.map((t)=>c.cyan(t)).join(", ")}`)}shouldSkipPr(e,t){let n=e.config.get("pr").skip;for(let r of t.labels)if(n.labels.some((i)=>i.toLowerCase()===r.toLowerCase()))return`label "${r}" is in skip list`;if(n.authors.some((r)=>r.toLowerCase()===t.author.toLowerCase()))return`author "${t.author}" is in skip list`;for(let r of n.titlePatterns)try{if(new RegExp(r,"i").test(t.title))return`title matches skip pattern "${r}"`}catch{l.warn(c.yellow(`Invalid regex pattern in pr.skip.titlePatterns: "${r}"`))}return null}async determineBumpType(e,t,n){if(e.args.bump){if(!Lr(e.args.bump))throw new d(`Invalid bump type: ${e.args.bump}`,"Use major, minor, or patch");return e.args.bump}if(t)return l.info(`${c.dim("Detected bump:")} ${c.bold(t)} (from ${this.getBumpSource(t,n,e)})`),t;if(e.args.yes)throw new d("Cannot determine bump type automatically","Add a label to the PR or use --bump to specify explicitly");if(!e.interactive)throw new d("Cannot determine bump type","Use --bump to specify explicitly");return ye({message:"What type of change is this?",options:[{label:"patch - Bug fixes, minor changes",value:"patch"},{label:"minor - New features (backwards compatible)",value:"minor"},{label:"major - Breaking changes",value:"major"}]})}getBumpSource(e,t,n){let r=n.config.get("pr").labelMapping;for(let i of t){let s=i.toLowerCase();for(let[o,a]of Object.entries(r))if(s===o.toLowerCase()&&a===e)return`label: ${i}`}return"title"}async determinePackages(e,t){let n=Array.from(t);if(e.args.packages){let r=e.args.packages.split(",").map((s)=>s.trim()).filter(Boolean),i=r.filter((s)=>!t.has(s));if(i.length>0)throw new d(`Packages not affected by this PR: ${i.join(", ")}`,`Affected packages: ${n.join(", ")}`);return r}if(n.length===1||e.args.yes||!e.interactive)return l.info(`${c.dim("Affected packages:")} ${n.map((r)=>c.bold(r)).join(", ")}`),n;return ce({initialValues:n,message:"Select packages to include",options:n.map((r)=>({label:r,value:r})),required:!0})}buildStoneData(e){let{allPackages:t,bump:n,commits:r,description:i,message:s,packages:o}=e,a={commits:r,description:i,message:s};if(n==="major")a.major=o;else if(n==="minor")a.minor=o;else a.patch=o;return a.dependency=J(Le(o,t)),a}logPreview(e,t){let n=[];if(t)n.push(c.bold(c.yellow("[dry-run]")));if(n.push(`${c.dim("Stone:")} ${c.bold(e.message)}`),e.major?.length)n.push(` ${c.red("major")}: ${e.major.join(", ")}`);if(e.minor?.length)n.push(` ${c.yellow("minor")}: ${e.minor.join(", ")}`);if(e.patch?.length)n.push(` ${c.green("patch")}: ${e.patch.join(", ")}`);if(e.commits?.length)n.push(` ${c.dim(`${e.commits.length} commit(s)`)}`);if(e.description){let r=e.description.length>Hr?`${e.description.slice(0,Hr)}...`:e.description;n.push(` ${c.dim("Description:")} ${r}`)}l.step(n.join(`
|
|
189
|
+
`))}}var io=D({changelog:{alias:"c",description:"Generate changelogs",type:"boolean"},createRelease:{alias:"r",description:"Create a release on git provider",type:"boolean"},dryRun:{alias:"d",default:!1,description:"Preview without making changes",type:"boolean"},noCommit:{default:!1,description:"Skip creating release commit",type:"boolean"},npm:{alias:"n",description:"Publish to NPM",type:"boolean"},preview:{default:!1,description:"Preview changelogs then prompt to delete",type:"boolean"},publishOnly:{default:!1,description:"Publish from currentRelease (no file changes)",type:"boolean"},push:{alias:"p",description:"Push commits and tags to remote",type:"boolean"},tags:{alias:"t",description:"Create git tags",type:"boolean"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class hn extends I{name="roll";description="Execute a release from pending stones";args=io;async execute(e){if(e.args.publishOnly){await this.executePublishOnly(e);return}let t=this.resolveOptions(e),r=await new $(e.config).list();if(r.length===0)throw new d("No pending stones found",`Create a stone with ${c.green(`${A} version`)} first`);let{packages:i}=await S.scan({single:e.config.get("single")}),s=R.mergeAll(r),o=ee.applyStone(s,i);if(o.length===0)throw new d("No packages to update","Stones don't reference any known packages");if(e.args.preview){await this.previewChangelogs(e,r,o);return}if(this.printPreview(s,o,t),!t.dryRun&&!e.args.yes&&e.interactive){if(!await F({initialValue:!0,message:"Proceed with release?"}))return}if(t.dryRun){l.info(c.yellow("Dry run complete - no changes made"));return}await this.executeRelease(e,s,o,r,t)}async previewChangelogs(e,t,n){let r=e.config.get("changelog"),i=new we(r),s=K();s.start("Generating changelog preview..."),await i.generate(t,n),s.stop("Changelog preview generated");let o=n.map((g)=>c.dim(` ${g.name}/CHANGELOG.md`)).join(`
|
|
190
|
+
`);if(l.info(`
|
|
191
|
+
Preview files created:
|
|
192
|
+
${o}`),r.root)l.info(c.dim(" CHANGELOG.md (root)"));if(l.info(""),await F({initialValue:!0,message:"Revert changes?"}))await i.rollback(),l.info(c.dim("Changes reverted"));else l.info(c.yellow("Changes kept"))}resolveOptions(e){let t=e.config.get("release"),n=e.config.get("changelog"),r=!e.args.noCommit;return{changelog:e.args.changelog??n.generate,commit:r,createRelease:r?e.args.createRelease??t.createRelease:!1,dryRun:e.args.dryRun,npm:e.args.npm??t.npm,push:r?e.args.push??t.push:!1,tags:r?e.args.tags??t.tags:!1}}printPreview(e,t,n){let r=[];if(n.dryRun)r.push(c.bold(c.yellow("[dry-run]")));if(r.push(`${c.bold("Release:")} ${e.message}`),e.tag)r.push(`${c.dim("Tag:")} ${e.tag}`);r.push(""),r.push(c.bold("Packages:"));for(let i of t)r.push(` ${i.label}`);r.push(""),r.push(c.dim(`Changelog: ${n.changelog?"yes":"no"}`)),r.push(c.dim(`Git tags: ${n.tags?"yes":"no"}`)),r.push(c.dim(`NPM publish: ${n.npm?"yes":"no"}`)),r.push(c.dim(`Push to remote: ${n.push?"yes":"no"}`)),r.push(c.dim(`Create release: ${n.createRelease?"yes":"no"}`)),l.step(r.join(`
|
|
193
|
+
`))}async executeRelease(e,t,n,r,i){let s=new kt(e.config,i);await s.preflight(n);let o=K();try{if(o.start("Updating package versions..."),await s.updatePackageVersions(n),o.stop("Package versions updated"),i.changelog)o.start("Generating changelogs..."),await s.generateChangelogs(r,n),o.stop("Changelogs generated");if(await this.deleteStones(e,r),i.commit)o.start("Creating release commit..."),await s.createCommit(t,n),o.stop("Release commit created");if(e.config.set("lastStone",{commit:await this.getCurrentCommit(),date:new Date().toISOString()}),i.tags)o.start("Creating git tags..."),await s.createGitTags(n),o.stop("Git tags created");if(i.npm)o.start("Publishing to NPM..."),await s.publishToNpm(n),o.stop("Published to NPM");if(i.push)o.start("Pushing to remote..."),await s.pushToRemote(),o.stop("Pushed to remote");if(i.createRelease)o.start("Creating release..."),await s.createGitRelease(r,n),o.stop("Release created");N(`Released ${c.bold(String(n.length))} package(s)
|
|
194
|
+
Run ${c.green(`${A} check`)} to verify`,c.green("Release complete"))}catch(a){o.error("Release failed, rolling back...");try{await s.rollback()}finally{await this.restoreStones(e,r)}throw a}}async deleteStones(e,t){let n=new $(e.config);for(let r of t)await n.delete(r.id)}async restoreStones(e,t){let n=new $(e.config);for(let r of t)await n.save(r)}async getCurrentCommit(){try{return(await Bun.$`git rev-parse HEAD`.quiet()).stdout.toString().trim()}catch{return""}}async executePublishOnly(e){let t=e.config.get("currentRelease");if(!t)throw new d("No currentRelease found in config","Run `sis actions release-pr` first to prepare a release");let n=Object.entries(t.packages);if(n.length===0)throw new d("No packages in currentRelease","The release config appears to be empty");let{packages:r}=await S.scan({single:e.config.get("single")}),i=[];for(let[a,{oldVersion:g,newVersion:m}]of n){let u=r.get(a);if(u)i.push(u.withVersions(g,m))}if(i.length===0)throw new d("No matching packages found","Packages in currentRelease don't exist in workspace");l.info(c.bold("Publish-only mode")),l.info(c.dim(`Timestamp: ${t.timestamp}`)),l.info(c.dim(`Stones: ${t.stoneIds.join(", ")}`)),l.info(""),l.info(c.bold("Packages to publish:"));for(let a of i)l.info(` ${a.name}@${a.newVersion??a.version}`);l.info("");let s=e.config.get("release"),o={createRelease:e.args.createRelease??s.createRelease,dryRun:e.args.dryRun,npm:e.args.npm??s.npm,tags:e.args.tags??s.tags};if(o.dryRun){l.info(c.yellow("[dry-run] Would publish packages"));return}if(!e.args.yes&&e.interactive){if(!await F({initialValue:!0,message:"Proceed with publishing?"}))return}await this.executePublish(e,i,t,o)}async executePublish(e,t,n,r){let i=new kt(e.config,{changelog:!1,createRelease:r.createRelease,dryRun:r.dryRun,npm:r.npm,push:!1,tags:r.tags}),s=K();try{if(r.tags)s.start("Creating and pushing git tags..."),await i.createGitTags(t),await i.pushTags(),s.stop("Git tags pushed");if(r.npm)s.start("Publishing to NPM..."),await i.publishToNpm(t),s.stop("Published to NPM");if(r.createRelease){s.start("Creating release...");let a=await new $(e.config).getReleasedStones(n.timestamp),g=a.length>0?a:[this.createFallbackStone(t)];await i.createGitRelease(g,t),s.stop("Release created")}e.config.set("lastStone",{commit:await this.getCurrentCommit(),date:new Date().toISOString()}),N(`Published ${c.bold(String(t.length))} package(s)
|
|
195
|
+
Run ${c.green(`${A} check`)} to verify`,c.green("Publish complete"))}catch(o){throw s.error("Publish failed"),o}}createFallbackStone(e){let t=`Release ${e.map((n)=>`${n.name}@${n.newVersion??n.version}`).join(", ")}`;return R.create({message:t},0)}}class $e extends I{async resolveStone(e,t,n){if(n)return this.promptStone(t);if(!e)throw new d("Stone ID is required",`Usage: ${A} stone ${this.name} <id>`);let r=await t.get(e);if(!r)throw new d(`Stone '${e}' not found`,`Run '${A} stone list' to see available stones`);return r}async promptStone(e){let t=await e.list();if(t.length===0)throw new d("No pending stones found");let n=t.map((r)=>({label:`${r.id} - ${r.message}`,value:r}));return ye({message:`Select a stone to ${this.name}`,options:n})}}var so=_({id:{description:"Stone ID to delete"}});class fn extends $e{name="delete";description="Delete a pending stone";positionals=so;prompts=!0;async execute(e){let t=new $(e.config),n=await this.resolveStone(e.positionals.id,t,e.interactive);if(e.interactive){if(!await F({initialValue:!1,message:`Delete stone '${n.id}'?`}))return}await t.delete(n.id),l.success(`Stone '${c.bold(n.id)}' deleted`)}}var oo=_({id:{description:"Stone ID to edit"}}),ao=D({message:{alias:"m",description:"New commit message",type:"string"}});class dn extends $e{name="edit";description="Edit a pending stone";positionals=oo;args=ao;prompts=!0;async execute(e){let t=new $(e.config),n=await this.resolveStone(e.positionals.id,t,e.interactive),r=await this.resolveMessage(e,n.message),i=n.withMessage(r);await t.save(i),l.success(`Updated commit message for stone '${c.bold(n.id)}'`)}async resolveMessage(e,t){if(e.args.message)return e.args.message;if(!e.interactive)throw new d("--message is required in non-interactive mode");return Z({initialValue:t,message:"Commit message",placeholder:t})}}var co=D({json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"},verbose:{alias:"v",default:!1,description:"Show detailed info",type:"boolean"}});class yn extends I{name="list";description="List all pending stones";args=co;async execute(e){let t=new $(e.config),n=await t.list();if(n.length===0){this.printEmpty(e.args.json);return}if(e.args.json)this.printJson(n,t);else this.printFormatted(n,e.args.verbose)}printEmpty(e){if(e)console.log(JSON.stringify([]));else l.info("No pending stones found")}printJson(e,t){let n=e.map((r)=>({path:t.getFilePath(r.id),...r.toJson()}));console.log(JSON.stringify(n,null,2))}printFormatted(e,t){let n=`Found ${c.bold(String(e.length))} pending stone${e.length>1?"s":""}`,r=e.map((i)=>this.formatStone(i,t)).join(`
|
|
196
|
+
|
|
197
|
+
`);l.info(`${n}
|
|
198
|
+
|
|
199
|
+
${r}`)}formatStone(e,t){let n=[];if(n.push(`${c.dim("-")} ${c.bold(e.id)}`),n.push(` ${c.dim("Message:")} ${e.message}`),e.tag)n.push(` ${c.dim("Tag:")} ${c.cyan(e.tag)}`);if(e.major.length)n.push(` ${c.red("Major:")} ${e.major.join(", ")}`);if(e.minor.length)n.push(` ${c.yellow("Minor:")} ${e.minor.join(", ")}`);if(e.patch.length)n.push(` ${c.green("Patch:")} ${e.patch.join(", ")}`);if(t&&e.description){n.push(` ${c.dim("Description:")}`);for(let r of e.description.split(`
|
|
200
|
+
`))n.push(` ${c.dim(r)}`)}return n.join(`
|
|
201
|
+
`)}}var go=_({ids:{description:"Stone IDs to merge (at least 2)",variadic:!0}}),mo=D({delete:{alias:"d",default:!1,description:"Delete original stones after merge",type:"boolean"},message:{alias:"m",description:"Commit message for merged stone",type:"string"}});class bn extends I{name="merge";description="Merge multiple stones into one";positionals=go;args=mo;prompts=!0;async execute(e){let t=new $(e.config),n=await this.resolveStones(e,t),r=await this.resolveMessage(e),{stone:i,conflicts:s}=R.merge(n,r);if(await t.save(i),await this.resolveDelete(e))await t.deleteMany(n.map((a)=>a.id));this.printResult(i.id,s)}async resolveStones(e,t){let n=await t.list();if(n.length<2)throw new d("Need at least 2 stones to merge");if(e.interactive)return this.promptStones(n);let r=e.positionals.ids;if(r.length<2)throw new d("Need at least 2 stone IDs",`Usage: ${A} stone merge <id1> <id2> [...] -m "message"`);let i=n.filter((s)=>r.includes(s.id));if(i.length!==r.length){let s=i.map((a)=>a.id),o=r.filter((a)=>!s.includes(a));throw new d(`Stone(s) not found: ${o.join(", ")}`)}return i}async resolveMessage(e){if(e.args.message)return e.args.message;if(!e.interactive)throw new d("--message is required in non-interactive mode");return Z({message:"Commit message for merged stone",placeholder:"feat: combined changes"})}async resolveDelete(e){if(e.args.delete)return!0;if(e.interactive)return F({initialValue:!1,message:"Delete original stones?"});return!1}async promptStones(e){let t=e.map((r)=>({label:`${r.id} - ${r.message}`,value:r})),n=await ce({message:"Select stones to merge (at least 2)",options:t,required:!0});if(n.length<2)throw new d("Need to select at least 2 stones");return n}printResult(e,t){if(l.success(`Created merged stone: ${c.bold(e)}`),t.length>0)N(`Resolved ${t.length} package conflict(s) using highest bump type:
|
|
202
|
+
`+t.map((n)=>` ${c.dim("-")} ${n}`).join(`
|
|
203
|
+
`),c.yellow("Conflicts resolved"))}}var po=40,lo=_({id:{description:"Stone ID to display"}}),uo=D({json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}});class Pn extends $e{name="show";description="Show details of a specific stone";positionals=lo;args=uo;prompts=!0;async execute(e){let t=new $(e.config),n=await this.resolveStone(e.positionals.id,t,e.interactive);this.printStone(n,t,e.args.json)}printStone(e,t,n){if(n)console.log(JSON.stringify({path:t.getFilePath(e.id),...e.toJson()},null,2));else this.printFormatted(e,t)}printFormatted(e,t){let n=[];if(n.push(c.bold(`Stone: ${e.id}`)),n.push(c.dim(`Path: ${t.getFilePath(e.id)}`)),n.push(c.dim("-".repeat(po))),n.push(""),n.push(`${c.dim("Message:")} ${e.message}`),e.tag)n.push(`${c.dim("Tag:")} ${c.cyan(e.tag)}`);if(e.description)n.push(`${c.dim("Description:")} ${e.description}`);n.push("");let r=[{bump:"major",packages:e.major},{bump:"minor",packages:e.minor},{bump:"patch",packages:e.patch},{bump:"dependency",packages:e.dependency},{bump:"snapshot",packages:e.snapshot}];for(let{bump:i,packages:s}of r)if(s.length>0){let o=Ee[i];n.push(`${o(i)}: ${s.join(", ")}`)}l.info(n.join(`
|
|
204
|
+
`))}}class wn extends I{name="stone";description="Manage version stones";init(){this.registerSubcommands([new yn,new Pn,new fn,new dn,new bn])}}var ho=_({message:{description:"Stone message (commit message)"},description:{description:"Stone description (optional details)"}}),fo=D({dryRun:{alias:"d",default:!1,description:"Preview without writing files",type:"boolean"},filter:{alias:"f",description:"Filter packages by name",type:"string"},fromCommits:{default:!1,description:"Generate stones from conventional commits",type:"boolean"},major:{alias:"M",description:"Packages for major bump (comma-separated)",type:"string"},minor:{alias:"m",description:"Packages for minor bump (comma-separated)",type:"string"},patch:{alias:"p",description:"Packages for patch bump (comma-separated)",type:"string"},tag:{alias:"t",description:"Prerelease tag (e.g. beta, alpha)",type:"string"},yes:{alias:"y",default:!1,description:"Skip confirmation prompts",type:"boolean"}});class vn extends I{name="version";description="Create a new version stone";positionals=ho;args=fo;prompts=!0;async execute(e){if(e.args.fromCommits)await this.executeFromCommits(e);else if(e.interactive)await this.executeInteractive(e);else await this.executeDirect(e)}async executeInteractive(e){let{packages:t,packageNames:n}=await S.scan({single:e.config.get("single")});if(n.length===0)throw new d("No packages found matching the criteria");let r=await this.selectPackagesInteractive(t,n),i=await this.promptMessage(),s=await this.promptDescription(),o=this.buildStoneData({description:s,message:i,packages:t,selection:r});await this.createStone(e,o,t)}async executeDirect(e){let t=this.parsePackageArgs(e.args);if(!e.positionals.message)throw new d("Message positional is required in non-interactive mode");let{packages:n}=await S.scan({filter:e.args.filter,single:e.config.get("single")}),r=this.validatePackages(t,n);if(r.length>0)throw new d(`Unknown packages: ${r.join(", ")}`);let i=this.buildStoneData({description:e.positionals.description,message:e.positionals.message,packages:n,selection:t,tag:e.args.tag});await this.createStone(e,i,n)}parsePackageArgs(e){let t=(i)=>i?.split(",").map((s)=>s.trim()).filter(Boolean)??[],n={major:t(e.major),minor:t(e.minor),patch:t(e.patch)};if(!(n.major.length>0||n.minor.length>0||n.patch.length>0))throw new d("At least one of --major (-M), --minor (-m), or --patch (-p) is required");return n}validatePackages(e,t){return[...e.major,...e.minor,...e.patch].filter((r)=>!t.has(r))}async executeFromCommits(e){let n=await new Ce(e.config).analyze({filter:e.args.filter,single:e.config.get("single")});if(n.length===0){l.info("No conventional commits found since last release");return}let{packages:r}=await S.scan({filter:e.args.filter,single:e.config.get("single")});l.info(`Found ${c.bold(String(n.length))} commit group(s) to process`);let i=new $(e.config),s=0;for(let o of n){let a=Ce.buildStoneData(o,r,e.args.tag);if(e.args.dryRun)this.logDryRunStone(a);else{let g=await i.create(a);s++,l.success(`Created stone: ${c.bold(g.id)}`)}}if(!e.args.dryRun&&s>0)N(`Created ${c.bold(String(s))} stone(s) from commits.
|
|
205
|
+
Run ${c.green(`${A} preview`)} to see what will be released.`,c.green("Success"))}async selectPackagesInteractive(e,t){let n=[],r={major:[],minor:[],patch:[]};for(let i of["major","minor","patch"]){let s=t.filter((a)=>!n.includes(a));if(s.length===0)break;let o=await this.promptPackages(i,s,e);if(n.push(...o),i==="major")r.major=o;else if(i==="minor")r.minor=o;else r.patch=o}if(n.length===0)throw new d("No packages selected");return r}async promptPackages(e,t,n){let r=Ee[e],i=t.map((s)=>{let o=n.get(s);return{label:o?o.withBump(e).label:s,value:s}});return ce({message:`Select packages for ${c.bold(r(e))} bump`,options:i,required:!1})}async promptMessage(){return Z({message:"Stone message (used as commit message)",placeholder:"feat: add new feature",validate:(e)=>e?.trim()?void 0:"Message is required"})}async promptDescription(){return(await Z({message:"Description (optional, press enter to skip)",placeholder:"Additional details about this change..."}))?.trim()||void 0}buildStoneData(e){let{selection:t,message:n,packages:r,tag:i,description:s}=e,o=[...t.major,...t.minor,...t.patch],a=Le(o,r);return{dependency:J(a),description:s,major:J(t.major),message:n,minor:J(t.minor),patch:J(t.patch),tag:i}}async createStone(e,t,n){let r=new $(e.config);if(this.logPreview(t,n,e.args.dryRun),e.args.dryRun)return;if(!e.args.yes&&e.interactive){if(!await F({initialValue:!0,message:"Create this stone?"}))return}let i=await r.create(t);N(`Run ${c.green(`${A} roll`)} to release packages
|
|
206
|
+
or create another stone with ${c.green(`${A} version`)}`,`Stone ${c.bold(i.id)} ${c.green("created")}`)}logPreview(e,t,n){let r=[];if(n)r.push(c.bold(c.yellow("[dry-run]")));if(r.push(`${c.dim("Stone:")} ${c.bold(e.message)}`),e.tag)r.push(`${c.dim("Tag:")} ${e.tag}`);let i=[{bump:"major",names:e.major},{bump:"minor",names:e.minor},{bump:"patch",names:e.patch},{bump:"dependency",names:e.dependency}];for(let{bump:s,names:o}of i){if(!o?.length)continue;for(let a of o){let g=t.get(a);if(g)r.push(` ${g.withBump(s,e.tag).label}`)}}l.step(r.join(`
|
|
207
|
+
`))}logDryRunStone(e){let t=[c.bold(c.yellow("[dry-run]")),`Stone: ${e.message}`];if(e.major?.length)t.push(` Major: ${e.major.join(", ")}`);if(e.minor?.length)t.push(` Minor: ${e.minor.join(", ")}`);if(e.patch?.length)t.push(` Patch: ${e.patch.join(", ")}`);if(e.dependency?.length)t.push(` Dependency: ${e.dependency.join(", ")}`);if(e.description)t.push(` ${c.dim("Commits:")}
|
|
208
|
+
${c.dim(e.description)}`);l.info(t.join(`
|
|
209
|
+
`))}}class Wr extends zt{constructor(){super(new Yt(`${lt}/${Rr}`,Fe),{bin:A,clearOnStart:!0,exitLabel:"Give Up",goodbyeMessage:"The boulder rolls back down...",name:"SISYPHUS",promptMessage:"Choose your boulder:",version:yr})}init(){this.registerCommands([new gn,new mn,new pn,new ln,new un,new hn,new wn,new vn])}}var yo=new Wr;yo.run();
|