reciple 10.0.5 → 10.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/commands/build.d.mts +1 -6
- package/dist/bin/commands/build.mjs +3 -2
- package/dist/bin/commands/build.mjs.map +1 -1
- package/dist/bin/commands/create.mjs +2 -3
- package/dist/bin/commands/create.mjs.map +1 -1
- package/dist/bin/commands/createModule.d.mts +0 -1
- package/dist/bin/commands/createModule.mjs +3 -2
- package/dist/bin/commands/createModule.mjs.map +1 -1
- package/dist/bin/commands/start.d.mts +0 -1
- package/dist/bin/commands/start.mjs +3 -2
- package/dist/bin/commands/start.mjs.map +1 -1
- package/dist/bin/commands/startSharding.mjs +3 -2
- package/dist/bin/commands/startSharding.mjs.map +1 -1
- package/dist/classes/cli/CLI.d.mts +1 -0
- package/dist/classes/cli/CLI.mjs +9 -1
- package/dist/classes/cli/CLI.mjs.map +1 -1
- package/dist/classes/cli/ConfigReader.d.mts +1 -4
- package/dist/classes/cli/ConfigReader.mjs +3 -8
- package/dist/classes/cli/ConfigReader.mjs.map +1 -1
- package/dist/classes/templates/TemplateBuilder.d.mts +1 -3
- package/dist/classes/templates/TemplateBuilder.mjs +28 -36
- package/dist/classes/templates/TemplateBuilder.mjs.map +1 -1
- package/dist/classes/validation/CommandModuleValidator.d.mts +17 -17
- package/dist/classes/validation/EventModuleValidator.d.mts +9 -9
- package/dist/classes/validation/PostconditionModule.d.mts +8 -8
- package/dist/classes/validation/PreconditionModule.d.mts +7 -7
- package/dist/package.mjs +5 -5
- package/package.json +5 -5
|
@@ -6,11 +6,6 @@ declare class BuildSubcommand extends CLISubcommand {
|
|
|
6
6
|
subcommand: Command;
|
|
7
7
|
execute(): Promise<void>;
|
|
8
8
|
}
|
|
9
|
-
declare namespace BuildSubcommand {
|
|
10
|
-
interface Flags {
|
|
11
|
-
config?: string;
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
9
|
//#endregion
|
|
15
|
-
export { BuildSubcommand
|
|
10
|
+
export { BuildSubcommand as default };
|
|
16
11
|
//# sourceMappingURL=build.d.mts.map
|
|
@@ -6,9 +6,10 @@ import { build } from "tsdown";
|
|
|
6
6
|
|
|
7
7
|
//#region src/bin/commands/build.ts
|
|
8
8
|
var BuildSubcommand = class extends CLISubcommand {
|
|
9
|
-
subcommand = new Command("build").description("Build the reciple modules defined in config file").
|
|
9
|
+
subcommand = new Command("build").description("Build the reciple modules defined in config file").argument("[project]", "The root directory of your project");
|
|
10
10
|
async execute() {
|
|
11
|
-
|
|
11
|
+
await this.cli.setCurrentDirectory(this.subcommand.args[0]);
|
|
12
|
+
const { build: buildConfig } = await new ConfigReader(await ConfigReader.find() ?? ConfigReader.createConfigFilename("js")).read();
|
|
12
13
|
let plugins = buildConfig.plugins ? Array.isArray(buildConfig.plugins) ? buildConfig.plugins : [buildConfig.plugins] : [];
|
|
13
14
|
plugins.push(CLI.createTsdownLogger(this.cli.logger));
|
|
14
15
|
await build({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.mjs","names":[],"sources":["../../../src/bin/commands/build.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport { build } from 'tsdown';\nimport { CLI } from '../../classes/cli/CLI.js';\n\nexport default class BuildSubcommand extends CLISubcommand {\n public subcommand: Command = new Command('build')\n .description('Build the reciple modules defined in config file')\n .
|
|
1
|
+
{"version":3,"file":"build.mjs","names":[],"sources":["../../../src/bin/commands/build.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport { build } from 'tsdown';\nimport { CLI } from '../../classes/cli/CLI.js';\n\nexport default class BuildSubcommand extends CLISubcommand {\n public subcommand: Command = new Command('build')\n .description('Build the reciple modules defined in config file')\n .argument('[project]', 'The root directory of your project');\n\n public async execute(): Promise<void> {\n await this.cli.setCurrentDirectory(this.subcommand.args[0]);\n\n const configReader = new ConfigReader(\n await ConfigReader.find()\n ?? ConfigReader.createConfigFilename('js')\n );\n\n const { build: buildConfig } = await configReader.read();\n\n let plugins = buildConfig.plugins\n ? Array.isArray(buildConfig.plugins)\n ? buildConfig.plugins\n : [buildConfig.plugins]\n : [];\n\n plugins.push(CLI.createTsdownLogger(this.cli.logger));\n\n await build({\n ...buildConfig,\n logLevel: 'silent',\n plugins,\n });\n }\n}\n"],"mappings":";;;;;;;AAMA,IAAqB,kBAArB,cAA6C,cAAc;CACvD,AAAO,aAAsB,IAAI,QAAQ,QAAQ,CAC5C,YAAY,mDAAmD,CAC/D,SAAS,aAAa,qCAAqC;CAEhE,MAAa,UAAyB;AAClC,QAAM,KAAK,IAAI,oBAAoB,KAAK,WAAW,KAAK,GAAG;EAO3D,MAAM,EAAE,OAAO,gBAAgB,MALV,IAAI,aACrB,MAAM,aAAa,MAAM,IACtB,aAAa,qBAAqB,KAAK,CAC7C,CAEiD,MAAM;EAExD,IAAI,UAAU,YAAY,UACpB,MAAM,QAAQ,YAAY,QAAQ,GAC9B,YAAY,UACZ,CAAC,YAAY,QAAQ,GACzB,EAAE;AAER,UAAQ,KAAK,IAAI,mBAAmB,KAAK,IAAI,OAAO,CAAC;AAErD,QAAM,MAAM;GACR,GAAG;GACH,UAAU;GACV;GACH,CAAC"}
|
|
@@ -8,7 +8,7 @@ import { inspect } from "node:util";
|
|
|
8
8
|
|
|
9
9
|
//#region src/bin/commands/create.ts
|
|
10
10
|
var CreateSubcommand = class extends CLISubcommand {
|
|
11
|
-
subcommand = new Command("create").description("Create a new reciple project").argument("[
|
|
11
|
+
subcommand = new Command("create").description("Create a new reciple project").argument("[project]", "The root directory of your project").option("-c, --config <path>", "Path to the configuration file").option("-t, --token <DiscordToken>", "Set your Discord Bot token").option("-T, --typescript", "Use TypeScript").addOption(new Option("-p, --package-manager <name>", "The name of the package manager to use").choices([
|
|
12
12
|
"npm",
|
|
13
13
|
"yarn",
|
|
14
14
|
"pnpm",
|
|
@@ -19,7 +19,6 @@ var CreateSubcommand = class extends CLISubcommand {
|
|
|
19
19
|
const flags = this.cli.getFlags("create");
|
|
20
20
|
const template = new TemplateBuilder({
|
|
21
21
|
cli: this.cli,
|
|
22
|
-
directory: this.subcommand.args[0],
|
|
23
22
|
typescript: flags?.typescript,
|
|
24
23
|
packageManager: flags?.packageManager,
|
|
25
24
|
defaultAll: flags?.default,
|
|
@@ -27,7 +26,7 @@ var CreateSubcommand = class extends CLISubcommand {
|
|
|
27
26
|
});
|
|
28
27
|
try {
|
|
29
28
|
await template.init();
|
|
30
|
-
await template.createDirectory();
|
|
29
|
+
await template.createDirectory({ directory: this.subcommand.args[0] });
|
|
31
30
|
await template.setupLanguage();
|
|
32
31
|
await template.createConfig();
|
|
33
32
|
await template.createEnvFile({ envFile: this.cli.flags.env[0] });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.mjs","names":[],"sources":["../../../src/bin/commands/create.ts"],"sourcesContent":["import { Command, Option } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { TemplateBuilder } from '../../classes/templates/TemplateBuilder.js';\nimport { cancel } from '@clack/prompts';\nimport { inspect } from 'node:util';\nimport { NotAnError } from '../../classes/NotAnError.js';\nimport type { PackageManagerName } from 'nypm';\nimport { colors } from '@prtty/prtty';\n\nexport default class CreateSubcommand extends CLISubcommand {\n public subcommand: Command = new Command('create')\n .description('Create a new reciple project')\n .argument('[
|
|
1
|
+
{"version":3,"file":"create.mjs","names":[],"sources":["../../../src/bin/commands/create.ts"],"sourcesContent":["import { Command, Option } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { TemplateBuilder } from '../../classes/templates/TemplateBuilder.js';\nimport { cancel } from '@clack/prompts';\nimport { inspect } from 'node:util';\nimport { NotAnError } from '../../classes/NotAnError.js';\nimport type { PackageManagerName } from 'nypm';\nimport { colors } from '@prtty/prtty';\n\nexport default class CreateSubcommand extends CLISubcommand {\n public subcommand: Command = new Command('create')\n .description('Create a new reciple project')\n .argument('[project]', 'The root directory of your project')\n .option('-c, --config <path>', 'Path to the configuration file')\n .option('-t, --token <DiscordToken>', 'Set your Discord Bot token')\n .option('-T, --typescript', 'Use TypeScript')\n .addOption(new Option('-p, --package-manager <name>', 'The name of the package manager to use')\n .choices(['npm', 'yarn', 'pnpm', 'bun', 'deno'])\n )\n .option('-D, --default', 'Use defaults for prompts')\n .option('--install', 'Install dependencies during setup', true)\n .option('--no-install', 'Do not install dependencies during setup')\n .option('--build', 'Build the project after creation', true)\n .option('--no-build', 'Do not build the project after creation')\n .allowUnknownOption(true);\n\n public async execute(): Promise<void> {\n const flags = this.cli.getFlags<CreateSubcommand.Flags>('create');\n const template = new TemplateBuilder({\n cli: this.cli,\n typescript: flags?.typescript,\n packageManager: flags?.packageManager,\n defaultAll: flags?.default,\n token: flags?.token,\n });\n\n try {\n await template.init();\n await template.createDirectory({ directory: this.subcommand.args[0] });\n await template.setupLanguage();\n await template.createConfig();\n await template.createEnvFile({ envFile: this.cli.flags.env[0] });\n await template.createTemplate();\n await template.setPackageManager();\n await template.installDependencies({ value: flags?.install });\n await template.createModules();\n await template.build({ skipBuild: !flags?.build });\n } catch (error) {\n cancel(colors.red(error instanceof NotAnError ? error.message : inspect(error)));\n }\n }\n}\n\nexport namespace CreateSubcommand {\n export interface Flags {\n config?: string;\n token?: string;\n default?: boolean;\n typescript?: boolean;\n packageManager?: PackageManagerName;\n install: boolean;\n build: boolean;\n }\n}\n"],"mappings":";;;;;;;;;AASA,IAAqB,mBAArB,cAA8C,cAAc;CACxD,AAAO,aAAsB,IAAI,QAAQ,SAAS,CAC7C,YAAY,+BAA+B,CAC3C,SAAS,aAAa,qCAAqC,CAC3D,OAAO,uBAAuB,iCAAiC,CAC/D,OAAO,8BAA8B,6BAA6B,CAClE,OAAO,oBAAoB,iBAAiB,CAC5C,UAAU,IAAI,OAAO,gCAAgC,yCAAyC,CAC1F,QAAQ;EAAC;EAAO;EAAQ;EAAQ;EAAO;EAAO,CAAC,CACnD,CACA,OAAO,iBAAiB,2BAA2B,CACnD,OAAO,aAAa,qCAAqC,KAAK,CAC9D,OAAO,gBAAgB,2CAA2C,CAClE,OAAO,WAAW,oCAAoC,KAAK,CAC3D,OAAO,cAAc,0CAA0C,CAC/D,mBAAmB,KAAK;CAE7B,MAAa,UAAyB;EAClC,MAAM,QAAQ,KAAK,IAAI,SAAiC,SAAS;EACjE,MAAM,WAAW,IAAI,gBAAgB;GACjC,KAAK,KAAK;GACV,YAAY,OAAO;GACnB,gBAAgB,OAAO;GACvB,YAAY,OAAO;GACnB,OAAO,OAAO;GACjB,CAAC;AAEF,MAAI;AACA,SAAM,SAAS,MAAM;AACrB,SAAM,SAAS,gBAAgB,EAAE,WAAW,KAAK,WAAW,KAAK,IAAI,CAAC;AACtE,SAAM,SAAS,eAAe;AAC9B,SAAM,SAAS,cAAc;AAC7B,SAAM,SAAS,cAAc,EAAE,SAAS,KAAK,IAAI,MAAM,IAAI,IAAI,CAAC;AAChE,SAAM,SAAS,gBAAgB;AAC/B,SAAM,SAAS,mBAAmB;AAClC,SAAM,SAAS,oBAAoB,EAAE,OAAO,OAAO,SAAS,CAAC;AAC7D,SAAM,SAAS,eAAe;AAC9B,SAAM,SAAS,MAAM,EAAE,WAAW,CAAC,OAAO,OAAO,CAAC;WAC7C,OAAO;AACZ,UAAO,OAAO,IAAI,iBAAiB,aAAa,MAAM,UAAU,QAAQ,MAAM,CAAC,CAAC"}
|
|
@@ -9,11 +9,12 @@ import { inspect } from "node:util";
|
|
|
9
9
|
|
|
10
10
|
//#region src/bin/commands/createModule.ts
|
|
11
11
|
var CreateModuleSubcommand = class extends CLISubcommand {
|
|
12
|
-
subcommand = new Command("module").description("Creates new module").argument("[
|
|
12
|
+
subcommand = new Command("module").description("Creates new reciple module").argument("[project]", "The root directory of your project").option("--template, -t <template>", "Template source name").option("--filename", "The filename of the module").option("-T, --typescript", "Use TypeScript").option("-D, --default", "Use defaults for prompts").enablePositionalOptions(true);
|
|
13
13
|
parent = "create";
|
|
14
14
|
async execute() {
|
|
15
15
|
const flags = this.subcommand.opts();
|
|
16
|
-
|
|
16
|
+
await this.cli.setCurrentDirectory(this.subcommand.args[0]);
|
|
17
|
+
const configReader = await new ConfigReader(await ConfigReader.find() ?? ConfigReader.createConfigFilename("js")).read();
|
|
17
18
|
const template = new ModuleTemplateBuilder({
|
|
18
19
|
cli: this.cli,
|
|
19
20
|
config: configReader,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createModule.mjs","names":[],"sources":["../../../src/bin/commands/createModule.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport { ModuleTemplateBuilder } from '../../classes/templates/ModuleTemplateBuilder.js';\nimport { cancel } from '@clack/prompts';\nimport { colors } from '@prtty/prtty';\nimport { NotAnError } from '../../classes/NotAnError.js';\nimport { inspect } from 'node:util';\n\nexport default class CreateModuleSubcommand extends CLISubcommand {\n public subcommand: Command = new Command('module')\n .description('Creates new module')\n .argument('[
|
|
1
|
+
{"version":3,"file":"createModule.mjs","names":[],"sources":["../../../src/bin/commands/createModule.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport { ModuleTemplateBuilder } from '../../classes/templates/ModuleTemplateBuilder.js';\nimport { cancel } from '@clack/prompts';\nimport { colors } from '@prtty/prtty';\nimport { NotAnError } from '../../classes/NotAnError.js';\nimport { inspect } from 'node:util';\n\nexport default class CreateModuleSubcommand extends CLISubcommand {\n public subcommand: Command = new Command('module')\n .description('Creates new reciple module')\n .argument('[project]', 'The root directory of your project')\n .option('--template, -t <template>', 'Template source name')\n .option('--filename', 'The filename of the module')\n .option('-T, --typescript', 'Use TypeScript')\n .option('-D, --default', 'Use defaults for prompts')\n .enablePositionalOptions(true);\n\n public parent: string = 'create';\n\n public async execute(): Promise<void> {\n const flags = this.subcommand.opts<CreateModuleSubcommand.Flags>();\n\n await this.cli.setCurrentDirectory(this.subcommand.args[0]);\n\n const configReader = await new ConfigReader(\n await ConfigReader.find()\n ?? ConfigReader.createConfigFilename('js')\n ).read();\n\n const template = new ModuleTemplateBuilder({\n cli: this.cli,\n config: configReader,\n typescript: flags.typescript,\n filename: flags.filename,\n defaultAll: flags?.default\n });\n\n try {\n await template.init();\n await template.setupLanguage();\n await template.setupTemplate();\n await template.setupPlaceholders();\n await template.setupDirectory();\n await template.setupFilename();\n await template.build();\n } catch (error) {\n cancel(colors.red(error instanceof NotAnError ? error.message : inspect(error)));\n }\n }\n}\n\nexport namespace CreateModuleSubcommand {\n export interface Flags {\n template?: string;\n filename?: string;\n typescript?: boolean;\n default?: boolean;\n }\n}\n"],"mappings":";;;;;;;;;;AASA,IAAqB,yBAArB,cAAoD,cAAc;CAC9D,AAAO,aAAsB,IAAI,QAAQ,SAAS,CAC7C,YAAY,6BAA6B,CACzC,SAAS,aAAa,qCAAqC,CAC3D,OAAO,6BAA6B,uBAAuB,CAC3D,OAAO,cAAc,6BAA6B,CAClD,OAAO,oBAAoB,iBAAiB,CAC5C,OAAO,iBAAiB,2BAA2B,CACnD,wBAAwB,KAAK;CAElC,AAAO,SAAiB;CAExB,MAAa,UAAyB;EAClC,MAAM,QAAQ,KAAK,WAAW,MAAoC;AAElE,QAAM,KAAK,IAAI,oBAAoB,KAAK,WAAW,KAAK,GAAG;EAE3D,MAAM,eAAe,MAAM,IAAI,aAC3B,MAAM,aAAa,MAAM,IACtB,aAAa,qBAAqB,KAAK,CAC7C,CAAC,MAAM;EAER,MAAM,WAAW,IAAI,sBAAsB;GACvC,KAAK,KAAK;GACV,QAAQ;GACR,YAAY,MAAM;GAClB,UAAU,MAAM;GAChB,YAAY,OAAO;GACtB,CAAC;AAEF,MAAI;AACA,SAAM,SAAS,MAAM;AACrB,SAAM,SAAS,eAAe;AAC9B,SAAM,SAAS,eAAe;AAC9B,SAAM,SAAS,mBAAmB;AAClC,SAAM,SAAS,gBAAgB;AAC/B,SAAM,SAAS,eAAe;AAC9B,SAAM,SAAS,OAAO;WACjB,OAAO;AACZ,UAAO,OAAO,IAAI,iBAAiB,aAAa,MAAM,UAAU,QAAQ,MAAM,CAAC,CAAC"}
|
|
@@ -15,10 +15,11 @@ import { build } from "tsdown";
|
|
|
15
15
|
|
|
16
16
|
//#region src/bin/commands/start.ts
|
|
17
17
|
var StartSubcommand = class extends CLISubcommand {
|
|
18
|
-
subcommand = new Command("start").description("Start the reciple client").
|
|
18
|
+
subcommand = new Command("start").description("Start the reciple client").argument("[project]", "The root directory of your project").option("-t, --token <DiscordToken>", "Set your Discord Bot token").option("-b, --build", "Build the modules before starting the client").allowUnknownOption(true);
|
|
19
19
|
async execute() {
|
|
20
20
|
const flags = this.subcommand.opts();
|
|
21
|
-
|
|
21
|
+
await this.cli.setCurrentDirectory(this.subcommand.args[0]);
|
|
22
|
+
const { client, config, build: buildConfig } = await new ConfigReader(await ConfigReader.find() ?? ConfigReader.createConfigFilename("js")).read();
|
|
22
23
|
const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);
|
|
23
24
|
let token = flags.token || config.token || "";
|
|
24
25
|
token = resolveEnvProtocol(token) || token;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.mjs","names":["DiscordJsVersion"],"sources":["../../../src/bin/commands/start.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport { Logger } from '@prtty/print';\nimport { Format, resolveEnvProtocol } from '@reciple/utils';\nimport { Client, CommandType } from '@reciple/core';\nimport { ModuleLoader } from '../../classes/client/ModuleLoader.js';\nimport { ModuleManager } from '../../classes/managers/ModuleManager.js';\nimport { version as DiscordJsVersion } from 'discord.js';\nimport { EventListeners } from '../../classes/client/EventListeners.js';\nimport { RuntimeEnvironment } from '../../classes/cli/RuntimeEnvironment.js';\nimport { build } from 'tsdown';\nimport { CLI } from '../../classes/cli/CLI.js';\nimport { colors } from '@prtty/prtty';\n\nexport default class StartSubcommand extends CLISubcommand {\n public subcommand: Command = new Command('start')\n .description('Start the reciple client')\n .option('-c, --config <path>', 'Path to the configuration file')\n .option('-t, --token <DiscordToken>', 'Set your Discord Bot token')\n .option('-b, --build', 'Build the modules before starting the client')\n .allowUnknownOption(true);\n\n public async execute(): Promise<void> {\n const flags = this.subcommand.opts<StartSubcommand.Flags>();\n const configReader = new ConfigReader(\n flags.config\n ?? await ConfigReader.find()\n ?? ConfigReader.createConfigFilename('js')\n );\n\n const { client, config, build: buildConfig } = await configReader.read();\n\n const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);\n\n let token = flags.token || config.token || '';\n token = resolveEnvProtocol(token) || token;\n\n function handleProcessError(err: unknown) {\n logger.error(err);\n process.exit(1);\n }\n\n process.once('uncaughtException', handleProcessError);\n process.once('unhandledRejection', handleProcessError);\n process.on('warning', warn => logger.warn(warn));\n\n logger.log(colors.magenta(`⚡ Initializing reciple!`));\n\n if (flags.build) {\n let plugins = buildConfig.plugins\n ? Array.isArray(buildConfig.plugins)\n ? buildConfig.plugins\n : [buildConfig.plugins]\n : [];\n\n plugins.push(CLI.createTsdownLogger());\n\n await build({\n ...buildConfig,\n logLevel: 'silent',\n plugins,\n });\n }\n\n Object.assign(client, {\n logger,\n cli: this.cli,\n config\n });\n\n Object.assign(client, {\n modules: new ModuleManager(client),\n moduleLoader: new ModuleLoader(client),\n eventListeners: new EventListeners()\n });\n\n Reflect.set(global, 'useClient', () => client);\n Reflect.set(global, 'useLogger', () => logger);\n\n EventListeners.registerLoggerEventListeners(client);\n\n logger.log(colors.green(`📦 Version Info:`));\n logger.log(` ├─ ${colors.cyan(`reciple`)}\\t\\t${colors.yellow(`${this.cli.version}`)}`);\n logger.log(` ├─ ${colors.cyan(`@reciple/client`)}\\t${colors.yellow(`${Client.version}`)}`);\n logger.log(` └─ ${colors.cyan(`discord.js`)}\\t${colors.yellow(`${DiscordJsVersion}`)}`);\n\n const modules = await client.moduleLoader.findModules();\n\n Object.assign(client, {\n _onBeforeLogin: async() => {\n const enabledModules = await client.modules.enableModules({ modules });\n\n client.once('clientReady', async() => {\n if (!client.isReady()) return;\n\n EventListeners.registerCommandsEventListeners(client);\n\n logger.debug(`Client is ready!`);\n process.removeListener('uncaughtException', handleProcessError);\n process.removeListener('unhandledRejection', handleProcessError);\n\n const notEnabledModules = modules.length - enabledModules.length;\n logger.log(colors.green(`✅ ${enabledModules.length} ${Format.plural(enabledModules.length, 'module')} ${Format.plural(enabledModules.length, 'is', 'are')} enabled.${notEnabledModules > 0 ? colors.red(` (${notEnabledModules} not enabled)`) : ''}`));\n\n const readyModules = await client.modules.readyModules();\n const notReadyModules = readyModules.length - enabledModules.length;\n\n logger.log(colors.green(`✅ ${readyModules.length} ${Format.plural(readyModules.length, 'module')} ${Format.plural(readyModules.length, 'is', 'are')} ready.${notReadyModules > 0 ? colors.red(` (${notReadyModules} not ready)`) : ''}`));\n\n await client.commands.registerApplicationCommands({\n ...config.applicationCommandsRegister,\n commands: client.commands.applicationCommands,\n });\n\n process.stdin.resume();\n\n const commands = {\n contextMenus: client.commands.cache.filter(c => c.type === CommandType.ContextMenu).size,\n message: client.commands.cache.filter(c => c.type === CommandType.Message).size,\n slash: client.commands.cache.filter(c => c.type === CommandType.Slash).size\n };\n\n logger.log(`🔑 Logged in as ${colors.bold(colors.cyan(client.user.displayName))} ${colors.magenta(`(${client.user.id})`)}`);\n logger.log(` ├─ Loaded ${colors.green(modules.length.toLocaleString())} ${Format.plural(modules.length, 'module')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.contextMenus.toLocaleString())} context menu ${Format.plural(commands.contextMenus, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.message.toLocaleString())} message ${Format.plural(commands.message, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.slash.toLocaleString())} slash ${Format.plural(commands.slash, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(client.preconditions.cache.size.toLocaleString())} global ${Format.plural(client.preconditions.cache.size, 'precondition')}.`);\n logger.log(` └─ Loaded ${colors.green(client.postconditions.cache.size.toLocaleString())} global ${Format.plural(client.postconditions.cache.size, 'postcondition')}.`);\n });\n\n client.eventListeners.registerProcessExitEvents(async signal => RuntimeEnvironment.handleExitSignal(client, signal));\n },\n _onBeforeDestroy: async (client: Client) => {\n await client.modules.disableModules();\n }\n })\n\n logger.debug(`Logging in...`);\n await client.login(token);\n }\n}\n\nexport namespace StartSubcommand {\n export interface Flags {\n config?: string;\n token?: string;\n build?: boolean;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,IAAqB,kBAArB,cAA6C,cAAc;CACvD,AAAO,aAAsB,IAAI,QAAQ,QAAQ,CAC5C,YAAY,2BAA2B,CACvC,OAAO,uBAAuB,iCAAiC,CAC/D,OAAO,8BAA8B,6BAA6B,CAClE,OAAO,eAAe,+CAA+C,CACrE,mBAAmB,KAAK;CAE7B,MAAa,UAAyB;EAClC,MAAM,QAAQ,KAAK,WAAW,MAA6B;EAO3D,MAAM,EAAE,QAAQ,QAAQ,OAAO,gBAAgB,MAN1B,IAAI,aACrB,MAAM,UACH,MAAM,aAAa,MAAM,IACzB,aAAa,qBAAqB,KAAK,CAC7C,CAEiE,MAAM;EAExE,MAAM,SAAS,OAAO,kBAAkB,SAAS,KAAK,IAAI,SAAS,OAAO,SAAS,KAAK,IAAI,OAAO,MAAM,OAAO,OAAO;EAEvH,IAAI,QAAQ,MAAM,SAAS,OAAO,SAAS;AACvC,UAAQ,mBAAmB,MAAM,IAAI;EAEzC,SAAS,mBAAmB,KAAc;AACtC,UAAO,MAAM,IAAI;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AAI,cAAc,OAAO,MAAM,QAAQ,OAAO,gBAAgB,CAAC,CAAC,GAAG,OAAO,OAAO,QAAQ,QAAQ,SAAS,CAAC,GAAG;AACrH,YAAO,IAAI,cAAc,OAAO,MAAM,SAAS,aAAa,gBAAgB,CAAC,CAAC,gBAAgB,OAAO,OAAO,SAAS,cAAc,UAAU,CAAC,GAAG;AACjJ,YAAO,IAAI,cAAc,OAAO,MAAM,SAAS,QAAQ,gBAAgB,CAAC,CAAC,WAAW,OAAO,OAAO,SAAS,SAAS,UAAU,CAAC,GAAG;AAClI,YAAO,IAAI,cAAc,OAAO,MAAM,SAAS,MAAM,gBAAgB,CAAC,CAAC,SAAS,OAAO,OAAO,SAAS,OAAO,UAAU,CAAC,GAAG;AAC5H,YAAO,IAAI,cAAc,OAAO,MAAM,OAAO,cAAc,MAAM,KAAK,gBAAgB,CAAC,CAAC,UAAU,OAAO,OAAO,OAAO,cAAc,MAAM,MAAM,eAAe,CAAC,GAAG;AACpK,YAAO,IAAI,cAAc,OAAO,MAAM,OAAO,eAAe,MAAM,KAAK,gBAAgB,CAAC,CAAC,UAAU,OAAO,OAAO,OAAO,eAAe,MAAM,MAAM,gBAAgB,CAAC,GAAG;MACzK;AAEF,WAAO,eAAe,0BAA0B,OAAM,WAAU,mBAAmB,iBAAiB,QAAQ,OAAO,CAAC;;GAExH,kBAAkB,OAAO,WAAmB;AACxC,UAAM,OAAO,QAAQ,gBAAgB;;GAE5C,CAAC;AAEF,SAAO,MAAM,gBAAgB;AAC7B,QAAM,OAAO,MAAM,MAAM"}
|
|
1
|
+
{"version":3,"file":"start.mjs","names":["DiscordJsVersion"],"sources":["../../../src/bin/commands/start.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport { Logger } from '@prtty/print';\nimport { Format, resolveEnvProtocol } from '@reciple/utils';\nimport { Client, CommandType } from '@reciple/core';\nimport { ModuleLoader } from '../../classes/client/ModuleLoader.js';\nimport { ModuleManager } from '../../classes/managers/ModuleManager.js';\nimport { version as DiscordJsVersion } from 'discord.js';\nimport { EventListeners } from '../../classes/client/EventListeners.js';\nimport { RuntimeEnvironment } from '../../classes/cli/RuntimeEnvironment.js';\nimport { build } from 'tsdown';\nimport { CLI } from '../../classes/cli/CLI.js';\nimport { colors } from '@prtty/prtty';\n\nexport default class StartSubcommand extends CLISubcommand {\n public subcommand: Command = new Command('start')\n .description('Start the reciple client')\n .argument('[project]', 'The root directory of your project')\n .option('-t, --token <DiscordToken>', 'Set your Discord Bot token')\n .option('-b, --build', 'Build the modules before starting the client')\n .allowUnknownOption(true);\n\n public async execute(): Promise<void> {\n const flags = this.subcommand.opts<StartSubcommand.Flags>();\n\n await this.cli.setCurrentDirectory(this.subcommand.args[0]);\n\n const configReader = new ConfigReader(\n await ConfigReader.find()\n ?? ConfigReader.createConfigFilename('js')\n );\n\n const { client, config, build: buildConfig } = await configReader.read();\n\n const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);\n\n let token = flags.token || config.token || '';\n token = resolveEnvProtocol(token) || token;\n\n function handleProcessError(err: unknown) {\n logger.error(err);\n process.exit(1);\n }\n\n process.once('uncaughtException', handleProcessError);\n process.once('unhandledRejection', handleProcessError);\n process.on('warning', warn => logger.warn(warn));\n\n logger.log(colors.magenta(`⚡ Initializing reciple!`));\n\n if (flags.build) {\n let plugins = buildConfig.plugins\n ? Array.isArray(buildConfig.plugins)\n ? buildConfig.plugins\n : [buildConfig.plugins]\n : [];\n\n plugins.push(CLI.createTsdownLogger());\n\n await build({\n ...buildConfig,\n logLevel: 'silent',\n plugins,\n });\n }\n\n Object.assign(client, {\n logger,\n cli: this.cli,\n config\n });\n\n Object.assign(client, {\n modules: new ModuleManager(client),\n moduleLoader: new ModuleLoader(client),\n eventListeners: new EventListeners()\n });\n\n Reflect.set(global, 'useClient', () => client);\n Reflect.set(global, 'useLogger', () => logger);\n\n EventListeners.registerLoggerEventListeners(client);\n\n logger.log(colors.green(`📦 Version Info:`));\n logger.log(` ├─ ${colors.cyan(`reciple`)}\\t\\t${colors.yellow(`${this.cli.version}`)}`);\n logger.log(` ├─ ${colors.cyan(`@reciple/client`)}\\t${colors.yellow(`${Client.version}`)}`);\n logger.log(` └─ ${colors.cyan(`discord.js`)}\\t${colors.yellow(`${DiscordJsVersion}`)}`);\n\n const modules = await client.moduleLoader.findModules();\n\n Object.assign(client, {\n _onBeforeLogin: async() => {\n const enabledModules = await client.modules.enableModules({ modules });\n\n client.once('clientReady', async() => {\n if (!client.isReady()) return;\n\n EventListeners.registerCommandsEventListeners(client);\n\n logger.debug(`Client is ready!`);\n process.removeListener('uncaughtException', handleProcessError);\n process.removeListener('unhandledRejection', handleProcessError);\n\n const notEnabledModules = modules.length - enabledModules.length;\n logger.log(colors.green(`✅ ${enabledModules.length} ${Format.plural(enabledModules.length, 'module')} ${Format.plural(enabledModules.length, 'is', 'are')} enabled.${notEnabledModules > 0 ? colors.red(` (${notEnabledModules} not enabled)`) : ''}`));\n\n const readyModules = await client.modules.readyModules();\n const notReadyModules = readyModules.length - enabledModules.length;\n\n logger.log(colors.green(`✅ ${readyModules.length} ${Format.plural(readyModules.length, 'module')} ${Format.plural(readyModules.length, 'is', 'are')} ready.${notReadyModules > 0 ? colors.red(` (${notReadyModules} not ready)`) : ''}`));\n\n await client.commands.registerApplicationCommands({\n ...config.applicationCommandsRegister,\n commands: client.commands.applicationCommands,\n });\n\n process.stdin.resume();\n\n const commands = {\n contextMenus: client.commands.cache.filter(c => c.type === CommandType.ContextMenu).size,\n message: client.commands.cache.filter(c => c.type === CommandType.Message).size,\n slash: client.commands.cache.filter(c => c.type === CommandType.Slash).size\n };\n\n logger.log(`🔑 Logged in as ${colors.bold(colors.cyan(client.user.displayName))} ${colors.magenta(`(${client.user.id})`)}`);\n logger.log(` ├─ Loaded ${colors.green(modules.length.toLocaleString())} ${Format.plural(modules.length, 'module')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.contextMenus.toLocaleString())} context menu ${Format.plural(commands.contextMenus, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.message.toLocaleString())} message ${Format.plural(commands.message, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(commands.slash.toLocaleString())} slash ${Format.plural(commands.slash, 'command')}.`);\n logger.log(` ├─ Loaded ${colors.green(client.preconditions.cache.size.toLocaleString())} global ${Format.plural(client.preconditions.cache.size, 'precondition')}.`);\n logger.log(` └─ Loaded ${colors.green(client.postconditions.cache.size.toLocaleString())} global ${Format.plural(client.postconditions.cache.size, 'postcondition')}.`);\n });\n\n client.eventListeners.registerProcessExitEvents(async signal => RuntimeEnvironment.handleExitSignal(client, signal));\n },\n _onBeforeDestroy: async (client: Client) => {\n await client.modules.disableModules();\n }\n })\n\n logger.debug(`Logging in...`);\n await client.login(token);\n }\n}\n\nexport namespace StartSubcommand {\n export interface Flags {\n token?: string;\n build?: boolean;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,IAAqB,kBAArB,cAA6C,cAAc;CACvD,AAAO,aAAsB,IAAI,QAAQ,QAAQ,CAC5C,YAAY,2BAA2B,CACvC,SAAS,aAAa,qCAAqC,CAC3D,OAAO,8BAA8B,6BAA6B,CAClE,OAAO,eAAe,+CAA+C,CACrE,mBAAmB,KAAK;CAE7B,MAAa,UAAyB;EAClC,MAAM,QAAQ,KAAK,WAAW,MAA6B;AAE3D,QAAM,KAAK,IAAI,oBAAoB,KAAK,WAAW,KAAK,GAAG;EAO3D,MAAM,EAAE,QAAQ,QAAQ,OAAO,gBAAgB,MAL1B,IAAI,aACrB,MAAM,aAAa,MAAM,IACtB,aAAa,qBAAqB,KAAK,CAC7C,CAEiE,MAAM;EAExE,MAAM,SAAS,OAAO,kBAAkB,SAAS,KAAK,IAAI,SAAS,OAAO,SAAS,KAAK,IAAI,OAAO,MAAM,OAAO,OAAO;EAEvH,IAAI,QAAQ,MAAM,SAAS,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AO,KAAK,YAAY,CAAC,CAAC,GAAG,OAAO,QAAQ,IAAI,OAAO,KAAK,GAAG,GAAG,GAAG;AAC3H,YAAO,IAAI,cAAc,OAAO,MAAM,QAAQ,OAAO,gBAAgB,CAAC,CAAC,GAAG,OAAO,OAAO,QAAQ,QAAQ,SAAS,CAAC,GAAG;AACrH,YAAO,IAAI,cAAc,OAAO,MAAM,SAAS,aAAa,gBAAgB,CAAC,CAAC,gBAAgB,OAAO,OAAO,SAAS,cAAc,UAAU,CAAC,GAAG;AACjJ,YAAO,IAAI,cAAc,OAAO,MAAM,SAAS,QAAQ,gBAAgB,CAAC,CAAC,WAAW,OAAO,OAAO,SAAS,SAAS,UAAU,CAAC,GAAG;AAClI,YAAO,IAAI,cAAc,OAAO,MAAM,SAAS,MAAM,gBAAgB,CAAC,CAAC,SAAS,OAAO,OAAO,SAAS,OAAO,UAAU,CAAC,GAAG;AAC5H,YAAO,IAAI,cAAc,OAAO,MAAM,OAAO,cAAc,MAAM,KAAK,gBAAgB,CAAC,CAAC,UAAU,OAAO,OAAO,OAAO,cAAc,MAAM,MAAM,eAAe,CAAC,GAAG;AACpK,YAAO,IAAI,cAAc,OAAO,MAAM,OAAO,eAAe,MAAM,KAAK,gBAAgB,CAAC,CAAC,UAAU,OAAO,OAAO,OAAO,eAAe,MAAM,MAAM,gBAAgB,CAAC,GAAG;MACzK;AAEF,WAAO,eAAe,0BAA0B,OAAM,WAAU,mBAAmB,iBAAiB,QAAQ,OAAO,CAAC;;GAExH,kBAAkB,OAAO,WAAmB;AACxC,UAAM,OAAO,QAAQ,gBAAgB;;GAE5C,CAAC;AAEF,SAAO,MAAM,gBAAgB;AAC7B,QAAM,OAAO,MAAM,MAAM"}
|
|
@@ -12,18 +12,19 @@ import { build } from "tsdown";
|
|
|
12
12
|
//#region src/bin/commands/startSharding.ts
|
|
13
13
|
var StartShardingSubcommand = class extends CLISubcommand {
|
|
14
14
|
parent = "start";
|
|
15
|
-
subcommand = new Command("sharding").description("Start the reciple client in sharding mode").
|
|
15
|
+
subcommand = new Command("sharding").description("Start the reciple client in sharding mode").argument("[project]", "The root directory of your project").option("-t, --token <DiscordToken>", "Set your Discord Bot token").option("-b, --build", "Build the modules before starting the client").allowUnknownOption(true);
|
|
16
16
|
async execute() {
|
|
17
17
|
process.env.RECIPLE_SHARDING = "true";
|
|
18
18
|
process.env.RECIPLE_FIRST_SHARD = "true";
|
|
19
19
|
const recipleFlags = this.cli.getFlags();
|
|
20
20
|
const flags = this.subcommand.opts();
|
|
21
|
+
await this.cli.setCurrentDirectory(this.subcommand.args[0]);
|
|
21
22
|
const shardArgs = [
|
|
22
23
|
...CLI.stringifyFlags(recipleFlags, this.cli.command),
|
|
23
24
|
"start",
|
|
24
25
|
...CLI.stringifyFlags(flags, this.command)
|
|
25
26
|
];
|
|
26
|
-
const { config, build: buildConfig, sharding } = await new ConfigReader(
|
|
27
|
+
const { config, build: buildConfig, sharding } = await new ConfigReader(await ConfigReader.find() ?? ConfigReader.createConfigFilename("js")).read();
|
|
27
28
|
const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);
|
|
28
29
|
logger.label = "ShardingManager";
|
|
29
30
|
let token = flags.token || config.token || "";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"startSharding.mjs","names":[],"sources":["../../../src/bin/commands/startSharding.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport type { StartSubcommand } from './start.js';\nimport { Logger } from '@prtty/print';\nimport { resolveEnvProtocol } from '@reciple/utils';\nimport { colors } from '@prtty/prtty';\nimport { CLI } from '../../classes/cli/CLI.js';\nimport { build } from 'tsdown';\nimport { ShardingManager } from 'discord.js';\nimport { EventListeners } from '../../classes/client/EventListeners.js';\n\nexport default class StartShardingSubcommand extends CLISubcommand {\n public parent?: string = 'start';\n\n public subcommand: Command = new Command('sharding')\n .description('Start the reciple client in sharding mode')\n .
|
|
1
|
+
{"version":3,"file":"startSharding.mjs","names":[],"sources":["../../../src/bin/commands/startSharding.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CLISubcommand } from '../../classes/cli/CLISubcommand.js';\nimport { ConfigReader } from '../../classes/cli/ConfigReader.js';\nimport type { StartSubcommand } from './start.js';\nimport { Logger } from '@prtty/print';\nimport { resolveEnvProtocol } from '@reciple/utils';\nimport { colors } from '@prtty/prtty';\nimport { CLI } from '../../classes/cli/CLI.js';\nimport { build } from 'tsdown';\nimport { ShardingManager } from 'discord.js';\nimport { EventListeners } from '../../classes/client/EventListeners.js';\n\nexport default class StartShardingSubcommand extends CLISubcommand {\n public parent?: string = 'start';\n\n public subcommand: Command = new Command('sharding')\n .description('Start the reciple client in sharding mode')\n .argument('[project]', 'The root directory of your project')\n .option('-t, --token <DiscordToken>', 'Set your Discord Bot token')\n .option('-b, --build', 'Build the modules before starting the client')\n .allowUnknownOption(true);\n\n public async execute(): Promise<void> {\n process.env.RECIPLE_SHARDING = 'true';\n process.env.RECIPLE_FIRST_SHARD = 'true';\n\n const recipleFlags = this.cli.getFlags();\n const flags = this.subcommand.opts<ShardingSubcommand.Flags>();\n\n await this.cli.setCurrentDirectory(this.subcommand.args[0]);\n\n const shardArgs: string[] = [\n ...CLI.stringifyFlags(recipleFlags, this.cli.command),\n 'start',\n ...CLI.stringifyFlags(flags, this.command)\n ];\n\n const configReader = new ConfigReader(\n await ConfigReader.find()\n ?? ConfigReader.createConfigFilename('js')\n );\n\n const { config, build: buildConfig, sharding } = await configReader.read();\n const logger = config.logger instanceof Logger ? this.cli.logger = config.logger : this.cli.logger.clone(config.logger);\n\n logger.label = 'ShardingManager';\n\n let token = flags.token || config.token || '';\n token = resolveEnvProtocol(token) || token;\n\n logger.log(colors.magenta(`⚡ Initializing reciple sharding manager!`));\n\n const processErrorLogger = (err: any) => {\n logger?.error(err);\n process.exit(1);\n };\n\n process.once('uncaughtException', processErrorLogger);\n process.once('unhandledRejection', processErrorLogger);\n process.on('warning', warn => logger.warn(warn));\n\n if (flags.build) {\n let plugins = buildConfig.plugins\n ? Array.isArray(buildConfig.plugins)\n ? buildConfig.plugins\n : [buildConfig.plugins]\n : [];\n\n plugins.push(CLI.createTsdownLogger());\n\n await build({\n ...buildConfig,\n logLevel: 'silent',\n plugins,\n });\n }\n\n if (!sharding) {\n logger.error('Sharding is not enabled in the config file');\n process.exit(1);\n }\n\n Reflect.set(global, 'useLogger', () => logger);\n\n const eventListeners = new EventListeners();\n const manager = new ShardingManager(CLI.bin, {\n ...sharding,\n token: token,\n shardArgs\n });\n\n manager.on('shardCreate', shard => {\n logger.log(colors.magenta(`🚀 Launched shard ${colors.green(String(shard.id))}`));\n\n shard.on('ready', () => {\n logger.log(colors.magenta(`✅ Shard ${colors.green(String(shard.id))} is ready!`));\n\n if (process.env.RECIPLE_FIRST_SHARD === 'true') {\n process.env.RECIPLE_FIRST_SHARD = 'false';\n }\n });\n\n shard.on('reconnecting', () => {\n logger.log(colors.magenta(`🔄 Shard ${colors.green(String(shard.id))} is reconnecting...`));\n });\n\n shard.on('resume', () => {\n logger.log(colors.magenta(`✅ Shard ${colors.green(String(shard.id))} has resumed!`));\n });\n\n shard.on('disconnect', () => {\n logger.log(colors.magenta(`🛑 Shard ${colors.green(String(shard.id))} is disconnected!`));\n });\n\n shard.on('death', () => {\n logger.error(`🛑 Shard ${colors.green(String(shard.id))} has died!`);\n });\n\n shard.on('error', error => {\n logger.error(`❌ Shard ${colors.green(String(shard.id))} encountered an error:`, error);\n });\n\n shard.on('message', message => {\n // TODO: Handle shard messages\n });\n });\n\n eventListeners.registerProcessExitEvents(signal => this.destroyShardingManager(manager));\n process.stdin.resume();\n\n await manager.spawn();\n }\n\n public destroyShardingManager(manager: ShardingManager): void {\n const logger = useLogger();\n\n manager.shards.map(s => {\n logger.log(colors.magenta(`🚧 Destroying shard ${s.id}`));\n\n if (s.process) {\n s.process.kill();\n } else {\n s.kill();\n }\n\n logger.log(colors.magenta(`🛑 Destroyed shard ${s.id}`));\n });\n\n logger.log(colors.magenta(`🚨 Destroyed all shards`));\n setTimeout(() => process.exit(0), 500);\n }\n}\n\nexport namespace ShardingSubcommand {\n export interface Flags extends StartSubcommand.Flags {}\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAqB,0BAArB,cAAqD,cAAc;CAC/D,AAAO,SAAkB;CAEzB,AAAO,aAAsB,IAAI,QAAQ,WAAW,CAC/C,YAAY,4CAA4C,CACxD,SAAS,aAAa,qCAAqC,CAC3D,OAAO,8BAA8B,6BAA6B,CAClE,OAAO,eAAe,+CAA+C,CACrE,mBAAmB,KAAK;CAE7B,MAAa,UAAyB;AAClC,UAAQ,IAAI,mBAAmB;AAC/B,UAAQ,IAAI,sBAAsB;EAElC,MAAM,eAAe,KAAK,IAAI,UAAU;EACxC,MAAM,QAAQ,KAAK,WAAW,MAAgC;AAE9D,QAAM,KAAK,IAAI,oBAAoB,KAAK,WAAW,KAAK,GAAG;EAE3D,MAAM,YAAsB;GACxB,GAAG,IAAI,eAAe,cAAc,KAAK,IAAI,QAAQ;GACrD;GACA,GAAG,IAAI,eAAe,OAAO,KAAK,QAAQ;GAC7C;EAOD,MAAM,EAAE,QAAQ,OAAO,aAAa,aAAa,MAL5B,IAAI,aACrB,MAAM,aAAa,MAAM,IACtB,aAAa,qBAAqB,KAAK,CAC7C,CAEmE,MAAM;EAC1E,MAAM,SAAS,OAAO,kBAAkB,SAAS,KAAK,IAAI,SAAS,OAAO,SAAS,KAAK,IAAI,OAAO,MAAM,OAAO,OAAO;AAEvH,SAAO,QAAQ;EAEf,IAAI,QAAQ,MAAM,SAAS,OAAO,SAAS;AACvC,UAAQ,mBAAmB,MAAM,IAAI;AAEzC,SAAO,IAAI,OAAO,QAAQ,2CAA2C,CAAC;EAEtE,MAAM,sBAAsB,QAAa;AACrC,WAAQ,MAAM,IAAI;AAClB,WAAQ,KAAK,EAAE;;AAGnB,UAAQ,KAAK,qBAAqB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AmB,CAAC;KAC3F;AAEF,SAAM,GAAG,eAAe;AACpB,WAAO,MAAM,YAAY,OAAO,MAAM,OAAO,MAAM,GAAG,CAAC,CAAC,YAAY;KACtE;AAEF,SAAM,GAAG,UAAS,UAAS;AACvB,WAAO,MAAM,WAAW,OAAO,MAAM,OAAO,MAAM,GAAG,CAAC,CAAC,yBAAyB,MAAM;KACxF;AAEF,SAAM,GAAG,YAAW,YAAW,GAE7B;IACJ;AAEF,iBAAe,2BAA0B,WAAU,KAAK,uBAAuB,QAAQ,CAAC;AACxF,UAAQ,MAAM,QAAQ;AAEtB,QAAM,QAAQ,OAAO;;CAGzB,AAAO,uBAAuB,SAAgC;EAC1D,MAAM,SAAS,WAAW;AAE1B,UAAQ,OAAO,KAAI,MAAK;AACpB,UAAO,IAAI,OAAO,QAAQ,uBAAuB,EAAE,KAAK,CAAC;AAEzD,OAAI,EAAE,QACF,GAAE,QAAQ,MAAM;OAEhB,GAAE,MAAM;AAGZ,UAAO,IAAI,OAAO,QAAQ,sBAAsB,EAAE,KAAK,CAAC;IAC1D;AAEF,SAAO,IAAI,OAAO,QAAQ,0BAA0B,CAAC;AACrD,mBAAiB,QAAQ,KAAK,EAAE,EAAE,IAAI"}
|
|
@@ -16,6 +16,7 @@ declare class CLI {
|
|
|
16
16
|
parse(argv?: string[]): Promise<this>;
|
|
17
17
|
loadCommands(): Promise<void>;
|
|
18
18
|
handlePreAction(cmd: Command, action: Command): Promise<void>;
|
|
19
|
+
setCurrentDirectory(cwd?: string): Promise<void>;
|
|
19
20
|
getFlags<Flags extends Record<string, any> = Record<string, any>>(command: Command | string, mergeDefault?: false): Flags | undefined;
|
|
20
21
|
getFlags<Flags extends Record<string, any> = Record<string, any>>(command: Command | string, mergeDefault: true): Flags & CLI.Flags | undefined;
|
|
21
22
|
getFlags(command?: undefined): CLI.Flags;
|
package/dist/classes/cli/CLI.mjs
CHANGED
|
@@ -70,6 +70,14 @@ var CLI = class {
|
|
|
70
70
|
});
|
|
71
71
|
this.logger.debug(`Loaded environment variables from ${this.flags.env.join(", ")}`);
|
|
72
72
|
}
|
|
73
|
+
async setCurrentDirectory(cwd) {
|
|
74
|
+
cwd ??= process.cwd();
|
|
75
|
+
if (!await stat(cwd).then((s) => s.isDirectory()).catch(() => false)) {
|
|
76
|
+
console.log(colors.red("Please specify a valid project directory"));
|
|
77
|
+
process.exit(1);
|
|
78
|
+
}
|
|
79
|
+
process.chdir(cwd);
|
|
80
|
+
}
|
|
73
81
|
getFlags(command, mergeDefault = false) {
|
|
74
82
|
if (!command) return this.flags;
|
|
75
83
|
command = typeof command === "string" ? this.command.commands.find((c) => c.name() === command) : command;
|
|
@@ -87,7 +95,7 @@ var CLI = class {
|
|
|
87
95
|
(function(_CLI) {
|
|
88
96
|
_CLI.root = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../");
|
|
89
97
|
_CLI.bin = path.join(CLI.root, "dist/bin/reciple.mjs");
|
|
90
|
-
_CLI.version = "10.0.
|
|
98
|
+
_CLI.version = "10.0.6";
|
|
91
99
|
function stringifyFlags(flags, command, ignored = []) {
|
|
92
100
|
let arr = [];
|
|
93
101
|
for (const [key, value] of Object.entries(flags)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CLI.mjs","names":[],"sources":["../../../src/classes/cli/CLI.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { fileURLToPath } from 'node:url';\nimport path from 'node:path';\nimport { coerce } from 'semver';\nimport { Format, isDebugging, recursiveDefaults } from '@reciple/utils';\nimport { logger, Logger, LogLevel } from '@prtty/print';\nimport { config as loadEnv } from '@dotenvx/dotenvx';\nimport { readdir, stat } from 'node:fs/promises';\nimport { CLISubcommand } from './CLISubcommand.js';\nimport { spinner, type SpinnerOptions } from '@clack/prompts';\nimport type { RolldownPlugin } from 'rolldown';\nimport { colors } from '@prtty/prtty';\n\nexport class CLI {\n public build: string;\n public version: string;\n public command: Command;\n public logger: Logger;\n\n get isDebugging(): boolean {\n return this.flags.debug;\n }\n\n get flags(): CLI.Flags {\n return this.command.opts();\n }\n\n constructor(public readonly options: CLI.Options) {\n this.build = options.build;\n this.version = String(coerce(this.build) ?? this.build);\n\n this.command = new Command()\n .name(options.name)\n .description(options.description)\n .version(options.build, '-v, --version', 'Output the CLI version number')\n .option('-D, --debug', 'Enable debug mode', isDebugging())\n .option('--no-debug', 'Disabled debug mode')\n .option('--env <file>', 'Load environment variables from .env file', (v, p) => p.concat(v), [] as string[])\n .enablePositionalOptions(true)\n .hook('preAction', this.handlePreAction.bind(this))\n .showHelpAfterError();\n\n this.logger = options.logger instanceof Logger ? options.logger : new Logger(options.logger);\n\n if (this.flags.debug) {\n this.logger.logLevel = LogLevel.Debug;\n this.logger.writeLevel = LogLevel.Debug;\n }\n }\n\n public async parse(argv?: string[]): Promise<this> {\n await this.loadCommands();\n await this.command.parseAsync(argv);\n return this;\n }\n\n public async loadCommands(): Promise<void> {\n this.logger.debug(`Loading cli commands from ${this.options.subcommandsDir}`);\n\n const dirStat = await stat(this.options.subcommandsDir).catch(() => undefined);\n if (!dirStat?.isDirectory()) return;\n\n const files = (await readdir(this.options.subcommandsDir))\n .map(f => path.join(this.options.subcommandsDir, f))\n .filter(f => f.endsWith('.mjs'));\n\n const hasParent: CLISubcommand[] = [];\n\n for (const file of files) {\n const Subommand = recursiveDefaults<CLISubcommand.Constructor>(await import(path.isAbsolute(file) ? `file://${file}` : file));\n if (!Subommand || typeof Subommand !== 'function') continue;\n\n const instance = new Subommand({ cli: this, command: this.command });\n\n if (instance.parent) {\n hasParent.push(instance);\n continue;\n }\n\n CLISubcommand.registerSubcommand(instance);\n }\n\n for (const instance of hasParent) {\n CLISubcommand.registerSubcommand(instance);\n }\n }\n\n public async handlePreAction(cmd: Command, action: Command): Promise<void> {\n this.logger.debug(`Executing ${action.name()}`);\n this.logger.debug(`Debug mode is ${this.flags.debug ? 'enabled' : 'disabled'}`);\n process.env.NODE_ENV = this.flags.debug ? 'development' : process.env.NODE_ENV;\n\n loadEnv({\n path: this.flags.env.length ? this.flags.env : [path.join(process.cwd(), '.env')],\n debug: this.flags.debug,\n quiet: !this.flags.debug,\n ignore: ['MISSING_ENV_FILE']\n });\n\n this.logger.debug(`Loaded environment variables from ${this.flags.env.join(', ')}`);\n }\n\n public getFlags<Flags extends Record<string, any> = Record<string, any>>(command: Command|string, mergeDefault?: false): Flags|undefined;\n public getFlags<Flags extends Record<string, any> = Record<string, any>>(command: Command|string, mergeDefault: true): Flags & CLI.Flags|undefined;\n public getFlags(command?: undefined): CLI.Flags;\n public getFlags(command?: Command|string, mergeDefault: boolean = false): Record<string, any>|undefined {\n if (!command) return this.flags;\n\n command = typeof command === 'string' ? this.command.commands.find(c => c.name() === command) : command;\n const flags = command?.opts();\n\n return mergeDefault ? { ...this.flags, ...flags } : flags;\n }\n\n public getCommand(name: string): Command|undefined;\n public getCommand(name?: undefined): Command;\n public getCommand(name?: string): Command|undefined {\n if (!name) return this.command;\n\n return this.command.commands.find(c => c.name() === name);\n }\n}\n\nexport namespace CLI {\n export interface Options {\n name: string;\n description: string;\n build: string;\n subcommandsDir: string;\n logger?: Logger|Logger.Options;\n }\n\n export interface Flags {\n debug: boolean;\n env: string[];\n }\n\n export const root: string = path.join(path.dirname(fileURLToPath(import.meta.url)), '../../../');\n export const bin: string = path.join(CLI.root, 'dist/bin/reciple.mjs');\n export const version = process.env.__VERSION__;\n\n export function stringifyFlags(flags: Record<string, any>, command: Command, ignored: string[] = []): string[] {\n let arr: string[] = [];\n\n for (const [key, value] of Object.entries(flags)) {\n const option = command.options.find(o => o.name() === key || o.attributeName() === key);\n if (!option || ignored.includes(key)) continue;\n\n const flag = option.long ?? option.short ?? `--${option.name()}`;\n\n if (!option.flags.endsWith('>') && !option.flags.endsWith(']') && typeof value === 'boolean') {\n if (value) arr.push(flag);\n continue;\n }\n\n arr.push(flag, String(value));\n }\n\n return arr;\n }\n\n export interface SpinnerPromiseOptions<T> {\n indicator?: SpinnerOptions['indicator'];\n promise: Promise<T>;\n message?: string;\n successMessage?: string;\n errorMessage?: string;\n }\n\n export function createSpinnerPromise<T>(options: SpinnerPromiseOptions<T>): [Promise<T>, ReturnType<typeof spinner>] {\n const loader = spinner({ indicator: options.indicator });\n\n return [\n new Promise<T>((resolve, reject) => {\n loader.start(options.message);\n\n options.promise\n .then((value) => {\n loader.stop(options.successMessage);\n resolve(value);\n })\n .catch((error) => {\n loader.stop(options.errorMessage);\n reject(error);\n });\n }),\n loader\n ];\n }\n\n export function createTsdownLogger(_logger: Logger = logger): RolldownPlugin {\n let startedAt: number;\n\n return {\n name: 'reciple:log-build-completion',\n buildStart: () => {\n _logger.log(colors.green('🚀 Building reciple modules...'));\n startedAt = Date.now();\n },\n renderChunk: (code, info) => {\n const size = Format.bytes(Buffer.byteLength(code, 'utf8'));\n _logger.log(` ├─ ${colors.cyan(size)}\\t${colors.bold(info.fileName)}`);\n\n return { code };\n },\n buildEnd: error => {\n if (error) _logger.error(error)\n },\n closeBundle: () => {\n const time = Format.duration(Date.now() - startedAt);\n _logger.log(colors.green(`✅ Build success in `) + colors.yellow(`${time}`));\n }\n };\n }\n\n export const ignoredDefault = [\n '.git',\n '.log',\n '.nyc_output',\n '.sass-cache',\n '.yarn',\n 'bower_components',\n 'coverage',\n 'node_modules'\n ]\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,IAAa,MAAb,MAAiB;CACb,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CAEP,IAAI,cAAuB;AACvB,SAAO,KAAK,MAAM;;CAGtB,IAAI,QAAmB;AACnB,SAAO,KAAK,QAAQ,MAAM;;CAG9B,YAAY,AAAgB,SAAsB;EAAtB;AACxB,OAAK,QAAQ,QAAQ;AACrB,OAAK,UAAU,OAAO,OAAO,KAAK,MAAM,IAAI,KAAK,MAAM;AAEvD,OAAK,UAAU,IAAI,SAAQ,CACtB,KAAK,QAAQ,KAAI,CACjB,YAAY,QAAQ,YAAW,CAC/B,QAAQ,QAAQ,OAAO,iBAAiB,gCAA+B,CAC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1B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACJ"}
|
|
1
|
+
{"version":3,"file":"CLI.mjs","names":[],"sources":["../../../src/classes/cli/CLI.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { fileURLToPath } from 'node:url';\nimport path from 'node:path';\nimport { coerce } from 'semver';\nimport { Format, isDebugging, recursiveDefaults } from '@reciple/utils';\nimport { logger, Logger, LogLevel } from '@prtty/print';\nimport { config as loadEnv } from '@dotenvx/dotenvx';\nimport { readdir, stat } from 'node:fs/promises';\nimport { CLISubcommand } from './CLISubcommand.js';\nimport { spinner, type SpinnerOptions } from '@clack/prompts';\nimport type { RolldownPlugin } from 'rolldown';\nimport { colors } from '@prtty/prtty';\n\nexport class CLI {\n public build: string;\n public version: string;\n public command: Command;\n public logger: Logger;\n\n get isDebugging(): boolean {\n return this.flags.debug;\n }\n\n get flags(): CLI.Flags {\n return this.command.opts();\n }\n\n constructor(public readonly options: CLI.Options) {\n this.build = options.build;\n this.version = String(coerce(this.build) ?? this.build);\n\n this.command = new Command()\n .name(options.name)\n .description(options.description)\n .version(options.build, '-v, --version', 'Output the CLI version number')\n .option('-D, --debug', 'Enable debug mode', isDebugging())\n .option('--no-debug', 'Disabled debug mode')\n .option('--env <file>', 'Load environment variables from .env file', (v, p) => p.concat(v), [] as string[])\n .enablePositionalOptions(true)\n .hook('preAction', this.handlePreAction.bind(this))\n .showHelpAfterError();\n\n this.logger = options.logger instanceof Logger ? options.logger : new Logger(options.logger);\n\n if (this.flags.debug) {\n this.logger.logLevel = LogLevel.Debug;\n this.logger.writeLevel = LogLevel.Debug;\n }\n }\n\n public async parse(argv?: string[]): Promise<this> {\n await this.loadCommands();\n await this.command.parseAsync(argv);\n return this;\n }\n\n public async loadCommands(): Promise<void> {\n this.logger.debug(`Loading cli commands from ${this.options.subcommandsDir}`);\n\n const dirStat = await stat(this.options.subcommandsDir).catch(() => undefined);\n if (!dirStat?.isDirectory()) return;\n\n const files = (await readdir(this.options.subcommandsDir))\n .map(f => path.join(this.options.subcommandsDir, f))\n .filter(f => f.endsWith('.mjs'));\n\n const hasParent: CLISubcommand[] = [];\n\n for (const file of files) {\n const Subommand = recursiveDefaults<CLISubcommand.Constructor>(await import(path.isAbsolute(file) ? `file://${file}` : file));\n if (!Subommand || typeof Subommand !== 'function') continue;\n\n const instance = new Subommand({ cli: this, command: this.command });\n\n if (instance.parent) {\n hasParent.push(instance);\n continue;\n }\n\n CLISubcommand.registerSubcommand(instance);\n }\n\n for (const instance of hasParent) {\n CLISubcommand.registerSubcommand(instance);\n }\n }\n\n public async handlePreAction(cmd: Command, action: Command): Promise<void> {\n this.logger.debug(`Executing ${action.name()}`);\n this.logger.debug(`Debug mode is ${this.flags.debug ? 'enabled' : 'disabled'}`);\n process.env.NODE_ENV = this.flags.debug ? 'development' : process.env.NODE_ENV;\n\n loadEnv({\n path: this.flags.env.length ? this.flags.env : [path.join(process.cwd(), '.env')],\n debug: this.flags.debug,\n quiet: !this.flags.debug,\n ignore: ['MISSING_ENV_FILE']\n });\n\n this.logger.debug(`Loaded environment variables from ${this.flags.env.join(', ')}`);\n }\n\n public async setCurrentDirectory(cwd?: string): Promise<void> {\n cwd ??= process.cwd();\n\n if (!(await stat(cwd).then(s => s.isDirectory()).catch(() => false))) {\n console.log(colors.red('Please specify a valid project directory'));\n process.exit(1);\n }\n\n process.chdir(cwd);\n }\n\n public getFlags<Flags extends Record<string, any> = Record<string, any>>(command: Command|string, mergeDefault?: false): Flags|undefined;\n public getFlags<Flags extends Record<string, any> = Record<string, any>>(command: Command|string, mergeDefault: true): Flags & CLI.Flags|undefined;\n public getFlags(command?: undefined): CLI.Flags;\n public getFlags(command?: Command|string, mergeDefault: boolean = false): Record<string, any>|undefined {\n if (!command) return this.flags;\n\n command = typeof command === 'string' ? this.command.commands.find(c => c.name() === command) : command;\n const flags = command?.opts();\n\n return mergeDefault ? { ...this.flags, ...flags } : flags;\n }\n\n public getCommand(name: string): Command|undefined;\n public getCommand(name?: undefined): Command;\n public getCommand(name?: string): Command|undefined {\n if (!name) return this.command;\n\n return this.command.commands.find(c => c.name() === name);\n }\n}\n\nexport namespace CLI {\n export interface Options {\n name: string;\n description: string;\n build: string;\n subcommandsDir: string;\n logger?: Logger|Logger.Options;\n }\n\n export interface Flags {\n debug: boolean;\n env: string[];\n }\n\n export const root: string = path.join(path.dirname(fileURLToPath(import.meta.url)), '../../../');\n export const bin: string = path.join(CLI.root, 'dist/bin/reciple.mjs');\n export const version = process.env.__VERSION__;\n\n export function stringifyFlags(flags: Record<string, any>, command: Command, ignored: string[] = []): string[] {\n let arr: string[] = [];\n\n for (const [key, value] of Object.entries(flags)) {\n const option = command.options.find(o => o.name() === key || o.attributeName() === key);\n if (!option || ignored.includes(key)) continue;\n\n const flag = option.long ?? option.short ?? `--${option.name()}`;\n\n if (!option.flags.endsWith('>') && !option.flags.endsWith(']') && typeof value === 'boolean') {\n if (value) arr.push(flag);\n continue;\n }\n\n arr.push(flag, String(value));\n }\n\n return arr;\n }\n\n export interface SpinnerPromiseOptions<T> {\n indicator?: SpinnerOptions['indicator'];\n promise: Promise<T>;\n message?: string;\n successMessage?: string;\n errorMessage?: string;\n }\n\n export function createSpinnerPromise<T>(options: SpinnerPromiseOptions<T>): [Promise<T>, ReturnType<typeof spinner>] {\n const loader = spinner({ indicator: options.indicator });\n\n return [\n new Promise<T>((resolve, reject) => {\n loader.start(options.message);\n\n options.promise\n .then((value) => {\n loader.stop(options.successMessage);\n resolve(value);\n })\n .catch((error) => {\n loader.stop(options.errorMessage);\n reject(error);\n });\n }),\n loader\n ];\n }\n\n export function createTsdownLogger(_logger: Logger = logger): RolldownPlugin {\n let startedAt: number;\n\n return {\n name: 'reciple:log-build-completion',\n buildStart: () => {\n _logger.log(colors.green('🚀 Building reciple modules...'));\n startedAt = Date.now();\n },\n renderChunk: (code, info) => {\n const size = Format.bytes(Buffer.byteLength(code, 'utf8'));\n _logger.log(` ├─ ${colors.cyan(size)}\\t${colors.bold(info.fileName)}`);\n\n return { code };\n },\n buildEnd: error => {\n if (error) _logger.error(error)\n },\n closeBundle: () => {\n const time = Format.duration(Date.now() - startedAt);\n _logger.log(colors.green(`✅ Build success in `) + colors.yellow(`${time}`));\n }\n };\n }\n\n export const ignoredDefault = [\n '.git',\n '.log',\n '.nyc_output',\n '.sass-cache',\n '.yarn',\n 'bower_components',\n 'coverage',\n 'node_modules'\n ]\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,IAAa,MAAb,MAAiB;CACb,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CAEP,IAAI,cAAuB;AACvB,SAAO,KAAK,MAAM;;CAGtB,IAAI,QAAmB;AACnB,SAAO,KAAK,QAAQ,MAAM;;CAG9B,YAAY,AAAgB,SAAsB;EAAtB;AACxB,OAAK,QAAQ,QAAQ;AACrB,OAAK,UAAU,OAAO,OAAO,KAAK,MAAM,IAAI,KAAK,MAAM;AAEvD,OAAK,UAAU,IAAI,SAAQ,CACtB,KAAK,QAAQ,KAAI,CACjB,YAAY,QAAQ,YAAW,CAC/B,QAAQ,QAAQ,OAAO,iBAAiB,gCAA+B,CACvE,OAAO,eAAe,qBAAqB,aAAa,CAAA,CACxD,OAAO,cAAc,sBAAqB,CAC1C,OAAO,gBAAgB,8CAA+C,GAAG,MAAM,EAAE,OAAO,EAAE,EAAE,EAAE,CAAY,CAC1G,wBAAwB,KAAI,CAC5B,KAAK,aAAa,KAAK,gBAAgB,KAAK,KAAK,CAAA,CACjD,oBAAoB;AAEzB,OAAK,SAAS,QAAQ,kBAAkB,SAAS,QAAQ,SAAS,IAAI,OAAO,QAAQ,OAAO;AAE5F,MAAI,KAAK,MAAM,OAAO;AAClB,QAAK,OAAO,WAAW,SAAS;AAChC,QAAK,OAAO,aAAa,SAAS;;;CAI1C,MAAa,MAAM,MAAgC;AAC/C,QAAM,KAAK,cAAc;AACzB,QAAM,KAAK,QAAQ,WAAW,KAAK;AACnC,SAAO;;CAGX,MAAa,eAA8B;AACvC,OAAK,OAAO,MA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AO,MAAM,CAAC;;AAGjC,SAAO;;;CAWJ,SAAS,qBAAwB,SAA6E;EACjH,MAAM,SAAS,QAAQ,EAAE,WAAW,QAAQ,WAAW,CAAC;AAExD,SAAO,CACH,IAAI,SAAY,SAAS,WAAW;AAChC,UAAO,MAAM,QAAQ,QAAQ;AAE7B,WAAQ,QACH,MAAM,UAAU;AACb,WAAO,KAAK,QAAQ,eAAe;AACnC,YAAQ,MAAM;KACjB,CACA,OAAO,UAAU;AACd,WAAO,KAAK,QAAQ,aAAa;AACjC,WAAO,MAAM;KACf;IACR,EACF,OACH;;;CAGE,SAAS,mBAAmB,UAAkB,QAAwB;EACzE,IAAI;AAEJ,SAAO;GACH,MAAM;GACN,kBAAkB;AACd,YAAQ,IAAI,OAAO,MAAM,iCAAiC,CAAC;AAC3D,gBAAY,KAAK,KAAK;;GAE1B,cAAc,MAAM,SAAS;IACzB,MAAM,OAAO,OAAO,MAAM,OAAO,WAAW,MAAM,OAAO,CAAC;AAC1D,YAAQ,IAAI,OAAO,OAAO,KAAK,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,SAAS,GAAG;AAEtE,WAAO,EAAE,MAAM;;GAEnB,WAAU,UAAS;AACf,QAAI,MAAO,SAAQ,MAAM,MAAK;;GAElC,mBAAmB;IACf,MAAM,OAAO,OAAO,SAAS,KAAK,KAAK,GAAG,UAAU;AACpD,YAAQ,IAAI,OAAO,MAAM,sBAAsB,GAAG,OAAO,OAAO,GAAG,OAAO,CAAC;;GAElF;;;uBAGyB;EAC1B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACJ"}
|
|
@@ -35,9 +35,7 @@ declare class ConfigReader {
|
|
|
35
35
|
get build(): UserConfig;
|
|
36
36
|
get sharding(): ShardingManagerOptions | null;
|
|
37
37
|
constructor(filepath: string);
|
|
38
|
-
read(options?: Omit<Options, 'path'>
|
|
39
|
-
ignoreInstanceCheck?: boolean;
|
|
40
|
-
}): Promise<ConfigReader>;
|
|
38
|
+
read(options?: Omit<Options, 'path'>): Promise<ConfigReader>;
|
|
41
39
|
create(options: Omit<ConfigReader.CreateOptions, 'path'>): Promise<ConfigReader>;
|
|
42
40
|
static exists(file: string): Promise<boolean>;
|
|
43
41
|
static create(options: ConfigReader.CreateOptions): Promise<ConfigReader>;
|
|
@@ -52,7 +50,6 @@ declare namespace ConfigReader {
|
|
|
52
50
|
readOptions?: Omit<Options, 'path'> | false;
|
|
53
51
|
}
|
|
54
52
|
interface FindOptions {
|
|
55
|
-
cwd?: string;
|
|
56
53
|
lang?: LangType;
|
|
57
54
|
directories?: string[];
|
|
58
55
|
}
|
|
@@ -30,16 +30,13 @@ var ConfigReader = class ConfigReader {
|
|
|
30
30
|
this.filepath = filepath;
|
|
31
31
|
}
|
|
32
32
|
async read(options) {
|
|
33
|
-
const originalPath = process.cwd();
|
|
34
|
-
process.chdir(path.dirname(this.filepath));
|
|
35
33
|
const { module } = await unrun({
|
|
36
34
|
...options,
|
|
37
35
|
debug: isDebugging(),
|
|
38
36
|
preset: "bundle-require",
|
|
39
37
|
path: this.filepath
|
|
40
38
|
});
|
|
41
|
-
|
|
42
|
-
if (!module || !module.client || !options?.ignoreInstanceCheck && !(module.client instanceof Client)) throw new RecipleError(`exported client is not an instance of ${colors.cyan("Client")} from ${colors.green("\"@reciple/core\"")}.`);
|
|
39
|
+
if (!module || !module.client) throw new RecipleError(`exported client is not an instance of ${colors.cyan("Client")} from ${colors.green("\"@reciple/core\"")}.`);
|
|
43
40
|
this._client = module.client;
|
|
44
41
|
this._config = module.config;
|
|
45
42
|
this._build = module.build;
|
|
@@ -63,9 +60,7 @@ var ConfigReader = class ConfigReader {
|
|
|
63
60
|
}
|
|
64
61
|
static async find(options) {
|
|
65
62
|
const filenames = ConfigReader.configFilenames.filter((f) => !options?.lang || f.endsWith(options.lang));
|
|
66
|
-
const
|
|
67
|
-
const directories = [cwd];
|
|
68
|
-
directories.push(...options?.directories ?? [path.join(cwd, ".config")]);
|
|
63
|
+
const directories = options?.directories ?? [".", ".config"];
|
|
69
64
|
for (const directory of directories) {
|
|
70
65
|
if (!(await stat(directory).catch(() => void 0))?.isDirectory()) continue;
|
|
71
66
|
const file = (await readdir(directory)).find((f) => filenames.includes(f));
|
|
@@ -78,7 +73,7 @@ var ConfigReader = class ConfigReader {
|
|
|
78
73
|
async function getProjectLang(cwd) {
|
|
79
74
|
const hasTsConfig = !!await resolveTSConfig(cwd, { try: true });
|
|
80
75
|
const configLangIsTypescript = !!await ConfigReader.find({
|
|
81
|
-
cwd,
|
|
76
|
+
directories: [cwd, path.join(cwd, ".config")],
|
|
82
77
|
lang: "ts"
|
|
83
78
|
});
|
|
84
79
|
return hasTsConfig || configLangIsTypescript ? "ts" : "js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConfigReader.mjs","names":[],"sources":["../../../src/classes/cli/ConfigReader.ts"],"sourcesContent":["import type { ModuleLoader } from '../client/ModuleLoader.js';\nimport type { ModuleManager } from '../managers/ModuleManager.js';\nimport type { EventListeners } from '../client/EventListeners.js';\nimport type { Logger } from '@prtty/print';\nimport { CLI } from './CLI.js';\nimport { Client, RecipleError, type Config } from '@reciple/core';\nimport type { BuildConfig } from '../../helpers/types.js';\nimport type { UserConfig as TsdownConfig } from 'tsdown';\nimport path from 'node:path';\nimport { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { resolveTSConfig } from 'pkg-types';\nimport { unrun, type Options as UnrunOptions } from 'unrun';\nimport { colors } from '@prtty/prtty';\nimport type { ShardingManagerOptions } from 'discord.js';\nimport { isDebugging } from '@reciple/utils';\n\ndeclare module \"@reciple/core\" {\n interface Config {\n token?: string;\n modules?: ModuleLoader.Config;\n logger?: Logger|Logger.Options;\n }\n\n interface Client {\n readonly modules: ModuleManager;\n readonly moduleLoader: ModuleLoader;\n readonly eventListeners: EventListeners;\n readonly cli: CLI;\n logger: Logger;\n }\n}\n\nexport class ConfigReader {\n private _client: Client|null = null;\n private _config: Config|null = null;\n private _build: BuildConfig|null = null;\n private _sharding: ShardingManagerOptions|null = null;\n\n get client() {\n if (!this._client) throw new RecipleError('client is not yet loaded from config.');\n return this._client;\n }\n\n get config() {\n return this._config ?? {};\n }\n\n get build() {\n return ConfigReader.normalizeTsdownConfig({\n overrides: this._build ?? {}\n });\n }\n\n get sharding() {\n return this._sharding;\n }\n\n constructor(public readonly filepath: string) {}\n\n public async read(options?: Omit<UnrunOptions, 'path'>
|
|
1
|
+
{"version":3,"file":"ConfigReader.mjs","names":[],"sources":["../../../src/classes/cli/ConfigReader.ts"],"sourcesContent":["import type { ModuleLoader } from '../client/ModuleLoader.js';\nimport type { ModuleManager } from '../managers/ModuleManager.js';\nimport type { EventListeners } from '../client/EventListeners.js';\nimport type { Logger } from '@prtty/print';\nimport { CLI } from './CLI.js';\nimport { Client, RecipleError, type Config } from '@reciple/core';\nimport type { BuildConfig } from '../../helpers/types.js';\nimport type { UserConfig as TsdownConfig } from 'tsdown';\nimport path from 'node:path';\nimport { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { resolveTSConfig } from 'pkg-types';\nimport { unrun, type Options as UnrunOptions } from 'unrun';\nimport { colors } from '@prtty/prtty';\nimport type { ShardingManagerOptions } from 'discord.js';\nimport { isDebugging } from '@reciple/utils';\n\ndeclare module \"@reciple/core\" {\n interface Config {\n token?: string;\n modules?: ModuleLoader.Config;\n logger?: Logger|Logger.Options;\n }\n\n interface Client {\n readonly modules: ModuleManager;\n readonly moduleLoader: ModuleLoader;\n readonly eventListeners: EventListeners;\n readonly cli: CLI;\n logger: Logger;\n }\n}\n\nexport class ConfigReader {\n private _client: Client|null = null;\n private _config: Config|null = null;\n private _build: BuildConfig|null = null;\n private _sharding: ShardingManagerOptions|null = null;\n\n get client() {\n if (!this._client) throw new RecipleError('client is not yet loaded from config.');\n return this._client;\n }\n\n get config() {\n return this._config ?? {};\n }\n\n get build() {\n return ConfigReader.normalizeTsdownConfig({\n overrides: this._build ?? {}\n });\n }\n\n get sharding() {\n return this._sharding;\n }\n\n constructor(public readonly filepath: string) {}\n\n public async read(options?: Omit<UnrunOptions, 'path'>): Promise<ConfigReader> {\n const { module } = await unrun<Config>({\n ...options,\n debug: isDebugging(),\n preset: 'bundle-require',\n path: this.filepath\n });\n\n if (!module || !module.client) {\n throw new RecipleError(`exported client is not an instance of ${colors.cyan('Client')} from ${colors.green('\"@reciple/core\"')}.`);\n }\n\n this._client = module.client;\n this._config = module.config;\n this._build = module.build;\n this._sharding = module.sharding ?? null;\n\n return this;\n }\n\n public async create(options: Omit<ConfigReader.CreateOptions, 'path'>): Promise<ConfigReader> {\n const exists = await ConfigReader.exists(this.filepath);\n\n if (exists && options.throwIfExists === true) {\n throw new RecipleError(`Config file already exists at ${colors.green(path.relative(process.cwd(), this.filepath))}.`);\n }\n\n if (!exists || exists && options.overwrite !== false) {\n await mkdir(path.dirname(this.filepath), { recursive: true });\n await writeFile(this.filepath, await ConfigReader.getDefaultContent(options.type));\n }\n\n return options.readOptions !== false ? this.read(options.readOptions) : this;\n }\n\n public static async exists(file: string): Promise<boolean> {\n return await stat(file).then(s => s.isFile()).catch(() => false);\n }\n\n public static async create(options: ConfigReader.CreateOptions): Promise<ConfigReader> {\n return new ConfigReader(options.path).create(options);\n }\n\n public static async find(options?: ConfigReader.FindOptions): Promise<string|null> {\n const filenames = ConfigReader.configFilenames.filter(f => !options?.lang || f.endsWith(options.lang));\n const directories = options?.directories ?? ['.', '.config'];\n\n for (const directory of directories) {\n const stats = await stat(directory).catch(() => undefined);\n\n if (!stats?.isDirectory()) continue;\n\n const file = (await readdir(directory)).find(f => filenames.includes(f));\n if (file) return path.join(directory, file);\n }\n\n return null;\n }\n}\n\nexport namespace ConfigReader {\n export interface CreateOptions {\n path: string;\n overwrite?: boolean;\n throwIfExists?: boolean;\n type: LangType;\n readOptions?: Omit<UnrunOptions, 'path'>|false;\n }\n\n export interface FindOptions {\n lang?: LangType;\n directories?: string[];\n }\n\n export async function getProjectLang(cwd: string): Promise<LangType> {\n const hasTsConfig = !!await resolveTSConfig(cwd, { try: true });\n const configLangIsTypescript = !!(await ConfigReader.find({\n directories: [cwd, path.join(cwd, '.config')],\n lang: 'ts'\n }));\n\n return hasTsConfig || configLangIsTypescript ? 'ts' : 'js';\n }\n\n export type LangType = 'ts'|'js';\n\n export const defaultConfigPath = {\n ts: path.join(CLI.root, 'assets/config', `reciple.config.ts`),\n js: path.join(CLI.root, 'assets/config', `reciple.config.js`)\n };\n\n export async function getDefaultContent(type: LangType): Promise<string> {\n const filepath = ConfigReader.defaultConfigPath[type];\n const content = await readFile(filepath, 'utf-8');\n return content;\n }\n\n export const configFilenames = [\n 'reciple.config.ts',\n 'reciple.config.mts',\n 'reciple.config.js',\n 'reciple.config.mjs'\n ];\n\n export function createConfigFilename(type: LangType, esm: boolean = false): string {\n return `reciple.config.${esm ? 'm' : ''}${type}`;\n }\n\n export function normalizeTsdownConfig({ type, overrides }: { type?: LangType; overrides?: BuildConfig; } = {}): TsdownConfig {\n return {\n entry: [`./src/**/*.{ts,tsx,js,jsx}`],\n outDir: './modules',\n tsconfig: `./${type ?? 'ts'}config.json`,\n external: [],\n noExternal: [],\n sourcemap: true,\n treeshake: true,\n clean: true,\n ...overrides,\n watch: false,\n platform: 'node',\n format: 'esm',\n unbundle: true,\n skipNodeModulesBundle: true\n };\n }\n}\n"],"mappings":";;;;;;;;;;AAgCA,IAAa,eAAb,MAAa,aAAa;CACtB,AAAQ,UAAuB;CAC/B,AAAQ,UAAuB;CAC/B,AAAQ,SAA2B;CACnC,AAAQ,YAAyC;CAEjD,IAAI,SAAS;AACT,MAAI,CAAC,KAAK,QAAS,OAAM,IAAI,aAAa,wCAAwC;AAClF,SAAO,KAAK;;CAGhB,IAAI,SAAS;AACT,SAAO,KAAK,WAAW,EAAE;;CAG7B,IAAI,QAAQ;AACR,SAAO,aAAa,sBAAsB,EACtC,WAAW,KAAK,UAAU,EAAE,EAC/B,CAAC;;CAGN,IAAI,WAAW;AACX,SAAO,KAAK;;CAGhB,Y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
|
|
6
6
|
//#region src/classes/templates/TemplateBuilder.d.ts
|
|
7
7
|
declare class TemplateBuilder {
|
|
8
|
-
|
|
8
|
+
originalCwd: string;
|
|
9
9
|
cli: CLI;
|
|
10
10
|
typescript?: boolean;
|
|
11
11
|
token?: string;
|
|
@@ -14,7 +14,6 @@ declare class TemplateBuilder {
|
|
|
14
14
|
packageJson?: PackageJsonBuilder;
|
|
15
15
|
packageManager?: PackageManagerName;
|
|
16
16
|
dependenciesInstalled: boolean;
|
|
17
|
-
get directory(): string;
|
|
18
17
|
get relativeDirectory(): string;
|
|
19
18
|
get packageJsonPath(): string;
|
|
20
19
|
get name(): string;
|
|
@@ -33,7 +32,6 @@ declare class TemplateBuilder {
|
|
|
33
32
|
declare namespace TemplateBuilder {
|
|
34
33
|
interface Options {
|
|
35
34
|
cli: CLI;
|
|
36
|
-
directory?: string;
|
|
37
35
|
typescript?: boolean;
|
|
38
36
|
packageManager?: PackageManagerName;
|
|
39
37
|
defaultAll?: boolean;
|
|
@@ -16,7 +16,7 @@ import { detectPackageManager, installDependencies, installDependenciesCommand,
|
|
|
16
16
|
|
|
17
17
|
//#region src/classes/templates/TemplateBuilder.ts
|
|
18
18
|
var TemplateBuilder = class TemplateBuilder {
|
|
19
|
-
|
|
19
|
+
originalCwd = process.cwd();
|
|
20
20
|
cli;
|
|
21
21
|
typescript;
|
|
22
22
|
token;
|
|
@@ -25,21 +25,17 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
25
25
|
packageJson;
|
|
26
26
|
packageManager;
|
|
27
27
|
dependenciesInstalled = false;
|
|
28
|
-
get directory() {
|
|
29
|
-
return this._directory ?? process.cwd();
|
|
30
|
-
}
|
|
31
28
|
get relativeDirectory() {
|
|
32
|
-
return path.relative(process.cwd()
|
|
29
|
+
return path.relative(this.originalCwd, process.cwd());
|
|
33
30
|
}
|
|
34
31
|
get packageJsonPath() {
|
|
35
|
-
return path.join(
|
|
32
|
+
return path.join(process.cwd(), "package.json");
|
|
36
33
|
}
|
|
37
34
|
get name() {
|
|
38
|
-
return slug(path.basename(
|
|
35
|
+
return slug(path.basename(process.cwd()));
|
|
39
36
|
}
|
|
40
37
|
constructor(options) {
|
|
41
38
|
this.cli = options.cli;
|
|
42
|
-
this._directory = options.directory;
|
|
43
39
|
this.typescript = options.typescript;
|
|
44
40
|
this.defaultAll = options.defaultAll ?? false;
|
|
45
41
|
this.packageManager = options.packageManager;
|
|
@@ -50,40 +46,42 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
50
46
|
return this;
|
|
51
47
|
}
|
|
52
48
|
async createDirectory(options) {
|
|
53
|
-
|
|
54
|
-
if (!
|
|
49
|
+
let cwd = this.originalCwd;
|
|
50
|
+
if (!options?.directory) {
|
|
55
51
|
const dir = this.defaultAll ? process.cwd() : await text({
|
|
56
52
|
message: `Enter project directory`,
|
|
57
53
|
placeholder: `Leave empty to use current directory`,
|
|
58
54
|
defaultValue: process.cwd(),
|
|
59
55
|
validate: (value) => {
|
|
60
|
-
|
|
61
|
-
if (existsSync(
|
|
56
|
+
value = path.resolve(value);
|
|
57
|
+
if (existsSync(value) && !statSync(value).isDirectory()) return "Invalid folder directory";
|
|
62
58
|
}
|
|
63
59
|
});
|
|
64
60
|
if (isCancel(dir)) throw new NotAnError("Operation cancelled");
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
61
|
+
cwd = path.resolve(dir);
|
|
62
|
+
} else cwd = path.resolve(options.directory);
|
|
63
|
+
const stats = await stat(cwd).catch(() => void 0);
|
|
64
|
+
const relative = path.relative(process.cwd(), cwd);
|
|
65
|
+
if (stats) {
|
|
66
|
+
let files = await readdir(cwd);
|
|
70
67
|
files = micromatch.not(files, options?.ignoredFiles ?? TemplateBuilder.ignoredDirectoryFiles, { dot: true });
|
|
71
68
|
if (files.length) switch (options?.onNotEmpty) {
|
|
72
|
-
case "throw": throw new NotAnError(`Directory ${colors.cyan(
|
|
69
|
+
case "throw": throw new NotAnError(`Directory ${colors.cyan(relative)} is not empty`);
|
|
73
70
|
case "ignore": return this;
|
|
74
71
|
default:
|
|
75
72
|
const overwrite = this.defaultAll ? false : await confirm({
|
|
76
|
-
message: `Directory ${colors.cyan(
|
|
73
|
+
message: `Directory ${colors.cyan(relative)} is not empty. Would you like to continue?`,
|
|
77
74
|
active: "Yes",
|
|
78
75
|
inactive: "No",
|
|
79
76
|
initialValue: false
|
|
80
77
|
});
|
|
81
|
-
if (!overwrite) throw new NotAnError(`Directory ${colors.cyan(
|
|
78
|
+
if (!overwrite) throw new NotAnError(`Directory ${colors.cyan(relative)} is not empty`);
|
|
82
79
|
if (isCancel(overwrite)) throw new NotAnError("Operation cancelled");
|
|
83
80
|
break;
|
|
84
81
|
}
|
|
85
82
|
}
|
|
86
|
-
await mkdir(
|
|
83
|
+
await mkdir(cwd, { recursive: true });
|
|
84
|
+
process.chdir(cwd);
|
|
87
85
|
return this;
|
|
88
86
|
}
|
|
89
87
|
async setupLanguage(options) {
|
|
@@ -102,7 +100,7 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
102
100
|
}
|
|
103
101
|
async createEnvFile(options) {
|
|
104
102
|
const tokenKey = options?.tokenKey ?? "DISCORD_TOKEN";
|
|
105
|
-
const envFile = options?.envFile ? path.resolve(options.envFile) :
|
|
103
|
+
const envFile = options?.envFile ? path.resolve(options.envFile) : ".env";
|
|
106
104
|
const stats = await stat(envFile).catch(() => void 0);
|
|
107
105
|
let env = options?.env ?? {};
|
|
108
106
|
env = stats ? parse(await readFile(envFile, "utf-8"), { processEnv: env }) : env;
|
|
@@ -131,10 +129,7 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
131
129
|
}
|
|
132
130
|
async createConfig(options) {
|
|
133
131
|
let filepath = options?.path;
|
|
134
|
-
|
|
135
|
-
cwd: this.directory,
|
|
136
|
-
lang: this.typescript ? "ts" : this.typescript === false ? "js" : void 0
|
|
137
|
-
}) ?? path.join(this.directory, ConfigReader.createConfigFilename(this.typescript ? "ts" : "js"));
|
|
132
|
+
filepath ??= await ConfigReader.find({ lang: this.typescript ? "ts" : this.typescript === false ? "js" : void 0 }) ?? ConfigReader.createConfigFilename(this.typescript ? "ts" : "js");
|
|
138
133
|
if (await ConfigReader.exists(filepath)) {
|
|
139
134
|
const overwrite = this.defaultAll ? false : await confirm({
|
|
140
135
|
message: `Config file already exists at ${colors.green(path.relative(process.cwd(), filepath))}. Would you like to overwrite it?`,
|
|
@@ -172,11 +167,11 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
172
167
|
}
|
|
173
168
|
}
|
|
174
169
|
const [template, loader] = CLI.createSpinnerPromise({
|
|
175
|
-
promise: Promise.all([TemplateBuilder.copy(source,
|
|
170
|
+
promise: Promise.all([TemplateBuilder.copy(source, process.cwd(), {
|
|
176
171
|
...options,
|
|
177
172
|
rename,
|
|
178
173
|
overwrite
|
|
179
|
-
}), TemplateBuilder.copy(globals,
|
|
174
|
+
}), TemplateBuilder.copy(globals, process.cwd(), {
|
|
180
175
|
...options,
|
|
181
176
|
rename,
|
|
182
177
|
overwrite
|
|
@@ -191,7 +186,7 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
191
186
|
async setPackageManager(options) {
|
|
192
187
|
this.packageManager = options?.packageManager ?? this.packageManager;
|
|
193
188
|
if (!this.packageManager) {
|
|
194
|
-
const defaultPackageManager = await detectPackageManager(
|
|
189
|
+
const defaultPackageManager = await detectPackageManager(process.cwd()).then((pm) => pm?.name ?? "npm");
|
|
195
190
|
const packageManager = this.defaultAll ? defaultPackageManager : await select({
|
|
196
191
|
message: "Select package manager",
|
|
197
192
|
options: [{
|
|
@@ -253,7 +248,6 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
253
248
|
}
|
|
254
249
|
await CLI.createSpinnerPromise({
|
|
255
250
|
promise: installDependencies({
|
|
256
|
-
cwd: this.directory,
|
|
257
251
|
packageManager: this.packageManager,
|
|
258
252
|
silent: !isDebugging()
|
|
259
253
|
}),
|
|
@@ -267,28 +261,27 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
267
261
|
return this;
|
|
268
262
|
}
|
|
269
263
|
async createModules() {
|
|
270
|
-
const modulesDirectory = path.join(this.directory, "src");
|
|
271
264
|
const moduleTemplates = await ModuleTemplateBuilder.resolveModuleTemplates(this.typescript ? "ts" : "js");
|
|
272
|
-
await mkdir(
|
|
265
|
+
await mkdir("src", { recursive: true });
|
|
273
266
|
if (!this.dependenciesInstalled) {
|
|
274
267
|
log.warn("Dependencies not installed. Skipping module creation.");
|
|
275
268
|
return this;
|
|
276
269
|
}
|
|
277
270
|
const moduleOptions = {
|
|
278
271
|
cli: this.cli,
|
|
279
|
-
config: await this.config?.read(
|
|
272
|
+
config: await this.config?.read(),
|
|
280
273
|
defaultAll: true,
|
|
281
274
|
typescript: this.typescript
|
|
282
275
|
};
|
|
283
276
|
const [template, loader] = CLI.createSpinnerPromise({
|
|
284
277
|
promise: Promise.all([new ModuleTemplateBuilder({
|
|
285
278
|
...moduleOptions,
|
|
286
|
-
directory:
|
|
279
|
+
directory: "src/commands",
|
|
287
280
|
filename: `SlashCommand.${this.typescript ? "ts" : "js"}`,
|
|
288
281
|
template: moduleTemplates.find((t) => t.name === "SlashCommand")
|
|
289
282
|
}).setupPlaceholders().then((m) => m.build({ silent: true })), new ModuleTemplateBuilder({
|
|
290
283
|
...moduleOptions,
|
|
291
|
-
directory:
|
|
284
|
+
directory: "src/events",
|
|
292
285
|
filename: `ClientEvent.${this.typescript ? "ts" : "js"}`,
|
|
293
286
|
template: moduleTemplates.find((t) => t.name === "ClientEvent")
|
|
294
287
|
}).setupPlaceholders().then((m) => m.build({ silent: true }))]),
|
|
@@ -302,7 +295,6 @@ var TemplateBuilder = class TemplateBuilder {
|
|
|
302
295
|
async build(options) {
|
|
303
296
|
if (!options?.skipBuild && this.dependenciesInstalled) await CLI.createSpinnerPromise({
|
|
304
297
|
promise: runScript("build", {
|
|
305
|
-
cwd: this.directory,
|
|
306
298
|
packageManager: this.packageManager,
|
|
307
299
|
silent: !isDebugging()
|
|
308
300
|
}),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TemplateBuilder.mjs","names":["parseDotenv"],"sources":["../../../src/classes/templates/TemplateBuilder.ts"],"sourcesContent":["import { isDebugging, PackageJsonBuilder } from '@reciple/utils';\nimport { ConfigReader } from '../cli/ConfigReader.js';\nimport { copyFile, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { confirm, intro, isCancel, outro, select, text, log } from '@clack/prompts';\nimport micromatch from 'micromatch';\nimport { CLI } from '../cli/CLI.js';\nimport path from 'node:path';\nimport { existsSync, statSync } from 'node:fs';\nimport { NotAnError } from '../NotAnError.js';\nimport { slug } from 'github-slugger';\nimport { packageJSON } from '../../helpers/constants.js';\nimport { parse as parseDotenv } from '@dotenvx/dotenvx';\nimport { ModuleTemplateBuilder } from './ModuleTemplateBuilder.js';\nimport { detectPackageManager, installDependencies, installDependenciesCommand, runScript, runScriptCommand, type PackageManagerName } from 'nypm';\nimport { colors } from '@prtty/prtty';\n\nexport class TemplateBuilder {\n private _directory?: string;\n\n public cli: CLI;\n public typescript?: boolean;\n public token?: string;\n public defaultAll: boolean;\n\n public config?: ConfigReader;\n public packageJson?: PackageJsonBuilder;\n\n public packageManager?: PackageManagerName;\n public dependenciesInstalled: boolean = false;\n\n get directory() {\n return this._directory ?? process.cwd();\n }\n\n get relativeDirectory() {\n return path.relative(process.cwd(), this.directory) || './';\n }\n\n get packageJsonPath() {\n return path.join(this.directory, 'package.json');\n }\n\n get name() {\n return slug(path.basename(this.directory));\n }\n\n constructor(options: TemplateBuilder.Options) {\n this.cli = options.cli;\n this._directory = options.directory;\n this.typescript = options.typescript;\n this.defaultAll = options.defaultAll ?? false;\n this.packageManager = options.packageManager;\n this.token = options.token;\n }\n\n public async init(): Promise<this> {\n intro(colors.bold().black().bgCyan(` ${this.cli.command.name()} create - v${this.cli.build} `));\n return this;\n }\n\n public async createDirectory(options?: TemplateBuilder.CreateDirectoryOptions): Promise<this> {\n this._directory = options?.directory ?? this._directory;\n\n if (!this._directory) {\n const dir = this.defaultAll\n ? process.cwd()\n : await text({\n message: `Enter project directory`,\n placeholder: `Leave empty to use current directory`,\n defaultValue: process.cwd(),\n validate: value => {\n const dir = path.resolve(value);\n if (existsSync(dir) && !statSync(dir).isDirectory()) return 'Invalid folder directory';\n }\n });\n\n if (isCancel(dir)) throw new NotAnError('Operation cancelled');\n this._directory = dir;\n }\n\n this._directory = path.resolve(this._directory);\n\n const stats = await stat(this.directory).catch(() => undefined);\n\n if (stats) {\n let files = await readdir(this.directory);\n files = micromatch.not(files, options?.ignoredFiles ?? TemplateBuilder.ignoredDirectoryFiles, { dot: true });\n\n if (files.length) {\n switch (options?.onNotEmpty) {\n case 'throw':\n throw new NotAnError(`Directory ${colors.cyan(this.relativeDirectory)} is not empty`);\n case 'ignore':\n return this;\n default:\n const overwrite = this.defaultAll\n ? false\n : await confirm({\n message: `Directory ${colors.cyan(this.relativeDirectory)} is not empty. Would you like to continue?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (!overwrite) throw new NotAnError(`Directory ${colors.cyan(this.relativeDirectory)} is not empty`);\n if (isCancel(overwrite)) throw new NotAnError('Operation cancelled');\n break;\n }\n }\n }\n\n await mkdir(this.directory, { recursive: true });\n return this;\n }\n\n public async setupLanguage(options?: TemplateBuilder.SetupLanguageOptions): Promise<this> {\n this.typescript = options?.typescript ?? this.typescript;\n\n if (!this.typescript) {\n const isTypeScript = this.defaultAll\n ? false\n : await confirm({\n message: 'Would you like to use TypeScript?',\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (isCancel(isTypeScript)) throw new NotAnError('Operation cancelled');\n this.typescript = isTypeScript;\n }\n\n return this;\n }\n\n public async createEnvFile(options?: TemplateBuilder.CreateEnvFileOptions): Promise<this> {\n const tokenKey = options?.tokenKey ?? 'DISCORD_TOKEN';\n const envFile = options?.envFile ? path.resolve(options.envFile) : path.join(this.directory, '.env');\n const stats = await stat(envFile).catch(() => undefined);\n\n let env = options?.env ?? {};\n env = stats\n ? parseDotenv(await readFile(envFile, 'utf-8'), {\n processEnv: env\n })\n : env;\n\n if (env[tokenKey]) {\n const skip = this.defaultAll || await confirm({\n message: 'Discord bot token already exists in .env file, do you want to skip?',\n initialValue: true,\n active: 'Yes',\n inactive: 'No'\n });\n\n if (isCancel(skip)) throw new NotAnError('Operation cancelled');\n if (skip) return this;\n }\n\n const token = await text({\n message: 'Enter Discord Bot Token',\n placeholder: 'Bot Token from Discord Developer Portal',\n defaultValue: env[tokenKey]\n });\n\n if (isCancel(token)) throw new NotAnError('Operation cancelled');\n env[tokenKey] = token;\n\n await writeFile(envFile, `\\n${tokenKey}=\"${token}\"\\n`, {\n encoding: 'utf-8',\n flag: 'a'\n });\n\n return this;\n }\n\n public async createConfig(options?: TemplateBuilder.CreateConfigOptions): Promise<this> {\n let filepath = options?.path;\n\n if (!filepath) {\n filepath = await ConfigReader.find({\n cwd: this.directory,\n lang: this.typescript\n ? 'ts'\n : this.typescript === false\n ? 'js'\n : undefined\n }) ?? path.join(\n this.directory,\n ConfigReader.createConfigFilename(this.typescript ? 'ts' : 'js')\n );\n }\n\n const exists = await ConfigReader.exists(filepath);\n\n if (exists) {\n const overwrite = this.defaultAll\n ? false\n : await confirm({\n message: `Config file already exists at ${colors.green(path.relative(process.cwd(), filepath))}. Would you like to overwrite it?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (!overwrite) return this;\n if (isCancel(overwrite)) throw new NotAnError('Operation cancelled');\n }\n\n this.config = await ConfigReader.create({\n ...options,\n path: filepath,\n type: this.typescript ? 'ts' : 'js',\n overwrite: true,\n readOptions: false\n });\n\n return this;\n }\n\n public async createTemplate(options?: TemplateBuilder.CreateModulesOptions): Promise<this> {\n const source = path.join(CLI.root, './assets/templates/', this.typescript ? 'typescript' : 'javascript');\n const globals = path.join(CLI.root, './assets/global/');\n\n function rename(data: TemplateBuilder.CopyMetadata) {\n switch (data.basename) {\n case 'gitignore':\n return '.gitignore';\n default:\n return options?.rename?.(data) ?? data.basename;\n }\n }\n\n function overwrite(data: TemplateBuilder.CopyMetadata) {\n switch (data.basename) {\n case 'gitignore':\n return false;\n case 'tsconfig.json':\n case 'jsconfig.json':\n return true;\n default:\n return (typeof options?.overwrite === 'boolean' ? options.overwrite : options?.overwrite?.(data)) ?? true;\n }\n }\n\n const [template, loader] = CLI.createSpinnerPromise({\n promise: Promise.all([\n TemplateBuilder.copy(source, this.directory, { ...options, rename, overwrite }),\n TemplateBuilder.copy(globals, this.directory, { ...options, rename, overwrite })\n ]),\n message: 'Copying template files',\n successMessage: 'Files copied successfully',\n errorMessage: 'Failed to copy files'\n });\n\n await template;\n return this;\n }\n\n public async setPackageManager(options?: TemplateBuilder.SetPackageManagerOptions) {\n this.packageManager = options?.packageManager ?? this.packageManager;\n\n if (!this.packageManager) {\n const defaultPackageManager = await detectPackageManager(this.directory).then(pm => pm?.name ?? 'npm');\n const packageManager: PackageManagerName|symbol = this.defaultAll\n ? defaultPackageManager\n : await select({\n message: 'Select package manager',\n options: [\n { value: defaultPackageManager, label: defaultPackageManager },\n ...[\n { value: 'npm', label: 'npm' },\n { value: 'yarn', label: 'yarn' },\n { value: 'pnpm', label: 'pnpm' },\n { value: 'bun', label: 'bun' },\n { value: 'deno', label: 'deno' }\n ].filter(o => o.value !== defaultPackageManager) as { value: PackageManagerName; label: string; }[]\n ],\n initialValue: defaultPackageManager\n });\n\n if (isCancel(packageManager)) throw new NotAnError('Operation cancelled');\n this.packageManager = packageManager;\n }\n\n this.packageJson = await PackageJsonBuilder.read(this.packageJsonPath, true);\n this.packageJson.merge({\n name: this.name,\n private: true,\n type: 'module',\n scripts: {\n build: `reciple build`,\n start: 'reciple start',\n dev: 'nodemon',\n },\n ...TemplateBuilder.createDependencyRecord(this.typescript ? 'ts' : 'js'),\n });\n\n await this.packageJson?.write(this.packageJsonPath, true);\n\n return this;\n }\n\n public async installDependencies(options?: TemplateBuilder.InstallDependenciesOptions): Promise<this> {\n if (options?.value !== false) {\n if (options?.value === undefined) {\n const install = this.defaultAll\n ? true\n : await confirm({\n message: `Would you like to install dependencies?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: true\n });\n\n if (isCancel(install)) throw new NotAnError('Operation cancelled');\n if (!install) return this;\n }\n\n await CLI.createSpinnerPromise({\n promise: installDependencies({\n cwd: this.directory,\n packageManager: this.packageManager,\n silent: !isDebugging()\n }),\n indicator: 'timer',\n errorMessage: `${colors.bold().red('✗')} Failed to install dependencies`,\n successMessage: `${colors.bold().green('✔')} Dependencies installed successfully`,\n message: `${colors.bold().dim('$')} Installing dependencies`\n })[0];\n\n this.dependenciesInstalled = true;\n }\n\n return this;\n }\n\n public async createModules(): Promise<this> {\n const modulesDirectory = path.join(this.directory, 'src');\n const moduleTemplates = await ModuleTemplateBuilder.resolveModuleTemplates(this.typescript ? 'ts' : 'js');\n\n await mkdir(modulesDirectory, { recursive: true });\n\n if (!this.dependenciesInstalled) {\n log.warn('Dependencies not installed. Skipping module creation.');\n return this;\n }\n\n const moduleOptions: ModuleTemplateBuilder.Options = {\n cli: this.cli,\n config: await this.config?.read({ ignoreInstanceCheck: true })!,\n defaultAll: true,\n typescript: this.typescript,\n };\n\n const [template, loader] = CLI.createSpinnerPromise({\n promise: Promise.all([\n new ModuleTemplateBuilder({\n ...moduleOptions,\n directory: path.join(modulesDirectory, 'commands'),\n filename: `SlashCommand.${this.typescript ? 'ts' : 'js'}`,\n template: moduleTemplates.find(t => t.name === 'SlashCommand')\n })\n .setupPlaceholders()\n .then(m => m.build({ silent: true })),\n new ModuleTemplateBuilder({\n ...moduleOptions,\n directory: path.join(modulesDirectory, 'events'),\n filename: `ClientEvent.${this.typescript ? 'ts' : 'js'}`,\n template: moduleTemplates.find(t => t.name === 'ClientEvent')\n })\n .setupPlaceholders()\n .then(m => m.build({ silent: true }))\n ]),\n message: 'Creating module templates',\n successMessage: 'Module templates created successfully',\n errorMessage: 'Failed to create module templates'\n });\n\n await template;\n return this;\n }\n\n public async build(options?: TemplateBuilder.BuildOptions): Promise<this> {\n if (!options?.skipBuild && this.dependenciesInstalled) await CLI.createSpinnerPromise({\n promise: runScript('build', {\n cwd: this.directory,\n packageManager: this.packageManager,\n silent: !isDebugging()\n }),\n indicator: 'timer',\n errorMessage: `${colors.bold().red('✗')} Failed to build project`,\n successMessage: `${colors.bold().green('✔')} Project built successfully`,\n message: `${colors.bold().dim('$')} Building project`\n })[0];\n\n outro(`Project created in ${colors.cyan(this.relativeDirectory)}`);\n\n console.log(`\\n${colors.bold().green('✔')} Start developing:`);\n\n if (this.relativeDirectory !== './') {\n console.log(` • ${colors.cyan().bold(`cd ${this.relativeDirectory}`)}`);\n }\n\n console.log(` • ${colors.cyan().bold(installDependenciesCommand(this.packageManager ?? 'npm'))} ${colors.dim('(Install dependencies)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'build'))} ${colors.dim('(Build)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'dev'))} ${colors.dim('(Development)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'start'))} ${colors.dim('(Production)')}`);\n\n\n return this;\n }\n}\n\nexport namespace TemplateBuilder {\n export interface Options {\n cli: CLI;\n directory?: string;\n typescript?: boolean;\n packageManager?: PackageManagerName;\n defaultAll?: boolean;\n token?: string;\n }\n\n export const ignoredDirectoryFiles = ['.*', 'LICENSE'];\n\n export const dependencies: Record<'ts'|'js'|'both', Partial<Record<'dependencies'|'devDependencies', Record<string, string>>>> = {\n both: {\n dependencies: {\n '@reciple/core': packageJSON.dependencies?.['@reciple/core']!,\n '@reciple/jsx': packageJSON.dependencies?.['@reciple/jsx']!,\n 'reciple': `^${packageJSON.version}`,\n },\n devDependencies: {\n '@types/node': packageJSON.devDependencies?.['@types/node']!,\n nodemon: packageJSON.devDependencies?.nodemon!,\n typescript: packageJSON.devDependencies?.['typescript']!,\n }\n },\n ts: {},\n js: {}\n };\n\n export function createDependencyRecord(type: 'ts'|'js'): Partial<Record<'dependencies'|'devDependencies', Record<string, string>>> {\n const record = type === 'ts'\n ? dependencies.ts\n : type === 'js'\n ? dependencies.js\n : {};\n\n record.dependencies = { ...record.dependencies, ...dependencies.both.dependencies };\n record.devDependencies = { ...record.devDependencies, ...dependencies.both.devDependencies };\n\n return record;\n }\n\n export interface CreateDirectoryOptions {\n directory?: string;\n ignoredFiles?: string[];\n onNotEmpty?: 'prompt'|'throw'|'ignore';\n }\n\n export interface SetupLanguageOptions {\n typescript?: boolean;\n }\n\n export interface CreateConfigOptions extends Partial<ConfigReader.CreateOptions> {}\n\n export interface CreateModulesOptions extends Partial<CopyOptions> {}\n\n export interface SetPackageManagerOptions {\n packageManager?: PackageManagerName;\n }\n\n export interface InstallDependenciesOptions {\n value?: boolean;\n }\n\n export interface CreateEnvFileOptions {\n envFile?: string;\n tokenKey?: string;\n env?: Record<string, string>;\n }\n\n export interface BuildOptions {\n skipBuild?: boolean;\n }\n\n export interface CopyOptions {\n overwrite?: boolean|((data: CopyMetadata) => boolean);\n filter?: (data: CopyMetadata) => boolean;\n rename?: (data: CopyMetadata) => string;\n }\n\n export interface CopyMetadata {\n basename: string;\n src: string;\n dest: string;\n }\n\n export async function copy(from: string, to: string, options?: CopyOptions): Promise<void> {\n const fromStats = await stat(from).catch(() => undefined);\n if (!fromStats) return;\n\n if (fromStats.isDirectory()) {\n const files = await readdir(from);\n\n for (const file of files) {\n const data: CopyMetadata = {\n basename: file,\n src: path.join(from, file),\n dest: to\n };\n\n await copy(\n data.src,\n path.join(to,\n options?.rename\n ? options.rename(data)\n : file\n ),\n options\n );\n }\n return;\n }\n\n const data: CopyMetadata = {\n basename: path.basename(from),\n src: from,\n dest: to\n };\n\n if (options?.filter && !options.filter(data)) return;\n\n const toStats = await stat(to).catch(() => undefined);\n const overwrite = typeof options?.overwrite === 'function'\n ? options.overwrite(data)\n :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B;IAC7C;GACJ;EACD,IAAI,EAAE;EACN,IAAI,EAAE;EACT;CAEM,SAAS,uBAAuB,MAA4F;EAC/H,MAAM,SAAS,SAAS,OAClB,aAAa,KACb,SAAS,OACL,aAAa,KACb,EAAE;AAEZ,SAAO,eAAe;GAAE,GAAG,OAAO;GAAc,GAAG,aAAa,KAAK;GAAc;AACnF,SAAO,kBAAkB;GAAE,GAAG,OAAO;GAAiB,GAAG,aAAa,KAAK;GAAiB;AAE5F,SAAO;;;CA+CJ,eAAe,KAAK,MAAc,IAAY,SAAsC;EACvF,MAAM,YAAY,MAAM,KAAK,KAAK,CAAC,YAAY,OAAU;AACzD,MAAI,CAAC,UAAW;AAEhB,MAAI,UAAU,aAAa,EAAE;GACzB,MAAM,QAAQ,MAAM,QAAQ,KAAK;AAEjC,QAAK,MAAM,QAAQ,OAAO;IACtB,MAAM,OAAqB;KACvB,UAAU;KACV,KAAK,KAAK,KAAK,MAAM,KAAK;KAC1B,MAAM;KACT;AAED,UAAM,KACF,KAAK,KACL,KAAK,KAAK,IACN,SAAS,SACH,QAAQ,OAAO,KAAK,GACpB,KACT,EACD,QACH;;AAEL;;EAGJ,MAAM,OAAqB;GACvB,UAAU,KAAK,SAAS,KAAK;GAC7B,KAAK;GACL,MAAM;GACT;AAED,MAAI,SAAS,UAAU,CAAC,QAAQ,OAAO,KAAK,CAAE;EAE9C,MAAM,UAAU,MAAM,KAAK,GAAG,CAAC,YAAY,OAAU;EACrD,MAAM,YAAY,OAAO,SAAS,cAAc,aAC1C,QAAQ,UAAU,KAAK,GACvB,SAAS,aAAa;AAE5B,MAAI,WAAW,UAAW;AAE1B,QAAM,MAAM,KAAK,QAAQ,GAAG,EAAE,EAAE,WAAW,MAAM,CAAC;AAClD,QAAM,SAAS,MAAM,GAAG"}
|
|
1
|
+
{"version":3,"file":"TemplateBuilder.mjs","names":["parseDotenv"],"sources":["../../../src/classes/templates/TemplateBuilder.ts"],"sourcesContent":["import { isDebugging, PackageJsonBuilder } from '@reciple/utils';\nimport { ConfigReader } from '../cli/ConfigReader.js';\nimport { copyFile, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { confirm, intro, isCancel, outro, select, text, log } from '@clack/prompts';\nimport micromatch from 'micromatch';\nimport { CLI } from '../cli/CLI.js';\nimport path from 'node:path';\nimport { existsSync, statSync } from 'node:fs';\nimport { NotAnError } from '../NotAnError.js';\nimport { slug } from 'github-slugger';\nimport { packageJSON } from '../../helpers/constants.js';\nimport { parse as parseDotenv } from '@dotenvx/dotenvx';\nimport { ModuleTemplateBuilder } from './ModuleTemplateBuilder.js';\nimport { detectPackageManager, installDependencies, installDependenciesCommand, runScript, runScriptCommand, type PackageManagerName } from 'nypm';\nimport { colors } from '@prtty/prtty';\n\nexport class TemplateBuilder {\n public originalCwd: string = process.cwd();\n\n public cli: CLI;\n public typescript?: boolean;\n public token?: string;\n public defaultAll: boolean;\n\n public config?: ConfigReader;\n public packageJson?: PackageJsonBuilder;\n\n public packageManager?: PackageManagerName;\n public dependenciesInstalled: boolean = false;\n\n get relativeDirectory() {\n return path.relative(this.originalCwd, process.cwd());\n }\n\n get packageJsonPath() {\n return path.join(process.cwd(), 'package.json');\n }\n\n get name() {\n return slug(path.basename(process.cwd()));\n }\n\n constructor(options: TemplateBuilder.Options) {\n this.cli = options.cli;\n this.typescript = options.typescript;\n this.defaultAll = options.defaultAll ?? false;\n this.packageManager = options.packageManager;\n this.token = options.token;\n }\n\n public async init(): Promise<this> {\n intro(colors.bold().black().bgCyan(` ${this.cli.command.name()} create - v${this.cli.build} `));\n return this;\n }\n\n public async createDirectory(options?: TemplateBuilder.CreateDirectoryOptions): Promise<this> {\n let cwd: string = this.originalCwd;\n\n if (!options?.directory) {\n const dir = this.defaultAll\n ? process.cwd()\n : await text({\n message: `Enter project directory`,\n placeholder: `Leave empty to use current directory`,\n defaultValue: process.cwd(),\n validate: value => {\n value = path.resolve(value);\n if (existsSync(value) && !statSync(value).isDirectory()) return 'Invalid folder directory';\n }\n });\n\n if (isCancel(dir)) throw new NotAnError('Operation cancelled');\n\n cwd = path.resolve(dir);\n } else {\n cwd = path.resolve(options.directory);\n }\n\n const stats = await stat(cwd).catch(() => undefined);\n const relative = path.relative(process.cwd(), cwd);\n\n if (stats) {\n let files = await readdir(cwd);\n files = micromatch.not(files, options?.ignoredFiles ?? TemplateBuilder.ignoredDirectoryFiles, { dot: true });\n\n if (files.length) {\n switch (options?.onNotEmpty) {\n case 'throw':\n throw new NotAnError(`Directory ${colors.cyan(relative)} is not empty`);\n case 'ignore':\n return this;\n default:\n const overwrite = this.defaultAll\n ? false\n : await confirm({\n message: `Directory ${colors.cyan(relative)} is not empty. Would you like to continue?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (!overwrite) throw new NotAnError(`Directory ${colors.cyan(relative)} is not empty`);\n if (isCancel(overwrite)) throw new NotAnError('Operation cancelled');\n break;\n }\n }\n }\n\n await mkdir(cwd, { recursive: true });\n process.chdir(cwd);\n return this;\n }\n\n public async setupLanguage(options?: TemplateBuilder.SetupLanguageOptions): Promise<this> {\n this.typescript = options?.typescript ?? this.typescript;\n\n if (!this.typescript) {\n const isTypeScript = this.defaultAll\n ? false\n : await confirm({\n message: 'Would you like to use TypeScript?',\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (isCancel(isTypeScript)) throw new NotAnError('Operation cancelled');\n this.typescript = isTypeScript;\n }\n\n return this;\n }\n\n public async createEnvFile(options?: TemplateBuilder.CreateEnvFileOptions): Promise<this> {\n const tokenKey = options?.tokenKey ?? 'DISCORD_TOKEN';\n const envFile = options?.envFile ? path.resolve(options.envFile) : '.env';\n const stats = await stat(envFile).catch(() => undefined);\n\n let env = options?.env ?? {};\n env = stats\n ? parseDotenv(await readFile(envFile, 'utf-8'), {\n processEnv: env\n })\n : env;\n\n if (env[tokenKey]) {\n const skip = this.defaultAll || await confirm({\n message: 'Discord bot token already exists in .env file, do you want to skip?',\n initialValue: true,\n active: 'Yes',\n inactive: 'No'\n });\n\n if (isCancel(skip)) throw new NotAnError('Operation cancelled');\n if (skip) return this;\n }\n\n const token = await text({\n message: 'Enter Discord Bot Token',\n placeholder: 'Bot Token from Discord Developer Portal',\n defaultValue: env[tokenKey]\n });\n\n if (isCancel(token)) throw new NotAnError('Operation cancelled');\n env[tokenKey] = token;\n\n await writeFile(envFile, `\\n${tokenKey}=\"${token}\"\\n`, {\n encoding: 'utf-8',\n flag: 'a'\n });\n\n return this;\n }\n\n public async createConfig(options?: TemplateBuilder.CreateConfigOptions): Promise<this> {\n let filepath = options?.path;\n\n filepath ??= await ConfigReader.find({\n lang: this.typescript ? 'ts' : this.typescript === false ? 'js' : undefined\n }) ?? ConfigReader.createConfigFilename(this.typescript ? 'ts' : 'js');\n\n const exists = await ConfigReader.exists(filepath);\n\n if (exists) {\n const overwrite = this.defaultAll\n ? false\n : await confirm({\n message: `Config file already exists at ${colors.green(path.relative(process.cwd(), filepath))}. Would you like to overwrite it?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: false\n });\n\n if (!overwrite) return this;\n if (isCancel(overwrite)) throw new NotAnError('Operation cancelled');\n }\n\n this.config = await ConfigReader.create({\n ...options,\n path: filepath,\n type: this.typescript ? 'ts' : 'js',\n overwrite: true,\n readOptions: false\n });\n\n return this;\n }\n\n public async createTemplate(options?: TemplateBuilder.CreateModulesOptions): Promise<this> {\n const source = path.join(CLI.root, './assets/templates/', this.typescript ? 'typescript' : 'javascript');\n const globals = path.join(CLI.root, './assets/global/');\n\n function rename(data: TemplateBuilder.CopyMetadata) {\n switch (data.basename) {\n case 'gitignore':\n return '.gitignore';\n default:\n return options?.rename?.(data) ?? data.basename;\n }\n }\n\n function overwrite(data: TemplateBuilder.CopyMetadata) {\n switch (data.basename) {\n case 'gitignore':\n return false;\n case 'tsconfig.json':\n case 'jsconfig.json':\n return true;\n default:\n return (typeof options?.overwrite === 'boolean' ? options.overwrite : options?.overwrite?.(data)) ?? true;\n }\n }\n\n const [template, loader] = CLI.createSpinnerPromise({\n promise: Promise.all([\n TemplateBuilder.copy(source, process.cwd(), { ...options, rename, overwrite }),\n TemplateBuilder.copy(globals, process.cwd(), { ...options, rename, overwrite })\n ]),\n message: 'Copying template files',\n successMessage: 'Files copied successfully',\n errorMessage: 'Failed to copy files'\n });\n\n await template;\n return this;\n }\n\n public async setPackageManager(options?: TemplateBuilder.SetPackageManagerOptions) {\n this.packageManager = options?.packageManager ?? this.packageManager;\n\n if (!this.packageManager) {\n const defaultPackageManager = await detectPackageManager(process.cwd()).then(pm => pm?.name ?? 'npm');\n const packageManager: PackageManagerName|symbol = this.defaultAll\n ? defaultPackageManager\n : await select({\n message: 'Select package manager',\n options: [\n { value: defaultPackageManager, label: defaultPackageManager },\n ...[\n { value: 'npm', label: 'npm' },\n { value: 'yarn', label: 'yarn' },\n { value: 'pnpm', label: 'pnpm' },\n { value: 'bun', label: 'bun' },\n { value: 'deno', label: 'deno' }\n ].filter(o => o.value !== defaultPackageManager) as { value: PackageManagerName; label: string; }[]\n ],\n initialValue: defaultPackageManager\n });\n\n if (isCancel(packageManager)) throw new NotAnError('Operation cancelled');\n this.packageManager = packageManager;\n }\n\n this.packageJson = await PackageJsonBuilder.read(this.packageJsonPath, true);\n this.packageJson.merge({\n name: this.name,\n private: true,\n type: 'module',\n scripts: {\n build: `reciple build`,\n start: 'reciple start',\n dev: 'nodemon',\n },\n ...TemplateBuilder.createDependencyRecord(this.typescript ? 'ts' : 'js'),\n });\n\n await this.packageJson?.write(this.packageJsonPath, true);\n\n return this;\n }\n\n public async installDependencies(options?: TemplateBuilder.InstallDependenciesOptions): Promise<this> {\n if (options?.value !== false) {\n if (options?.value === undefined) {\n const install = this.defaultAll\n ? true\n : await confirm({\n message: `Would you like to install dependencies?`,\n active: 'Yes',\n inactive: 'No',\n initialValue: true\n });\n\n if (isCancel(install)) throw new NotAnError('Operation cancelled');\n if (!install) return this;\n }\n\n await CLI.createSpinnerPromise({\n promise: installDependencies({\n packageManager: this.packageManager,\n silent: !isDebugging()\n }),\n indicator: 'timer',\n errorMessage: `${colors.bold().red('✗')} Failed to install dependencies`,\n successMessage: `${colors.bold().green('✔')} Dependencies installed successfully`,\n message: `${colors.bold().dim('$')} Installing dependencies`\n })[0];\n\n this.dependenciesInstalled = true;\n }\n\n return this;\n }\n\n public async createModules(): Promise<this> {\n const moduleTemplates = await ModuleTemplateBuilder.resolveModuleTemplates(this.typescript ? 'ts' : 'js');\n\n await mkdir('src', { recursive: true });\n\n if (!this.dependenciesInstalled) {\n log.warn('Dependencies not installed. Skipping module creation.');\n return this;\n }\n\n const moduleOptions: ModuleTemplateBuilder.Options = {\n cli: this.cli,\n config: await this.config?.read()!,\n defaultAll: true,\n typescript: this.typescript,\n };\n\n const [template, loader] = CLI.createSpinnerPromise({\n promise: Promise.all([\n new ModuleTemplateBuilder({\n ...moduleOptions,\n directory: 'src/commands',\n filename: `SlashCommand.${this.typescript ? 'ts' : 'js'}`,\n template: moduleTemplates.find(t => t.name === 'SlashCommand')\n })\n .setupPlaceholders()\n .then(m => m.build({ silent: true })),\n new ModuleTemplateBuilder({\n ...moduleOptions,\n directory: 'src/events',\n filename: `ClientEvent.${this.typescript ? 'ts' : 'js'}`,\n template: moduleTemplates.find(t => t.name === 'ClientEvent')\n })\n .setupPlaceholders()\n .then(m => m.build({ silent: true }))\n ]),\n message: 'Creating module templates',\n successMessage: 'Module templates created successfully',\n errorMessage: 'Failed to create module templates'\n });\n\n await template;\n return this;\n }\n\n public async build(options?: TemplateBuilder.BuildOptions): Promise<this> {\n if (!options?.skipBuild && this.dependenciesInstalled) await CLI.createSpinnerPromise({\n promise: runScript('build', {\n packageManager: this.packageManager,\n silent: !isDebugging()\n }),\n indicator: 'timer',\n errorMessage: `${colors.bold().red('✗')} Failed to build project`,\n successMessage: `${colors.bold().green('✔')} Project built successfully`,\n message: `${colors.bold().dim('$')} Building project`\n })[0];\n\n outro(`Project created in ${colors.cyan(this.relativeDirectory)}`);\n\n console.log(`\\n${colors.bold().green('✔')} Start developing:`);\n\n if (this.relativeDirectory !== './') {\n console.log(` • ${colors.cyan().bold(`cd ${this.relativeDirectory}`)}`);\n }\n\n console.log(` • ${colors.cyan().bold(installDependenciesCommand(this.packageManager ?? 'npm'))} ${colors.dim('(Install dependencies)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'build'))} ${colors.dim('(Build)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'dev'))} ${colors.dim('(Development)')}`);\n console.log(` • ${colors.cyan().bold(runScriptCommand(this.packageManager ?? 'npm', 'start'))} ${colors.dim('(Production)')}`);\n\n\n return this;\n }\n}\n\nexport namespace TemplateBuilder {\n export interface Options {\n cli: CLI;\n typescript?: boolean;\n packageManager?: PackageManagerName;\n defaultAll?: boolean;\n token?: string;\n }\n\n export const ignoredDirectoryFiles = ['.*', 'LICENSE'];\n\n export const dependencies: Record<'ts'|'js'|'both', Partial<Record<'dependencies'|'devDependencies', Record<string, string>>>> = {\n both: {\n dependencies: {\n '@reciple/core': packageJSON.dependencies?.['@reciple/core']!,\n '@reciple/jsx': packageJSON.dependencies?.['@reciple/jsx']!,\n 'reciple': `^${packageJSON.version}`,\n },\n devDependencies: {\n '@types/node': packageJSON.devDependencies?.['@types/node']!,\n nodemon: packageJSON.devDependencies?.nodemon!,\n typescript: packageJSON.devDependencies?.['typescript']!,\n }\n },\n ts: {},\n js: {}\n };\n\n export function createDependencyRecord(type: 'ts'|'js'): Partial<Record<'dependencies'|'devDependencies', Record<string, string>>> {\n const record = type === 'ts'\n ? dependencies.ts\n : type === 'js'\n ? dependencies.js\n : {};\n\n record.dependencies = { ...record.dependencies, ...dependencies.both.dependencies };\n record.devDependencies = { ...record.devDependencies, ...dependencies.both.devDependencies };\n\n return record;\n }\n\n export interface CreateDirectoryOptions {\n directory?: string;\n ignoredFiles?: string[];\n onNotEmpty?: 'prompt'|'throw'|'ignore';\n }\n\n export interface SetupLanguageOptions {\n typescript?: boolean;\n }\n\n export interface CreateConfigOptions extends Partial<ConfigReader.CreateOptions> {}\n\n export interface CreateModulesOptions extends Partial<CopyOptions> {}\n\n export interface SetPackageManagerOptions {\n packageManager?: PackageManagerName;\n }\n\n export interface InstallDependenciesOptions {\n value?: boolean;\n }\n\n export interface CreateEnvFileOptions {\n envFile?: string;\n tokenKey?: string;\n env?: Record<string, string>;\n }\n\n export interface BuildOptions {\n skipBuild?: boolean;\n }\n\n export interface CopyOptions {\n overwrite?: boolean|((data: CopyMetadata) => boolean);\n filter?: (data: CopyMetadata) => boolean;\n rename?: (data: CopyMetadata) => string;\n }\n\n export interface CopyMetadata {\n basename: string;\n src: string;\n dest: string;\n }\n\n export async function copy(from: string, to: string, options?: CopyOptions): Promise<void> {\n const fromStats = await stat(from).catch(() => undefined);\n if (!fromStats) return;\n\n if (fromStats.isDirectory()) {\n const files = await readdir(from);\n\n for (const file of files) {\n const data: CopyMetadata = {\n basename: file,\n src: path.join(from, file),\n dest: to\n };\n\n await copy(\n data.src,\n path.join(to,\n options?.rename\n ? options.rename(data)\n : file\n ),\n options\n );\n }\n return;\n }\n\n const data: CopyMetadata = {\n basename: path.basename(from),\n src: from,\n dest: to\n };\n\n if (options?.filter && !options.filter(data)) return;\n\n const toStats = await stat(to).catch(() => undefined);\n const overwrite = typeof options?.overwrite === 'function'\n ? options.overwrite(data)\n : options?.overwrite ?? true;\n\n if (toStats && overwrite) return;\n\n await mkdir(path.dirname(to), { recursive: true });\n await copyFile(from, to);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,IAAa,kBAAb,MAAa,gBAAgB;CACzB,AAAO,cAAsB,QAAQ,KAAK;CAE1C,AAAO;CACP,AAAO;CACP,AAAO;CACP,AAAO;CAEP,AAAO;CACP,AAAO;CAEP,AAAO;CACP,AAAO,wBAAiC;CAExC,IAAI,oBAAoB;AACpB,SAAO,KAAK,SAAS,KAAK,aAAa,QAAQ,KAAK,CAAC;;CAGzD,IAAI,kBAAkB;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KACF,KAAK,KACL,KAAK,KAAK,IACN,SAAS,SACH,QAAQ,OAAO,KAAK,GACpB,KACT,EACD,QACH;;AAEL;;EAGJ,MAAM,OAAqB;GACvB,UAAU,KAAK,SAAS,KAAK;GAC7B,KAAK;GACL,MAAM;GACT;AAED,MAAI,SAAS,UAAU,CAAC,QAAQ,OAAO,KAAK,CAAE;EAE9C,MAAM,UAAU,MAAM,KAAK,GAAG,CAAC,YAAY,OAAU;EACrD,MAAM,YAAY,OAAO,SAAS,cAAc,aAC1C,QAAQ,UAAU,KAAK,GACvB,SAAS,aAAa;AAE5B,MAAI,WAAW,UAAW;AAE1B,QAAM,MAAM,KAAK,QAAQ,GAAG,EAAE,EAAE,WAAW,MAAM,CAAC;AAClD,QAAM,SAAS,MAAM,GAAG"}
|
|
@@ -3,11 +3,11 @@ import { AnyCommandModuleData } from "../../helpers/types.mjs";
|
|
|
3
3
|
import "../../index.mjs";
|
|
4
4
|
import * as _reciple_core0 from "@reciple/core";
|
|
5
5
|
import { Validator } from "@reciple/core";
|
|
6
|
-
import * as
|
|
6
|
+
import * as _sapphire_shapeshift18 from "@sapphire/shapeshift";
|
|
7
7
|
|
|
8
8
|
//#region src/classes/validation/CommandModuleValidator.d.ts
|
|
9
9
|
declare class CommandModuleValidator extends Validator {
|
|
10
|
-
static object:
|
|
10
|
+
static object: _sapphire_shapeshift18.ObjectValidator<{
|
|
11
11
|
id: string | undefined;
|
|
12
12
|
moduleType: ModuleType | undefined;
|
|
13
13
|
onEnable: Function | undefined;
|
|
@@ -16,23 +16,23 @@ declare class CommandModuleValidator extends Validator {
|
|
|
16
16
|
} & {
|
|
17
17
|
id: string;
|
|
18
18
|
type: _reciple_core0.CommandType;
|
|
19
|
-
data:
|
|
19
|
+
data: _sapphire_shapeshift18.UndefinedToOptional<{
|
|
20
20
|
name: any;
|
|
21
21
|
description: any;
|
|
22
22
|
aliases: any;
|
|
23
23
|
options: any;
|
|
24
24
|
flags: any;
|
|
25
|
-
}> |
|
|
25
|
+
}> | _sapphire_shapeshift18.UndefinedToOptional<{
|
|
26
26
|
type: any;
|
|
27
27
|
name: any;
|
|
28
28
|
}>;
|
|
29
29
|
cooldown: number | undefined;
|
|
30
|
-
preconditions:
|
|
30
|
+
preconditions: _sapphire_shapeshift18.UndefinedToOptional<{
|
|
31
31
|
id: any;
|
|
32
32
|
scope: any;
|
|
33
33
|
execute: any;
|
|
34
34
|
}>[] | undefined;
|
|
35
|
-
postconditions:
|
|
35
|
+
postconditions: _sapphire_shapeshift18.UndefinedToOptional<{
|
|
36
36
|
id: any;
|
|
37
37
|
scope: any;
|
|
38
38
|
execute: any;
|
|
@@ -40,7 +40,7 @@ declare class CommandModuleValidator extends Validator {
|
|
|
40
40
|
disabledPreconditions: string[] | undefined;
|
|
41
41
|
disabledPostconditions: string[] | undefined;
|
|
42
42
|
execute: Function;
|
|
43
|
-
},
|
|
43
|
+
}, _sapphire_shapeshift18.UndefinedToOptional<{
|
|
44
44
|
id: string | undefined;
|
|
45
45
|
moduleType: ModuleType | undefined;
|
|
46
46
|
onEnable: Function | undefined;
|
|
@@ -49,23 +49,23 @@ declare class CommandModuleValidator extends Validator {
|
|
|
49
49
|
} & {
|
|
50
50
|
id: string;
|
|
51
51
|
type: _reciple_core0.CommandType;
|
|
52
|
-
data:
|
|
52
|
+
data: _sapphire_shapeshift18.UndefinedToOptional<{
|
|
53
53
|
name: any;
|
|
54
54
|
description: any;
|
|
55
55
|
aliases: any;
|
|
56
56
|
options: any;
|
|
57
57
|
flags: any;
|
|
58
|
-
}> |
|
|
58
|
+
}> | _sapphire_shapeshift18.UndefinedToOptional<{
|
|
59
59
|
type: any;
|
|
60
60
|
name: any;
|
|
61
61
|
}>;
|
|
62
62
|
cooldown: number | undefined;
|
|
63
|
-
preconditions:
|
|
63
|
+
preconditions: _sapphire_shapeshift18.UndefinedToOptional<{
|
|
64
64
|
id: any;
|
|
65
65
|
scope: any;
|
|
66
66
|
execute: any;
|
|
67
67
|
}>[] | undefined;
|
|
68
|
-
postconditions:
|
|
68
|
+
postconditions: _sapphire_shapeshift18.UndefinedToOptional<{
|
|
69
69
|
id: any;
|
|
70
70
|
scope: any;
|
|
71
71
|
execute: any;
|
|
@@ -74,9 +74,9 @@ declare class CommandModuleValidator extends Validator {
|
|
|
74
74
|
disabledPostconditions: string[] | undefined;
|
|
75
75
|
execute: Function;
|
|
76
76
|
}>>;
|
|
77
|
-
static resolvable:
|
|
77
|
+
static resolvable: _sapphire_shapeshift18.UnionValidator<_sapphire_shapeshift18.UndefinedToOptional<{
|
|
78
78
|
toJSON: Function;
|
|
79
|
-
}> |
|
|
79
|
+
}> | _sapphire_shapeshift18.UndefinedToOptional<{
|
|
80
80
|
id: string | undefined;
|
|
81
81
|
moduleType: ModuleType | undefined;
|
|
82
82
|
onEnable: Function | undefined;
|
|
@@ -85,23 +85,23 @@ declare class CommandModuleValidator extends Validator {
|
|
|
85
85
|
} & {
|
|
86
86
|
id: string;
|
|
87
87
|
type: _reciple_core0.CommandType;
|
|
88
|
-
data:
|
|
88
|
+
data: _sapphire_shapeshift18.UndefinedToOptional<{
|
|
89
89
|
name: any;
|
|
90
90
|
description: any;
|
|
91
91
|
aliases: any;
|
|
92
92
|
options: any;
|
|
93
93
|
flags: any;
|
|
94
|
-
}> |
|
|
94
|
+
}> | _sapphire_shapeshift18.UndefinedToOptional<{
|
|
95
95
|
type: any;
|
|
96
96
|
name: any;
|
|
97
97
|
}>;
|
|
98
98
|
cooldown: number | undefined;
|
|
99
|
-
preconditions:
|
|
99
|
+
preconditions: _sapphire_shapeshift18.UndefinedToOptional<{
|
|
100
100
|
id: any;
|
|
101
101
|
scope: any;
|
|
102
102
|
execute: any;
|
|
103
103
|
}>[] | undefined;
|
|
104
|
-
postconditions:
|
|
104
|
+
postconditions: _sapphire_shapeshift18.UndefinedToOptional<{
|
|
105
105
|
id: any;
|
|
106
106
|
scope: any;
|
|
107
107
|
execute: any;
|
|
@@ -3,19 +3,19 @@ import { EventModule } from "../modules/events/EventModule.mjs";
|
|
|
3
3
|
import "../../index.mjs";
|
|
4
4
|
import { Validator } from "@reciple/core";
|
|
5
5
|
import { EventEmitter } from "node:events";
|
|
6
|
-
import * as
|
|
6
|
+
import * as _sapphire_shapeshift9 from "@sapphire/shapeshift";
|
|
7
7
|
|
|
8
8
|
//#region src/classes/validation/EventModuleValidator.d.ts
|
|
9
9
|
declare class EventModuleValidator extends Validator {
|
|
10
|
-
static emitter:
|
|
10
|
+
static emitter: _sapphire_shapeshift9.InstanceValidator<EventEmitter<{
|
|
11
11
|
[x: string]: any[];
|
|
12
12
|
[x: number]: any[];
|
|
13
13
|
[x: symbol]: any[];
|
|
14
14
|
}>>;
|
|
15
|
-
static event:
|
|
16
|
-
static once:
|
|
17
|
-
static onEvent:
|
|
18
|
-
static object:
|
|
15
|
+
static event: _sapphire_shapeshift9.StringValidator<string>;
|
|
16
|
+
static once: _sapphire_shapeshift9.UnionValidator<boolean | undefined>;
|
|
17
|
+
static onEvent: _sapphire_shapeshift9.InstanceValidator<Function>;
|
|
18
|
+
static object: _sapphire_shapeshift9.ObjectValidator<{
|
|
19
19
|
id: string | undefined;
|
|
20
20
|
moduleType: ModuleType | undefined;
|
|
21
21
|
onEnable: Function | undefined;
|
|
@@ -30,7 +30,7 @@ declare class EventModuleValidator extends Validator {
|
|
|
30
30
|
event: string;
|
|
31
31
|
once: boolean | undefined;
|
|
32
32
|
onEvent: Function;
|
|
33
|
-
},
|
|
33
|
+
}, _sapphire_shapeshift9.UndefinedToOptional<{
|
|
34
34
|
id: string | undefined;
|
|
35
35
|
moduleType: ModuleType | undefined;
|
|
36
36
|
onEnable: Function | undefined;
|
|
@@ -46,9 +46,9 @@ declare class EventModuleValidator extends Validator {
|
|
|
46
46
|
once: boolean | undefined;
|
|
47
47
|
onEvent: Function;
|
|
48
48
|
}>>;
|
|
49
|
-
static resolvable:
|
|
49
|
+
static resolvable: _sapphire_shapeshift9.UnionValidator<_sapphire_shapeshift9.UndefinedToOptional<{
|
|
50
50
|
toJSON: Function;
|
|
51
|
-
}> |
|
|
51
|
+
}> | _sapphire_shapeshift9.UndefinedToOptional<{
|
|
52
52
|
id: string | undefined;
|
|
53
53
|
moduleType: ModuleType | undefined;
|
|
54
54
|
onEnable: Function | undefined;
|
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
import { PostconditionModule } from "../modules/PostconditionModule.mjs";
|
|
2
2
|
import { CommandPostconditionReason, CommandType, Validator } from "@reciple/core";
|
|
3
|
-
import * as
|
|
3
|
+
import * as _sapphire_shapeshift35 from "@sapphire/shapeshift";
|
|
4
4
|
|
|
5
5
|
//#region src/classes/validation/PostconditionModule.d.ts
|
|
6
6
|
declare class PostconditionModuleValidator extends Validator {
|
|
7
|
-
static scope:
|
|
8
|
-
static accepts:
|
|
9
|
-
static execute:
|
|
10
|
-
static object:
|
|
7
|
+
static scope: _sapphire_shapeshift35.UnionValidator<CommandType[] | undefined>;
|
|
8
|
+
static accepts: _sapphire_shapeshift35.UnionValidator<CommandPostconditionReason[] | undefined>;
|
|
9
|
+
static execute: _sapphire_shapeshift35.InstanceValidator<Function>;
|
|
10
|
+
static object: _sapphire_shapeshift35.ObjectValidator<{
|
|
11
11
|
scope: CommandType[] | undefined;
|
|
12
12
|
execute: Function;
|
|
13
|
-
},
|
|
13
|
+
}, _sapphire_shapeshift35.UndefinedToOptional<{
|
|
14
14
|
scope: CommandType[] | undefined;
|
|
15
15
|
execute: Function;
|
|
16
16
|
}>>;
|
|
17
|
-
static resolvable:
|
|
17
|
+
static resolvable: _sapphire_shapeshift35.UnionValidator<_sapphire_shapeshift35.UndefinedToOptional<{
|
|
18
18
|
toJSON: Function;
|
|
19
|
-
}> |
|
|
19
|
+
}> | _sapphire_shapeshift35.UndefinedToOptional<{
|
|
20
20
|
scope: CommandType[] | undefined;
|
|
21
21
|
execute: Function;
|
|
22
22
|
}>>;
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import { PreconditionModule } from "../modules/PreconditionModule.mjs";
|
|
2
2
|
import { CommandType, Validator } from "@reciple/core";
|
|
3
|
-
import * as
|
|
3
|
+
import * as _sapphire_shapeshift43 from "@sapphire/shapeshift";
|
|
4
4
|
|
|
5
5
|
//#region src/classes/validation/PreconditionModule.d.ts
|
|
6
6
|
declare class PreconditionModuleValidator extends Validator {
|
|
7
|
-
static scope:
|
|
8
|
-
static execute:
|
|
9
|
-
static object:
|
|
7
|
+
static scope: _sapphire_shapeshift43.UnionValidator<CommandType[] | undefined>;
|
|
8
|
+
static execute: _sapphire_shapeshift43.InstanceValidator<Function>;
|
|
9
|
+
static object: _sapphire_shapeshift43.ObjectValidator<{
|
|
10
10
|
scope: CommandType[] | undefined;
|
|
11
11
|
execute: Function;
|
|
12
|
-
},
|
|
12
|
+
}, _sapphire_shapeshift43.UndefinedToOptional<{
|
|
13
13
|
scope: CommandType[] | undefined;
|
|
14
14
|
execute: Function;
|
|
15
15
|
}>>;
|
|
16
|
-
static resolvable:
|
|
16
|
+
static resolvable: _sapphire_shapeshift43.UnionValidator<_sapphire_shapeshift43.UndefinedToOptional<{
|
|
17
17
|
toJSON: Function;
|
|
18
|
-
}> |
|
|
18
|
+
}> | _sapphire_shapeshift43.UndefinedToOptional<{
|
|
19
19
|
scope: CommandType[] | undefined;
|
|
20
20
|
execute: Function;
|
|
21
21
|
}>>;
|
package/dist/package.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//#region package.json
|
|
2
2
|
var package_default = {
|
|
3
3
|
name: "reciple",
|
|
4
|
-
version: "10.0.
|
|
4
|
+
version: "10.0.6",
|
|
5
5
|
license: "LGPL-3.0-only",
|
|
6
6
|
description: "The CLI for reciple",
|
|
7
7
|
module: "./dist/index.mjs",
|
|
@@ -57,15 +57,15 @@ var package_default = {
|
|
|
57
57
|
devDependencies: {
|
|
58
58
|
"@reciple/jsx": "^10.0.1",
|
|
59
59
|
"@types/micromatch": "^4.0.10",
|
|
60
|
-
"@types/node": "
|
|
60
|
+
"@types/node": "*",
|
|
61
61
|
"@types/semver": "^7.7.1",
|
|
62
62
|
"nodemon": "^3.1.11",
|
|
63
63
|
"rolldown": "^1.0.0-rc.1",
|
|
64
|
-
"typescript": "
|
|
64
|
+
"typescript": "*"
|
|
65
65
|
},
|
|
66
66
|
peerDependencies: {
|
|
67
|
-
"@reciple/core": "
|
|
68
|
-
"discord.js": "
|
|
67
|
+
"@reciple/core": "*",
|
|
68
|
+
"discord.js": "*"
|
|
69
69
|
},
|
|
70
70
|
peerDependenciesMeta: {
|
|
71
71
|
"@reciple/core": { "optional": false },
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "reciple",
|
|
3
|
-
"version": "10.0.
|
|
3
|
+
"version": "10.0.6",
|
|
4
4
|
"license": "LGPL-3.0-only",
|
|
5
5
|
"description": "The CLI for reciple",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -56,15 +56,15 @@
|
|
|
56
56
|
"devDependencies": {
|
|
57
57
|
"@reciple/jsx": "^10.0.1",
|
|
58
58
|
"@types/micromatch": "^4.0.10",
|
|
59
|
-
"@types/node": "
|
|
59
|
+
"@types/node": "*",
|
|
60
60
|
"@types/semver": "^7.7.1",
|
|
61
61
|
"nodemon": "^3.1.11",
|
|
62
62
|
"rolldown": "^1.0.0-rc.1",
|
|
63
|
-
"typescript": "
|
|
63
|
+
"typescript": "*"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|
|
66
|
-
"@reciple/core": "
|
|
67
|
-
"discord.js": "
|
|
66
|
+
"@reciple/core": "*",
|
|
67
|
+
"discord.js": "*"
|
|
68
68
|
},
|
|
69
69
|
"peerDependenciesMeta": {
|
|
70
70
|
"@reciple/core": {
|