commandkit 0.1.10 → 0.1.11-dev.20240202064607

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/bin/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ require('source-map-support').install();
3
+ import('commandkit/cli');
package/package.json CHANGED
@@ -1,58 +1,69 @@
1
1
  {
2
- "name": "commandkit",
3
- "description": "Beginner friendly command & event handler for Discord.js",
4
- "version": "0.1.10",
5
- "license": "MIT",
6
- "main": "./dist/index.js",
7
- "module": "./dist/index.mjs",
8
- "types": "./dist/index.d.ts",
9
- "bin": "./bin/index.mjs",
10
- "exports": {
11
- ".": {
12
- "require": "./dist/index.js",
13
- "import": "./dist/index.mjs",
14
- "types": "./dist/index.d.ts"
15
- }
2
+ "name": "commandkit",
3
+ "description": "Beginner friendly command & event handler for Discord.js",
4
+ "version": "0.1.11-dev.20240202064607",
5
+ "license": "MIT",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.mjs",
8
+ "types": "./dist/index.d.ts",
9
+ "bin": "./bin/index.mjs",
10
+ "exports": {
11
+ ".": {
12
+ "require": "./dist/index.js",
13
+ "import": "./dist/index.mjs",
14
+ "types": "./dist/index.d.ts"
16
15
  },
17
- "files": [
18
- "dist",
19
- "bin"
20
- ],
21
- "scripts": {
22
- "lint": "tsc",
23
- "dev": "tsup --watch",
24
- "build": "tsup",
25
- "deploy": "npm publish",
26
- "deploy-dev": "npm publish --access public --tag dev",
27
- "test": "cd ./tests && node ../bin/index.mjs dev",
28
- "test:build": "cd ./tests && node ../bin/index.mjs build",
29
- "test:prod": "cd ./tests && node ../bin/index.mjs start"
30
- },
31
- "repository": {
32
- "url": "git+https://github.com/underctrl-io/commandkit.git"
33
- },
34
- "homepage": "https://commandkit.js.org",
35
- "keywords": [
36
- "discord.js",
37
- "command handler",
38
- "event handler"
39
- ],
40
- "dependencies": {
41
- "commander": "^11.1.0",
42
- "dotenv": "^16.3.1",
43
- "ora": "^7.0.1",
44
- "rfdc": "^1.3.0",
45
- "rimraf": "^5.0.5",
46
- "tsup": "^7.2.0"
47
- },
48
- "devDependencies": {
49
- "@types/node": "^20.5.9",
50
- "discord.js": "^14.13.0",
51
- "tsconfig": "workspace:*",
52
- "tsx": "^3.12.8",
53
- "typescript": "^5.1.6"
54
- },
55
- "peerDependencies": {
56
- "discord.js": "^14"
16
+ "./cli": {
17
+ "require": "./dist/environment/cli.js",
18
+ "import": "./dist/environment/cli.mjs",
19
+ "types": "./dist/environment/cli.d.ts"
57
20
  }
58
- }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "bin"
25
+ ],
26
+ "scripts": {
27
+ "lint": "tsc --noEmit",
28
+ "dev": "tsup --watch",
29
+ "build": "tsup",
30
+ "deploy": "npm publish",
31
+ "test": "vitest",
32
+ "test:dev": "cd ./tests && node ../bin/index.mjs dev",
33
+ "test:build": "cd ./tests && node ../bin/index.mjs build",
34
+ "test:prod": "cd ./tests && node ../bin/index.mjs start"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/underctrl-io/commandkit",
39
+ "directory": "packages/commandkit"
40
+ },
41
+ "homepage": "https://commandkit.js.org",
42
+ "keywords": [
43
+ "discord.js",
44
+ "command handler",
45
+ "event handler"
46
+ ],
47
+ "dependencies": {
48
+ "dotenv-cra": "^3.0.3",
49
+ "ora": "^8.0.1",
50
+ "rfdc": "^1.3.1",
51
+ "rimraf": "^5.0.5",
52
+ "source-map-support": "^0.5.21",
53
+ "tsup": "^8.0.1",
54
+ "yargs": "^17.7.2"
55
+ },
56
+ "devDependencies": {
57
+ "@types/node": "^20.11.6",
58
+ "@types/yargs": "^17.0.32",
59
+ "discord.js": "^14.14.1",
60
+ "esbuild-plugin-version-injector": "^1.2.1",
61
+ "tsconfig": "workspace:*",
62
+ "tsx": "^4.7.0",
63
+ "typescript": "^5.3.3",
64
+ "vitest": "^1.2.1"
65
+ },
66
+ "peerDependencies": {
67
+ "discord.js": "^14"
68
+ }
69
+ }
package/bin/build.mjs DELETED
@@ -1,107 +0,0 @@
1
- // @ts-check
2
-
3
- import { readFile, writeFile } from 'node:fs/promises';
4
- import { join } from 'node:path';
5
- import { build } from 'tsup';
6
- import { Colors, erase, findCommandKitConfig, panic, write } from './common.mjs';
7
- import ora from 'ora';
8
-
9
- export async function bootstrapProductionBuild(config) {
10
- const {
11
- sourcemap = false,
12
- minify = false,
13
- outDir = 'dist',
14
- antiCrash = true,
15
- src,
16
- main,
17
- requirePolyfill: polyfillRequire,
18
- } = await findCommandKitConfig(config);
19
-
20
- const status = ora('Creating optimized production build...\n').start();
21
- const start = performance.now();
22
-
23
- erase(outDir);
24
-
25
- try {
26
- await build({
27
- clean: true,
28
- format: ['esm'],
29
- dts: false,
30
- skipNodeModulesBundle: true,
31
- minify,
32
- shims: true,
33
- banner: {
34
- js: '/* Optimized production build generated by CommandKit */',
35
- },
36
- sourcemap,
37
- keepNames: true,
38
- outDir,
39
- silent: true,
40
- watch: false,
41
- entry: [src, '!dist', '!.commandkit', `!${outDir}`],
42
- });
43
-
44
- await injectShims(outDir, main, antiCrash, polyfillRequire);
45
-
46
- status.succeed(
47
- Colors.green(`Build completed in ${(performance.now() - start).toFixed(2)}ms!`),
48
- );
49
- write(
50
- Colors.green(
51
- `\nRun ${Colors.magenta(`commandkit start`)} ${Colors.green('to start your bot.')}`,
52
- ),
53
- );
54
- } catch (e) {
55
- status.fail(`Build failed after ${(performance.now() - start).toFixed(2)}ms!`);
56
- panic(e);
57
- }
58
- }
59
-
60
- export async function injectShims(outDir, main, antiCrash, polyfillRequire) {
61
- const path = join(process.cwd(), outDir, main);
62
-
63
- const head = ['\n\n;await (async()=>{', " 'use strict';"].join('\n');
64
- const tail = '\n})();';
65
- const requireScript = polyfillRequire
66
- ? [
67
- '// --- CommandKit require() polyfill ---',
68
- ' if (typeof require === "undefined") {',
69
- ' const { createRequire } = await import("node:module");',
70
- ' const __require = createRequire(import.meta.url);',
71
- ' Object.defineProperty(globalThis, "require", {',
72
- ' value: (id) => {',
73
- ' return __require(id);',
74
- ' },',
75
- ' configurable: true,',
76
- ' enumerable: false,',
77
- ' writable: true,',
78
- ' });',
79
- ' }',
80
- '// --- CommandKit require() polyfill ---',
81
- ].join('\n')
82
- : '';
83
-
84
- const antiCrashScript = antiCrash
85
- ? [
86
- '// --- CommandKit Anti-Crash Monitor ---',
87
- " // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process",
88
- ' // instead of using it as a means to resume operation.',
89
- ' // But it exists here due to compatibility reasons with discord bot ecosystem.',
90
- " const p = (t) => `\\x1b[33m${t}\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';",
91
- ' if (!process.eventNames().includes(e1)) // skip if it is already handled',
92
- ' process.on(e1, (e) => {',
93
- ' l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));',
94
- ' })',
95
- ' if (!process.eventNames().includes(e2)) // skip if it is already handled',
96
- ' process.on(e2, (r) => {',
97
- ' l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));',
98
- ' });',
99
- '// --- CommandKit Anti-Crash Monitor ---',
100
- ].join('\n')
101
- : '';
102
-
103
- const contents = await readFile(path, 'utf-8');
104
- const finalScript = [head, requireScript, antiCrashScript, tail, '\n\n', contents].join('\n');
105
-
106
- return writeFile(path, finalScript);
107
- }
package/bin/common.mjs DELETED
@@ -1,102 +0,0 @@
1
- // @ts-check
2
-
3
- import { rimrafSync } from 'rimraf';
4
- import { join } from 'node:path';
5
- import fs from 'node:fs';
6
-
7
- const resetColor = '\x1b[0m';
8
-
9
- export const Colors = {
10
- reset: (text) => `${text}${resetColor}`,
11
- bright: (text) => `\x1b[1m${text}${resetColor}`,
12
- dim: (text) => `\x1b[2m${text}${resetColor}`,
13
- underscore: (text) => `\x1b[4m${text}${resetColor}`,
14
- blink: (text) => `\x1b[5m${text}${resetColor}`,
15
- reverse: (text) => `\x1b[7m${text}${resetColor}`,
16
- hidden: (text) => `\x1b[8m${text}${resetColor}`,
17
-
18
- black: (text) => `\x1b[30m${text}${resetColor}`,
19
- red: (text) => `\x1b[31m${text}${resetColor}`,
20
- green: (text) => `\x1b[32m${text}${resetColor}`,
21
- yellow: (text) => `\x1b[33m${text}${resetColor}`,
22
- blue: (text) => `\x1b[34m${text}${resetColor}`,
23
- magenta: (text) => `\x1b[35m${text}${resetColor}`,
24
- cyan: (text) => `\x1b[36m${text}${resetColor}`,
25
- white: (text) => `\x1b[37m${text}${resetColor}`,
26
-
27
- bgBlack: (text) => `\x1b[40m${text}${resetColor}`,
28
- bgRed: (text) => `\x1b[41m${text}${resetColor}`,
29
- bgGreen: (text) => `\x1b[42m${text}${resetColor}`,
30
- bgYellow: (text) => `\x1b[43m${text}${resetColor}`,
31
- bgBlue: (text) => `\x1b[44m${text}${resetColor}`,
32
- bgMagenta: (text) => `\x1b[45m${text}${resetColor}`,
33
- bgCyan: (text) => `\x1b[46m${text}${resetColor}`,
34
- bgWhite: (text) => `\x1b[47m${text}${resetColor}`,
35
- };
36
-
37
- export function write(message) {
38
- process.stdout.write(message);
39
- process.stdout.write('\n');
40
- }
41
-
42
- /**
43
- * @returns {never}
44
- */
45
- export function panic(message) {
46
- write(Colors.red(`Error: ${message}`));
47
- process.exit(1);
48
- }
49
-
50
- export function findPackageJSON() {
51
- const cwd = process.cwd();
52
- const target = join(cwd, 'package.json');
53
-
54
- if (!fs.existsSync(target)) {
55
- panic('Could not find package.json in current directory.');
56
- }
57
-
58
- return JSON.parse(fs.readFileSync(target, 'utf8'));
59
- }
60
-
61
- const possibleFileNames = [
62
- 'commandkit.json',
63
- 'commandkit.config.json',
64
- 'commandkit.js',
65
- 'commandkit.config.js',
66
- 'commandkit.mjs',
67
- 'commandkit.config.mjs',
68
- 'commandkit.cjs',
69
- 'commandkit.config.cjs',
70
- ];
71
-
72
- export async function findCommandKitConfig(src) {
73
- const cwd = process.cwd();
74
- const locations = src ? [join(cwd, src)] : possibleFileNames.map((name) => join(cwd, name));
75
-
76
- for (const location of locations) {
77
- try {
78
- return await loadConfigInner(location);
79
- } catch (e) {
80
- continue;
81
- }
82
- }
83
-
84
- panic('Could not locate commandkit config.');
85
- }
86
-
87
- async function loadConfigInner(target) {
88
- const isJSON = target.endsWith('.json');
89
-
90
- /**
91
- * @type {import('..').CommandKitConfig}
92
- */
93
- const config = await import(`file://${target}`, {
94
- assert: isJSON ? { type: 'json' } : undefined,
95
- }).then((conf) => conf.default || conf);
96
-
97
- return config;
98
- }
99
-
100
- export function erase(dir) {
101
- rimrafSync(dir);
102
- }
@@ -1,168 +0,0 @@
1
- // @ts-check
2
- import { config as dotenv } from 'dotenv';
3
- import { join } from 'node:path';
4
- import { build } from 'tsup';
5
- import { Colors, erase, findCommandKitConfig, panic, write } from './common.mjs';
6
- import { parseEnv } from './parse-env.mjs';
7
- import child_process from 'node:child_process';
8
- import ora from 'ora';
9
- import { injectShims } from './build.mjs';
10
-
11
- const RESTARTING_MSG_PATTERN = /^Restarting '|".+'|"\n?$/;
12
- const FAILED_RUNNING_PATTERN = /^Failed running '.+'|"\n?$/;
13
-
14
- export async function bootstrapDevelopmentServer(opts) {
15
- const {
16
- src,
17
- main,
18
- watch = Boolean(opts.noWatch),
19
- nodeOptions = [],
20
- envExtra = true,
21
- clearRestartLogs = true,
22
- outDir,
23
- requirePolyfill,
24
- } = await findCommandKitConfig(opts.config);
25
-
26
- if (!src) {
27
- panic('Could not find src in commandkit.json');
28
- }
29
-
30
- if (!main) {
31
- panic('Could not find main in commandkit.json');
32
- }
33
-
34
- const watchMode = watch;
35
- const status = ora(Colors.green('Starting a development server...\n')).start();
36
- const start = performance.now();
37
-
38
- if (watchMode && !nodeOptions.includes('--watch')) {
39
- nodeOptions.push('--watch');
40
- } else if (!watchMode && nodeOptions.includes('--watch')) {
41
- nodeOptions.splice(nodeOptions.indexOf('--watch'), 1);
42
- }
43
-
44
- if (!nodeOptions.includes('--enable-source-maps')) {
45
- nodeOptions.push('--enable-source-maps');
46
- }
47
-
48
- erase('.commandkit');
49
-
50
- try {
51
- await build({
52
- clean: true,
53
- format: ['esm'],
54
- dts: false,
55
- skipNodeModulesBundle: true,
56
- minify: false,
57
- shims: true,
58
- sourcemap: 'inline',
59
- keepNames: true,
60
- outDir: '.commandkit',
61
- silent: true,
62
- entry: [src, '!dist', '!.commandkit', `!${outDir}`].filter(Boolean),
63
- watch: watchMode,
64
- async onSuccess() {
65
- return await injectShims('.commandkit', main, false, requirePolyfill);
66
- },
67
- });
68
-
69
- status.succeed(
70
- Colors.green(`Dev server started in ${(performance.now() - start).toFixed(2)}ms!\n`),
71
- );
72
-
73
- if (watchMode) write(Colors.cyan('Watching for file changes...\n'));
74
-
75
- const processEnv = {};
76
-
77
- const env = dotenv({
78
- path: join(process.cwd(), '.env'),
79
- // @ts-expect-error
80
- processEnv,
81
- });
82
-
83
- if (envExtra) {
84
- parseEnv(processEnv);
85
- }
86
-
87
- if (env.error) {
88
- write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`));
89
- }
90
-
91
- if (env.parsed) {
92
- write(Colors.blue('[DOTENV] Loaded .env file!'));
93
- }
94
-
95
- /**
96
- * @type {child_process.ChildProcessWithoutNullStreams}
97
- */
98
- const ps = child_process.spawn(
99
- 'node',
100
- [...nodeOptions, join(process.cwd(), '.commandkit', main)],
101
- {
102
- env: {
103
- ...process.env,
104
- ...processEnv,
105
- NODE_ENV: 'development',
106
- // @ts-expect-error
107
- COMMANDKIT_DEV: true,
108
- // @ts-expect-error
109
- COMMANDKIT_PRODUCTION: false,
110
- },
111
- cwd: process.cwd(),
112
- },
113
- );
114
-
115
- let isLastLogRestarting = false,
116
- hasStarted = false;
117
-
118
- ps.stdout.on('data', (data) => {
119
- const message = data.toString();
120
-
121
- if (FAILED_RUNNING_PATTERN.test(message)) {
122
- write(Colors.cyan('Failed running the bot, waiting for changes...'));
123
- isLastLogRestarting = false;
124
- if (!hasStarted) hasStarted = true;
125
- return;
126
- }
127
-
128
- if (clearRestartLogs && !RESTARTING_MSG_PATTERN.test(message)) {
129
- write(message);
130
- isLastLogRestarting = false;
131
- } else {
132
- if (isLastLogRestarting || !hasStarted) {
133
- if (!hasStarted) hasStarted = true;
134
- return;
135
- }
136
- write(Colors.cyan('⌀ Restarting the bot...'));
137
- isLastLogRestarting = true;
138
- }
139
-
140
- if (!hasStarted) hasStarted = true;
141
- });
142
-
143
- ps.stderr.on('data', (data) => {
144
- const message = data.toString();
145
-
146
- if (
147
- message.includes(
148
- 'ExperimentalWarning: Watch mode is an experimental feature and might change at any time',
149
- )
150
- )
151
- return;
152
-
153
- write(Colors.red(message));
154
- });
155
-
156
- ps.on('close', (code) => {
157
- write('\n');
158
- process.exit(code ?? 0);
159
- });
160
-
161
- ps.on('error', (err) => {
162
- panic(err);
163
- });
164
- } catch (e) {
165
- status.fail(`Error occurred after ${(performance.now() - start).toFixed(2)}ms!\n`);
166
- panic(e.stack ?? e);
167
- }
168
- }
package/bin/index.mjs DELETED
@@ -1,39 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // @ts-check
4
-
5
- import { Command } from 'commander';
6
- import { bootstrapDevelopmentServer } from './development.mjs';
7
- import { bootstrapProductionServer } from './production.mjs';
8
- import { bootstrapProductionBuild } from './build.mjs';
9
-
10
- const program = new Command('commandkit');
11
-
12
- program
13
- .command('dev')
14
- .description('Start your bot in development mode.')
15
- .option('-c, --config <path>', 'Path to your commandkit config file.', './commandkit.js')
16
- .action(() => {
17
- const options = program.opts();
18
- bootstrapDevelopmentServer(options);
19
- });
20
-
21
- program
22
- .command('start')
23
- .description('Start your bot in production mode after running the build command.')
24
- .option('-c, --config <path>', 'Path to your commandkit.json file.', './commandkit.js')
25
- .action(() => {
26
- const options = program.opts();
27
- bootstrapProductionServer(options.config);
28
- });
29
-
30
- program
31
- .command('build')
32
- .description('Build your project for production usage.')
33
- .option('-c, --config <path>', 'Path to your commandkit.json file.', './commandkit.json')
34
- .action(() => {
35
- const options = program.opts();
36
- bootstrapProductionBuild(options.config);
37
- });
38
-
39
- program.parse();
package/bin/parse-env.mjs DELETED
@@ -1,61 +0,0 @@
1
- // @ts-check
2
-
3
- import { randomUUID } from 'node:crypto';
4
-
5
- const valuesMap = {
6
- true: true,
7
- false: false,
8
- null: null,
9
- undefined: undefined,
10
- __UUIDv4__: () => randomUUID(),
11
- };
12
-
13
- const VALUE_PREFIXES = {
14
- JSON: 'JSON::',
15
- DATE: 'DATE::',
16
- };
17
-
18
- function catcher(fn) {
19
- try {
20
- fn();
21
- return true;
22
- } catch {
23
- return false;
24
- }
25
- }
26
-
27
- export function parseEnv(src) {
28
- for (const key in src) {
29
- const value = src[key];
30
-
31
- if (typeof value !== 'string') continue;
32
-
33
- if (value.startsWith(VALUE_PREFIXES.JSON)) {
34
- catcher(() => (src[key] = JSON.parse(value.replace(VALUE_PREFIXES.JSON, ''))));
35
- continue;
36
- }
37
-
38
- if (value.startsWith(VALUE_PREFIXES.DATE)) {
39
- src[key] = new Date(value.replace(VALUE_PREFIXES.DATE, ''));
40
- continue;
41
- }
42
-
43
- if (value.includes(',')) {
44
- src[key] = value.split(',').map((v) => v.trim());
45
- continue;
46
- }
47
-
48
- if (/^[0-9]+n$/.test(value)) {
49
- src[key] = BigInt(value);
50
- continue;
51
- }
52
-
53
- if (value in valuesMap) {
54
- src[key] =
55
- typeof valuesMap[value] === 'function' ? valuesMap[value]() : valuesMap[value];
56
- continue;
57
- }
58
- }
59
-
60
- return src;
61
- }
@@ -1,83 +0,0 @@
1
- // @ts-check
2
- import { config as dotenv } from 'dotenv';
3
- import { existsSync } from 'node:fs';
4
- import { join } from 'node:path';
5
- import { Colors, findCommandKitConfig, panic, write } from './common.mjs';
6
- import { parseEnv } from './parse-env.mjs';
7
- import child_process from 'node:child_process';
8
-
9
- export async function bootstrapProductionServer(config) {
10
- const {
11
- main,
12
- outDir = 'dist',
13
- envExtra = true,
14
- sourcemap,
15
- } = await findCommandKitConfig(config);
16
-
17
- if (!existsSync(join(process.cwd(), outDir, main))) {
18
- panic('Could not find production build, maybe run `commandkit build` first?');
19
- }
20
-
21
- try {
22
- const processEnv = {};
23
-
24
- const env = dotenv({
25
- path: join(process.cwd(), '.env'),
26
- // @ts-expect-error
27
- processEnv,
28
- });
29
-
30
- if (envExtra) {
31
- parseEnv(processEnv);
32
- }
33
-
34
- if (env.error) {
35
- write(Colors.yellow(`[DOTENV] Warning: ${env.error.message}`));
36
- }
37
-
38
- if (env.parsed) {
39
- write(Colors.blue('[DOTENV] Loaded .env file!'));
40
- }
41
-
42
- /**
43
- * @type {child_process.ChildProcessWithoutNullStreams}
44
- */
45
- const ps = child_process.spawn(
46
- 'node',
47
- [sourcemap ? '--enable-source-maps' : '', join(process.cwd(), outDir, main)].filter(
48
- Boolean,
49
- ),
50
- {
51
- env: {
52
- ...process.env,
53
- ...processEnv,
54
- NODE_ENV: 'production',
55
- // @ts-expect-error
56
- COMMANDKIT_DEV: false,
57
- // @ts-expect-error
58
- COMMANDKIT_PROD: true,
59
- },
60
- cwd: process.cwd(),
61
- },
62
- );
63
-
64
- ps.stdout.on('data', (data) => {
65
- write(data.toString());
66
- });
67
-
68
- ps.stderr.on('data', (data) => {
69
- write(Colors.red(data.toString()));
70
- });
71
-
72
- ps.on('close', (code) => {
73
- write('\n');
74
- process.exit(code ?? 0);
75
- });
76
-
77
- ps.on('error', (err) => {
78
- panic(err);
79
- });
80
- } catch (e) {
81
- panic(e);
82
- }
83
- }