nuxt-discord 0.0.16 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +249 -171
- package/dist/module.d.mts +128 -11
- package/dist/module.json +3 -3
- package/dist/module.mjs +1015 -328
- package/dist/runtime/acknowledgement.d.ts +10 -0
- package/dist/runtime/acknowledgement.js +124 -0
- package/dist/runtime/client/chat-theme.css +52 -0
- package/dist/runtime/client/components/ChatAvatar.d.vue.ts +6 -0
- package/dist/runtime/client/components/ChatAvatar.vue +11 -0
- package/dist/runtime/client/components/ChatAvatar.vue.d.ts +6 -0
- package/dist/runtime/client/components/CommandPicker.d.vue.ts +24 -0
- package/dist/runtime/client/components/CommandPicker.vue +67 -0
- package/dist/runtime/client/components/CommandPicker.vue.d.ts +24 -0
- package/dist/runtime/client/components/CommandTestBar.d.vue.ts +60 -0
- package/dist/runtime/client/components/CommandTestBar.vue +335 -0
- package/dist/runtime/client/components/CommandTestBar.vue.d.ts +60 -0
- package/dist/runtime/client/components/CommandTranscript.d.vue.ts +39 -0
- package/dist/runtime/client/components/CommandTranscript.vue +147 -0
- package/dist/runtime/client/components/CommandTranscript.vue.d.ts +39 -0
- package/dist/runtime/client/components/ProjectLogo.d.vue.ts +3 -0
- package/dist/runtime/client/components/ProjectLogo.vue +31 -0
- package/dist/runtime/client/components/ProjectLogo.vue.d.ts +3 -0
- package/dist/runtime/client/components/TheHeader.d.vue.ts +3 -0
- package/dist/runtime/client/components/TheHeader.vue +53 -16
- package/dist/runtime/client/components/TheHeader.vue.d.ts +2 -2
- package/dist/runtime/client/components/appearance-select.d.ts +17 -0
- package/dist/runtime/client/components/appearance-select.js +15 -0
- package/dist/runtime/client/pages/activity.d.vue.ts +3 -0
- package/dist/runtime/client/pages/activity.vue +202 -0
- package/dist/runtime/client/pages/activity.vue.d.ts +3 -0
- package/dist/runtime/client/pages/context-menus.d.vue.ts +3 -0
- package/dist/runtime/client/pages/context-menus.vue +120 -0
- package/dist/runtime/client/pages/context-menus.vue.d.ts +3 -0
- package/dist/runtime/client/pages/listeners.d.vue.ts +3 -0
- package/dist/runtime/client/pages/listeners.vue +68 -0
- package/dist/runtime/client/pages/listeners.vue.d.ts +3 -0
- package/dist/runtime/client/pages/overview.d.vue.ts +3 -0
- package/dist/runtime/client/pages/overview.vue +280 -0
- package/dist/runtime/client/pages/overview.vue.d.ts +3 -0
- package/dist/runtime/client/pages/slash-commands.d.vue.ts +3 -0
- package/dist/runtime/client/pages/slash-commands.vue +185 -354
- package/dist/runtime/client/pages/slash-commands.vue.d.ts +2 -3
- package/dist/runtime/client/style.css +4 -1
- package/dist/runtime/client/useActivityLog.d.ts +7 -0
- package/dist/runtime/client/useActivityLog.js +76 -0
- package/dist/runtime/client/useCommandRegistry.d.ts +7 -0
- package/dist/runtime/client/useCommandRegistry.js +34 -0
- package/dist/runtime/client/useDashboardCatalog.d.ts +5 -0
- package/dist/runtime/client/useDashboardCatalog.js +9 -0
- package/dist/runtime/dashboard/auth.d.ts +4 -0
- package/dist/runtime/dashboard/auth.js +65 -0
- package/dist/runtime/dashboard/oauth.d.ts +3 -0
- package/dist/runtime/dashboard/oauth.js +151 -0
- package/dist/runtime/dashboard/permissions.d.ts +4 -0
- package/dist/runtime/dashboard/permissions.js +84 -0
- package/dist/runtime/dashboard/signin.d.ts +2 -0
- package/dist/runtime/dashboard/signin.js +39 -0
- package/dist/runtime/diagnostics.d.ts +4 -0
- package/dist/runtime/diagnostics.js +24 -0
- package/dist/runtime/discordInvocation.d.ts +14 -0
- package/dist/runtime/discordInvocation.js +28 -0
- package/dist/runtime/middleware.d.ts +1 -0
- package/dist/runtime/middleware.js +12 -0
- package/dist/runtime/registration.d.ts +65 -0
- package/dist/runtime/registration.js +354 -0
- package/dist/runtime/server/api/discord/activity.get.d.ts +2 -0
- package/dist/runtime/server/api/discord/activity.get.js +6 -0
- package/dist/runtime/server/api/discord/catalog.get.d.ts +2 -0
- package/dist/runtime/server/api/discord/catalog.get.js +3 -0
- package/dist/runtime/server/api/discord/slash-command/autocomplete.post.d.ts +2 -0
- package/dist/runtime/server/api/discord/slash-command/autocomplete.post.js +14 -0
- package/dist/runtime/server/api/discord/slash-command/register.post.d.ts +1 -1
- package/dist/runtime/server/api/discord/slash-command/register.post.js +1 -1
- package/dist/runtime/server/api/discord/slash-command/remote-all.get.d.ts +1 -1
- package/dist/runtime/server/api/discord/slash-command/remote-diff.post.d.ts +1 -19
- package/dist/runtime/server/api/discord/slash-command/remote-diff.post.js +3 -1
- package/dist/runtime/server/api/discord/slash-command/test.post.d.ts +20 -0
- package/dist/runtime/server/api/discord/slash-command/test.post.js +19 -0
- package/dist/runtime/server/plugins/discord.js +93 -31
- package/dist/runtime/server/utils/client.d.ts +58 -20
- package/dist/runtime/server/utils/client.js +410 -371
- package/dist/runtime/server/utils/defineContextMenu.d.ts +49 -0
- package/dist/runtime/server/utils/defineContextMenu.js +12 -0
- package/dist/runtime/server/utils/defineListener.d.ts +24 -0
- package/dist/runtime/server/utils/defineListener.js +7 -0
- package/dist/runtime/server/utils/defineMiddleware.d.ts +29 -0
- package/dist/runtime/server/utils/defineMiddleware.js +24 -0
- package/dist/runtime/server/utils/describeCommand.d.ts +2 -0
- package/dist/runtime/server/utils/describeOption.d.ts +1 -1
- package/dist/runtime/server/utils/messageSender.d.ts +37 -0
- package/dist/runtime/server/utils/messageSender.js +149 -0
- package/dist/runtime/server/utils/middleware/cooldown.d.ts +1 -0
- package/dist/runtime/server/utils/middleware/cooldown.js +39 -0
- package/dist/runtime/server/utils/middleware/guildOnly.d.ts +1 -0
- package/dist/runtime/server/utils/middleware/guildOnly.js +6 -0
- package/dist/runtime/server/utils/middleware/ownerOnly.d.ts +1 -0
- package/dist/runtime/server/utils/middleware/ownerOnly.js +10 -0
- package/dist/runtime/server/utils/middleware/requireRole.d.ts +1 -0
- package/dist/runtime/server/utils/middleware/requireRole.js +15 -0
- package/dist/runtime/server/utils/reply.d.ts +13 -3
- package/dist/runtime/server/utils/reply.js +111 -162
- package/dist/runtime/server/utils/simulateInteraction.d.ts +20 -0
- package/dist/runtime/server/utils/simulateInteraction.js +127 -0
- package/dist/runtime/server/utils/useTextChannel.d.ts +56 -0
- package/dist/runtime/server/utils/useTextChannel.js +105 -0
- package/dist/types.d.mts +11 -1
- package/dist/types.d.ts +11 -1
- package/package.json +62 -44
- package/dist/runtime/client/components/TheHeader.css +0 -1
- package/dist/runtime/client/pages/slash-commands.css +0 -1
- package/dist/runtime/client/uno.config.d.ts +0 -2
- package/dist/runtime/client/uno.config.js +0 -10
package/dist/module.mjs
CHANGED
|
@@ -1,21 +1,26 @@
|
|
|
1
|
-
import { createResolver,
|
|
2
|
-
import { ApplicationCommandOptionType, GatewayIntentBits } from 'discord.js';
|
|
1
|
+
import { createResolver, extendPages, addServerTemplate, addTemplate, addTypeTemplate, updateTemplates, isIgnored, defineNuxtModule, addServerHandler, extendRouteRules, addServerScanDir, addServerPlugin, addServerImportsDir, addImports, loadNuxtModuleInstance } from '@nuxt/kit';
|
|
2
|
+
import { ApplicationCommandOptionType, Locale, GatewayIntentBits } from 'discord.js';
|
|
3
3
|
import { logger } from '../dist/runtime/logger.js';
|
|
4
4
|
import fs, { globSync, readFileSync } from 'node:fs';
|
|
5
|
-
import path from 'node:path';
|
|
6
|
-
import ts
|
|
5
|
+
import path, { relative, sep } from 'node:path';
|
|
6
|
+
import ts from 'typescript';
|
|
7
|
+
import '../dist/runtime/server/utils/defineMiddleware.js';
|
|
8
|
+
import { resolveMiddlewareTags } from '../dist/runtime/middleware.js';
|
|
9
|
+
import { rm } from 'node:fs/promises';
|
|
10
|
+
import { pathToFileURL } from 'node:url';
|
|
7
11
|
import chokidar from 'chokidar';
|
|
8
12
|
import { listen } from 'listhen';
|
|
9
13
|
import { rollup } from 'rollup';
|
|
10
14
|
import { WebSocketServer } from 'ws';
|
|
11
|
-
import
|
|
12
|
-
import { genSafeVariableName, genImport, genArrayFromRaw, genString } from 'knitwork';
|
|
15
|
+
import { genSafeVariableName, genImport, genString, genArrayFromRaw } from 'knitwork';
|
|
13
16
|
|
|
14
17
|
function createContext(options, nuxt) {
|
|
15
18
|
return {
|
|
16
19
|
nuxt,
|
|
17
20
|
options,
|
|
18
21
|
slashCommands: [],
|
|
22
|
+
contextMenus: [],
|
|
23
|
+
listeners: [],
|
|
19
24
|
resolve: {
|
|
20
25
|
root: createResolver(nuxt.options.rootDir).resolve,
|
|
21
26
|
module: createResolver(import.meta.url).resolve
|
|
@@ -24,16 +29,55 @@ function createContext(options, nuxt) {
|
|
|
24
29
|
};
|
|
25
30
|
}
|
|
26
31
|
|
|
27
|
-
|
|
32
|
+
function prepareClient(ctx) {
|
|
33
|
+
ctx.nuxt.hook("icon:clientBundleIcons", (icons) => {
|
|
34
|
+
for (const name of [
|
|
35
|
+
"lucide:blocks",
|
|
36
|
+
"lucide:circle-x",
|
|
37
|
+
"lucide:eye",
|
|
38
|
+
"lucide:gift",
|
|
39
|
+
"lucide:pin",
|
|
40
|
+
"lucide:plus",
|
|
41
|
+
"lucide:send-horizontal",
|
|
42
|
+
"lucide:shapes",
|
|
43
|
+
"lucide:smile",
|
|
44
|
+
"lucide:sticker",
|
|
45
|
+
"simple-icons:discord",
|
|
46
|
+
"simple-icons:github"
|
|
47
|
+
]) icons.add(name);
|
|
48
|
+
});
|
|
28
49
|
ctx.nuxt.options.css.push(ctx.resolve.module("runtime/client/style.css"));
|
|
29
|
-
await installModule("@nuxt/ui");
|
|
30
50
|
extendPages((pages) => {
|
|
31
51
|
pages.unshift(
|
|
32
52
|
{
|
|
33
|
-
name: "
|
|
53
|
+
name: "discord-overview",
|
|
54
|
+
path: "/discord",
|
|
55
|
+
file: ctx.resolve.module("./runtime/client/pages/overview.vue"),
|
|
56
|
+
mode: "client"
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
name: "discord-slash-commands",
|
|
34
60
|
path: "/discord/slash-commands",
|
|
35
61
|
file: ctx.resolve.module("./runtime/client/pages/slash-commands.vue"),
|
|
36
62
|
mode: "client"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
name: "discord-context-menus",
|
|
66
|
+
path: "/discord/context-menus",
|
|
67
|
+
file: ctx.resolve.module("./runtime/client/pages/context-menus.vue"),
|
|
68
|
+
mode: "client"
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
name: "discord-listeners",
|
|
72
|
+
path: "/discord/listeners",
|
|
73
|
+
file: ctx.resolve.module("./runtime/client/pages/listeners.vue"),
|
|
74
|
+
mode: "client"
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
name: "discord-activity",
|
|
78
|
+
path: "/discord/activity",
|
|
79
|
+
file: ctx.resolve.module("./runtime/client/pages/activity.vue"),
|
|
80
|
+
mode: "client"
|
|
37
81
|
}
|
|
38
82
|
);
|
|
39
83
|
});
|
|
@@ -43,7 +87,12 @@ const typeIdentifierToEnum = {
|
|
|
43
87
|
number: ApplicationCommandOptionType.Number,
|
|
44
88
|
integer: ApplicationCommandOptionType.Integer,
|
|
45
89
|
string: ApplicationCommandOptionType.String,
|
|
46
|
-
boolean: ApplicationCommandOptionType.Boolean
|
|
90
|
+
boolean: ApplicationCommandOptionType.Boolean,
|
|
91
|
+
User: ApplicationCommandOptionType.User,
|
|
92
|
+
Channel: ApplicationCommandOptionType.Channel,
|
|
93
|
+
Role: ApplicationCommandOptionType.Role,
|
|
94
|
+
Mentionable: ApplicationCommandOptionType.Mentionable,
|
|
95
|
+
Attachment: ApplicationCommandOptionType.Attachment
|
|
47
96
|
};
|
|
48
97
|
|
|
49
98
|
const macros = {
|
|
@@ -52,7 +101,7 @@ const macros = {
|
|
|
52
101
|
ctx.logger.warn("describeCommand macro requires a object literal as the first argument");
|
|
53
102
|
return;
|
|
54
103
|
}
|
|
55
|
-
const describeCommandOptions = ["name", "description"];
|
|
104
|
+
const describeCommandOptions = ["name", "description", "defer"];
|
|
56
105
|
const isValidOption = (key) => describeCommandOptions.includes(key);
|
|
57
106
|
const options = {};
|
|
58
107
|
for (const prop of node.arguments[0].properties) {
|
|
@@ -71,6 +120,11 @@ const macros = {
|
|
|
71
120
|
command.name = options.name ?? command.name;
|
|
72
121
|
}
|
|
73
122
|
command.description = options.description ?? command.description;
|
|
123
|
+
if (options.defer !== void 0) {
|
|
124
|
+
if (!["public", "private", "manual"].includes(options.defer))
|
|
125
|
+
throw new Error(`Invalid describeCommand defer policy in ${command.path}`);
|
|
126
|
+
command.defer = options.defer;
|
|
127
|
+
}
|
|
74
128
|
},
|
|
75
129
|
describeOption(ctx, node, command) {
|
|
76
130
|
if (node.arguments.length !== 2) {
|
|
@@ -95,7 +149,9 @@ const macros = {
|
|
|
95
149
|
const validOptionKeys = ["name", "description", "min", "max", "minLength", "maxLength", "choices"];
|
|
96
150
|
const isValidOptionKey = (key) => validOptionKeys.includes(key);
|
|
97
151
|
Reflect.deleteProperty(macroOptions, "autocomplete");
|
|
98
|
-
option.hasAutocomplete = node.arguments[1].properties.
|
|
152
|
+
option.hasAutocomplete = node.arguments[1].properties.some(
|
|
153
|
+
(prop) => (ts.isPropertyAssignment(prop) || ts.isShorthandPropertyAssignment(prop) || ts.isMethodDeclaration(prop)) && (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) && prop.name.text === "autocomplete"
|
|
154
|
+
);
|
|
99
155
|
for (const key in macroOptions) {
|
|
100
156
|
if (!isValidOptionKey(key)) {
|
|
101
157
|
ctx.logger.warn(`describeOption: unknown option key "${key}" for option "${name}" in command "${command.name}"`);
|
|
@@ -108,6 +164,9 @@ const macros = {
|
|
|
108
164
|
}
|
|
109
165
|
option[key] = value;
|
|
110
166
|
}
|
|
167
|
+
},
|
|
168
|
+
useMiddleware(_ctx, _node, command) {
|
|
169
|
+
command.middleware ??= [];
|
|
111
170
|
}
|
|
112
171
|
};
|
|
113
172
|
function parseLiteral(node) {
|
|
@@ -149,25 +208,126 @@ function parseLiteral(node) {
|
|
|
149
208
|
return void 0;
|
|
150
209
|
}
|
|
151
210
|
|
|
152
|
-
function
|
|
211
|
+
function readMiddlewareTags(file, definition) {
|
|
212
|
+
const statement = file.statements.find((node) => ts.isExportAssignment(node) || ts.isFunctionDeclaration(node) && node.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword));
|
|
213
|
+
const blocks = statement?.jsDoc ?? [];
|
|
214
|
+
const tags = /* @__PURE__ */ new Set([...blocks.flatMap((block) => [...block.tags ?? []]), ...definition ? ts.getJSDocTags(definition) : []]);
|
|
215
|
+
const names = [...tags].filter((tag) => tag.tagName.text === "middleware").map((tag) => tag.comment?.toString().trim() ?? "");
|
|
216
|
+
resolveMiddlewareTags(names, file.fileName);
|
|
217
|
+
return names;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function isOptionTypeIdentifier(s) {
|
|
221
|
+
return s in typeIdentifierToEnum;
|
|
222
|
+
}
|
|
223
|
+
const validLocales = new Set(Object.values(Locale));
|
|
224
|
+
const LOCALE_TAG_RE = /^\.([a-z]{2}(?:-[A-Z]{2})?)\s(.+)$/s;
|
|
225
|
+
const modifiersMap = {
|
|
226
|
+
string: ["minLength", "maxLength", "choices"],
|
|
227
|
+
number: ["min", "max", "choices"],
|
|
228
|
+
integer: ["min", "max", "choices"],
|
|
229
|
+
boolean: [],
|
|
230
|
+
User: [],
|
|
231
|
+
Channel: [],
|
|
232
|
+
Role: [],
|
|
233
|
+
Mentionable: [],
|
|
234
|
+
Attachment: []
|
|
235
|
+
};
|
|
236
|
+
function containsCommandFile(commands, file) {
|
|
237
|
+
return commands.some((command) => command.path === file || containsCommandFile(command.subcommands, file));
|
|
238
|
+
}
|
|
239
|
+
function collectSlashCommands(ctx, changed) {
|
|
153
240
|
const commandFiles = globSync(`${ctx.resolve.root(ctx.options.dir, "commands")}/**/*.ts`);
|
|
241
|
+
const previous = ctx.slashCommands;
|
|
242
|
+
const options = { noLib: true, noResolve: true, types: [] };
|
|
243
|
+
const changes = changed && ts.createProgram(
|
|
244
|
+
commandFiles.filter((file) => changed.has(file.split(path.sep).join("/"))),
|
|
245
|
+
options,
|
|
246
|
+
ts.createCompilerHost(options, true)
|
|
247
|
+
);
|
|
248
|
+
const problem = changes?.getSyntacticDiagnostics()[0];
|
|
249
|
+
if (problem) {
|
|
250
|
+
throw new SyntaxError(ts.formatDiagnostic(problem, {
|
|
251
|
+
getCanonicalFileName: (file) => file,
|
|
252
|
+
getCurrentDirectory: ts.sys.getCurrentDirectory,
|
|
253
|
+
getNewLine: () => "\n"
|
|
254
|
+
}));
|
|
255
|
+
}
|
|
154
256
|
ctx.slashCommands = [];
|
|
155
257
|
for (const file of commandFiles) {
|
|
156
|
-
const
|
|
258
|
+
const checkedSource = changes?.getSourceFile(file);
|
|
259
|
+
const command = processCommandFile(ctx, file, checkedSource);
|
|
157
260
|
if (command) {
|
|
158
261
|
ctx.slashCommands.push(command);
|
|
262
|
+
} else if (checkedSource && containsCommandFile(previous, file)) {
|
|
263
|
+
throw new Error(`Edited command has no supported default handler in ${file}`);
|
|
159
264
|
}
|
|
160
265
|
}
|
|
266
|
+
processSubcommands(ctx);
|
|
267
|
+
applyLocalizations(ctx);
|
|
161
268
|
}
|
|
162
|
-
function
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
269
|
+
function applyLocalizations(ctx) {
|
|
270
|
+
const localesDir = ctx.resolve.root(ctx.options.dir, "locales");
|
|
271
|
+
const localeFiles = globSync(`${localesDir}/*.json`);
|
|
272
|
+
if (localeFiles.length === 0)
|
|
273
|
+
return;
|
|
274
|
+
for (const localeFile of localeFiles) {
|
|
275
|
+
const localeName = path.parse(localeFile).name;
|
|
276
|
+
if (!validLocales.has(localeName)) {
|
|
277
|
+
ctx.logger.warn(`Unknown locale "${localeName}" in ${localeFile}, skipping. Valid locales: ${[...validLocales].join(", ")}`);
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
const locale = localeName;
|
|
281
|
+
let entries;
|
|
282
|
+
try {
|
|
283
|
+
entries = JSON.parse(readFileSync(localeFile, "utf-8"));
|
|
284
|
+
} catch {
|
|
285
|
+
ctx.logger.warn(`Failed to parse locale file: ${localeFile}`);
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
for (const [commandName, entry] of Object.entries(entries)) {
|
|
289
|
+
const command = ctx.slashCommands.find((c) => c.name === commandName);
|
|
290
|
+
if (!command) {
|
|
291
|
+
ctx.logger.warn(`Locale "${locale}": command "${commandName}" not found`);
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
if (entry.name) {
|
|
295
|
+
command.nameLocalizations ??= {};
|
|
296
|
+
command.nameLocalizations[locale] = entry.name;
|
|
297
|
+
}
|
|
298
|
+
if (entry.description) {
|
|
299
|
+
command.descriptionLocalizations ??= {};
|
|
300
|
+
command.descriptionLocalizations[locale] = entry.description;
|
|
301
|
+
}
|
|
302
|
+
if (entry.options) {
|
|
303
|
+
for (const [optionName, optionEntry] of Object.entries(entry.options)) {
|
|
304
|
+
const option = command.options.find((o) => o.name === optionName);
|
|
305
|
+
if (!option) {
|
|
306
|
+
ctx.logger.warn(`Locale "${locale}": option "${optionName}" not found in command "${commandName}"`);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (optionEntry.name) {
|
|
310
|
+
option.nameLocalizations ??= {};
|
|
311
|
+
option.nameLocalizations[locale] = optionEntry.name;
|
|
312
|
+
}
|
|
313
|
+
if (optionEntry.description) {
|
|
314
|
+
option.descriptionLocalizations ??= {};
|
|
315
|
+
option.descriptionLocalizations[locale] = optionEntry.description;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function readGuildTags(tags) {
|
|
323
|
+
const guildTags = tags.filter((tag) => tag.tagName.text === "guild");
|
|
324
|
+
if (!guildTags.length)
|
|
325
|
+
return void 0;
|
|
326
|
+
const ids = guildTags.flatMap((tag) => tag.comment?.toString().trim() || []);
|
|
327
|
+
return ids.length ? ids : true;
|
|
328
|
+
}
|
|
329
|
+
function processCommandFile(ctx, file, sourceFile = ts.createSourceFile(file, readFileSync(file).toString(), ts.ScriptTarget.Latest, true)) {
|
|
330
|
+
const commandDefinition = findCommandExport(sourceFile)?.handler;
|
|
171
331
|
if (!commandDefinition) {
|
|
172
332
|
ctx.logger.warn(`No command definition found for ${file}`);
|
|
173
333
|
return;
|
|
@@ -176,16 +336,55 @@ function processCommandFile(ctx, file) {
|
|
|
176
336
|
const command = {
|
|
177
337
|
path: file,
|
|
178
338
|
options: [],
|
|
339
|
+
subcommands: [],
|
|
179
340
|
name
|
|
180
341
|
};
|
|
181
342
|
if ((ts.isFunctionDeclaration(commandDefinition) || ts.isFunctionExpression(commandDefinition)) && !!commandDefinition.name && ts.isIdentifier(commandDefinition.name) && commandDefinition.name.escapedText) {
|
|
182
343
|
command.name = commandDefinition.name.escapedText;
|
|
183
344
|
}
|
|
345
|
+
const jsDocComment = getJSDocComment(commandDefinition);
|
|
184
346
|
const jsDocTags = getJSDocTags(commandDefinition);
|
|
185
|
-
const
|
|
186
|
-
const
|
|
347
|
+
const isBaseTag = (tag) => !tag.comment?.toString().startsWith(".");
|
|
348
|
+
const nameTag = jsDocTags.find((tag) => tag.tagName.escapedText === "name" && isBaseTag(tag));
|
|
349
|
+
const descriptionTag = jsDocTags.find((tag) => tag.tagName.escapedText === "description" && isBaseTag(tag));
|
|
187
350
|
command.name = nameTag?.comment?.toString() ?? command.name;
|
|
188
|
-
command.description = descriptionTag?.comment?.toString() ??
|
|
351
|
+
command.description = descriptionTag?.comment?.toString() ?? jsDocComment;
|
|
352
|
+
const nsfwTag = jsDocTags.find((tag) => tag.tagName.escapedText === "nsfw");
|
|
353
|
+
if (nsfwTag) {
|
|
354
|
+
command.nsfw = nsfwTag.comment?.toString().trim() !== "false";
|
|
355
|
+
}
|
|
356
|
+
const dmTag = jsDocTags.find((tag) => tag.tagName.escapedText === "dm");
|
|
357
|
+
if (dmTag) {
|
|
358
|
+
const allowDm = dmTag.comment?.toString().trim() !== "false";
|
|
359
|
+
command.contexts = allowDm ? [0, 1, 2] : [0];
|
|
360
|
+
}
|
|
361
|
+
const permissionsTag = jsDocTags.find((tag) => tag.tagName.escapedText === "defaultMemberPermissions");
|
|
362
|
+
if (permissionsTag && permissionsTag.comment) {
|
|
363
|
+
command.defaultMemberPermissions = permissionsTag.comment.toString().trim();
|
|
364
|
+
}
|
|
365
|
+
command.guilds = readGuildTags(jsDocTags);
|
|
366
|
+
const middleware = readMiddlewareTags(sourceFile, commandDefinition);
|
|
367
|
+
if (middleware.length)
|
|
368
|
+
command.middleware = middleware;
|
|
369
|
+
for (const tag of jsDocTags) {
|
|
370
|
+
const tagName = tag.tagName.escapedText;
|
|
371
|
+
const comment = tag.comment?.toString();
|
|
372
|
+
if (!comment)
|
|
373
|
+
continue;
|
|
374
|
+
if (tagName === "name" || tagName === "description") {
|
|
375
|
+
const localeMatch = comment.match(LOCALE_TAG_RE);
|
|
376
|
+
if (localeMatch) {
|
|
377
|
+
const [, locale, value] = localeMatch;
|
|
378
|
+
if (!validLocales.has(locale)) {
|
|
379
|
+
ctx.logger.warn(`Unknown locale "${locale}" in @${tagName}.${locale} for ${file}`);
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
const key = tagName === "name" ? "nameLocalizations" : "descriptionLocalizations";
|
|
383
|
+
command[key] ??= {};
|
|
384
|
+
command[key][locale] = value.trim();
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
189
388
|
if (!commandDefinition.body) {
|
|
190
389
|
ctx.logger.warn(`No body found for command definition in ${file}`);
|
|
191
390
|
return;
|
|
@@ -200,8 +399,16 @@ function processCommandFile(ctx, file) {
|
|
|
200
399
|
}
|
|
201
400
|
}
|
|
202
401
|
};
|
|
203
|
-
const getType = (type) => {
|
|
402
|
+
const getType = (type, initializer) => {
|
|
204
403
|
if (!type) {
|
|
404
|
+
if (initializer) {
|
|
405
|
+
if (ts.isNumericLiteral(initializer) || ts.isPrefixUnaryExpression(initializer) && [ts.SyntaxKind.MinusToken, ts.SyntaxKind.PlusToken].includes(initializer.operator) && ts.isNumericLiteral(initializer.operand))
|
|
406
|
+
return { type: "number" };
|
|
407
|
+
if (initializer.kind === ts.SyntaxKind.TrueKeyword || initializer.kind === ts.SyntaxKind.FalseKeyword)
|
|
408
|
+
return { type: "boolean" };
|
|
409
|
+
if (ts.isStringLiteralLike(initializer))
|
|
410
|
+
return { type: "string" };
|
|
411
|
+
}
|
|
205
412
|
ctx.logger.warn(`No type found for slash command option in ${file}, defaulting to string`);
|
|
206
413
|
return { type: "string" };
|
|
207
414
|
}
|
|
@@ -212,7 +419,7 @@ function processCommandFile(ctx, file) {
|
|
|
212
419
|
return { type: "string" };
|
|
213
420
|
}
|
|
214
421
|
const typeName2 = types.values().next().value;
|
|
215
|
-
if (!
|
|
422
|
+
if (!typeName2 || !isOptionTypeIdentifier(typeName2)) {
|
|
216
423
|
ctx.logger.warn(`Unrecognizable type ${type.getText(sourceFile)}, defaulting to string`);
|
|
217
424
|
return { type: "string" };
|
|
218
425
|
}
|
|
@@ -237,7 +444,7 @@ function processCommandFile(ctx, file) {
|
|
|
237
444
|
};
|
|
238
445
|
}
|
|
239
446
|
const typeName = type.getText(sourceFile);
|
|
240
|
-
if (typeName && typeName
|
|
447
|
+
if (typeName && isOptionTypeIdentifier(typeName)) {
|
|
241
448
|
return { type: typeName };
|
|
242
449
|
}
|
|
243
450
|
ctx.logger.warn(`Unknown slash command option type: ${type.getText(sourceFile)} in ${file}, defaulting to string`);
|
|
@@ -245,7 +452,7 @@ function processCommandFile(ctx, file) {
|
|
|
245
452
|
};
|
|
246
453
|
for (const param of commandDefinition.parameters) {
|
|
247
454
|
const name2 = param.name.getText(sourceFile);
|
|
248
|
-
let { type, choices } = getType(param.type);
|
|
455
|
+
let { type, choices } = getType(param.type, param.initializer);
|
|
249
456
|
const jsDocTagIdx = jsDocTags.findIndex((tag) => ts.isJSDocParameterTag(tag) && tag.name.getText() === name2);
|
|
250
457
|
const findModifiers = (modifiers2) => {
|
|
251
458
|
let idx = jsDocTagIdx;
|
|
@@ -262,20 +469,13 @@ function processCommandFile(ctx, file) {
|
|
|
262
469
|
return ret;
|
|
263
470
|
};
|
|
264
471
|
const jsdocDescription = jsDocTagIdx !== -1 ? jsDocTags[jsDocTagIdx].comment?.toString() ?? "" : "";
|
|
265
|
-
const modifiersMap = {
|
|
266
|
-
string: ["minLength", "maxLength", "choices"],
|
|
267
|
-
number: ["min", "max", "choices"],
|
|
268
|
-
integer: ["min", "max", "choices"],
|
|
269
|
-
boolean: []
|
|
270
|
-
};
|
|
271
472
|
const modifiers = findModifiers(modifiersMap[type]);
|
|
272
473
|
choices = choices ?? modifiers.choices;
|
|
273
474
|
command.options.push({
|
|
274
475
|
name: name2,
|
|
275
|
-
// TODO: remove this type assertion
|
|
276
476
|
type: typeIdentifierToEnum[type],
|
|
277
477
|
description: jsdocDescription,
|
|
278
|
-
required: !param.questionToken,
|
|
478
|
+
required: !param.questionToken && !param.initializer,
|
|
279
479
|
varname: name2,
|
|
280
480
|
hasAutocomplete: false,
|
|
281
481
|
...modifiers,
|
|
@@ -295,25 +495,75 @@ function processCommandFile(ctx, file) {
|
|
|
295
495
|
const macroName = macroCall.expression.escapedText;
|
|
296
496
|
macros[macroName](ctx, macroCall, command);
|
|
297
497
|
}
|
|
498
|
+
command.description ||= command.name;
|
|
298
499
|
if (outOfRangMacroCalls.length > 0) {
|
|
299
500
|
ctx.logger.warn(`Macros in file ${file} must be called at the top of the file`);
|
|
300
501
|
}
|
|
502
|
+
const commandsDir = ctx.resolve.root(ctx.options.dir, "commands");
|
|
503
|
+
const parents = path.relative(commandsDir, file).split(path.sep).slice(0, -1);
|
|
504
|
+
if (parents.length > 2) {
|
|
505
|
+
ctx.logger.warn(`Only 2 levels of subcommand nesting are supported, see https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups`);
|
|
506
|
+
return;
|
|
507
|
+
} else if (parents.length === 1) {
|
|
508
|
+
command.parents = [
|
|
509
|
+
path.resolve(commandsDir, `${parents[0]}.ts`)
|
|
510
|
+
];
|
|
511
|
+
} else if (parents.length === 2) {
|
|
512
|
+
command.parents = [
|
|
513
|
+
path.resolve(commandsDir, `${parents[0]}.ts`),
|
|
514
|
+
path.resolve(commandsDir, parents[0], `${parents[1]}.ts`)
|
|
515
|
+
];
|
|
516
|
+
} else {
|
|
517
|
+
command.parents = [];
|
|
518
|
+
}
|
|
301
519
|
return command;
|
|
302
520
|
}
|
|
303
|
-
function
|
|
304
|
-
let
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
if (
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
521
|
+
function processSubcommands(ctx) {
|
|
522
|
+
for (let i = 0; i < 2; i++) {
|
|
523
|
+
const done = [];
|
|
524
|
+
ctx.slashCommands.forEach((command, i2) => {
|
|
525
|
+
if (command.parents.length > 0) {
|
|
526
|
+
const rootCommand = ctx.slashCommands.find((c) => c.path === command.parents[0]);
|
|
527
|
+
if (rootCommand) {
|
|
528
|
+
if (command.parents.length === 1) {
|
|
529
|
+
done.unshift(i2);
|
|
530
|
+
rootCommand.subcommands.push(command);
|
|
531
|
+
} else {
|
|
532
|
+
const subcommandGroup = rootCommand.subcommands.find(
|
|
533
|
+
(c) => c.path === command.parents[1]
|
|
534
|
+
);
|
|
535
|
+
if (subcommandGroup) {
|
|
536
|
+
done.unshift(i2);
|
|
537
|
+
subcommandGroup.subcommands.push(command);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
311
541
|
}
|
|
312
|
-
}
|
|
313
|
-
|
|
542
|
+
});
|
|
543
|
+
done.forEach((i2) => ctx.slashCommands.splice(i2, 1));
|
|
544
|
+
}
|
|
545
|
+
const notProcessed = ctx.slashCommands.filter((c) => c.parents.length > 0);
|
|
546
|
+
for (const command of notProcessed) {
|
|
547
|
+
ctx.logger.warn(`Slash command ${command.name} is not processed, please create dummy parent command files:
|
|
548
|
+
${command.parents.map((p) => ` - ${p}`).join("\n")}`);
|
|
549
|
+
}
|
|
550
|
+
ctx.slashCommands = ctx.slashCommands.filter((c) => c.parents.length === 0);
|
|
551
|
+
}
|
|
552
|
+
function findCommandExport(sourceFile) {
|
|
553
|
+
for (const statement of sourceFile.statements) {
|
|
554
|
+
if (ts.isFunctionDeclaration(statement) && statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword))
|
|
555
|
+
return { statement, handler: statement };
|
|
556
|
+
if (!ts.isExportAssignment(statement) || statement.isExportEquals)
|
|
557
|
+
continue;
|
|
558
|
+
const expression = statement.expression;
|
|
559
|
+
if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression))
|
|
560
|
+
return { statement, handler: expression };
|
|
561
|
+
if (ts.isCallExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === "defineSlashCommand") {
|
|
562
|
+
const handler = expression.arguments[0];
|
|
563
|
+
if (handler && (ts.isArrowFunction(handler) || ts.isFunctionExpression(handler)))
|
|
564
|
+
return { statement, handler };
|
|
314
565
|
}
|
|
315
|
-
}
|
|
316
|
-
return commandDefinition;
|
|
566
|
+
}
|
|
317
567
|
}
|
|
318
568
|
function extractMacroCalls(definitionBody) {
|
|
319
569
|
let macrosEnd = false;
|
|
@@ -338,6 +588,17 @@ function extractMacroCalls(definitionBody) {
|
|
|
338
588
|
function isMacroCallExpression(node) {
|
|
339
589
|
return ts.isExpressionStatement(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText in macros;
|
|
340
590
|
}
|
|
591
|
+
function getJSDocComment(node) {
|
|
592
|
+
const jsDocs = ts.getJSDocCommentsAndTags(node);
|
|
593
|
+
for (const doc of jsDocs) {
|
|
594
|
+
if (ts.isJSDoc(doc) && doc.comment) {
|
|
595
|
+
return typeof doc.comment === "string" ? doc.comment : doc.comment.map((c) => c.text).join("");
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
if (node.parent) {
|
|
599
|
+
return getJSDocComment(node.parent);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
341
602
|
function getJSDocTags(node) {
|
|
342
603
|
const tags = ts.getJSDocTags(node);
|
|
343
604
|
if (tags.length > 0) {
|
|
@@ -355,115 +616,481 @@ function getJSDocTags(node) {
|
|
|
355
616
|
return [];
|
|
356
617
|
}
|
|
357
618
|
|
|
358
|
-
|
|
359
|
-
const
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
619
|
+
function collectContextMenus(ctx) {
|
|
620
|
+
const contextMenuDir = ctx.resolve.root(ctx.options.dir, "context-menus");
|
|
621
|
+
const allFiles = globSync(`${contextMenuDir}/**/*.ts`);
|
|
622
|
+
ctx.contextMenus = [];
|
|
623
|
+
for (const file of allFiles) {
|
|
624
|
+
const menu = processContextMenuFile(ctx, file);
|
|
625
|
+
if (menu) {
|
|
626
|
+
ctx.contextMenus.push(menu);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
function processContextMenuFile(ctx, file) {
|
|
631
|
+
const source = readFileSync(file, "utf-8");
|
|
632
|
+
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
|
|
633
|
+
let type;
|
|
634
|
+
let nameFromDefine;
|
|
635
|
+
ts.forEachChild(sourceFile, (node) => {
|
|
636
|
+
if (ts.isExportAssignment(node) && ts.isCallExpression(node.expression)) {
|
|
637
|
+
const call = node.expression;
|
|
638
|
+
if (ts.isIdentifier(call.expression)) {
|
|
639
|
+
const fnName = call.expression.escapedText;
|
|
640
|
+
if (fnName === "defineUserContextMenu") {
|
|
641
|
+
type = "user";
|
|
642
|
+
} else if (fnName === "defineMessageContextMenu") {
|
|
643
|
+
type = "message";
|
|
644
|
+
}
|
|
645
|
+
if (type && call.arguments.length > 0) {
|
|
646
|
+
const firstArg = call.arguments[0];
|
|
647
|
+
if (ts.isStringLiteral(firstArg)) {
|
|
648
|
+
nameFromDefine = firstArg.text;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
365
651
|
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
652
|
+
}
|
|
653
|
+
});
|
|
654
|
+
if (!type) {
|
|
655
|
+
ctx.logger.warn(`No defineUserContextMenu or defineMessageContextMenu call found in ${file}`);
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
let name = nameFromDefine;
|
|
659
|
+
if (!name) {
|
|
660
|
+
const jsDocName = getJSDocTag(sourceFile, "name");
|
|
661
|
+
if (jsDocName) {
|
|
662
|
+
name = jsDocName;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
if (!name) {
|
|
666
|
+
name = path.basename(file, ".ts");
|
|
667
|
+
}
|
|
668
|
+
const middleware = readMiddlewareTags(sourceFile);
|
|
669
|
+
const definition = sourceFile.statements.find(ts.isExportAssignment);
|
|
670
|
+
const guilds = readGuildTags(ts.getJSDocTags(definition));
|
|
671
|
+
return { name, type, path: file, ...guilds && { guilds }, ...middleware.length > 0 ? { middleware } : {} };
|
|
672
|
+
}
|
|
673
|
+
function getJSDocTag(sourceFile, tagName) {
|
|
674
|
+
let result;
|
|
675
|
+
ts.forEachChild(sourceFile, (node) => {
|
|
676
|
+
if (ts.isExportAssignment(node)) {
|
|
677
|
+
const tags = ts.getJSDocTags(node);
|
|
678
|
+
for (const tag of tags) {
|
|
679
|
+
if (tag.tagName.escapedText === tagName && tag.comment) {
|
|
680
|
+
result = tag.comment.toString().trim();
|
|
377
681
|
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
commandDefinition.name,
|
|
387
|
-
commandDefinition.typeParameters,
|
|
388
|
-
commandDefinition.parameters,
|
|
389
|
-
commandDefinition.type,
|
|
390
|
-
commandDefinition.body
|
|
391
|
-
);
|
|
392
|
-
}
|
|
393
|
-
commandDefinition = commandDefinition;
|
|
394
|
-
const [macroCalls] = extractMacroCalls(commandDefinition.body);
|
|
395
|
-
if (ts.isBlock(commandDefinition.body)) {
|
|
396
|
-
if (isFunctionExpression(commandDefinition)) {
|
|
397
|
-
commandDefinition = ts.factory.createFunctionExpression(
|
|
398
|
-
commandDefinition.modifiers,
|
|
399
|
-
commandDefinition.asteriskToken,
|
|
400
|
-
commandDefinition.name,
|
|
401
|
-
commandDefinition.typeParameters,
|
|
402
|
-
commandDefinition.parameters,
|
|
403
|
-
commandDefinition.type,
|
|
404
|
-
ts.factory.createBlock(
|
|
405
|
-
commandDefinition.body.statements.filter((s) => !isMacroCallExpression(s)),
|
|
406
|
-
true
|
|
407
|
-
)
|
|
408
|
-
);
|
|
409
|
-
} else if (isArrowFunction(commandDefinition)) {
|
|
410
|
-
commandDefinition = ts.factory.createArrowFunction(
|
|
411
|
-
commandDefinition.modifiers,
|
|
412
|
-
commandDefinition.typeParameters,
|
|
413
|
-
commandDefinition.parameters,
|
|
414
|
-
commandDefinition.type,
|
|
415
|
-
commandDefinition.equalsGreaterThanToken,
|
|
416
|
-
ts.factory.createBlock(
|
|
417
|
-
commandDefinition.body.statements.filter((s) => !isMacroCallExpression(s)),
|
|
418
|
-
true
|
|
419
|
-
)
|
|
420
|
-
);
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
return ts.factory.createExportAssignment(
|
|
424
|
-
[],
|
|
425
|
-
false,
|
|
426
|
-
ts.factory.createObjectLiteralExpression([
|
|
427
|
-
ts.factory.createPropertyAssignment("execute", commandDefinition),
|
|
428
|
-
ts.factory.createPropertyAssignment(
|
|
429
|
-
"optionMacros",
|
|
430
|
-
ts.factory.createObjectLiteralExpression(
|
|
431
|
-
macroCalls.filter((m) => m.expression.escapedText === "describeOption" && ts.isIdentifier(m.arguments[0]) && m.arguments.length > 1).map((m) => ts.factory.createPropertyAssignment(m.arguments[0].escapedText, m.arguments[1]))
|
|
432
|
-
)
|
|
433
|
-
)
|
|
434
|
-
])
|
|
435
|
-
);
|
|
682
|
+
}
|
|
683
|
+
if (!result) {
|
|
684
|
+
const comments = ts.getJSDocCommentsAndTags(node);
|
|
685
|
+
for (const doc of comments) {
|
|
686
|
+
if (ts.isJSDoc(doc) && doc.tags) {
|
|
687
|
+
for (const tag of doc.tags) {
|
|
688
|
+
if (tag.tagName.escapedText === tagName && tag.comment) {
|
|
689
|
+
result = tag.comment.toString().trim();
|
|
436
690
|
}
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
});
|
|
697
|
+
return result;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function collectListeners(ctx) {
|
|
701
|
+
const listenersDir = ctx.resolve.root(ctx.options.dir, "listeners");
|
|
702
|
+
const listenerFiles = globSync(`${listenersDir}/**/*.ts`);
|
|
703
|
+
ctx.listeners = [];
|
|
704
|
+
for (const file of listenerFiles) {
|
|
705
|
+
const listener = processListenerFile(ctx, file);
|
|
706
|
+
if (listener) {
|
|
707
|
+
ctx.listeners.push(listener);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
function processListenerFile(ctx, file) {
|
|
712
|
+
const source = readFileSync(file, "utf-8");
|
|
713
|
+
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
|
|
714
|
+
let event;
|
|
715
|
+
let once = false;
|
|
716
|
+
ts.forEachChild(sourceFile, (node) => {
|
|
717
|
+
if (ts.isExportAssignment(node) && ts.isCallExpression(node.expression)) {
|
|
718
|
+
const call = node.expression;
|
|
719
|
+
if (ts.isIdentifier(call.expression) && call.expression.escapedText === "defineListener") {
|
|
720
|
+
const firstArg = call.arguments[0];
|
|
721
|
+
if (firstArg && ts.isStringLiteral(firstArg)) {
|
|
722
|
+
event = firstArg.text;
|
|
723
|
+
}
|
|
724
|
+
const thirdArg = call.arguments[2];
|
|
725
|
+
if (thirdArg && ts.isObjectLiteralExpression(thirdArg)) {
|
|
726
|
+
for (const prop of thirdArg.properties) {
|
|
727
|
+
if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.escapedText === "once" && prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
|
|
728
|
+
once = true;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
if (!event) {
|
|
736
|
+
ctx.logger.warn(`No defineListener call found in ${file}`);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
return { path: file, event, once };
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
const registry = '(globalThis[Symbol.for("nuxt-discord.hmr.modules")] ??= new Map())';
|
|
743
|
+
const livePrefix = "\0discord:live:";
|
|
744
|
+
const registryEntry = "\0discord:hot-registry";
|
|
745
|
+
function captureCommandImports(rootDir, buildDir, runtimeDir, publish) {
|
|
746
|
+
const importsByModule = /* @__PURE__ */ new Map();
|
|
747
|
+
return {
|
|
748
|
+
name: "discord:capture-command-imports",
|
|
749
|
+
transform: {
|
|
750
|
+
order: "post",
|
|
751
|
+
async handler(code, id) {
|
|
752
|
+
const projectFile = id.startsWith(rootDir + path.sep) && !id.startsWith(buildDir + path.sep) && !id.includes("/node_modules/");
|
|
753
|
+
if (!projectFile && !id.startsWith(runtimeDir + path.sep) && !id.endsWith("discord/slashCommands"))
|
|
754
|
+
return;
|
|
755
|
+
const sources = new Set(ts.preProcessFile(code, true).importedFiles.map((file) => file.fileName));
|
|
756
|
+
const lines = [];
|
|
757
|
+
const ids = [];
|
|
758
|
+
for (const source of sources) {
|
|
759
|
+
const resolved = await this.resolve(source, id);
|
|
760
|
+
if (!resolved || resolved.external)
|
|
761
|
+
continue;
|
|
762
|
+
ids.push(resolved.id);
|
|
763
|
+
lines.push(`;${registry}.set(${JSON.stringify(resolved.id)}, () => import(${JSON.stringify(source)}))`);
|
|
764
|
+
}
|
|
765
|
+
importsByModule.set(id, ids);
|
|
766
|
+
if (lines.length)
|
|
767
|
+
return { code: `${code}
|
|
768
|
+
${lines.join("\n")}`, map: null };
|
|
769
|
+
}
|
|
770
|
+
},
|
|
771
|
+
writeBundle() {
|
|
772
|
+
const ids = /* @__PURE__ */ new Set();
|
|
773
|
+
const visited = /* @__PURE__ */ new Set();
|
|
774
|
+
const visit = (id) => {
|
|
775
|
+
const info = this.getModuleInfo(id);
|
|
776
|
+
if (visited.has(id) || !info?.isIncluded)
|
|
777
|
+
return;
|
|
778
|
+
visited.add(id);
|
|
779
|
+
importsByModule.get(id)?.forEach((dep) => ids.add(dep));
|
|
780
|
+
info.importedIds.forEach(visit);
|
|
781
|
+
};
|
|
782
|
+
for (const id of this.getModuleIds()) {
|
|
783
|
+
if (id.endsWith("discord/slashCommands") || this.getModuleInfo(id)?.isEntry)
|
|
784
|
+
visit(id);
|
|
785
|
+
}
|
|
786
|
+
publish(ids);
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
function reuseCommandDependencies(entries, updated, changed) {
|
|
791
|
+
return {
|
|
792
|
+
name: "discord:reuse-command-imports",
|
|
793
|
+
resolveId: {
|
|
794
|
+
order: "pre",
|
|
795
|
+
async handler(source, importer, options) {
|
|
796
|
+
if (!importer || source.startsWith(livePrefix))
|
|
797
|
+
return;
|
|
798
|
+
const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
|
|
799
|
+
if (!resolved || resolved.id.startsWith(livePrefix) || changed.has(resolved.id))
|
|
800
|
+
return resolved;
|
|
801
|
+
const url = updated.get(resolved.id);
|
|
802
|
+
if (url)
|
|
803
|
+
return { id: url, external: true };
|
|
804
|
+
return entries.has(resolved.id) ? livePrefix + resolved.id : resolved;
|
|
805
|
+
}
|
|
806
|
+
},
|
|
807
|
+
load(id) {
|
|
808
|
+
if (id.startsWith(livePrefix)) {
|
|
809
|
+
return {
|
|
810
|
+
code: `export const __discordNamespace = await ${registry}.get(${JSON.stringify(id.slice(livePrefix.length))})(); export default __discordNamespace.default`,
|
|
811
|
+
syntheticNamedExports: "__discordNamespace"
|
|
441
812
|
};
|
|
442
|
-
const res = ts.transform(sourceFile, [transformer]);
|
|
443
|
-
const printer = ts.createPrinter({
|
|
444
|
-
newLine: ts.NewLineKind.LineFeed,
|
|
445
|
-
removeComments: false
|
|
446
|
-
});
|
|
447
|
-
const transformed = printer.printFile(res.transformed[0]);
|
|
448
|
-
return transformed;
|
|
449
|
-
} catch {
|
|
450
|
-
return null;
|
|
451
813
|
}
|
|
452
814
|
}
|
|
453
815
|
};
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
function prepareTemplates(ctx) {
|
|
819
|
+
addServerTemplate({
|
|
820
|
+
filename: "discord/catalog",
|
|
821
|
+
getContents: () => {
|
|
822
|
+
const catalog = { commands: ctx.slashCommands, menus: ctx.contextMenus, listeners: ctx.listeners };
|
|
823
|
+
return `export default ${JSON.stringify(catalog, (key, value) => key === "path" && !ctx.nuxt.options.dev ? relative(ctx.nuxt.options.rootDir, value).split(sep).join("/") : value)}`;
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
addServerTemplate({
|
|
827
|
+
filename: "discord/slashCommands",
|
|
828
|
+
getContents: () => getSlashCommandTemplateContent(
|
|
829
|
+
ctx,
|
|
830
|
+
/* commandRuntime */
|
|
831
|
+
true
|
|
832
|
+
)
|
|
833
|
+
});
|
|
834
|
+
addTemplate({
|
|
835
|
+
filename: "discord/slashCommands",
|
|
836
|
+
getContents: () => getSlashCommandTemplateContent(
|
|
837
|
+
ctx,
|
|
838
|
+
/* commandRuntime */
|
|
839
|
+
false
|
|
840
|
+
)
|
|
841
|
+
});
|
|
842
|
+
addServerTemplate({
|
|
843
|
+
filename: "discord/contextMenus",
|
|
844
|
+
getContents: () => {
|
|
845
|
+
if (ctx.contextMenus.length === 0) {
|
|
846
|
+
return "export default []";
|
|
847
|
+
}
|
|
848
|
+
const entries = ctx.contextMenus.map((cm, i) => {
|
|
849
|
+
const varName = `cm_${i}`;
|
|
850
|
+
return {
|
|
851
|
+
importLine: `import ${varName} from '${cm.path}'`,
|
|
852
|
+
entry: `{ ...${varName}, name: ${JSON.stringify(cm.name)}, middleware: ${JSON.stringify(cm.middleware ?? [])}, guilds: ${JSON.stringify(cm.guilds)}, path: ${JSON.stringify(cm.path)} }`
|
|
853
|
+
};
|
|
854
|
+
});
|
|
855
|
+
return [
|
|
856
|
+
...entries.map((e) => e.importLine),
|
|
857
|
+
`export default [${entries.map((e) => e.entry).join(", ")}]`
|
|
858
|
+
].join("\n");
|
|
859
|
+
}
|
|
860
|
+
});
|
|
861
|
+
addTemplate({
|
|
862
|
+
filename: "discord/contextMenus",
|
|
863
|
+
getContents: () => {
|
|
864
|
+
return `export default ${JSON.stringify(ctx.contextMenus.map((cm) => ({
|
|
865
|
+
name: cm.name,
|
|
866
|
+
type: cm.type,
|
|
867
|
+
guilds: cm.guilds,
|
|
868
|
+
path: cm.path
|
|
869
|
+
})))}`;
|
|
870
|
+
}
|
|
871
|
+
});
|
|
872
|
+
addServerTemplate({
|
|
873
|
+
filename: "discord/listeners",
|
|
874
|
+
getContents: () => {
|
|
875
|
+
if (ctx.listeners.length === 0) {
|
|
876
|
+
return "export default []";
|
|
877
|
+
}
|
|
878
|
+
const imports = ctx.listeners.map((l, i) => {
|
|
879
|
+
const name = `listener_${i}`;
|
|
880
|
+
return { name, code: `import ${name} from '${l.path}'` };
|
|
881
|
+
});
|
|
882
|
+
return [
|
|
883
|
+
...imports.map((i) => i.code),
|
|
884
|
+
`export default [${imports.map((i) => i.name).join(", ")}]`
|
|
885
|
+
].join("\n");
|
|
886
|
+
}
|
|
887
|
+
});
|
|
888
|
+
addTemplate({
|
|
889
|
+
filename: "discord/listeners",
|
|
890
|
+
getContents: () => {
|
|
891
|
+
return `export default ${JSON.stringify(ctx.listeners.map((l) => ({
|
|
892
|
+
event: l.event,
|
|
893
|
+
once: l.once ?? false,
|
|
894
|
+
path: l.path
|
|
895
|
+
})))}`;
|
|
896
|
+
}
|
|
897
|
+
});
|
|
898
|
+
addTypeTemplate({
|
|
899
|
+
filename: "discord/types.d.ts",
|
|
900
|
+
getContents: () => `
|
|
901
|
+
declare module 'discord/catalog' {
|
|
902
|
+
const catalog: import('nuxt-discord').DashboardCatalog
|
|
903
|
+
export default catalog
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
declare module 'discord/slashCommands' {
|
|
907
|
+
const slashCommands: import('nuxt-discord').SlashCommandRuntime[]
|
|
908
|
+
export default slashCommands
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
declare module '#build/discord/slashCommands' {
|
|
912
|
+
const slashCommands: import('nuxt-discord').SlashCommand[]
|
|
913
|
+
export default slashCommands
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
declare module '#build/discord/contextMenus' {
|
|
917
|
+
const contextMenus: import('nuxt-discord').ContextMenu[]
|
|
918
|
+
export default contextMenus
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
declare module '#build/discord/listeners' {
|
|
922
|
+
const listeners: import('nuxt-discord').Listener[]
|
|
923
|
+
export default listeners
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
declare module 'discord/contextMenus' {
|
|
927
|
+
const contextMenus: (import('nuxt-discord/types').ContextMenuDefinition & { name: string, path: string })[]
|
|
928
|
+
export default contextMenus
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
declare module 'discord/listeners' {
|
|
932
|
+
const listeners: import('nuxt-discord/types').ListenerDefinition[]
|
|
933
|
+
export default listeners
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
type integer = import('nuxt-discord').integer
|
|
937
|
+
`
|
|
938
|
+
}, { nuxt: true, nitro: true });
|
|
939
|
+
addTypeTemplate({
|
|
940
|
+
filename: "discord/augmentations.d.ts",
|
|
941
|
+
getContents: () => `
|
|
942
|
+
import type { DiscordClient, DiscordClientError, DiscordRuntimeConfig, NuxtDiscordOptions } from 'nuxt-discord/types'
|
|
943
|
+
import type { Interaction } from 'discord.js'
|
|
944
|
+
|
|
945
|
+
declare module 'nitropack/types' {
|
|
946
|
+
interface NitroRuntimeHooks {
|
|
947
|
+
'discord:client:config': (options: NuxtDiscordOptions['client']) => void
|
|
948
|
+
'discord:client:ready': (client: DiscordClient) => void
|
|
949
|
+
'discord:client:error': (error: DiscordClientError) => void
|
|
950
|
+
'discord:interaction:before': (ctx: { interaction: Interaction, type: 'command' | 'context-menu' }) => void
|
|
951
|
+
'discord:interaction:after': (ctx: { interaction: Interaction, type: 'command' | 'context-menu', status: 'ok' | 'denied' | 'error', detail?: string }) => void
|
|
952
|
+
'discord:interaction:denied': (ctx: { interaction: Interaction, type: 'command' | 'context-menu', reason: string, middleware: string }) => void
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
declare module '@nuxt/schema' {
|
|
957
|
+
interface RuntimeConfig {
|
|
958
|
+
discord: DiscordRuntimeConfig
|
|
959
|
+
}
|
|
960
|
+
interface PublicRuntimeConfig {
|
|
961
|
+
discord: { wsUrl?: string }
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
`
|
|
965
|
+
}, { nuxt: true, nitro: true });
|
|
966
|
+
}
|
|
967
|
+
function getSlashCommandTemplateContent(ctx, commandRuntime) {
|
|
968
|
+
const imports = commandRuntime ? Object.fromEntries(ctx.slashCommands.flatMap(
|
|
969
|
+
function getImports(cmd) {
|
|
970
|
+
const name = genSafeVariableName(cmd.path);
|
|
971
|
+
return [
|
|
972
|
+
[cmd.path, { name, code: genImport(cmd.path, [{ name: "default", as: name }]) }],
|
|
973
|
+
..."subcommands" in cmd ? cmd.subcommands.flatMap(getImports) : []
|
|
974
|
+
];
|
|
975
|
+
}
|
|
976
|
+
)) : {};
|
|
977
|
+
return [
|
|
978
|
+
...Object.values(imports).map(({ code }) => code),
|
|
979
|
+
`export default [
|
|
980
|
+
${ctx.slashCommands.map((cmd) => genCommandObject(cmd)).join(",\n")}]`
|
|
981
|
+
].join("\n");
|
|
982
|
+
function genCommandObject({
|
|
983
|
+
options,
|
|
984
|
+
parents,
|
|
985
|
+
subcommands,
|
|
986
|
+
...rest
|
|
987
|
+
}) {
|
|
988
|
+
return ` {
|
|
989
|
+
${Object.entries(rest).filter(([, v]) => v !== void 0).map(([key, value]) => `${key}: ${typeof value === "string" ? genString(value) : JSON.stringify(value)}`).join(",\n ")},
|
|
990
|
+
options: ${genArrayFromRaw(options, void 0, { preserveTypes: true })},
|
|
991
|
+
${subcommands.length > 0 ? `subcommands: [${subcommands.map(genCommandObject).join(",")}],` : ""}
|
|
992
|
+
${commandRuntime ? `...${imports[rest.path].name},` : ""}
|
|
993
|
+
}`;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
const TransformPlugin = (ctx) => {
|
|
998
|
+
const commandsDir = `${ctx.resolve.root(ctx.options.dir, "commands").split(path.sep).join("/")}/`;
|
|
999
|
+
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
|
|
1000
|
+
return {
|
|
1001
|
+
name: "transform-slash-commands",
|
|
1002
|
+
load(id) {
|
|
1003
|
+
if (!id.split(path.sep).join("/").startsWith(commandsDir) || !id.endsWith(".ts"))
|
|
1004
|
+
return;
|
|
1005
|
+
const source = ts.createSourceFile(id, fs.readFileSync(id, "utf-8"), ts.ScriptTarget.Latest, true);
|
|
1006
|
+
const command = findCommandExport(source);
|
|
1007
|
+
if (!command || !command.handler.body)
|
|
1008
|
+
return;
|
|
1009
|
+
const runtime = createRuntimeExport(command.handler, command.handler.body);
|
|
1010
|
+
const statements = source.statements.map((statement) => statement === command.statement ? runtime : statement);
|
|
1011
|
+
return printer.printFile(ts.factory.updateSourceFile(source, statements));
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
454
1014
|
};
|
|
1015
|
+
function createRuntimeExport(handler, originalBody) {
|
|
1016
|
+
const [macroCalls] = extractMacroCalls(originalBody);
|
|
1017
|
+
const body = ts.isBlock(originalBody) ? ts.factory.updateBlock(originalBody, originalBody.statements.filter((statement) => !isMacroCallExpression(statement))) : originalBody;
|
|
1018
|
+
let execute;
|
|
1019
|
+
if (ts.isArrowFunction(handler)) {
|
|
1020
|
+
execute = ts.factory.updateArrowFunction(handler, handler.modifiers, handler.typeParameters, handler.parameters, handler.type, handler.equalsGreaterThanToken, body);
|
|
1021
|
+
} else {
|
|
1022
|
+
execute = ts.factory.createFunctionExpression(
|
|
1023
|
+
ts.getModifiers(handler)?.filter((modifier) => modifier.kind !== ts.SyntaxKind.ExportKeyword && modifier.kind !== ts.SyntaxKind.DefaultKeyword),
|
|
1024
|
+
handler.asteriskToken,
|
|
1025
|
+
handler.name,
|
|
1026
|
+
handler.typeParameters,
|
|
1027
|
+
handler.parameters,
|
|
1028
|
+
handler.type,
|
|
1029
|
+
body
|
|
1030
|
+
// Function declarations and function expressions always have a block body.
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
const middlewareCalls = macroCalls.filter((m) => m.expression.escapedText === "useMiddleware" && m.arguments.length >= 1);
|
|
1034
|
+
const middlewareEntries = middlewareCalls.map((m) => {
|
|
1035
|
+
const ref = m.arguments[0];
|
|
1036
|
+
const props = [
|
|
1037
|
+
ts.factory.createPropertyAssignment("name", ts.factory.createPropertyAccessExpression(ref, "name")),
|
|
1038
|
+
ts.factory.createPropertyAssignment("fn", ts.factory.createPropertyAccessExpression(ref, "fn"))
|
|
1039
|
+
];
|
|
1040
|
+
if (m.arguments.length > 1) {
|
|
1041
|
+
props.push(ts.factory.createPropertyAssignment("options", m.arguments[1]));
|
|
1042
|
+
}
|
|
1043
|
+
return ts.factory.createObjectLiteralExpression(props);
|
|
1044
|
+
});
|
|
1045
|
+
return ts.factory.createExportAssignment(
|
|
1046
|
+
[],
|
|
1047
|
+
false,
|
|
1048
|
+
ts.factory.createObjectLiteralExpression([
|
|
1049
|
+
ts.factory.createPropertyAssignment("execute", execute),
|
|
1050
|
+
ts.factory.createPropertyAssignment(
|
|
1051
|
+
"optionMacros",
|
|
1052
|
+
ts.factory.createObjectLiteralExpression(
|
|
1053
|
+
macroCalls.filter((m) => m.expression.escapedText === "describeOption" && m.arguments.length > 1 && ts.isIdentifier(m.arguments[0])).map((m) => ts.factory.createPropertyAssignment(m.arguments[0].escapedText, m.arguments[1]))
|
|
1054
|
+
)
|
|
1055
|
+
),
|
|
1056
|
+
...middlewareEntries.length > 0 ? [ts.factory.createPropertyAssignment(
|
|
1057
|
+
"middlewareEntries",
|
|
1058
|
+
ts.factory.createArrayLiteralExpression(middlewareEntries)
|
|
1059
|
+
)] : []
|
|
1060
|
+
])
|
|
1061
|
+
);
|
|
1062
|
+
}
|
|
455
1063
|
|
|
456
1064
|
function prepareHMR(ctx) {
|
|
457
1065
|
const { nuxt, options } = ctx;
|
|
458
|
-
|
|
459
|
-
|
|
1066
|
+
const watching = nuxt.options.dev && options.watch.enabled;
|
|
1067
|
+
const commandsDir = ctx.resolve.root(options.dir, "commands") + path.sep;
|
|
1068
|
+
const hotDir = path.join(nuxt.options.buildDir, "discord", "hmr");
|
|
1069
|
+
let dependencies = /* @__PURE__ */ new Set();
|
|
1070
|
+
const updated = /* @__PURE__ */ new Map();
|
|
1071
|
+
let revision = 0;
|
|
1072
|
+
let nextRevision = 0;
|
|
1073
|
+
let rollupConfig;
|
|
1074
|
+
nuxt.hook("nitro:init", (nitro) => {
|
|
1075
|
+
nitro.hooks.hook("rollup:before", (_nitro, config) => {
|
|
1076
|
+
config.plugins = [config.plugins, TransformPlugin(ctx)];
|
|
1077
|
+
if (watching) {
|
|
1078
|
+
rollupConfig = { ...config, plugins: config.plugins };
|
|
1079
|
+
config.plugins = [config.plugins, captureCommandImports(nuxt.options.rootDir, nuxt.options.buildDir, ctx.resolve.module("runtime/server"), (ids) => {
|
|
1080
|
+
dependencies = ids;
|
|
1081
|
+
updated.clear();
|
|
1082
|
+
revision = 0;
|
|
1083
|
+
})];
|
|
1084
|
+
}
|
|
1085
|
+
});
|
|
1086
|
+
});
|
|
1087
|
+
if (watching) {
|
|
460
1088
|
const ignoreCommandsDir = (file) => {
|
|
461
|
-
if (file.startsWith(commandsDir)) {
|
|
1089
|
+
if (file === commandsDir.slice(0, -1) || file.startsWith(commandsDir)) {
|
|
462
1090
|
return true;
|
|
463
1091
|
}
|
|
464
1092
|
return isIgnored(file);
|
|
465
1093
|
};
|
|
466
|
-
let rollupConfig;
|
|
467
1094
|
nuxt.hook("nitro:config", (nitroConfig) => {
|
|
468
1095
|
nitroConfig.watchOptions ??= {};
|
|
469
1096
|
const existingNitroIgnored = nitroConfig.watchOptions.ignored;
|
|
@@ -475,18 +1102,6 @@ function prepareHMR(ctx) {
|
|
|
475
1102
|
nitroIgnored.push(existingNitroIgnored);
|
|
476
1103
|
}
|
|
477
1104
|
nitroConfig.watchOptions.ignored = nitroIgnored;
|
|
478
|
-
const originalBeforeHook = nitroConfig.hooks?.["rollup:before"];
|
|
479
|
-
nitroConfig.hooks = {
|
|
480
|
-
...nitroConfig.hooks,
|
|
481
|
-
"rollup:before": (nitroCtx, config) => {
|
|
482
|
-
originalBeforeHook?.(nitroCtx, config);
|
|
483
|
-
config.plugins = [
|
|
484
|
-
config.plugins,
|
|
485
|
-
TransformPlugin(ctx)
|
|
486
|
-
];
|
|
487
|
-
rollupConfig = config;
|
|
488
|
-
}
|
|
489
|
-
};
|
|
490
1105
|
});
|
|
491
1106
|
nuxt.options.vite.server ??= {};
|
|
492
1107
|
nuxt.options.vite.server.watch ??= {};
|
|
@@ -503,78 +1118,132 @@ function prepareHMR(ctx) {
|
|
|
503
1118
|
let websocket;
|
|
504
1119
|
let listener;
|
|
505
1120
|
const websocketOptions = options.watch || {};
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
}
|
|
523
|
-
});
|
|
1121
|
+
nuxt.hook("nitro:init", async (nitro) => {
|
|
1122
|
+
websocket = createWebSocket();
|
|
1123
|
+
await rm(hotDir, { recursive: true, force: true });
|
|
1124
|
+
listener = await listen(() => "Nuxt Discord", websocketOptions);
|
|
1125
|
+
nitro.options.runtimeConfig.public.discord = {
|
|
1126
|
+
wsUrl: listener.url.replace("http", "ws")
|
|
1127
|
+
};
|
|
1128
|
+
listener.server.on("upgrade", websocket.serve);
|
|
1129
|
+
websocket.on("full-update", (client) => {
|
|
1130
|
+
try {
|
|
1131
|
+
client.send(JSON.stringify({
|
|
1132
|
+
event: "full-update",
|
|
1133
|
+
commands: ctx.slashCommands
|
|
1134
|
+
}));
|
|
1135
|
+
} catch {
|
|
1136
|
+
}
|
|
524
1137
|
});
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
1138
|
+
websocket.on("command-revision", (client) => {
|
|
1139
|
+
if (revision)
|
|
1140
|
+
client.send(JSON.stringify({ event: "command-revision", revision }));
|
|
1141
|
+
});
|
|
1142
|
+
websocket.on("registration-updated", () => websocket.broadcast({ event: "registration-updated" }));
|
|
1143
|
+
websocket.on("activity", (_client, message) => {
|
|
1144
|
+
websocket.broadcast(message);
|
|
1145
|
+
});
|
|
1146
|
+
});
|
|
1147
|
+
const dirty = /* @__PURE__ */ new Set();
|
|
1148
|
+
const modified = /* @__PURE__ */ new Set();
|
|
1149
|
+
nuxt.hook("nitro:init", (nitro) => {
|
|
1150
|
+
nitro.hooks.hook("compiled", () => {
|
|
1151
|
+
modified.forEach((file) => dirty.add(file));
|
|
1152
|
+
void rebuild();
|
|
1153
|
+
});
|
|
1154
|
+
});
|
|
1155
|
+
let building = false;
|
|
1156
|
+
let closed = false;
|
|
1157
|
+
async function rebuild() {
|
|
1158
|
+
if (building || !rollupConfig || closed)
|
|
531
1159
|
return;
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
1160
|
+
building = true;
|
|
1161
|
+
try {
|
|
1162
|
+
while (dirty.size) {
|
|
1163
|
+
if (closed)
|
|
1164
|
+
return;
|
|
1165
|
+
const changed = new Set(dirty);
|
|
1166
|
+
dirty.clear();
|
|
1167
|
+
const version = ++nextRevision;
|
|
1168
|
+
const initial = dependencies;
|
|
1169
|
+
const outputDir = path.join(hotDir, String(version));
|
|
1170
|
+
try {
|
|
1171
|
+
const snapshot = { ...ctx };
|
|
1172
|
+
collectSlashCommands(snapshot, changed);
|
|
1173
|
+
const source = getSlashCommandTemplateContent(snapshot, true);
|
|
1174
|
+
const additions = await buildCommandUpdate(rollupConfig, source, outputDir, initial, updated, changed);
|
|
1175
|
+
if (initial !== dependencies || closed) {
|
|
1176
|
+
changed.forEach((file) => dirty.add(file));
|
|
1177
|
+
continue;
|
|
1178
|
+
}
|
|
1179
|
+
ctx.slashCommands = snapshot.slashCommands;
|
|
1180
|
+
for (const id of changed)
|
|
1181
|
+
updated.delete(id);
|
|
1182
|
+
additions.forEach((url, id) => updated.set(id, url));
|
|
1183
|
+
revision = version;
|
|
1184
|
+
websocket?.broadcast({ event: "command-revision", revision });
|
|
1185
|
+
websocket?.broadcast({ event: "full-update", commands: ctx.slashCommands });
|
|
1186
|
+
await updateTemplates({ filter: (template) => template.filename === "discord/slashCommands" });
|
|
1187
|
+
} catch (error) {
|
|
1188
|
+
ctx.logger.error("Could not reload slash commands:", error);
|
|
1189
|
+
const retry = dirty.size > 0;
|
|
1190
|
+
changed.forEach((file) => dirty.add(file));
|
|
1191
|
+
if (!retry)
|
|
1192
|
+
break;
|
|
1193
|
+
}
|
|
540
1194
|
}
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
1195
|
+
} finally {
|
|
1196
|
+
building = false;
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
const watcher = chokidar.watch(commandsDir, { ignoreInitial: true }).on("all", (event, file) => {
|
|
1200
|
+
if (["add", "change", "unlink"].includes(event) && file.endsWith(".ts")) {
|
|
1201
|
+
const id = path.resolve(file).split(path.sep).join("/");
|
|
1202
|
+
dirty.add(id);
|
|
1203
|
+
modified.add(id);
|
|
1204
|
+
void rebuild();
|
|
545
1205
|
}
|
|
546
1206
|
});
|
|
547
|
-
nuxt.hook("close", () => {
|
|
1207
|
+
nuxt.hook("close", async () => {
|
|
1208
|
+
closed = true;
|
|
1209
|
+
await watcher.close();
|
|
548
1210
|
listener?.server.close();
|
|
549
1211
|
websocket?.close();
|
|
550
1212
|
});
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
async function buildCommandUpdate(config, source, outputDir, dependencies, updated, changed) {
|
|
1216
|
+
const additions = /* @__PURE__ */ new Map();
|
|
1217
|
+
const bundle = await rollup({
|
|
1218
|
+
...config,
|
|
1219
|
+
input: registryEntry,
|
|
1220
|
+
treeshake: false,
|
|
1221
|
+
preserveEntrySignatures: "strict",
|
|
1222
|
+
plugins: [
|
|
1223
|
+
{ name: "discord:hot-registry", resolveId: (id) => id === registryEntry ? id : null, load: (id) => id === registryEntry ? source : null },
|
|
1224
|
+
reuseCommandDependencies(dependencies, updated, changed),
|
|
1225
|
+
config.plugins
|
|
1226
|
+
]
|
|
1227
|
+
});
|
|
1228
|
+
try {
|
|
1229
|
+
const { output } = await bundle.write({
|
|
1230
|
+
...config.output,
|
|
1231
|
+
dir: outputDir,
|
|
1232
|
+
entryFileNames: (chunk) => chunk.facadeModuleId === registryEntry ? "commands.mjs" : "[name]-[hash].mjs",
|
|
1233
|
+
inlineDynamicImports: false,
|
|
1234
|
+
preserveModules: true,
|
|
1235
|
+
minifyInternalExports: false,
|
|
1236
|
+
manualChunks: void 0,
|
|
1237
|
+
sourcemap: false
|
|
1238
|
+
});
|
|
1239
|
+
for (const chunk of output) {
|
|
1240
|
+
if (chunk.type === "chunk" && chunk.facadeModuleId)
|
|
1241
|
+
additions.set(chunk.facadeModuleId, pathToFileURL(path.join(outputDir, chunk.fileName)).href);
|
|
576
1242
|
}
|
|
1243
|
+
} finally {
|
|
1244
|
+
await bundle.close();
|
|
577
1245
|
}
|
|
1246
|
+
return additions;
|
|
578
1247
|
}
|
|
579
1248
|
function createWebSocket() {
|
|
580
1249
|
const wss = new WebSocketServer({ noServer: true });
|
|
@@ -623,33 +1292,6 @@ function createWebSocket() {
|
|
|
623
1292
|
}
|
|
624
1293
|
};
|
|
625
1294
|
}
|
|
626
|
-
async function generateDynamicCommandBuild(file, config, ctx) {
|
|
627
|
-
let bundle;
|
|
628
|
-
try {
|
|
629
|
-
bundle = await rollup({
|
|
630
|
-
...config,
|
|
631
|
-
input: file,
|
|
632
|
-
plugins: [
|
|
633
|
-
config.plugins,
|
|
634
|
-
{
|
|
635
|
-
name: "discord:resolve-alias-and-externalize",
|
|
636
|
-
resolveId: (id) => {
|
|
637
|
-
if (!id.includes(file) && !id.endsWith(".ts")) {
|
|
638
|
-
return { id: resolveAlias(id), external: true };
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
]
|
|
643
|
-
});
|
|
644
|
-
const { output } = await bundle.generate({ ...config.output, sourcemap: false });
|
|
645
|
-
fs.mkdirSync(path.join(ctx.nuxt.options.buildDir, "discord", "commands"), { recursive: true });
|
|
646
|
-
fs.writeFileSync(file.replace(ctx.resolve.root(ctx.nuxt.options.rootDir), ctx.nuxt.options.buildDir).replace(".ts", ".mjs"), output[0].code, { encoding: "utf-8", flush: true });
|
|
647
|
-
} catch (error) {
|
|
648
|
-
ctx.logger.error(`Error processing command file ${file}:`, error);
|
|
649
|
-
return;
|
|
650
|
-
}
|
|
651
|
-
await bundle.close();
|
|
652
|
-
}
|
|
653
1295
|
|
|
654
1296
|
function prepareRuntimeConfig(ctx) {
|
|
655
1297
|
ctx.nuxt.hook("nitro:config", (config) => {
|
|
@@ -658,92 +1300,34 @@ function prepareRuntimeConfig(ctx) {
|
|
|
658
1300
|
config.runtimeConfig.discord.client = ctx.options.client;
|
|
659
1301
|
config.runtimeConfig.discord.autoStart = ctx.options.autoStart;
|
|
660
1302
|
config.runtimeConfig.discord.sync = ctx.options.watch.sync ?? false;
|
|
1303
|
+
config.runtimeConfig.discord.guilds = ctx.options.guilds ?? [];
|
|
661
1304
|
config.runtimeConfig.discord.dir = ctx.resolve.root(ctx.options.dir);
|
|
662
1305
|
config.runtimeConfig.discord.buildDir = ctx.nuxt.options.buildDir;
|
|
663
1306
|
config.runtimeConfig.discord.rootDir = ctx.nuxt.options.rootDir;
|
|
1307
|
+
config.runtimeConfig.discord.interactionTimeout = ctx.options.interactionTimeout;
|
|
664
1308
|
});
|
|
665
1309
|
}
|
|
666
1310
|
|
|
667
|
-
|
|
668
|
-
addServerTemplate({
|
|
669
|
-
filename: "discord/slashCommands",
|
|
670
|
-
getContents: () => getSlashCommandTemplateContent(
|
|
671
|
-
ctx,
|
|
672
|
-
/* commandRuntime */
|
|
673
|
-
true
|
|
674
|
-
)
|
|
675
|
-
});
|
|
676
|
-
addTemplate({
|
|
677
|
-
filename: "discord/slashCommands",
|
|
678
|
-
getContents: () => getSlashCommandTemplateContent(
|
|
679
|
-
ctx,
|
|
680
|
-
/* commandRuntime */
|
|
681
|
-
false
|
|
682
|
-
)
|
|
683
|
-
});
|
|
684
|
-
const typesTemplateDst = addTypeTemplate({
|
|
685
|
-
filename: "discord/types.d.ts",
|
|
686
|
-
// proposal-string-dedent when?
|
|
687
|
-
getContents: () => `
|
|
688
|
-
declare module 'discord/slashCommands' {
|
|
689
|
-
declare const slashCommands: import('nuxt-discord').SlashCommandRuntime[]
|
|
690
|
-
export default slashCommands
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
type integer = import('nuxt-discord').integer
|
|
694
|
-
|
|
695
|
-
declare global {
|
|
696
|
-
declare module 'nitropack/types' {
|
|
697
|
-
interface NitroRuntimeHooks {
|
|
698
|
-
'discord:client:config': (options: import('nuxt-discord').NuxtDiscordOptions['client']) => void
|
|
699
|
-
'discord:client:ready': (client: DiscordClient) => void
|
|
700
|
-
'discord:client:error': (error: DiscordClientError) => void
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
declare module '@nuxt/schema' {
|
|
705
|
-
interface RuntimeConfig {
|
|
706
|
-
discord: import('nuxt-discord').DiscordRuntimeConfig
|
|
707
|
-
}
|
|
708
|
-
interface PublicRuntimeConfig {
|
|
709
|
-
discord: {
|
|
710
|
-
wsUrl?: string
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
`
|
|
716
|
-
}).dst;
|
|
717
|
-
ctx.nuxt.options.nitro.typescript ||= {};
|
|
718
|
-
ctx.nuxt.options.nitro.typescript.tsConfig = defu(ctx.nuxt.options.nitro.typescript.tsConfig, {
|
|
719
|
-
include: [typesTemplateDst]
|
|
720
|
-
});
|
|
721
|
-
}
|
|
722
|
-
function getSlashCommandTemplateContent(ctx, commandRuntime) {
|
|
723
|
-
const imports = commandRuntime ? ctx.slashCommands.map(({ path }) => {
|
|
724
|
-
const name = genSafeVariableName(path);
|
|
725
|
-
return { name, code: genImport(path, [{ name: "default", as: name }]) };
|
|
726
|
-
}) : [];
|
|
727
|
-
return [
|
|
728
|
-
...imports.map(({ code }) => code),
|
|
729
|
-
`export default [
|
|
730
|
-
${ctx.slashCommands.map(({ options, ...rest }, i) => ` {
|
|
731
|
-
${Object.entries(rest).map(([key, value]) => `${key}: ${genString(value)}`).join(",\n ")},
|
|
732
|
-
|
|
733
|
-
options: ${genArrayFromRaw(options, void 0, { preserveTypes: true })},
|
|
734
|
-
${commandRuntime ? `
|
|
735
|
-
...${imports[i].name},
|
|
736
|
-
` : ""}
|
|
737
|
-
},
|
|
738
|
-
`).join("")}]`
|
|
739
|
-
].join("\n");
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
const module = defineNuxtModule({
|
|
1311
|
+
const module$1 = defineNuxtModule({
|
|
743
1312
|
meta: {
|
|
744
1313
|
name: "nuxt-discord",
|
|
745
1314
|
configKey: "discord"
|
|
746
1315
|
},
|
|
1316
|
+
async moduleDependencies(nuxt) {
|
|
1317
|
+
if (nuxt.options.dev || nuxt.options._prepare)
|
|
1318
|
+
return { "@nuxt/ui": {} };
|
|
1319
|
+
let hosted = nuxt.options.discord && nuxt.options.discord.dashboard;
|
|
1320
|
+
for (const entry of nuxt.options.modules) {
|
|
1321
|
+
if (!Array.isArray(entry) || typeof entry[1]?.dashboard !== "boolean")
|
|
1322
|
+
continue;
|
|
1323
|
+
const { nuxtModule } = await loadNuxtModuleInstance(entry[0], nuxt);
|
|
1324
|
+
if ((await nuxtModule.getMeta?.())?.name === "nuxt-discord") {
|
|
1325
|
+
hosted = entry[1].dashboard;
|
|
1326
|
+
break;
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
return hosted ? { "@nuxt/ui": {} } : {};
|
|
1330
|
+
},
|
|
747
1331
|
defaults: {
|
|
748
1332
|
client: {
|
|
749
1333
|
intents: [GatewayIntentBits.Guilds],
|
|
@@ -763,18 +1347,121 @@ const module = defineNuxtModule({
|
|
|
763
1347
|
},
|
|
764
1348
|
setup(discordOptions, nuxt) {
|
|
765
1349
|
const ctx = createContext(discordOptions, nuxt);
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
1350
|
+
const development = nuxt.options.dev || nuxt.options._prepare;
|
|
1351
|
+
const hostedDashboard = !development && discordOptions.dashboard === true;
|
|
1352
|
+
if (hostedDashboard) {
|
|
1353
|
+
addServerHandler({ middleware: true, handler: ctx.resolve.module("runtime/dashboard/auth") });
|
|
1354
|
+
for (const route of ["/discord", "/discord/**", "/api/discord", "/api/discord/**"])
|
|
1355
|
+
extendRouteRules(route, { prerender: false, cache: false }, { override: true });
|
|
1356
|
+
for (const [path, method] of [
|
|
1357
|
+
["catalog", "get"],
|
|
1358
|
+
["activity", "get"],
|
|
1359
|
+
["slash-command/all", "get"],
|
|
1360
|
+
["slash-command/remote-all", "get"],
|
|
1361
|
+
["slash-command/remote-diff", "post"],
|
|
1362
|
+
["slash-command/register", "post"],
|
|
1363
|
+
["slash-command/test", "post"],
|
|
1364
|
+
["slash-command/autocomplete", "post"]
|
|
1365
|
+
]) {
|
|
1366
|
+
addServerHandler({
|
|
1367
|
+
route: `/api/discord/${path}`,
|
|
1368
|
+
method,
|
|
1369
|
+
handler: ctx.resolve.module(`runtime/server/api/discord/${path}.${method}`)
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
if (development || hostedDashboard) {
|
|
1374
|
+
extendRouteRules("/discord", { ssr: false });
|
|
1375
|
+
extendRouteRules("/discord/**", { ssr: false });
|
|
1376
|
+
prepareClient(ctx);
|
|
1377
|
+
}
|
|
1378
|
+
if (development) {
|
|
1379
|
+
addServerScanDir(ctx.resolve.module("runtime/server"));
|
|
1380
|
+
} else {
|
|
1381
|
+
const plugin = ctx.resolve.module("runtime/server/plugins/discord");
|
|
1382
|
+
addServerPlugin(plugin);
|
|
1383
|
+
nuxt.hook("nitro:init", (nitro) => {
|
|
1384
|
+
nitro.hooks.hook("prerender:config", (config) => {
|
|
1385
|
+
config.plugins = config.plugins?.filter((entry) => entry !== plugin);
|
|
1386
|
+
});
|
|
1387
|
+
});
|
|
1388
|
+
addServerImportsDir(ctx.resolve.module("runtime/server/utils"));
|
|
1389
|
+
addServerImportsDir(ctx.resolve.module("runtime/server/utils/middleware"));
|
|
1390
|
+
}
|
|
1391
|
+
addImports([
|
|
1392
|
+
{
|
|
1393
|
+
name: "defineSlashCommand",
|
|
1394
|
+
as: "defineSlashCommand",
|
|
1395
|
+
from: ctx.resolve.module("runtime/server/utils/defineSlashCommand")
|
|
1396
|
+
},
|
|
1397
|
+
{
|
|
1398
|
+
name: "defineListener",
|
|
1399
|
+
as: "defineListener",
|
|
1400
|
+
from: ctx.resolve.module("runtime/server/utils/defineListener")
|
|
1401
|
+
},
|
|
1402
|
+
{
|
|
1403
|
+
name: "defineUserContextMenu",
|
|
1404
|
+
as: "defineUserContextMenu",
|
|
1405
|
+
from: ctx.resolve.module("runtime/server/utils/defineContextMenu")
|
|
1406
|
+
},
|
|
1407
|
+
{
|
|
1408
|
+
name: "defineMessageContextMenu",
|
|
1409
|
+
as: "defineMessageContextMenu",
|
|
1410
|
+
from: ctx.resolve.module("runtime/server/utils/defineContextMenu")
|
|
1411
|
+
},
|
|
1412
|
+
{
|
|
1413
|
+
name: "defineMiddleware",
|
|
1414
|
+
as: "defineMiddleware",
|
|
1415
|
+
from: ctx.resolve.module("runtime/server/utils/defineMiddleware")
|
|
1416
|
+
},
|
|
1417
|
+
{
|
|
1418
|
+
name: "MiddlewareError",
|
|
1419
|
+
as: "MiddlewareError",
|
|
1420
|
+
from: ctx.resolve.module("runtime/server/utils/defineMiddleware")
|
|
1421
|
+
},
|
|
1422
|
+
{
|
|
1423
|
+
name: "useMiddleware",
|
|
1424
|
+
as: "useMiddleware",
|
|
1425
|
+
from: ctx.resolve.module("runtime/server/utils/defineMiddleware")
|
|
1426
|
+
},
|
|
1427
|
+
{
|
|
1428
|
+
name: "useMiddlewareContext",
|
|
1429
|
+
as: "useMiddlewareContext",
|
|
1430
|
+
from: ctx.resolve.module("runtime/server/utils/defineMiddleware")
|
|
1431
|
+
},
|
|
1432
|
+
{
|
|
1433
|
+
name: "guildOnly",
|
|
1434
|
+
as: "guildOnly",
|
|
1435
|
+
from: ctx.resolve.module("runtime/server/utils/middleware/guildOnly")
|
|
1436
|
+
},
|
|
1437
|
+
{
|
|
1438
|
+
name: "ownerOnly",
|
|
1439
|
+
as: "ownerOnly",
|
|
1440
|
+
from: ctx.resolve.module("runtime/server/utils/middleware/ownerOnly")
|
|
1441
|
+
},
|
|
1442
|
+
{
|
|
1443
|
+
name: "cooldown",
|
|
1444
|
+
as: "cooldown",
|
|
1445
|
+
from: ctx.resolve.module("runtime/server/utils/middleware/cooldown")
|
|
1446
|
+
},
|
|
1447
|
+
{
|
|
1448
|
+
name: "requireRole",
|
|
1449
|
+
as: "requireRole",
|
|
1450
|
+
from: ctx.resolve.module("runtime/server/utils/middleware/requireRole")
|
|
1451
|
+
},
|
|
1452
|
+
{
|
|
1453
|
+
name: "useTextChannel",
|
|
1454
|
+
as: "useTextChannel",
|
|
1455
|
+
from: ctx.resolve.module("runtime/server/utils/useTextChannel")
|
|
1456
|
+
}
|
|
1457
|
+
]);
|
|
772
1458
|
prepareRuntimeConfig(ctx);
|
|
773
1459
|
collectSlashCommands(ctx);
|
|
1460
|
+
collectContextMenus(ctx);
|
|
1461
|
+
collectListeners(ctx);
|
|
774
1462
|
prepareTemplates(ctx);
|
|
775
1463
|
prepareHMR(ctx);
|
|
776
|
-
prepareClient(ctx);
|
|
777
1464
|
}
|
|
778
1465
|
});
|
|
779
1466
|
|
|
780
|
-
export { module as default };
|
|
1467
|
+
export { module$1 as default };
|