nuxt-discord 0.0.13 → 0.0.15

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 CHANGED
@@ -253,7 +253,7 @@ Here's what's planned for future releases:
253
253
  - [ ] Better JSDocs support JSDoc comments
254
254
  - [ ] Localization support
255
255
  - [ ] File-based subcommands
256
- - [ ] Auto-complete API
256
+ - [x] Auto-complete API
257
257
  - [ ] Guild-specific commands
258
258
  - [ ] Nuxt-devtools integration
259
259
  - [ ] Unit tests
package/dist/module.d.mts CHANGED
@@ -3,7 +3,7 @@ import * as __runtime_logger from '../dist/runtime/logger.js';
3
3
  import * as _nuxt_kit from '@nuxt/kit';
4
4
  import * as nuxt_schema from 'nuxt/schema';
5
5
  import { DiscordClient } from '/Users/jeffz/Dev/nuxt-discord/dist/runtime/server/utils/client.js';
6
- import { IntegerOption, NumberOption, StringOption } from '../dist/runtime/server/utils/describeOption.js';
6
+ import { IntegerOption, NumberOption, StringOption, DescribeOptionOptions } from '../dist/runtime/server/utils/describeOption.js';
7
7
  import { ClientOptions, ApplicationCommandOptionType, ChatInputCommandInteraction } from 'discord.js';
8
8
  import { ListenOptions } from 'listhen';
9
9
  import { MaybeRef } from 'vue';
@@ -93,6 +93,7 @@ interface SlashCommandOptionBase {
93
93
  description: string;
94
94
  type: ApplicationCommandOptionType;
95
95
  required: boolean;
96
+ hasAutocomplete: boolean;
96
97
  }
