@elysiumjs/styx 0.8.2 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +102 -0
- package/README.md +52 -41
- package/dist/assets.d.ts +31 -0
- package/dist/cli/app.d.ts +15 -0
- package/dist/cli/route.d.ts +51 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +200 -0
- package/dist/commands/index.d.ts +1 -0
- package/dist/commands/routes_generate.command.d.ts +11 -0
- package/dist/config.d.ts +5 -0
- package/dist/create/code.d.ts +77 -0
- package/dist/create/create.command.d.ts +60 -0
- package/dist/create/names.d.ts +42 -0
- package/dist/create/versions.d.ts +7 -0
- package/dist/index.js +9 -3
- package/dist/routes/collect.d.ts +20 -0
- package/dist/routes/render.d.ts +39 -0
- package/package.json +13 -10
- package/stubs/http.controller.stub +1 -1
- package/stubs/ws.controller.stub +1 -1
- package/templates/feature-hephaestus/.specs +7 -0
- package/templates/feature-hephaestus/hephaestus.config.ts +7 -0
- package/templates/feature-prettier/.prettierignore +5 -0
- package/templates/feature-prettier/.prettierrc +23 -0
- package/templates/feature-prettier/.specs +13 -0
- package/templates/plugin-sentry/.env.example +2 -0
- package/templates/plugin-sentry/.specs +12 -0
- package/templates/shared-module/commands/.gitkeep +0 -0
- package/templates/shared-module/controllers/http/.gitkeep +0 -0
- package/templates/shared-module/controllers/wamp/.gitkeep +0 -0
- package/templates/shared-module/controllers/ws/.gitkeep +0 -0
- package/templates/shared-module/jobs/.gitkeep +0 -0
- package/templates/shared-module/middlewares/.gitkeep +0 -0
- package/templates/shared-module/models/.gitkeep +0 -0
- package/templates/shared-module/repositories/.gitkeep +0 -0
- package/templates/shared-module/services/.gitkeep +0 -0
- package/templates/shared-module/utils/.gitkeep +0 -0
- package/templates/shared-module/validators/.gitkeep +0 -0
- package/templates/template-multi/.gitattributes +15 -0
- package/templates/template-multi/README.md +20 -0
- package/templates/template-multi/gitignore +45 -0
- package/templates/template-multi/index.ts +10 -0
- package/templates/template-multi/package.json +8 -0
- package/templates/template-multi/src/modules/.gitkeep +0 -0
- package/templates/template-multi/tsconfig.json +32 -0
- package/templates/template-multi/types.d.ts +5 -0
- package/templates/template-single/.gitattributes +15 -0
- package/templates/template-single/README.md +20 -0
- package/templates/template-single/gitignore +45 -0
- package/templates/template-single/index.ts +10 -0
- package/templates/template-single/package.json +8 -0
- package/templates/template-single/tsconfig.json +32 -0
- package/templates/template-single/types.d.ts +5 -0
- package/dist/styx.js +0 -11
package/dist/cli.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:!0}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __legacyDecorateClassTS=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};var __legacyMetadataTS=(k,v)=>{if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(k,v)};var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};var __require=import.meta.require;var require_package=__commonJS(function(exports,module){module.exports={name:"@elysiumjs/styx",version:"0.9.0",license:"Apache-2.0",description:"The command line tool of the Elysium.js framework: creates projects, generates code and runs app commands.",private:!1,author:"Workbud Technologies Inc.",repository:{type:"git",url:"git+https://github.com/na2axl/elysiumjs.git",directory:"@elysiumjs/styx"},homepage:"https://github.com/na2axl/elysiumjs/tree/main/@elysiumjs/styx#readme",bugs:{url:"https://github.com/na2axl/elysiumjs/issues"},scripts:{format:'prettier --write "./src/**/*.ts"',clean:"rimraf dist","build:js":"bun build ./src/cli.ts ./src/index.ts --outdir ./dist --target bun -e @elysiumjs/* --root ./src --minify-syntax --minify-whitespace","build:ts":"tsc",build:"bun run clean && bun run build:js && bun run build:ts",typecheck:"tsc --noEmit",prepublishOnly:"bun run build",test:"bun test","test:coverage":"bun test --coverage","build:bin":"bun scripts/build-bin.ts"},keywords:["elysium","framework","web","api","typescript","cli"],type:"module",sideEffects:!1,bin:{styx:"dist/cli.js"},module:"dist/index.js",types:"dist/index.d.ts",files:["dist","stubs","templates","CHANGELOG.md"],devDependencies:{"@elysiumjs/core":"workspace:*","@elysiumjs/hephaestus":"workspace:*","@elysiumjs/runtime-bun":"workspace:*","@types/prompts":"^2.4.9","@types/string-template":"^1.0.7",prompts:"^2.4.2",radash:"catalog:","string-template":"^1.0.0"},dependencies:{"@elysiumjs/core":"workspace:^","@elysiumjs/runtime-bun":"workspace:^"}}});import{Command}from"@elysiumjs/core";var BaseCommand;var init_base_command=__esm(()=>{BaseCommand=class BaseCommand extends Command{static dev=!0}});var require_kleur=__commonJS(function(exports,module){var{FORCE_COLOR,NODE_DISABLE_COLORS,TERM}=process.env,$={enabled:!NODE_DISABLE_COLORS&&TERM!=="dumb"&&FORCE_COLOR!=="0",reset:init(0,0),bold:init(1,22),dim:init(2,22),italic:init(3,23),underline:init(4,24),inverse:init(7,27),hidden:init(8,28),strikethrough:init(9,29),black:init(30,39),red:init(31,39),green:init(32,39),yellow:init(33,39),blue:init(34,39),magenta:init(35,39),cyan:init(36,39),white:init(37,39),gray:init(90,39),grey:init(90,39),bgBlack:init(40,49),bgRed:init(41,49),bgGreen:init(42,49),bgYellow:init(43,49),bgBlue:init(44,49),bgMagenta:init(45,49),bgCyan:init(46,49),bgWhite:init(47,49)};function run(arr,str){let i=0,tmp,beg="",end="";for(;i<arr.length;i++)if(tmp=arr[i],beg+=tmp.open,end+=tmp.close,str.includes(tmp.close))str=str.replace(tmp.rgx,tmp.close+tmp.open);return beg+str+end}function chain(has,keys){let ctx={has,keys};return ctx.reset=$.reset.bind(ctx),ctx.bold=$.bold.bind(ctx),ctx.dim=$.dim.bind(ctx),ctx.italic=$.italic.bind(ctx),ctx.underline=$.underline.bind(ctx),ctx.inverse=$.inverse.bind(ctx),ctx.hidden=$.hidden.bind(ctx),ctx.strikethrough=$.strikethrough.bind(ctx),ctx.black=$.black.bind(ctx),ctx.red=$.red.bind(ctx),ctx.green=$.green.bind(ctx),ctx.yellow=$.yellow.bind(ctx),ctx.blue=$.blue.bind(ctx),ctx.magenta=$.magenta.bind(ctx),ctx.cyan=$.cyan.bind(ctx),ctx.white=$.white.bind(ctx),ctx.gray=$.gray.bind(ctx),ctx.grey=$.grey.bind(ctx),ctx.bgBlack=$.bgBlack.bind(ctx),ctx.bgRed=$.bgRed.bind(ctx),ctx.bgGreen=$.bgGreen.bind(ctx),ctx.bgYellow=$.bgYellow.bind(ctx),ctx.bgBlue=$.bgBlue.bind(ctx),ctx.bgMagenta=$.bgMagenta.bind(ctx),ctx.bgCyan=$.bgCyan.bind(ctx),ctx.bgWhite=$.bgWhite.bind(ctx),ctx}function init(open,close){let blk={open:`\x1B[${open}m`,close:`\x1B[${close}m`,rgx:new RegExp(`\\x1b\\[${close}m`,"g")};return function(txt){if(this!==void 0&&this.has!==void 0)return this.has.includes(open)||(this.has.push(open),this.keys.push(blk)),txt===void 0?this:$.enabled?run(this.keys,txt+""):txt+"";return txt===void 0?chain([open],[blk]):$.enabled?run([blk],txt+""):txt+""}}module.exports=$});var require_action=__commonJS(function(exports,module){module.exports=(key,isSelect)=>{if(key.meta&&key.name!=="escape")return;if(key.ctrl){if(key.name==="a")return"first";if(key.name==="c")return"abort";if(key.name==="d")return"abort";if(key.name==="e")return"last";if(key.name==="g")return"reset"}if(isSelect){if(key.name==="j")return"down";if(key.name==="k")return"up"}if(key.name==="return")return"submit";if(key.name==="enter")return"submit";if(key.name==="backspace")return"delete";if(key.name==="delete")return"deleteForward";if(key.name==="abort")return"abort";if(key.name==="escape")return"exit";if(key.name==="tab")return"next";if(key.name==="pagedown")return"nextPage";if(key.name==="pageup")return"prevPage";if(key.name==="home")return"home";if(key.name==="end")return"end";if(key.name==="up")return"up";if(key.name==="down")return"down";if(key.name==="right")return"right";if(key.name==="left")return"left";return!1}});var require_strip=__commonJS(function(exports,module){module.exports=(str)=>{let pattern=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|"),RGX=new RegExp(pattern,"g");return typeof str==="string"?str.replace(RGX,""):str}});var require_src=__commonJS(function(exports,module){var cursor={to(x,y){if(!y)return`\x1B[${x+1}G`;return`\x1B[${y+1};${x+1}H`},move(x,y){let ret="";if(x<0)ret+=`\x1B[${-x}D`;else if(x>0)ret+=`\x1B[${x}C`;if(y<0)ret+=`\x1B[${-y}A`;else if(y>0)ret+=`\x1B[${y}B`;return ret},up:(count=1)=>`\x1B[${count}A`,down:(count=1)=>`\x1B[${count}B`,forward:(count=1)=>`\x1B[${count}C`,backward:(count=1)=>`\x1B[${count}D`,nextLine:(count=1)=>"\x1B[E".repeat(count),prevLine:(count=1)=>"\x1B[F".repeat(count),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},scroll={up:(count=1)=>"\x1B[S".repeat(count),down:(count=1)=>"\x1B[T".repeat(count)},erase={screen:"\x1B[2J",up:(count=1)=>"\x1B[1J".repeat(count),down:(count=1)=>"\x1B[J".repeat(count),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(count){let clear="";for(let i=0;i<count;i++)clear+=this.line+(i<count-1?cursor.up():"");if(count)clear+=cursor.left;return clear}};module.exports={cursor,scroll,erase,beep:"\x07"}});var require_clear=__commonJS(function(exports,module){function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol<"u"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0,F=function(){};return{s:F,n:function(){if(i>=o.length)return{done:!0};return{done:!1,value:o[i++]}},e:function(_e){throw _e},f:F}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
4
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var normalCompletion=!0,didErr=!1,err;return{s:function(){it=it.call(o)},n:function(){var step=it.next();return normalCompletion=step.done,step},e:function(_e2){didErr=!0,err=_e2},f:function(){try{if(!normalCompletion&&it.return!=null)it.return()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}var strip=require_strip(),_require=require_src(),erase=_require.erase,cursor=_require.cursor,width=(str)=>[...strip(str)].length;module.exports=function(prompt,perLine){if(!perLine)return erase.line+cursor.to(0);let rows=0,lines=prompt.split(/\r?\n/);var _iterator=_createForOfIteratorHelper(lines),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){let line=_step.value;rows+=1+Math.floor(Math.max(width(line)-1,0)/perLine)}}catch(err){_iterator.e(err)}finally{_iterator.f()}return erase.lines(rows)}});var require_figures=__commonJS(function(exports,module){var main={arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",radioOn:"\u25C9",radioOff:"\u25EF",tick:"\u2714",cross:"\u2716",ellipsis:"\u2026",pointerSmall:"\u203A",line:"\u2500",pointer:"\u276F"},win={arrowUp:main.arrowUp,arrowDown:main.arrowDown,arrowLeft:main.arrowLeft,arrowRight:main.arrowRight,radioOn:"(*)",radioOff:"( )",tick:"\u221A",cross:"\xD7",ellipsis:"...",pointerSmall:"\xBB",line:"\u2500",pointer:">"},figures=process.platform==="win32"?win:main;module.exports=figures});var require_style=__commonJS(function(exports,module){var c=require_kleur(),figures=require_figures(),styles=Object.freeze({password:{scale:1,render:(input)=>"*".repeat(input.length)},emoji:{scale:2,render:(input)=>"\uD83D\uDE03".repeat(input.length)},invisible:{scale:0,render:(input)=>""},default:{scale:1,render:(input)=>`${input}`}}),render=(type)=>styles[type]||styles.default,symbols=Object.freeze({aborted:c.red(figures.cross),done:c.green(figures.tick),exited:c.yellow(figures.cross),default:c.cyan("?")}),symbol=(done,aborted,exited)=>aborted?symbols.aborted:exited?symbols.exited:done?symbols.done:symbols.default,delimiter=(completing)=>c.gray(completing?figures.ellipsis:figures.pointerSmall),item=(expandable,expanded)=>c.gray(expandable?expanded?figures.pointerSmall:"+":figures.line);module.exports={styles,render,symbols,symbol,delimiter,item}});var require_lines=__commonJS(function(exports,module){var strip=require_strip();module.exports=function(msg,perLine){let lines=String(strip(msg)||"").split(/\r?\n/);if(!perLine)return lines.length;return lines.map((l)=>Math.ceil(l.length/perLine)).reduce((a,b)=>a+b)}});var require_wrap=__commonJS(function(exports,module){module.exports=(msg,opts={})=>{let tab=Number.isSafeInteger(parseInt(opts.margin))?Array(parseInt(opts.margin)).fill(" ").join(""):opts.margin||"",width=opts.width;return(msg||"").split(/\r?\n/g).map((line)=>line.split(/\s+/g).reduce((arr,w)=>{if(w.length+tab.length>=width||arr[arr.length-1].length+w.length+1<width)arr[arr.length-1]+=` ${w}`;else arr.push(`${tab}${w}`);return arr},[tab]).join(`
|
|
5
|
+
`)).join(`
|
|
6
|
+
`)}});var require_entriesToDisplay=__commonJS(function(exports,module){module.exports=(cursor,total,maxVisible)=>{maxVisible=maxVisible||total;let startIndex=Math.min(total-maxVisible,cursor-Math.floor(maxVisible/2));if(startIndex<0)startIndex=0;let endIndex=Math.min(startIndex+maxVisible,total);return{startIndex,endIndex}}});var require_util=__commonJS(function(exports,module){module.exports={action:require_action(),clear:require_clear(),style:require_style(),strip:require_strip(),figures:require_figures(),lines:require_lines(),wrap:require_wrap(),entriesToDisplay:require_entriesToDisplay()}});var require_prompt=__commonJS(function(exports,module){var readline=__require("readline"),_require=require_util(),action=_require.action,EventEmitter=__require("events"),_require2=require_src(),beep=_require2.beep,cursor=_require2.cursor,color=require_kleur();class Prompt extends EventEmitter{constructor(opts={}){super();this.firstRender=!0,this.in=opts.stdin||process.stdin,this.out=opts.stdout||process.stdout,this.onRender=(opts.onRender||(()=>{return})).bind(this);let rl=readline.createInterface({input:this.in,escapeCodeTimeout:50});if(readline.emitKeypressEvents(this.in,rl),this.in.isTTY)this.in.setRawMode(!0);let isSelect=["SelectPrompt","MultiselectPrompt"].indexOf(this.constructor.name)>-1,keypress=(str,key)=>{let a=action(key,isSelect);if(a===!1)this._&&this._(str,key);else if(typeof this[a]==="function")this[a](key);else this.bell()};this.close=()=>{if(this.out.write(cursor.show),this.in.removeListener("keypress",keypress),this.in.isTTY)this.in.setRawMode(!1);rl.close(),this.emit(this.aborted?"abort":this.exited?"exit":"submit",this.value),this.closed=!0},this.in.on("keypress",keypress)}fire(){this.emit("state",{value:this.value,aborted:!!this.aborted,exited:!!this.exited})}bell(){this.out.write(beep)}render(){if(this.onRender(color),this.firstRender)this.firstRender=!1}}module.exports=Prompt});var require_text=__commonJS(function(exports,module){function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){reject(error);return}if(info.done)resolve(value);else Promise.resolve(value).then(_next,_throw)}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}var color=require_kleur(),Prompt=require_prompt(),_require=require_src(),erase=_require.erase,cursor=_require.cursor,_require2=require_util(),style=_require2.style,clear=_require2.clear,lines=_require2.lines,figures=_require2.figures;class TextPrompt extends Prompt{constructor(opts={}){super(opts);this.transform=style.render(opts.style),this.scale=this.transform.scale,this.msg=opts.message,this.initial=opts.initial||"",this.validator=opts.validate||(()=>!0),this.value="",this.errorMsg=opts.error||"Please Enter A Valid Value",this.cursor=Number(!!this.initial),this.cursorOffset=0,this.clear=clear("",this.out.columns),this.render()}set value(v){if(!v&&this.initial)this.placeholder=!0,this.rendered=color.gray(this.transform.render(this.initial));else this.placeholder=!1,this.rendered=this.transform.render(v);this._value=v,this.fire()}get value(){return this._value}reset(){this.value="",this.cursor=Number(!!this.initial),this.cursorOffset=0,this.fire(),this.render()}exit(){this.abort()}abort(){this.value=this.value||this.initial,this.done=this.aborted=!0,this.error=!1,this.red=!1,this.fire(),this.render(),this.out.write(`
|
|
7
|
+
`),this.close()}validate(){var _this=this;return _asyncToGenerator(function*(){let valid=yield _this.validator(_this.value);if(typeof valid==="string")_this.errorMsg=valid,valid=!1;_this.error=!valid})()}submit(){var _this2=this;return _asyncToGenerator(function*(){if(_this2.value=_this2.value||_this2.initial,_this2.cursorOffset=0,_this2.cursor=_this2.rendered.length,yield _this2.validate(),_this2.error){_this2.red=!0,_this2.fire(),_this2.render();return}_this2.done=!0,_this2.aborted=!1,_this2.fire(),_this2.render(),_this2.out.write(`
|
|
8
|
+
`),_this2.close()})()}next(){if(!this.placeholder)return this.bell();this.value=this.initial,this.cursor=this.rendered.length,this.fire(),this.render()}moveCursor(n){if(this.placeholder)return;this.cursor=this.cursor+n,this.cursorOffset+=n}_(c,key){let s1=this.value.slice(0,this.cursor),s2=this.value.slice(this.cursor);this.value=`${s1}${c}${s2}`,this.red=!1,this.cursor=this.placeholder?0:s1.length+1,this.render()}delete(){if(this.isCursorAtStart())return this.bell();let s1=this.value.slice(0,this.cursor-1),s2=this.value.slice(this.cursor);if(this.value=`${s1}${s2}`,this.red=!1,this.isCursorAtStart())this.cursorOffset=0;else this.cursorOffset++,this.moveCursor(-1);this.render()}deleteForward(){if(this.cursor*this.scale>=this.rendered.length||this.placeholder)return this.bell();let s1=this.value.slice(0,this.cursor),s2=this.value.slice(this.cursor+1);if(this.value=`${s1}${s2}`,this.red=!1,this.isCursorAtEnd())this.cursorOffset=0;else this.cursorOffset++;this.render()}first(){this.cursor=0,this.render()}last(){this.cursor=this.value.length,this.render()}left(){if(this.cursor<=0||this.placeholder)return this.bell();this.moveCursor(-1),this.render()}right(){if(this.cursor*this.scale>=this.rendered.length||this.placeholder)return this.bell();this.moveCursor(1),this.render()}isCursorAtStart(){return this.cursor===0||this.placeholder&&this.cursor===1}isCursorAtEnd(){return this.cursor===this.rendered.length||this.placeholder&&this.cursor===this.rendered.length+1}render(){if(this.closed)return;if(!this.firstRender){if(this.outputError)this.out.write(cursor.down(lines(this.outputError,this.out.columns)-1)+clear(this.outputError,this.out.columns));this.out.write(clear(this.outputText,this.out.columns))}if(super.render(),this.outputError="",this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(this.done),this.red?color.red(this.rendered):this.rendered].join(" "),this.error)this.outputError+=this.errorMsg.split(`
|
|
9
|
+
`).reduce((a,l,i)=>a+`
|
|
10
|
+
${i?" ":figures.pointerSmall} ${color.red().italic(l)}`,"");this.out.write(erase.line+cursor.to(0)+this.outputText+cursor.save+this.outputError+cursor.restore+cursor.move(this.cursorOffset,0))}}module.exports=TextPrompt});var require_select=__commonJS(function(exports,module){var color=require_kleur(),Prompt=require_prompt(),_require=require_util(),style=_require.style,clear=_require.clear,figures=_require.figures,wrap=_require.wrap,entriesToDisplay=_require.entriesToDisplay,_require2=require_src(),cursor=_require2.cursor;class SelectPrompt extends Prompt{constructor(opts={}){super(opts);this.msg=opts.message,this.hint=opts.hint||"- Use arrow-keys. Return to submit.",this.warn=opts.warn||"- This option is disabled",this.cursor=opts.initial||0,this.choices=opts.choices.map((ch,idx)=>{if(typeof ch==="string")ch={title:ch,value:idx};return{title:ch&&(ch.title||ch.value||ch),value:ch&&(ch.value===void 0?idx:ch.value),description:ch&&ch.description,selected:ch&&ch.selected,disabled:ch&&ch.disabled}}),this.optionsPerPage=opts.optionsPerPage||10,this.value=(this.choices[this.cursor]||{}).value,this.clear=clear("",this.out.columns),this.render()}moveCursor(n){this.cursor=n,this.value=this.choices[n].value,this.fire()}reset(){this.moveCursor(0),this.fire(),this.render()}exit(){this.abort()}abort(){this.done=this.aborted=!0,this.fire(),this.render(),this.out.write(`
|
|
11
|
+
`),this.close()}submit(){if(!this.selection.disabled)this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
12
|
+
`),this.close();else this.bell()}first(){this.moveCursor(0),this.render()}last(){this.moveCursor(this.choices.length-1),this.render()}up(){if(this.cursor===0)this.moveCursor(this.choices.length-1);else this.moveCursor(this.cursor-1);this.render()}down(){if(this.cursor===this.choices.length-1)this.moveCursor(0);else this.moveCursor(this.cursor+1);this.render()}next(){this.moveCursor((this.cursor+1)%this.choices.length),this.render()}_(c,key){if(c===" ")return this.submit()}get selection(){return this.choices[this.cursor]}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));super.render();let _entriesToDisplay=entriesToDisplay(this.cursor,this.choices.length,this.optionsPerPage),{startIndex,endIndex}=_entriesToDisplay;if(this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(!1),this.done?this.selection.title:this.selection.disabled?color.yellow(this.warn):color.gray(this.hint)].join(" "),!this.done){this.outputText+=`
|
|
13
|
+
`;for(let i=startIndex;i<endIndex;i++){let title,prefix,desc="",v=this.choices[i];if(i===startIndex&&startIndex>0)prefix=figures.arrowUp;else if(i===endIndex-1&&endIndex<this.choices.length)prefix=figures.arrowDown;else prefix=" ";if(v.disabled)title=this.cursor===i?color.gray().underline(v.title):color.strikethrough().gray(v.title),prefix=(this.cursor===i?color.bold().gray(figures.pointer)+" ":" ")+prefix;else if(title=this.cursor===i?color.cyan().underline(v.title):v.title,prefix=(this.cursor===i?color.cyan(figures.pointer)+" ":" ")+prefix,v.description&&this.cursor===i){if(desc=` - ${v.description}`,prefix.length+title.length+desc.length>=this.out.columns||v.description.split(/\r?\n/).length>1)desc=`
|
|
14
|
+
`+wrap(v.description,{margin:3,width:this.out.columns})}this.outputText+=`${prefix} ${title}${color.gray(desc)}
|
|
15
|
+
`}}this.out.write(this.outputText)}}module.exports=SelectPrompt});var require_toggle=__commonJS(function(exports,module){var color=require_kleur(),Prompt=require_prompt(),_require=require_util(),style=_require.style,clear=_require.clear,_require2=require_src(),cursor=_require2.cursor,erase=_require2.erase;class TogglePrompt extends Prompt{constructor(opts={}){super(opts);this.msg=opts.message,this.value=!!opts.initial,this.active=opts.active||"on",this.inactive=opts.inactive||"off",this.initialValue=this.value,this.render()}reset(){this.value=this.initialValue,this.fire(),this.render()}exit(){this.abort()}abort(){this.done=this.aborted=!0,this.fire(),this.render(),this.out.write(`
|
|
16
|
+
`),this.close()}submit(){this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
17
|
+
`),this.close()}deactivate(){if(this.value===!1)return this.bell();this.value=!1,this.render()}activate(){if(this.value===!0)return this.bell();this.value=!0,this.render()}delete(){this.deactivate()}left(){this.deactivate()}right(){this.activate()}down(){this.deactivate()}up(){this.activate()}next(){this.value=!this.value,this.fire(),this.render()}_(c,key){if(c===" ")this.value=!this.value;else if(c==="1")this.value=!0;else if(c==="0")this.value=!1;else return this.bell();this.render()}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));super.render(),this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(this.done),this.value?this.inactive:color.cyan().underline(this.inactive),color.gray("/"),this.value?color.cyan().underline(this.active):this.active].join(" "),this.out.write(erase.line+cursor.to(0)+this.outputText)}}module.exports=TogglePrompt});var require_datepart=__commonJS(function(exports,module){class DatePart{constructor({token,date,parts,locales}){this.token=token,this.date=date||new Date,this.parts=parts||[this],this.locales=locales||{}}up(){}down(){}next(){let currentIdx=this.parts.indexOf(this);return this.parts.find((part,idx)=>idx>currentIdx&&part instanceof DatePart)}setTo(val){}prev(){let parts=[].concat(this.parts).reverse(),currentIdx=parts.indexOf(this);return parts.find((part,idx)=>idx>currentIdx&&part instanceof DatePart)}toString(){return String(this.date)}}module.exports=DatePart});var require_meridiem=__commonJS(function(exports,module){var DatePart=require_datepart();class Meridiem extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setHours((this.date.getHours()+12)%24)}down(){this.up()}toString(){let meridiem=this.date.getHours()>12?"pm":"am";return/\A/.test(this.token)?meridiem.toUpperCase():meridiem}}module.exports=Meridiem});var require_day=__commonJS(function(exports,module){var DatePart=require_datepart(),pos=(n)=>(n=n%10,n===1?"st":n===2?"nd":n===3?"rd":"th");class Day extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setDate(this.date.getDate()+1)}down(){this.date.setDate(this.date.getDate()-1)}setTo(val){this.date.setDate(parseInt(val.substr(-2)))}toString(){let date=this.date.getDate(),day=this.date.getDay();return this.token==="DD"?String(date).padStart(2,"0"):this.token==="Do"?date+pos(date):this.token==="d"?day+1:this.token==="ddd"?this.locales.weekdaysShort[day]:this.token==="dddd"?this.locales.weekdays[day]:date}}module.exports=Day});var require_hours=__commonJS(function(exports,module){var DatePart=require_datepart();class Hours extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setHours(this.date.getHours()+1)}down(){this.date.setHours(this.date.getHours()-1)}setTo(val){this.date.setHours(parseInt(val.substr(-2)))}toString(){let hours=this.date.getHours();if(/h/.test(this.token))hours=hours%12||12;return this.token.length>1?String(hours).padStart(2,"0"):hours}}module.exports=Hours});var require_milliseconds=__commonJS(function(exports,module){var DatePart=require_datepart();class Milliseconds extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setMilliseconds(this.date.getMilliseconds()+1)}down(){this.date.setMilliseconds(this.date.getMilliseconds()-1)}setTo(val){this.date.setMilliseconds(parseInt(val.substr(-this.token.length)))}toString(){return String(this.date.getMilliseconds()).padStart(4,"0").substr(0,this.token.length)}}module.exports=Milliseconds});var require_minutes=__commonJS(function(exports,module){var DatePart=require_datepart();class Minutes extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setMinutes(this.date.getMinutes()+1)}down(){this.date.setMinutes(this.date.getMinutes()-1)}setTo(val){this.date.setMinutes(parseInt(val.substr(-2)))}toString(){let m=this.date.getMinutes();return this.token.length>1?String(m).padStart(2,"0"):m}}module.exports=Minutes});var require_month=__commonJS(function(exports,module){var DatePart=require_datepart();class Month extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setMonth(this.date.getMonth()+1)}down(){this.date.setMonth(this.date.getMonth()-1)}setTo(val){val=parseInt(val.substr(-2))-1,this.date.setMonth(val<0?0:val)}toString(){let month=this.date.getMonth(),tl=this.token.length;return tl===2?String(month+1).padStart(2,"0"):tl===3?this.locales.monthsShort[month]:tl===4?this.locales.months[month]:String(month+1)}}module.exports=Month});var require_seconds=__commonJS(function(exports,module){var DatePart=require_datepart();class Seconds extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setSeconds(this.date.getSeconds()+1)}down(){this.date.setSeconds(this.date.getSeconds()-1)}setTo(val){this.date.setSeconds(parseInt(val.substr(-2)))}toString(){let s=this.date.getSeconds();return this.token.length>1?String(s).padStart(2,"0"):s}}module.exports=Seconds});var require_year=__commonJS(function(exports,module){var DatePart=require_datepart();class Year extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setFullYear(this.date.getFullYear()+1)}down(){this.date.setFullYear(this.date.getFullYear()-1)}setTo(val){this.date.setFullYear(val.substr(-4))}toString(){let year=String(this.date.getFullYear()).padStart(4,"0");return this.token.length===2?year.substr(-2):year}}module.exports=Year});var require_dateparts=__commonJS(function(exports,module){module.exports={DatePart:require_datepart(),Meridiem:require_meridiem(),Day:require_day(),Hours:require_hours(),Milliseconds:require_milliseconds(),Minutes:require_minutes(),Month:require_month(),Seconds:require_seconds(),Year:require_year()}});var require_date=__commonJS(function(exports,module){function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){reject(error);return}if(info.done)resolve(value);else Promise.resolve(value).then(_next,_throw)}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}var color=require_kleur(),Prompt=require_prompt(),_require=require_util(),style=_require.style,clear=_require.clear,figures=_require.figures,_require2=require_src(),erase=_require2.erase,cursor=_require2.cursor,_require3=require_dateparts(),DatePart=_require3.DatePart,Meridiem=_require3.Meridiem,Day=_require3.Day,Hours=_require3.Hours,Milliseconds=_require3.Milliseconds,Minutes=_require3.Minutes,Month=_require3.Month,Seconds=_require3.Seconds,Year=_require3.Year,regex=/\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g,regexGroups={1:({token})=>token.replace(/\\(.)/g,"$1"),2:(opts)=>new Day(opts),3:(opts)=>new Month(opts),4:(opts)=>new Year(opts),5:(opts)=>new Meridiem(opts),6:(opts)=>new Hours(opts),7:(opts)=>new Minutes(opts),8:(opts)=>new Seconds(opts),9:(opts)=>new Milliseconds(opts)},dfltLocales={months:"January,February,March,April,May,June,July,August,September,October,November,December".split(","),monthsShort:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),weekdaysShort:"Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",")};class DatePrompt extends Prompt{constructor(opts={}){super(opts);this.msg=opts.message,this.cursor=0,this.typed="",this.locales=Object.assign(dfltLocales,opts.locales),this._date=opts.initial||new Date,this.errorMsg=opts.error||"Please Enter A Valid Value",this.validator=opts.validate||(()=>!0),this.mask=opts.mask||"YYYY-MM-DD HH:mm:ss",this.clear=clear("",this.out.columns),this.render()}get value(){return this.date}get date(){return this._date}set date(date){if(date)this._date.setTime(date.getTime())}set mask(mask){let result;this.parts=[];while(result=regex.exec(mask)){let match=result.shift(),idx=result.findIndex((gr)=>gr!=null);this.parts.push(idx in regexGroups?regexGroups[idx]({token:result[idx]||match,date:this.date,parts:this.parts,locales:this.locales}):result[idx]||match)}let parts=this.parts.reduce((arr,i)=>{if(typeof i==="string"&&typeof arr[arr.length-1]==="string")arr[arr.length-1]+=i;else arr.push(i);return arr},[]);this.parts.splice(0),this.parts.push(...parts),this.reset()}moveCursor(n){this.typed="",this.cursor=n,this.fire()}reset(){this.moveCursor(this.parts.findIndex((p)=>p instanceof DatePart)),this.fire(),this.render()}exit(){this.abort()}abort(){this.done=this.aborted=!0,this.error=!1,this.fire(),this.render(),this.out.write(`
|
|
18
|
+
`),this.close()}validate(){var _this=this;return _asyncToGenerator(function*(){let valid=yield _this.validator(_this.value);if(typeof valid==="string")_this.errorMsg=valid,valid=!1;_this.error=!valid})()}submit(){var _this2=this;return _asyncToGenerator(function*(){if(yield _this2.validate(),_this2.error){_this2.color="red",_this2.fire(),_this2.render();return}_this2.done=!0,_this2.aborted=!1,_this2.fire(),_this2.render(),_this2.out.write(`
|
|
19
|
+
`),_this2.close()})()}up(){this.typed="",this.parts[this.cursor].up(),this.render()}down(){this.typed="",this.parts[this.cursor].down(),this.render()}left(){let prev=this.parts[this.cursor].prev();if(prev==null)return this.bell();this.moveCursor(this.parts.indexOf(prev)),this.render()}right(){let next=this.parts[this.cursor].next();if(next==null)return this.bell();this.moveCursor(this.parts.indexOf(next)),this.render()}next(){let next=this.parts[this.cursor].next();this.moveCursor(next?this.parts.indexOf(next):this.parts.findIndex((part)=>part instanceof DatePart)),this.render()}_(c){if(/\d/.test(c))this.typed+=c,this.parts[this.cursor].setTo(this.typed),this.render()}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));if(super.render(),this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(!1),this.parts.reduce((arr,p,idx)=>arr.concat(idx===this.cursor&&!this.done?color.cyan().underline(p.toString()):p),[]).join("")].join(" "),this.error)this.outputText+=this.errorMsg.split(`
|
|
20
|
+
`).reduce((a,l,i)=>a+`
|
|
21
|
+
${i?" ":figures.pointerSmall} ${color.red().italic(l)}`,"");this.out.write(erase.line+cursor.to(0)+this.outputText)}}module.exports=DatePrompt});var require_number=__commonJS(function(exports,module){function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){reject(error);return}if(info.done)resolve(value);else Promise.resolve(value).then(_next,_throw)}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}var color=require_kleur(),Prompt=require_prompt(),_require=require_src(),cursor=_require.cursor,erase=_require.erase,_require2=require_util(),style=_require2.style,figures=_require2.figures,clear=_require2.clear,lines=_require2.lines,isNumber=/[0-9]/,isDef=(any)=>any!==void 0,round=(number,precision)=>{let factor=Math.pow(10,precision);return Math.round(number*factor)/factor};class NumberPrompt extends Prompt{constructor(opts={}){super(opts);this.transform=style.render(opts.style),this.msg=opts.message,this.initial=isDef(opts.initial)?opts.initial:"",this.float=!!opts.float,this.round=opts.round||2,this.inc=opts.increment||1,this.min=isDef(opts.min)?opts.min:-1/0,this.max=isDef(opts.max)?opts.max:1/0,this.errorMsg=opts.error||"Please Enter A Valid Value",this.validator=opts.validate||(()=>!0),this.color="cyan",this.value="",this.typed="",this.lastHit=0,this.render()}set value(v){if(!v&&v!==0)this.placeholder=!0,this.rendered=color.gray(this.transform.render(`${this.initial}`)),this._value="";else this.placeholder=!1,this.rendered=this.transform.render(`${round(v,this.round)}`),this._value=round(v,this.round);this.fire()}get value(){return this._value}parse(x){return this.float?parseFloat(x):parseInt(x)}valid(c){return c==="-"||c==="."&&this.float||isNumber.test(c)}reset(){this.typed="",this.value="",this.fire(),this.render()}exit(){this.abort()}abort(){let x=this.value;this.value=x!==""?x:this.initial,this.done=this.aborted=!0,this.error=!1,this.fire(),this.render(),this.out.write(`
|
|
22
|
+
`),this.close()}validate(){var _this=this;return _asyncToGenerator(function*(){let valid=yield _this.validator(_this.value);if(typeof valid==="string")_this.errorMsg=valid,valid=!1;_this.error=!valid})()}submit(){var _this2=this;return _asyncToGenerator(function*(){if(yield _this2.validate(),_this2.error){_this2.color="red",_this2.fire(),_this2.render();return}let x=_this2.value;_this2.value=x!==""?x:_this2.initial,_this2.done=!0,_this2.aborted=!1,_this2.error=!1,_this2.fire(),_this2.render(),_this2.out.write(`
|
|
23
|
+
`),_this2.close()})()}up(){if(this.typed="",this.value==="")this.value=this.min-this.inc;if(this.value>=this.max)return this.bell();this.value+=this.inc,this.color="cyan",this.fire(),this.render()}down(){if(this.typed="",this.value==="")this.value=this.min+this.inc;if(this.value<=this.min)return this.bell();this.value-=this.inc,this.color="cyan",this.fire(),this.render()}delete(){let val=this.value.toString();if(val.length===0)return this.bell();if(this.value=this.parse(val=val.slice(0,-1))||"",this.value!==""&&this.value<this.min)this.value=this.min;this.color="cyan",this.fire(),this.render()}next(){this.value=this.initial,this.fire(),this.render()}_(c,key){if(!this.valid(c))return this.bell();let now=Date.now();if(now-this.lastHit>1000)this.typed="";if(this.typed+=c,this.lastHit=now,this.color="cyan",c===".")return this.fire();if(this.value=Math.min(this.parse(this.typed),this.max),this.value>this.max)this.value=this.max;if(this.value<this.min)this.value=this.min;this.fire(),this.render()}render(){if(this.closed)return;if(!this.firstRender){if(this.outputError)this.out.write(cursor.down(lines(this.outputError,this.out.columns)-1)+clear(this.outputError,this.out.columns));this.out.write(clear(this.outputText,this.out.columns))}if(super.render(),this.outputError="",this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(this.done),!this.done||!this.done&&!this.placeholder?color[this.color]().underline(this.rendered):this.rendered].join(" "),this.error)this.outputError+=this.errorMsg.split(`
|
|
24
|
+
`).reduce((a,l,i)=>a+`
|
|
25
|
+
${i?" ":figures.pointerSmall} ${color.red().italic(l)}`,"");this.out.write(erase.line+cursor.to(0)+this.outputText+cursor.save+this.outputError+cursor.restore)}}module.exports=NumberPrompt});var require_multiselect=__commonJS(function(exports,module){var color=require_kleur(),_require=require_src(),cursor=_require.cursor,Prompt=require_prompt(),_require2=require_util(),clear=_require2.clear,figures=_require2.figures,style=_require2.style,wrap=_require2.wrap,entriesToDisplay=_require2.entriesToDisplay;class MultiselectPrompt extends Prompt{constructor(opts={}){super(opts);if(this.msg=opts.message,this.cursor=opts.cursor||0,this.scrollIndex=opts.cursor||0,this.hint=opts.hint||"",this.warn=opts.warn||"- This option is disabled -",this.minSelected=opts.min,this.showMinError=!1,this.maxChoices=opts.max,this.instructions=opts.instructions,this.optionsPerPage=opts.optionsPerPage||10,this.value=opts.choices.map((ch,idx)=>{if(typeof ch==="string")ch={title:ch,value:idx};return{title:ch&&(ch.title||ch.value||ch),description:ch&&ch.description,value:ch&&(ch.value===void 0?idx:ch.value),selected:ch&&ch.selected,disabled:ch&&ch.disabled}}),this.clear=clear("",this.out.columns),!opts.overrideRender)this.render()}reset(){this.value.map((v)=>!v.selected),this.cursor=0,this.fire(),this.render()}selected(){return this.value.filter((v)=>v.selected)}exit(){this.abort()}abort(){this.done=this.aborted=!0,this.fire(),this.render(),this.out.write(`
|
|
26
|
+
`),this.close()}submit(){let selected=this.value.filter((e)=>e.selected);if(this.minSelected&&selected.length<this.minSelected)this.showMinError=!0,this.render();else this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
27
|
+
`),this.close()}first(){this.cursor=0,this.render()}last(){this.cursor=this.value.length-1,this.render()}next(){this.cursor=(this.cursor+1)%this.value.length,this.render()}up(){if(this.cursor===0)this.cursor=this.value.length-1;else this.cursor--;this.render()}down(){if(this.cursor===this.value.length-1)this.cursor=0;else this.cursor++;this.render()}left(){this.value[this.cursor].selected=!1,this.render()}right(){if(this.value.filter((e)=>e.selected).length>=this.maxChoices)return this.bell();this.value[this.cursor].selected=!0,this.render()}handleSpaceToggle(){let v=this.value[this.cursor];if(v.selected)v.selected=!1,this.render();else if(v.disabled||this.value.filter((e)=>e.selected).length>=this.maxChoices)return this.bell();else v.selected=!0,this.render()}toggleAll(){if(this.maxChoices!==void 0||this.value[this.cursor].disabled)return this.bell();let newSelected=!this.value[this.cursor].selected;this.value.filter((v)=>!v.disabled).forEach((v)=>v.selected=newSelected),this.render()}_(c,key){if(c===" ")this.handleSpaceToggle();else if(c==="a")this.toggleAll();else return this.bell()}renderInstructions(){if(this.instructions===void 0||this.instructions){if(typeof this.instructions==="string")return this.instructions;return`
|
|
28
|
+
Instructions:
|
|
29
|
+
${figures.arrowUp}/${figures.arrowDown}: Highlight option
|
|
30
|
+
${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
|
|
31
|
+
`+(this.maxChoices===void 0?` a: Toggle all
|
|
32
|
+
`:"")+" enter/return: Complete answer"}return""}renderOption(cursor,v,i,arrowIndicator){let prefix=(v.selected?color.green(figures.radioOn):figures.radioOff)+" "+arrowIndicator+" ",title,desc;if(v.disabled)title=cursor===i?color.gray().underline(v.title):color.strikethrough().gray(v.title);else if(title=cursor===i?color.cyan().underline(v.title):v.title,cursor===i&&v.description){if(desc=` - ${v.description}`,prefix.length+title.length+desc.length>=this.out.columns||v.description.split(/\r?\n/).length>1)desc=`
|
|
33
|
+
`+wrap(v.description,{margin:prefix.length,width:this.out.columns})}return prefix+title+color.gray(desc||"")}paginateOptions(options){if(options.length===0)return color.red("No matches for this query.");let _entriesToDisplay=entriesToDisplay(this.cursor,options.length,this.optionsPerPage),{startIndex,endIndex}=_entriesToDisplay,prefix,styledOptions=[];for(let i=startIndex;i<endIndex;i++){if(i===startIndex&&startIndex>0)prefix=figures.arrowUp;else if(i===endIndex-1&&endIndex<options.length)prefix=figures.arrowDown;else prefix=" ";styledOptions.push(this.renderOption(this.cursor,options[i],i,prefix))}return`
|
|
34
|
+
`+styledOptions.join(`
|
|
35
|
+
`)}renderOptions(options){if(!this.done)return this.paginateOptions(options);return""}renderDoneOrInstructions(){if(this.done)return this.value.filter((e)=>e.selected).map((v)=>v.title).join(", ");let output=[color.gray(this.hint),this.renderInstructions()];if(this.value[this.cursor].disabled)output.push(color.yellow(this.warn));return output.join(" ")}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);super.render();let prompt=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(!1),this.renderDoneOrInstructions()].join(" ");if(this.showMinError)prompt+=color.red(`You must select a minimum of ${this.minSelected} choices.`),this.showMinError=!1;prompt+=this.renderOptions(this.value),this.out.write(this.clear+prompt),this.clear=clear(prompt,this.out.columns)}}module.exports=MultiselectPrompt});var require_autocomplete=__commonJS(function(exports,module){function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){reject(error);return}if(info.done)resolve(value);else Promise.resolve(value).then(_next,_throw)}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}var color=require_kleur(),Prompt=require_prompt(),_require=require_src(),erase=_require.erase,cursor=_require.cursor,_require2=require_util(),style=_require2.style,clear=_require2.clear,figures=_require2.figures,wrap=_require2.wrap,entriesToDisplay=_require2.entriesToDisplay,getVal=(arr,i)=>arr[i]&&(arr[i].value||arr[i].title||arr[i]),getTitle=(arr,i)=>arr[i]&&(arr[i].title||arr[i].value||arr[i]),getIndex=(arr,valOrTitle)=>{let index=arr.findIndex((el)=>el.value===valOrTitle||el.title===valOrTitle);return index>-1?index:void 0};class AutocompletePrompt extends Prompt{constructor(opts={}){super(opts);this.msg=opts.message,this.suggest=opts.suggest,this.choices=opts.choices,this.initial=typeof opts.initial==="number"?opts.initial:getIndex(opts.choices,opts.initial),this.select=this.initial||opts.cursor||0,this.i18n={noMatches:opts.noMatches||"no matches found"},this.fallback=opts.fallback||this.initial,this.clearFirst=opts.clearFirst||!1,this.suggestions=[],this.input="",this.limit=opts.limit||10,this.cursor=0,this.transform=style.render(opts.style),this.scale=this.transform.scale,this.render=this.render.bind(this),this.complete=this.complete.bind(this),this.clear=clear("",this.out.columns),this.complete(this.render),this.render()}set fallback(fb){this._fb=Number.isSafeInteger(parseInt(fb))?parseInt(fb):fb}get fallback(){let choice;if(typeof this._fb==="number")choice=this.choices[this._fb];else if(typeof this._fb==="string")choice={title:this._fb};return choice||this._fb||{title:this.i18n.noMatches}}moveSelect(i){if(this.select=i,this.suggestions.length>0)this.value=getVal(this.suggestions,i);else this.value=this.fallback.value;this.fire()}complete(cb){var _this=this;return _asyncToGenerator(function*(){let p=_this.completing=_this.suggest(_this.input,_this.choices),suggestions=yield p;if(_this.completing!==p)return;_this.suggestions=suggestions.map((s,i,arr)=>({title:getTitle(arr,i),value:getVal(arr,i),description:s.description})),_this.completing=!1;let l=Math.max(suggestions.length-1,0);_this.moveSelect(Math.min(l,_this.select)),cb&&cb()})()}reset(){this.input="",this.complete(()=>{this.moveSelect(this.initial!==void 0?this.initial:0),this.render()}),this.render()}exit(){if(this.clearFirst&&this.input.length>0)this.reset();else this.done=this.exited=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
36
|
+
`),this.close()}abort(){this.done=this.aborted=!0,this.exited=!1,this.fire(),this.render(),this.out.write(`
|
|
37
|
+
`),this.close()}submit(){this.done=!0,this.aborted=this.exited=!1,this.fire(),this.render(),this.out.write(`
|
|
38
|
+
`),this.close()}_(c,key){let s1=this.input.slice(0,this.cursor),s2=this.input.slice(this.cursor);this.input=`${s1}${c}${s2}`,this.cursor=s1.length+1,this.complete(this.render),this.render()}delete(){if(this.cursor===0)return this.bell();let s1=this.input.slice(0,this.cursor-1),s2=this.input.slice(this.cursor);this.input=`${s1}${s2}`,this.complete(this.render),this.cursor=this.cursor-1,this.render()}deleteForward(){if(this.cursor*this.scale>=this.rendered.length)return this.bell();let s1=this.input.slice(0,this.cursor),s2=this.input.slice(this.cursor+1);this.input=`${s1}${s2}`,this.complete(this.render),this.render()}first(){this.moveSelect(0),this.render()}last(){this.moveSelect(this.suggestions.length-1),this.render()}up(){if(this.select===0)this.moveSelect(this.suggestions.length-1);else this.moveSelect(this.select-1);this.render()}down(){if(this.select===this.suggestions.length-1)this.moveSelect(0);else this.moveSelect(this.select+1);this.render()}next(){if(this.select===this.suggestions.length-1)this.moveSelect(0);else this.moveSelect(this.select+1);this.render()}nextPage(){this.moveSelect(Math.min(this.select+this.limit,this.suggestions.length-1)),this.render()}prevPage(){this.moveSelect(Math.max(this.select-this.limit,0)),this.render()}left(){if(this.cursor<=0)return this.bell();this.cursor=this.cursor-1,this.render()}right(){if(this.cursor*this.scale>=this.rendered.length)return this.bell();this.cursor=this.cursor+1,this.render()}renderOption(v,hovered,isStart,isEnd){let desc,prefix=isStart?figures.arrowUp:isEnd?figures.arrowDown:" ",title=hovered?color.cyan().underline(v.title):v.title;if(prefix=(hovered?color.cyan(figures.pointer)+" ":" ")+prefix,v.description){if(desc=` - ${v.description}`,prefix.length+title.length+desc.length>=this.out.columns||v.description.split(/\r?\n/).length>1)desc=`
|
|
39
|
+
`+wrap(v.description,{margin:3,width:this.out.columns})}return prefix+" "+title+color.gray(desc||"")}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));super.render();let _entriesToDisplay=entriesToDisplay(this.select,this.choices.length,this.limit),{startIndex,endIndex}=_entriesToDisplay;if(this.outputText=[style.symbol(this.done,this.aborted,this.exited),color.bold(this.msg),style.delimiter(this.completing),this.done&&this.suggestions[this.select]?this.suggestions[this.select].title:this.rendered=this.transform.render(this.input)].join(" "),!this.done){let suggestions=this.suggestions.slice(startIndex,endIndex).map((item,i)=>this.renderOption(item,this.select===i+startIndex,i===0&&startIndex>0,i+startIndex===endIndex-1&&endIndex<this.choices.length)).join(`
|
|
40
|
+
`);this.outputText+=`
|
|
41
|
+
`+(suggestions||color.gray(this.fallback.title))}this.out.write(erase.line+cursor.to(0)+this.outputText)}}module.exports=AutocompletePrompt});var require_autocompleteMultiselect=__commonJS(function(exports,module){var color=require_kleur(),_require=require_src(),cursor=_require.cursor,MultiselectPrompt=require_multiselect(),_require2=require_util(),clear=_require2.clear,style=_require2.style,figures=_require2.figures;class AutocompleteMultiselectPrompt extends MultiselectPrompt{constructor(opts={}){opts.overrideRender=!0;super(opts);this.inputValue="",this.clear=clear("",this.out.columns),this.filteredOptions=this.value,this.render()}last(){this.cursor=this.filteredOptions.length-1,this.render()}next(){this.cursor=(this.cursor+1)%this.filteredOptions.length,this.render()}up(){if(this.cursor===0)this.cursor=this.filteredOptions.length-1;else this.cursor--;this.render()}down(){if(this.cursor===this.filteredOptions.length-1)this.cursor=0;else this.cursor++;this.render()}left(){this.filteredOptions[this.cursor].selected=!1,this.render()}right(){if(this.value.filter((e)=>e.selected).length>=this.maxChoices)return this.bell();this.filteredOptions[this.cursor].selected=!0,this.render()}delete(){if(this.inputValue.length)this.inputValue=this.inputValue.substr(0,this.inputValue.length-1),this.updateFilteredOptions()}updateFilteredOptions(){let currentHighlight=this.filteredOptions[this.cursor];this.filteredOptions=this.value.filter((v)=>{if(this.inputValue){if(typeof v.title==="string"){if(v.title.toLowerCase().includes(this.inputValue.toLowerCase()))return!0}if(typeof v.value==="string"){if(v.value.toLowerCase().includes(this.inputValue.toLowerCase()))return!0}return!1}return!0});let newHighlightIndex=this.filteredOptions.findIndex((v)=>v===currentHighlight);this.cursor=newHighlightIndex<0?0:newHighlightIndex,this.render()}handleSpaceToggle(){let v=this.filteredOptions[this.cursor];if(v.selected)v.selected=!1,this.render();else if(v.disabled||this.value.filter((e)=>e.selected).length>=this.maxChoices)return this.bell();else v.selected=!0,this.render()}handleInputChange(c){this.inputValue=this.inputValue+c,this.updateFilteredOptions()}_(c,key){if(c===" ")this.handleSpaceToggle();else this.handleInputChange(c)}renderInstructions(){if(this.instructions===void 0||this.instructions){if(typeof this.instructions==="string")return this.instructions;return`
|
|
42
|
+
Instructions:
|
|
43
|
+
${figures.arrowUp}/${figures.arrowDown}: Highlight option
|
|
44
|
+
${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
|
|
45
|
+
[a,b,c]/delete: Filter choices
|
|
46
|
+
enter/return: Complete answer
|
|
47
|
+
`}return""}renderCurrentInput(){return`
|
|
48
|
+
Filtered results for: ${this.inputValue?this.inputValue:color.gray("Enter something to filter")}
|
|
49
|
+
`}renderOption(cursor,v,i){let title;if(v.disabled)title=cursor===i?color.gray().underline(v.title):color.strikethrough().gray(v.title);else title=cursor===i?color.cyan().underline(v.title):v.title;return(v.selected?color.green(figures.radioOn):figures.radioOff)+" "+title}renderDoneOrInstructions(){if(this.done)return this.value.filter((e)=>e.selected).map((v)=>v.title).join(", ");let output=[color.gray(this.hint),this.renderInstructions(),this.renderCurrentInput()];if(this.filteredOptions.length&&this.filteredOptions[this.cursor].disabled)output.push(color.yellow(this.warn));return output.join(" ")}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);super.render();let prompt=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(!1),this.renderDoneOrInstructions()].join(" ");if(this.showMinError)prompt+=color.red(`You must select a minimum of ${this.minSelected} choices.`),this.showMinError=!1;prompt+=this.renderOptions(this.filteredOptions),this.out.write(this.clear+prompt),this.clear=clear(prompt,this.out.columns)}}module.exports=AutocompleteMultiselectPrompt});var require_confirm=__commonJS(function(exports,module){var color=require_kleur(),Prompt=require_prompt(),_require=require_util(),style=_require.style,clear=_require.clear,_require2=require_src(),erase=_require2.erase,cursor=_require2.cursor;class ConfirmPrompt extends Prompt{constructor(opts={}){super(opts);this.msg=opts.message,this.value=opts.initial,this.initialValue=!!opts.initial,this.yesMsg=opts.yes||"yes",this.yesOption=opts.yesOption||"(Y/n)",this.noMsg=opts.no||"no",this.noOption=opts.noOption||"(y/N)",this.render()}reset(){this.value=this.initialValue,this.fire(),this.render()}exit(){this.abort()}abort(){this.done=this.aborted=!0,this.fire(),this.render(),this.out.write(`
|
|
50
|
+
`),this.close()}submit(){this.value=this.value||!1,this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
51
|
+
`),this.close()}_(c,key){if(c.toLowerCase()==="y")return this.value=!0,this.submit();if(c.toLowerCase()==="n")return this.value=!1,this.submit();return this.bell()}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));super.render(),this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(this.done),this.done?this.value?this.yesMsg:this.noMsg:color.gray(this.initialValue?this.yesOption:this.noOption)].join(" "),this.out.write(erase.line+cursor.to(0)+this.outputText)}}module.exports=ConfirmPrompt});var require_elements=__commonJS(function(exports,module){module.exports={TextPrompt:require_text(),SelectPrompt:require_select(),TogglePrompt:require_toggle(),DatePrompt:require_date(),NumberPrompt:require_number(),MultiselectPrompt:require_multiselect(),AutocompletePrompt:require_autocomplete(),AutocompleteMultiselectPrompt:require_autocompleteMultiselect(),ConfirmPrompt:require_confirm()}});var require_prompts=__commonJS(function(exports){var $=exports,el=require_elements(),noop=(v)=>v;function toPrompt(type,args,opts={}){return new Promise((res,rej)=>{let p=new el[type](args),onAbort=opts.onAbort||noop,onSubmit=opts.onSubmit||noop,onExit=opts.onExit||noop;p.on("state",args.onState||noop),p.on("submit",(x)=>res(onSubmit(x))),p.on("exit",(x)=>res(onExit(x))),p.on("abort",(x)=>rej(onAbort(x)))})}$.text=(args)=>toPrompt("TextPrompt",args);$.password=(args)=>(args.style="password",$.text(args));$.invisible=(args)=>(args.style="invisible",$.text(args));$.number=(args)=>toPrompt("NumberPrompt",args);$.date=(args)=>toPrompt("DatePrompt",args);$.confirm=(args)=>toPrompt("ConfirmPrompt",args);$.list=(args)=>{let sep=args.separator||",";return toPrompt("TextPrompt",args,{onSubmit:(str)=>str.split(sep).map((s)=>s.trim())})};$.toggle=(args)=>toPrompt("TogglePrompt",args);$.select=(args)=>toPrompt("SelectPrompt",args);$.multiselect=(args)=>{args.choices=[].concat(args.choices||[]);let toSelected=(items)=>items.filter((item)=>item.selected).map((item)=>item.value);return toPrompt("MultiselectPrompt",args,{onAbort:toSelected,onSubmit:toSelected})};$.autocompleteMultiselect=(args)=>{args.choices=[].concat(args.choices||[]);let toSelected=(items)=>items.filter((item)=>item.selected).map((item)=>item.value);return toPrompt("AutocompleteMultiselectPrompt",args,{onAbort:toSelected,onSubmit:toSelected})};var byTitle=(input,choices)=>Promise.resolve(choices.filter((item)=>item.title.slice(0,input.length).toLowerCase()===input.toLowerCase()));$.autocomplete=(args)=>(args.suggest=args.suggest||byTitle,args.choices=[].concat(args.choices||[]),toPrompt("AutocompletePrompt",args))});var require_dist=__commonJS(function(exports,module){function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable});keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2)ownKeys(Object(source),!0).forEach(function(key){_defineProperty(target,key,source[key])});else if(Object.getOwnPropertyDescriptors)Object.defineProperties(target,Object.getOwnPropertyDescriptors(source));else ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}return target}function _defineProperty(obj,key,value){if(key in obj)Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0});else obj[key]=value;return obj}function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol<"u"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0,F=function(){};return{s:F,n:function(){if(i>=o.length)return{done:!0};return{done:!1,value:o[i++]}},e:function(_e){throw _e},f:F}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
52
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var normalCompletion=!0,didErr=!1,err;return{s:function(){it=it.call(o)},n:function(){var step=it.next();return normalCompletion=step.done,step},e:function(_e2){didErr=!0,err=_e2},f:function(){try{if(!normalCompletion&&it.return!=null)it.return()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){reject(error);return}if(info.done)resolve(value);else Promise.resolve(value).then(_next,_throw)}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)})}}var prompts=require_prompts(),passOn=["suggest","format","onState","validate","onRender","type"],noop=()=>{};function prompt(){return _prompt.apply(this,arguments)}function _prompt(){return _prompt=_asyncToGenerator(function*(questions=[],{onSubmit=noop,onCancel=noop}={}){let answers={},override=prompt._override||{};questions=[].concat(questions);let answer,question,quit,name,type,lastPrompt,getFormattedAnswer=function(){var _ref=_asyncToGenerator(function*(question,answer,skipValidation=!1){if(!skipValidation&&question.validate&&question.validate(answer)!==!0)return;return question.format?yield question.format(answer,answers):answer});return function(_x,_x2){return _ref.apply(this,arguments)}}();var _iterator=_createForOfIteratorHelper(questions),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){question=_step.value;var _question=question;if(name=_question.name,type=_question.type,typeof type==="function")type=yield type(answer,_objectSpread({},answers),question),question.type=type;if(!type)continue;for(let key in question){if(passOn.includes(key))continue;let value=question[key];question[key]=typeof value==="function"?yield value(answer,_objectSpread({},answers),lastPrompt):value}if(lastPrompt=question,typeof question.message!=="string")throw Error("prompt message is required");var _question2=question;if(name=_question2.name,type=_question2.type,prompts[type]===void 0)throw Error(`prompt type (${type}) is not defined`);if(override[question.name]!==void 0){if(answer=yield getFormattedAnswer(question,override[question.name]),answer!==void 0){answers[name]=answer;continue}}try{answer=prompt._injected?getInjectedAnswer(prompt._injected,question.initial):yield prompts[type](question),answers[name]=answer=yield getFormattedAnswer(question,answer,!0),quit=yield onSubmit(question,answer,answers)}catch(err){quit=!(yield onCancel(question,answers))}if(quit)return answers}}catch(err){_iterator.e(err)}finally{_iterator.f()}return answers}),_prompt.apply(this,arguments)}function getInjectedAnswer(injected,deafultValue){let answer=injected.shift();if(answer instanceof Error)throw answer;return answer===void 0?deafultValue:answer}function inject(answers){prompt._injected=(prompt._injected||[]).concat(answers)}function override(answers){prompt._override=Object.assign({},answers)}module.exports=Object.assign(prompt,{prompt,prompts,inject,override})});var require_action2=__commonJS(function(exports,module){module.exports=(key,isSelect)=>{if(key.meta&&key.name!=="escape")return;if(key.ctrl){if(key.name==="a")return"first";if(key.name==="c")return"abort";if(key.name==="d")return"abort";if(key.name==="e")return"last";if(key.name==="g")return"reset"}if(isSelect){if(key.name==="j")return"down";if(key.name==="k")return"up"}if(key.name==="return")return"submit";if(key.name==="enter")return"submit";if(key.name==="backspace")return"delete";if(key.name==="delete")return"deleteForward";if(key.name==="abort")return"abort";if(key.name==="escape")return"exit";if(key.name==="tab")return"next";if(key.name==="pagedown")return"nextPage";if(key.name==="pageup")return"prevPage";if(key.name==="home")return"home";if(key.name==="end")return"end";if(key.name==="up")return"up";if(key.name==="down")return"down";if(key.name==="right")return"right";if(key.name==="left")return"left";return!1}});var require_strip2=__commonJS(function(exports,module){module.exports=(str)=>{let pattern=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|"),RGX=new RegExp(pattern,"g");return typeof str==="string"?str.replace(RGX,""):str}});var require_clear2=__commonJS(function(exports,module){var strip=require_strip2(),{erase,cursor}=require_src(),width=(str)=>[...strip(str)].length;module.exports=function(prompt,perLine){if(!perLine)return erase.line+cursor.to(0);let rows=0,lines=prompt.split(/\r?\n/);for(let line of lines)rows+=1+Math.floor(Math.max(width(line)-1,0)/perLine);return erase.lines(rows)}});var require_figures2=__commonJS(function(exports,module){var main={arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",radioOn:"\u25C9",radioOff:"\u25EF",tick:"\u2714",cross:"\u2716",ellipsis:"\u2026",pointerSmall:"\u203A",line:"\u2500",pointer:"\u276F"},win={arrowUp:main.arrowUp,arrowDown:main.arrowDown,arrowLeft:main.arrowLeft,arrowRight:main.arrowRight,radioOn:"(*)",radioOff:"( )",tick:"\u221A",cross:"\xD7",ellipsis:"...",pointerSmall:"\xBB",line:"\u2500",pointer:">"},figures=process.platform==="win32"?win:main;module.exports=figures});var require_style2=__commonJS(function(exports,module){var c=require_kleur(),figures=require_figures2(),styles=Object.freeze({password:{scale:1,render:(input)=>"*".repeat(input.length)},emoji:{scale:2,render:(input)=>"\uD83D\uDE03".repeat(input.length)},invisible:{scale:0,render:(input)=>""},default:{scale:1,render:(input)=>`${input}`}}),render=(type)=>styles[type]||styles.default,symbols=Object.freeze({aborted:c.red(figures.cross),done:c.green(figures.tick),exited:c.yellow(figures.cross),default:c.cyan("?")}),symbol=(done,aborted,exited)=>aborted?symbols.aborted:exited?symbols.exited:done?symbols.done:symbols.default,delimiter=(completing)=>c.gray(completing?figures.ellipsis:figures.pointerSmall),item=(expandable,expanded)=>c.gray(expandable?expanded?figures.pointerSmall:"+":figures.line);module.exports={styles,render,symbols,symbol,delimiter,item}});var require_lines2=__commonJS(function(exports,module){var strip=require_strip2();module.exports=function(msg,perLine){let lines=String(strip(msg)||"").split(/\r?\n/);if(!perLine)return lines.length;return lines.map((l)=>Math.ceil(l.length/perLine)).reduce((a,b)=>a+b)}});var require_wrap2=__commonJS(function(exports,module){module.exports=(msg,opts={})=>{let tab=Number.isSafeInteger(parseInt(opts.margin))?Array(parseInt(opts.margin)).fill(" ").join(""):opts.margin||"",width=opts.width;return(msg||"").split(/\r?\n/g).map((line)=>line.split(/\s+/g).reduce((arr,w)=>{if(w.length+tab.length>=width||arr[arr.length-1].length+w.length+1<width)arr[arr.length-1]+=` ${w}`;else arr.push(`${tab}${w}`);return arr},[tab]).join(`
|
|
53
|
+
`)).join(`
|
|
54
|
+
`)}});var require_entriesToDisplay2=__commonJS(function(exports,module){module.exports=(cursor,total,maxVisible)=>{maxVisible=maxVisible||total;let startIndex=Math.min(total-maxVisible,cursor-Math.floor(maxVisible/2));if(startIndex<0)startIndex=0;let endIndex=Math.min(startIndex+maxVisible,total);return{startIndex,endIndex}}});var require_util2=__commonJS(function(exports,module){module.exports={action:require_action2(),clear:require_clear2(),style:require_style2(),strip:require_strip2(),figures:require_figures2(),lines:require_lines2(),wrap:require_wrap2(),entriesToDisplay:require_entriesToDisplay2()}});var require_prompt2=__commonJS(function(exports,module){var readline=__require("readline"),{action}=require_util2(),EventEmitter=__require("events"),{beep,cursor}=require_src(),color=require_kleur();class Prompt extends EventEmitter{constructor(opts={}){super();this.firstRender=!0,this.in=opts.stdin||process.stdin,this.out=opts.stdout||process.stdout,this.onRender=(opts.onRender||(()=>{return})).bind(this);let rl=readline.createInterface({input:this.in,escapeCodeTimeout:50});if(readline.emitKeypressEvents(this.in,rl),this.in.isTTY)this.in.setRawMode(!0);let isSelect=["SelectPrompt","MultiselectPrompt"].indexOf(this.constructor.name)>-1,keypress=(str,key)=>{let a=action(key,isSelect);if(a===!1)this._&&this._(str,key);else if(typeof this[a]==="function")this[a](key);else this.bell()};this.close=()=>{if(this.out.write(cursor.show),this.in.removeListener("keypress",keypress),this.in.isTTY)this.in.setRawMode(!1);rl.close(),this.emit(this.aborted?"abort":this.exited?"exit":"submit",this.value),this.closed=!0},this.in.on("keypress",keypress)}fire(){this.emit("state",{value:this.value,aborted:!!this.aborted,exited:!!this.exited})}bell(){this.out.write(beep)}render(){if(this.onRender(color),this.firstRender)this.firstRender=!1}}module.exports=Prompt});var require_text2=__commonJS(function(exports,module){var color=require_kleur(),Prompt=require_prompt2(),{erase,cursor}=require_src(),{style,clear,lines,figures}=require_util2();class TextPrompt extends Prompt{constructor(opts={}){super(opts);this.transform=style.render(opts.style),this.scale=this.transform.scale,this.msg=opts.message,this.initial=opts.initial||"",this.validator=opts.validate||(()=>!0),this.value="",this.errorMsg=opts.error||"Please Enter A Valid Value",this.cursor=Number(!!this.initial),this.cursorOffset=0,this.clear=clear("",this.out.columns),this.render()}set value(v){if(!v&&this.initial)this.placeholder=!0,this.rendered=color.gray(this.transform.render(this.initial));else this.placeholder=!1,this.rendered=this.transform.render(v);this._value=v,this.fire()}get value(){return this._value}reset(){this.value="",this.cursor=Number(!!this.initial),this.cursorOffset=0,this.fire(),this.render()}exit(){this.abort()}abort(){this.value=this.value||this.initial,this.done=this.aborted=!0,this.error=!1,this.red=!1,this.fire(),this.render(),this.out.write(`
|
|
55
|
+
`),this.close()}async validate(){let valid=await this.validator(this.value);if(typeof valid==="string")this.errorMsg=valid,valid=!1;this.error=!valid}async submit(){if(this.value=this.value||this.initial,this.cursorOffset=0,this.cursor=this.rendered.length,await this.validate(),this.error){this.red=!0,this.fire(),this.render();return}this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
56
|
+
`),this.close()}next(){if(!this.placeholder)return this.bell();this.value=this.initial,this.cursor=this.rendered.length,this.fire(),this.render()}moveCursor(n){if(this.placeholder)return;this.cursor=this.cursor+n,this.cursorOffset+=n}_(c,key){let s1=this.value.slice(0,this.cursor),s2=this.value.slice(this.cursor);this.value=`${s1}${c}${s2}`,this.red=!1,this.cursor=this.placeholder?0:s1.length+1,this.render()}delete(){if(this.isCursorAtStart())return this.bell();let s1=this.value.slice(0,this.cursor-1),s2=this.value.slice(this.cursor);if(this.value=`${s1}${s2}`,this.red=!1,this.isCursorAtStart())this.cursorOffset=0;else this.cursorOffset++,this.moveCursor(-1);this.render()}deleteForward(){if(this.cursor*this.scale>=this.rendered.length||this.placeholder)return this.bell();let s1=this.value.slice(0,this.cursor),s2=this.value.slice(this.cursor+1);if(this.value=`${s1}${s2}`,this.red=!1,this.isCursorAtEnd())this.cursorOffset=0;else this.cursorOffset++;this.render()}first(){this.cursor=0,this.render()}last(){this.cursor=this.value.length,this.render()}left(){if(this.cursor<=0||this.placeholder)return this.bell();this.moveCursor(-1),this.render()}right(){if(this.cursor*this.scale>=this.rendered.length||this.placeholder)return this.bell();this.moveCursor(1),this.render()}isCursorAtStart(){return this.cursor===0||this.placeholder&&this.cursor===1}isCursorAtEnd(){return this.cursor===this.rendered.length||this.placeholder&&this.cursor===this.rendered.length+1}render(){if(this.closed)return;if(!this.firstRender){if(this.outputError)this.out.write(cursor.down(lines(this.outputError,this.out.columns)-1)+clear(this.outputError,this.out.columns));this.out.write(clear(this.outputText,this.out.columns))}if(super.render(),this.outputError="",this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(this.done),this.red?color.red(this.rendered):this.rendered].join(" "),this.error)this.outputError+=this.errorMsg.split(`
|
|
57
|
+
`).reduce((a,l,i)=>a+`
|
|
58
|
+
${i?" ":figures.pointerSmall} ${color.red().italic(l)}`,"");this.out.write(erase.line+cursor.to(0)+this.outputText+cursor.save+this.outputError+cursor.restore+cursor.move(this.cursorOffset,0))}}module.exports=TextPrompt});var require_select2=__commonJS(function(exports,module){var color=require_kleur(),Prompt=require_prompt2(),{style,clear,figures,wrap,entriesToDisplay}=require_util2(),{cursor}=require_src();class SelectPrompt extends Prompt{constructor(opts={}){super(opts);this.msg=opts.message,this.hint=opts.hint||"- Use arrow-keys. Return to submit.",this.warn=opts.warn||"- This option is disabled",this.cursor=opts.initial||0,this.choices=opts.choices.map((ch,idx)=>{if(typeof ch==="string")ch={title:ch,value:idx};return{title:ch&&(ch.title||ch.value||ch),value:ch&&(ch.value===void 0?idx:ch.value),description:ch&&ch.description,selected:ch&&ch.selected,disabled:ch&&ch.disabled}}),this.optionsPerPage=opts.optionsPerPage||10,this.value=(this.choices[this.cursor]||{}).value,this.clear=clear("",this.out.columns),this.render()}moveCursor(n){this.cursor=n,this.value=this.choices[n].value,this.fire()}reset(){this.moveCursor(0),this.fire(),this.render()}exit(){this.abort()}abort(){this.done=this.aborted=!0,this.fire(),this.render(),this.out.write(`
|
|
59
|
+
`),this.close()}submit(){if(!this.selection.disabled)this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
60
|
+
`),this.close();else this.bell()}first(){this.moveCursor(0),this.render()}last(){this.moveCursor(this.choices.length-1),this.render()}up(){if(this.cursor===0)this.moveCursor(this.choices.length-1);else this.moveCursor(this.cursor-1);this.render()}down(){if(this.cursor===this.choices.length-1)this.moveCursor(0);else this.moveCursor(this.cursor+1);this.render()}next(){this.moveCursor((this.cursor+1)%this.choices.length),this.render()}_(c,key){if(c===" ")return this.submit()}get selection(){return this.choices[this.cursor]}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));super.render();let{startIndex,endIndex}=entriesToDisplay(this.cursor,this.choices.length,this.optionsPerPage);if(this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(!1),this.done?this.selection.title:this.selection.disabled?color.yellow(this.warn):color.gray(this.hint)].join(" "),!this.done){this.outputText+=`
|
|
61
|
+
`;for(let i=startIndex;i<endIndex;i++){let title,prefix,desc="",v=this.choices[i];if(i===startIndex&&startIndex>0)prefix=figures.arrowUp;else if(i===endIndex-1&&endIndex<this.choices.length)prefix=figures.arrowDown;else prefix=" ";if(v.disabled)title=this.cursor===i?color.gray().underline(v.title):color.strikethrough().gray(v.title),prefix=(this.cursor===i?color.bold().gray(figures.pointer)+" ":" ")+prefix;else if(title=this.cursor===i?color.cyan().underline(v.title):v.title,prefix=(this.cursor===i?color.cyan(figures.pointer)+" ":" ")+prefix,v.description&&this.cursor===i){if(desc=` - ${v.description}`,prefix.length+title.length+desc.length>=this.out.columns||v.description.split(/\r?\n/).length>1)desc=`
|
|
62
|
+
`+wrap(v.description,{margin:3,width:this.out.columns})}this.outputText+=`${prefix} ${title}${color.gray(desc)}
|
|
63
|
+
`}}this.out.write(this.outputText)}}module.exports=SelectPrompt});var require_toggle2=__commonJS(function(exports,module){var color=require_kleur(),Prompt=require_prompt2(),{style,clear}=require_util2(),{cursor,erase}=require_src();class TogglePrompt extends Prompt{constructor(opts={}){super(opts);this.msg=opts.message,this.value=!!opts.initial,this.active=opts.active||"on",this.inactive=opts.inactive||"off",this.initialValue=this.value,this.render()}reset(){this.value=this.initialValue,this.fire(),this.render()}exit(){this.abort()}abort(){this.done=this.aborted=!0,this.fire(),this.render(),this.out.write(`
|
|
64
|
+
`),this.close()}submit(){this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
65
|
+
`),this.close()}deactivate(){if(this.value===!1)return this.bell();this.value=!1,this.render()}activate(){if(this.value===!0)return this.bell();this.value=!0,this.render()}delete(){this.deactivate()}left(){this.deactivate()}right(){this.activate()}down(){this.deactivate()}up(){this.activate()}next(){this.value=!this.value,this.fire(),this.render()}_(c,key){if(c===" ")this.value=!this.value;else if(c==="1")this.value=!0;else if(c==="0")this.value=!1;else return this.bell();this.render()}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));super.render(),this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(this.done),this.value?this.inactive:color.cyan().underline(this.inactive),color.gray("/"),this.value?color.cyan().underline(this.active):this.active].join(" "),this.out.write(erase.line+cursor.to(0)+this.outputText)}}module.exports=TogglePrompt});var require_datepart2=__commonJS(function(exports,module){class DatePart{constructor({token,date,parts,locales}){this.token=token,this.date=date||new Date,this.parts=parts||[this],this.locales=locales||{}}up(){}down(){}next(){let currentIdx=this.parts.indexOf(this);return this.parts.find((part,idx)=>idx>currentIdx&&part instanceof DatePart)}setTo(val){}prev(){let parts=[].concat(this.parts).reverse(),currentIdx=parts.indexOf(this);return parts.find((part,idx)=>idx>currentIdx&&part instanceof DatePart)}toString(){return String(this.date)}}module.exports=DatePart});var require_meridiem2=__commonJS(function(exports,module){var DatePart=require_datepart2();class Meridiem extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setHours((this.date.getHours()+12)%24)}down(){this.up()}toString(){let meridiem=this.date.getHours()>12?"pm":"am";return/\A/.test(this.token)?meridiem.toUpperCase():meridiem}}module.exports=Meridiem});var require_day2=__commonJS(function(exports,module){var DatePart=require_datepart2(),pos=(n)=>(n=n%10,n===1?"st":n===2?"nd":n===3?"rd":"th");class Day extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setDate(this.date.getDate()+1)}down(){this.date.setDate(this.date.getDate()-1)}setTo(val){this.date.setDate(parseInt(val.substr(-2)))}toString(){let date=this.date.getDate(),day=this.date.getDay();return this.token==="DD"?String(date).padStart(2,"0"):this.token==="Do"?date+pos(date):this.token==="d"?day+1:this.token==="ddd"?this.locales.weekdaysShort[day]:this.token==="dddd"?this.locales.weekdays[day]:date}}module.exports=Day});var require_hours2=__commonJS(function(exports,module){var DatePart=require_datepart2();class Hours extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setHours(this.date.getHours()+1)}down(){this.date.setHours(this.date.getHours()-1)}setTo(val){this.date.setHours(parseInt(val.substr(-2)))}toString(){let hours=this.date.getHours();if(/h/.test(this.token))hours=hours%12||12;return this.token.length>1?String(hours).padStart(2,"0"):hours}}module.exports=Hours});var require_milliseconds2=__commonJS(function(exports,module){var DatePart=require_datepart2();class Milliseconds extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setMilliseconds(this.date.getMilliseconds()+1)}down(){this.date.setMilliseconds(this.date.getMilliseconds()-1)}setTo(val){this.date.setMilliseconds(parseInt(val.substr(-this.token.length)))}toString(){return String(this.date.getMilliseconds()).padStart(4,"0").substr(0,this.token.length)}}module.exports=Milliseconds});var require_minutes2=__commonJS(function(exports,module){var DatePart=require_datepart2();class Minutes extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setMinutes(this.date.getMinutes()+1)}down(){this.date.setMinutes(this.date.getMinutes()-1)}setTo(val){this.date.setMinutes(parseInt(val.substr(-2)))}toString(){let m=this.date.getMinutes();return this.token.length>1?String(m).padStart(2,"0"):m}}module.exports=Minutes});var require_month2=__commonJS(function(exports,module){var DatePart=require_datepart2();class Month extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setMonth(this.date.getMonth()+1)}down(){this.date.setMonth(this.date.getMonth()-1)}setTo(val){val=parseInt(val.substr(-2))-1,this.date.setMonth(val<0?0:val)}toString(){let month=this.date.getMonth(),tl=this.token.length;return tl===2?String(month+1).padStart(2,"0"):tl===3?this.locales.monthsShort[month]:tl===4?this.locales.months[month]:String(month+1)}}module.exports=Month});var require_seconds2=__commonJS(function(exports,module){var DatePart=require_datepart2();class Seconds extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setSeconds(this.date.getSeconds()+1)}down(){this.date.setSeconds(this.date.getSeconds()-1)}setTo(val){this.date.setSeconds(parseInt(val.substr(-2)))}toString(){let s=this.date.getSeconds();return this.token.length>1?String(s).padStart(2,"0"):s}}module.exports=Seconds});var require_year2=__commonJS(function(exports,module){var DatePart=require_datepart2();class Year extends DatePart{constructor(opts={}){super(opts)}up(){this.date.setFullYear(this.date.getFullYear()+1)}down(){this.date.setFullYear(this.date.getFullYear()-1)}setTo(val){this.date.setFullYear(val.substr(-4))}toString(){let year=String(this.date.getFullYear()).padStart(4,"0");return this.token.length===2?year.substr(-2):year}}module.exports=Year});var require_dateparts2=__commonJS(function(exports,module){module.exports={DatePart:require_datepart2(),Meridiem:require_meridiem2(),Day:require_day2(),Hours:require_hours2(),Milliseconds:require_milliseconds2(),Minutes:require_minutes2(),Month:require_month2(),Seconds:require_seconds2(),Year:require_year2()}});var require_date2=__commonJS(function(exports,module){var color=require_kleur(),Prompt=require_prompt2(),{style,clear,figures}=require_util2(),{erase,cursor}=require_src(),{DatePart,Meridiem,Day,Hours,Milliseconds,Minutes,Month,Seconds,Year}=require_dateparts2(),regex=/\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g,regexGroups={1:({token})=>token.replace(/\\(.)/g,"$1"),2:(opts)=>new Day(opts),3:(opts)=>new Month(opts),4:(opts)=>new Year(opts),5:(opts)=>new Meridiem(opts),6:(opts)=>new Hours(opts),7:(opts)=>new Minutes(opts),8:(opts)=>new Seconds(opts),9:(opts)=>new Milliseconds(opts)},dfltLocales={months:"January,February,March,April,May,June,July,August,September,October,November,December".split(","),monthsShort:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),weekdaysShort:"Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",")};class DatePrompt extends Prompt{constructor(opts={}){super(opts);this.msg=opts.message,this.cursor=0,this.typed="",this.locales=Object.assign(dfltLocales,opts.locales),this._date=opts.initial||new Date,this.errorMsg=opts.error||"Please Enter A Valid Value",this.validator=opts.validate||(()=>!0),this.mask=opts.mask||"YYYY-MM-DD HH:mm:ss",this.clear=clear("",this.out.columns),this.render()}get value(){return this.date}get date(){return this._date}set date(date){if(date)this._date.setTime(date.getTime())}set mask(mask){let result;this.parts=[];while(result=regex.exec(mask)){let match=result.shift(),idx=result.findIndex((gr)=>gr!=null);this.parts.push(idx in regexGroups?regexGroups[idx]({token:result[idx]||match,date:this.date,parts:this.parts,locales:this.locales}):result[idx]||match)}let parts=this.parts.reduce((arr,i)=>{if(typeof i==="string"&&typeof arr[arr.length-1]==="string")arr[arr.length-1]+=i;else arr.push(i);return arr},[]);this.parts.splice(0),this.parts.push(...parts),this.reset()}moveCursor(n){this.typed="",this.cursor=n,this.fire()}reset(){this.moveCursor(this.parts.findIndex((p)=>p instanceof DatePart)),this.fire(),this.render()}exit(){this.abort()}abort(){this.done=this.aborted=!0,this.error=!1,this.fire(),this.render(),this.out.write(`
|
|
66
|
+
`),this.close()}async validate(){let valid=await this.validator(this.value);if(typeof valid==="string")this.errorMsg=valid,valid=!1;this.error=!valid}async submit(){if(await this.validate(),this.error){this.color="red",this.fire(),this.render();return}this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
67
|
+
`),this.close()}up(){this.typed="",this.parts[this.cursor].up(),this.render()}down(){this.typed="",this.parts[this.cursor].down(),this.render()}left(){let prev=this.parts[this.cursor].prev();if(prev==null)return this.bell();this.moveCursor(this.parts.indexOf(prev)),this.render()}right(){let next=this.parts[this.cursor].next();if(next==null)return this.bell();this.moveCursor(this.parts.indexOf(next)),this.render()}next(){let next=this.parts[this.cursor].next();this.moveCursor(next?this.parts.indexOf(next):this.parts.findIndex((part)=>part instanceof DatePart)),this.render()}_(c){if(/\d/.test(c))this.typed+=c,this.parts[this.cursor].setTo(this.typed),this.render()}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));if(super.render(),this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(!1),this.parts.reduce((arr,p,idx)=>arr.concat(idx===this.cursor&&!this.done?color.cyan().underline(p.toString()):p),[]).join("")].join(" "),this.error)this.outputText+=this.errorMsg.split(`
|
|
68
|
+
`).reduce((a,l,i)=>a+`
|
|
69
|
+
${i?" ":figures.pointerSmall} ${color.red().italic(l)}`,"");this.out.write(erase.line+cursor.to(0)+this.outputText)}}module.exports=DatePrompt});var require_number2=__commonJS(function(exports,module){var color=require_kleur(),Prompt=require_prompt2(),{cursor,erase}=require_src(),{style,figures,clear,lines}=require_util2(),isNumber=/[0-9]/,isDef=(any)=>any!==void 0,round=(number,precision)=>{let factor=Math.pow(10,precision);return Math.round(number*factor)/factor};class NumberPrompt extends Prompt{constructor(opts={}){super(opts);this.transform=style.render(opts.style),this.msg=opts.message,this.initial=isDef(opts.initial)?opts.initial:"",this.float=!!opts.float,this.round=opts.round||2,this.inc=opts.increment||1,this.min=isDef(opts.min)?opts.min:-1/0,this.max=isDef(opts.max)?opts.max:1/0,this.errorMsg=opts.error||"Please Enter A Valid Value",this.validator=opts.validate||(()=>!0),this.color="cyan",this.value="",this.typed="",this.lastHit=0,this.render()}set value(v){if(!v&&v!==0)this.placeholder=!0,this.rendered=color.gray(this.transform.render(`${this.initial}`)),this._value="";else this.placeholder=!1,this.rendered=this.transform.render(`${round(v,this.round)}`),this._value=round(v,this.round);this.fire()}get value(){return this._value}parse(x){return this.float?parseFloat(x):parseInt(x)}valid(c){return c==="-"||c==="."&&this.float||isNumber.test(c)}reset(){this.typed="",this.value="",this.fire(),this.render()}exit(){this.abort()}abort(){let x=this.value;this.value=x!==""?x:this.initial,this.done=this.aborted=!0,this.error=!1,this.fire(),this.render(),this.out.write(`
|
|
70
|
+
`),this.close()}async validate(){let valid=await this.validator(this.value);if(typeof valid==="string")this.errorMsg=valid,valid=!1;this.error=!valid}async submit(){if(await this.validate(),this.error){this.color="red",this.fire(),this.render();return}let x=this.value;this.value=x!==""?x:this.initial,this.done=!0,this.aborted=!1,this.error=!1,this.fire(),this.render(),this.out.write(`
|
|
71
|
+
`),this.close()}up(){if(this.typed="",this.value==="")this.value=this.min-this.inc;if(this.value>=this.max)return this.bell();this.value+=this.inc,this.color="cyan",this.fire(),this.render()}down(){if(this.typed="",this.value==="")this.value=this.min+this.inc;if(this.value<=this.min)return this.bell();this.value-=this.inc,this.color="cyan",this.fire(),this.render()}delete(){let val=this.value.toString();if(val.length===0)return this.bell();if(this.value=this.parse(val=val.slice(0,-1))||"",this.value!==""&&this.value<this.min)this.value=this.min;this.color="cyan",this.fire(),this.render()}next(){this.value=this.initial,this.fire(),this.render()}_(c,key){if(!this.valid(c))return this.bell();let now=Date.now();if(now-this.lastHit>1000)this.typed="";if(this.typed+=c,this.lastHit=now,this.color="cyan",c===".")return this.fire();if(this.value=Math.min(this.parse(this.typed),this.max),this.value>this.max)this.value=this.max;if(this.value<this.min)this.value=this.min;this.fire(),this.render()}render(){if(this.closed)return;if(!this.firstRender){if(this.outputError)this.out.write(cursor.down(lines(this.outputError,this.out.columns)-1)+clear(this.outputError,this.out.columns));this.out.write(clear(this.outputText,this.out.columns))}if(super.render(),this.outputError="",this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(this.done),!this.done||!this.done&&!this.placeholder?color[this.color]().underline(this.rendered):this.rendered].join(" "),this.error)this.outputError+=this.errorMsg.split(`
|
|
72
|
+
`).reduce((a,l,i)=>a+`
|
|
73
|
+
${i?" ":figures.pointerSmall} ${color.red().italic(l)}`,"");this.out.write(erase.line+cursor.to(0)+this.outputText+cursor.save+this.outputError+cursor.restore)}}module.exports=NumberPrompt});var require_multiselect2=__commonJS(function(exports,module){var color=require_kleur(),{cursor}=require_src(),Prompt=require_prompt2(),{clear,figures,style,wrap,entriesToDisplay}=require_util2();class MultiselectPrompt extends Prompt{constructor(opts={}){super(opts);if(this.msg=opts.message,this.cursor=opts.cursor||0,this.scrollIndex=opts.cursor||0,this.hint=opts.hint||"",this.warn=opts.warn||"- This option is disabled -",this.minSelected=opts.min,this.showMinError=!1,this.maxChoices=opts.max,this.instructions=opts.instructions,this.optionsPerPage=opts.optionsPerPage||10,this.value=opts.choices.map((ch,idx)=>{if(typeof ch==="string")ch={title:ch,value:idx};return{title:ch&&(ch.title||ch.value||ch),description:ch&&ch.description,value:ch&&(ch.value===void 0?idx:ch.value),selected:ch&&ch.selected,disabled:ch&&ch.disabled}}),this.clear=clear("",this.out.columns),!opts.overrideRender)this.render()}reset(){this.value.map((v)=>!v.selected),this.cursor=0,this.fire(),this.render()}selected(){return this.value.filter((v)=>v.selected)}exit(){this.abort()}abort(){this.done=this.aborted=!0,this.fire(),this.render(),this.out.write(`
|
|
74
|
+
`),this.close()}submit(){let selected=this.value.filter((e)=>e.selected);if(this.minSelected&&selected.length<this.minSelected)this.showMinError=!0,this.render();else this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
75
|
+
`),this.close()}first(){this.cursor=0,this.render()}last(){this.cursor=this.value.length-1,this.render()}next(){this.cursor=(this.cursor+1)%this.value.length,this.render()}up(){if(this.cursor===0)this.cursor=this.value.length-1;else this.cursor--;this.render()}down(){if(this.cursor===this.value.length-1)this.cursor=0;else this.cursor++;this.render()}left(){this.value[this.cursor].selected=!1,this.render()}right(){if(this.value.filter((e)=>e.selected).length>=this.maxChoices)return this.bell();this.value[this.cursor].selected=!0,this.render()}handleSpaceToggle(){let v=this.value[this.cursor];if(v.selected)v.selected=!1,this.render();else if(v.disabled||this.value.filter((e)=>e.selected).length>=this.maxChoices)return this.bell();else v.selected=!0,this.render()}toggleAll(){if(this.maxChoices!==void 0||this.value[this.cursor].disabled)return this.bell();let newSelected=!this.value[this.cursor].selected;this.value.filter((v)=>!v.disabled).forEach((v)=>v.selected=newSelected),this.render()}_(c,key){if(c===" ")this.handleSpaceToggle();else if(c==="a")this.toggleAll();else return this.bell()}renderInstructions(){if(this.instructions===void 0||this.instructions){if(typeof this.instructions==="string")return this.instructions;return`
|
|
76
|
+
Instructions:
|
|
77
|
+
${figures.arrowUp}/${figures.arrowDown}: Highlight option
|
|
78
|
+
${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
|
|
79
|
+
`+(this.maxChoices===void 0?` a: Toggle all
|
|
80
|
+
`:"")+" enter/return: Complete answer"}return""}renderOption(cursor2,v,i,arrowIndicator){let prefix=(v.selected?color.green(figures.radioOn):figures.radioOff)+" "+arrowIndicator+" ",title,desc;if(v.disabled)title=cursor2===i?color.gray().underline(v.title):color.strikethrough().gray(v.title);else if(title=cursor2===i?color.cyan().underline(v.title):v.title,cursor2===i&&v.description){if(desc=` - ${v.description}`,prefix.length+title.length+desc.length>=this.out.columns||v.description.split(/\r?\n/).length>1)desc=`
|
|
81
|
+
`+wrap(v.description,{margin:prefix.length,width:this.out.columns})}return prefix+title+color.gray(desc||"")}paginateOptions(options){if(options.length===0)return color.red("No matches for this query.");let{startIndex,endIndex}=entriesToDisplay(this.cursor,options.length,this.optionsPerPage),prefix,styledOptions=[];for(let i=startIndex;i<endIndex;i++){if(i===startIndex&&startIndex>0)prefix=figures.arrowUp;else if(i===endIndex-1&&endIndex<options.length)prefix=figures.arrowDown;else prefix=" ";styledOptions.push(this.renderOption(this.cursor,options[i],i,prefix))}return`
|
|
82
|
+
`+styledOptions.join(`
|
|
83
|
+
`)}renderOptions(options){if(!this.done)return this.paginateOptions(options);return""}renderDoneOrInstructions(){if(this.done)return this.value.filter((e)=>e.selected).map((v)=>v.title).join(", ");let output=[color.gray(this.hint),this.renderInstructions()];if(this.value[this.cursor].disabled)output.push(color.yellow(this.warn));return output.join(" ")}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);super.render();let prompt=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(!1),this.renderDoneOrInstructions()].join(" ");if(this.showMinError)prompt+=color.red(`You must select a minimum of ${this.minSelected} choices.`),this.showMinError=!1;prompt+=this.renderOptions(this.value),this.out.write(this.clear+prompt),this.clear=clear(prompt,this.out.columns)}}module.exports=MultiselectPrompt});var require_autocomplete2=__commonJS(function(exports,module){var color=require_kleur(),Prompt=require_prompt2(),{erase,cursor}=require_src(),{style,clear,figures,wrap,entriesToDisplay}=require_util2(),getVal=(arr,i)=>arr[i]&&(arr[i].value||arr[i].title||arr[i]),getTitle=(arr,i)=>arr[i]&&(arr[i].title||arr[i].value||arr[i]),getIndex=(arr,valOrTitle)=>{let index=arr.findIndex((el)=>el.value===valOrTitle||el.title===valOrTitle);return index>-1?index:void 0};class AutocompletePrompt extends Prompt{constructor(opts={}){super(opts);this.msg=opts.message,this.suggest=opts.suggest,this.choices=opts.choices,this.initial=typeof opts.initial==="number"?opts.initial:getIndex(opts.choices,opts.initial),this.select=this.initial||opts.cursor||0,this.i18n={noMatches:opts.noMatches||"no matches found"},this.fallback=opts.fallback||this.initial,this.clearFirst=opts.clearFirst||!1,this.suggestions=[],this.input="",this.limit=opts.limit||10,this.cursor=0,this.transform=style.render(opts.style),this.scale=this.transform.scale,this.render=this.render.bind(this),this.complete=this.complete.bind(this),this.clear=clear("",this.out.columns),this.complete(this.render),this.render()}set fallback(fb){this._fb=Number.isSafeInteger(parseInt(fb))?parseInt(fb):fb}get fallback(){let choice;if(typeof this._fb==="number")choice=this.choices[this._fb];else if(typeof this._fb==="string")choice={title:this._fb};return choice||this._fb||{title:this.i18n.noMatches}}moveSelect(i){if(this.select=i,this.suggestions.length>0)this.value=getVal(this.suggestions,i);else this.value=this.fallback.value;this.fire()}async complete(cb){let p=this.completing=this.suggest(this.input,this.choices),suggestions=await p;if(this.completing!==p)return;this.suggestions=suggestions.map((s,i,arr)=>({title:getTitle(arr,i),value:getVal(arr,i),description:s.description})),this.completing=!1;let l=Math.max(suggestions.length-1,0);this.moveSelect(Math.min(l,this.select)),cb&&cb()}reset(){this.input="",this.complete(()=>{this.moveSelect(this.initial!==void 0?this.initial:0),this.render()}),this.render()}exit(){if(this.clearFirst&&this.input.length>0)this.reset();else this.done=this.exited=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
84
|
+
`),this.close()}abort(){this.done=this.aborted=!0,this.exited=!1,this.fire(),this.render(),this.out.write(`
|
|
85
|
+
`),this.close()}submit(){this.done=!0,this.aborted=this.exited=!1,this.fire(),this.render(),this.out.write(`
|
|
86
|
+
`),this.close()}_(c,key){let s1=this.input.slice(0,this.cursor),s2=this.input.slice(this.cursor);this.input=`${s1}${c}${s2}`,this.cursor=s1.length+1,this.complete(this.render),this.render()}delete(){if(this.cursor===0)return this.bell();let s1=this.input.slice(0,this.cursor-1),s2=this.input.slice(this.cursor);this.input=`${s1}${s2}`,this.complete(this.render),this.cursor=this.cursor-1,this.render()}deleteForward(){if(this.cursor*this.scale>=this.rendered.length)return this.bell();let s1=this.input.slice(0,this.cursor),s2=this.input.slice(this.cursor+1);this.input=`${s1}${s2}`,this.complete(this.render),this.render()}first(){this.moveSelect(0),this.render()}last(){this.moveSelect(this.suggestions.length-1),this.render()}up(){if(this.select===0)this.moveSelect(this.suggestions.length-1);else this.moveSelect(this.select-1);this.render()}down(){if(this.select===this.suggestions.length-1)this.moveSelect(0);else this.moveSelect(this.select+1);this.render()}next(){if(this.select===this.suggestions.length-1)this.moveSelect(0);else this.moveSelect(this.select+1);this.render()}nextPage(){this.moveSelect(Math.min(this.select+this.limit,this.suggestions.length-1)),this.render()}prevPage(){this.moveSelect(Math.max(this.select-this.limit,0)),this.render()}left(){if(this.cursor<=0)return this.bell();this.cursor=this.cursor-1,this.render()}right(){if(this.cursor*this.scale>=this.rendered.length)return this.bell();this.cursor=this.cursor+1,this.render()}renderOption(v,hovered,isStart,isEnd){let desc,prefix=isStart?figures.arrowUp:isEnd?figures.arrowDown:" ",title=hovered?color.cyan().underline(v.title):v.title;if(prefix=(hovered?color.cyan(figures.pointer)+" ":" ")+prefix,v.description){if(desc=` - ${v.description}`,prefix.length+title.length+desc.length>=this.out.columns||v.description.split(/\r?\n/).length>1)desc=`
|
|
87
|
+
`+wrap(v.description,{margin:3,width:this.out.columns})}return prefix+" "+title+color.gray(desc||"")}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));super.render();let{startIndex,endIndex}=entriesToDisplay(this.select,this.choices.length,this.limit);if(this.outputText=[style.symbol(this.done,this.aborted,this.exited),color.bold(this.msg),style.delimiter(this.completing),this.done&&this.suggestions[this.select]?this.suggestions[this.select].title:this.rendered=this.transform.render(this.input)].join(" "),!this.done){let suggestions=this.suggestions.slice(startIndex,endIndex).map((item,i)=>this.renderOption(item,this.select===i+startIndex,i===0&&startIndex>0,i+startIndex===endIndex-1&&endIndex<this.choices.length)).join(`
|
|
88
|
+
`);this.outputText+=`
|
|
89
|
+
`+(suggestions||color.gray(this.fallback.title))}this.out.write(erase.line+cursor.to(0)+this.outputText)}}module.exports=AutocompletePrompt});var require_autocompleteMultiselect2=__commonJS(function(exports,module){var color=require_kleur(),{cursor}=require_src(),MultiselectPrompt=require_multiselect2(),{clear,style,figures}=require_util2();class AutocompleteMultiselectPrompt extends MultiselectPrompt{constructor(opts={}){opts.overrideRender=!0;super(opts);this.inputValue="",this.clear=clear("",this.out.columns),this.filteredOptions=this.value,this.render()}last(){this.cursor=this.filteredOptions.length-1,this.render()}next(){this.cursor=(this.cursor+1)%this.filteredOptions.length,this.render()}up(){if(this.cursor===0)this.cursor=this.filteredOptions.length-1;else this.cursor--;this.render()}down(){if(this.cursor===this.filteredOptions.length-1)this.cursor=0;else this.cursor++;this.render()}left(){this.filteredOptions[this.cursor].selected=!1,this.render()}right(){if(this.value.filter((e)=>e.selected).length>=this.maxChoices)return this.bell();this.filteredOptions[this.cursor].selected=!0,this.render()}delete(){if(this.inputValue.length)this.inputValue=this.inputValue.substr(0,this.inputValue.length-1),this.updateFilteredOptions()}updateFilteredOptions(){let currentHighlight=this.filteredOptions[this.cursor];this.filteredOptions=this.value.filter((v)=>{if(this.inputValue){if(typeof v.title==="string"){if(v.title.toLowerCase().includes(this.inputValue.toLowerCase()))return!0}if(typeof v.value==="string"){if(v.value.toLowerCase().includes(this.inputValue.toLowerCase()))return!0}return!1}return!0});let newHighlightIndex=this.filteredOptions.findIndex((v)=>v===currentHighlight);this.cursor=newHighlightIndex<0?0:newHighlightIndex,this.render()}handleSpaceToggle(){let v=this.filteredOptions[this.cursor];if(v.selected)v.selected=!1,this.render();else if(v.disabled||this.value.filter((e)=>e.selected).length>=this.maxChoices)return this.bell();else v.selected=!0,this.render()}handleInputChange(c){this.inputValue=this.inputValue+c,this.updateFilteredOptions()}_(c,key){if(c===" ")this.handleSpaceToggle();else this.handleInputChange(c)}renderInstructions(){if(this.instructions===void 0||this.instructions){if(typeof this.instructions==="string")return this.instructions;return`
|
|
90
|
+
Instructions:
|
|
91
|
+
${figures.arrowUp}/${figures.arrowDown}: Highlight option
|
|
92
|
+
${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
|
|
93
|
+
[a,b,c]/delete: Filter choices
|
|
94
|
+
enter/return: Complete answer
|
|
95
|
+
`}return""}renderCurrentInput(){return`
|
|
96
|
+
Filtered results for: ${this.inputValue?this.inputValue:color.gray("Enter something to filter")}
|
|
97
|
+
`}renderOption(cursor2,v,i){let title;if(v.disabled)title=cursor2===i?color.gray().underline(v.title):color.strikethrough().gray(v.title);else title=cursor2===i?color.cyan().underline(v.title):v.title;return(v.selected?color.green(figures.radioOn):figures.radioOff)+" "+title}renderDoneOrInstructions(){if(this.done)return this.value.filter((e)=>e.selected).map((v)=>v.title).join(", ");let output=[color.gray(this.hint),this.renderInstructions(),this.renderCurrentInput()];if(this.filteredOptions.length&&this.filteredOptions[this.cursor].disabled)output.push(color.yellow(this.warn));return output.join(" ")}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);super.render();let prompt=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(!1),this.renderDoneOrInstructions()].join(" ");if(this.showMinError)prompt+=color.red(`You must select a minimum of ${this.minSelected} choices.`),this.showMinError=!1;prompt+=this.renderOptions(this.filteredOptions),this.out.write(this.clear+prompt),this.clear=clear(prompt,this.out.columns)}}module.exports=AutocompleteMultiselectPrompt});var require_confirm2=__commonJS(function(exports,module){var color=require_kleur(),Prompt=require_prompt2(),{style,clear}=require_util2(),{erase,cursor}=require_src();class ConfirmPrompt extends Prompt{constructor(opts={}){super(opts);this.msg=opts.message,this.value=opts.initial,this.initialValue=!!opts.initial,this.yesMsg=opts.yes||"yes",this.yesOption=opts.yesOption||"(Y/n)",this.noMsg=opts.no||"no",this.noOption=opts.noOption||"(y/N)",this.render()}reset(){this.value=this.initialValue,this.fire(),this.render()}exit(){this.abort()}abort(){this.done=this.aborted=!0,this.fire(),this.render(),this.out.write(`
|
|
98
|
+
`),this.close()}submit(){this.value=this.value||!1,this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
99
|
+
`),this.close()}_(c,key){if(c.toLowerCase()==="y")return this.value=!0,this.submit();if(c.toLowerCase()==="n")return this.value=!1,this.submit();return this.bell()}render(){if(this.closed)return;if(this.firstRender)this.out.write(cursor.hide);else this.out.write(clear(this.outputText,this.out.columns));super.render(),this.outputText=[style.symbol(this.done,this.aborted),color.bold(this.msg),style.delimiter(this.done),this.done?this.value?this.yesMsg:this.noMsg:color.gray(this.initialValue?this.yesOption:this.noOption)].join(" "),this.out.write(erase.line+cursor.to(0)+this.outputText)}}module.exports=ConfirmPrompt});var require_elements2=__commonJS(function(exports,module){module.exports={TextPrompt:require_text2(),SelectPrompt:require_select2(),TogglePrompt:require_toggle2(),DatePrompt:require_date2(),NumberPrompt:require_number2(),MultiselectPrompt:require_multiselect2(),AutocompletePrompt:require_autocomplete2(),AutocompleteMultiselectPrompt:require_autocompleteMultiselect2(),ConfirmPrompt:require_confirm2()}});var require_prompts2=__commonJS(function(exports){var $=exports,el=require_elements2(),noop=(v)=>v;function toPrompt(type,args,opts={}){return new Promise((res,rej)=>{let p=new el[type](args),onAbort=opts.onAbort||noop,onSubmit=opts.onSubmit||noop,onExit=opts.onExit||noop;p.on("state",args.onState||noop),p.on("submit",(x)=>res(onSubmit(x))),p.on("exit",(x)=>res(onExit(x))),p.on("abort",(x)=>rej(onAbort(x)))})}$.text=(args)=>toPrompt("TextPrompt",args);$.password=(args)=>(args.style="password",$.text(args));$.invisible=(args)=>(args.style="invisible",$.text(args));$.number=(args)=>toPrompt("NumberPrompt",args);$.date=(args)=>toPrompt("DatePrompt",args);$.confirm=(args)=>toPrompt("ConfirmPrompt",args);$.list=(args)=>{let sep=args.separator||",";return toPrompt("TextPrompt",args,{onSubmit:(str)=>str.split(sep).map((s)=>s.trim())})};$.toggle=(args)=>toPrompt("TogglePrompt",args);$.select=(args)=>toPrompt("SelectPrompt",args);$.multiselect=(args)=>{args.choices=[].concat(args.choices||[]);let toSelected=(items)=>items.filter((item)=>item.selected).map((item)=>item.value);return toPrompt("MultiselectPrompt",args,{onAbort:toSelected,onSubmit:toSelected})};$.autocompleteMultiselect=(args)=>{args.choices=[].concat(args.choices||[]);let toSelected=(items)=>items.filter((item)=>item.selected).map((item)=>item.value);return toPrompt("AutocompleteMultiselectPrompt",args,{onAbort:toSelected,onSubmit:toSelected})};var byTitle=(input,choices)=>Promise.resolve(choices.filter((item)=>item.title.slice(0,input.length).toLowerCase()===input.toLowerCase()));$.autocomplete=(args)=>(args.suggest=args.suggest||byTitle,args.choices=[].concat(args.choices||[]),toPrompt("AutocompletePrompt",args))});var require_lib=__commonJS(function(exports,module){var prompts=require_prompts2(),passOn=["suggest","format","onState","validate","onRender","type"],noop=()=>{};async function prompt(questions=[],{onSubmit=noop,onCancel=noop}={}){let answers={},override=prompt._override||{};questions=[].concat(questions);let answer,question,quit,name,type,lastPrompt,getFormattedAnswer=async(question,answer,skipValidation=!1)=>{if(!skipValidation&&question.validate&&question.validate(answer)!==!0)return;return question.format?await question.format(answer,answers):answer};for(question of questions){if({name,type}=question,typeof type==="function")type=await type(answer,{...answers},question),question.type=type;if(!type)continue;for(let key in question){if(passOn.includes(key))continue;let value=question[key];question[key]=typeof value==="function"?await value(answer,{...answers},lastPrompt):value}if(lastPrompt=question,typeof question.message!=="string")throw Error("prompt message is required");if({name,type}=question,prompts[type]===void 0)throw Error(`prompt type (${type}) is not defined`);if(override[question.name]!==void 0){if(answer=await getFormattedAnswer(question,override[question.name]),answer!==void 0){answers[name]=answer;continue}}try{answer=prompt._injected?getInjectedAnswer(prompt._injected,question.initial):await prompts[type](question),answers[name]=answer=await getFormattedAnswer(question,answer,!0),quit=await onSubmit(question,answer,answers)}catch(err){quit=!await onCancel(question,answers)}if(quit)return answers}return answers}function getInjectedAnswer(injected,deafultValue){let answer=injected.shift();if(answer instanceof Error)throw answer;return answer===void 0?deafultValue:answer}function inject(answers){prompt._injected=(prompt._injected||[]).concat(answers)}function override(answers){prompt._override=Object.assign({},answers)}module.exports=Object.assign(prompt,{prompt,prompts,inject,override})});var require_prompts3=__commonJS(function(exports,module){function isNodeLT(tar){tar=(Array.isArray(tar)?tar:tar.split(".")).map(Number);let i=0,src=process.versions.node.split(".").map(Number);for(;i<tar.length;i++){if(src[i]>tar[i])return!1;if(tar[i]>src[i])return!0}return!1}module.exports=isNodeLT("8.6.0")?require_dist():require_lib()});var isObject=(value)=>!!value&&value.constructor===Object;var init_typed=()=>{};var objectify=(array,getKey,getValue=(item)=>item)=>array.reduce((acc,item)=>(acc[getKey(item)]=getValue(item),acc),{});var init_array=()=>{};var assign=(initial,override)=>{if(!initial||!override)return initial??override??{};return Object.entries({...initial,...override}).reduce((acc,[key,value])=>({...acc,[key]:(()=>{if(isObject(initial[key]))return assign(initial[key],value);return value})()}),{})};var init_object=__esm(()=>{init_typed()});var capitalize=(str)=>{if(!str||str.length===0)return"";let lower=str.toLowerCase();return lower.substring(0,1).toUpperCase()+lower.substring(1,lower.length)},snake=(str,options)=>{let parts=str?.replace(/([A-Z])+/g,capitalize).split(/(?=[A-Z])|[\.\-\s_]/).map((x)=>x.toLowerCase())??[];if(parts.length===0)return"";if(parts.length===1)return parts[0];let result=parts.reduce((acc,part)=>`${acc}_${part.toLowerCase()}`);return options?.splitOnNumber===!1?result:result.replace(/([A-Za-z]{1}[0-9]{1})/,(val)=>`${val[0]}_${val[1]}`)},pascal=(str)=>{let parts=str?.split(/[\.\-\s_]/).map((x)=>x.toLowerCase())??[];if(parts.length===0)return"";return parts.map((str2)=>str2.charAt(0).toUpperCase()+str2.slice(1)).join("")},trim=(str,charsToTrim=" ")=>{if(!str)return"";let toTrim=charsToTrim.replace(/[\W]{1}/g,"\\$&"),regex=new RegExp(`^[${toTrim}]+|[${toTrim}]+$`,"g");return str.replace(regex,"")};var init_string=()=>{};var init_esm=__esm(()=>{init_array();init_object();init_string()});var require_string_template=__commonJS(function(exports,module){var nargs=/\{([0-9a-zA-Z_]+)\}/g;module.exports=template;function template(string){var args;if(arguments.length===2&&typeof arguments[1]==="object")args=arguments[1];else{args=Array(arguments.length-1);for(var i=1;i<arguments.length;++i)args[i-1]=arguments[i]}if(!args||!args.hasOwnProperty)args={};return string.replace(nargs,function(match,i,index){var result;if(string[index-1]==="{"&&string[index+match.length]==="}")return i;else{if(result=args.hasOwnProperty(i)?args[i]:null,result===null||result===void 0)return"";return result}})}});import{existsSync}from"fs";import{dirname,join}from"path";var embedded,findPackageRoot=()=>{let dir=import.meta.dir;while(!existsSync(join(dir,"stubs"))||!existsSync(join(dir,"package.json"))){let parent=dirname(dir);if(parent===dir)throw Error("Could not find the files of the styx package.");dir=parent}return dir},packageRoot,assetPath=(path)=>(packageRoot??=findPackageRoot(),join(packageRoot,path)),readAsset=async(path)=>{if(embedded){let text=embedded.getAssetString(path);if(text===null)throw Error(`Styx has no file ${path}.`);return text}return Bun.file(assetPath(path)).text()},listAssets=async(folder)=>{let prefix=`${folder}/`;if(embedded)return embedded.listAssets().map((path)=>path.replaceAll("\\","/")).filter((path)=>path.startsWith(prefix)).map((path)=>path.slice(prefix.length)).sort();let root=assetPath(folder);if(!existsSync(root))return[];return(await Array.fromAsync(new Bun.Glob("**").scan({cwd:root,dot:!0}))).map((path)=>path.replaceAll("\\","/")).sort()};var init_assets=()=>{};import{existsSync as existsSync2}from"fs";import{mkdir,readdir,rename}from"fs/promises";import{dirname as dirname2,extname,join as join2}from"path";import{Application,ElysiumError}from"@elysiumjs/core";var AppEntryNotFoundError,resolveAppEntry=async(projectPath)=>{let appFile=join2(projectPath,"src","app.ts"),entry=existsSync2(appFile)?appFile:join2(projectPath,"index.ts"),exports=await import(entry);for(let value of Object.values(exports))if(typeof value==="function"&&value.prototype instanceof Application)return value;throw new AppEntryNotFoundError(entry)},getProjectPath=()=>{let startPath=process.cwd(),dir=startPath;while(!0){if(existsSync2(join2(dir,".elysiumrc")))return dir;let parentDir=dirname2(dir);if(dir===parentDir)break;dir=parentDir}return startPath},createModule=async(name,oldName)=>{let root=getProjectPath();{let moduleDir=join2(root,"src","modules",name);if(await mkdir(moduleDir,{recursive:!0}),!oldName){let moduleFile=join2(moduleDir,`${name}.module.ts`);if(!existsSync2(moduleFile)){let className=`${pascal(name)}Module`;await Bun.write(moduleFile,`import { Module } from '@elysiumjs/core';
|
|
100
|
+
|
|
101
|
+
@Module.register({
|
|
102
|
+
services: [],
|
|
103
|
+
controllers: [],
|
|
104
|
+
commands: []
|
|
105
|
+
})
|
|
106
|
+
export class ${className} extends Module {}
|
|
107
|
+
`)}}if(oldName)if(oldName==="root"){let entries=await readdir(join2(root,"src"));for(let entry of entries){if(["app.ts","env.ts","database","modules"].includes(entry))continue;let oldPath=join2(root,"src",entry),newPath=join2(moduleDir,entry==="main.module.ts"?`${name}.module.ts`:entry);await rename(oldPath,newPath)}}else{let oldModuleDir=join2(root,"src","modules",oldName);await rename(oldModuleDir,moduleDir)}}{let pkg=await Bun.file(join2(root,"package.json")).json();if(pkg.imports=pkg.imports??{},pkg.imports[`#${name}/*`]=`./src/modules/${name}/*.ts`,oldName&&oldName!=="root")delete pkg.imports[`#${oldName}/*`];await Bun.write(join2(root,"package.json"),JSON.stringify(pkg,null,2))}{let rc=await Bun.file(join2(root,".elysiumrc")).json();if(rc.mono=!1,rc.modules=rc.modules??{},rc.modules[name]=`./src/modules/${name}`,oldName)delete rc.modules[oldName];await Bun.write(join2(root,".elysiumrc"),JSON.stringify(rc,null,2))}if(oldName){let rewriteImports=async(dir)=>{let entries=await readdir(dir,{withFileTypes:!0});for(let entry of entries){let fullPath=join2(dir,entry.name);if(entry.isDirectory())await rewriteImports(fullPath);else if(extname(entry.name)===".ts"){let text=await Bun.file(fullPath).text();if(oldName==="root")text=text.replace(new RegExp(`(['"])#${oldName}/((?!(env|app|database(?:/|$))).*?)(['"])`,"g"),`$1#${name}/$2$4`);else text=text.replace(new RegExp(`(['"])#${oldName}/`,"g"),`$1#${name}/`);text=text.replace(new RegExp(`(['"])#${oldName}/main\\.module(['"])/g`,"g"),`$1#${name}/${name}.module$2`),text=text.replace(new RegExp(`(['"])#${oldName}/main\\.module\\.ts(['"])?/g`,"g"),`$1#${name}/${name}.module$2`),await Bun.write(fullPath,text)}}};await rewriteImports(root)}};var init_utils=__esm(()=>{init_esm();AppEntryNotFoundError=class AppEntryNotFoundError extends ElysiumError{path;constructor(path){super(`Could not find an exported Application class in ${path}`);this.path=path}}});import{join as join3}from"path";var parseProjectConfig=async()=>{let file=Bun.file(join3(getProjectPath(),".elysiumrc"));if(!file.exists())throw Error("Elysium config file not found.");return file.json()},getModulePath=async(moduleName)=>{let config=await parseProjectConfig();if(config.mono)return"./src";return config.modules[moduleName]},addToModuleHint=async(list,className,moduleName)=>{let config=await parseProjectConfig();if(!config.mono&&!moduleName)return`Add ${className} to the ${list} list of the module that should own it.`;let name=config.mono?"main":moduleName,path=await getModulePath(name);return`Add ${className} to the ${list} list of ${pascal(name)}Module in ${path}/${name}.module.ts.`};var init_config=__esm(()=>{init_esm();init_utils()});import{Command as Command2,CommandArgumentType}from"@elysiumjs/core";var import_prompts,import_string_template,MakeCommandCommand;var init_make_command_command=__esm(()=>{init_esm();init_assets();init_config();init_base_command();import_prompts=__toESM(require_prompts3(),1),import_string_template=__toESM(require_string_template(),1);MakeCommandCommand=class MakeCommandCommand extends BaseCommand{static command="make:command";static description="Creates a new command.";async run(){if(!this.command||!this.name)return this.setup();let config=await parseProjectConfig(),answers={module:this.module,name:this.name,command:this.command,description:this.description};if(!answers.module&&!config.mono){let module=await import_prompts.default({type:"select",name:"module",message:"Module:",choices:Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))});answers.module=module.module}return this.build(answers)}async setup(){let config=await parseProjectConfig(),answers=await import_prompts.default([{type(){return config.mono?null:"select"},name:"module",message:"Module:",choices(){return Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))}},{type:"text",name:"command",message:"Command Name:",initial:"user:say",validate(value){if(value.length<1)return"Command name cannot be empty";return!0}},{type:"text",name:"description",message:"Command Description:",initial:"Say something",validate(value){if(value.length<1)return"Command description cannot be empty";return!0}}],{onCancel:()=>{this.error("Operation cancelled."),process.exit(0)}});return answers.name=pascal(answers.command.replaceAll(":","_")),this.build(answers)}async build(answers){if(!answers.name){this.error("Operation cancelled.");return}if(!answers.name.endsWith("Command"))answers.name+="Command";let stubText=await readAsset("stubs/command.stub"),stub=import_string_template.default(stubText,answers),path=answers.module?await getModulePath(answers.module):"./src",name=snake(answers.name.replace("Command","")),file=Bun.file(`${path}/commands/${name}.command.ts`);await file.write(stub),this.success(`Command ${this.bold(file.name)} created successfully.`),this.info(await addToModuleHint("commands",answers.name,answers.module))}};__legacyDecorateClassTS([Command2.arg({description:"The name of the command to create",type:CommandArgumentType.STRING}),__legacyMetadataTS("design:type",String)],MakeCommandCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command2.arg({description:"The module where the command will be created",type:CommandArgumentType.STRING}),__legacyMetadataTS("design:type",String)],MakeCommandCommand.prototype,"module",void 0),__legacyDecorateClassTS([Command2.arg({description:"The command to create",type:CommandArgumentType.STRING}),__legacyMetadataTS("design:type",String)],MakeCommandCommand.prototype,"command",void 0),__legacyDecorateClassTS([Command2.arg({description:"The description of the command",type:CommandArgumentType.STRING}),__legacyMetadataTS("design:type",String)],MakeCommandCommand.prototype,"description",void 0),MakeCommandCommand=__legacyDecorateClassTS([Command2.register()],MakeCommandCommand)});import{Command as Command3,CommandArgumentType as CommandArgumentType2}from"@elysiumjs/core";var import_prompts2,import_string_template2,MakeControllerCommand;var init_make_controller_command=__esm(()=>{init_esm();init_assets();init_config();init_base_command();import_prompts2=__toESM(require_prompts3(),1),import_string_template2=__toESM(require_string_template(),1);MakeControllerCommand=class MakeControllerCommand extends BaseCommand{constructor(){super(...arguments);this.http=!1;this.wamp=!1;this.ws=!1;this.server=!1;this.request=!1;this.path="/users"}static command="make:controller";static description="Creates a new controller.";async run(){if(!this.name)return this.setup();let config=await parseProjectConfig(),answers={module:this.module,type:"http",scope:"SERVER",name:this.name,path:this.path,realm:this.realm??"realm1"};if(!answers.module&&!config.mono){let module=await import_prompts2.default({type:"select",name:"module",message:"Module:",choices:Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))});answers.module=module.module}if(this.http)answers.type="http";else if(this.wamp)answers.type="wamp";else if(this.ws)answers.type="ws";if(this.server)answers.scope="SERVER";else if(this.request)answers.scope="REQUEST";return this.build(answers)}async setup(){let mode="http",config=await parseProjectConfig(),answers=await import_prompts2.default([{type(){return config.mono?null:"select"},name:"module",message:"Module:",choices(){return Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))}},{type:"select",name:"type",message:"Controller Type:",choices:[{title:"HTTP",value:"http"},{title:"WAMP",value:"wamp"},{title:"WebSocket",value:"ws"}]},{type:"text",name:"name",message:"Controller Name:",initial:"UserController",validate:(value)=>{if(value.length<1)return"Controller name cannot be empty";return!0}},{type:"text",name:"path",message(_prev,values){return mode=values.type,values.type==="wamp"?"Controller URL":"Controller Path:"},initial(_prev,values){return values.type==="wamp"?"ws://localhost:8000":"/users"},validate(value){if(mode==="wamp")return value.match(/^wss?:\/\//)?!0:"The URL must start with ws:// or wss://";if(value[0]!=="/")return"The path must start with a slash (/)";return!0}},{type(_prev,values){return values.type==="http"?"select":null},name:"scope",message:"Controller Scope:",choices:[{title:"SERVER",value:"SERVER",description:"An unique instance of the controller is created for the entire lifecycle of the server."},{title:"REQUEST",value:"REQUEST",description:"An instance of the controller is created for each request."}]},{type(_prev,values){return values.type==="wamp"?"text":null},name:"realm",message:"Controller Realm:",initial:"realm1",validate(value){if(value.length<1)return"Realm name cannot be empty";return!0}}],{onCancel:()=>{this.error("Operation cancelled."),process.exit(0)}});return this.build(answers)}async build(answers){if(!answers.type||!answers.name||!answers.path){this.error("Operation cancelled.");return}if(!answers.name.endsWith("Controller"))answers.name+="Controller";let stubText=await readAsset(`stubs/${answers.type}.controller.stub`),stub=import_string_template2.default(stubText,answers),path=answers.module?await getModulePath(answers.module):"./src",name=snake(answers.name.replace("Controller","")),file=Bun.file(`${path}/controllers/${answers.type}/${name}.controller.ts`);await file.write(stub),this.success(`Controller ${this.bold(file.name)} created successfully.`),this.info(await addToModuleHint("controllers",answers.name,answers.module))}};__legacyDecorateClassTS([Command3.arg({description:"The name of the controller to create",type:CommandArgumentType2.STRING}),__legacyMetadataTS("design:type",String)],MakeControllerCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command3.arg({description:"The module where the controller will be created",type:CommandArgumentType2.STRING}),__legacyMetadataTS("design:type",String)],MakeControllerCommand.prototype,"module",void 0),__legacyDecorateClassTS([Command3.arg({description:"Whether to create a HTTP controller",type:CommandArgumentType2.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],MakeControllerCommand.prototype,"http",void 0),__legacyDecorateClassTS([Command3.arg({description:"Whether to create a WAMP controller",type:CommandArgumentType2.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],MakeControllerCommand.prototype,"wamp",void 0),__legacyDecorateClassTS([Command3.arg({description:"Whether to create a WebSocket controller",type:CommandArgumentType2.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],MakeControllerCommand.prototype,"ws",void 0),__legacyDecorateClassTS([Command3.arg({description:"Whether to create a SERVER scope controller",type:CommandArgumentType2.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],MakeControllerCommand.prototype,"server",void 0),__legacyDecorateClassTS([Command3.arg({description:"Whether to create a REQUEST scope controller",type:CommandArgumentType2.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],MakeControllerCommand.prototype,"request",void 0),__legacyDecorateClassTS([Command3.arg({description:"The path or URL of the controller",type:CommandArgumentType2.STRING}),__legacyMetadataTS("design:type",String)],MakeControllerCommand.prototype,"path",void 0),__legacyDecorateClassTS([Command3.arg({description:"The realm of the controller (only applicable to WAMP controllers)",type:CommandArgumentType2.STRING}),__legacyMetadataTS("design:type",String)],MakeControllerCommand.prototype,"realm",void 0),MakeControllerCommand=__legacyDecorateClassTS([Command3.register()],MakeControllerCommand)});import{Command as Command4,CommandArgumentType as CommandArgumentType3}from"@elysiumjs/core";var import_prompts3,import_string_template3,MakeJobCommand;var init_make_job_command=__esm(()=>{init_esm();init_assets();init_config();init_base_command();import_prompts3=__toESM(require_prompts3(),1),import_string_template3=__toESM(require_string_template(),1);MakeJobCommand=class MakeJobCommand extends BaseCommand{constructor(){super(...arguments);this.queue="default"}static command="make:job";static description="Creates a new job.";async run(){if(!this.name)return this.setup();let config=await parseProjectConfig(),answers={module:this.module,name:this.name,alias:this.alias,queue:this.queue??"default"};if(!answers.module&&!config.mono){let module=await import_prompts3.default({type:"select",name:"module",message:"Module:",choices:Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))});answers.module=module.module}return this.build(answers)}async setup(){let config=await parseProjectConfig(),answers=await import_prompts3.default([{type(){return config.mono?null:"select"},name:"module",message:"Module:",choices(){return Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))}},{type:"text",name:"name",message:"Job Name:",initial:"SendEmailJob",validate(value){if(value.length<1)return"Job name cannot be empty";return!0}},{type:"text",name:"alias",message:"Job Alias:",initial(_,values){return values.name},validate(value){if(value.length<1)return"Job alias cannot be empty";return!0}},{type:"text",name:"queue",message:"Job Queue:",initial:"default"}],{onCancel:()=>{this.error("Operation cancelled."),process.exit(0)}});return this.build(answers)}async build(answers){if(!answers.name){this.error("Operation cancelled.");return}if(!answers.name.endsWith("Job"))answers.name+="Job";if(!answers.alias)answers.alias=answers.name;let stubText=await readAsset("stubs/job.stub"),stub=import_string_template3.default(stubText,answers),path=answers.module?await getModulePath(answers.module):"./src",name=snake(answers.name.replace("Job","")),file=Bun.file(`${path}/jobs/${name}.job.ts`);await file.write(stub),this.success(`Job ${this.bold(file.name)} created successfully.`),this.info(await addToModuleHint("jobs",answers.name,answers.module))}};__legacyDecorateClassTS([Command4.arg({description:"The name of the job to create",type:CommandArgumentType3.STRING}),__legacyMetadataTS("design:type",String)],MakeJobCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command4.arg({description:"The module where the job will be created",type:CommandArgumentType3.STRING}),__legacyMetadataTS("design:type",String)],MakeJobCommand.prototype,"module",void 0),__legacyDecorateClassTS([Command4.arg({description:"The alias of the job to create",type:CommandArgumentType3.STRING}),__legacyMetadataTS("design:type",String)],MakeJobCommand.prototype,"alias",void 0),__legacyDecorateClassTS([Command4.arg({description:"The name of the queue where the job will be dispatched",type:CommandArgumentType3.STRING,default:"default"}),__legacyMetadataTS("design:type",String)],MakeJobCommand.prototype,"queue",void 0),MakeJobCommand=__legacyDecorateClassTS([Command4.register()],MakeJobCommand)});import{Command as Command5,CommandArgumentType as CommandArgumentType4}from"@elysiumjs/core";var import_prompts4,import_string_template4,MakeMiddlewareCommand;var init_make_middleware_command=__esm(()=>{init_esm();init_assets();init_config();init_base_command();import_prompts4=__toESM(require_prompts3(),1),import_string_template4=__toESM(require_string_template(),1);MakeMiddlewareCommand=class MakeMiddlewareCommand extends BaseCommand{static command="make:middleware";static description="Creates a new middleware.";async run(){if(!this.name)return this.setup();let config=await parseProjectConfig(),answers={module:this.module,name:this.name};if(!answers.module&&!config.mono){let module=await import_prompts4.default({type:"select",name:"module",message:"Module:",choices:Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))});answers.module=module.module}return this.build(answers)}async setup(){let config=await parseProjectConfig(),answers=await import_prompts4.default([{type(){return config.mono?null:"select"},name:"module",message:"Module:",choices(){return Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))}},{type:"text",name:"name",message:"Middleware Name:",initial:"AuthMiddleware",validate(value){if(value.length<1)return"Middleware name cannot be empty";return!0}}],{onCancel:()=>{this.error("Operation cancelled."),process.exit(0)}});return this.build(answers)}async build(answers){if(!answers.name){this.error("Operation cancelled.");return}if(!answers.name.endsWith("Middleware"))answers.name+="Middleware";let stubText=await readAsset("stubs/middleware.stub"),stub=import_string_template4.default(stubText,answers),path=answers.module?await getModulePath(answers.module):"./src",name=snake(answers.name.replace("Middleware","")),file=Bun.file(`${path}/middlewares/${name}.middleware.ts`);await file.write(stub),this.success(`Middleware ${this.bold(file.name)} created successfully.`)}};__legacyDecorateClassTS([Command5.arg({description:"The name of the middleware to create",type:CommandArgumentType4.STRING}),__legacyMetadataTS("design:type",String)],MakeMiddlewareCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command5.arg({description:"The module where the middleware will be created",type:CommandArgumentType4.STRING}),__legacyMetadataTS("design:type",String)],MakeMiddlewareCommand.prototype,"module",void 0),MakeMiddlewareCommand=__legacyDecorateClassTS([Command5.register()],MakeMiddlewareCommand)});import{Command as Command6,CommandArgumentType as CommandArgumentType5}from"@elysiumjs/core";var import_prompts5,import_string_template5,MakeModelCommand;var init_make_model_command=__esm(()=>{init_esm();init_assets();init_config();init_base_command();import_prompts5=__toESM(require_prompts3(),1),import_string_template5=__toESM(require_string_template(),1);MakeModelCommand=class MakeModelCommand extends BaseCommand{constructor(){super(...arguments);this.supportTenancy=!1}static command="make:model";static description="Creates a new model.";async run(){if(!this.name||!this.tableName)return this.setup();let config=await parseProjectConfig(),answers={module:this.module,table:this.tableName,name:this.name,supportTenancy:this.supportTenancy};if(!answers.module&&!config.mono){let module=await import_prompts5.default({type:"select",name:"module",message:"Module:",choices:Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))},{onCancel:()=>process.exit(1)});answers.module=module.module}if(!answers.name)answers.name=trim(pascal(answers.table),"s");return answers.canonicalName=answers.name,this.build(answers)}async setup(){let config=await parseProjectConfig(),answers=await import_prompts5.default([{type(){return config.mono?null:"select"},name:"module",message:"Module:",choices(){return Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))}},{type:"text",name:"table",message:"Table Name:",initial:"users",validate(value){if(value.length<1)return"Table name cannot be empty";return!0}},{type:"text",name:"name",message:"Model Name:",initial(_,values){return trim(pascal(values.table),"s")},validate(value){if(value.length<1)return"Model name cannot be empty";return!0}},{type:"select",name:"supportTenancy",message:"Support Tenancy:",choices:[{title:"Yes",value:!0,description:"The model supports multi-tenancy."},{title:"No",value:!1,description:"The model does not support multi-tenancy."}]}],{onCancel:()=>{this.error("Operation cancelled."),process.exit(0)}});return this.build(answers)}async build(answers){if(!answers.name){this.error("Operation cancelled.");return}if(!answers.name.endsWith("Model"))answers.name+="Model";answers.canonicalName=answers.name.replace("Model","");let stubText=await readAsset("stubs/model.stub"),stub=import_string_template5.default(stubText,answers),path=answers.module?await getModulePath(answers.module):"./src",name=snake(answers.name.replace("Model","")),file=Bun.file(`${path}/models/${name}.model.ts`);await file.write(stub),this.success(`Model ${this.bold(file.name)} created successfully.`)}};__legacyDecorateClassTS([Command6.arg({description:"The name of the model to create",type:CommandArgumentType5.STRING}),__legacyMetadataTS("design:type",String)],MakeModelCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command6.arg({description:"The module where the model will be created",type:CommandArgumentType5.STRING}),__legacyMetadataTS("design:type",String)],MakeModelCommand.prototype,"module",void 0),__legacyDecorateClassTS([Command6.arg({name:"table",description:"The name of the table wrapped by the model",type:CommandArgumentType5.STRING}),__legacyMetadataTS("design:type",String)],MakeModelCommand.prototype,"tableName",void 0),__legacyDecorateClassTS([Command6.arg({name:"support-tenancy",description:"Support tenancy",type:CommandArgumentType5.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],MakeModelCommand.prototype,"supportTenancy",void 0),MakeModelCommand=__legacyDecorateClassTS([Command6.register()],MakeModelCommand)});import{Command as Command7,CommandArgumentType as CommandArgumentType6}from"@elysiumjs/core";var import_prompts6,import_string_template6,MakeRepositoryCommand;var init_make_repository_command=__esm(()=>{init_esm();init_assets();init_config();init_base_command();import_prompts6=__toESM(require_prompts3(),1),import_string_template6=__toESM(require_string_template(),1);MakeRepositoryCommand=class MakeRepositoryCommand extends BaseCommand{constructor(){super(...arguments);this.factory=!1;this.singleton=!1}static command="make:repository";static description="Creates a new repository.";async run(){if(!this.name)return this.setup();let config=await parseProjectConfig(),answers={module:this.module,name:this.name,alias:this.alias,scope:this.factory?"FACTORY":this.singleton?"SINGLETON":"SINGLETON",model:this.model};if(!answers.module&&!config.mono){let module=await import_prompts6.default({type:"select",name:"module",message:"Module:",choices:Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))});answers.module=module.module}return this.build(answers)}async setup(){let config=await parseProjectConfig(),answers=await import_prompts6.default([{type(){return config.mono?null:"select"},name:"module",message:"Module:",choices(){return Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))}},{type:"text",name:"name",message:"Repository Name:",initial:"UserRepository",validate(value){if(value.length<1)return"Repository name cannot be empty";return!0}},{type:"text",name:"model",message:"Model Name:",initial:"UserModel",validate(value){if(value.length<1)return"Model name cannot be empty";return!0}},{type:"text",name:"alias",message:"Repository Alias:",initial(_,values){return values.name},validate(value){if(value.length<1)return"Repository alias cannot be empty";return!0}},{type:"select",name:"scope",message:"Repository Scope:",choices:[{title:"SINGLETON",value:"SINGLETON",description:"A single instance of the repository is created."},{title:"FACTORY",value:"FACTORY",description:"A new instance of the repository is created each time it is injected."}]}],{onCancel:()=>{this.error("Operation cancelled."),process.exit(0)}});return this.build(answers)}async build(answers){if(!answers.name){this.error("Operation cancelled.");return}if(!answers.name.endsWith("Repository"))answers.name+="Repository";if(!answers.alias)answers.alias=answers.name;let stubText=await readAsset("stubs/repository.stub"),stub=import_string_template6.default(stubText,{...answers,module:answers.module??"root",model_name:snake(answers.model.replace("Model",""))}),path=answers.module?await getModulePath(answers.module):"./src",name=snake(answers.name.replace("Repository","")),file=Bun.file(`${path}/repositories/${name}.repository.ts`);await file.write(stub),this.success(`Repository ${this.bold(file.name)} created successfully.`)}};__legacyDecorateClassTS([Command7.arg({description:"The name of the repository to create",type:CommandArgumentType6.STRING}),__legacyMetadataTS("design:type",String)],MakeRepositoryCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command7.arg({description:"The module where the repository will be created",type:CommandArgumentType6.STRING}),__legacyMetadataTS("design:type",String)],MakeRepositoryCommand.prototype,"module",void 0),__legacyDecorateClassTS([Command7.arg({description:"The alias of the repository to create",type:CommandArgumentType6.STRING}),__legacyMetadataTS("design:type",String)],MakeRepositoryCommand.prototype,"alias",void 0),__legacyDecorateClassTS([Command7.arg({description:"The model used by the repository",type:CommandArgumentType6.STRING}),__legacyMetadataTS("design:type",String)],MakeRepositoryCommand.prototype,"model",void 0),__legacyDecorateClassTS([Command7.arg({description:"Create a factory repository",type:CommandArgumentType6.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],MakeRepositoryCommand.prototype,"factory",void 0),__legacyDecorateClassTS([Command7.arg({description:"Create a singleton repository",type:CommandArgumentType6.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],MakeRepositoryCommand.prototype,"singleton",void 0),MakeRepositoryCommand=__legacyDecorateClassTS([Command7.register()],MakeRepositoryCommand)});import{Command as Command8,CommandArgumentType as CommandArgumentType7}from"@elysiumjs/core";var import_prompts7,import_string_template7,MakeServiceCommand;var init_make_service_command=__esm(()=>{init_esm();init_assets();init_config();init_base_command();import_prompts7=__toESM(require_prompts3(),1),import_string_template7=__toESM(require_string_template(),1);MakeServiceCommand=class MakeServiceCommand extends BaseCommand{constructor(){super(...arguments);this.factory=!1;this.singleton=!1}static command="make:service";static description="Creates a new service.";async run(){if(!this.name)return this.setup();let config=await parseProjectConfig(),answers={module:this.module,name:this.name,alias:this.alias,scope:this.factory?"FACTORY":this.singleton?"SINGLETON":"SINGLETON"};if(!answers.module&&!config.mono){let module=await import_prompts7.default({type:"select",name:"module",message:"Module:",choices:Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))});answers.module=module.module}return this.build(answers)}async setup(){let config=await parseProjectConfig(),answers=await import_prompts7.default([{type(){return config.mono?null:"select"},name:"module",message:"Module:",choices(){return Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))}},{type:"text",name:"name",message:"Service Name:",initial:"UserService",validate(value){if(value.length<1)return"Service name cannot be empty";return!0}},{type:"text",name:"alias",message:"Service Alias:",initial(_,values){return values.name},validate(value){if(value.length<1)return"Service alias cannot be empty";return!0}},{type:"select",name:"scope",message:"Service Scope:",choices:[{title:"SINGLETON",value:"SINGLETON",description:"A single instance of the service is created."},{title:"FACTORY",value:"FACTORY",description:"A new instance of the service is created each time it is injected."}]}],{onCancel:()=>{this.error("Operation cancelled."),process.exit(0)}});return this.build(answers)}async build(answers){if(!answers.name){this.error("Operation cancelled.");return}if(!answers.name.endsWith("Service"))answers.name+="Service";if(!answers.alias)answers.alias=answers.name;let stubText=await readAsset("stubs/service.stub"),stub=import_string_template7.default(stubText,answers),path=answers.module?await getModulePath(answers.module):"./src",name=snake(answers.name.replace("Service","")),file=Bun.file(`${path}/services/${name}.service.ts`);await file.write(stub),this.success(`Service ${this.bold(file.name)} created successfully.`),this.info(await addToModuleHint("services",answers.name,answers.module))}};__legacyDecorateClassTS([Command8.arg({description:"The name of the service to create",type:CommandArgumentType7.STRING}),__legacyMetadataTS("design:type",String)],MakeServiceCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command8.arg({description:"The module where the service will be created",type:CommandArgumentType7.STRING}),__legacyMetadataTS("design:type",String)],MakeServiceCommand.prototype,"module",void 0),__legacyDecorateClassTS([Command8.arg({description:"The alias of the service to create",type:CommandArgumentType7.STRING}),__legacyMetadataTS("design:type",String)],MakeServiceCommand.prototype,"alias",void 0),__legacyDecorateClassTS([Command8.arg({description:"Create a factory service",type:CommandArgumentType7.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],MakeServiceCommand.prototype,"factory",void 0),__legacyDecorateClassTS([Command8.arg({description:"Create a singleton service",type:CommandArgumentType7.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],MakeServiceCommand.prototype,"singleton",void 0),MakeServiceCommand=__legacyDecorateClassTS([Command8.register()],MakeServiceCommand)});import{Command as Command9,CommandArgumentType as CommandArgumentType8}from"@elysiumjs/core";var import_prompts8,import_string_template8,MakeValidatorCommand;var init_make_validator_command=__esm(()=>{init_esm();init_assets();init_config();init_base_command();import_prompts8=__toESM(require_prompts3(),1),import_string_template8=__toESM(require_string_template(),1);MakeValidatorCommand=class MakeValidatorCommand extends BaseCommand{static command="make:validator";static description="Creates a new validator.";async run(){if(!this.name)return this.setup();let config=await parseProjectConfig(),answers={module:this.module,name:this.name};if(!answers.module&&!config.mono){let module=await import_prompts8.default({type:"select",name:"module",message:"Module:",choices:Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))});answers.module=module.module}return this.build(answers)}async setup(){let config=await parseProjectConfig(),answers=await import_prompts8.default([{type(){return config.mono?null:"select"},name:"module",message:"Module:",choices(){return Object.keys(config.modules??{}).map((moduleName)=>({title:moduleName,value:moduleName}))}},{type:"text",name:"name",message:"Validator Name:",initial:"LoginValidator",validate(value){if(value.length<1)return"Validator name cannot be empty";return!0}}],{onCancel:()=>{this.error("Operation cancelled."),process.exit(0)}});return this.build(answers)}async build(answers){if(!answers.name){this.error("Operation cancelled.");return}if(!answers.name.endsWith("Validator"))answers.name+="Validator";if(!answers.request_name)answers.request_name=answers.name.replace("Validator","Request");let stubText=await readAsset("stubs/validator.stub"),stub=import_string_template8.default(stubText,answers),path=answers.module?await getModulePath(answers.module):"./src",name=snake(answers.name.replace("Validator","")),file=Bun.file(`${path}/validators/${name}.validator.ts`);await file.write(stub),this.success(`Validator ${this.bold(file.name)} created successfully.`)}};__legacyDecorateClassTS([Command9.arg({description:"The name of the validator to create",type:CommandArgumentType8.STRING}),__legacyMetadataTS("design:type",String)],MakeValidatorCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command9.arg({description:"The module where the validator will be created",type:CommandArgumentType8.STRING}),__legacyMetadataTS("design:type",String)],MakeValidatorCommand.prototype,"module",void 0),MakeValidatorCommand=__legacyDecorateClassTS([Command9.register()],MakeValidatorCommand)});import{exists,rm}from"fs/promises";import{join as join4}from"path";import{Command as Command10,CommandArgumentType as CommandArgumentType9}from"@elysiumjs/core";var import_prompts9,ModuleNewCommand;var init_module_new_command=__esm(()=>{init_esm();init_config();init_utils();init_base_command();import_prompts9=__toESM(require_prompts3(),1);ModuleNewCommand=class ModuleNewCommand extends BaseCommand{static command="module:new";static description="Creates a new module.";module;convert=!1;async run(){let config=await parseProjectConfig();if(!this.name){let name=await import_prompts9.default({type:"text",name:"name",message:"New module name:",initial:"module",validate(value){return value.length>0?!0:"Module name cannot be empty"}},{onCancel:()=>process.exit(0)});this.name=snake(name.name)}if(config.mono){let{module,convert}=await import_prompts9.default([{type:"confirm",name:"convert",message:"This project is a mono-module project. Do you want to convert it to a multi-module project?",initial:!1},{type:(convert)=>convert?"text":null,name:"module",message:"Current module name:",initial:"main",validate(value){return value.length>0?!0:"Module name cannot be empty"}}],{onCancel:()=>process.exit(0)});if(!convert)return this.error("Operation cancelled. The project is left unchanged.");this.module=snake(module),this.convert=convert}if(this.convert){let modulesDir=join4(getProjectPath(),"src","modules");if(await exists(modulesDir))await rm(modulesDir,{recursive:!0});await createModule(this.module,"root"),this.success("Project converted to multi-module."),this.success(`Module '${this.module}' created.`)}await createModule(this.name),this.success(`Module '${this.name}' created.`)}};__legacyDecorateClassTS([Command10.arg({description:"The name of the module to create",type:CommandArgumentType9.STRING}),__legacyMetadataTS("design:type",String)],ModuleNewCommand.prototype,"name",void 0),ModuleNewCommand=__legacyDecorateClassTS([Command10.register()],ModuleNewCommand)});import{Command as Command11,CommandArgumentType as CommandArgumentType10}from"@elysiumjs/core";var import_prompts10,ModuleRenameCommand;var init_module_rename_command=__esm(()=>{init_config();init_utils();init_base_command();import_prompts10=__toESM(require_prompts3(),1);ModuleRenameCommand=class ModuleRenameCommand extends BaseCommand{static command="module:rename";static description="Renames a module.";async run(){if((await parseProjectConfig()).mono)return this.error("This operation is not supported for mono-module projects.");if(!this.module){let{module}=await import_prompts10.default({type:"text",name:"module",message:"Module to rename:",validate:(value)=>value.length>0});this.module=module}if(!this.name){let{name}=await import_prompts10.default({type:"text",name:"name",message:"New module name:",initial:this.module,validate:(value)=>value.length>0});this.name=name}if(this.module===this.name)return this.info("Module name is the same as the current name.");await createModule(this.name,this.module),this.success(`Module '${this.module}' renamed to '${this.name}'.`)}};__legacyDecorateClassTS([Command11.arg({description:"The module to rename",type:CommandArgumentType10.STRING}),__legacyMetadataTS("design:type",String)],ModuleRenameCommand.prototype,"module",void 0),__legacyDecorateClassTS([Command11.arg({description:"The new name of the module",type:CommandArgumentType10.STRING}),__legacyMetadataTS("design:type",String)],ModuleRenameCommand.prototype,"name",void 0),ModuleRenameCommand=__legacyDecorateClassTS([Command11.register()],ModuleRenameCommand)});import{basename,dirname as dirname3,join as join5,relative,resolve}from"path";import{Http}from"@elysiumjs/core";var IGNORED,locateControllers=async(projectPath,outFile)=>{let found=new Map,glob=new Bun.Glob("**/*.{ts,tsx}"),roots=["src","index.ts"];for(let root of roots){let base=join5(projectPath,root),files=root.endsWith(".ts")?await Bun.file(base).exists()?[base]:[]:await Array.fromAsync(glob.scan({cwd:base,absolute:!0})).catch(()=>[]);for(let file of files.sort()){if(IGNORED.test(file)||resolve(file)===resolve(outFile))continue;if(file.includes("/node_modules/"))continue;if(!(await Bun.file(file).text()).includes("Http.controller"))continue;let exports=await import(file);for(let[exportName,value]of Object.entries(exports))if(typeof value==="function"&&!found.has(value))found.set(value,{file,exportName,className:value.name})}}return found},defaultName=({file,className})=>{if(className&&className!=="default"&&!className.endsWith("_default"))return className;let name=basename(file).replace(/\.[cm]?[jt]sx?$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map((part)=>part[0].toUpperCase()+part.slice(1)).join("");return/^[A-Za-z_$]/.test(name)?name:`_${name}`},specifierFor=(outFile,file)=>{let path=relative(dirname3(outFile),file).replaceAll("\\","/").replace(/\.tsx?$/,"");return path.startsWith(".")?path:`./${path}`},collectRoutes=async(projectPath,app,outFile)=>{await new Promise((resolve)=>process.nextTick(resolve));let graph=app.moduleGraph("production"),located=await locateControllers(projectPath,outFile);await new Promise((resolve)=>process.nextTick(resolve));let modules=[],missing=[];for(let node of graph.nodes){let controllers=[];for(let controller of node.props.controllers??[]){let description=Http.describe(controller);if(!description)continue;let source=located.get(controller);if(!source){missing.push(controller.name);continue}controllers.push({exportName:source.exportName,...source.exportName==="default"?{className:defaultName(source)}:{},specifier:specifierFor(outFile,source.file),path:description.path,routes:description.routes})}if(controllers.length>0)modules.push({id:node.id,prefix:node.props.prefix,controllers})}return{modules,missing}};var init_collect=__esm(()=>{IGNORED=/(\.d|\.test|\.spec)\.tsx?$/});var METHODS,quote=(value)=>`'${value.replaceAll("\\","\\\\").replaceAll("'","\\'")}'`,identifier=(value)=>value.replace(/[^A-Za-z0-9_$]/g,"_").replace(/^(\d)/,"_$1"),pathSlugs=(path)=>Array.from(path.matchAll(/:([A-Za-z0-9_]+)\??/g),(match)=>match[1]),renderRoute=(controller,route)=>{let method=`${controller}[${quote(route.name)}]`,parameter=(index)=>`Parameters<${method}>[${index}]`,hook=[],params=new Map;for(let slug of pathSlugs(route.path))params.set(slug,"string");for(let{slug,index}of route.params)params.set(slug,parameter(index));if(params.size>0){let fields=Array.from(params,([slug,type])=>`${quote(slug)}: ${type}`).join("; ");hook.push(`params: schema<{ ${fields} }>()`)}if(route.query!==void 0)hook.push(`query: schema<${parameter(route.query)}>()`);if(route.body!==void 0)hook.push(`body: schema<${parameter(route.body)}>()`);let hookObject=hook.length>0?`{ ${hook.join(", ")} }`:"{}",args=`${quote(route.path)}, ${hookObject}, returns<ReturnType<${method}>>()`;return METHODS.has(route.method)?`.${route.method.toLowerCase()}(${args})`:`.route(${quote(route.method)}, ${args})`},renderRoutes=(modules)=>{let imports=new Map,names=new Set,local=new Map;for(let module of modules)for(let controller of module.controllers){let preferred=controller.exportName==="default"&&controller.className?controller.className:controller.exportName,name=preferred;for(let i=2;names.has(name);i++)name=`${preferred}$${i}`;names.add(name),local.set(controller,name);let specifiers=imports.get(controller.specifier)??new Map;specifiers.set(name,controller.exportName),imports.set(controller.specifier,specifiers)}let lines=["// Generated by `styx routes:generate`. Do not edit: run the command again after changing a controller.","/* eslint-disable */","import type { Elysia, t } from '@elysiumjs/core';",""];for(let[specifier,specifiers]of[...imports].sort(([a],[b])=>a.localeCompare(b))){let list=Array.from(specifiers,([name,exported])=>name===exported?name:`${exported} as ${name}`).join(", ");lines.push(`import type { ${list} } from ${quote(specifier)};`)}lines.push("","declare function routes<const Prefix extends string = ''>(prefix?: Prefix): Elysia<Prefix>;","declare function schema<T>(): ReturnType<typeof t.Unsafe<T>>;","declare function returns<T>(): () => T;","");let moduleNames=[];for(let module of modules){let name=`${identifier(module.id)}Routes`;while(moduleNames.includes(name))name=`_${name}`;moduleNames.push(name);let controllers=module.controllers.map((controller)=>{let chain=controller.routes.map((route)=>`
|
|
108
|
+
${renderRoute(local.get(controller),route)}`).join("");return`
|
|
109
|
+
.use(
|
|
110
|
+
routes(${quote(controller.path)})${chain}
|
|
111
|
+
)`}),prefix=module.prefix?quote(module.prefix):"";lines.push(`/** The routes of the module ${module.id}. */`),lines.push(`const ${name} = () =>
|
|
112
|
+
routes(${prefix})${controllers.join("")};`,"")}let uses=moduleNames.map((name)=>`.use(${name}())`).join("");return lines.push(`const app = () => routes()${uses};`,""),lines.push("/** The routes of the app, for typed clients: `treaty<AppRoutes>(url)`. */"),lines.push("export type AppRoutes = ReturnType<typeof app>;",""),lines.join(`
|
|
113
|
+
`)};var init_render=__esm(()=>{METHODS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"])});import{join as join6,relative as relative2}from"path";import{Command as Command12,CommandArgumentType as CommandArgumentType11,ConsoleFormat}from"@elysiumjs/core";var RoutesGenerateCommand;var init_routes_generate_command=__esm(()=>{init_config();init_collect();init_render();init_utils();init_base_command();RoutesGenerateCommand=class RoutesGenerateCommand extends BaseCommand{static command="routes:generate";static description="Writes the route types of the app (AppRoutes) for typed clients.";async run(){let projectPath=getProjectPath(),config=await parseProjectConfig(),outFile=join6(projectPath,this.out??config.routes??"src/routes.gen.ts"),app=await resolveAppEntry(projectPath),{modules,missing}=await collectRoutes(projectPath,app,outFile);await Bun.write(outFile,renderRoutes(modules));for(let name of missing)this.warning(`${name} is not declared in the project sources, so its routes are not in AppRoutes.`);let count=modules.reduce((total,module)=>total+module.controllers.reduce((sum,controller)=>sum+controller.routes.length,0),0);this.success(`Wrote ${count} routes to ${this.format(relative2(projectPath,outFile),ConsoleFormat.BOLD)}.`)}};__legacyDecorateClassTS([Command12.arg({description:"The file to write, relative to the project (default: src/routes.gen.ts)",type:CommandArgumentType11.STRING}),__legacyMetadataTS("design:type",String)],RoutesGenerateCommand.prototype,"out",void 0),RoutesGenerateCommand=__legacyDecorateClassTS([Command12.register()],RoutesGenerateCommand)});var init_commands=__esm(()=>{init_base_command();init_make_command_command();init_make_controller_command();init_make_job_command();init_make_middleware_command();init_make_model_command();init_make_repository_command();init_make_service_command();init_make_validator_command();init_module_new_command();init_module_rename_command();init_routes_generate_command()});var TOOL_VERSIONS,versionFor=(name)=>{let elysium={"@elysiumjs/moirai-drizzle":"0.1.0","@elysiumjs/ariadne-redis":"0.1.0","@elysiumjs/runtime-bun":"0.1.0","@elysiumjs/cerberus":"0.3.3","@elysiumjs/ariadne":"0.1.0","@elysiumjs/moirai":"0.1.0","@elysiumjs/themis":"0.1.0","@elysiumjs/themis-redis":"0.0.1","@elysiumjs/heracles":"0.8.0","@elysiumjs/argus":"0.3.0","@elysiumjs/mnemosyne-drizzle":"0.4.0","@elysiumjs/mnemosyne":"0.4.0","@elysiumjs/runtime-node":"0.1.0","@elysiumjs/hermes":"0.5.0","@elysiumjs/themis-workers":"0.0.1","@elysiumjs/hephaestus":"0.4.0","@elysiumjs/ariadne-workers":"0.1.0","@elysiumjs/redis":"0.1.0","@elysiumjs/heracles-workers":"0.1.0","@elysiumjs/plugin-sentry":"0.3.0","@elysiumjs/core":"0.11.0","@elysiumjs/styx":"0.9.0","@elysiumjs/runtime-workers":"0.1.0"}[name];if(elysium)return`^${elysium}`;let range=TOOL_VERSIONS[name];if(!range)throw Error(`No version is known for ${name}.`);return range},getModuleCode=(module)=>`import { Module } from '@elysiumjs/core';
|
|
114
|
+
|
|
115
|
+
@Module.register({
|
|
116
|
+
controllers: []
|
|
117
|
+
})
|
|
118
|
+
export class ${module}Module extends Module {}
|
|
119
|
+
`,RUNTIMES,appPackages=(runtime,parts)=>{let prod=["@elysiumjs/core","@elysiumjs/hermes",RUNTIMES[runtime].package],dev=["@elysiumjs/styx","typescript",...RUNTIMES[runtime].devPackages];if(parts.database){if(prod.push("@elysiumjs/mnemosyne-drizzle"),dev.push("drizzle-kit"),runtime!=="bun")prod.push("postgres")}if(parts.cache){if(prod.push("@elysiumjs/redis"),runtime==="node")prod.push("ioredis")}return{prod,dev}},partCode=(runtime,parts)=>{let imports=[],modules=[];if(parts.cache)if(runtime==="bun")imports.push("import { RedisModule } from '@elysiumjs/redis';"),modules.push(`RedisModule.with(() => ({
|
|
120
|
+
default: 'cache',
|
|
121
|
+
connections: { cache: { url: process.env.REDIS_URL! } }
|
|
122
|
+
}))`);else if(runtime==="node")imports.push("import { ioredis, RedisModule } from '@elysiumjs/redis';"),imports.push("import IORedis from 'ioredis';"),modules.push(`RedisModule.with(() => ({
|
|
123
|
+
default: 'cache',
|
|
124
|
+
client: ioredis((url, options) => new IORedis(url, { ...options, lazyConnect: true })),
|
|
125
|
+
connections: { cache: { url: process.env.REDIS_URL! } }
|
|
126
|
+
}))`);else imports.push("import { RedisModule, upstash } from '@elysiumjs/redis';"),modules.push(`RedisModule.with(() => ({
|
|
127
|
+
default: 'cache',
|
|
128
|
+
client: upstash({ token: process.env.UPSTASH_REDIS_REST_TOKEN! }),
|
|
129
|
+
connections: { cache: { url: process.env.UPSTASH_REDIS_REST_URL! } }
|
|
130
|
+
}))`);if(parts.database)if(imports.push("import { DrizzleModule } from '@elysiumjs/mnemosyne-drizzle';"),runtime==="bun")modules.push(`DrizzleModule.with(() => ({
|
|
131
|
+
default: 'main',
|
|
132
|
+
connections: { main: { connection: process.env.DATABASE_URL! } }
|
|
133
|
+
}))`);else if(runtime==="node")imports.push("import { postgresJs } from '@elysiumjs/mnemosyne-drizzle/postgres-js';"),modules.push(`DrizzleModule.with(() => ({
|
|
134
|
+
default: 'main',
|
|
135
|
+
connections: { main: { driver: postgresJs({ connection: process.env.DATABASE_URL! }) } }
|
|
136
|
+
}))`);else imports.push("import { hyperdrive } from '@elysiumjs/mnemosyne-drizzle/hyperdrive';"),imports.push("import { postgresJs } from '@elysiumjs/mnemosyne-drizzle/postgres-js';"),modules.push(`DrizzleModule.with(() => ({
|
|
137
|
+
default: 'main',
|
|
138
|
+
connections: {
|
|
139
|
+
main: {
|
|
140
|
+
driver: hyperdrive({
|
|
141
|
+
binding: 'HYPERDRIVE',
|
|
142
|
+
driver: (url) => postgresJs({ connection: { url, max: 5, fetch_types: false } })
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}))`);return{imports,modules}},getAppCode=(projectName,modules,enabledModules=[],runtime="bun",parts={database:!0,cache:!0})=>{let choice=RUNTIMES[runtime],part=partCode(runtime,parts),entries=[runtime==="workers"?"HermesModule.with({ level: 'debug', transport: 'console' })":"HermesModule.with({ level: 'debug', format: 'pretty' })",...part.modules,...enabledModules.map((module)=>module.expression),...Object.keys(modules).map((module)=>`${pascal(module)}Module`)];return`import type { ServerError } from '@elysiumjs/core';
|
|
147
|
+
|
|
148
|
+
import { Application, getLogger, t } from '@elysiumjs/core';
|
|
149
|
+
import { HermesModule } from '@elysiumjs/hermes';
|
|
150
|
+
import { runtime as ${choice.alias} } from '${choice.package}';
|
|
151
|
+
${[...part.imports,...enabledModules.map((module)=>`import { ${module.import} } from '${module.name}';`)].join(`
|
|
152
|
+
`)}
|
|
153
|
+
|
|
154
|
+
${Object.keys(modules).map((module)=>`import { ${pascal(module)}Module } from '${modules[module]}';`).join(`
|
|
155
|
+
`)}
|
|
156
|
+
|
|
157
|
+
export const env = t.Object({});
|
|
158
|
+
|
|
159
|
+
@Application.register({
|
|
160
|
+
runtime: ${choice.alias},
|
|
161
|
+
modules: [
|
|
162
|
+
${entries.join(`,
|
|
163
|
+
`)}
|
|
164
|
+
],
|
|
165
|
+
server: {
|
|
166
|
+
name: '${projectName}',
|
|
167
|
+
port: parseInt(process.env.PORT!, 10) || 3000
|
|
168
|
+
},
|
|
169
|
+
debug: false,
|
|
170
|
+
openapi: {
|
|
171
|
+
path: '/docs',
|
|
172
|
+
documentation: {
|
|
173
|
+
info: {
|
|
174
|
+
title: '${projectName}',
|
|
175
|
+
description: '${projectName} API Documentation',
|
|
176
|
+
version: '1.0.0'
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
env
|
|
181
|
+
})
|
|
182
|
+
export class App extends Application {
|
|
183
|
+
protected onError(e: ServerError): Promise<boolean> {
|
|
184
|
+
getLogger().error(e.error.message, { error: e.error });
|
|
185
|
+
return super.onError(e);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
`},getScripts=(runtime)=>{let common={routes:"styx routes:generate",typecheck:"styx routes:generate && tsc --noEmit"};if(runtime==="node")return{build:"styx build --target node --entry ./index.ts",start:"node --enable-source-maps dist/server.js serve",dev:"styx build --target node --entry ./index.ts && node --enable-source-maps dist/server.js serve",...common};if(runtime==="workers")return{build:"styx build --target workers",dev:"styx build --target workers && wrangler dev",deploy:"styx build --target workers && wrangler deploy",...common};return{dev:"bun --watch styx serve",...common}},getWorkerCode=()=>`import { createWorker } from '@elysiumjs/runtime-workers';
|
|
189
|
+
|
|
190
|
+
import { App } from '#root/app';
|
|
191
|
+
|
|
192
|
+
const worker = await createWorker(new App());
|
|
193
|
+
|
|
194
|
+
// The AOT plugin of styx build --target workers compiles the routes of the exported app.
|
|
195
|
+
export const app = worker.app;
|
|
196
|
+
|
|
197
|
+
export default worker;
|
|
198
|
+
`,getWranglerConfig=(projectName,parts)=>{let config={$schema:"node_modules/wrangler/config-schema.json",name:projectName.replace(/^@[^/]+\//,""),main:"dist/worker.js",compatibility_date:"2026-10-01",compatibility_flags:["nodejs_compat"],observability:{enabled:!0}};if(parts.database)config.hyperdrive=[{binding:"HYPERDRIVE",id:"<your-hyperdrive-id>",localConnectionString:`postgres://postgres:postgres@localhost:5432/${config.name}`}];return JSON.stringify(config,null,"\t")+`
|
|
199
|
+
`};var init_code=__esm(()=>{init_esm();TOOL_VERSIONS={prettier:"^3.9.10","@ianvs/prettier-plugin-sort-imports":"^4.7.1",typescript:"^7.0.2","drizzle-kit":"^1.0.0-rc.5",postgres:"^3.4.7",ioredis:"^5.8.2","@types/bun":"^1.3.1","@types/node":"^24.10.0","@cloudflare/workers-types":"^4.20251101.0",wrangler:"^4.158.0"},RUNTIMES={bun:{title:"Bun",description:"Run with Bun (https://bun.sh)",package:"@elysiumjs/runtime-bun",alias:"bunRuntime",types:["bun"],devPackages:["@types/bun"]},node:{title:"Node.js",description:"Run with Node.js (https://nodejs.org), built with styx build --target node",package:"@elysiumjs/runtime-node",alias:"nodeRuntime",types:["node"],devPackages:["@types/node"]},workers:{title:"Cloudflare Workers",description:"Deploy to Cloudflare Workers (https://workers.cloudflare.com)",package:"@elysiumjs/runtime-workers",alias:"workersRuntime",types:["@cloudflare/workers-types","node"],devPackages:["@cloudflare/workers-types","@types/node","wrangler"]}}});import{relative as relative3,resolve as resolve2,sep}from"path";import{ElysiumError as ElysiumError2}from"@elysiumjs/core";var PACKAGE_NAME,MODULE_NAME,InvalidNameError,validateProjectName=(name)=>{let match=PACKAGE_NAME.exec(name);if(!match)throw new InvalidNameError("project",name,'use lower-case letters, digits, "-", "_", "." or "~", optionally under an @scope/');let[,,directory]=match;return directory},validateModuleName=(name)=>{if(!MODULE_NAME.test(name))throw new InvalidNameError("module",name,'start with a lower-case letter, then use lower-case letters, digits or "-"');return name},resolveProjectPath=(base,directory)=>{let path=resolve2(base,directory),inside=relative3(resolve2(base),path);if(inside===""||inside===".."||inside.startsWith(`..${sep}`)||resolve2(inside)===inside)throw new InvalidNameError("project",directory,`it must be a folder inside ${resolve2(base)}`);return path};var init_names=__esm(()=>{PACKAGE_NAME=/^(?:@([a-z0-9-~][a-z0-9-._~]*)\/)?([a-z0-9-~][a-z0-9-._~]*)$/,MODULE_NAME=/^[a-z][a-z0-9-]*$/;InvalidNameError=class InvalidNameError extends ElysiumError2{kind;value;reason;constructor(kind,value,reason){super(`Invalid ${kind} name "${value}": ${reason}`);this.kind=kind;this.value=value;this.reason=reason}}});import{existsSync as existsSync3}from"fs";import{mkdir as mkdir2,readdir as readdir2,rm as rm2}from"fs/promises";import{dirname as dirname4,join as join7,relative as relative4}from"path";import{Command as Command13,CommandArgumentType as CommandArgumentType12,ConsoleFormat as ConsoleFormat2}from"@elysiumjs/core";var import_prompts11,PACKAGE_MANAGERS,runWith=(manager)=>`${manager} run`,list2=(value)=>typeof value==="string"?value.split(",").map((item)=>item.trim()).filter(Boolean):void 0,copyAssets=async(folder,to,projectName,skip=[])=>{for(let path of await listAssets(folder)){let target=join7(to,path);await mkdir2(dirname4(target),{recursive:!0});let file=path.split("/").at(-1);if(file===".gitkeep"||skip.includes(file))continue;let text=await readAsset(`${folder}/${path}`),renamed=file==="gitignore"?join7(dirname4(target),".gitignore"):target;await Bun.write(renamed,text.replaceAll("{PROJECT_NAME}",projectName))}},createProject=async(options,exec,progress=()=>{})=>{let directory=validateProjectName(options.name),projectPath=resolveProjectPath(options.path,directory),modules=options.template==="single"?["main"]:options.modules.map(validateModuleName);if(!RUNTIMES[options.runtime])throw Error(`Unknown runtime ${options.runtime}.`);if(!PACKAGE_MANAGERS.includes(options.packageManager))throw Error(`Unknown package manager ${options.packageManager}.`);let parts={database:options.database,cache:options.cache};if((await listAssets(`templates/template-${options.template}`)).length===0)throw Error(`Unknown template ${options.template}.`);if(progress("Creating project directory..."),existsSync3(projectPath)&&(await readdir2(projectPath)).length>0){if(!options.force)throw Error(`${projectPath} already exists and is not empty.`);await rm2(projectPath,{recursive:!0,force:!0})}await mkdir2(projectPath,{recursive:!0}),progress("Copying template files..."),await copyAssets(`templates/template-${options.template}`,projectPath,options.name),await writeRuntimeFiles(projectPath,options),await Bun.write(join7(projectPath,".elysiumrc"),JSON.stringify({projectName:options.name,mono:options.template!=="multi",modules:options.template==="multi"?objectify(modules,(m)=>m,(m)=>`src/modules/${m}`):void 0},null,2));for(let module of modules){let modulePath=options.template==="multi"?join7(projectPath,"src","modules",module):join7(projectPath,"src");await copyAssets("templates/shared-module",modulePath,options.name),await Bun.write(join7(modulePath,`${snake(module)}.module.ts`),getModuleCode(pascal(module)))}let packageFile=join7(projectPath,"package.json"),packageJson=assign(await Bun.file(packageFile).json(),{scripts:getScripts(options.runtime),imports:options.template==="multi"?objectify(modules,(m)=>`#${m}/*`,(m)=>`./src/modules/${m}/*.ts`):{"#root/*":"./src/*.ts"}}),base=appPackages(options.runtime,parts),devPackages=[...base.dev],packages=[...base.prod],enabledModules=[];for(let[kind,names]of[["plugin",options.plugins],["feature",options.features]])for(let name of names){let folder=`templates/${kind}-${name}`;if((await listAssets(folder)).length===0)throw Error(`Unknown ${kind} ${name}.`);await copyAssets(folder,projectPath,options.name,[".specs"]);let specs=JSON.parse(await readAsset(`${folder}/.specs`));if(devPackages.push(...specs.packages?.dev??[]),packages.push(...specs.packages?.prod??[]),specs.patch)packageJson=assign(packageJson,specs.patch);if(specs.module)enabledModules.push(specs.module)}let declare=(names)=>objectify(names,(n)=>n,versionFor);if(packageJson=assign(packageJson,{dependencies:{...packageJson.dependencies,...declare(packages)},devDependencies:{...packageJson.devDependencies,...declare(devPackages)}}),await Bun.write(packageFile,JSON.stringify(packageJson,null,2)+`
|
|
200
|
+
`),await Bun.write(join7(projectPath,"src","app.ts"),getAppCode(options.name,objectify(modules,(m)=>m,(m)=>options.template==="multi"?`#${m}/${snake(m)}.module`:`#root/${snake(m)}.module`),enabledModules,options.runtime,parts)),options.install){if(progress("Installing dependencies..."),await exec(projectPath,[options.packageManager,"install"]),options.features.includes("prettier"))progress("Formatting code using Prettier..."),await exec(projectPath,[options.packageManager,"run","format"])}if(options.git)progress("Initializing Git repository..."),await exec(projectPath,["git","init"]);return projectPath},writeRuntimeFiles=async(projectPath,options)=>{let tsconfigFile=join7(projectPath,"tsconfig.json"),tsconfig=await Bun.file(tsconfigFile).text(),types=JSON.stringify(RUNTIMES[options.runtime].types);await Bun.write(tsconfigFile,tsconfig.replace(/"types":\s*\[[^\]]*\]/,`"types": ${types}`));let readmeFile=join7(projectPath,"README.md"),readme=await Bun.file(readmeFile).text();if(await Bun.write(readmeFile,readme.replaceAll("{INSTALL}",`${options.packageManager} install`).replaceAll("{RUN}",runWith(options.packageManager))),options.runtime==="workers")await rm2(join7(projectPath,"index.ts"),{force:!0}),await mkdir2(join7(projectPath,"src"),{recursive:!0}),await Bun.write(join7(projectPath,"src","worker.ts"),getWorkerCode()),await Bun.write(join7(projectPath,"wrangler.jsonc"),getWranglerConfig(options.name,{database:options.database,cache:options.cache}))},execIn=async(cwd,command)=>{let proc=Bun.spawn(command,{cwd,stdout:"pipe",stderr:"pipe"});if(await proc.exited!==0)throw Error(`${command.join(" ")} failed: ${await new Response(proc.stderr).text()}`)},CreateCommand;var init_create_command=__esm(()=>{init_esm();init_assets();init_code();init_names();import_prompts11=__toESM(require_prompts3(),1),PACKAGE_MANAGERS=["bun","npm","pnpm"];CreateCommand=class CreateCommand extends Command13{static command="create";static description="Creates a new Elysium project.";static dev=!1;async run(){this.write(`Welcome to ${this.format("Elysium",ConsoleFormat2.MAGENTA,ConsoleFormat2.UNDERLINE)}`),this.newLine();let options=await this.ask(),s=process.stdout.isTTY?this.spinner("Creating project..."):{update:(step)=>this.info(step),complete:(message)=>this.success(message),fail:(message)=>this.error(message)};try{let projectPath=await createProject(options,execIn,(step)=>s.update(step));s.complete(`Project ${options.name} created successfully`);let dev=`${runWith(options.packageManager)} dev`;this.info(`Open it with ${this.format(`cd ${relative4(process.cwd(),projectPath)}`,ConsoleFormat2.BLUE,ConsoleFormat2.BOLD)}, then run ${this.format(dev,ConsoleFormat2.BLUE,ConsoleFormat2.BOLD)}`)}catch(error){s.fail(error instanceof Error?error.message:String(error)),process.exitCode=1}}async ask(){let interactive=!this.yes&&process.stdin.isTTY===!0,given={name:this.name,path:this.path,template:this.template,runtime:this.runtime,database:this.database,cache:this.cache,packageManager:this.packageManager,modules:list2(this.modules),plugins:list2(this.plugins),features:list2(this.features),git:this.git},questions=[{type:given.name?null:"text",name:"name",message:"What is the name of the project?",initial:"elysium-app",validate:(value)=>{try{return validateProjectName(value),!0}catch(error){return error.message}}},{type:given.template?null:"select",name:"template",message:"Which template would you like to use?",choices:[{title:"Single Module",value:"single",description:"A single module project"},{title:"Multi Module",value:"multi",description:"A project with several modules (monolith)"}]},{type:given.runtime?null:"select",name:"runtime",message:"Which runtime will the app run on?",choices:Object.entries(RUNTIMES).map(([value,runtime])=>({title:runtime.title,value,description:runtime.description}))},{type:given.database===void 0?"confirm":null,name:"database",message:"Set up a PostgreSQL database?",initial:!0},{type:given.cache===void 0?"confirm":null,name:"cache",message:"Set up a Redis cache?",initial:!1},{type:given.packageManager?null:"select",name:"packageManager",message:"Which package manager will install the dependencies?",choices:PACKAGE_MANAGERS.map((manager)=>({title:manager,value:manager})),initial:(_,values)=>(given.runtime??values.runtime??"bun")==="bun"?0:1},{type:(_,values)=>given.modules||(given.template??values.template)!=="multi"?null:"list",name:"modules",message:"Which modules would you like to include? (separate by commas)",initial:"main",separator:","},{type:given.plugins?null:"multiselect",name:"plugins",message:"Which plugins would you like to include?",choices:[{title:"Sentry",value:"sentry",description:"Error reporting (https://sentry.io)"}]},{type:given.features?null:"multiselect",name:"features",message:"Select features:",choices:[{title:"Prettier",value:"prettier",description:"Format code with Prettier"},{title:"Hephaestus",value:"hephaestus",description:"Build standalone executables and Docker images"}]},{type:given.git===void 0?"confirm":null,name:"git",message:"Initialize a Git repository?",initial:!0}],answers=interactive?await import_prompts11.default(questions,{onCancel:()=>{this.error("Project creation cancelled."),process.exit(1)}}):{},runtime=given.runtime??answers.runtime??"bun",name=given.name??answers.name;if(!name)throw Error("Give the project a name: styx create my-app");return validateProjectName(name),{name,path:given.path??".",template:given.template??answers.template??"single",runtime,database:given.database??answers.database??!0,cache:given.cache??answers.cache??!1,packageManager:given.packageManager??answers.packageManager??(runtime==="bun"?"bun":"npm"),modules:given.modules??answers.modules??["main"],plugins:given.plugins??answers.plugins??[],features:given.features??answers.features??[],git:given.git??answers.git??!1,install:this.install??!0,force:this.force??!1}}};__legacyDecorateClassTS([Command13.arg({description:"The name of the project",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"name",void 0),__legacyDecorateClassTS([Command13.arg({description:"Where to create the project",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"path",void 0),__legacyDecorateClassTS([Command13.arg({description:"The template: single or multi",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"template",void 0),__legacyDecorateClassTS([Command13.arg({description:"The runtime: bun, node or workers",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"runtime",void 0),__legacyDecorateClassTS([Command13.arg({description:"Set up a PostgreSQL connection",type:CommandArgumentType12.BOOLEAN}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"database",void 0),__legacyDecorateClassTS([Command13.arg({description:"Set up a Redis connection",type:CommandArgumentType12.BOOLEAN}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"cache",void 0),__legacyDecorateClassTS([Command13.arg({name:"package-manager",description:"The package manager: bun, npm or pnpm",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"packageManager",void 0),__legacyDecorateClassTS([Command13.arg({description:"The modules of a multi template, comma separated",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"modules",void 0),__legacyDecorateClassTS([Command13.arg({description:"The plugins to add, comma separated (sentry)",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"plugins",void 0),__legacyDecorateClassTS([Command13.arg({description:"The features to add, comma separated (prettier, hephaestus)",type:CommandArgumentType12.STRING}),__legacyMetadataTS("design:type",String)],CreateCommand.prototype,"features",void 0),__legacyDecorateClassTS([Command13.arg({description:"Initialize a Git repository",type:CommandArgumentType12.BOOLEAN}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"git",void 0),__legacyDecorateClassTS([Command13.arg({description:"Install the dependencies",type:CommandArgumentType12.BOOLEAN,default:!0}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"install",void 0),__legacyDecorateClassTS([Command13.arg({description:"Replace a folder that is not empty",type:CommandArgumentType12.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"force",void 0),__legacyDecorateClassTS([Command13.arg({description:"Use the defaults instead of asking",type:CommandArgumentType12.BOOLEAN,default:!1}),__legacyMetadataTS("design:type",Boolean)],CreateCommand.prototype,"yes",void 0),CreateCommand=__legacyDecorateClassTS([Command13.register()],CreateCommand)});import{Application as Application2,Module}from"@elysiumjs/core";import{runtime as bunRuntime}from"@elysiumjs/runtime-bun";var StyxCliModule,runCli=async(argv,tools=[])=>{class StyxCli extends Application2{}StyxCli=__legacyDecorateClassTS([Application2.register({runtime:bunRuntime,modules:[StyxCliModule,...tools],openapi:!1})],StyxCli),await new StyxCli().run(argv)};var init_app=__esm(()=>{init_commands();init_create_command();StyxCliModule=class StyxCliModule extends Module{};StyxCliModule=__legacyDecorateClassTS([Module.register({commands:[CreateCommand,MakeCommandCommand,MakeControllerCommand,MakeJobCommand,MakeMiddlewareCommand,MakeModelCommand,MakeRepositoryCommand,MakeServiceCommand,MakeValidatorCommand,ModuleNewCommand,ModuleRenameCommand,RoutesGenerateCommand]})],StyxCliModule)});import{existsSync as existsSync4,realpathSync}from"fs";import{dirname as dirname5,join as join8}from"path";var GLOBAL_COMMANDS=new Set(["create","new"]),isGenerator=(command)=>command!==void 0&&/^(make|module):/.test(command),isAppTool=(command)=>command!==void 0&&(command==="build"||/^(routes|hephaestus):/.test(command)),isCliCommand=(command)=>isGenerator(command)||isAppTool(command),withPositionalName=(argv)=>{let[,name,...rest]=argv;if(name===void 0||name.startsWith("--"))return["create",...argv.slice(1)];return["create","--name",name,...rest]},route=(argv,context)=>{let[command]=argv;if(command==="--version"||command==="-v"||command==="version")return{kind:"version"};if(command!==void 0&&GLOBAL_COMMANDS.has(command))return{kind:"cli",argv:withPositionalName(argv)};if(!context.project){if(command===void 0||command==="list"||command==="help"||isCliCommand(command))return isCliCommand(command)?{kind:"error",message:`Run ${command} inside an Elysium project (a folder with an .elysiumrc file).`}:{kind:"cli",argv};return{kind:"error",message:"Not inside an Elysium project (no .elysiumrc found). Create one with: styx create my-app"}}if(context.projectCli&&context.projectCli!==context.self)return{kind:"handoff",cli:context.projectCli,argv};if(isGenerator(command))return{kind:"cli",argv};if(!context.projectCli)return{kind:"error",message:"This project does not install @elysiumjs/styx. Add it with: bun add -D @elysiumjs/styx"};if(command==="build")return{kind:"cli",argv:["hephaestus:build",...argv.slice(1)]};if(isAppTool(command))return{kind:"cli",argv};return{kind:"app",project:context.project,argv}};var findProject=(from)=>{for(let dir=from;;dir=dirname5(dir)){if(existsSync4(join8(dir,".elysiumrc")))return dir;if(dirname5(dir)===dir)return}},resolveFrom=(project,specifier)=>{try{return Bun.resolveSync(specifier,project)}catch{return}},real=(path)=>{try{return realpathSync(path)}catch{return path}},findProjectCli=(project)=>{let cli=resolveFrom(project,"@elysiumjs/styx/dist/cli.js");return cli?real(cli):void 0},loadTools=async(project,isProjectCli)=>{if(!project||!isProjectCli)return[];let entry=resolveFrom(project,"@elysiumjs/hephaestus");if(!entry)return[];let hephaestus=await import(entry);return hephaestus.HephaestusModule?[hephaestus.HephaestusModule]:[]},argv=process.argv.slice(2),project=findProject(process.cwd()),projectCli=project?findProjectCli(project):void 0,self=real(Bun.main),decision=route(argv,{project,projectCli,self});switch(decision.kind){case"version":{let{version}=await Promise.resolve().then(() => __toESM(require_package(),1));console.log(version);break}case"error":console.error(decision.message),process.exit(1);case"handoff":{let bun=Bun.which("bun");if(!bun)console.error("Bun is needed to run the Styx installed in this project: https://bun.sh"),process.exit(1);let proc=Bun.spawn([bun,decision.cli,...decision.argv],{stdio:["inherit","inherit","inherit"]});process.exit(await proc.exited)}case"cli":{await Promise.resolve().then(() => init_app());await runCli(decision.argv,await loadTools(project,projectCli===self));break}case"app":{await Promise.resolve().then(() => init_utils());let{ElysiumError}=await import("@elysiumjs/core");try{await new(await resolveAppEntry(decision.project))().run(decision.argv)}catch(error){if(!(error instanceof ElysiumError))throw error;console.error(error.message),process.exit(1)}break}}
|