@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/commands/index.d.ts
CHANGED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { BaseCommand } from './base.command';
|
|
2
|
+
/**
|
|
3
|
+
* Writes the route types of the app, for typed clients such as Eden: `treaty<AppRoutes>(url)`.
|
|
4
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
5
|
+
*/
|
|
6
|
+
export declare class RoutesGenerateCommand extends BaseCommand {
|
|
7
|
+
static readonly command: string;
|
|
8
|
+
static readonly description: string;
|
|
9
|
+
private out?;
|
|
10
|
+
run(): Promise<void>;
|
|
11
|
+
}
|
package/dist/config.d.ts
CHANGED
|
@@ -17,6 +17,11 @@ export interface ProjectConfig {
|
|
|
17
17
|
* Only used if the Elysium project is not a mono module.
|
|
18
18
|
*/
|
|
19
19
|
modules?: Record<string, string>;
|
|
20
|
+
/**
|
|
21
|
+
* The file `styx routes:generate` writes the route types to, relative to the project.
|
|
22
|
+
* @default 'src/routes.gen.ts'
|
|
23
|
+
*/
|
|
24
|
+
routes?: string;
|
|
20
25
|
}
|
|
21
26
|
/**
|
|
22
27
|
* Parses the Elysium project's configuration file.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The version range written to the `package.json` of a new project for a package: a caret range
|
|
3
|
+
* on the version released with Styx for `@elysiumjs/*` (each package has its own version), a
|
|
4
|
+
* known range for the tools features add.
|
|
5
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
6
|
+
* @param name The package name.
|
|
7
|
+
* @throws When no version is known for the package.
|
|
8
|
+
*/
|
|
9
|
+
export declare const versionFor: (name: string) => string;
|
|
10
|
+
export declare const getModuleCode: (module: string) => string;
|
|
11
|
+
/**
|
|
12
|
+
* A runtime the generated app can run on.
|
|
13
|
+
*/
|
|
14
|
+
export type RuntimeChoice = {
|
|
15
|
+
/** The prompt label. */
|
|
16
|
+
title: string;
|
|
17
|
+
/** The prompt hint. */
|
|
18
|
+
description: string;
|
|
19
|
+
/** The package exporting the runtime as `runtime`. */
|
|
20
|
+
package: string;
|
|
21
|
+
/** The local name the app imports `runtime` as. */
|
|
22
|
+
alias: string;
|
|
23
|
+
/** The `types` of the generated tsconfig. */
|
|
24
|
+
types: string[];
|
|
25
|
+
/** The development packages the runtime needs. */
|
|
26
|
+
devPackages: string[];
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* The runtimes offered by the runtime step, by prompt value.
|
|
30
|
+
*/
|
|
31
|
+
export declare const RUNTIMES: Record<'bun' | 'node' | 'workers', RuntimeChoice>;
|
|
32
|
+
/**
|
|
33
|
+
* The parts of the generated app that can be left out.
|
|
34
|
+
*/
|
|
35
|
+
export type AppParts = {
|
|
36
|
+
/** A PostgreSQL connection through `@elysiumjs/mnemosyne-drizzle`. */
|
|
37
|
+
database: boolean;
|
|
38
|
+
/** A Redis connection through `@elysiumjs/redis`. */
|
|
39
|
+
cache: boolean;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* The packages the app of a runtime needs for its parts.
|
|
43
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
44
|
+
* @param runtime The runtime key.
|
|
45
|
+
* @param parts The parts of the app.
|
|
46
|
+
*/
|
|
47
|
+
export declare const appPackages: (runtime: keyof typeof RUNTIMES, parts: AppParts) => {
|
|
48
|
+
prod: string[];
|
|
49
|
+
dev: string[];
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* A module added to the generated app by a plugin or a feature.
|
|
53
|
+
*/
|
|
54
|
+
export type EnabledModule = {
|
|
55
|
+
/** The package to import the module from. */
|
|
56
|
+
name: string;
|
|
57
|
+
/** The exported name of the module. */
|
|
58
|
+
import: string;
|
|
59
|
+
/** The expression to put in the app's `modules` list. */
|
|
60
|
+
expression: string;
|
|
61
|
+
};
|
|
62
|
+
export declare const getAppCode: (projectName: string, modules: Record<string, string>, enabledModules?: EnabledModule[], runtime?: keyof typeof RUNTIMES, parts?: AppParts) => string;
|
|
63
|
+
/**
|
|
64
|
+
* The scripts of a project, per runtime and package manager.
|
|
65
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
66
|
+
* @param runtime The runtime key.
|
|
67
|
+
*/
|
|
68
|
+
export declare const getScripts: (runtime: keyof typeof RUNTIMES) => Record<string, string>;
|
|
69
|
+
/** The Worker entry of a Cloudflare Workers project. */
|
|
70
|
+
export declare const getWorkerCode: () => string;
|
|
71
|
+
/**
|
|
72
|
+
* The wrangler config of a Cloudflare Workers project.
|
|
73
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
74
|
+
* @param projectName The project name.
|
|
75
|
+
* @param parts The parts of the app, for the bindings they need.
|
|
76
|
+
*/
|
|
77
|
+
export declare const getWranglerConfig: (projectName: string, parts: AppParts) => string;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { Command } from '@elysiumjs/core';
|
|
2
|
+
import { RUNTIMES } from './code';
|
|
3
|
+
/** The package managers `styx create` can install with. */
|
|
4
|
+
export declare const PACKAGE_MANAGERS: readonly ['bun', 'npm', 'pnpm'];
|
|
5
|
+
/** A package manager `styx create` can install with. */
|
|
6
|
+
export type PackageManager = (typeof PACKAGE_MANAGERS)[number];
|
|
7
|
+
/** The answers that describe the project to create. */
|
|
8
|
+
export type CreateOptions = {
|
|
9
|
+
name: string;
|
|
10
|
+
path: string;
|
|
11
|
+
template: 'single' | 'multi';
|
|
12
|
+
runtime: keyof typeof RUNTIMES;
|
|
13
|
+
/** Whether to set up a PostgreSQL connection. */
|
|
14
|
+
database: boolean;
|
|
15
|
+
/** Whether to set up a Redis connection. */
|
|
16
|
+
cache: boolean;
|
|
17
|
+
/** The package manager that installs the dependencies and runs the scripts. */
|
|
18
|
+
packageManager: PackageManager;
|
|
19
|
+
modules: string[];
|
|
20
|
+
plugins: string[];
|
|
21
|
+
features: string[];
|
|
22
|
+
git: boolean;
|
|
23
|
+
install: boolean;
|
|
24
|
+
force: boolean;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Writes a new Elysium project. Installing dependencies and running git are left to `run`.
|
|
28
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
29
|
+
* @param options The project to create.
|
|
30
|
+
* @param exec Runs a shell command in the project folder.
|
|
31
|
+
* @param progress Reports the current step.
|
|
32
|
+
* @returns The folder of the new project.
|
|
33
|
+
*/
|
|
34
|
+
export declare const createProject: (options: CreateOptions, exec: (cwd: string, command: string[]) => Promise<void>, progress?: (step: string) => void) => Promise<string>;
|
|
35
|
+
/**
|
|
36
|
+
* Creates a new Elysium project: `styx create my-app`. Asks for what the arguments leave out.
|
|
37
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
38
|
+
*/
|
|
39
|
+
export declare class CreateCommand extends Command {
|
|
40
|
+
static readonly command: string;
|
|
41
|
+
static readonly description: string;
|
|
42
|
+
static readonly dev: boolean;
|
|
43
|
+
private name?;
|
|
44
|
+
private path?;
|
|
45
|
+
private template?;
|
|
46
|
+
private runtime?;
|
|
47
|
+
private database?;
|
|
48
|
+
private cache?;
|
|
49
|
+
private packageManager?;
|
|
50
|
+
private modules?;
|
|
51
|
+
private plugins?;
|
|
52
|
+
private features?;
|
|
53
|
+
private git?;
|
|
54
|
+
private install?;
|
|
55
|
+
private force?;
|
|
56
|
+
private yes?;
|
|
57
|
+
run(): Promise<void>;
|
|
58
|
+
/** Builds the options from the arguments, asking for what they leave out. */
|
|
59
|
+
private ask;
|
|
60
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { ElysiumError } from '@elysiumjs/core';
|
|
2
|
+
/**
|
|
3
|
+
* Thrown when a project or module name given to `styx create` is not usable.
|
|
4
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
5
|
+
*/
|
|
6
|
+
export declare class InvalidNameError extends ElysiumError {
|
|
7
|
+
readonly kind: string;
|
|
8
|
+
readonly value: string;
|
|
9
|
+
readonly reason: string;
|
|
10
|
+
/**
|
|
11
|
+
* @param kind What the name is for, such as `project` or `module`.
|
|
12
|
+
* @param value The refused name.
|
|
13
|
+
* @param reason Why it is refused.
|
|
14
|
+
*/
|
|
15
|
+
constructor(kind: string, value: string, reason: string);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Checks a project name, which must be a lower-case npm package name, optionally scoped.
|
|
19
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
20
|
+
* @param name The project name.
|
|
21
|
+
* @returns The name of the project directory: the name without its scope.
|
|
22
|
+
* @throws {InvalidNameError} When the name is not a valid package name.
|
|
23
|
+
*/
|
|
24
|
+
export declare const validateProjectName: (name: string) => string;
|
|
25
|
+
/**
|
|
26
|
+
* Checks a module name.
|
|
27
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
28
|
+
* @param name The module name.
|
|
29
|
+
* @returns The name, unchanged.
|
|
30
|
+
* @throws {InvalidNameError} When the name does not start with a lower-case letter followed by
|
|
31
|
+
* lower-case letters, digits or "-".
|
|
32
|
+
*/
|
|
33
|
+
export declare const validateModuleName: (name: string) => string;
|
|
34
|
+
/**
|
|
35
|
+
* Resolves the directory of a new project, which must lie strictly inside `base`.
|
|
36
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
37
|
+
* @param base The folder the project is created in.
|
|
38
|
+
* @param directory The project directory, from {@link validateProjectName}.
|
|
39
|
+
* @returns The absolute project path.
|
|
40
|
+
* @throws {InvalidNameError} When the path would leave `base` or be `base` itself.
|
|
41
|
+
*/
|
|
42
|
+
export declare const resolveProjectPath: (base: string, directory: string) => string;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The versions of the `@elysiumjs/*` packages of the workspace Styx is built in, by name. Import
|
|
3
|
+
* it as a macro (`with { type: 'macro' }`): the map is read when Styx is bundled, so the published
|
|
4
|
+
* CLI writes the versions it was released with.
|
|
5
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
6
|
+
*/
|
|
7
|
+
export declare const elysiumVersions: () => Record<string, string>;
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
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 __require=import.meta.require;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.
|
|
2
|
+
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;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.
|
|
3
3
|
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(`
|
|
4
4
|
`)).join(`
|
|
5
5
|
`)}});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(`
|
|
@@ -95,7 +95,7 @@ Instructions:
|
|
|
95
95
|
Filtered results for: ${this.inputValue?this.inputValue:color.gray("Enter something to filter")}
|
|
96
96
|
`}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(`
|
|
97
97
|
`),this.close()}submit(){this.value=this.value||!1,this.done=!0,this.aborted=!1,this.fire(),this.render(),this.out.write(`
|
|
98
|
-
`),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
|
|
98
|
+
`),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';
|
|
99
99
|
|
|
100
100
|
@Module.register({
|
|
101
101
|
services: [],
|
|
@@ -103,4 +103,10 @@ Filtered results for: ${this.inputValue?this.inputValue:color.gray("Enter someth
|
|
|
103
103
|
commands: []
|
|
104
104
|
})
|
|
105
105
|
export class ${className} extends Module {}
|
|
106
|
-
`)}}if(oldName)if(oldName==="root"){let entries=await readdir(join(root,"src"));for(let entry of entries){if(["app.ts","env.ts","database","modules"].includes(entry))continue;let oldPath=join(root,"src",entry),newPath=join(moduleDir,entry==="main.module.ts"?`${name}.module.ts`:entry);await rename(oldPath,newPath)}}else{let oldModuleDir=join(root,"src","modules",oldName);await rename(oldModuleDir,moduleDir)}}{let pkg=await Bun.file(join(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(join(root,"package.json"),JSON.stringify(pkg,null,2))}{let rc=await Bun.file(join(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(join(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=join(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 parseProjectConfig=async()=>{let file=Bun.file(join2(getProjectPath(),".elysiumrc"));if(!file.exists())throw Error("Elysium config file not found.");return file.json()};var 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.`};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 stubFile=Bun.file(join3(getRootPath(),"stubs/command.stub")),stub=import_string_template.default(await stubFile.text(),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);var import_prompts2=__toESM(require_prompts3(),1);import{join as join4}from"path";import{Command as Command3,CommandArgumentType as CommandArgumentType2}from"@elysiumjs/core";var import_string_template2=__toESM(require_string_template(),1);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 stubFile=Bun.file(join4(getRootPath(),`stubs/${answers.type}.controller.stub`)),stub=import_string_template2.default(await stubFile.text(),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);var import_prompts3=__toESM(require_prompts3(),1);import{join as join5}from"path";import{Command as Command4,CommandArgumentType as CommandArgumentType3}from"@elysiumjs/core";var import_string_template3=__toESM(require_string_template(),1);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 stubFile=Bun.file(join5(getRootPath(),"stubs/job.stub")),stub=import_string_template3.default(await stubFile.text(),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);var import_prompts4=__toESM(require_prompts3(),1);import{join as join6}from"path";import{Command as Command5,CommandArgumentType as CommandArgumentType4}from"@elysiumjs/core";var import_string_template4=__toESM(require_string_template(),1);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 stubFile=Bun.file(join6(getRootPath(),"stubs/middleware.stub")),stub=import_string_template4.default(await stubFile.text(),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);var import_prompts5=__toESM(require_prompts3(),1);import{join as join7}from"path";import{Command as Command6,CommandArgumentType as CommandArgumentType5}from"@elysiumjs/core";var import_string_template5=__toESM(require_string_template(),1);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 stubFile=Bun.file(join7(getRootPath(),"stubs/model.stub")),stub=import_string_template5.default(await stubFile.text(),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);var import_prompts6=__toESM(require_prompts3(),1);import{join as join8}from"path";import{Command as Command7,CommandArgumentType as CommandArgumentType6}from"@elysiumjs/core";var import_string_template6=__toESM(require_string_template(),1);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 stubFile=Bun.file(join8(getRootPath(),"stubs/repository.stub")),stub=import_string_template6.default(await stubFile.text(),{...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);var import_prompts7=__toESM(require_prompts3(),1);import{join as join9}from"path";import{Command as Command8,CommandArgumentType as CommandArgumentType7}from"@elysiumjs/core";var import_string_template7=__toESM(require_string_template(),1);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 stubFile=Bun.file(join9(getRootPath(),"stubs/service.stub")),stub=import_string_template7.default(await stubFile.text(),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);var import_prompts8=__toESM(require_prompts3(),1);import{join as join10}from"path";import{Command as Command9,CommandArgumentType as CommandArgumentType8}from"@elysiumjs/core";var import_string_template8=__toESM(require_string_template(),1);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 stubFile=Bun.file(join10(getRootPath(),"stubs/validator.stub")),stub=import_string_template8.default(await stubFile.text(),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);var import_prompts9=__toESM(require_prompts3(),1);import{exists,rm}from"fs/promises";import{join as join11}from"path";import{Command as Command10,CommandArgumentType as CommandArgumentType9}from"@elysiumjs/core";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=join11(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);var import_prompts10=__toESM(require_prompts3(),1);import{Command as Command11,CommandArgumentType as CommandArgumentType10}from"@elysiumjs/core";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);class StyxModule extends Module{}StyxModule=__legacyDecorateClassTS([Module.register({env:["development"],commands:[MakeCommandCommand,MakeControllerCommand,MakeJobCommand,MakeMiddlewareCommand,MakeModelCommand,MakeRepositoryCommand,MakeServiceCommand,MakeValidatorCommand,ModuleNewCommand,ModuleRenameCommand]})],StyxModule);export{StyxModule};
|
|
106
|
+
`)}}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)=>`
|
|
107
|
+
${renderRoute(local.get(controller),route)}`).join("");return`
|
|
108
|
+
.use(
|
|
109
|
+
routes(${quote(controller.path)})${chain}
|
|
110
|
+
)`}),prefix=module.prefix?quote(module.prefix):"";lines.push(`/** The routes of the module ${module.id}. */`),lines.push(`const ${name} = () =>
|
|
111
|
+
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(`
|
|
112
|
+
`)};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()});init_commands();import{Module}from"@elysiumjs/core";class StyxModule extends Module{}StyxModule=__legacyDecorateClassTS([Module.register({env:["development"],commands:[MakeCommandCommand,MakeControllerCommand,MakeJobCommand,MakeMiddlewareCommand,MakeModelCommand,MakeRepositoryCommand,MakeServiceCommand,MakeValidatorCommand,ModuleNewCommand,ModuleRenameCommand]})],StyxModule);export{StyxModule};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Application } from '@elysiumjs/core';
|
|
2
|
+
import type { ModuleRoutes } from './render';
|
|
3
|
+
/**
|
|
4
|
+
* The result of reading the routes of an app.
|
|
5
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
6
|
+
*/
|
|
7
|
+
export type CollectedRoutes = {
|
|
8
|
+
/** The modules with controllers, in mounting order. */
|
|
9
|
+
modules: ModuleRoutes[];
|
|
10
|
+
/** Controllers whose source file was not found in the project; their routes are left out. */
|
|
11
|
+
missing: string[];
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Reads the modules, controllers and routes of an app, without booting it.
|
|
15
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
16
|
+
* @param projectPath The project folder.
|
|
17
|
+
* @param app The application class, already imported.
|
|
18
|
+
* @param outFile The file the routes will be written to, to compute import paths.
|
|
19
|
+
*/
|
|
20
|
+
export declare const collectRoutes: (projectPath: string, app: typeof Application, outFile: string) => Promise<CollectedRoutes>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { HttpRouteDescription } from '@elysiumjs/core';
|
|
2
|
+
/**
|
|
3
|
+
* A controller whose routes go in the generated types.
|
|
4
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
5
|
+
*/
|
|
6
|
+
export type ControllerRoutes = {
|
|
7
|
+
/** The exported name of the controller class, `default` for a default export. */
|
|
8
|
+
exportName: string;
|
|
9
|
+
/** The name of the controller class. Names a default export, which has no name of its own. */
|
|
10
|
+
className?: string;
|
|
11
|
+
/** The module specifier the generated file imports the class from. */
|
|
12
|
+
specifier: string;
|
|
13
|
+
/** The path of the controller. */
|
|
14
|
+
path: string;
|
|
15
|
+
/** The routes of the controller. */
|
|
16
|
+
routes: HttpRouteDescription[];
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* A module whose controllers go in the generated types.
|
|
20
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
21
|
+
*/
|
|
22
|
+
export type ModuleRoutes = {
|
|
23
|
+
/** The id of the module. */
|
|
24
|
+
id: string;
|
|
25
|
+
/** The prefix of every controller path in the module. */
|
|
26
|
+
prefix?: string;
|
|
27
|
+
/** The controllers of the module, in mounting order. */
|
|
28
|
+
controllers: ControllerRoutes[];
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Renders the file holding the route types of an app, for typed clients such as Eden.
|
|
32
|
+
*
|
|
33
|
+
* The file is type-only: it declares one Elysia chain per module, built from the controller
|
|
34
|
+
* routes, whose parameter, query, body and response types come from the controller method
|
|
35
|
+
* signatures. Nothing in it runs.
|
|
36
|
+
* @author Axel Nana <axel.nana@workbud.com>
|
|
37
|
+
* @param modules The modules with controllers, in mounting order.
|
|
38
|
+
*/
|
|
39
|
+
export declare const renderRoutes: (modules: ModuleRoutes[]) => string;
|