nuxt-discord 0.0.17 → 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.
Files changed (112) hide show
  1. package/README.md +249 -171
  2. package/dist/module.d.mts +108 -10
  3. package/dist/module.json +3 -3
  4. package/dist/module.mjs +966 -345
  5. package/dist/runtime/acknowledgement.d.ts +10 -0
  6. package/dist/runtime/acknowledgement.js +124 -0
  7. package/dist/runtime/client/chat-theme.css +52 -0
  8. package/dist/runtime/client/components/ChatAvatar.d.vue.ts +6 -0
  9. package/dist/runtime/client/components/ChatAvatar.vue +11 -0
  10. package/dist/runtime/client/components/ChatAvatar.vue.d.ts +6 -0
  11. package/dist/runtime/client/components/CommandPicker.d.vue.ts +24 -0
  12. package/dist/runtime/client/components/CommandPicker.vue +67 -0
  13. package/dist/runtime/client/components/CommandPicker.vue.d.ts +24 -0
  14. package/dist/runtime/client/components/CommandTestBar.d.vue.ts +60 -0
  15. package/dist/runtime/client/components/CommandTestBar.vue +335 -0
  16. package/dist/runtime/client/components/CommandTestBar.vue.d.ts +60 -0
  17. package/dist/runtime/client/components/CommandTranscript.d.vue.ts +39 -0
  18. package/dist/runtime/client/components/CommandTranscript.vue +147 -0
  19. package/dist/runtime/client/components/CommandTranscript.vue.d.ts +39 -0
  20. package/dist/runtime/client/components/ProjectLogo.d.vue.ts +3 -0
  21. package/dist/runtime/client/components/ProjectLogo.vue +31 -0
  22. package/dist/runtime/client/components/ProjectLogo.vue.d.ts +3 -0
  23. package/dist/runtime/client/components/TheHeader.d.vue.ts +3 -0
  24. package/dist/runtime/client/components/TheHeader.vue +53 -16
  25. package/dist/runtime/client/components/TheHeader.vue.d.ts +2 -2
  26. package/dist/runtime/client/components/appearance-select.d.ts +17 -0
  27. package/dist/runtime/client/components/appearance-select.js +15 -0
  28. package/dist/runtime/client/pages/activity.d.vue.ts +3 -0
  29. package/dist/runtime/client/pages/activity.vue +202 -0
  30. package/dist/runtime/client/pages/activity.vue.d.ts +3 -0
  31. package/dist/runtime/client/pages/context-menus.d.vue.ts +3 -0
  32. package/dist/runtime/client/pages/context-menus.vue +120 -0
  33. package/dist/runtime/client/pages/context-menus.vue.d.ts +3 -0
  34. package/dist/runtime/client/pages/listeners.d.vue.ts +3 -0
  35. package/dist/runtime/client/pages/listeners.vue +68 -0
  36. package/dist/runtime/client/pages/listeners.vue.d.ts +3 -0
  37. package/dist/runtime/client/pages/overview.d.vue.ts +3 -0
  38. package/dist/runtime/client/pages/overview.vue +280 -0
  39. package/dist/runtime/client/pages/overview.vue.d.ts +3 -0
  40. package/dist/runtime/client/pages/slash-commands.d.vue.ts +3 -0
  41. package/dist/runtime/client/pages/slash-commands.vue +185 -359
  42. package/dist/runtime/client/pages/slash-commands.vue.d.ts +2 -3
  43. package/dist/runtime/client/style.css +4 -1
  44. package/dist/runtime/client/useActivityLog.d.ts +7 -0
  45. package/dist/runtime/client/useActivityLog.js +76 -0
  46. package/dist/runtime/client/useCommandRegistry.d.ts +7 -0
  47. package/dist/runtime/client/useCommandRegistry.js +34 -0
  48. package/dist/runtime/client/useDashboardCatalog.d.ts +5 -0
  49. package/dist/runtime/client/useDashboardCatalog.js +9 -0
  50. package/dist/runtime/dashboard/auth.d.ts +4 -0
  51. package/dist/runtime/dashboard/auth.js +65 -0
  52. package/dist/runtime/dashboard/oauth.d.ts +3 -0
  53. package/dist/runtime/dashboard/oauth.js +151 -0
  54. package/dist/runtime/dashboard/permissions.d.ts +4 -0
  55. package/dist/runtime/dashboard/permissions.js +84 -0
  56. package/dist/runtime/dashboard/signin.d.ts +2 -0
  57. package/dist/runtime/dashboard/signin.js +39 -0
  58. package/dist/runtime/diagnostics.d.ts +4 -0
  59. package/dist/runtime/diagnostics.js +24 -0
  60. package/dist/runtime/discordInvocation.d.ts +14 -0
  61. package/dist/runtime/discordInvocation.js +28 -0
  62. package/dist/runtime/middleware.d.ts +1 -0
  63. package/dist/runtime/middleware.js +12 -0
  64. package/dist/runtime/registration.d.ts +65 -0
  65. package/dist/runtime/registration.js +354 -0
  66. package/dist/runtime/server/api/discord/activity.get.d.ts +2 -0
  67. package/dist/runtime/server/api/discord/activity.get.js +6 -0
  68. package/dist/runtime/server/api/discord/catalog.get.d.ts +2 -0
  69. package/dist/runtime/server/api/discord/catalog.get.js +3 -0
  70. package/dist/runtime/server/api/discord/slash-command/autocomplete.post.d.ts +2 -0
  71. package/dist/runtime/server/api/discord/slash-command/autocomplete.post.js +14 -0
  72. package/dist/runtime/server/api/discord/slash-command/register.post.d.ts +1 -1
  73. package/dist/runtime/server/api/discord/slash-command/register.post.js +1 -1
  74. package/dist/runtime/server/api/discord/slash-command/remote-all.get.d.ts +1 -1
  75. package/dist/runtime/server/api/discord/slash-command/remote-diff.post.d.ts +1 -238
  76. package/dist/runtime/server/api/discord/slash-command/remote-diff.post.js +3 -1
  77. package/dist/runtime/server/api/discord/slash-command/test.post.d.ts +20 -0
  78. package/dist/runtime/server/api/discord/slash-command/test.post.js +19 -0
  79. package/dist/runtime/server/plugins/discord.js +93 -31
  80. package/dist/runtime/server/utils/client.d.ts +59 -246
  81. package/dist/runtime/server/utils/client.js +413 -451
  82. package/dist/runtime/server/utils/defineContextMenu.d.ts +49 -0
  83. package/dist/runtime/server/utils/defineContextMenu.js +12 -0
  84. package/dist/runtime/server/utils/defineListener.d.ts +24 -0
  85. package/dist/runtime/server/utils/defineListener.js +7 -0
  86. package/dist/runtime/server/utils/defineMiddleware.d.ts +29 -0
  87. package/dist/runtime/server/utils/defineMiddleware.js +24 -0
  88. package/dist/runtime/server/utils/describeCommand.d.ts +2 -0
  89. package/dist/runtime/server/utils/describeOption.d.ts +1 -1
  90. package/dist/runtime/server/utils/messageSender.d.ts +37 -0
  91. package/dist/runtime/server/utils/messageSender.js +149 -0
  92. package/dist/runtime/server/utils/middleware/cooldown.d.ts +1 -0
  93. package/dist/runtime/server/utils/middleware/cooldown.js +39 -0
  94. package/dist/runtime/server/utils/middleware/guildOnly.d.ts +1 -0
  95. package/dist/runtime/server/utils/middleware/guildOnly.js +6 -0
  96. package/dist/runtime/server/utils/middleware/ownerOnly.d.ts +1 -0
  97. package/dist/runtime/server/utils/middleware/ownerOnly.js +10 -0
  98. package/dist/runtime/server/utils/middleware/requireRole.d.ts +1 -0
  99. package/dist/runtime/server/utils/middleware/requireRole.js +15 -0
  100. package/dist/runtime/server/utils/reply.d.ts +13 -3
  101. package/dist/runtime/server/utils/reply.js +111 -162
  102. package/dist/runtime/server/utils/simulateInteraction.d.ts +20 -0
  103. package/dist/runtime/server/utils/simulateInteraction.js +127 -0
  104. package/dist/runtime/server/utils/useTextChannel.d.ts +56 -0
  105. package/dist/runtime/server/utils/useTextChannel.js +105 -0
  106. package/dist/types.d.mts +11 -1
  107. package/dist/types.d.ts +11 -1
  108. package/package.json +62 -44
  109. package/dist/runtime/client/components/TheHeader.css +0 -1
  110. package/dist/runtime/client/pages/slash-commands.css +0 -1
  111. package/dist/runtime/client/uno.config.d.ts +0 -2
  112. package/dist/runtime/client/uno.config.js +0 -10