97
98
  interface SlashCommandIntegerOption extends SlashCommandOptionBase, Omit<IntegerOption, 'name' | 'description'> {
98
99
  type: ApplicationCommandOptionType.Integer;
@@ -113,13 +114,16 @@ interface SlashCommand {
113
114
  name: string;
114
115
  description: string;
115
116
  path: string;
116
- options: SlashCommandOption[];
117
+ options: (SlashCommandOption & {
118
+ varname: string;
119
+ })[];
117
120
  }
118
121
  interface SlashCommandRuntime extends SlashCommand {
119
122
  /** if execute is not defined load must be defined */
120
- load?: () => Promise<SlashCommandRuntime['execute']>;
123
+ load?: () => Promise<Pick<SlashCommandRuntime, 'execute' | 'optionMacros'>>;
121
124
  execute?: (...args: (SlashCommandOptionType | undefined)[]) => SlashCommandReturnType;
122
125
  id?: string;
126
+ optionMacros?: Record<string, DescribeOptionOptions>;
123
127
  }
124
128
  interface NuxtDiscordContext {
125
129
  nuxt: nuxt_schema.Nuxt;
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-discord",
3
3
  "configKey": "discord",
4
- "version": "0.0.13",
4
+ "version": "0.0.15",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.1",
7
7
  "unbuild": "3.5.0"
package/dist/module.mjs CHANGED
@@ -1,9 +1,9 @@
1
- import { createResolver, installModule, extendPages, updateTemplates, addVitePlugin, isIgnored, addServerTemplate, addTemplate, addTypeTemplate, defineNuxtModule, addServerScanDir, addImports } from '@nuxt/kit';
1
+ import { createResolver, installModule, extendPages, updateTemplates, addVitePlugin, isIgnored, resolveAlias, addServerTemplate, addTemplate, addTypeTemplate, defineNuxtModule, addServerScanDir, addImports } from '@nuxt/kit';
2
2
  import { ApplicationCommandOptionType, GatewayIntentBits } from 'discord.js';
3
3
  import { logger } from '../dist/runtime/logger.js';
4
4
  import fs, { globSync, readFileSync } from 'node:fs';
5
5
  import path from 'node:path';
6
- import ts from 'typescript';
6
+ import ts, { isFunctionExpression, isArrowFunction } from 'typescript';
7
7
  import chokidar from 'chokidar';
8
8
  import { listen } from 'listhen';
9
9
  import { rollup } from 'rollup';
@@ -94,6 +94,8 @@ const macros = {
94
94
  const macroOptions = parseLiteral(node.arguments[1]);
95
95
  const validOptionKeys = ["name", "description", "min", "max", "minLength", "maxLength", "choices"];
96
96
  const isValidOptionKey = (key) => validOptionKeys.includes(key);
97
+ 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;
97
99
  for (const key in macroOptions) {
98
100
  if (!isValidOptionKey(key)) {
99
101
  ctx.logger.warn(`describeOption: unknown option key "${key}" for option "${name}" in command "${command.name}"`);
@@ -147,30 +149,25 @@ function parseLiteral(node) {
147
149
  return void 0;
148
150
  }
149
151
 
150
- function collectSlashCommands(ctx, out) {
152
+ function collectSlashCommands(ctx) {
151
153
  const commandFiles = globSync(`${ctx.resolve.root(ctx.options.dir, "commands")}/**/*.ts`);
152
- out ??= ctx.slashCommands;
154
+ ctx.slashCommands = [];
153
155
  for (const file of commandFiles) {
154
156
  const command = processCommandFile(ctx, file);
155
157
  if (command) {
156
- out.push(command);
158
+ ctx.slashCommands.push(command);
157
159
  }
158
160
  }
159
161
  }
160
162
  function processCommandFile(ctx, file) {
161
- const sourceFile = ts.createSourceFile(file, readFileSync(file).toString(), ts.ScriptTarget.Latest, true);
162
- let commandDefinition;
163
- ts.forEachChild(sourceFile, (node) => {
164
- if (ts.isExportAssignment(node)) {
165
- if (ts.isArrowFunction(node.expression)) {
166
- commandDefinition = node.expression;
167
- } 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]))) {
168
- commandDefinition = node.expression.arguments[0];
169
- }
170
- } else if (ts.isFunctionDeclaration(node) && !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.ExportDefault)) {
171
- commandDefinition = node;
172
- }
173
- });
163
+ const sourceFile = ts.createSourceFile(
164
+ file,
165
+ readFileSync(file).toString(),
166
+ ts.ScriptTarget.Latest,
167
+ /* setParentNodes */
168
+ true
169
+ );
170
+ const commandDefinition = extractCommandDefinition(sourceFile);
174
171
  if (!commandDefinition) {
175
172
  ctx.logger.warn(`No command definition found for ${file}`);
176
173
  return;
@@ -279,6 +276,8 @@ function processCommandFile(ctx, file) {
279
276
  type: typeIdentifierToEnum[type],
280
277
  description: jsdocDescription,
281
278
  required: !param.questionToken,
279
+ varname: name2,
280
+ hasAutocomplete: false,
282
281
  ...modifiers,
283
282
  ...choices ? {
284
283
  choices: choices.map((choice) => {
@@ -291,23 +290,53 @@ function processCommandFile(ctx, file) {
291
290
  } : {}
292
291
  });
293
292
  }
293
+ const [macroCalls, outOfRangMacroCalls] = extractMacroCalls(commandDefinition.body);
294
+ for (const macroCall of macroCalls) {
295
+ const macroName = macroCall.expression.escapedText;
296
+ macros[macroName](ctx, macroCall, command);
297
+ }
298
+ if (outOfRangMacroCalls.length > 0) {
299
+ ctx.logger.warn(`Macros in file ${file} must be called at the top of the file`);
300
+ }
301
+ return command;
302
+ }
303
+ function extractCommandDefinition(sourceFile) {
304
+ let commandDefinition;
305
+ ts.forEachChild(sourceFile, (node) => {
306
+ if (ts.isExportAssignment(node)) {
307
+ if (ts.isArrowFunction(node.expression)) {
308
+ commandDefinition = node.expression;
309
+ } 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]))) {
310
+ commandDefinition = node.expression.arguments[0];
311
+ }
312
+ } else if (ts.isFunctionDeclaration(node) && !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.ExportDefault)) {
313
+ commandDefinition = node;
314
+ }
315
+ });
316
+ return commandDefinition;
317
+ }
318
+ function extractMacroCalls(definitionBody) {
294
319
  let macrosEnd = false;
295
- let warned = false;
296
- ts.forEachChild(commandDefinition.body, (node) => {
297
- if (ts.isExpressionStatement(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText in macros) {
320
+ const macroCalls = [];
321
+ const outOfRangMacroCalls = [];
322
+ ts.forEachChild(definitionBody, (node) => {
323
+ if (isMacroCallExpression(node)) {
298
324
  if (macrosEnd) {
299
- if (!warned) {
300
- ctx.logger.warn(`${node.expression.expression.escapedText} macro must be called at the top in file ${file}`);
301
- warned = true;
302
- }
325
+ outOfRangMacroCalls.push(node.expression);
303
326
  return;
304
327
  }
305
- macros[node.expression.expression.escapedText](ctx, node.expression, command);
328
+ macroCalls.push(node.expression);
306
329
  } else {
307
330
  macrosEnd = true;
308
331
  }
309
332
  });
310
- return command;
333
+ return [
334
+ macroCalls,
335
+ outOfRangMacroCalls
336
+ ];
337
+ }
338
+ function isMacroCallExpression(node) {
339
+ return ts.isExpressionStatement(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText in macros;
311
340
  }
312
341
  function getJSDocTags(node) {
313
342
  const tags = ts.getJSDocTags(node);
@@ -326,6 +355,104 @@ function getJSDocTags(node) {
326
355
  return [];
327
356
  }
328
357
 
358
+ const TransformPlugin = (ctx) => {
359
+ const commandsDir = ctx.resolve.root(ctx.options.dir, "commands");
360
+ return {
361
+ name: "transform-slash-commands",
362
+ async load(id) {
363
+ if (!id.startsWith(commandsDir)) {
364
+ return;
365
+ }
366
+ try {
367
+ const sourceFile = ts.createSourceFile(
368
+ id,
369
+ fs.readFileSync(id, "utf-8"),
370
+ ts.ScriptTarget.Latest,
371
+ /* setParentNodes */
372
+ true
373
+ );
374
+ let commandDefinition = extractCommandDefinition(sourceFile);
375
+ if (!commandDefinition || !commandDefinition.body) {
376
+ return;
377
+ }
378
+ const transformer = (context) => {
379
+ return (sourceFile2) => {
380
+ const visitor = (node) => {
381
+ if (ts.isExportAssignment(node) || ts.isFunctionDeclaration(node) && !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.ExportDefault)) {
382
+ if (ts.isFunctionDeclaration(commandDefinition)) {
383
+ commandDefinition = ts.factory.createFunctionExpression(
384
+ ts.getModifiers(commandDefinition)?.filter((m) => m.kind !== ts.SyntaxKind.ExportKeyword && m.kind !== ts.SyntaxKind.DefaultKeyword),
385
+ commandDefinition.asteriskToken,
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
+ );
436
+ }
437
+ return ts.visitEachChild(node, visitor, context);
438
+ };
439
+ return ts.visitNode(sourceFile2, visitor);
440
+ };
441
+ };
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
+ }
452
+ }
453
+ };
454
+ };
455
+
329
456
  function prepareHMR(ctx) {
330
457
  const { nuxt, options } = ctx;
331
458
  if (nuxt.options.dev) {
@@ -348,8 +475,15 @@ function prepareHMR(ctx) {
348
475
  nitroIgnored.push(existingNitroIgnored);
349
476
  }
350
477
  nitroConfig.watchOptions.ignored = nitroIgnored;
351
- nitroConfig.hooks ??= {
352
- "rollup:before": (_, config) => {
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
+ ];
353
487
  rollupConfig = config;
354
488
  }
355
489
  };
@@ -378,12 +512,11 @@ function prepareHMR(ctx) {
378
512
  };
379
513
  listener.server.on("upgrade", websocket.serve);
380
514
  websocket.on("full-update", (client) => {
381
- const commands = [];
382
- collectSlashCommands(ctx, commands);
515
+ collectSlashCommands(ctx);
383
516
  try {
384
517
  client.send(JSON.stringify({
385
518
  event: "full-update",
386
- commands
519
+ commands: ctx.slashCommands
387
520
  }));
388
521
  } catch {
389
522
  }
@@ -496,8 +629,17 @@ async function generateDynamicCommandBuild(file, config, ctx) {
496
629
  bundle = await rollup({
497
630
  ...config,
498
631
  input: file,
499
- // externalize all modules except the command file itself, excluding .ts files
500
- external: (id) => !id.includes(file) && !id.endsWith(".ts")
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
+ ]
501
643
  });
502
644
  const { output } = await bundle.generate({ ...config.output, sourcemap: false });
503
645
  fs.mkdirSync(path.join(ctx.nuxt.options.buildDir, "discord", "commands"), { recursive: true });
@@ -527,17 +669,17 @@ function prepareTemplates(ctx) {
527
669
  filename: "discord/slashCommands",
528
670
  getContents: () => getSlashCommandTemplateContent(
529
671
  ctx,
530
- /* importExecute */
672
+ /* commandRuntime */
531
673
  true
532
674
  )
533
675
  });
534
676
  addTemplate({
535
677
  filename: "discord/slashCommands",
536
- getContents: () => `${getSlashCommandTemplateContent(
678
+ getContents: () => getSlashCommandTemplateContent(
537
679
  ctx,
538
- /* importExecute */
680
+ /* commandRuntime */
539
681
  false
540
- )}`
682
+ )
541
683
  });
542
684
  const typesTemplateDst = addTypeTemplate({
543
685
  filename: "discord/types.d.ts",
@@ -577,20 +719,23 @@ declare global {
577
719
  include: [typesTemplateDst]
578
720
  });
579
721
  }
580
- function getSlashCommandTemplateContent(ctx, importExecute) {
581
- const imports = importExecute ? ctx.slashCommands.map(({ path }) => {
722
+ function getSlashCommandTemplateContent(ctx, commandRuntime) {
723
+ const imports = commandRuntime ? ctx.slashCommands.map(({ path }) => {
582
724
  const name = genSafeVariableName(path);
583
725
  return { name, code: genImport(path, [{ name: "default", as: name }]) };
584
726
  }) : [];
585
727
  return [
586
728
  ...imports.map(({ code }) => code),
587
- `export default ${genArrayFromRaw(
588
- ctx.slashCommands.map(({ options, ...rest }, i) => ({
589
- ...Object.fromEntries(Object.entries(rest).map(([key, value]) => [key, genString(value)])),
590
- options: genArrayFromRaw(options, void 0, { preserveTypes: true }),
591
- ...importExecute ? { execute: imports[i].name } : {}
592
- }))
593
- )}`
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("")}]`
594
739
  ].join("\n");
595
740
  }
596
741
 
@@ -1,7 +1,6 @@
1
1
  <script setup>
2
2
  import { computed, ref, useFetch, useRuntimeConfig, watchEffect } from "#imports";
3
3
  import { useWebSocket } from "@vueuse/core";
4
- import slashCommands from "discord/slashCommands";
5
4
  import TheHeader from "../components/TheHeader.vue";
6
5
  import "../style.css";
7
6
  import "./slash-commands.css";
@@ -70,7 +69,7 @@ function getRemoteId(command) {
70
69
  }
71
70
  return void 0;
72
71
  }
73
- const commands = ref(slashCommands);
72
+ const commands = ref([]);
74
73
  const {
75
74
  data: diff,
76
75
  refresh: refreshDiff
@@ -330,6 +329,13 @@ const statusClasses = {
330
329
  color="error"
331
330
  size="sm"
332
331
  />
332
+ <UBadge
333
+ v-if="option.hasAutocomplete"
334
+ label="autocomplete"
335
+ variant="soft"
336
+ color="info"
337
+ size="sm"
338
+ />
333
339
  <!-- Restriction badges -->
334
340
  <UBadge
335
341
  v-if="'min' in option && option.min !== void 0"
@@ -1,4 +1,4 @@
1
- import type { APIApplicationCommand, ChatInputCommandInteraction, RESTGetAPIApplicationCommandsResult, RESTPutAPIApplicationCommandsResult } from 'discord.js';
1
+ import type { APIApplicationCommand, ChatInputCommandInteraction, CommandInteraction, RESTGetAPIApplicationCommandsResult, RESTPutAPIApplicationCommandsResult } from 'discord.js';
2
2
  import type { NuxtDiscordOptions, SlashCommandRuntime } from '../../../types.js';
3
3
  import { Client as InternalClient } from 'discord.js';
4
4
  export interface DiscordClientErrorBase {
@@ -7,17 +7,17 @@ export interface DiscordClientErrorBase {
7
7
  }
8
8
  export interface UnknownSlashCommandError extends DiscordClientErrorBase {
9
9
  type: 'UnknownSlashCommandError';
10
- interaction: ChatInputCommandInteraction;
10
+ interaction: CommandInteraction;
11
11
  }
12
12
  export interface MissingRequiredOptionError extends DiscordClientErrorBase {
13
13
  type: 'MissingRequiredOptionError';
14
- interaction: ChatInputCommandInteraction;
14
+ interaction: CommandInteraction;
15
15
  command: SlashCommandRuntime;
16
16
  option: string;
17
17
  }
18
18
  export interface SlashCommandExecutionError extends DiscordClientErrorBase {
19
19
  type: 'SlashCommandExecutionError';
20
- interaction: ChatInputCommandInteraction;
20
+ interaction: CommandInteraction;
21
21
  command: SlashCommandRuntime;
22
22
  error: unknown;
23
23
  }
@@ -37,11 +37,7 @@ export class DiscordClient {
37
37
  this.#clientOptions = { ...options };
38
38
  await this.#nitro.hooks.callHook("discord:client:config", this.#clientOptions);
39
39
  this.#client = new InternalClient(this.#clientOptions);
40
- this.#client.on(Events.InteractionCreate, (interaction) => {
41
- if (!interaction.isChatInputCommand())
42
- return;
43
- this.#handleSlashCommand(interaction);
44
- });
40
+ this.#client.on(Events.InteractionCreate, (interaction) => this.#handleInteraction(interaction));
45
41
  this.startScope();
46
42
  const { resolve, promise } = Promise.withResolvers();
47
43
  this.#client.once(Events.ClientReady, (readyClient) => {
@@ -52,6 +48,52 @@ export class DiscordClient {
52
48
  await this.#client.login(this.#token);
53
49
  return promise;
54
50
  }
51
+ async #handleInteraction(interaction) {
52
+ if (!interaction.isAutocomplete() && !interaction.isChatInputCommand()) {
53
+ return;
54
+ }
55
+ const commandName = interaction.commandName;
56
+ const command = this.#slashCommands.find((cmd) => cmd.name === commandName);
57
+ if (!command) {
58
+ logger.warn(`Unknown slash command: ${commandName}`);
59
+ this.#nitro.hooks.callHook("discord:client:error", {
60
+ type: "UnknownSlashCommandError",
61
+ client: this,
62
+ interaction
63
+ });
64
+ return;
65
+ }
66
+ if (!command.execute && command.load) {
67
+ try {
68
+ const dynamicCommand = await command.load();
69
+ Object.assign(command, dynamicCommand);
70
+ } catch (error) {
71
+ this.#nitro.hooks.callHook("discord:client:error", {
72
+ type: "SlashCommandExecutionError",
73
+ client: this,
74
+ interaction,
75
+ command,
76
+ error
77
+ });
78
+ return;
79
+ }
80
+ }
81
+ if (!command.execute && !command.load) {
82
+ this.#nitro.hooks.callHook("discord:client:error", {
83
+ type: "SlashCommandExecutionError",
84
+ client: this,
85
+ interaction,
86
+ command,
87
+ error: new Error(`Slash command "${commandName}" cannot be executed or loaded`)
88
+ });
89
+ return;
90
+ }
91
+ if (interaction.isAutocomplete()) {
92
+ await this.#handleAutocomplete(interaction, command);
93
+ } else if (interaction.isChatInputCommand()) {
94
+ await this.#handleSlashCommand(interaction, command);
95
+ }
96
+ }
55
97
  async stop() {
56
98
  if (this.#client) {
57
99
  await this.#client.destroy();
@@ -107,18 +149,7 @@ export class DiscordClient {
107
149
  }
108
150
  #interactionScopes = /* @__PURE__ */ new WeakMap();
109
151
  #commandFinalizationRegistry = new FinalizationRegistry((scope) => scope.stop());
110
- async #handleSlashCommand(interaction) {
111
- const name = interaction.commandName;
112
- const command = this.#slashCommands.find((cmd) => cmd.name === name);
113
- if (!command) {
114
- logger.warn(`Unknown slash command: ${name}`);
115
- this.#nitro.hooks.callHook("discord:client:error", {
116
- type: "UnknownSlashCommandError",
117
- client: this,
118
- interaction
119
- });
120
- return;
121
- }
152
+ async #handleSlashCommand(interaction, command) {
122
153
  const args = [];
123
154
  for (const option of command.options) {
124
155
  const opt = interaction.options.get(option.name, option.required);
@@ -134,29 +165,6 @@ export class DiscordClient {
134
165
  }
135
166
  args.push(opt?.value);
136
167
  }
137
- if (!command.execute && !command.load) {
138
- this.#nitro.hooks.callHook("discord:client:error", {
139
- type: "SlashCommandExecutionError",
140
- client: this,
141
- interaction,
142
- command,
143
- error: new Error(`Slash command "${name}" cannot be executed or loaded`)
144
- });
145
- return;
146
- } else if (!command.execute && command.load) {
147
- try {
148
- command.execute = await command.load();
149
- } catch (error) {
150
- this.#nitro.hooks.callHook("discord:client:error", {
151
- type: "SlashCommandExecutionError",
152
- client: this,
153
- interaction,
154
- command,
155
- error
156
- });
157
- return;
158
- }
159
- }
160
168
  let scope;
161
169
  if (this.#scope) {
162
170
  this.#scope.run(() => scope = effectScope());
@@ -235,6 +243,29 @@ export class DiscordClient {
235
243
  });
236
244
  }
237
245
  }
246
+ async #handleAutocomplete(interaction, command) {
247
+ const commandName = interaction.commandName;
248
+ if (!command) {
249
+ logger.warn(`Unknown slash command: ${commandName}`);
250
+ this.#nitro.hooks.callHook("discord:client:error", {
251
+ type: "UnknownSlashCommandError",
252
+ client: this,
253
+ interaction
254
+ });
255
+ return;
256
+ }
257
+ const focusedOption = interaction.options.getFocused(true);
258
+ const varname = command.options.find((opt) => opt.name === focusedOption.name)?.varname;
259
+ if (!varname) {
260
+ return;
261
+ }
262
+ const autocompleteFunction = command.optionMacros?.[varname]?.autocomplete;
263
+ if (!autocompleteFunction) {
264
+ return;
265
+ }
266
+ const choices = await autocompleteFunction(focusedOption.value, interaction);
267
+ await interaction.respond(choices);
268
+ }
238
269
  #getSlashCommandBuilder(command) {
239
270
  const builder = new SlashCommandBuilder().setName(command.name).setDescription(command.description);
240
271
  for (const option of command.options) {
@@ -250,6 +281,9 @@ export class DiscordClient {
250
281
  opt = opt.setMaxLength(option.maxLength);
251
282
  if (option.choices)
252
283
  opt = opt.addChoices(...option.choices);
284
+ if (option.hasAutocomplete) {
285
+ opt = opt.setAutocomplete(true);
286
+ }
253
287
  return opt;
254
288
  });
255
289
  break;
@@ -264,6 +298,8 @@ export class DiscordClient {
264
298
  opt = opt.setMaxValue(option.max);
265
299
  if (option.choices)
266
300
  opt = opt.addChoices(...option.choices);
301
+ if (option.hasAutocomplete)
302
+ opt = opt.setAutocomplete(true);
267
303
  return opt;
268
304
  });
269
305
  break;
@@ -278,6 +314,8 @@ export class DiscordClient {
278
314
  opt = opt.setMaxValue(option.max);
279
315
  if (option.choices)
280
316
  opt = opt.addChoices(...option.choices);
317
+ if (option.hasAutocomplete)
318
+ opt = opt.setAutocomplete(true);
281
319
  return opt;
282
320
  });
283
321
  break;
@@ -427,6 +465,9 @@ function optionEqual(a, b) {
427
465
  return false;
428
466
  }
429
467
  }
468
+ if (a.hasAutocomplete !== !!("autocomplete" in b && b.autocomplete)) {
469
+ return false;
470
+ }
430
471
  return true;
431
472
  }
432
473
  export function isPromise(value) {
@@ -1,4 +1,4 @@
1
- import type { APIApplicationCommandOptionChoice } from 'discord.js';
1
+ import type { APIApplicationCommandOptionChoice, ApplicationCommandOptionChoiceData, AutocompleteInteraction } from 'discord.js';
2
2
  import type { SlashCommandOptionType } from '../../../types.js';
3
3
  export interface DescribeOptionOptionsBase {
4
4
  /** The name of the command. */
@@ -6,6 +6,10 @@ export interface DescribeOptionOptionsBase {
6
6
  /** A brief description of the command. */
7
7
  description?: string;
8
8
  }
9
+ type MaybePromise<T> = T | Promise<T>;
10
+ interface AutocompleteFunction {
11
+ (value: string, interaction: AutocompleteInteraction): MaybePromise<ApplicationCommandOptionChoiceData[]>;
12
+ }
9
13
  export interface IntegerOption<T extends number = number> extends DescribeOptionOptionsBase {
10
14
  /** The minimum value for the integer option. */
11
15
  min?: number;
@@ -13,6 +17,8 @@ export interface IntegerOption<T extends number = number> extends DescribeOption
13
17
  max?: number;
14
18
  /** An array of choices for the integer option. */
15
19
  choices?: APIApplicationCommandOptionChoice<T>[];
20
+ /** A function to handle autocomplete for the integer option. */
21
+ autocomplete?: AutocompleteFunction;
16
22
  }
17
23
  export interface NumberOption<T extends number = number> extends DescribeOptionOptionsBase {
18
24
  /** The minimum value for the number option. */
@@ -21,6 +27,8 @@ export interface NumberOption<T extends number = number> extends DescribeOptionO
21
27
  max?: number;
22
28
  /** An array of choices for the number option. */
23
29
  choices?: APIApplicationCommandOptionChoice<T>[];
30
+ /** A function to handle autocomplete for the number option. */
31
+ autocomplete?: AutocompleteFunction;
24
32
  }
25
33
  export interface StringOption<T extends string = string> extends DescribeOptionOptionsBase {
26
34
  /** The minimum length of the string option. */
@@ -29,8 +37,11 @@ export interface StringOption<T extends string = string> extends DescribeOptionO
29
37
  maxLength?: number;
30
38
  /** An array of choices for the string option. */
31
39
  choices?: APIApplicationCommandOptionChoice<T>[];
40
+ /** A function to handle autocomplete for the string option. */
41
+ autocomplete?: AutocompleteFunction;
32
42
  }
33
43
  export type DescribeOptionOptions = IntegerOption | NumberOption | StringOption;
44
+ export type NarrowedDescribeOptionOptions<T extends SlashCommandOptionType> = T extends integer ? IntegerOption<T> : T extends number ? NumberOption<T> : T extends string ? StringOption<T> : never;
34
45
  /**
35
46
  * A compiler macro that describes a slash command option. Used for defining
36
47
  * metadata for registering slash command options. Options defined here will
@@ -54,4 +65,5 @@ export type DescribeOptionOptions = IntegerOption | NumberOption | StringOption;
54
65
  * ],
55
66
  * })
56
67
  */
57
- export declare function describeOption<const T extends SlashCommandOptionType>(_option: T | undefined, _options: T extends integer ? IntegerOption<T> : T extends number ? NumberOption<T> : T extends string ? StringOption<T> : never): void;
68
+ export declare function describeOption<const T extends SlashCommandOptionType>(_option: T | undefined, _options: NarrowedDescribeOptionOptions<T>): void;
69
+ export {};
@@ -1,8 +1,14 @@
1
- import type { BaseMessageOptions, InteractionCallbackResponse, InteractionReplyOptions, InteractionResponse, Message } from 'discord.js';
1
+ import type { BaseMessageOptions, ButtonComponentData, ButtonInteraction, InteractionCallbackResponse, InteractionReplyOptions, InteractionResponse, Message, MessageCollectorOptionsParams } from 'discord.js';
2
2
  import type { MaybeRef } from 'vue';
3
3
  import type { SlashCommandCustomReturnHandler } from '../../../types.js';
4
+ import { ComponentType } from 'discord.js';
4
5
  type OmitPreservingCallSignature<T, K extends keyof T = keyof T> = Omit<T, K> & (T extends (...args: infer R) => infer S ? (...args: R) => S : unknown);
5
6
  type File = NonNullable<BaseMessageOptions['files']>[number];
7
+ type ButtonCollectorOptions = Partial<Omit<MessageCollectorOptionsParams<ComponentType.Button>, 'componentType'>>;
8
+ type MaybeRefObject<T> = T extends any ? {
9
+ [K in keyof T]: MaybeRef<T[K]>;
10
+ } : never;
11
+ type DistributiveOmit<T, K extends keyof T> = T extends any ? Omit<T, K> : never;
6
12
  type ReplyFunction = SlashCommandCustomReturnHandler & {
7
13
  (text?: MaybeRef<string>, options?: InteractionReplyOptions): SlashCommandCustomReturnHandler & {
8
14
  [Symbol.iterator]: () => {
@@ -16,6 +22,13 @@ type ReplyFunction = SlashCommandCustomReturnHandler & {
16
22
  flags: (flags: MaybeRef<InteractionReplyOptions['flags']>) => ReplyFunction;
17
23
  file: (file: MaybeRef<File>) => ReplyFunction;
18
24
  files: (files: MaybeRef<File[]>) => ReplyFunction;
25
+ button: {
26
+ (label: MaybeRef<string>, handler: (interaction: ButtonInteraction) => void | Promise<void>, options?: Partial<MaybeRefObject<DistributiveOmit<ButtonComponentData, 'label' | 'type'>>> & {
27
+ defer?: boolean;
28
+ hide?: MaybeRef<boolean>;
29
+ collector?: ButtonCollectorOptions;
30
+ }): ReplyFunction;
31
+ };
19
32
  send: ReplyFunction;
20
33
  };
21
34
  export declare const reply: ReplyFunction;
@@ -1,12 +1,46 @@
1
- import { MessageFlags } from "discord.js";
2
- import { isRef, reactive, watch } from "vue";
3
- function createReplyFunction({ ...defaultOptions } = {}) {
1
+ import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType, MessageFlags } from "discord.js";
2
+ import { computed, isRef, reactive, toValue, watch } from "vue";
3
+ function createReplyFunction({
4
+ buttons,
5
+ ...defaultOptions
6
+ } = {}) {
4
7
  const reply2 = (...args) => {
5
- if (typeof args[0] === "string" || typeof args[0] === "undefined" || isRef(args[0]) || typeof args[0] === "function") {
8
+ const buttonComponents = computed(() => getButtonComponent(buttons ?? []));
9
+ let buttonInteractionCollectors = [];
10
+ function registerButtonCollectors(msg) {
11
+ for (const collector of buttonInteractionCollectors) {
12
+ collector.stop();
13
+ }
14
+ buttonInteractionCollectors = [];
15
+ for (const [_, handler, options] of buttons ?? []) {
16
+ let collectorOptions;
17
+ if (options && "collector" in options && options.collector) {
18
+ collectorOptions = options.collector;
19
+ }
20
+ if ("resource" in msg) {
21
+ buttonInteractionCollectors.push(msg.resource.message.createMessageComponentCollector({
22
+ componentType: ComponentType.Button,
23
+ ...collectorOptions
24
+ }));
25
+ } else {
26
+ buttonInteractionCollectors.push(msg.createMessageComponentCollector({
27
+ componentType: ComponentType.Button,
28
+ ...collectorOptions
29
+ }));
30
+ }
31
+ buttonInteractionCollectors[buttonInteractionCollectors.length - 1].on("collect", async (buttonInteraction) => {
32
+ if (options?.defer ?? true)
33
+ buttonInteraction.deferUpdate();
34
+ await handler(buttonInteraction);
35
+ });
36
+ }
37
+ }
38
+ if (typeof args[0] === "string" || typeof args[0] === "undefined" || isRef(args[0])) {
6
39
  const [text, options] = args;
7
40
  let message;
8
41
  const replyOptions = reactive({
9
42
  content: text,
43
+ ...buttonComponents.value.length > 0 ? { components: buttonComponents } : {},
10
44
  ...defaultOptions,
11
45
  ...options
12
46
  });
@@ -14,7 +48,10 @@ function createReplyFunction({ ...defaultOptions } = {}) {
14
48
  const method = interaction.replied ? "followUp" : interaction.deferred ? "editReply" : "reply";
15
49
  message = interaction[method](
16
50
  replyOptions
17
- ).catch((err) => err);
51
+ ).then((msg) => {
52
+ registerButtonCollectors(msg);
53
+ return msg;
54
+ }).catch((err) => err);
18
55
  return message;
19
56
  };
20
57
  Object.defineProperty(handler, Symbol.iterator, {
@@ -34,6 +71,7 @@ function createReplyFunction({ ...defaultOptions } = {}) {
34
71
  msg.edit(options2);
35
72
  else
36
73
  msg.resource?.message?.edit(options2);
74
+ registerButtonCollectors(msg);
37
75
  }, { deep: true, flush: "sync" });
38
76
  return handler;
39
77
  } else {
@@ -49,6 +87,7 @@ function createReplyFunction({ ...defaultOptions } = {}) {
49
87
  message.edit(opts);
50
88
  else
51
89
  message.resource?.message?.edit(opts);
90
+ registerButtonCollectors(message);
52
91
  }, { deep: true, flush: "sync" });
53
92
  return {
54
93
  [Symbol.iterator]: () => ({
@@ -70,33 +109,76 @@ function createReplyFunction({ ...defaultOptions } = {}) {
70
109
  }
71
110
  },
72
111
  flags: {
73
- get() {
74
- return (flags) => createReplyFunction({
75
- ...defaultOptions,
76
- flags
77
- });
78
- }
112
+ value: (flags) => createReplyFunction({
113
+ ...defaultOptions,
114
+ flags
115
+ })
79
116
  },
80
117
  file: {
81
- get() {
82
- return (file) => createReplyFunction({
83
- ...defaultOptions,
84
- files: defaultOptions.files != null ? [...defaultOptions.files, file] : [file]
85
- });
86
- }
118
+ value: (file) => createReplyFunction({
119
+ ...defaultOptions,
120
+ files: defaultOptions.files != null ? [...defaultOptions.files, file] : [file]
121
+ })
87
122
  },
88
123
  files: {
89
- get() {
90
- return (files) => createReplyFunction({
91
- ...defaultOptions,
92
- files: defaultOptions.files != null ? [...defaultOptions.files, ...files] : files
93
- });
94
- }
124
+ value: (files) => createReplyFunction({
125
+ ...defaultOptions,
126
+ files: defaultOptions.files != null ? [...defaultOptions.files, ...files] : files
127
+ })
95
128
  },
96
129
  send: {
97
130
  value: reply2
131
+ },
132
+ button: {
133
+ value: (...args) => {
134
+ return createReplyFunction({
135
+ ...defaultOptions,
136
+ buttons: [
137
+ ...buttons ?? [],
138
+ args
139
+ ]
140
+ });
141
+ }
98
142
  }
99
143
  });
100
144
  return reply2;
101
145
  }
102
146
  export const reply = createReplyFunction();
147
+ function getButtonComponent(buttons) {
148
+ if (buttons.length === 0)
149
+ return [];
150
+ let row = new ActionRowBuilder();
151
+ const rows = [row];
152
+ const it = Iterator.from(buttons).filter(([, , options]) => !(toValue(options?.hide) ?? false)).map(([label, , options]) => {
153
+ if (options == null) {
154
+ options = {};
155
+ }
156
+ if (toValue(options.style) == null) {
157
+ options.style = ButtonStyle.Primary;
158
+ }
159
+ if (options.style === ButtonStyle.Primary) {
160
+ if (!("customId" in options) || options.customId == null) {
161
+ options.customId = `${Date.now()}`;
162
+ }
163
+ }
164
+ return new ButtonBuilder(
165
+ Object.fromEntries(
166
+ Object.entries({
167
+ label,
168
+ ...options,
169
+ type: ComponentType.Button
170
+ }).map(([key, value]) => [key, toValue(value)])
171
+ )
172
+ );
173
+ });
174
+ for (let i = 0; i < 5; i++) {
175
+ row.addComponents(...Array.from(it.take(5)));
176
+ if (row.components.length >= 5) {
177
+ row = new ActionRowBuilder();
178
+ rows.push(row);
179
+ }
180
+ }
181
+ if (row.components.length === 0)
182
+ rows.pop();
183
+ return rows;
184
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-discord",
3
3
  "type": "module",
4
- "version": "0.0.13",
4
+ "version": "0.0.15",
5
5
  "description": "A Nuxt module for building Discord bots",
6
6
  "author": "Jize Zou <jeffzou2001@gmail.com> (https://github.com/zojize)",
7
7
  "license": "MIT",
@@ -34,37 +34,37 @@
34
34
  "discord.js": "^14.21.0"
35
35
  },
36
36
  "dependencies": {
37
- "@nuxt/kit": "^3.17.5",
37
+ "@nuxt/kit": "^3.17.6",
38
38
  "@nuxt/ui": "^3.2.0",
39
39
  "ansis": "^4.1.0",
40
40
  "chokidar": "^4.0.3",
41
41
  "defu": "^6.1.4",
42
42
  "knitwork": "^1.2.0",
43
43
  "listhen": "^1.9.0",
44
- "rollup": "^4.44.1",
45
- "simple-icons": "^15.3.0",
46
- "unocss": "^66.3.2",
47
- "ws": "^8.18.2"
44
+ "rollup": "^4.45.0",
45
+ "simple-icons": "^15.5.0",
46
+ "unocss": "^66.3.3",
47
+ "ws": "^8.18.3"
48
48
  },
49
49
  "devDependencies": {
50
- "@antfu/eslint-config": "^4.16.1",
51
- "@nuxt/devtools": "^2.5.0",
52
- "@nuxt/eslint-config": "^1.4.1",
50
+ "@antfu/eslint-config": "^4.16.2",
51
+ "@nuxt/devtools": "^2.6.2",
52
+ "@nuxt/eslint-config": "^1.5.2",
53
53
  "@nuxt/module-builder": "^1.0.1",
54
- "@nuxt/schema": "^3.17.5",
55
- "@nuxt/test-utils": "^3.19.1",
56
- "@types/node": "^24.0.4",
57
- "@unocss/eslint-plugin": "^66.3.2",
58
- "@vueuse/core": "^13.4.0",
59
- "changelogen": "^0.6.1",
60
- "eslint": "^9.29.0",
54
+ "@nuxt/schema": "^3.17.6",
55
+ "@nuxt/test-utils": "^3.19.2",
56
+ "@types/node": "^24.0.13",
57
+ "@unocss/eslint-plugin": "^66.3.3",
58
+ "@vueuse/core": "^13.5.0",
59
+ "changelogen": "^0.6.2",
60
+ "eslint": "^9.31.0",
61
61
  "lint-staged": "^16.1.2",
62
- "nuxt": "^3.17.5",
62
+ "nuxt": "^3.17.6",
63
63
  "simple-git-hooks": "^2.13.0",
64
64
  "typescript": "~5.8.3",
65
65
  "unbuild": "^3.5.0",
66
66
  "vitest": "^3.2.4",
67
- "vue-tsc": "^2.2.10"
67
+ "vue-tsc": "^2.2.12"
68
68
  },
69
69
  "resolutions": {
70
70
  "nuxt-discord": "workspace:*"