@r5n/atlas 0.6.4 → 0.6.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +36 -36
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,60 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
`),u=!1;for(let h=0;h<c.length;h++){let
|
|
5
|
-
`){if(r)s+=
|
|
6
|
-
`){if(i&&
|
|
7
|
-
`)}var N=
|
|
3
|
+
var Fn=Object.create;var{getPrototypeOf:Mn,defineProperty:$e,getOwnPropertyNames:Nn}=Object;var ye=Object.prototype.hasOwnProperty;function Ln(t){return this[t]}var jn,Vn,be=(t,e,n)=>{var s=t!=null&&typeof t==="object";if(s){var i=e?jn??=new WeakMap:Vn??=new WeakMap,r=i.get(t);if(r)return r}n=t!=null?Fn(Mn(t)):{};let o=e||!t||!t.__esModule||!ye.call(t,"default")?$e(n,"default",{value:t,enumerable:!0}):n;if(t&&typeof t==="object"||typeof t==="function"){for(let a of Nn(t))if(!ye.call(o,a))$e(o,a,{get:Ln.bind(t,a),enumerable:!0})}if(s)i.set(t,o);return o};var Un=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Vt=Un(function(dr,De){var jt={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},es={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},ns={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?jt.up():"");if(t)e+=jt.left;return e}};De.exports={cursor:jt,scroll:es,erase:ns,beep:"\x07"}});import{join as Zi}from"path";class W extends Error{constructor(t="Operation cancelled"){super(t)}}class g extends Error{hint;exitCode;constructor(t,e,n=1){super(t);this.hint=e;this.exitCode=n}}import{stdout as Fe,stdin as ss}from"process";import is from"readline";var ve=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let n=0;t.lastIndex=0;while(t.test(e))n+=1;return e.length-n}})(),we=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,xe=(t)=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var Gn=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Hn=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ce=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Bn=/\t{1,1000}/y,Se=/[\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,Wn=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Jn=/\p{M}+/gu,Kn={limit:1/0,ellipsis:""},Ae=(t,e={},n={})=>{let s=e.limit??1/0,i=e.ellipsis??"",r=e?.ellipsisWidth??(i?Ae(i,Kn,n).width:0),o=0,a=n.controlWidth??0,l=n.tabWidth??8,c=n.emojiWidth??2,u=2,h=n.regularWidth??1,f=n.wideWidth??2,m=[[Wn,h],[Gn,0],[Hn,a],[Bn,l],[Se,c],[Ce,f]],d=0,b=0,E=t.length,_=0,x=!1,P=E,R=Math.max(0,s-r),C=0,O=0,T=0,p=0;t:while(!0){if(O>C||b>=E&&b>d){let S=t.slice(C,O)||t.slice(d,b);_=0;for(let D of S.replaceAll(Jn,"")){let F=D.codePointAt(0)||0;if(we(F))p=2;else if(xe(F))p=f;else p=h;if(T+p>R)P=Math.min(P,Math.max(C,d)+_);if(T+p>s){x=!0;break t}_+=D.length,T+=p}C=O=0}if(b>=E)break t;for(let S=0,D=m.length;S<D;S++){let[F,ge]=m[S];if(F.lastIndex=b,F.test(t)){if(_=F===Ce?ve(t.slice(b,F.lastIndex)):F===Se?1:F.lastIndex-b,p=_*ge,T+p>R)P=Math.min(P,b+Math.floor((R-T)/ge));if(T+p>s){x=!0;break t}T+=p,C=d,O=b,b=d=F.lastIndex;continue t}}b+=1}return{width:x?R:T,index:x?P:E,truncated:x,ellipsed:x&&s>=r}},Ee=Ae;var qn={limit:1/0,ellipsis:"",ellipsisWidth:0},Xn=(t,e={})=>Ee(t,qn,e).width,U=Xn;var lt="\x1B",Oe="\x9B",zn=39,Nt="\x07",Pe="[",Yn="]",ke="m",Lt=`${Yn}8;;`,Ie=new RegExp(`(?:\\${Pe}(?<code>\\d+)m|\\${Lt}(?<uri>.*)${Nt})`,"y"),_e=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},Te=(t)=>`${lt}${Pe}${t}${ke}`,Re=(t)=>`${lt}${Lt}${t}${Nt}`,Mt=(t,e,n)=>{let s=e[Symbol.iterator](),i=!1,r=!1,o=t.at(-1),a=o===void 0?0:U(o),l=s.next(),c=s.next(),u=0;while(!l.done){let h=l.value,f=U(h);if(a+f<=n)t[t.length-1]+=h;else t.push(h),a=0;if(h===lt||h===Oe)i=!0,r=e.startsWith(Lt,u+1);if(i){if(r){if(h===Nt)i=!1,r=!1}else if(h===ke)i=!1}else if(a+=f,a===n&&!c.done)t.push(""),a=0;l=c,c=s.next(),u+=h.length}if(o=t.at(-1),!a&&o!==void 0&&o.length&&t.length>1)t[t.length-2]+=t.pop()},Qn=(t)=>{let e=t.split(" "),n=e.length;while(n){if(U(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},Zn=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let s="",i,r,o=t.split(" "),a=[""],l=0;for(let h=0;h<o.length;h++){let f=o[h];if(n.trim!==!1){let d=a.at(-1)??"",b=d.trimStart();if(d.length!==b.length)a[a.length-1]=b,l=U(b)}if(h!==0){if(l>=e&&(n.wordWrap===!1||n.trim===!1))a.push(""),l=0;if(l||n.trim===!1)a[a.length-1]+=" ",l++}let m=U(f);if(n.hard&&m>e){let d=e-l,b=1+Math.floor((m-d-1)/e);if(Math.floor((m-1)/e)<b)a.push("");Mt(a,f,e),l=U(a.at(-1)??"");continue}if(l+m>e&&l&&m){if(n.wordWrap===!1&&l<e){Mt(a,f,e),l=U(a.at(-1)??"");continue}a.push(""),l=0}if(l+m>e&&n.wordWrap===!1){Mt(a,f,e),l=U(a.at(-1)??"");continue}a[a.length-1]+=f,l+=m}if(n.trim!==!1)a=a.map((h)=>Qn(h));let c=a.join(`
|
|
4
|
+
`),u=!1;for(let h=0;h<c.length;h++){let f=c[h];if(s+=f,!u){if(u=f>="\uD800"&&f<="\uDBFF",u)continue}else u=!1;if(f===lt||f===Oe){Ie.lastIndex=h+1;let d=Ie.exec(c)?.groups;if(d?.code!==void 0){let b=Number.parseFloat(d.code);i=b===zn?void 0:b}else if(d?.uri!==void 0)r=d.uri.length===0?void 0:d.uri}if(c[h+1]===`
|
|
5
|
+
`){if(r)s+=Re("");let m=i?_e(i):void 0;if(i&&m)s+=Te(m)}else if(f===`
|
|
6
|
+
`){if(i&&_e(i))s+=Te(i);if(r)s+=Re(r)}}return s},ts=/\r?\n/;function Q(t,e,n){return String(t).normalize().split(ts).map((s)=>Zn(s,e,n)).join(`
|
|
7
|
+
`)}var N=be(Vt(),1);function dt(t,e,n){if(!n.some((o)=>!o.disabled))return t;let s=t+e,i=Math.max(n.length-1,0),r=s<0?i:s>i?0:s;return n[r]?.disabled?dt(r,e<0?-1:1,n):r}var rs=["up","down","left","right","space","enter","cancel"],os=["January","February","March","April","May","June","July","August","September","October","November","December"],G={actions:new Set(rs),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:[...os],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function Me(t,e){if(typeof t=="string")return G.aliases.get(t)===e;for(let n of t)if(n!==void 0&&Me(n,e))return!0;return!1}function as(t,e){if(t===e)return;let n=t.split(`
|
|
8
8
|
`),s=e.split(`
|
|
9
|
-
`),i=Math.max(n.length,s.length),r=[];for(let o=0;o<i;o++)n[o]!==s[o]&&r.push(o);return{lines:r,numLinesBefore:n.length,numLinesAfter:s.length,numLines:i}}var
|
|
9
|
+
`),i=Math.max(n.length,s.length),r=[];for(let o=0;o<i;o++)n[o]!==s[o]&&r.push(o);return{lines:r,numLinesBefore:n.length,numLinesAfter:s.length,numLines:i}}var pr=globalThis.process.platform.startsWith("win"),Ut=Symbol("clack:cancel");function ht(t){return t===Ut}function ut(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var Gt=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,Ht=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function ft(t,e,n,s=n,i=n,r){let o=Gt(t??Fe);return Q(e,o-n.length,{hard:!0,trim:!1}).split(`
|
|
10
10
|
`).map((a,l,c)=>{let u=r?r(a,l):a;return l===0?`${s}${u}`:l===c.length-1?`${i}${u}`:`${n}${u}`}).join(`
|
|
11
|
-
`)}function
|
|
11
|
+
`)}function Ne(t,e){if("~standard"in t){let n=t["~standard"].validate(e);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 t(e)}class Le{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,e=!0){let{input:n=ss,output:s=Fe,render:i,signal:r,...o}=t;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=e,this._abortSignal=r,this.input=n,this.output=s}unsubscribe(){this._subscribers.clear()}setSubscriber(t,e){let n=this._subscribers.get(t)??[];n.push(e),this._subscribers.set(t,n)}on(t,e){this.setSubscriber(t,{cb:e})}once(t,e){this.setSubscriber(t,{cb:e,once:!0})}emit(t,...e){let n=this._subscribers.get(t)??[],s=[];for(let i of n)i.cb(...e),i.once&&s.push(()=>n.splice(n.indexOf(i),1));for(let i of s)i()}prompt(){return new Promise((t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Ut);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=is.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),ut(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(N.cursor.show),this.output.off("resize",this.render),ut(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(N.cursor.show),this.output.off("resize",this.render),ut(this.input,!1),t(Ut)})})}_isActionKey(t,e){return t==="\t"}_shouldSubmit(t,e){return!0}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,e){this.userInput=t??"",this.emit("userInput",this.userInput),e&&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(t,e){if(this._track&&e.name!=="return"&&(e.name&&this._isActionKey(t,e)&&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"),e?.name&&(!this._track&&G.aliases.has(e.name)&&this.emit("cursor",G.aliases.get(e.name)),G.actions.has(e.name)&&this.emit("cursor",e.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t,e),e?.name==="return"&&this._shouldSubmit(t,e)){if(this.opts.validate){let n=Ne(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")}Me([t,e?.name,e?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
12
12
|
`),ut(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Q(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
13
13
|
`).length-1;this.output.write(N.cursor.move(-999,t*-1))}render(){let t=Q(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(N.cursor.hide);else{let e=as(this._prevFrame,t),n=Ht(this.output);if(this.restoreCursor(),e){let s=Math.max(0,e.numLinesAfter-n),i=Math.max(0,e.numLinesBefore-n),r=e.lines.find((o)=>o>=s);if(r===void 0){this._prevFrame=t;return}if(e.lines.length===1){this.output.write(N.cursor.move(0,r-i)),this.output.write(N.erase.lines(1));let o=t.split(`
|
|
14
14
|
`);this.output.write(o[r]),this._prevFrame=t,this.output.write(N.cursor.move(0,o.length-r-1));return}else if(e.lines.length>1){if(s<i)r=s;else{let a=r-i;a>0&&this.output.write(N.cursor.move(0,a))}this.output.write(N.erase.down());let o=t.split(`
|
|
15
15
|
`).slice(r);this.output.write(o.join(`
|
|
16
|
-
`)),this._prevFrame=t;return}}this.output.write(N.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}var je=class extends
|
|
17
|
-
`);E.push(p),_+=p.length}if(_>u){let C=0,O=0,T=_,p=t-x,S=u,D=()=>
|
|
18
|
-
`);if(h.length>0){let[m
|
|
16
|
+
`)),this._prevFrame=t;return}}this.output.write(N.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}}var je=class extends Le{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:i})=>i===e.initialValue),s=n===-1?0:n;this.cursor=this.options[s]?.disabled?dt(s,1,this.options):s,this.changeValue(),this.on("cursor",(i)=>{switch(i){case"left":case"up":this.cursor=dt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=dt(this.cursor,1,this.options);break}this.changeValue()})}};import{styleText as y,stripVTControlCharacters as Rr}from"util";import j from"process";var Ge=be(Vt(),1);function cs(){if(j.platform!=="win32")return j.env.TERM!=="linux";return Boolean(j.env.CI)||Boolean(j.env.WT_SESSION)||Boolean(j.env.TERMINUS_SUBLIME)||j.env.ConEmuTask==="{cmd::Cmder}"||j.env.TERM_PROGRAM==="Terminus-Sublime"||j.env.TERM_PROGRAM==="vscode"||j.env.TERM==="xterm-256color"||j.env.TERM==="alacritty"||j.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var ls=cs();var I=(t,e)=>ls?t:e,us=I("\u25C6","*"),ds=I("\u25A0","x"),hs=I("\u25B2","x"),He=I("\u25C7","o"),fs=I("\u250C","T"),k=I("\u2502","|"),Bt=I("\u2514","\u2014"),Dr=I("\u2510","T"),Fr=I("\u2518","\u2014"),ms=I("\u25CF",">"),Ve=I("\u25CB"," "),Mr=I("\u25FB","[\u2022]"),Nr=I("\u25FC","[+]"),Lr=I("\u25FB","[ ]"),jr=I("\u25AA","\u2022"),Vr=I("\u2500","-"),Ur=I("\u256E","+"),Gr=I("\u251C","+"),Hr=I("\u256F","+"),Br=I("\u2570","+"),Wr=I("\u256D","+"),ps=I("\u25CF","\u2022"),gs=I("\u25C6","*"),$s=I("\u25B2","!"),ys=I("\u25A0","x"),bs=(t)=>{switch(t){case"initial":case"active":return y("cyan",us);case"cancel":return y("red",ds);case"error":return y("yellow",hs);case"submit":return y("green",He)}},vs=(t)=>{switch(t){case"initial":case"active":return y("cyan",k);case"cancel":return y("red",k);case"error":return y("yellow",k);case"submit":return y("green",k)}};function ws(t,e){let n=[`${e?`${y("cyan",k)} `:""}${t.join(" \u2022 ")}`];return e&&n.push(y("cyan",Bt)),n}var Ue=(t,e,n,s,i,r=!1)=>{let o=e,a=0;if(r)for(let l=s-1;l>=n;l--){let c=t[l];if(c&&(o-=c.length),a++,o<=i)break}else for(let l=n;l<s;l++){let c=t[l];if(c&&(o-=c.length),a++,o<=i)break}return{lineCount:o,removals:a}},xs=({cursor:t,options:e,style:n,output:s=process.stdout,maxItems:i=Number.POSITIVE_INFINITY,columnPadding:r=0,rowPadding:o=4})=>{let a=Gt(s)-r,l=Ht(s),c=y("dim","..."),u=Math.max(l-o,0),h=Math.max(Math.min(i,u),5),f=0;t>=h-3&&(f=Math.max(Math.min(t-h+3,e.length-h),0));let m=h<e.length&&f>0,d=h<e.length&&f+h<e.length,b=Math.min(f+h,e.length),E=[],_=0;m&&_++,d&&_++;let x=f+(m?1:0),P=b-(d?1:0);for(let C=x;C<P;C++){let O=e[C],T=O?n(O,C===t):"",p=Q(T,a,{hard:!0,trim:!1}).split(`
|
|
17
|
+
`);E.push(p),_+=p.length}if(_>u){let C=0,O=0,T=_,p=t-x,S=u,D=()=>Ue(E,T,0,p,S),F=()=>Ue(E,T,p+1,E.length,S,!0);m?({lineCount:T,removals:C}=D(),T>S&&(d||(S-=1),{lineCount:T,removals:O}=F())):(d||(S-=1),{lineCount:T,removals:O}=F(),T>S&&(S-=1,{lineCount:T,removals:C}=D())),C>0&&(m=!0,E.splice(0,C)),O>0&&(d=!0,E.splice(E.length-O,O))}let R=[];m&&R.push(c);for(let C of E)for(let O of C)R.push(O);return d&&R.push(c),R};var Jr=[`${y("dim","\u2191/\u2193")} to navigate`,`${y("dim","Space:")} select`,`${y("dim","Enter:")} confirm`];var A={message:(t=[],{symbol:e=y("gray",k),secondarySymbol:n=y("gray",k),output:s=process.stdout,spacing:i=1,withGuide:r}={})=>{let o=[],a=r??G.withGuide,l=a?n:"",c=a?`${e} `:"",u=a?`${n} `:"";for(let f=0;f<i;f++)o.push(l);let h=Array.isArray(t)?t:t.split(`
|
|
18
|
+
`);if(h.length>0){let[f,...m]=h;f.length>0?o.push(`${c}${f}`):o.push(a?e:"");for(let d of m)d.length>0?o.push(`${u}${d}`):o.push(a?n:"")}s.write(`${o.join(`
|
|
19
19
|
`)}
|
|
20
|
-
`)},info:(t,e)=>{A.message(t,{...e,symbol:y("blue",ps)})},success:(t,e)=>{A.message(t,{...e,symbol:y("green",gs)})},step:(t,e)=>{A.message(t,{...e,symbol:y("green",
|
|
20
|
+
`)},info:(t,e)=>{A.message(t,{...e,symbol:y("blue",ps)})},success:(t,e)=>{A.message(t,{...e,symbol:y("green",gs)})},step:(t,e)=>{A.message(t,{...e,symbol:y("green",He)})},warn:(t,e)=>{A.message(t,{...e,symbol:y("yellow",$s)})},warning:(t,e)=>{A.warn(t,e)},error:(t,e)=>{A.message(t,{...e,symbol:y("red",ys)})}};var pt=(t="",e)=>{let n=e?.output??process.stdout,s=e?.withGuide??G.withGuide?`${y("gray",fs)} `:"";n.write(`${s}${t}
|
|
21
21
|
`)},gt=(t="",e)=>{let n=e?.output??process.stdout,s=e?.withGuide??G.withGuide?`${y("gray",k)}
|
|
22
22
|
${y("gray",Bt)} `:"";n.write(`${s}${t}
|
|
23
23
|
|
|
24
|
-
`)};var
|
|
24
|
+
`)};var Kr={light:I("\u2500","-"),heavy:I("\u2501","="),block:I("\u2588","#")};var Cs=[`${y("dim","\u2191/\u2193")} to navigate`,`${y("dim","Enter:")} confirm`],mt=(t,e)=>t.includes(`
|
|
25
25
|
`)?t.split(`
|
|
26
26
|
`).map((n)=>e(n)).join(`
|
|
27
|
-
`):e(t),
|
|
27
|
+
`):e(t),Be=(t)=>{let e=(s,i)=>{if(s===void 0)return"";let r=s.label??String(s.value);switch(i){case"disabled":return`${y("gray",Ve)} ${mt(r,(o)=>y("gray",o))}${s.hint?` ${y("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${mt(r,(o)=>y("dim",o))}`;case"active":return`${y("green",ms)} ${r}${s.hint?` ${y("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${mt(r,(o)=>y(["strikethrough","dim"],o))}`;default:return`${y("dim",Ve)} ${mt(r,(o)=>y("dim",o))}`}},n=t.showInstructions??!0;return new je({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let s=t.withGuide??G.withGuide,i=`${bs(this.state)} `,r=`${vs(this.state)} `,o=ft(t.output,t.message,r,i),a=`${s?`${y("gray",k)}
|
|
28
28
|
`:""}${o}
|
|
29
|
-
`;switch(this.state){case"submit":{let l=s?`${y("gray",k)} `:"",c=
|
|
29
|
+
`;switch(this.state){case"submit":{let l=s?`${y("gray",k)} `:"",c=ft(t.output,e(this.options[this.cursor],"selected"),l);return`${a}${c}`}case"cancel":{let l=s?`${y("gray",k)} `:"",c=ft(t.output,e(this.options[this.cursor],"cancelled"),l);return`${a}${c}${s?`
|
|
30
30
|
${y("gray",k)}`:""}`}default:{let l=s?`${y("cyan",k)} `:"",c=a.split(`
|
|
31
31
|
`).length,u=n?ws(Cs,s):s?[y("cyan",Bt)]:[],h=u.join(`
|
|
32
|
-
`),
|
|
32
|
+
`),f=u.length+1;return`${a}${l}${xs({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:l.length,rowPadding:c+f,style:(m,d)=>e(m,m.disabled?"disabled":d?"active":"inactive")}).join(`
|
|
33
33
|
${l}`)}
|
|
34
34
|
${h}
|
|
35
|
-
`}}}}).prompt()};var
|
|
35
|
+
`}}}}).prompt()};var qr=`${y("gray",k)} `;var As=!process.env.NO_COLOR&&(process.env.FORCE_COLOR||(process.stdout?.isTTY??!1)),Ke=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Es=["bold","dim","italic","underline","reset"],qe={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Is={black:"\x1B[30m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",green:"\x1B[32m",magenta:"\x1B[35m",red:"\x1B[31m",white:"\x1B[37m",yellow:"\x1B[33m"},_s={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"},We={"\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 $t(t){return(e)=>As?`${t}${e}${qe.reset}`:e}function Ts(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<32&&n!==27)return!1}return!0}function Je({bright:t=!1,color:e}){let n=Bun.color(e,"ansi"),s=typeof n==="string"&&n.length>0&&Ts(n)?n:Is[e];if(!s)return"";return t&&s in We?We[s]:s}var Rs=Ke.reduce((t,e)=>{let n=Je({color:e});if(n)t[e]=$t(n);let s=Je({bright:!0,color:e});if(s)t[`${e}Bright`]=$t(s);return t},{}),Os=Es.reduce((t,e)=>(t[e]=$t(qe[e]),t),{}),Ps=Ke.reduce((t,e)=>{let n=_s[e];if(n){let s=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[s]=$t(n)}return t},{}),v={...Rs,...Os,...Ps};function Ns(t){if(ht(t))throw new W;return t}function Ls(t){return t.map((e)=>e.key?`${v.bold(e.key)} ${v.dim(e.text)}`:v.dim(e.text)).join(v.dim(" \xB7 "))}function js(t){A.info(Ls(t))}var Vs={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 Wt(t){return js(Vs.select),Ns(await Be({showInstructions:!1,...t}))}var Us=4;function Z(t,e=0){if(e>=Us)return;let n=[...t instanceof AggregateError?t.errors:[],...t.cause!==void 0?[t.cause]:[]];for(let s of n){if(A.info(v.dim(`caused by: ${s instanceof Error?s.message:String(s)}`)),s instanceof g&&s.hint)A.info(v.dim(` ${s.hint}`));if(s instanceof Error)Z(s,e+1)}}function Jt(t){return t==null?[]:Array.isArray(t)?t:[t]}function Gs(t,e,n,s){var i,r=t[e],o=~s.string.indexOf(e)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~s.boolean.indexOf(e)?n==="false"?!1:n==="true"||(t._.push((i=+n,i*0===0)?i:n),!!n):(i=+n,i*0===0)?i:n;t[e]=r==null?o:Array.isArray(r)?r.concat(o):[r,o]}function rt(t,e){t=t||[],e=e||{};var n,s,i,r,o,a={_:[]},l=0,c=0,u=0,h=t.length;let f=e.alias!==void 0,m=e.unknown!==void 0,d=e.default!==void 0;if(e.alias=e.alias||{},e.string=Jt(e.string),e.boolean=Jt(e.boolean),f)for(n in e.alias){s=e.alias[n]=Jt(e.alias[n]);for(l=0;l<s.length;l++)(e.alias[s[l]]=s.concat(n)).splice(l,1)}for(l=e.boolean.length;l-- >0;){s=e.alias[e.boolean[l]]||[];for(c=s.length;c-- >0;)e.boolean.push(s[c])}for(l=e.string.length;l-- >0;){s=e.alias[e.string[l]]||[];for(c=s.length;c-- >0;)e.string.push(s[c])}if(d){for(n in e.default)if(r=typeof e.default[n],s=e.alias[n]=e.alias[n]||[],e[r]!==void 0){e[r].push(n);for(l=0;l<s.length;l++)e[r].push(s[l])}}let b=m?Object.keys(e.alias):[];for(l=0;l<h;l++){if(i=t[l],i==="--"){a._=a._.concat(t.slice(++l));break}for(c=0;c<i.length;c++)if(i.charCodeAt(c)!==45)break;if(c===0)a._.push(i);else if(i.substring(c,c+3)==="no-"){if(r=i.substring(c+3),m&&!~b.indexOf(r))return e.unknown(i);a[r]=!1}else{for(u=c+1;u<i.length;u++)if(i.charCodeAt(u)===61)break;r=i.substring(c,u),o=i.substring(++u)||(l+1===h||(""+t[l+1]).charCodeAt(0)===45||t[++l]),s=c===2?[r]:r;for(u=0;u<s.length;u++){if(r=s[u],m&&!~b.indexOf(r))return e.unknown("-".repeat(c)+r);Gs(a,r,u+1<s.length||o,e)}}}if(d){for(n in e.default)if(a[n]===void 0)a[n]=e.default[n]}if(f)for(n in a){s=e.alias[n]||[];while(s.length>0)a[s.shift()]=a[n]}return a}var Xe=1,Hs=2;function tt(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Kt(t){let e={alias:{},boolean:[],default:{},string:[]};for(let[n,s]of Object.entries(t)){if(s.type==="boolean")e.boolean.push(n);else e.string.push(n);if(s.alias)e.alias[s.alias]=n;let i=tt(n);if(i!==n)e.alias[i]=n;if(s.default!==void 0)e.default[n]=s.default}return e}function yt(t,e){if(t in e)return`--${tt(t)}`;let n=Object.entries(e).find(([,s])=>s.alias===t)?.[0];if(n)return`--${tt(n)}`;return t.length===Xe?`-${t}`:`--${tt(t)}`}function H(t,e,n){let{alias:s}=Kt(e),i=Object.keys(t).find((r)=>!Object.hasOwn(e,r)&&!Object.hasOwn(s,r));if(i!==void 0)throw new g(`Unknown option: ${yt(i,e)}`,n)}function ze(t,e){for(let[s,i]of Object.entries(t))if(Array.isArray(i))throw new g(`${yt(s,e)} can only be provided once`);let n={...t};for(let[s,i]of Object.entries(e)){if(i.type!=="number")continue;let r=t[s];if(r===void 0)continue;let o=Number(r);if(typeof r==="boolean"||typeof r==="string"&&r.trim().length===0||!Number.isFinite(o)){let a=yt(s,e);throw new g(`Invalid number for ${a}: "${r}"`,`Use ${a}=<number> with a finite numeric value`)}n[s]=o}return n}function qt(t,e){let n=Kt(e);Ye(t,n,e,!0);let s=rt(t,n),i=s._[0],r=i?t.indexOf(i):-1,o=rt(r>=0?t.slice(0,r):t,n),{_:a,...l}=o;H(l,e,"Place command options after the command name");let{_:c,...u}=s,h=Object.fromEntries(Object.entries(u).filter(([m])=>(m in e)||(m in n.alias))),f=ze(h,e);return{command:i,flags:f,restArgs:r>=0?t.slice(r+1):[]}}function Xt(t,e={}){let n=Kt(e),s=Bs(t,n);Ye(s,n,e);let i=rt(s,n),{_:r,...o}=i;return{args:ze(o,e),rawPositionals:r}}function Ye(t,e,n,s=!1){let i=new Set;for(let r of t){if(r==="--")break;let o=r.match(/^-+/)?.[0];if(!o)continue;let a=r.slice(o.length),l=a.split("=",Xe)[0]??"",c=a.startsWith("no-")?[a.slice(3)]:o.length===Hs?[l]:[...l];for(let u of c){let h=Object.hasOwn(e.alias,u)?e.alias[u]??u:u;if(s&&!Object.hasOwn(n,h))continue;if(i.has(h))throw new g(`${yt(h,n)} can only be provided once`);i.add(h)}}}function Bs(t,e){let n=!0;return t.map((s)=>{if(s==="--")n=!1;if(!n)return s;return s.replace(/^--(no-[^=]+)(=.*)?$/,(i,r,o)=>{let a=e.alias[r];return a&&e.boolean.includes(a)?`--${a}${o??""}`:i})})}function zt(t,e){let n={},s=Object.entries(e);for(let[i,[r,o]]of s.entries())n[r]=o.variadic?t.slice(i):t[i];return n}function Qe(t,e){for(let[n,s]of Object.entries(e)){if(!s.required)continue;let i=t[n];if(Array.isArray(i)?i.length===0:!i)return`Missing required argument: <${n}${s.variadic?"...":""}>`}return null}var Ws=(t)=>t,w={arg:v.magenta,cmd:v.cyan,default:v.bold,desc:Ws,flag:v.green,header:(t)=>v.bold(v.yellow(t)),hint:v.dim,name:(t)=>v.bold(v.cyan(t)),placeholder:v.magenta};class Yt{metadata;commands;globalArgs;constructor(t,e,n){this.metadata=t;this.commands=e;this.globalArgs=n}version(){return`${w.name(this.metadata.name)} ${w.hint(this.metadata.version??"0.0.0")}`}global(){let t=[],{name:e,bin:n,version:s,description:i}=this.metadata;if(t.push(`${w.name(e)}${s?` ${w.hint(`v${s}`)}`:""}`),i)t.push(w.desc(i));t.push(""),t.push(w.header("Usage:")),t.push(` ${w.cmd(n)} ${w.placeholder("[command]")} ${w.placeholder("[options]")}`),t.push(""),t.push(w.header("Commands:"));let r=Array.from(this.commands.values()).map((o)=>[` ${w.cmd(o.name)}`,w.desc(o.description)]);return t.push(...this.formatColumns(r)),t.push(""),t.push(w.header("Options:")),t.push(...this.formatArgDefs(this.globalArgs)),t.push(""),t.push(`${w.hint("Run")} ${w.cmd(`${n} <command> --help`)} ${w.hint("for command details.")}`),t.join(`
|
|
36
36
|
`).trimEnd()}command(t,e){let n=[],s=e??this.metadata.bin,i=`${s} ${t.name}`,r=`${w.cmd(s)} ${w.cmd(t.name)}`;n.push(w.name(i)),n.push(w.desc(t.description)),n.push(""),n.push(w.header("Usage:"));let o=this.formatPositionalUsage(t.positionals);if(t.hasSubcommands())n.push(` ${r} ${w.placeholder("<subcommand>")} ${w.placeholder("[options]")}`);else{let c=[r];if(o)c.push(o);c.push(w.placeholder("[options]")),n.push(` ${c.join(" ")}`)}if(t.prompts&&Object.keys(t.positionals).length>0)n.push(` ${w.hint("Omit positional arguments to run interactively.")}`);if(n.push(""),t.hasSubcommands()){n.push(w.header("Subcommands:"));let c=t.getSubcommands().map((u)=>[` ${w.cmd(u.name)}`,w.desc(u.description)]);n.push(...this.formatColumns(c)),n.push("")}if(Object.entries(t.positionals).length>0)n.push(w.header("Arguments:")),n.push(...this.formatPositionalDefs(t.positionals)),n.push("");if(Object.entries(t.args).length>0)n.push(w.header("Options:")),n.push(...this.formatArgDefs(t.args));return n.join(`
|
|
37
|
-
`).trimEnd()}formatPositionalUsage(t){return Object.entries(t).map(([e,n])=>{let s=n.variadic?`${e}...`:e;return n.required?w.arg(`<${s}>`):w.arg(`[${s}]`)}).join(" ")}formatPositionalDefs(t){let e=Object.entries(t).map(([n,s])=>{let i=s.variadic?`${n}...`:n,r=w.desc(s.description??""),o=s.required?"":w.hint(" (optional)");return[` ${w.arg(i)}`,`${r}${o}`]});return this.formatColumns(e)}formatArgDefs(t){let e=[];for(let[n,s]of Object.entries(t)){let i=s.alias?`${w.flag(`-${s.alias}`)}, `:" ",r=s.type==="boolean"?"":` ${w.placeholder(`<${s.type==="number"?"number":"value"}>`)}`,o=`${i}${w.flag(`--${tt(n)}`)}${r}`,a=w.desc(s.description??""),l=this.formatDefault(s),c=l===void 0?"":` (default: ${w.default(l)})`;e.push([` ${o}`,`${a}${c}`])}return this.formatColumns(e)}formatDefault(t){if(typeof t.displayDefault==="string")return t.displayDefault;if(t.default===void 0)return;if(t.type==="boolean"&&t.default===!1)return;if(t.type==="string")return`"${t.default}"`;return String(t.default)}formatColumns(t){if(t.length===0)return[];let e=Math.max(...t.map(([s])=>this.stripAnsi(s).length)),n=2;return t.map(([s,i])=>{let r=e-this.stripAnsi(s).length+n;return`${s}${" ".repeat(r)}${i}`})}stripAnsi(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}}var J=new Uint32Array(65536),Js=(t,e)=>{let n=t.length,s=e.length,i=1<<n-1,r=-1,o=0,a=n,l=n;while(l--)J[t.charCodeAt(l)]|=1<<l;for(l=0;l<s;l++){let c=J[e.charCodeAt(l)],u=c|o;if(c|=(c&r)+r^r,o|=~(c|r),r&=c,o&i)a++;if(r&i)a--;o=o<<1|1,r=r<<1|~(u|o),o&=u}l=n;while(l--)J[t.charCodeAt(l)]=0;return a},Ks=(t,e)=>{let n=e.length,s=t.length,i=[],r=[],o=Math.ceil(n/32),a=Math.ceil(s/32);for(let d=0;d<o;d++)r[d]=-1,i[d]=0;let l=0;for(;l<a-1;l++){let d=0,b=-1,E=l*32,_=Math.min(32,s)+E;for(let x=E;x<_;x++)J[t.charCodeAt(x)]|=1<<x;for(let x=0;x<n;x++){let P=J[e.charCodeAt(x)],R=r[x/32|0]>>>x&1,C=i[x/32|0]>>>x&1,O=P|d,T=((P|C)&b)+b^b|P|C,p=d|~(T|b),S=b&T;if(p>>>31^R)r[x/32|0]^=1<<x;if(S>>>31^C)i[x/32|0]^=1<<x;p=p<<1|R,S=S<<1|C,b=S|~(O|p),d=p&O}for(let x=E;x<_;x++)J[t.charCodeAt(x)]=0}let c=0,u=-1,h=l*32,
|
|
38
|
-
Run "${s} --help" for usage.`),process.exit(1)}function vt(t,e){if(Array.isArray(e))return[...e];if(!tn(t)||!tn(e))return e;return Object.fromEntries([...Object.entries(t),...Object.entries(e).map(([n,s])=>[n,vt(Object.hasOwn(t,n)?t[n]:void 0,s)])])}function tn(t){if(t===null||typeof t!=="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var
|
|
39
|
-
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&s.length===0&&process.stdout.isTTY===!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:t}=
|
|
37
|
+
`).trimEnd()}formatPositionalUsage(t){return Object.entries(t).map(([e,n])=>{let s=n.variadic?`${e}...`:e;return n.required?w.arg(`<${s}>`):w.arg(`[${s}]`)}).join(" ")}formatPositionalDefs(t){let e=Object.entries(t).map(([n,s])=>{let i=s.variadic?`${n}...`:n,r=w.desc(s.description??""),o=s.required?"":w.hint(" (optional)");return[` ${w.arg(i)}`,`${r}${o}`]});return this.formatColumns(e)}formatArgDefs(t){let e=[];for(let[n,s]of Object.entries(t)){let i=s.alias?`${w.flag(`-${s.alias}`)}, `:" ",r=s.type==="boolean"?"":` ${w.placeholder(`<${s.type==="number"?"number":"value"}>`)}`,o=`${i}${w.flag(`--${tt(n)}`)}${r}`,a=w.desc(s.description??""),l=this.formatDefault(s),c=l===void 0?"":` (default: ${w.default(l)})`;e.push([` ${o}`,`${a}${c}`])}return this.formatColumns(e)}formatDefault(t){if(typeof t.displayDefault==="string")return t.displayDefault;if(t.default===void 0)return;if(t.type==="boolean"&&t.default===!1)return;if(t.type==="string")return`"${t.default}"`;return String(t.default)}formatColumns(t){if(t.length===0)return[];let e=Math.max(...t.map(([s])=>this.stripAnsi(s).length)),n=2;return t.map(([s,i])=>{let r=e-this.stripAnsi(s).length+n;return`${s}${" ".repeat(r)}${i}`})}stripAnsi(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}}var J=new Uint32Array(65536),Js=(t,e)=>{let n=t.length,s=e.length,i=1<<n-1,r=-1,o=0,a=n,l=n;while(l--)J[t.charCodeAt(l)]|=1<<l;for(l=0;l<s;l++){let c=J[e.charCodeAt(l)],u=c|o;if(c|=(c&r)+r^r,o|=~(c|r),r&=c,o&i)a++;if(r&i)a--;o=o<<1|1,r=r<<1|~(u|o),o&=u}l=n;while(l--)J[t.charCodeAt(l)]=0;return a},Ks=(t,e)=>{let n=e.length,s=t.length,i=[],r=[],o=Math.ceil(n/32),a=Math.ceil(s/32);for(let d=0;d<o;d++)r[d]=-1,i[d]=0;let l=0;for(;l<a-1;l++){let d=0,b=-1,E=l*32,_=Math.min(32,s)+E;for(let x=E;x<_;x++)J[t.charCodeAt(x)]|=1<<x;for(let x=0;x<n;x++){let P=J[e.charCodeAt(x)],R=r[x/32|0]>>>x&1,C=i[x/32|0]>>>x&1,O=P|d,T=((P|C)&b)+b^b|P|C,p=d|~(T|b),S=b&T;if(p>>>31^R)r[x/32|0]^=1<<x;if(S>>>31^C)i[x/32|0]^=1<<x;p=p<<1|R,S=S<<1|C,b=S|~(O|p),d=p&O}for(let x=E;x<_;x++)J[t.charCodeAt(x)]=0}let c=0,u=-1,h=l*32,f=Math.min(32,s-h)+h;for(let d=h;d<f;d++)J[t.charCodeAt(d)]|=1<<d;let m=s;for(let d=0;d<n;d++){let b=J[e.charCodeAt(d)],E=r[d/32|0]>>>d&1,_=i[d/32|0]>>>d&1,x=b|c,P=((b|_)&u)+u^u|b|_,R=c|~(P|u),C=u&P;if(m+=R>>>s-1&1,m-=C>>>s-1&1,R>>>31^E)r[d/32|0]^=1<<d;if(C>>>31^_)i[d/32|0]^=1<<d;R=R<<1|E,C=C<<1|_,u=C|~(x|R),c=R&x}for(let d=h;d<f;d++)J[t.charCodeAt(d)]=0;return m},qs=(t,e)=>{if(t.length<e.length){let n=e;e=t,t=n}if(e.length===0)return t.length;if(t.length<=32)return Js(t,e);return Ks(t,e)},Ze=(t,e)=>{let n=1/0,s=0;for(let i=0;i<e.length;i++){let r=qs(t,e[i]);if(r<n)n=r,s=i}return e[s]};function bt(t,e,n,s){let i=Ze(e,n);if(console.error(v.red(`Unknown ${t}: ${e}`)),i)console.error(v.yellow(`Did you mean "${i}"?`));console.error(`
|
|
38
|
+
Run "${s} --help" for usage.`),process.exit(1)}function vt(t,e){if(Array.isArray(e))return[...e];if(!tn(t)||!tn(e))return e;return Object.fromEntries([...Object.entries(t),...Object.entries(e).map(([n,s])=>[n,vt(Object.hasOwn(t,n)?t[n]:void 0,s)])])}function tn(t){if(t===null||typeof t!=="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Qt="__exit__";class et{command;env;prefix;options;selections;constructor(t,e,n,s={}){this.command=t;this.env=e;this.prefix=n;this.options=s;this.selections=s.selections??new Map}get commandPath(){return this.prefix?`${this.prefix} ${this.command.name}`:this.command.name}async route(t,e){if(e&&process.stdout.isTTY!==!0)throw new g("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(e)await this.routeInteractive();else await this.routeDirect(t)}async routeDirect(t){let[e,...n]=t;if(e&&this.command.hasSubcommands()){let s=this.command.getSubcommand(e);if(s){await this.handleSubcommandRoute(s,n);return}if(!e.startsWith("-")){this.handleUnknownSubcommand(e);return}}await this.executeCommand(t)}handleUnknownSubcommand(t){let e=this.command.getSubcommands().map((n)=>n.name);bt("subcommand",t,e,this.commandPath)}async handleSubcommandRoute(t,e){await new et(t,this.env,this.commandPath).route(e,!1)}async executeCommand(t){if(this.isHelpRequest(t)){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:s}=Xt(t,this.command.args),i=zt(s,this.command.positionals),r=Qe(i,this.command.positionals);if(r)A.error(r),console.error(`
|
|
39
|
+
Run "${this.commandPath} --help" for usage.`),process.exit(1);let o=this.command.prompts&&s.length===0&&process.stdout.isTTY===!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:t}=Xt([],this.command.args),e=zt([],this.command.positionals),n=this.buildContext(e,t,!0);await this.command.execute?.(n)}async runSubcommandMenu(){while(!0){let t=await this.promptSubcommandSelectionOrBack();if(t===null)return;if(t===Qt){this.options.onExit?.();return}let e=this.command.getSubcommand(t);if(e)this.selections.set(this.commandPath,t),await this.executeSubcommand(e)}}async promptSubcommandSelectionOrBack(){try{return await this.promptSubcommandSelection()}catch(t){if(t instanceof W){if(this.options.isRoot)this.options.onExit?.();return null}throw t}}async executeSubcommand(t){try{await new et(t,this.env,this.commandPath,{selections:this.selections}).route([],!0)}catch(e){if(e instanceof W)return;if(e instanceof g){if(A.warn(v.yellow(e.message)),e.hint)A.info(v.dim(e.hint));Z(e);return}throw e}}promptSubcommandSelection(){let{isRoot:t}=this.options,e=t?{hint:this.env.cli.exitHint,label:this.env.cli.exitLabel??"Exit",value:Qt}:{hint:"Return to previous menu",label:"Back",value:Qt};return Wt({message:t?this.env.cli.promptMessage??"Select:":`${this.command.name}:`,initialValue:this.selections.get(this.commandPath),options:[...this.command.getSubcommands().map((n)=>({hint:n.description,label:n.name,value:n.name})),e]})}buildContext(t,e,n){return{...this.env,args:e,interactive:n,positionals:t}}isHelpRequest(t){let e=t.indexOf("--"),n=e<0?t:t.slice(0,e);return n.includes("--help")||n.includes("-h")}printHelp(t){let e=t===this.command?this.prefix:this.commandPath;console.log(this.env.formatHelp(t,e))}}var Xs={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",name:"CLI",promptMessage:"What would you like to do?"},zs={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"}};class Zt{commands=new Map;metadata;configManager;help;bin;globalArgs={...zs};constructor(t,e){this.configManager=t,this.metadata={...Xs,...e},this.bin=this.metadata.bin??this.metadata.name,this.init(),this.help=new Yt({bin:this.bin,description:this.metadata.description,name:this.metadata.name,version:this.metadata.version},this.commands,this.globalArgs)}registerCommands(t){for(let e of t)e.init?.(),this.commands.set(e.name,e)}async run(t=process.argv.slice(2)){try{let{command:e,flags:n,restArgs:s}=qt(t,this.globalArgs);if(n.version&&!e)return console.log(this.help.version());if(n.interactive&&!e)return await this.runInteractive();if(!e)return console.log(this.help.global());if(e==="help")return this.printHelpFor(s[0]);await this.runDirect(e,s,!!n.help)}catch(e){this.handleError(e)}}printHelpFor(t){if(!t)return console.log(this.help.global());let e=this.commands.get(t);if(!e)return this.handleUnknownCommand(t);console.log(this.help.command(e))}async runInteractive(){this.showIntro();let t=this.createVirtualRootCommand(),e={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)},n=new et(t,e,this.bin,{isRoot:!0,onExit:()=>this.exit()});try{await n.route([],!0)}catch(s){this.handleError(s)}}createVirtualRootCommand(){return{description:this.metadata.description,getSubcommand:(t)=>this.commands.get(t),getSubcommands:()=>Array.from(this.commands.values()),hasSubcommands:()=>!0,name:this.metadata.name}}exit(){gt(this.metadata.goodbyeMessage),process.exit(0)}async runDirect(t,e,n){let s=this.commands.get(t);if(!s)return this.handleUnknownCommand(t);let i=e.length>0&&!e[0]?.startsWith("-");if(n&&!i)return console.log(this.help.command(s));try{let r={cli:this.metadata,config:this.configManager,formatHelp:this.help.command.bind(this.help)};await new et(s,r,this.bin).route(e,!1)}catch(r){this.handleError(r)}}showIntro(){if(this.metadata.clearOnStart)console.clear();let t=this.metadata.version?` v${this.metadata.version}`:"";pt(`${v.bgCyan(v.black(` ${this.metadata.name}${t} `))}`)}handleUnknownCommand(t){let e=Array.from(this.commands.keys());bt("command",t,e,this.bin)}handleError(t){if(this.metadata.onError?.(t))return;if(t instanceof W)process.exit(0);if(t instanceof g){if(A.warn(v.yellow(t.message)),t.hint)A.info(v.dim(t.hint));Z(t),process.exit(t.exitCode)}if(t instanceof Error)A.error(v.red(t.message)),Z(t),process.exit(1);console.error(v.red("Error:"),t),process.exit(1)}}class ot{args={};positionals={};prompts=!1;subcommands=new Map;registerSubcommands(t){for(let e of t)e.init?.(),this.subcommands.set(e.name,e)}hasSubcommands(){return this.subcommands.size>0}getSubcommand(t){return this.subcommands.get(t)}getSubcommands(){return Array.from(this.subcommands.values())}}function B(t){return t}function nt(t){return t}import L from"fs";import sn from"path";var wt=(t)=>(t.map=(e)=>wt((n)=>e(t(n))),t.or=(e)=>wt((n)=>{try{return t(n)}catch(s){return e(n)}}),t),en=()=>"bad banditype"();var te=(t)=>wt((e)=>typeof e===typeof t?e:en()),ee=()=>te("");var nn=()=>te(!0);var ne=()=>te();var se=(t)=>wt((e)=>e instanceof t?e:en());var at=(t)=>se(Object).map((e)=>{let n={};for(let s in t){let i=t[s](e[s]);i!==void 0&&(n[s]=i)}return n});function re(t,e){JSON.parse(t);let n=JSON.parse(JSON.stringify(e)),s=Ys(t),i=t.match(/^[\t ]+(?=\S)/m)?.[0]??" ",r=t.includes(`\r
|
|
40
40
|
`)?`\r
|
|
41
41
|
`:`
|
|
42
|
-
`,o=/\s/.test(t[s.start+1]??"")||s.entries.some((c)=>/:\s+$/.test(t.slice(c.start,c.node.start)))?" ":"";function a(c,u){let h=t.slice(c.start,c.end);if(JSON.stringify(c.value)===JSON.stringify(u))return h;let
|
|
43
|
-
`));let f
|
|
44
|
-
`));let E=(p)=>
|
|
45
|
-
`)?_:o}`,C=
|
|
46
|
-
`))});return`${
|
|
47
|
-
`,u-1)+1,
|
|
48
|
-
`,r+
|
|
49
|
-
`;if(
|
|
42
|
+
`,o=/\s/.test(t[s.start+1]??"")||s.entries.some((c)=>/:\s+$/.test(t.slice(c.start,c.node.start)))?" ":"";function a(c,u){let h=t.slice(c.start,c.end);if(JSON.stringify(c.value)===JSON.stringify(u))return h;let f=Array.isArray(u);if(u===null||typeof u!=="object"||c.value===null||typeof c.value!=="object"||Array.isArray(c.value)!==f)return l(u,c.start,h.includes(`
|
|
43
|
+
`));let m=f?u.map((p,S)=>String(S)):[...new Set([...c.entries.map((p)=>p.key).filter((p)=>Object.hasOwn(u,p)),...Object.keys(u)])];if(m.length===0)return f?"[]":"{}";let d=c.entries[0],b=c.entries.at(-1);if(!d||!b)return l(u,c.start,h.includes(`
|
|
44
|
+
`));let E=(p)=>f?u[Number(p)]:u[p];if(m.length===c.entries.length&&m.every((p,S)=>p===c.entries[S]?.key)){let p=c.start,S="";for(let D of c.entries)S+=t.slice(p,D.node.start)+a(D.node,E(D.key)),p=D.node.end;return S+t.slice(p,c.end)}let _=t.slice(c.start+1,d.start),x=t.slice(b.node.end,c.end-1),P=c.entries[1],R=P?t.slice(d.node.end,P.start):`,${_.includes(`
|
|
45
|
+
`)?_:o}`,C=f?"":t.slice(d.start,d.node.start).match(/:\s*$/)?.[0]??": ",O=new Map(c.entries.map((p)=>[p.key,p])),T=m.map((p)=>{let S=O.get(p);if(S)return t.slice(S.start,S.node.start)+a(S.node,E(p));return(f?"":JSON.stringify(p)+C)+l(E(p),d.start,_.includes(`
|
|
46
|
+
`))});return`${f?"[":"{"}${_}${T.join(R)}${x}${f?"]":"}"}`}function l(c,u,h){if(!h)return ie(c,o);let f=t.lastIndexOf(`
|
|
47
|
+
`,u-1)+1,m=t.slice(f,u).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(c,null,i).replaceAll(`
|
|
48
|
+
`,r+m)}return t.slice(0,s.start)+a(s,n)+t.slice(s.end)}function ie(t,e){if(Array.isArray(t))return`[${t.map((i)=>ie(i,e)).join(`,${e}`)}]`;if(t===null||typeof t!=="object")return JSON.stringify(t);let n=Object.entries(t);if(n.length===0)return"{}";let s=n.map(([i,r])=>`${JSON.stringify(i)}:${e}${ie(r,e)}`);return`{${e}${s.join(`,${e}`)}${e}}`}function Ys(t){let e=t.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),n=e.next().value;function s(){if(!n)throw Error("Unexpected end of JSON");let r=n;return n=e.next().value,r}function i(){let r=s(),o=[],a=r[0]==="{";if(!a&&r[0]!=="[")return{end:r.index+r[0].length,entries:o,start:r.index,value:JSON.parse(r[0])};let l=a?"}":"]";while(n&&n[0]!==l){let u=n.index,h=a?JSON.parse(s()[0]):String(o.length);if(a)s();if(o.push({key:h,node:i(),start:u}),n?.[0]===",")s()}let c=s().index+1;return{end:c,entries:o,start:r.index,value:JSON.parse(t.slice(r.index,c))}}return i()}var Qs=2,Zs=se(Object);class oe{config;configPath;defaultConfig;loadError;loadFailure;constructor(t,e,n={}){this.configPath=sn.resolve(t),this.defaultConfig=e,this.config=this.loadConfig(n)}get path(){return this.configPath}get failure(){return this.loadFailure}get(t){return this.assertLoaded(),this.config[t]}set(t,e){this.assertLoaded(),this.config={...this.config,[t]:e},this.save()}delete(t){this.assertLoaded(),delete this.config[t],this.save()}exists(){return L.existsSync(this.configPath)}getAll(){return this.assertLoaded(),structuredClone(this.config)}save(t){if(this.assertLoaded(),this.loadError)throw Error(`Cannot overwrite unreadable config at ${this.configPath}; repair the file and try again`,{cause:this.loadError});if(t)this.config={...t};this.ensureDirectoryExists();let e=this.exists()?L.realpathSync(this.configPath):this.configPath,n=`${e}.${crypto.randomUUID()}.tmp`;try{let s=this.exists()?L.statSync(this.configPath).mode:void 0,i=this.exists()?re(L.readFileSync(this.configPath,"utf-8"),this.config):`${JSON.stringify(this.config,null,Qs)}
|
|
49
|
+
`;if(L.writeFileSync(n,i,{flag:"wx",mode:s}),s!==void 0)L.chmodSync(n,s);L.renameSync(n,e)}catch(s){throw Error(`Failed to save config to ${this.configPath}`,{cause:s})}finally{L.rmSync(n,{force:!0})}}assertLoaded(){if(this.loadFailure)throw this.loadFailure}ensureDirectoryExists(){let t=sn.dirname(this.configPath);if(!L.existsSync(t))try{L.mkdirSync(t,{recursive:!0})}catch(e){throw Error(`Failed to create config directory at ${t}`,{cause:e})}}loadConfig({parse:t,strict:e}){if(!e&&!L.existsSync(this.configPath))return structuredClone(this.defaultConfig);try{let n=this.readConfigFile();if(n===void 0)return structuredClone(this.defaultConfig);let s=JSON.parse(n);if(Array.isArray(s))throw Error("Config must be an object");let i=vt(structuredClone(this.defaultConfig),Zs(s));return t?t(i):i}catch(n){if(e){let s=n instanceof Error?n.message:String(n);return this.loadFailure=Error(`Cannot read config at ${this.configPath}: ${s}`,{cause:n}),structuredClone(this.defaultConfig)}return this.loadError=n,console.warn(`Config file corrupted at ${this.configPath}. Using defaults.`),structuredClone(this.defaultConfig)}}readConfigFile(){try{return L.readFileSync(this.configPath,"utf-8")}catch(t){if(t.code==="ENOENT")return;throw t}}}var rn="0.6.5";import{mkdir as ji}from"fs/promises";import{dirname as Vi}from"path";class V extends ot{}import{existsSync as At,readFileSync as fi}from"fs";import{dirname as le,join as vn,parse as mi,resolve as ue}from"path";var on="ATLAS",an="atlas",K=".atlas",ct="config.json",cn=".env",xt={defaults:{profiles:[],exportFile:".env"},profiles:{}};import{homedir as ei}from"os";import{isAbsolute as ni,resolve as ln}from"path";function X(t,e,n){if(t!==void 0&&t.trim().length===0)throw new g(`--${e} must not be empty`,n)}function st(t,e){return t instanceof Error&&"code"in t&&t.code===e}function q(){return process.env.HOME||ei()}function it(t,e=process.cwd()){if(t==="~")return q();if(t.startsWith("~/"))return ln(q(),t.slice(2));if(ni(t))return t;return ln(e,t)}function Ct(t,e){if(t===void 0)return;let n=si(t);if(n.length===0)throw new g("--profile must include at least one profile",e);return n}function si(t){return t.split(",").map((e)=>e.trim()).filter(Boolean)}var St=/^[A-Za-z_][A-Za-z0-9_]*$/;var ii=['"',"'","`"];function un(t){let e=Object.create(null),n=t.split(/\r?\n/);for(let s=0;s<n.length;s+=1){let i=s+1,r=n[s]??"",o=r.trim();if(!o||o.startsWith("#"))continue;let a=o.startsWith("export ")?o.slice(7).trimStart():o,l=a.indexOf("=");if(l<0)throw Error(`Invalid dotenv syntax at line ${i}: expected KEY=VALUE`);let c=a.slice(0,l).trim();if(!St.test(c))throw Error(`Invalid dotenv key at line ${i}`);let u=a.slice(l+1).trim(),h=ri(u,r,n,s);if(h){e[c]=h.value,s=h.endIndex;continue}e[c]=hn(u)}return e}function dn(t){return Object.keys(t).sort().map((e,n)=>{let s=n+1;if(!St.test(e))throw Error(`Invalid dotenv key at entry ${s}`);let i=t[e]??"",r=ui(i,e);if(hn(r)!==i)throw Error(`Unrepresentable dotenv value for key ${e}`);return`${e}=${r}`}).join(`
|
|
50
50
|
`).concat(`
|
|
51
|
-
`)}function
|
|
52
|
-
`),i)}}return}function hn(t){let e=
|
|
53
|
-
`;if(t==="r")return"\r";if(t==="t")return"\t";if(t==='"')return'"';if(t==="\\")return"\\";if(t==="$")return"$";return}function gn(t){let e="";for(let n=0;n<t.length;n+=1){if(t[n]==="\\"&&t[n+1]==="$"){e+="$",n+=1;continue}e+=t[n]}return e}function
|
|
54
|
-
`)||t.includes("\r"))&&!t.includes("'")&&!pn(t,t.length))return`'${n}'`;if(!t.includes('"')&&!t.includes("\\"))return`"${
|
|
55
|
-
`)||t.includes("\r")||t.includes("#"))return!1;if(t.trim()!==t)return!1;return
|
|
56
|
-
`,t.args.force,"Atlas config"),A.success(`Created ${v.green(n)}`)}}var
|
|
57
|
-
`);return}if(n.length===0){A.info("No Atlas profiles configured");return}for(let s of n){let i=e.config.profiles[s],r=i?.description?v.dim(` - ${i.description}`):"";A.info(`${v.cyan(s)}${r}`)}})}}class Rn extends V{name="show";description="Show one Atlas profile";args=
|
|
51
|
+
`)}function ri(t,e,n,s){let i=ce(t[0]);if(i===void 0)return;if(ae(t,i,1)!==-1)return;let r=e.indexOf(i),o=[e.slice(r+1)];for(let a=s+1;a<n.length;a+=1){let l=n[a]??"",c=ae(l,i,0);if(c===-1){o.push(l);continue}if(!mn(l,c+1))return;return o.push(l.slice(0,c)),{endIndex:a,value:fn(o.join(`
|
|
52
|
+
`),i)}}return}function hn(t){let e=ce(t[0]);if(e!==void 0){let n=oi(t,e);if(n!==void 0)return fn(n,e)}return gn(ai(t).trimEnd())}function ce(t){return ii.find((e)=>e===t)}function fn(t,e){return e==='"'?ci(t):gn(t)}function oi(t,e){let n=ae(t,e,1);if(n===-1)return;if(!mn(t,n+1))return;return t.slice(1,n)}function mn(t,e){let n=t.slice(e).trimStart();return!n||n.startsWith("#")}function ae(t,e,n){for(let s=n;s<t.length;s+=1)if(t[s]===e&&!pn(t,s))return s;return-1}function pn(t,e){let n=0;for(let s=e-1;t[s]==="\\";s-=1)n+=1;return n%2===1}function ai(t){let e=t.search(/\s#/);return e<0?t:t.slice(0,e)}function ci(t){let e="";for(let n=0;n<t.length;n+=1){let s=t[n];if(s!=="\\"||n+1>=t.length){e+=s;continue}let i=t[n+1],r=li(i);if(r===void 0){e+=s;continue}e+=r,n+=1}return e}function li(t){if(t==="n")return`
|
|
53
|
+
`;if(t==="r")return"\r";if(t==="t")return"\t";if(t==='"')return'"';if(t==="\\")return"\\";if(t==="$")return"$";return}function gn(t){let e="";for(let n=0;n<t.length;n+=1){if(t[n]==="\\"&&t[n+1]==="$"){e+="$",n+=1;continue}e+=t[n]}return e}function ui(t,e){if(t.includes("\x00"))throw Error(`Unrepresentable dotenv value for key ${e}`);if(t==="")return"";let n=$n(t);if(di(t))return n;if(!(t.includes(`
|
|
54
|
+
`)||t.includes("\r"))&&!t.includes("'")&&!pn(t,t.length))return`'${n}'`;if(!t.includes('"')&&!t.includes("\\"))return`"${hi(t)}"`;throw Error(`Unrepresentable dotenv value for key ${e}`)}function di(t){if(t.includes(`
|
|
55
|
+
`)||t.includes("\r")||t.includes("#"))return!1;if(t.trim()!==t)return!1;return ce(t[0])===void 0}function $n(t){return t.replace(/\$(?!$)/g,"\\$&")}function hi(t){return $n(t).replace(/\n/g,"\\n").replace(/\r/g,"\\r")}var pi="must be a valid environment variable name matching [A-Za-z_][A-Za-z0-9_]*",gi=new Set(Object.getOwnPropertyNames(Object.prototype)),$i=nn().or(ne()),yi=ee().or(ne()),wn=ee();class M extends Error{_tag="AtlasConfigValidationError"}function bi(t={}){let e=ue(t.cwd??process.cwd()),n=ue(t.home??q()),s=vn(n,K,ct),i=At(s)?s:void 0,r=vi(e,i),o=r?le(le(r)):void 0;return{cwd:e,globalPath:i,home:n,projectPath:r,projectRoot:o}}function Y(t={}){let e=bi(t),n=yn(e.globalPath,e.home),s=yn(e.projectPath,e.projectRoot),i=z(),r=z();for(let a of[n,s]){if(!a)continue;for(let[l,c]of Object.entries(a.config.profiles))r[l]=c,i[l]=a.rootDir}return{config:{defaults:{...n?.config.defaults,...s?.config.defaults,profiles:[...n?.config.defaults?.profiles??[],...s?.config.defaults?.profiles??[]]},profiles:r},cwd:e.cwd,globalPath:e.globalPath,home:e.home,profileSources:i,projectPath:e.projectPath,projectRoot:e.projectRoot}}function Et(t,e={}){let n=[...t.config.defaults?.profiles??[],...e.profiles??[]],s=z(),i=[],r=new Set,o=e.env??process.env;function a(c,u){if(r.has(c))return;let h=Object.hasOwn(t.config.profiles,c)?t.config.profiles[c]:void 0;if(!h)throw new g(`Unknown Atlas profile: ${c}`,"Run 'atlas profiles list'");if(u.includes(c))throw new g(`Profile inheritance cycle: ${[...u,c].join(" -> ")}`);for(let d of h.extends??[])a(d,[...u,c]);let m=(Object.hasOwn(t.profileSources,c)?t.profileSources[c]:void 0)??t.projectRoot??t.cwd;for(let d of h.envFiles??[])Object.assign(s,Ti(it(d,m)));Object.assign(s,h.vars??{});for(let[d,b]of Object.entries(h.secrets??{})){let E=Ri(d,b,m,o);if(E!==void 0)s[d]=E}r.add(c),i.push(c)}for(let c of n)a(c,[]);let l=it(t.config.defaults?.exportFile??cn,t.projectRoot??t.cwd);return{env:s,exportFile:l,profiles:i}}function vi(t,e){let n=ue(t),s=mi(n).root;while(!0){let i=vn(n,K,ct);if(At(i)&&i!==e)return i;if(n===s)return;n=le(n)}}function yn(t,e){if(!t||!e)return;let n,s=me(t,`Atlas config ${t}`);try{n=JSON.parse(s)}catch(i){if(i instanceof SyntaxError)throw new g(`Invalid JSON in Atlas config ${t}`,"Fix the JSON syntax in the config file");throw i}try{return{config:wi(n),path:t,rootDir:e}}catch(i){let r=i instanceof M?i.message:"config failed validation";throw new g(`Invalid Atlas config at ${t}: ${r}`)}}function wi(t){let e=Tt(t,"config",["$schema","defaults","profiles"]);return at({$schema:(n)=>It(n,"$schema"),defaults:(n)=>xi(n,"defaults"),profiles:(n)=>Ci(n,"profiles")})(e)}function xi(t,e){if(t===void 0)return;let n=Tt(t,e,["exportFile","profiles"]);return at({exportFile:(s)=>xn(s,`${e}.exportFile`),profiles:(s)=>de(s,`${e}.profiles`)})(n)}function Ci(t,e){if(t===void 0)return z();let n=_t(t,e),s=z();for(let i of Object.keys(n)){let r=fe(e,i);if(gi.has(i))throw new M(`${r} must not use a prototype-sensitive profile name`);s[i]=Si(n[i],r)}return s}function Si(t,e){let n=Tt(t,e,["description","envFiles","extends","secrets","vars"]);return at({description:(s)=>It(s,`${e}.description`),envFiles:(s)=>de(s,`${e}.envFiles`),extends:(s)=>de(s,`${e}.extends`),secrets:(s)=>Ei(s,`${e}.secrets`),vars:(s)=>Ai(s,`${e}.vars`)})(n)}function Ai(t,e){if(t===void 0)return;let n=_t(t,e),s=z();for(let i of Object.keys(n)){let r=fe(e,i);he(i,r),s[i]=Rt(wn,n[i],r,"must be a string")}return s}function Ei(t,e){if(t===void 0)return;let n=_t(t,e),s=z();for(let i of Object.keys(n)){let r=fe(e,i);he(i,r),s[i]=Ii(n[i],r)}return s}function Ii(t,e){let n=Tt(t,e,["env","file","optional","trim"]),s=at({env:(i)=>_i(i,`${e}.env`),file:(i)=>xn(i,`${e}.file`),optional:(i)=>bn(i,`${e}.optional`),trim:(i)=>bn(i,`${e}.trim`)})(n);if(s.env===void 0&&s.file===void 0)throw new M(`${e} must define env or file`);if(s.env!==void 0&&s.file!==void 0)throw new M(`${e} must define only one of env or file`);if(s.env!==void 0&&s.trim!==void 0)throw new M(`${e}.trim only applies to file secrets`);return s}function de(t,e){if(t===void 0)return;if(!Array.isArray(t))throw new M(`${e} must be an array`);return t.map((n,s)=>{let i=`${e}[${s}]`,r=Rt(wn,n,i,"must be a string");return Cn(r,i)})}function xn(t,e){let n=It(t,e);return n===void 0?void 0:Cn(n,e)}function Cn(t,e){if(t.trim().length===0)throw new M(`${e} must be a non-empty string`);return t}function It(t,e){return Rt(yi,t,e,"must be a string")}function _i(t,e){let n=It(t,e);if(n===void 0)return;return he(n,e),n}function bn(t,e){return Rt($i,t,e,"must be a boolean")}function _t(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw new M(`${e} must be an object`);let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new M(`${e} must be an object`);return t}function Tt(t,e,n){let s=_t(t,e);for(let i of Object.keys(s))if(!n.includes(i))throw new M(`${e} has unknown key ${JSON.stringify(i)}`);return s}function he(t,e){if(!St.test(t))throw new M(`${e} ${pi}`)}function Rt(t,e,n,s){try{return t(e)}catch{throw new M(`${n} ${s}`)}}function fe(t,e){return`${t}[${JSON.stringify(e)}]`}function z(){return Object.create(null)}function Ti(t){if(!At(t))throw new g(`Atlas env file not found: ${t}`,"Create the file or remove it from the profile's envFiles");let e=me(t,`Atlas env file ${t}`);try{return un(e)}catch(n){let s=n instanceof Error?n.message:"env file failed to parse";throw new g(`Invalid dotenv file ${t}: ${s}`,"Fix the reported line in the env file")}}function Ri(t,e,n,s){if(e.env){let i=Object.hasOwn(s,e.env)?s[e.env]:void 0;if(i!==void 0)return i;if(e.optional)return;throw new g(`Missing required secret ${t}: env ${e.env} is not set`,`Set ${e.env} or mark the secret optional`)}if(e.file){let i=it(e.file,n);if(!At(i)){if(e.optional)return;throw new g(`Missing required secret ${t}: file ${i} does not exist`,"Create the file or mark the secret optional")}let r=me(i,`secret file ${i} for ${t}`);return e.trim===!1?r:r.trim()}if(e.optional)return;throw new g(`Missing required secret ${t}: secret ref must define env or file`)}function me(t,e){try{return fi(t,"utf8")}catch(n){let s=new g(`Failed to read ${e}`,"Check that the path is a readable file");throw s.cause=n,s}}import{randomUUID as Oi}from"crypto";import{link as Pi,lstat as ki,open as Di,rename as Fi,rm as Sn}from"fs/promises";import{basename as Mi,dirname as Ni,join as Li}from"path";var An=384;async function Ot(t,e,n,s="Output file"){let i=await ki(t).catch((a)=>{if(st(a,"ENOENT"))return null;throw a});if(i&&!i.isFile()&&!i.isSymbolicLink())throw new g(`Output path is not a regular file: ${t}`);let r=Li(Ni(t),`.${Mi(t)}.${Oi()}.tmp`),o=null;try{if(o=await Di(r,"wx",An),await o.chmod(An),await o.writeFile(e,"utf8"),await o.sync(),await o.close(),o=null,n)await Fi(r,t);else await Pi(r,t).catch((a)=>{if(st(a,"EEXIST"))throw new g(`${s} already exists: ${t}`,"Use --force to overwrite it");throw a}),await Sn(r)}catch(a){throw await o?.close().catch(()=>{return}),await Sn(r,{force:!0}).catch(()=>{return}),a}}var Ui="Usage: atlas export --profile <name,...>",En=B({cwd:{description:"Working directory override",type:"string"},force:{alias:"f",default:!1,description:"Overwrite an existing file",type:"boolean"},out:{alias:"o",description:"Output .env path",type:"string"},profile:{alias:"p",description:"Comma-separated profiles to apply",type:"string"},stdout:{default:!1,description:"Print to stdout instead of writing a file",type:"boolean"}});class Pt extends V{name="export";description="Export resolved Atlas env to a dotenv file";args=En;async execute(t){if(H(t.args,En,"Run 'atlas export --help' for supported options"),t.args.stdout&&t.args.out!==void 0)throw new g("--stdout cannot be combined with --out","Use --stdout to print, or --out <path> to write a file");X(t.args.cwd,"cwd","Usage: atlas export --cwd <dir>"),X(t.args.out,"out","Usage: atlas export --out <path>");let e=Ct(t.args.profile,Ui),n=t.args.cwd??process.cwd(),s=Y({cwd:n}),i=Et(s,{profiles:e}),r=dn(i.env);if(t.args.stdout){process.stdout.write(r);return}let o=t.args.out!==void 0?it(t.args.out,s.cwd):i.exportFile;await ji(Vi(o),{recursive:!0}),await Ot(o,r,t.args.force),A.success(`Wrote ${v.green(o)} using ${i.profiles.length} profile(s)`)}}import{mkdir as Gi}from"fs/promises";import{join as In}from"path";var _n=B({force:{alias:"f",default:!1,description:"Overwrite an existing config",type:"boolean"},global:{alias:"g",default:!1,description:"Write ~/.atlas/config.json",type:"boolean"}});class kt extends V{name="init";description="Create an Atlas config";args=_n;async execute(t){H(t.args,_n,"Run 'atlas init --help' for supported options");let e=t.args.global?q():process.cwd(),n=In(e,K,ct);await Gi(In(e,K),{recursive:!0}),await Ot(n,`${JSON.stringify(xt,null,2)}
|
|
56
|
+
`,t.args.force,"Atlas config"),A.success(`Created ${v.green(n)}`)}}var pe=B({cwd:{description:"Working directory override",type:"string"},json:{alias:"j",default:!1,description:"Output as JSON",type:"boolean"}}),Hi=nt({profile:{description:"Profile name",required:!0}});class Dt extends V{name="profiles";description="Inspect Atlas profiles";init(){this.registerSubcommands([new Tn,new Rn])}}class Tn extends V{name="list";description="List available profiles";args=pe;async execute(t){Pn(t.args.json,()=>{On(t.args);let e=Y({cwd:t.args.cwd??process.cwd()}),n=Object.keys(e.config.profiles).sort();if(t.args.json){process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
57
|
+
`);return}if(n.length===0){A.info("No Atlas profiles configured");return}for(let s of n){let i=e.config.profiles[s],r=i?.description?v.dim(` - ${i.description}`):"";A.info(`${v.cyan(s)}${r}`)}})}}class Rn extends V{name="show";description="Show one Atlas profile";args=pe;positionals=Hi;async execute(t){Pn(t.args.json,()=>{On(t.args);let e=t.positionals.profile;if(!e)throw new g("Profile name is required","Usage: atlas profiles show <profile>");let s=Y({cwd:t.args.cwd??process.cwd()}).config.profiles,i=Object.hasOwn(s,e)?s[e]:void 0;if(!i){let r=`Unknown Atlas profile: ${e}`;throw new g(r,"Run 'atlas profiles list'")}if(t.args.json){process.stdout.write(`${JSON.stringify(i,null,2)}
|
|
58
58
|
`);return}A.info(`${v.bold(e)}
|
|
59
|
-
${JSON.stringify(i,null,2)}`)})}}function On(t){H(t,
|
|
60
|
-
`),process.exitCode=n.exitCode}}import{statSync as
|
|
59
|
+
${JSON.stringify(i,null,2)}`)})}}function On(t){H(t,pe,"Run 'atlas profiles --help' for supported commands"),X(t.cwd,"cwd","Usage: atlas profiles <list|show> --cwd <dir>")}function Pn(t,e){try{e()}catch(n){if(!t||!(n instanceof g))throw n;process.stderr.write(`${JSON.stringify({error:n.message})}
|
|
60
|
+
`),process.exitCode=n.exitCode}}import{statSync as Bi}from"fs";import{resolve as Wi}from"path";var kn=B({cwd:{description:"Working directory override",type:"string"},profile:{alias:"p",description:"Comma-separated profiles to apply",type:"string"}}),Ji=127,Ki=126,qi="Put child command flags after --: atlas run -p app -- <cmd> --flags",Xi="Usage: atlas run --profile <name,...> -- <command...>",zi=nt({command:{description:"Command to run",required:!0,variadic:!0}});class Ft extends V{name="run";description="Run a command with resolved Atlas env";args=kn;positionals=zi;async execute(t){H(t.args,kn,qi);let e=t.positionals.command;if(e.length===0)throw new g("Command is required","Usage: atlas run --profile app:web -- <command...>");X(t.args.cwd,"cwd","Usage: atlas run --cwd <dir> -- <command...>");let n=Ct(t.args.profile,Xi),s=Wi(t.args.cwd??process.cwd());if(!Bi(s,{throwIfNoEntry:!1})?.isDirectory())throw new g(`Working directory is not a directory: ${s}`,"Usage: atlas run --cwd <dir> -- <command...>");let i=Qi(s,n),r=Yi(e,s,i),o=()=>r.kill("SIGINT"),a=()=>r.kill("SIGTERM");process.on("SIGINT",o),process.on("SIGTERM",a);let l;try{l=await r.exited}finally{process.off("SIGINT",o),process.off("SIGTERM",a)}if(l!==0)process.exit(l)}}function Yi(t,e,n){try{return Bun.spawn(t,{cwd:e,env:n,stderr:"inherit",stdin:"inherit",stdout:"inherit"})}catch(s){if(st(s,"ENOENT"))throw new g(`Command not found: ${t[0]}`,"Check that it is installed and on PATH",Ji);if(st(s,"EACCES"))throw new g(`Command is not executable: ${t[0]}`,"Check the executable permissions",Ki);throw s}}function Qi(t,e){let n=Y({cwd:t}),s=Et(n,{profiles:e});return{...Object.fromEntries(Object.entries(process.env).filter((r)=>r[1]!==void 0)),...s.env}}class Dn extends Zt{constructor(){super(new oe(Zi(q(),K,"cli-state.json"),xt),{bin:an,clearOnStart:!1,description:"Profile-based env composition for apps and environments",name:on,version:rn})}init(){this.registerCommands([new kt,new Dt,new Ft,new Pt])}}var tr=new Dn;tr.run();
|
package/package.json
CHANGED