package/dist/module.mjs CHANGED
@@ -1,21 +1,26 @@
1
- import { createResolver, installModule, extendPages, updateTemplates, addVitePlugin, isIgnored, resolveAlias, addServerTemplate, addTemplate, addTypeTemplate, defineNuxtModule, addServerScanDir, addImports } from '@nuxt/kit';
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, { isFunctionExpression, isArrowFunction } from 'typescript';
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 defu from 'defu';
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
- async function prepareClient(ctx) {
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: "slash-commands",
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.find((prop) => ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.escapedText === "autocomplete" || ts.isMethodDeclaration(prop) && ts.isIdentifier(prop.name) && prop.name.escapedText === "autocomplete") != null;
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,26 +208,126 @@ function parseLiteral(node) {
149
208
  return void 0;
150
209
  }
151
210
 
152
- function collectSlashCommands(ctx) {
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 command = processCommandFile(ctx, file);
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
  }
161
266
  processSubcommands(ctx);
267
+ applyLocalizations(ctx);
162
268
  }
163
- function processCommandFile(ctx, file) {
164
- const sourceFile = ts.createSourceFile(
165
- file,
166
- readFileSync(file).toString(),
167
- ts.ScriptTarget.Latest,
168
- /* setParentNodes */
169
- true
170
- );
171
- const commandDefinition = extractCommandDefinition(sourceFile);
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;
172
331
  if (!commandDefinition) {
173
332
  ctx.logger.warn(`No command definition found for ${file}`);
174
333
  return;
@@ -183,11 +342,49 @@ function processCommandFile(ctx, file) {
183
342
  if ((ts.isFunctionDeclaration(commandDefinition) || ts.isFunctionExpression(commandDefinition)) && !!commandDefinition.name && ts.isIdentifier(commandDefinition.name) && commandDefinition.name.escapedText) {
184
343
  command.name = commandDefinition.name.escapedText;
185
344
  }
345
+ const jsDocComment = getJSDocComment(commandDefinition);
186
346
  const jsDocTags = getJSDocTags(commandDefinition);
187
- const nameTag = jsDocTags.find((tag) => tag.tagName.escapedText === "name");
188
- const descriptionTag = jsDocTags.find((tag) => tag.tagName.escapedText === "description");
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));
189
350
  command.name = nameTag?.comment?.toString() ?? command.name;
190
- command.description = descriptionTag?.comment?.toString() ?? command.description;
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
+ }
191
388
  if (!commandDefinition.body) {
192
389
  ctx.logger.warn(`No body found for command definition in ${file}`);
193
390
  return;
@@ -202,8 +399,16 @@ function processCommandFile(ctx, file) {
202
399
  }
203
400
  }
