reciple 10.0.1-dev.7 → 10.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -0
- package/assets/config/reciple.config.js +7 -0
- package/assets/config/reciple.config.ts +5 -0
- package/assets/global/nodemon.json +1 -0
- package/assets/templates/javascript/jsconfig.json +14 -2
- package/assets/templates/typescript/tsconfig.json +14 -2
- package/dist/_virtual/{_@oxc-project_runtime@0.99.0 → _@oxc-project_runtime@0.108.0}/helpers/decorate.mjs +1 -1
- package/dist/bin/commands/build.mjs +1 -1
- package/dist/bin/commands/build.mjs.map +1 -1
- package/dist/bin/commands/create.mjs +3 -2
- package/dist/bin/commands/create.mjs.map +1 -1
- package/dist/bin/commands/createModule.mjs +2 -2
- package/dist/bin/commands/createModule.mjs.map +1 -1
- package/dist/bin/commands/start.mjs +10 -9
- package/dist/bin/commands/start.mjs.map +1 -1
- package/dist/bin/commands/startSharding.d.mts +18 -0
- package/dist/bin/commands/startSharding.mjs +101 -0
- package/dist/bin/commands/startSharding.mjs.map +1 -0
- package/dist/bin/reciple.mjs +0 -0
- package/dist/classes/cli/CLI.d.mts +1 -1
- package/dist/classes/cli/CLI.mjs +6 -5
- package/dist/classes/cli/CLI.mjs.map +1 -1
- package/dist/classes/cli/ConfigReader.d.mts +24 -29
- package/dist/classes/cli/ConfigReader.mjs +45 -61
- package/dist/classes/cli/ConfigReader.mjs.map +1 -1
- package/dist/classes/cli/RuntimeEnvironment.mjs +1 -1
- package/dist/classes/cli/RuntimeEnvironment.mjs.map +1 -1
- package/dist/classes/client/EventListeners.mjs +3 -2
- package/dist/classes/client/EventListeners.mjs.map +1 -1
- package/dist/classes/client/ModuleLoader.d.mts +3 -3
- package/dist/classes/client/ModuleLoader.mjs +10 -8
- package/dist/classes/client/ModuleLoader.mjs.map +1 -1
- package/dist/classes/managers/ModuleManager.mjs +5 -5
- package/dist/classes/managers/ModuleManager.mjs.map +1 -1
- package/dist/classes/modules/BaseModule.d.mts +0 -3
- package/dist/classes/modules/BaseModule.mjs +2 -4
- package/dist/classes/modules/BaseModule.mjs.map +1 -1
- package/dist/classes/modules/PostconditionModule.d.mts +1 -1
- package/dist/classes/modules/PostconditionModule.mjs +5 -5
- package/dist/classes/modules/PostconditionModule.mjs.map +1 -1
- package/dist/classes/modules/PreconditionModule.d.mts +1 -1
- package/dist/classes/modules/PreconditionModule.mjs +5 -5
- package/dist/classes/modules/PreconditionModule.mjs.map +1 -1
- package/dist/classes/modules/commands/ContextMenuCommandModule.d.mts +1 -1
- package/dist/classes/modules/commands/ContextMenuCommandModule.mjs +5 -5
- package/dist/classes/modules/commands/ContextMenuCommandModule.mjs.map +1 -1
- package/dist/classes/modules/commands/MessageCommandModule.d.mts +1 -1
- package/dist/classes/modules/commands/MessageCommandModule.mjs +5 -5
- package/dist/classes/modules/commands/MessageCommandModule.mjs.map +1 -1
- package/dist/classes/modules/commands/SlashCommandModule.d.mts +1 -1
- package/dist/classes/modules/commands/SlashCommandModule.mjs +5 -5
- package/dist/classes/modules/commands/SlashCommandModule.mjs.map +1 -1
- package/dist/classes/modules/events/EventModule.d.mts +3 -4
- package/dist/classes/modules/events/EventModule.mjs +3 -4
- package/dist/classes/modules/events/EventModule.mjs.map +1 -1
- package/dist/classes/templates/ModuleTemplateBuilder.d.mts +1 -1
- package/dist/classes/templates/ModuleTemplateBuilder.mjs +3 -3
- package/dist/classes/templates/ModuleTemplateBuilder.mjs.map +1 -1
- package/dist/classes/templates/TemplateBuilder.mjs +29 -24
- package/dist/classes/templates/TemplateBuilder.mjs.map +1 -1
- package/dist/classes/validation/BaseModuleValidator.d.mts +11 -11
- package/dist/classes/validation/CommandModuleValidator.d.mts +18 -18
- package/dist/classes/validation/EventModuleValidator.d.mts +28 -12
- package/dist/classes/validation/PostconditionModule.d.mts +9 -9
- package/dist/classes/validation/PreconditionModule.d.mts +7 -7
- package/dist/helpers/constants.d.mts +1 -2
- package/dist/helpers/constants.mjs +8 -8
- package/dist/helpers/constants.mjs.map +1 -1
- package/dist/helpers/types.d.mts +3 -1
- package/dist/index.d.mts +4 -5
- package/dist/index.mjs +3 -4
- package/dist/index.mjs.map +1 -1
- package/dist/package.mjs +18 -15
- package/dist/package.mjs.map +1 -1
- package/package.json +17 -14
- package/LICENSE +0 -155
|
@@ -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 { colors, Format, isDebugging, recursiveDefaults } from '@reciple/utils';\nimport { logger, Logger, LogLevel } from 'prtyprnt';\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';\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('--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.js');\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":";;;;;;;;;;;;AAYA,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,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,MAAM,6BAA6B,KAAK,QAAQ,iBAAiB;AAG7E,MAAI,EADY,MAAM,KAAK,KAAK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Aa;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"}
|
|
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,CACvE,OAAO,eAAe,qBAAqB,aAAa,CAAA,CACxD,OAAO,cAAc,sBAAqB,CAC1C,OAAO,gBAAgB,8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helpers/types.mjs";
|
|
|
3
3
|
import { ModuleLoader } from "../client/ModuleLoader.mjs";
|
|
4
4
|
import { ModuleManager } from "../managers/ModuleManager.mjs";
|
|
5
5
|
import { EventListeners } from "../client/EventListeners.mjs";
|
|
6
|
-
import { Logger } from "
|
|
6
|
+
import { Logger } from "@prtty/print";
|
|
7
7
|
import { Client, Config } from "@reciple/core";
|
|
8
8
|
import { Options } from "unrun";
|
|
9
|
+
import { ShardingManagerOptions } from "discord.js";
|
|
9
10
|
import { UserConfig } from "tsdown";
|
|
10
11
|
|
|
11
12
|
//#region src/classes/cli/ConfigReader.d.ts
|
|
@@ -28,53 +29,47 @@ declare class ConfigReader {
|
|
|
28
29
|
private _client;
|
|
29
30
|
private _config;
|
|
30
31
|
private _build;
|
|
32
|
+
private _sharding;
|
|
31
33
|
get client(): Client<boolean>;
|
|
32
34
|
get config(): Config;
|
|
33
35
|
get build(): UserConfig;
|
|
36
|
+
get sharding(): ShardingManagerOptions | null;
|
|
34
37
|
constructor(filepath: string);
|
|
35
|
-
read(options?: Omit<
|
|
36
|
-
create(options
|
|
37
|
-
exists(): Promise<boolean>;
|
|
38
|
+
read(options?: Omit<Options, 'path'>): Promise<ConfigReader>;
|
|
39
|
+
create(options: Omit<ConfigReader.CreateOptions, 'path'>): Promise<ConfigReader>;
|
|
40
|
+
static exists(file: string): Promise<boolean>;
|
|
38
41
|
static create(options: ConfigReader.CreateOptions): Promise<ConfigReader>;
|
|
39
|
-
static
|
|
40
|
-
static findConfig(directory: string, type?: 'ts' | 'js'): Promise<string | null>;
|
|
41
|
-
static getDefaultContent(type?: 'ts' | 'js'): Promise<string>;
|
|
42
|
+
static find(options?: ConfigReader.FindOptions): Promise<string | null>;
|
|
42
43
|
}
|
|
43
44
|
declare namespace ConfigReader {
|
|
44
|
-
function getProjectLang(dir: string): Promise<'ts' | 'js'>;
|
|
45
|
-
interface Structure {
|
|
46
|
-
client: Client;
|
|
47
|
-
config: Config;
|
|
48
|
-
}
|
|
49
|
-
interface ReadOptions extends Options {
|
|
50
|
-
createIfNotExists?: boolean;
|
|
51
|
-
createOptions?: Omit<CreateOptions, 'path'>;
|
|
52
|
-
}
|
|
53
45
|
interface CreateOptions {
|
|
54
|
-
|
|
46
|
+
path: string;
|
|
55
47
|
overwrite?: boolean;
|
|
56
|
-
|
|
57
|
-
type
|
|
58
|
-
readOptions?: Omit<
|
|
48
|
+
throwIfExists?: boolean;
|
|
49
|
+
type: LangType;
|
|
50
|
+
readOptions?: Omit<Options, 'path'> | false;
|
|
59
51
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
52
|
+
interface FindOptions {
|
|
53
|
+
cwd?: string;
|
|
54
|
+
lang?: LangType;
|
|
55
|
+
directories?: string[];
|
|
56
|
+
}
|
|
57
|
+
function getProjectLang(cwd: string): Promise<LangType>;
|
|
58
|
+
type LangType = 'ts' | 'js';
|
|
59
|
+
const defaultConfigPath: {
|
|
65
60
|
ts: string;
|
|
66
61
|
js: string;
|
|
67
62
|
};
|
|
68
|
-
|
|
63
|
+
function getDefaultContent(type: LangType): Promise<string>;
|
|
64
|
+
const configFilenames: string[];
|
|
65
|
+
function createConfigFilename(type: LangType, esm?: boolean): string;
|
|
69
66
|
function normalizeTsdownConfig({
|
|
70
67
|
type,
|
|
71
68
|
overrides
|
|
72
69
|
}?: {
|
|
73
|
-
type?:
|
|
70
|
+
type?: LangType;
|
|
74
71
|
overrides?: BuildConfig;
|
|
75
72
|
}): UserConfig;
|
|
76
|
-
function createConfigFilename(type: 'ts' | 'js', esm?: boolean): string;
|
|
77
|
-
function getLangTypeFromFilename(filename: string): 'ts' | 'js' | null;
|
|
78
73
|
}
|
|
79
74
|
//#endregion
|
|
80
75
|
export { ConfigReader };
|
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { CLI } from "./CLI.mjs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { colors } from "@reciple/utils";
|
|
4
3
|
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import { colors } from "@prtty/prtty";
|
|
5
5
|
import { Client, RecipleError } from "@reciple/core";
|
|
6
|
-
import { unrun } from "unrun";
|
|
7
6
|
import { resolveTSConfig } from "pkg-types";
|
|
7
|
+
import { unrun } from "unrun";
|
|
8
8
|
|
|
9
9
|
//#region src/classes/cli/ConfigReader.ts
|
|
10
10
|
var ConfigReader = class ConfigReader {
|
|
11
11
|
_client = null;
|
|
12
12
|
_config = null;
|
|
13
13
|
_build = null;
|
|
14
|
+
_sharding = null;
|
|
14
15
|
get client() {
|
|
15
16
|
if (!this._client) throw new RecipleError("client is not yet loaded from config.");
|
|
16
17
|
return this._client;
|
|
@@ -21,14 +22,13 @@ var ConfigReader = class ConfigReader {
|
|
|
21
22
|
get build() {
|
|
22
23
|
return ConfigReader.normalizeTsdownConfig({ overrides: this._build ?? {} });
|
|
23
24
|
}
|
|
25
|
+
get sharding() {
|
|
26
|
+
return this._sharding;
|
|
27
|
+
}
|
|
24
28
|
constructor(filepath) {
|
|
25
29
|
this.filepath = filepath;
|
|
26
30
|
}
|
|
27
31
|
async read(options) {
|
|
28
|
-
if (!await ConfigReader.hasFile(this.filepath) && options?.createIfNotExists !== false) return ConfigReader.create({
|
|
29
|
-
filepath: this.filepath,
|
|
30
|
-
readOptions: options
|
|
31
|
-
});
|
|
32
32
|
const { module } = await unrun({
|
|
33
33
|
...options,
|
|
34
34
|
path: this.filepath
|
|
@@ -37,71 +37,66 @@ var ConfigReader = class ConfigReader {
|
|
|
37
37
|
this._client = module.client;
|
|
38
38
|
this._config = module.config;
|
|
39
39
|
this._build = module.build;
|
|
40
|
+
this._sharding = module.sharding ?? null;
|
|
40
41
|
return this;
|
|
41
42
|
}
|
|
42
43
|
async create(options) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
async exists() {
|
|
49
|
-
return await ConfigReader.hasFile(this.filepath);
|
|
50
|
-
}
|
|
51
|
-
static async create(options) {
|
|
52
|
-
const type = options.type ?? ConfigReader.getLangTypeFromFilename(options.filepath) ?? "js";
|
|
53
|
-
if (await ConfigReader.hasFile(options.filepath) && !options.overwrite) {
|
|
54
|
-
if (options.throwOnConflict !== false) throw new RecipleError(`config file already exists at ${colors.green(options.filepath)}`);
|
|
55
|
-
const reader = new ConfigReader(options.filepath);
|
|
56
|
-
await reader.read(options.readOptions);
|
|
57
|
-
return reader;
|
|
44
|
+
const exists = await ConfigReader.exists(this.filepath);
|
|
45
|
+
if (exists && options.throwIfExists === true) throw new RecipleError(`Config file already exists at ${colors.green(path.relative(process.cwd(), this.filepath))}.`);
|
|
46
|
+
if (!exists || exists && options.overwrite !== false) {
|
|
47
|
+
await mkdir(path.dirname(this.filepath), { recursive: true });
|
|
48
|
+
await writeFile(this.filepath, await ConfigReader.getDefaultContent(options.type));
|
|
58
49
|
}
|
|
59
|
-
|
|
60
|
-
await writeFile(options.filepath, await this.getDefaultContent(type));
|
|
61
|
-
return new ConfigReader(options.filepath);
|
|
50
|
+
return options.readOptions !== false ? this.read(options.readOptions) : this;
|
|
62
51
|
}
|
|
63
|
-
static async
|
|
64
|
-
return stat(
|
|
52
|
+
static async exists(file) {
|
|
53
|
+
return await stat(file).then((s) => s.isFile()).catch(() => false);
|
|
65
54
|
}
|
|
66
|
-
static async
|
|
67
|
-
|
|
68
|
-
const files = (await readdir(directory)).find((f) => validFiles.includes(f));
|
|
69
|
-
return files ? path.join(directory, files) : null;
|
|
55
|
+
static async create(options) {
|
|
56
|
+
return new ConfigReader(options.path).create(options);
|
|
70
57
|
}
|
|
71
|
-
static async
|
|
72
|
-
const
|
|
73
|
-
|
|
58
|
+
static async find(options) {
|
|
59
|
+
const filenames = ConfigReader.configFilenames.filter((f) => !options?.lang || f.endsWith(options.lang));
|
|
60
|
+
const cwd = options?.cwd ?? process.cwd();
|
|
61
|
+
const directories = [cwd];
|
|
62
|
+
directories.push(...options?.directories ?? [path.join(cwd, ".config")]);
|
|
63
|
+
for (const directory of directories) {
|
|
64
|
+
if (!(await stat(directory).catch(() => void 0))?.isDirectory()) continue;
|
|
65
|
+
const file = (await readdir(directory)).find((f) => filenames.includes(f));
|
|
66
|
+
if (file) return path.join(directory, file);
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
74
69
|
}
|
|
75
70
|
};
|
|
76
71
|
(function(_ConfigReader) {
|
|
77
|
-
async function getProjectLang(
|
|
78
|
-
const hasTsConfig = !!await resolveTSConfig(
|
|
79
|
-
const configLangIsTypescript =
|
|
72
|
+
async function getProjectLang(cwd) {
|
|
73
|
+
const hasTsConfig = !!await resolveTSConfig(cwd, { try: true });
|
|
74
|
+
const configLangIsTypescript = !!await ConfigReader.find({
|
|
75
|
+
cwd,
|
|
76
|
+
lang: "ts"
|
|
77
|
+
});
|
|
80
78
|
return hasTsConfig || configLangIsTypescript ? "ts" : "js";
|
|
81
79
|
}
|
|
82
80
|
_ConfigReader.getProjectLang = getProjectLang;
|
|
83
|
-
|
|
84
|
-
ts: [
|
|
85
|
-
"ts",
|
|
86
|
-
"mts",
|
|
87
|
-
"tsx"
|
|
88
|
-
],
|
|
89
|
-
js: [
|
|
90
|
-
"js",
|
|
91
|
-
"mjs",
|
|
92
|
-
"jsx"
|
|
93
|
-
]
|
|
94
|
-
};
|
|
95
|
-
_ConfigReader.defaultConfigFilePaths = {
|
|
81
|
+
_ConfigReader.defaultConfigPath = {
|
|
96
82
|
ts: path.join(CLI.root, "assets/config", `reciple.config.ts`),
|
|
97
83
|
js: path.join(CLI.root, "assets/config", `reciple.config.js`)
|
|
98
84
|
};
|
|
99
|
-
|
|
85
|
+
async function getDefaultContent(type) {
|
|
86
|
+
const filepath = ConfigReader.defaultConfigPath[type];
|
|
87
|
+
return await readFile(filepath, "utf-8");
|
|
88
|
+
}
|
|
89
|
+
_ConfigReader.getDefaultContent = getDefaultContent;
|
|
90
|
+
_ConfigReader.configFilenames = [
|
|
100
91
|
"reciple.config.ts",
|
|
101
92
|
"reciple.config.mts",
|
|
102
93
|
"reciple.config.js",
|
|
103
94
|
"reciple.config.mjs"
|
|
104
95
|
];
|
|
96
|
+
function createConfigFilename(type, esm = false) {
|
|
97
|
+
return `reciple.config.${esm ? "m" : ""}${type}`;
|
|
98
|
+
}
|
|
99
|
+
_ConfigReader.createConfigFilename = createConfigFilename;
|
|
105
100
|
function normalizeTsdownConfig({ type, overrides } = {}) {
|
|
106
101
|
return {
|
|
107
102
|
entry: [`./src/**/*.{ts,tsx,js,jsx}`],
|
|
@@ -121,17 +116,6 @@ var ConfigReader = class ConfigReader {
|
|
|
121
116
|
};
|
|
122
117
|
}
|
|
123
118
|
_ConfigReader.normalizeTsdownConfig = normalizeTsdownConfig;
|
|
124
|
-
function createConfigFilename(type, esm = false) {
|
|
125
|
-
return `reciple.config.${type === "ts" ? esm ? "mts" : "ts" : esm ? "mjs" : "js"}`;
|
|
126
|
-
}
|
|
127
|
-
_ConfigReader.createConfigFilename = createConfigFilename;
|
|
128
|
-
function getLangTypeFromFilename(filename) {
|
|
129
|
-
const extention = path.extname(filename).slice(1);
|
|
130
|
-
if (FileTypes.ts.includes(extention)) return "ts";
|
|
131
|
-
if (FileTypes.js.includes(extention)) return "js";
|
|
132
|
-
return null;
|
|
133
|
-
}
|
|
134
|
-
_ConfigReader.getLangTypeFromFilename = getLangTypeFromFilename;
|
|
135
119
|
})(ConfigReader || (ConfigReader = {}));
|
|
136
120
|
|
|
137
121
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConfigReader.mjs","names":[
|
|
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';\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 path: this.filepath\n });\n\n if (!module || !module.client || !(module.client instanceof 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 cwd = options?.cwd ?? process.cwd();\n const directories = [cwd];\n\n directories.push(...(options?.directories ?? [path.join(cwd, '.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 cwd?: string;\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({ cwd, lang: 'ts' }));\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":";;;;;;;;;AA+BA,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,YAAY,AAAgB,UAAkB;EAAlB;;CAE5B,MAAa,KAAK,SAA6D;EAC3E,MAAM,EAAE,WAAW,MAAM,MAAc;GACnC,GAAG;GACH,MAAM,KAAK;GACd,CAAC;AAEF,MAAI,CAAC,UAAU,CAAC,OAAO,UAAU,EAAE,OAAO,kBAAkB,QACxD,OAAM,IAAI,aAAa,yCAAyC,OAAO,KAAK,SAAS,CAAC,QAAQ,OAAO,MAAM,oBAAkB,CAAC,GAAG;AAGrI,OAAK,UAAU,OAAO;AACtB,OAAK,UAAU,OAAO;AACtB,OAAK,SAAS,OAAO;AACrB,OAAK,YAAY,OAAO,YAAY;AAEpC,SAAO;;CAGX,MAAa,OAAO,SAA0E;EAC1F,MAAM,SAAS,MAAM,aAAa,OAAO,KAAK,SAAS;AAEvD,MAAI,UAAU,QAAQ,kBAAkB,KACpC,O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AM,aAAa,KAAK;GAAE;GAAK,MAAM;GAAM,CAAC;AAE9E,SAAO,eAAe,yBAAyB,OAAO;;;mCAKzB;EAC7B,IAAI,KAAK,KAAK,IAAI,MAAM,iBAAiB,oBAAoB;EAC7D,IAAI,KAAK,KAAK,IAAI,MAAM,iBAAiB,oBAAoB;EAChE;CAEM,eAAe,kBAAkB,MAAiC;EACrE,MAAM,WAAW,aAAa,kBAAkB;AAEhD,SADgB,MAAM,SAAS,UAAU,QAAQ;;;iCAItB;EAC3B;EACA;EACA;EACA;EACH;CAEM,SAAS,qBAAqB,MAAgB,MAAe,OAAe;AAC/E,SAAO,kBAAkB,MAAM,MAAM,KAAK;;;CAGvC,SAAS,sBAAsB,EAAE,MAAM,cAA6D,EAAE,EAAgB;AACzH,SAAO;GACH,OAAO,CAAC,6BAA6B;GACrC,QAAQ;GACR,UAAU,KAAK,QAAQ,KAAK;GAC5B,UAAU,EAAE;GACZ,YAAY,EAAE;GACd,WAAW;GACX,WAAW;GACX,OAAO;GACP,GAAG;GACH,OAAO;GACP,UAAU;GACV,QAAQ;GACR,UAAU;GACV,uBAAuB;GAC1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RuntimeEnvironment.mjs","names":[],"sources":["../../../src/classes/cli/RuntimeEnvironment.ts"],"sourcesContent":["import { colors } from '@
|
|
1
|
+
{"version":3,"file":"RuntimeEnvironment.mjs","names":[],"sources":["../../../src/classes/cli/RuntimeEnvironment.ts"],"sourcesContent":["import { colors } from '@prtty/prtty';\nimport type { Client } from '@reciple/core';\nimport { setTimeout } from 'node:timers/promises';\n\nexport class RuntimeEnvironment {}\n\nexport namespace RuntimeEnvironment {\n export let stopping = false;\n\n export type Type = 'node'|'deno'|'bun';\n\n export function get(): Type|null {\n if ('isBun' in process && process.isBun) return 'bun';\n if ('deno' in process.versions && process.versions.deno) return 'deno';\n if (process.versions.node) return 'node';\n\n return null;\n }\n\n export async function sleep(time: number): Promise<void> {\n return setTimeout(time);\n }\n\n export async function handleExitSignal(client: Client, signal: NodeJS.Signals) {\n if (stopping) return;\n\n stopping = true;\n\n client.logger?.warn(`Received exit signal: ${signal}`);\n\n await client.destroy();\n client.eventListeners.unregisterAll();\n\n const signalString = signal === 'SIGINT' ? 'keyboard interrupt' : signal === 'SIGTERM' ? 'terminate' : String(signal);\n\n await sleep(10);\n\n client.logger?.warn(`Process exited: ${colors.yellow(signalString)}`);\n client.logger?.closeFileWriteStream();\n process.exit(0);\n }\n}\n"],"mappings":";;;;AAIA,IAAa,qBAAb,MAAgC;;CAGrB,IAAI,0CAAW;CAIf,SAAS,MAAiB;AAC7B,MAAI,WAAW,WAAW,QAAQ,MAAO,QAAO;AAChD,MAAI,UAAU,QAAQ,YAAY,QAAQ,SAAS,KAAM,QAAO;AAChE,MAAI,QAAQ,SAAS,KAAM,QAAO;AAElC,SAAO;;;CAGJ,eAAe,MAAM,MAA6B;AACrD,SAAO,WAAW,KAAK;;;CAGpB,eAAe,iBAAiB,QAAgB,QAAwB;AAC3E,MAAI,SAAU;AAEd,aAAW;AAEX,SAAO,QAAQ,KAAK,yBAAyB,SAAS;AAEtD,QAAM,OAAO,SAAS;AACtB,SAAO,eAAe,eAAe;EAErC,MAAM,eAAe,WAAW,WAAW,uBAAuB,WAAW,YAAY,cAAc,OAAO,OAAO;AAErH,QAAM,MAAM,GAAG;AAEf,SAAO,QAAQ,KAAK,mBAAmB,OAAO,OAAO,aAAa,GAAG;AACrE,SAAO,QAAQ,sBAAsB;AACrC,UAAQ,KAAK,EAAE"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { BaseModule } from "../modules/BaseModule.mjs";
|
|
2
|
-
import { Format
|
|
2
|
+
import { Format } from "@reciple/utils";
|
|
3
|
+
import { colors } from "@prtty/prtty";
|
|
3
4
|
import { CommandType } from "@reciple/core";
|
|
4
5
|
|
|
5
6
|
//#region src/classes/client/EventListeners.ts
|
|
@@ -92,7 +93,7 @@ var EventListeners = class EventListeners {
|
|
|
92
93
|
event,
|
|
93
94
|
onEvent
|
|
94
95
|
});
|
|
95
|
-
const events = [defineCommandsEvent("applicationCommandsRegister", (commands, guildId) => client.logger.log(colors.green(`📩 Registered ${colors.cyan(commands.size)} application ${Format.plural(commands.size, "command")}${guildId ? ` to guild ${colors.magenta(guildId)}` : colors.magenta(" globally")}.`))), defineCommandsEvent("commandExecute", (data) => client.logger.debug(`Executed ${CommandType[data.command.type].toLowerCase()} command ${colors.cyan(`"${data.command.data.name}"`)} ${colors.magenta(`(${data.command.id})`)}`))];
|
|
96
|
+
const events = [defineCommandsEvent("applicationCommandsRegister", (commands, guildId) => client.logger.log(colors.green(`📩 Registered ${colors.cyan(commands.size.toLocaleString())} application ${Format.plural(commands.size, "command")}${guildId ? ` to guild ${colors.magenta(guildId)}` : colors.magenta(" globally")}.`))), defineCommandsEvent("commandExecute", (data) => client.logger.debug(`Executed ${CommandType[data.command.type].toLowerCase()} command ${colors.cyan(`"${data.command.data.name}"`)} ${colors.magenta(`(${data.command.id})`)}`))];
|
|
96
97
|
for (const event of events) client.eventListeners.register(event);
|
|
97
98
|
}
|
|
98
99
|
_EventListeners.registerCommandsEventListeners = registerCommandsEventListeners;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EventListeners.mjs","names":[
|
|
1
|
+
{"version":3,"file":"EventListeners.mjs","names":[],"sources":["../../../src/classes/client/EventListeners.ts"],"sourcesContent":["import { CommandType, type Client, type CommandManager } from '@reciple/core';\nimport type { EventEmitter } from 'node:events';\nimport type { ModuleManager } from '../managers/ModuleManager.js';\nimport { BaseModule } from '../modules/BaseModule.js';\nimport { Format } from '@reciple/utils';\nimport type { ModuleLoader } from './ModuleLoader.js';\nimport { colors } from '@prtty/prtty';\n\nexport class EventListeners {\n public registeredEvents: EventListeners.RegisteredEvent[] = [];\n\n public register(event: EventListeners.RegisteredEvent): this {\n event.onEvent = event.onEvent.bind(event);\n\n if (event.once) {\n event.emitter.once(event.event, event.onEvent);\n } else {\n event.emitter.on(event.event, event.onEvent);\n }\n\n this.registeredEvents.push(event);\n return this;\n }\n\n public unregister(event: EventListeners.RegisteredEvent): this {\n event.emitter.removeListener(event.event, event.onEvent);\n this.registeredEvents = this.registeredEvents.filter(e => e !== event);\n return this;\n }\n\n public unregisterAll(): this {\n this.registeredEvents.forEach(event => this.unregister(event));\n this.registeredEvents = [];\n return this;\n }\n\n public registerProcessExitEvents(listener: (signal: NodeJS.Signals) => any): this {\n for (const event of EventListeners.processExitEvents) {\n this.register({ emitter: process, event, onEvent: listener });\n }\n\n return this;\n }\n\n public unregisterProcessExitEvents(listener: (signal: NodeJS.Signals) => any): this {\n for (const event of EventListeners.processExitEvents) {\n this.unregister({ emitter: process, event, onEvent: listener });\n }\n\n return this;\n }\n}\n\nexport namespace EventListeners {\n export const processExitEvents = [\n 'SIGHUP',\n 'SIGINT',\n 'SIGQUIT',\n 'SIGABRT',\n 'SIGALRM',\n 'SIGTERM',\n 'SIGBREAK',\n 'SIGUSR2',\n ];\n\n export interface RegisteredEvent {\n event: string|symbol;\n emitter: EventEmitter;\n once?: boolean;\n onEvent: (...args: any) => any;\n }\n\n export function registerLoggerEventListeners(client: Client) {\n const defineModuleManagerEvent = <E extends keyof ModuleManager.Events>(event: E, onEvent: (...args: ModuleManager.Events[E]) => any): RegisteredEvent => ({ emitter: client.modules, event, onEvent });\n const defineModuleLoaderEvent = <E extends keyof ModuleLoader.Events>(event: E, onEvent: (...args: ModuleLoader.Events[E]) => any): RegisteredEvent => ({ emitter: client.moduleLoader, event, onEvent });\n const defineClientEvent = <E extends keyof Client.Events>(event: E, onEvent: (...args: Client.Events[E]) => any): RegisteredEvent => ({ emitter: client, event, onEvent });\n\n const events: RegisteredEvent[] = [\n defineModuleManagerEvent('modulePreEnable', (module) => client.logger.log(`Enabling module ${colors.cyan(`\"${BaseModule.getFilepath(module) || module.id}\"`)}`)),\n defineModuleManagerEvent('moduleEnable', (module) => client.logger.log(`Enabled module ${colors.cyan(`\"${BaseModule.getFilepath(module) || module.id}\"`)}`)),\n defineModuleManagerEvent('modulePreReady', (module) => client.logger.log(`Preparing module ${colors.cyan(`\"${BaseModule.getFilepath(module) || module.id}\"`)}`)),\n defineModuleManagerEvent('moduleReady', (module) => client.logger.log(`Ready module ${colors.cyan(`\"${BaseModule.getFilepath(module) || module.id}\"`)}`)),\n defineModuleManagerEvent('modulePreDisable', (module) => client.logger.log(`Disabling module ${colors.cyan(`\"${BaseModule.getFilepath(module) || module.id}\"`)}`)),\n defineModuleManagerEvent('moduleDisable', (module) => client.logger.log(`Disabled module ${colors.cyan(`\"${BaseModule.getFilepath(module) || module.id}\"`)}`)),\n defineModuleManagerEvent('moduleEnableError', (module, error) => client.logger.error(`Failed to enable module ${colors.cyan(`\"${BaseModule.getFilepath(module) || module.id}\"`)}:`, error)),\n defineModuleManagerEvent('moduleReadyError', (module, error) => client.logger.error(`Failed to ready module ${colors.cyan(`\"${BaseModule.getFilepath(module) || module.id}\"`)}:`, error)),\n defineModuleManagerEvent('moduleDisableError', (module, error) => client.logger.error(`Failed to disable module ${colors.cyan(`\"${BaseModule.getFilepath(module) || module.id}\"`)}:`, error)),\n defineModuleLoaderEvent('modulesResolving', () => client.logger.log(colors.green('🔍 Resolving modules...'))),\n defineModuleLoaderEvent('modulesResolved', (modules) => client.logger.log(colors.green(`✅ Resolved ${modules.length} ${Format.plural(modules.length, 'module')}.`))),\n defineModuleLoaderEvent('moduleResolving', (filepath) => client.logger.debug(`Resolving module ${colors.cyan(`\"${filepath}\"`)}`)),\n defineModuleLoaderEvent('moduleResolved', (module) => client.logger.debug(`Resolved module ${colors.cyan(`\"${BaseModule.getFilepath(module) || module.id}\"`)}`)),\n defineModuleLoaderEvent('moduleResolveError', (error) => client.logger.error(`Failed to resolve module:`, error)),\n defineClientEvent('debug', (message) => client.logger.debug(message)),\n ];\n\n for (const event of events) {\n client.eventListeners.register(event);\n }\n }\n\n export function registerCommandsEventListeners(client: Client) {\n const defineCommandsEvent = <E extends keyof CommandManager.Events>(event: E, onEvent: (...args: CommandManager.Events[E]) => any): RegisteredEvent => ({ emitter: client.commands!, event, onEvent });\n\n const events: RegisteredEvent[] = [\n defineCommandsEvent('applicationCommandsRegister', (commands, guildId) => client.logger.log(colors.green(`📩 Registered ${colors.cyan(commands.size.toLocaleString())} application ${Format.plural(commands.size, 'command')}${guildId ? ` to guild ${colors.magenta(guildId)}` : colors.magenta(' globally')}.`))),\n defineCommandsEvent('commandExecute', (data) => client.logger.debug(`Executed ${CommandType[data.command.type].toLowerCase()} command ${colors.cyan(`\"${data.command.data.name}\"`)} ${colors.magenta(`(${data.command.id})`)}`)),\n ];\n\n for (const event of events) {\n client.eventListeners.register(event);\n }\n }\n}\n"],"mappings":";;;;;;AAQA,IAAa,iBAAb,MAAa,eAAe;CACxB,AAAO,mBAAqD,EAAE;CAE9D,AAAO,SAAS,OAA6C;AACzD,QAAM,UAAU,MAAM,QAAQ,KAAK,MAAM;AAEzC,MAAI,MAAM,KACN,OAAM,QAAQ,KAAK,MAAM,OAAO,MAAM,QAAQ;MAE9C,OAAM,QAAQ,GAAG,MAAM,OAAO,MAAM,QAAQ;AAGhD,OAAK,iBAAiB,KAAK,MAAM;AACjC,SAAO;;CAGX,AAAO,WAAW,OAA6C;AAC3D,QAAM,QAAQ,eAAe,MAAM,OAAO,MAAM,QAAQ;AACxD,OAAK,mBAAmB,KAAK,iBAAiB,QAAO,MAAK,MAAM,MAAM;AACtE,SAAO;;CAGX,AAAO,gBAAsB;AACzB,OAAK,iBAAiB,SAAQ,UAAS,KAAK,WAAW,MAAM,CAAC;AAC9D,OAAK,mBAAmB,EAAE;AAC1B,SAAO;;CAGX,AAAO,0BAA0B,UAAiD;AAC9E,OAAK,MAAM,SAAS,eAAe,kBAC/B,MAAK,SAAS;GAAE,SAAS;GAAS;GAAO,SAAS;GAAU,CAAC;AAGjE,SAAO;;CAGX,AAAO,4BAA4B,UAAiD;AAChF,OAAK,MAAM,SAAS,eAAe,kBAC/B,MAAK,WAAW;GA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AAM,UAAU,GAAG,UAAU,aAAa,OAAO,QAAQ,QAAQ,KAAK,OAAO,QAAQ,YAAY,CAAC,GAAG,CAAC,CAAC,EACnT,oBAAoB,mBAAmB,SAAS,OAAO,OAAO,MAAM,YAAY,YAAY,KAAK,QAAQ,MAAM,aAAa,CAAC,WAAW,OAAO,KAAK,IAAI,KAAK,QAAQ,KAAK,KAAK,GAAG,CAAC,GAAG,OAAO,QAAQ,IAAI,KAAK,QAAQ,GAAG,GAAG,GAAG,CAAC,CACnO;AAED,OAAK,MAAM,SAAS,OAChB,QAAO,eAAe,SAAS,MAAM"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AnyModule } from "../../helpers/types.mjs";
|
|
2
|
-
import { Logger } from "
|
|
2
|
+
import { Logger } from "@prtty/print";
|
|
3
3
|
import { Client, RecipleError } from "@reciple/core";
|
|
4
4
|
import { Awaitable } from "discord.js";
|
|
5
5
|
import * as globby0 from "globby";
|
|
@@ -15,11 +15,11 @@ declare class ModuleLoader extends EventEmitter<ModuleLoader.Events> {
|
|
|
15
15
|
cwd?: string;
|
|
16
16
|
createDirectories?: boolean;
|
|
17
17
|
}): Promise<string[]>;
|
|
18
|
-
static
|
|
18
|
+
static scanForModulePaths(config?: ModuleLoader.Config & {
|
|
19
19
|
cwd?: string;
|
|
20
20
|
createDirectories?: boolean;
|
|
21
21
|
}): Promise<string[]>;
|
|
22
|
-
static
|
|
22
|
+
static resolveModuleFromPath(filepath: string, options?: {
|
|
23
23
|
cwd?: string;
|
|
24
24
|
}): Promise<AnyModule>;
|
|
25
25
|
static resolveSourceDirectories(options: ModuleLoader.ResolveSourceDirectoryOptions): Promise<string[]>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ModuleType } from "../../helpers/constants.mjs";
|
|
2
1
|
import { BaseModule } from "../modules/BaseModule.mjs";
|
|
2
|
+
import { ModuleType } from "../../helpers/constants.mjs";
|
|
3
3
|
import { BaseModuleValidator } from "../validation/BaseModuleValidator.mjs";
|
|
4
4
|
import { PostconditionModule } from "../modules/PostconditionModule.mjs";
|
|
5
5
|
import { PreconditionModule } from "../modules/PreconditionModule.mjs";
|
|
@@ -12,8 +12,9 @@ import { EventModuleValidator } from "../validation/EventModuleValidator.mjs";
|
|
|
12
12
|
import { PreconditionModuleValidator } from "../validation/PreconditionModule.mjs";
|
|
13
13
|
import { PostconditionModuleValidator } from "../validation/PostconditionModule.mjs";
|
|
14
14
|
import path from "node:path";
|
|
15
|
-
import {
|
|
15
|
+
import { recursiveDefaults } from "@reciple/utils";
|
|
16
16
|
import { mkdir, readdir, stat } from "node:fs/promises";
|
|
17
|
+
import { colors } from "@prtty/prtty";
|
|
17
18
|
import { CommandType, RecipleError } from "@reciple/core";
|
|
18
19
|
import "discord.js";
|
|
19
20
|
import micromatch from "micromatch";
|
|
@@ -29,12 +30,12 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
29
30
|
this.logger = this.client.logger.clone({ label: "ModuleLoader" });
|
|
30
31
|
}
|
|
31
32
|
async findModules(ignoreErrors = false) {
|
|
32
|
-
const modulePaths = await ModuleLoader.
|
|
33
|
+
const modulePaths = await ModuleLoader.scanForModulePaths(this.client.config?.modules);
|
|
33
34
|
const modules = [];
|
|
34
35
|
this.emit("modulesResolving", modulePaths);
|
|
35
36
|
for (const path$1 of modulePaths) try {
|
|
36
37
|
this.emit("moduleResolving", path$1);
|
|
37
|
-
const resolved = await ModuleLoader.
|
|
38
|
+
const resolved = await ModuleLoader.resolveModuleFromPath(path$1);
|
|
38
39
|
Object.assign(resolved, {
|
|
39
40
|
client: this.client,
|
|
40
41
|
__$filepath: path$1
|
|
@@ -75,7 +76,7 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
75
76
|
}
|
|
76
77
|
return directories;
|
|
77
78
|
}
|
|
78
|
-
static async
|
|
79
|
+
static async scanForModulePaths(config) {
|
|
79
80
|
const directories = await ModuleLoader.scanForDirectories(config);
|
|
80
81
|
let modules = [];
|
|
81
82
|
for (const directory of directories) {
|
|
@@ -94,11 +95,11 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
94
95
|
if (config?.sort) modules.sort(config.sort);
|
|
95
96
|
return modules;
|
|
96
97
|
}
|
|
97
|
-
static async
|
|
98
|
+
static async resolveModuleFromPath(filepath, options) {
|
|
98
99
|
if (!await stat(filepath).catch(() => void 0)) throw new RecipleError(`Module not found: ${filepath}`);
|
|
99
100
|
const data = recursiveDefaults(await import(`file://${path.resolve(options?.cwd ?? process.cwd(), filepath)}`));
|
|
100
101
|
if (BaseModule.isModule(data)) return data;
|
|
101
|
-
switch (data?.moduleType) {
|
|
102
|
+
if (data && "moduleType" in data) switch (data?.moduleType) {
|
|
102
103
|
case ModuleType.Command:
|
|
103
104
|
CommandModuleValidator.isValid(data);
|
|
104
105
|
switch (data.type) {
|
|
@@ -116,11 +117,12 @@ var ModuleLoader = class ModuleLoader extends EventEmitter {
|
|
|
116
117
|
case ModuleType.Postcondition:
|
|
117
118
|
PostconditionModuleValidator.isValid(data);
|
|
118
119
|
return PostconditionModule.from(data);
|
|
119
|
-
case ModuleType.Base:
|
|
120
120
|
default:
|
|
121
121
|
BaseModuleValidator.isValid(data);
|
|
122
122
|
return BaseModule.from(data);
|
|
123
123
|
}
|
|
124
|
+
BaseModuleValidator.isValid(data);
|
|
125
|
+
return BaseModule.from(data);
|
|
124
126
|
}
|
|
125
127
|
static async resolveSourceDirectories(options) {
|
|
126
128
|
const dir = path.isAbsolute(options.baseUrl) ? options.baseUrl : path.resolve(path.join(options.cwd ?? process.cwd(), options.baseUrl));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ModuleLoader.mjs","names":["client: Client","modules: AnyModule[]","path","scanned: string[]","directories: string[]","modules: string[]","globby: typeof import('globby')|null","globby"],"sources":["../../../src/classes/client/ModuleLoader.ts"],"sourcesContent":["import { type Awaitable } from 'discord.js';\nimport path from 'node:path';\nimport { mkdir, readdir, stat } from 'node:fs/promises';\nimport micromatch from 'micromatch';\nimport { globby, isDynamicPattern } from 'globby';\nimport { CommandType, RecipleError, type Client } from '@reciple/core';\nimport type { AnyModule, AnyModuleData } from '../../helpers/types.js';\nimport { colors, recursiveDefaults } from '@reciple/utils';\nimport { BaseModule } from '../modules/BaseModule.js';\nimport { BaseModuleValidator } from '../validation/BaseModuleValidator.js';\nimport { ModuleType } from '../../helpers/constants.js';\nimport { PostconditionModule } from '../modules/PostconditionModule.js';\nimport { PreconditionModule } from '../modules/PreconditionModule.js';\nimport { EventModule } from '../modules/events/EventModule.js';\nimport { MessageCommandModule } from '../modules/commands/MessageCommandModule.js';\nimport { SlashCommandModule } from '../modules/commands/SlashCommandModule.js';\nimport { ContextMenuCommandModule } from '../modules/commands/ContextMenuCommandModule.js';\nimport { CommandModuleValidator } from '../validation/CommandModuleValidator.js';\nimport { EventModuleValidator } from '../validation/EventModuleValidator.js';\nimport { PreconditionModuleValidator } from '../validation/PreconditionModule.js';\nimport { PostconditionModuleValidator } from '../validation/PostconditionModule.js';\nimport type { Logger } from 'prtyprnt';\nimport { EventEmitter } from 'node:events';\n\nexport class ModuleLoader extends EventEmitter<ModuleLoader.Events> {\n public readonly logger: Logger;\n\n constructor(public readonly client: Client) {\n super();\n\n this.logger = this.client.logger.clone({\n label: 'ModuleLoader'\n });\n }\n\n public async findModules(ignoreErrors: boolean = false): Promise<AnyModule[]> {\n const modulePaths = await ModuleLoader.scanForModules(this.client.config?.modules);\n const modules: AnyModule[] = [];\n\n this.emit('modulesResolving', modulePaths);\n\n for (const path of modulePaths) {\n try {\n this.emit('moduleResolving', path);\n const resolved = await ModuleLoader.resolveModulePath(path);\n\n Object.assign(resolved, { client: this.client, __$filepath: path });\n modules.push(resolved);\n\n this.emit('moduleResolved', resolved);\n } catch (error) {\n if (ignoreErrors) continue;\n\n this.emitOrThrow('moduleResolveError', new RecipleError({\n message: `Failed to load module: ${colors.cyan(path)}`,\n cause: error\n }));\n }\n }\n\n this.emit('modulesResolved', modules);\n return modules;\n }\n\n public static async scanForDirectories(config?: Pick<ModuleLoader.Config, 'directories'|'ignore'> & { cwd?: string; createDirectories?: boolean; }) {\n const cwd = config?.cwd ?? process.cwd();\n\n let scanned: string[] = [];\n let directories: string[] = [];\n\n for (const directory of config?.directories ?? []) {\n if (isDynamicPattern(directory, { cwd })) {\n const matches = await globby(directory, {\n cwd,\n ignore: config?.ignore,\n onlyDirectories: true,\n baseNameMatch: true,\n absolute: true\n });\n\n scanned.push(...matches);\n continue;\n }\n\n scanned.push(path.join(cwd, directory));\n }\n\n for (const directory of scanned) {\n const stats = await stat(directory).catch(() => undefined);\n\n if (!stats && config?.createDirectories !== false) {\n await mkdir(directory, { recursive: true });\n }\n\n directories.push(directory);\n }\n\n return directories;\n }\n\n public static async scanForModules(config?: ModuleLoader.Config & { cwd?: string; createDirectories?: boolean; }): Promise<string[]> {\n const directories = await ModuleLoader.scanForDirectories(config);\n\n let modules: string[] = [];\n\n for (const directory of directories) {\n let files = await readdir(directory);\n\n if (config?.ignore?.length) {\n files = micromatch.not(files, config.ignore, {\n cwd: directory,\n matchBase: true,\n dot: true\n });\n }\n\n files = files.map(f => path.join(directory, f));\n\n for (const file of files) {\n if (config?.filter ? !(await config?.filter(file)) : ModuleLoader.fileTypes.every(type => !file.endsWith(`.${type}`))) continue;\n modules.push(file);\n }\n }\n\n if (config?.sort) modules.sort(config.sort);\n\n return modules;\n }\n\n public static async resolveModulePath(filepath: string, options?: { cwd?: string; }): Promise<AnyModule> {\n const stats = await stat(filepath).catch(() => undefined);\n if (!stats) throw new RecipleError(`Module not found: ${filepath}`);\n\n const data = recursiveDefaults<AnyModule|AnyModuleData|undefined>(await import(`file://${path.resolve(options?.cwd ?? process.cwd(), filepath)}`));\n if (BaseModule.isModule(data)) return data;\n\n switch (data?.moduleType) {\n case ModuleType.Command:\n CommandModuleValidator.isValid(data);\n switch (data.type) {\n case CommandType.Message: return MessageCommandModule.from(data);\n case CommandType.Slash: return SlashCommandModule.from(data);\n case CommandType.ContextMenu: return ContextMenuCommandModule.from(data);\n default: throw new RecipleError(`Unknown command type from module: ${colors.cyan(filepath)}`);\n }\n case ModuleType.Event:\n EventModuleValidator.isValid(data);\n return EventModule.from(data);\n case ModuleType.Precondition:\n PreconditionModuleValidator.isValid(data);\n return PreconditionModule.from(data);\n case ModuleType.Postcondition:\n PostconditionModuleValidator.isValid(data);\n return PostconditionModule.from(data);\n case ModuleType.Base:\n default:\n BaseModuleValidator.isValid(data);\n return BaseModule.from(data);\n }\n }\n\n public static async resolveSourceDirectories(options: ModuleLoader.ResolveSourceDirectoryOptions): Promise<string[]> {\n const dir = path.isAbsolute(options.baseUrl) ? options.baseUrl : path.resolve(path.join(options.cwd ?? process.cwd(), options.baseUrl));\n\n const root = path.resolve(path.join(dir, options.rootDir));\n const out = path.resolve(path.join(dir, options.outDir));\n\n return options.directories.map(directory => path.resolve(directory).replace(out, root));\n }\n\n private emitOrThrow<K extends keyof Pick<ModuleLoader.Events, 'moduleResolveError'>>(event: K, error: RecipleError) {\n if (this.client.listenerCount(event) > 0) {\n // @ts-expect-error\n return this.emit(event, error);\n }\n\n throw error;\n }\n}\n\nexport namespace ModuleLoader {\n export let globby: typeof import('globby')|null = null;\n\n export const fileTypes = [\n 'js',\n 'mjs',\n 'jsx'\n ];\n\n export interface Config {\n directories?: string[];\n ignore?: string[];\n filter?: (filepath: string) => Awaitable<boolean>;\n sort?: (a: string, b: string) => number;\n }\n\n export interface Events {\n moduleResolveError: [error: RecipleError];\n moduleResolved: [module: AnyModule];\n moduleResolving: [filepath: string];\n modulesResolved: [modules: AnyModule[]];\n modulesResolving: [files: string[]];\n }\n\n export interface ResolveSourceDirectoryOptions {\n directories: string[];\n baseUrl: string;\n rootDir: string;\n outDir: string;\n cwd?: string;\n }\n\n export async function getGlobby(): Promise<typeof import('globby')> {\n if (globby) return globby;\n\n return globby = await import('globby');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,eAAb,MA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,QAAO,yBAAyB,KAAK,KAAK;KACxE,QAAS,OAAM,IAAI,aAAa,qCAAqC,OAAO,KAAK,SAAS,GAAG;;GAErG,KAAK,WAAW;AACZ,yBAAqB,QAAQ,KAAK;AAClC,WAAO,YAAY,KAAK,KAAK;GACjC,KAAK,WAAW;AACZ,gCAA4B,QAAQ,KAAK;AACzC,WAAO,mBAAmB,KAAK,KAAK;GACxC,KAAK,WAAW;AACZ,iCAA6B,QAAQ,KAAK;AAC1C,WAAO,oBAAoB,KAAK,KAAK;GACzC,KAAK,WAAW;GAChB;AACI,wBAAoB,QAAQ,KAAK;AACjC,WAAO,WAAW,KAAK,KAAK;;;CAIxC,aAAoB,yBAAyB,SAAwE;EACjH,MAAM,MAAM,KAAK,WAAW,QAAQ,QAAQ,GAAG,QAAQ,UAAU,KAAK,QAAQ,KAAK,KAAK,QAAQ,OAAO,QAAQ,KAAK,EAAE,QAAQ,QAAQ,CAAC;EAEvI,MAAM,OAAO,KAAK,QAAQ,KAAK,KAAK,KAAK,QAAQ,QAAQ,CAAC;EAC1D,MAAM,MAAM,KAAK,QAAQ,KAAK,KAAK,KAAK,QAAQ,OAAO,CAAC;AAExD,SAAO,QAAQ,YAAY,KAAI,cAAa,KAAK,QAAQ,UAAU,CAAC,QAAQ,KAAK,KAAK,CAAC;;CAG3F,AAAQ,YAA6E,OAAU,OAAqB;AAChH,MAAI,KAAK,OAAO,cAAc,MAAM,GAAG,EAEnC,QAAO,KAAK,KAAK,OAAO,MAAM;AAGlC,QAAM;;;;CAKH,IAAIC,kCAAuC;2BAEzB;EACrB;EACA;EACA;EACH;CAyBM,eAAe,YAA8C;AAChE,MAAIC,SAAQ,QAAOA;AAEnB,SAAO,WAAS,MAAM,OAAO"}
|
|
1
|
+
{"version":3,"file":"ModuleLoader.mjs","names":["path","globby"],"sources":["../../../src/classes/client/ModuleLoader.ts"],"sourcesContent":["import { type Awaitable } from 'discord.js';\nimport path from 'node:path';\nimport { mkdir, readdir, stat } from 'node:fs/promises';\nimport micromatch from 'micromatch';\nimport { globby, isDynamicPattern } from 'globby';\nimport { CommandType, RecipleError, type Client } from '@reciple/core';\nimport type { AnyModule, AnyModuleData } from '../../helpers/types.js';\nimport { recursiveDefaults } from '@reciple/utils';\nimport { BaseModule } from '../modules/BaseModule.js';\nimport { BaseModuleValidator } from '../validation/BaseModuleValidator.js';\nimport { ModuleType } from '../../helpers/constants.js';\nimport { PostconditionModule } from '../modules/PostconditionModule.js';\nimport { PreconditionModule } from '../modules/PreconditionModule.js';\nimport { EventModule } from '../modules/events/EventModule.js';\nimport { MessageCommandModule } from '../modules/commands/MessageCommandModule.js';\nimport { SlashCommandModule } from '../modules/commands/SlashCommandModule.js';\nimport { ContextMenuCommandModule } from '../modules/commands/ContextMenuCommandModule.js';\nimport { CommandModuleValidator } from '../validation/CommandModuleValidator.js';\nimport { EventModuleValidator } from '../validation/EventModuleValidator.js';\nimport { PreconditionModuleValidator } from '../validation/PreconditionModule.js';\nimport { PostconditionModuleValidator } from '../validation/PostconditionModule.js';\nimport type { Logger } from '@prtty/print';\nimport { EventEmitter } from 'node:events';\nimport { colors } from '@prtty/prtty';\n\nexport class ModuleLoader extends EventEmitter<ModuleLoader.Events> {\n public readonly logger: Logger;\n\n constructor(public readonly client: Client) {\n super();\n\n this.logger = this.client.logger.clone({\n label: 'ModuleLoader'\n });\n }\n\n public async findModules(ignoreErrors: boolean = false): Promise<AnyModule[]> {\n const modulePaths = await ModuleLoader.scanForModulePaths(this.client.config?.modules);\n const modules: AnyModule[] = [];\n\n this.emit('modulesResolving', modulePaths);\n\n for (const path of modulePaths) {\n try {\n this.emit('moduleResolving', path);\n const resolved = await ModuleLoader.resolveModuleFromPath(path);\n\n Object.assign(resolved, { client: this.client, __$filepath: path });\n modules.push(resolved);\n\n this.emit('moduleResolved', resolved);\n } catch (error) {\n if (ignoreErrors) continue;\n\n this.emitOrThrow('moduleResolveError', new RecipleError({\n message: `Failed to load module: ${colors.cyan(path)}`,\n cause: error\n }));\n }\n }\n\n this.emit('modulesResolved', modules);\n return modules;\n }\n\n public static async scanForDirectories(config?: Pick<ModuleLoader.Config, 'directories'|'ignore'> & { cwd?: string; createDirectories?: boolean; }) {\n const cwd = config?.cwd ?? process.cwd();\n\n let scanned: string[] = [];\n let directories: string[] = [];\n\n for (const directory of config?.directories ?? []) {\n if (isDynamicPattern(directory, { cwd })) {\n const matches = await globby(directory, {\n cwd,\n ignore: config?.ignore,\n onlyDirectories: true,\n baseNameMatch: true,\n absolute: true\n });\n\n scanned.push(...matches);\n continue;\n }\n\n scanned.push(path.join(cwd, directory));\n }\n\n for (const directory of scanned) {\n const stats = await stat(directory).catch(() => undefined);\n\n if (!stats && config?.createDirectories !== false) {\n await mkdir(directory, { recursive: true });\n }\n\n directories.push(directory);\n }\n\n return directories;\n }\n\n public static async scanForModulePaths(config?: ModuleLoader.Config & { cwd?: string; createDirectories?: boolean; }): Promise<string[]> {\n const directories = await ModuleLoader.scanForDirectories(config);\n\n let modules: string[] = [];\n\n for (const directory of directories) {\n let files = await readdir(directory);\n\n if (config?.ignore?.length) {\n files = micromatch.not(files, config.ignore, {\n cwd: directory,\n matchBase: true,\n dot: true\n });\n }\n\n files = files.map(f => path.join(directory, f));\n\n for (const file of files) {\n if (config?.filter ? !(await config?.filter(file)) : ModuleLoader.fileTypes.every(type => !file.endsWith(`.${type}`))) continue;\n modules.push(file);\n }\n }\n\n if (config?.sort) modules.sort(config.sort);\n\n return modules;\n }\n\n public static async resolveModuleFromPath(filepath: string, options?: { cwd?: string; }): Promise<AnyModule> {\n const stats = await stat(filepath).catch(() => undefined);\n if (!stats) throw new RecipleError(`Module not found: ${filepath}`);\n\n const data = recursiveDefaults<AnyModule|AnyModuleData|undefined>(await import(`file://${path.resolve(options?.cwd ?? process.cwd(), filepath)}`));\n if (BaseModule.isModule(data)) return data;\n\n if (data && 'moduleType' in data) {\n switch (data?.moduleType) {\n case ModuleType.Command:\n CommandModuleValidator.isValid(data);\n switch (data.type) {\n case CommandType.Message: return MessageCommandModule.from(data);\n case CommandType.Slash: return SlashCommandModule.from(data);\n case CommandType.ContextMenu: return ContextMenuCommandModule.from(data);\n default: throw new RecipleError(`Unknown command type from module: ${colors.cyan(filepath)}`);\n }\n case ModuleType.Event:\n EventModuleValidator.isValid(data);\n return EventModule.from(data);\n case ModuleType.Precondition:\n PreconditionModuleValidator.isValid(data);\n return PreconditionModule.from(data);\n case ModuleType.Postcondition:\n PostconditionModuleValidator.isValid(data);\n return PostconditionModule.from(data);\n default:\n BaseModuleValidator.isValid(data);\n return BaseModule.from(data);\n }\n }\n\n BaseModuleValidator.isValid(data);\n return BaseModule.from(data);\n }\n\n public static async resolveSourceDirectories(options: ModuleLoader.ResolveSourceDirectoryOptions): Promise<string[]> {\n const dir = path.isAbsolute(options.baseUrl) ? options.baseUrl : path.resolve(path.join(options.cwd ?? process.cwd(), options.baseUrl));\n\n const root = path.resolve(path.join(dir, options.rootDir));\n const out = path.resolve(path.join(dir, options.outDir));\n\n return options.directories.map(directory => path.resolve(directory).replace(out, root));\n }\n\n private emitOrThrow<K extends keyof Pick<ModuleLoader.Events, 'moduleResolveError'>>(event: K, error: RecipleError) {\n if (this.client.listenerCount(event) > 0) {\n // @ts-expect-error\n return this.emit(event, error);\n }\n\n throw error;\n }\n}\n\nexport namespace ModuleLoader {\n export let globby: typeof import('globby')|null = null;\n\n export const fileTypes = [\n 'js',\n 'mjs',\n 'jsx'\n ];\n\n export interface Config {\n directories?: string[];\n ignore?: string[];\n filter?: (filepath: string) => Awaitable<boolean>;\n sort?: (a: string, b: string) => number;\n }\n\n export interface Events {\n moduleResolveError: [error: RecipleError];\n moduleResolved: [module: AnyModule];\n moduleResolving: [filepath: string];\n modulesResolved: [modules: AnyModule[]];\n modulesResolving: [files: string[]];\n }\n\n export interface ResolveSourceDirectoryOptions {\n directories: string[];\n baseUrl: string;\n rootDir: string;\n outDir: string;\n cwd?: string;\n }\n\n export async function getGlobby(): Promise<typeof import('globby')> {\n if (globby) return globby;\n\n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