204
401
  };
205
- const getType = (type) => {
402
+ const getType = (type, initializer) => {
206
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
+ }
207
412
  ctx.logger.warn(`No type found for slash command option in ${file}, defaulting to string`);
208
413
  return { type: "string" };
209
414
  }
@@ -214,7 +419,7 @@ function processCommandFile(ctx, file) {
214
419
  return { type: "string" };
215
420
  }
216
421
  const typeName2 = types.values().next().value;
217
- if (!(typeName2 in typeIdentifierToEnum)) {
422
+ if (!typeName2 || !isOptionTypeIdentifier(typeName2)) {
218
423
  ctx.logger.warn(`Unrecognizable type ${type.getText(sourceFile)}, defaulting to string`);
219
424
  return { type: "string" };
220
425
  }
@@ -239,7 +444,7 @@ function processCommandFile(ctx, file) {
239
444
  };
240
445
  }
241
446
  const typeName = type.getText(sourceFile);
242
- if (typeName && typeName in typeIdentifierToEnum) {
447
+ if (typeName && isOptionTypeIdentifier(typeName)) {
243
448
  return { type: typeName };
244
449
  }
245
450
  ctx.logger.warn(`Unknown slash command option type: ${type.getText(sourceFile)} in ${file}, defaulting to string`);
@@ -247,7 +452,7 @@ function processCommandFile(ctx, file) {
247
452
  };
248
453
  for (const param of commandDefinition.parameters) {
249
454
  const name2 = param.name.getText(sourceFile);
250
- let { type, choices } = getType(param.type);
455
+ let { type, choices } = getType(param.type, param.initializer);
251
456
  const jsDocTagIdx = jsDocTags.findIndex((tag) => ts.isJSDocParameterTag(tag) && tag.name.getText() === name2);
252
457
  const findModifiers = (modifiers2) => {
253
458
  let idx = jsDocTagIdx;
@@ -264,20 +469,13 @@ function processCommandFile(ctx, file) {
264
469
  return ret;
265
470
  };
266
471
  const jsdocDescription = jsDocTagIdx !== -1 ? jsDocTags[jsDocTagIdx].comment?.toString() ?? "" : "";
267
- const modifiersMap = {
268
- string: ["minLength", "maxLength", "choices"],
269
- number: ["min", "max", "choices"],
270
- integer: ["min", "max", "choices"],
271
- boolean: []
272
- };
273
472
  const modifiers = findModifiers(modifiersMap[type]);
274
473
  choices = choices ?? modifiers.choices;
275
474
  command.options.push({
276
475
  name: name2,
277
- // TODO: remove this type assertion
278
476
  type: typeIdentifierToEnum[type],
279
477
  description: jsdocDescription,
280
- required: !param.questionToken,
478
+ required: !param.questionToken && !param.initializer,
281
479
  varname: name2,
282
480
  hasAutocomplete: false,
283
481
  ...modifiers,
@@ -297,6 +495,7 @@ function processCommandFile(ctx, file) {
297
495
  const macroName = macroCall.expression.escapedText;
298
496
  macros[macroName](ctx, macroCall, command);
299
497
  }
498
+ command.description ||= command.name;
300
499
  if (outOfRangMacroCalls.length > 0) {
301
500
  ctx.logger.warn(`Macros in file ${file} must be called at the top of the file`);
302
501
  }
@@ -350,20 +549,21 @@ ${command.parents.map((p) => ` - ${p}`).join("\n")}`);
350
549
  }
351
550
  ctx.slashCommands = ctx.slashCommands.filter((c) => c.parents.length === 0);
352
551
  }
353
- function extractCommandDefinition(sourceFile) {
354
- let commandDefinition;
355
- ts.forEachChild(sourceFile, (node) => {
356
- if (ts.isExportAssignment(node)) {
357
- if (ts.isArrowFunction(node.expression)) {
358
- commandDefinition = node.expression;
359
- } else if (ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText === "defineSlashCommand" && (ts.isArrowFunction(node.expression.arguments[0]) || ts.isFunctionExpression(node.expression.arguments[0]))) {
360
- commandDefinition = node.expression.arguments[0];
361
- }
362
- } else if (ts.isFunctionDeclaration(node) && !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.ExportDefault)) {
363
- commandDefinition = node;
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 };
364
565
  }
365
- });
366
- return commandDefinition;
566
+ }
367
567
  }
368
568
  function extractMacroCalls(definitionBody) {
369
569
  let macrosEnd = false;
@@ -388,6 +588,17 @@ function extractMacroCalls(definitionBody) {
388
588
  function isMacroCallExpression(node) {
389
589
  return ts.isExpressionStatement(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText in macros;
390
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
+ }
391
602
  function getJSDocTags(node) {
392
603
  const tags = ts.getJSDocTags(node);
393
604
  if (tags.length > 0) {
@@ -405,115 +616,481 @@ function getJSDocTags(node) {
405
616
  return [];
406
617
  }
407
618
 
408
- const TransformPlugin = (ctx) => {
409
- const commandsDir = ctx.resolve.root(ctx.options.dir, "commands");
410
- return {
411
- name: "transform-slash-commands",
412
- async load(id) {
413
- if (!id.startsWith(commandsDir)) {
414
- return;
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
+ }
415
651
  }
416
- try {
417
- const sourceFile = ts.createSourceFile(
418
- id,
419
- fs.readFileSync(id, "utf-8"),
420
- ts.ScriptTarget.Latest,
421
- /* setParentNodes */
422
- true
423
- );
424
- let commandDefinition = extractCommandDefinition(sourceFile);
425
- if (!commandDefinition || !commandDefinition.body) {
426
- return;
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();
427
681
  }
428
- const transformer = (context) => {
429
- return (sourceFile2) => {
430
- const visitor = (node) => {
431
- if (ts.isExportAssignment(node) || ts.isFunctionDeclaration(node) && !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.ExportDefault)) {
432
- if (ts.isFunctionDeclaration(commandDefinition)) {
433
- commandDefinition = ts.factory.createFunctionExpression(
434
- ts.getModifiers(commandDefinition)?.filter((m) => m.kind !== ts.SyntaxKind.ExportKeyword && m.kind !== ts.SyntaxKind.DefaultKeyword),
435
- commandDefinition.asteriskToken,
436
- commandDefinition.name,
437
- commandDefinition.typeParameters,
438
- commandDefinition.parameters,
439
- commandDefinition.type,
440
- commandDefinition.body
441
- );
442
- }
443
- commandDefinition = commandDefinition;
444
- const [macroCalls] = extractMacroCalls(commandDefinition.body);
445
- if (ts.isBlock(commandDefinition.body)) {
446
- if (isFunctionExpression(commandDefinition)) {
447
- commandDefinition = ts.factory.createFunctionExpression(
448
- commandDefinition.modifiers,
449
- commandDefinition.asteriskToken,
450
- commandDefinition.name,
451
- commandDefinition.typeParameters,
452
- commandDefinition.parameters,
453
- commandDefinition.type,
454
- ts.factory.createBlock(
455
- commandDefinition.body.statements.filter((s) => !isMacroCallExpression(s)),
456
- true
457
- )
458
- );
459
- } else if (isArrowFunction(commandDefinition)) {
460
- commandDefinition = ts.factory.createArrowFunction(
461
- commandDefinition.modifiers,
462
- commandDefinition.typeParameters,
463
- commandDefinition.parameters,
464
- commandDefinition.type,
465
- commandDefinition.equalsGreaterThanToken,
466
- ts.factory.createBlock(
467
- commandDefinition.body.statements.filter((s) => !isMacroCallExpression(s)),
468
- true
469
- )
470
- );
471
- }
472
- }
473
- return ts.factory.createExportAssignment(
474
- [],
475
- false,
476
- ts.factory.createObjectLiteralExpression([
477
- ts.factory.createPropertyAssignment("execute", commandDefinition),
478
- ts.factory.createPropertyAssignment(
479
- "optionMacros",
480
- ts.factory.createObjectLiteralExpression(
481
- 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]))
482
- )
483
- )
484
- ])
485
- );
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();
486
690
  }
487
- return ts.visitEachChild(node, visitor, context);
488
- };
489
- return ts.visitNode(sourceFile2, visitor);
490
- };
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"
491
812
  };
492
- const res = ts.transform(sourceFile, [transformer]);
493
- const printer = ts.createPrinter({
494
- newLine: ts.NewLineKind.LineFeed,
495
- removeComments: false
496
- });
497
- const transformed = printer.printFile(res.transformed[0]);
498
- return transformed;
499
- } catch {
500
- return null;
501
813
  }
502
814
  }
503
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
+ };
504
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
+ }
505
1063
 
506
1064
  function prepareHMR(ctx) {
507
1065
  const { nuxt, options } = ctx;
508
- if (nuxt.options.dev) {
509
- const commandsDir = ctx.resolve.root(options.dir, "commands");
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) {
510
1088
  const ignoreCommandsDir = (file) => {
511
- if (file.startsWith(commandsDir)) {
1089
+ if (file === commandsDir.slice(0, -1) || file.startsWith(commandsDir)) {
512
1090
  return true;
513
1091
  }
514
1092
  return isIgnored(file);
515
1093
  };
516
- let rollupConfig;
517
1094
  nuxt.hook("nitro:config", (nitroConfig) => {
518
1095
  nitroConfig.watchOptions ??= {};
519
1096
  const existingNitroIgnored = nitroConfig.watchOptions.ignored;
@@ -525,18 +1102,6 @@ function prepareHMR(ctx) {
525
1102
  nitroIgnored.push(existingNitroIgnored);
526
1103
  }
527
1104
  nitroConfig.watchOptions.ignored = nitroIgnored;
528
- const originalBeforeHook = nitroConfig.hooks?.["rollup:before"];
529
- nitroConfig.hooks = {
530
- ...nitroConfig.hooks,
531
- "rollup:before": (nitroCtx, config) => {
532
- originalBeforeHook?.(nitroCtx, config);
533
- config.plugins = [
534
- config.plugins,
535
- TransformPlugin(ctx)
536
- ];
537
- rollupConfig = config;
538
- }
539
- };
540
1105
  });
541
1106
  nuxt.options.vite.server ??= {};
542
1107
  nuxt.options.vite.server.watch ??= {};
@@ -553,78 +1118,132 @@ function prepareHMR(ctx) {
553
1118
  let websocket;
554
1119
  let listener;
555
1120
  const websocketOptions = options.watch || {};
556
- if (websocketOptions.enabled) {
557
- nuxt.hook("nitro:init", async (nitro) => {
558
- websocket = createWebSocket();
559
- listener = await listen(() => "Nuxt Discord", websocketOptions);
560
- nitro.options.runtimeConfig.public.discord = {
561
- wsUrl: listener.url.replace("http", "ws")
562
- };
563
- listener.server.on("upgrade", websocket.serve);
564
- websocket.on("full-update", (client) => {
565
- collectSlashCommands(ctx);
566
- try {
567
- client.send(JSON.stringify({
568
- event: "full-update",
569
- commands: ctx.slashCommands
570
- }));
571
- } catch {
572
- }
573
- });
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
+ }
574
1137
  });
575
- }
576
- const commandsBuildDir = path.join(ctx.nuxt.options.buildDir, "discord", "commands");
577
- fs.rmSync(commandsBuildDir, { recursive: true, force: true });
578
- fs.mkdirSync(commandsBuildDir, { recursive: true });
579
- chokidar.watch(ctx.resolve.root(ctx.options.dir, "commands"), { ignoreInitial: true }).on("all", async (event, path2) => {
580
- if (event === "all" || event === "error" || event === "raw") {
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)
581
1159
  return;
582
- }
583
- const fullPath = ctx.resolve.root(path2);
584
- if (fullPath.startsWith(commandsDir)) {
585
- path2 = ctx.resolve.root(path2);
586
- const command = processCommandFile(ctx, path2) ?? null;
587
- if (event === "add" || event === "change") {
588
- ctx.logger.log(`Dynamically loading slash command at ${path2}`);
589
- await generateDynamicCommandBuild(path2, rollupConfig, ctx);
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
+ }
590
1194
  }
591
- websocket?.broadcast({ event, path: path2, command });
592
- await updateTemplates({
593
- filter: (template) => template.filename === "discord/slashCommands"
594
- });
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();
595
1205
  }
596
1206
  });
597
- nuxt.hook("close", () => {
1207
+ nuxt.hook("close", async () => {
1208
+ closed = true;
1209
+ await watcher.close();
598
1210
  listener?.server.close();
599
1211
  websocket?.close();
600
1212
  });
601
- const packageJson = ctx.resolve.module("../package.json");
602
- if (fs.existsSync(packageJson) && JSON.parse(fs.readFileSync(packageJson, "utf-8")).name === "nuxt-discord") {
603
- (async () => {
604
- const { createGenerator } = await import('unocss');
605
- const config = (await import('../dist/runtime/client/uno.config.js')).default;
606
- const generator = await createGenerator(config);
607
- const clientDir = ctx.resolve.module("runtime/client");
608
- const generateCSS = async (path2) => {
609
- if (path2.startsWith(clientDir) && path2.endsWith(".vue")) {
610
- const content = fs.readFileSync(path2, "utf-8");
611
- const tokens = await generator.applyExtractors(content, path2);
612
- const { css } = await generator.generate(tokens);
613
- fs.writeFileSync(path2.replace(".vue", ".css"), css, "utf-8");
614
- }
615
- };
616
- const globPattern = `${clientDir}/**/*.vue`;
617
- fs.globSync(globPattern).forEach(generateCSS);
618
- addVitePlugin({
619
- name: "dev-nuxt-discord-generate-css",
620
- configureServer(server) {
621
- server.watcher.add(globPattern);
622
- server.watcher.on("change", generateCSS);
623
- }
624
- });
625
- })();
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);
626
1242
  }
1243
+ } finally {
1244
+ await bundle.close();
627
1245
  }
1246
+ return additions;
628
1247
  }
629
1248
  function createWebSocket() {
630
1249
  const wss = new WebSocketServer({ noServer: true });
@@ -673,34 +1292,6 @@ function createWebSocket() {
673
1292
  }
674
1293
  };
675
1294
  }
676
- async function generateDynamicCommandBuild(file, config, ctx) {
677
- let bundle;
678
- try {
679
- bundle = await rollup({
680
- ...config,
681
- input: file,
682
- plugins: [
683
- config.plugins,
684
- {
685
- name: "discord:resolve-alias-and-externalize",
686
- resolveId: (id) => {
687
- if (!id.includes(file) && !id.endsWith(".ts")) {
688
- return { id: resolveAlias(id), external: true };
689
- }
690
- }
691
- }
692
- ]
693
- });
694
- const { output } = await bundle.generate({ ...config.output, sourcemap: false });
695
- const outputFilePath = file.replace(ctx.resolve.root(ctx.nuxt.options.rootDir), ctx.nuxt.options.buildDir).replace(".ts", ".mjs");
696
- fs.mkdirSync(path.dirname(outputFilePath), { recursive: true });
697
- fs.writeFileSync(outputFilePath, output[0].code, { encoding: "utf-8", flush: true });
698
- } catch (error) {
699
- ctx.logger.error(`Error processing command file ${file}:`, error);
700
- return;
701
- }
702
- await bundle.close();
703
- }
704
1295
 
705
1296
  function prepareRuntimeConfig(ctx) {
706
1297
  ctx.nuxt.hook("nitro:config", (config) => {
@@ -709,107 +1300,34 @@ function prepareRuntimeConfig(ctx) {
709
1300
  config.runtimeConfig.discord.client = ctx.options.client;
710
1301
  config.runtimeConfig.discord.autoStart = ctx.options.autoStart;
711
1302
  config.runtimeConfig.discord.sync = ctx.options.watch.sync ?? false;
1303
+ config.runtimeConfig.discord.guilds = ctx.options.guilds ?? [];
712
1304
  config.runtimeConfig.discord.dir = ctx.resolve.root(ctx.options.dir);
713
1305
  config.runtimeConfig.discord.buildDir = ctx.nuxt.options.buildDir;
714
1306
  config.runtimeConfig.discord.rootDir = ctx.nuxt.options.rootDir;
1307
+ config.runtimeConfig.discord.interactionTimeout = ctx.options.interactionTimeout;
715
1308
  });
716
1309
  }
717
1310
 
718
- function prepareTemplates(ctx) {
719
- addServerTemplate({
720
- filename: "discord/slashCommands",
721
- getContents: () => getSlashCommandTemplateContent(
722
- ctx,
723
- /* commandRuntime */
724
- true
725
- )
726
- });
727
- addTemplate({
728
- filename: "discord/slashCommands",
729
- getContents: () => getSlashCommandTemplateContent(
730
- ctx,
731
- /* commandRuntime */
732
- false
733
- )
734
- });
735
- const typesTemplateDst = addTypeTemplate({
736
- filename: "discord/types.d.ts",
737
- // proposal-string-dedent when?
738
- getContents: () => `
739
- declare module 'discord/slashCommands' {
740
- declare const slashCommands: import('nuxt-discord').SlashCommandRuntime[]
741
- export default slashCommands
742
- }
743
-
744
- declare module '#build/discord/slashCommands' {
745
- declare const slashCommands: import('nuxt-discord').SlashCommand[]
746
- export default slashCommands
747
- }
748
-
749
- type integer = import('nuxt-discord').integer
750
-
751
- declare global {
752
- declare module 'nitropack/types' {
753
- interface NitroRuntimeHooks {
754
- 'discord:client:config': (options: import('nuxt-discord').NuxtDiscordOptions['client']) => void
755
- 'discord:client:ready': (client: DiscordClient) => void
756
- 'discord:client:error': (error: DiscordClientError) => void
757
- }
758
- }
759
-
760
- declare module '@nuxt/schema' {
761
- interface RuntimeConfig {
762
- discord: import('nuxt-discord').DiscordRuntimeConfig
763
- }
764
- interface PublicRuntimeConfig {
765
- discord: {
766
- wsUrl?: string
767
- }
768
- }
769
- }
770
- }
771
- `
772
- }).dst;
773
- ctx.nuxt.options.nitro.typescript ||= {};
774
- ctx.nuxt.options.nitro.typescript.tsConfig = defu(ctx.nuxt.options.nitro.typescript.tsConfig, {
775
- include: [typesTemplateDst]
776
- });
777
- }
778
- function getSlashCommandTemplateContent(ctx, commandRuntime) {
779
- const imports = commandRuntime ? Object.fromEntries(ctx.slashCommands.flatMap(
780
- function getImports(cmd) {
781
- const name = genSafeVariableName(cmd.path);
782
- return [
783
- [cmd.path, { name, code: genImport(cmd.path, [{ name: "default", as: name }]) }],
784
- ..."subcommands" in cmd ? cmd.subcommands.flatMap(getImports) : []
785
- ];
786
- }
787
- )) : {};
788
- return [
789
- ...Object.values(imports).map(({ code }) => code),
790
- `export default [
791
- ${ctx.slashCommands.map((cmd) => genCommandObject(cmd)).join(",\n")}]`
792
- ].join("\n");
793
- function genCommandObject({
794
- options,
795
- parents,
796
- subcommands,
797
- ...rest
798
- }) {
799
- return ` {
800
- ${Object.entries(rest).map(([key, value]) => `${key}: ${genString(value)}`).join(",\n ")},
801
- options: ${genArrayFromRaw(options, void 0, { preserveTypes: true })},
802
- ${subcommands.length > 0 ? `subcommands: [${subcommands.map(genCommandObject).join(",")}],` : ""}
803
- ${commandRuntime ? `...${imports[rest.path].name},` : ""}
804
- }`;
805
- }
806
- }
807
-
808
- const module = defineNuxtModule({
1311
+ const module$1 = defineNuxtModule({
809
1312
  meta: {
810
1313
  name: "nuxt-discord",
811
1314
  configKey: "discord"
812
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
+ },
813
1331
  defaults: {
814
1332
  client: {
815
1333
  intents: [GatewayIntentBits.Guilds],
@@ -829,18 +1347,121 @@ const module = defineNuxtModule({
829
1347
  },
830
1348
  setup(discordOptions, nuxt) {
831
1349
  const ctx = createContext(discordOptions, nuxt);
832
- addServerScanDir(ctx.resolve.module("runtime/server"));
833
- addImports([{
834
- name: "defineSlashCommand",
835
- as: "defineSlashCommand",
836
- from: ctx.resolve.module("runtime/server/utils/defineSlashCommand")
837
- }]);
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
+ ]);
838
1458
  prepareRuntimeConfig(ctx);
839
1459
  collectSlashCommands(ctx);
1460
+ collectContextMenus(ctx);
1461
+ collectListeners(ctx);
840
1462
  prepareTemplates(ctx);
841
1463
  prepareHMR(ctx);
842
- prepareClient(ctx);
843
1464
  }
844
1465
  });
845
1466
 
846
- export { module as default };
1467
+ export { module$1 as default };