nuxt-discord 0.0.8 → 0.0.9

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
@@ -29,11 +29,16 @@ export default defineNuxtConfig({
29
29
  modules: ['nuxt-discord'],
30
30
  discord: {
31
31
  // Discord bot configuration
32
- intents: ['Guilds'], // Discord gateway intents
32
+ client: {
33
+ intents: ['Guilds'], // Discord gateway intents
34
+ deferOnPromise: true, // Auto-defer interactions when command returns a promise
35
+ },
33
36
  dir: 'discord', // Directory for Discord-related files
34
37
  autoStart: true, // Auto-start the bot on server startup
35
38
  watch: {
36
39
  enabled: true, // Enable HMR for commands
40
+ port: 5720, // HMR server port
41
+ showURL: false, // Show HMR server URL in console
37
42
  sync: {
38
43
  debounce: 1000 // Sync delay in milliseconds
39
44
  }
@@ -209,15 +214,19 @@ export default (message: string) => {
209
214
  // nuxt.config.ts
210
215
  export default defineNuxtConfig({
211
216
  discord: {
212
- intents: [
213
- 'Guilds',
214
- 'GuildMessages'
215
- ],
217
+ client: {
218
+ intents: [
219
+ 'Guilds',
220
+ 'GuildMessages'
221
+ ],
222
+ deferOnPromise: true, // Auto-defer interactions when command returns a promise
223
+ },
216
224
  dir: 'discord',
217
225
  autoStart: true,
218
226
  watch: {
219
227
  enabled: true,
220
- port: 4222,
228
+ port: 5720, // HMR server port
229
+ showURL: false, // Show HMR server URL in console
221
230
  sync: {
222
231
  debounce: 1000
223
232
  }
package/dist/module.d.mts CHANGED
@@ -6,15 +6,29 @@ import { IntegerOption, NumberOption, StringOption } from '../dist/runtime/serve
6
6
  import { ClientOptions, ApplicationCommandOptionType, ChatInputCommandInteraction } from 'discord.js';
7
7
  import { ListenOptions } from 'listhen';
8
8
 
9
+ declare const logger: {
10
+ log: (...args: unknown[]) => void;
11
+ warn: (...args: unknown[]) => void;
12
+ error: (...args: unknown[]) => void;
13
+ };
14
+
9
15
  interface NuxtDiscordOptions {
10
16
  /**
11
- * The intents to use for the Discord client. Use
12
- * the 'nitro:client:config' hook to configure other
13
- * options passed to the Discord client.
17
+ * Options passed to the internal Discord client.
18
+ * Use the 'nitro:client:config' hook to configure
19
+ * client options in runtime.
14
20
  *
15
- * @default [GatewayIntentBits.Guilds]
21
+ * @default { intents: [GatewayIntentBits.Guilds] }
16
22
  */
17
- intents: ClientOptions['intents'];
23
+ client: ClientOptions & {
24
+ /**
25
+ * Whether to automatically defer the interaction reply
26
+ * on slash command execution if the command returns a promise.
27
+ *
28
+ * @default true
29
+ */
30
+ deferOnPromise?: boolean;
31
+ };
18
32
  /**
19
33
  * The directory to scan for nuxt-discord related
20
34
  * files, such as slash commands.
@@ -31,14 +45,13 @@ interface NuxtDiscordOptions {
31
45
  /**
32
46
  * HMR options
33
47
  */
34
- watch: {
48
+ watch: Partial<ListenOptions> & {
35
49
  /**
36
50
  * Enable or disable HMR for slash commands.
37
51
  *
38
52
  * @default true
39
53
  */
40
54
  enabled?: boolean;
41
- } & {
42
55
  /**
43
56
  * Whether to automatically register and update
44
57
  * slash commands on the Discord client.
@@ -52,10 +65,10 @@ interface NuxtDiscordOptions {
52
65
  */
53
66
  debounce?: number;
54
67
  };
55
- } & Partial<ListenOptions>;
68
+ };
56
69
  }
57
70
  interface DiscordRuntimeConfig {
58
- intents: ClientOptions['intents'];
71
+ client: NuxtDiscordOptions['client'];
59
72
  autoStart: boolean;
60
73
  sync: NuxtDiscordOptions['watch']['sync'];
61
74
  dir: string;
@@ -120,7 +133,7 @@ interface NuxtDiscordContext {
120
133
  root: _nuxt_kit.Resolver['resolve'];
121
134
  module: _nuxt_kit.Resolver['resolve'];
122
135
  };
123
- logger: ReturnType<typeof _nuxt_kit.useLogger>;
136
+ logger: typeof logger;
124
137
  }
125
138
 
126
139
  declare const _default: _nuxt_schema.NuxtModule<NuxtDiscordOptions, NuxtDiscordOptions, false>;
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-discord",
3
3
  "configKey": "discord",
4
- "version": "0.0.8",
4
+ "version": "0.0.9",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.1",
7
7
  "unbuild": "3.5.0"
package/dist/module.mjs CHANGED
@@ -1,5 +1,6 @@
1
- import { useLogger, createResolver, installModule, extendPages, updateTemplates, addVitePlugin, isIgnored, addServerTemplate, addTemplate, addTypeTemplate, defineNuxtModule, addServerScanDir, addImports } from '@nuxt/kit';
1
+ import { createResolver, installModule, extendPages, updateTemplates, addVitePlugin, isIgnored, addServerTemplate, addTemplate, addTypeTemplate, defineNuxtModule, addServerScanDir, addImports } from '@nuxt/kit';
2
2
  import { ApplicationCommandOptionType, GatewayIntentBits } from 'discord.js';
3
+ import ansis from 'ansis';
3
4
  import { globSync, readFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
4
5
  import path from 'node:path';
5
6
  import ts from 'typescript';
@@ -10,6 +11,13 @@ import { WebSocketServer } from 'ws';
10
11
  import defu from 'defu';
11
12
  import { genSafeVariableName, genImport, genArrayFromRaw, genString } from 'knitwork';
12
13
 
14
+ const logger = {
15
+ // eslint-disable-next-line no-console
16
+ log: (...args) => console.log(ansis.hex("#5865F2").bold("[Discord]"), ...args),
17
+ warn: (...args) => console.warn(ansis.yellow.bold("[Discord]"), ...args),
18
+ error: (...args) => console.error(ansis.red.bold("[Discord]"), ...args)
19
+ };
20
+
13
21
  function createContext(options, nuxt) {
14
22
  return {
15
23
  nuxt,
@@ -19,7 +27,7 @@ function createContext(options, nuxt) {
19
27
  root: createResolver(nuxt.options.rootDir).resolve,
20
28
  module: createResolver(import.meta.url).resolve
21
29
  },
22
- logger: useLogger("nuxt-discord")
30
+ logger
23
31
  };
24
32
  }
25
33
 
@@ -308,11 +316,15 @@ function prepareHMR(ctx) {
308
316
  });
309
317
  }
310
318
  chokidar.watch(ctx.resolve.root(ctx.options.dir, "commands"), { ignoreInitial: true }).on("all", async (event, path2) => {
319
+ if (event === "all" || event === "error" || event === "raw") {
320
+ return;
321
+ }
311
322
  const fullPath = ctx.resolve.root(path2);
312
323
  if (fullPath.startsWith(commandsDir)) {
313
324
  path2 = ctx.resolve.root(path2);
314
325
  const command = processCommandFile(ctx, path2) ?? null;
315
326
  if (event === "add" || event === "change") {
327
+ ctx.logger.log(`Dynamically loading slash command at ${path2}`);
316
328
  await generateDynamicCommandBuild(path2, rollupConfig, ctx);
317
329
  }
318
330
  websocket?.broadcast({ event, path: path2, command });
@@ -403,7 +415,12 @@ function createWebSocket() {
403
415
  async function generateDynamicCommandBuild(file, config, ctx) {
404
416
  let bundle;
405
417
  try {
406
- bundle = await rollup({ ...config, input: file });
418
+ bundle = await rollup({
419
+ ...config,
420
+ input: file,
421
+ // externalize all modules except the command file itself
422
+ external: (id) => !id.includes(file)
423
+ });
407
424
  const { output } = await bundle.generate({ ...config.output, sourcemap: false });
408
425
  mkdirSync(path.join(ctx.nuxt.options.buildDir, "discord", "commands"), { recursive: true });
409
426
  writeFileSync(file.replace(ctx.resolve.root(ctx.nuxt.options.rootDir), ctx.nuxt.options.buildDir).replace(".ts", ".mjs"), output[0].code, { encoding: "utf-8", flush: true });
@@ -418,7 +435,7 @@ function prepareRuntimeConfig(ctx) {
418
435
  ctx.nuxt.hook("nitro:config", (config) => {
419
436
  config.runtimeConfig ??= {};
420
437
  config.runtimeConfig.discord ??= {};
421
- config.runtimeConfig.discord.intents = ctx.options.intents;
438
+ config.runtimeConfig.discord.client = ctx.options.client;
422
439
  config.runtimeConfig.discord.autoStart = ctx.options.autoStart;
423
440
  config.runtimeConfig.discord.sync = ctx.options.watch.sync ?? false;
424
441
  config.runtimeConfig.discord.dir = ctx.resolve.root(ctx.options.dir);
@@ -458,7 +475,7 @@ type integer = import('nuxt-discord').integer
458
475
  declare global {
459
476
  declare module 'nitropack/types' {
460
477
  interface NitroRuntimeHooks {
461
- 'discord:client:config': (options: import('discord.js').ClientOptions) => void
478
+ 'discord:client:config': (options: import('nuxt-discord').NuxtDiscordOptions['client']) => void
462
479
  'discord:client:ready': (client: DiscordClient) => void
463
480
  'discord:client:error': (error: DiscordClientError) => void
464
481
  }
@@ -505,12 +522,15 @@ const module = defineNuxtModule({
505
522
  configKey: "discord"
506
523
  },
507
524
  defaults: {
508
- intents: [GatewayIntentBits.Guilds],
525
+ client: {
526
+ intents: [GatewayIntentBits.Guilds],
527
+ deferOnPromise: true
528
+ },
509
529
  dir: "discord",
510
530
  autoStart: true,
511
531
  watch: {
512
532
  enabled: true,
513
- port: 4222,
533
+ port: 5720,
514
534
  showURL: false,
515
535
  sync: {
516
536
  debounce: 1e3
@@ -134,18 +134,6 @@ const stats = computed(() => commandsWithStatus.value.reduce((acc, cmd) => {
134
134
  acc.conflict++;
135
135
  return acc;
136
136
  }, { added: 0, removed: 0, changed: 0, synced: 0, conflict: 0 }));
137
- const pendingSync = ref(false);
138
- async function syncCommands() {
139
- try {
140
- pendingSync.value = true;
141
- await $fetch("/api/discord/slash-command/register", { method: "POST" });
142
- await refreshDiff();
143
- } catch (error) {
144
- console.error("Error registering commands:", error);
145
- } finally {
146
- pendingSync.value = false;
147
- }
148
- }
149
137
  const runtimeConfig = useRuntimeConfig();
150
138
  let ws;
151
139
  if (import.meta.dev && runtimeConfig.public.discord?.wsUrl) {
@@ -154,13 +142,26 @@ if (import.meta.dev && runtimeConfig.public.discord?.wsUrl) {
154
142
  } else {
155
143
  ws = useWebSocket(runtimeConfig.public.discord.wsUrl, {
156
144
  autoReconnect: true,
157
- onConnected: () => {
145
+ onConnected: (ws2) => {
158
146
  console.log("WebSocket connection established for slash command hot reload");
159
- ws?.send(JSON.stringify({ event: "full-update" }));
147
+ ws2.send(JSON.stringify({ event: "full-update" }));
160
148
  }
161
149
  });
162
150
  }
163
151
  }
152
+ const pendingSync = ref(false);
153
+ async function syncCommands() {
154
+ try {
155
+ pendingSync.value = true;
156
+ await $fetch("/api/discord/slash-command/register", { method: "POST" });
157
+ await refreshDiff();
158
+ ws?.send(JSON.stringify({ event: "full-update" }));
159
+ } catch (error) {
160
+ console.error("Error registering commands:", error);
161
+ } finally {
162
+ pendingSync.value = false;
163
+ }
164
+ }
164
165
  watchEffect(() => {
165
166
  const message = ws?.data.value;
166
167
  if (!message)
@@ -1,7 +1,7 @@
1
- import { existsSync } from "node:fs";
1
+ import fs from "node:fs";
2
2
  import slashCommands from "discord/slashCommands";
3
3
  import { defineNitroPlugin, useRuntimeConfig } from "nitropack/runtime";
4
- import { logger } from "../internal/logger.js";
4
+ import { logger } from "../../../logger";
5
5
  import { DiscordClient } from "../utils/client.js";
6
6
  export default defineNitroPlugin(async (nitro) => {
7
7
  const runtimeConfig = useRuntimeConfig();
@@ -20,9 +20,9 @@ export default defineNitroPlugin(async (nitro) => {
20
20
  const runtimeCommand = cmd;
21
21
  const buildPath = cmd.path.replace(runtimeConfig.discord.rootDir, runtimeConfig.discord.buildDir).replace(/\.ts$/, ".mjs");
22
22
  const existingCommand = slashCommands.find((c) => c.path === cmd.path);
23
- if (existsSync(buildPath)) {
24
- logger.log(`Dynamically loading slash command at ${buildPath}`);
25
- runtimeCommand.load = () => import(`${buildPath}?${Date.now()}`).then((m) => m.default);
23
+ if (fs.existsSync(buildPath)) {
24
+ const lastModified = fs.statSync(buildPath).mtimeMs;
25
+ runtimeCommand.load = () => import(`${buildPath}?${lastModified}`).then((m) => m.default);
26
26
  } else if (existingCommand) {
27
27
  runtimeCommand.execute = existingCommand.execute;
28
28
  } else {
@@ -44,7 +44,6 @@ export default defineNitroPlugin(async (nitro) => {
44
44
  await client.registerSlashCommands();
45
45
  }
46
46
  if (runtimeConfig.discord.autoStart) {
47
- const options = { intents: runtimeConfig.discord.intents };
48
- await client.start(options);
47
+ await client.start(runtimeConfig.discord.client);
49
48
  }
50
49
  });
@@ -1,5 +1,5 @@
1
- import type { APIApplicationCommand, ChatInputCommandInteraction, ClientOptions, RESTGetAPIApplicationCommandsResult, RESTPutAPIApplicationCommandsResult } from 'discord.js';
2
- import type { SlashCommandRuntime } from '~/src/types';
1
+ import type { APIApplicationCommand, ChatInputCommandInteraction, RESTGetAPIApplicationCommandsResult, RESTPutAPIApplicationCommandsResult } from 'discord.js';
2
+ import type { NuxtDiscordOptions, SlashCommandRuntime } from '~/src/types';
3
3
  import { Client as InternalClient } from 'discord.js';
4
4
  export interface DiscordClientErrorBase {
5
5
  type: string;
@@ -32,7 +32,7 @@ export declare class DiscordClient {
32
32
  #private;
33
33
  get internalClient(): InternalClient<boolean> | null;
34
34
  constructor();
35
- start(options: ClientOptions): Promise<undefined>;
35
+ start(options: NuxtDiscordOptions['client']): Promise<undefined>;
36
36
  stop(): Promise<void>;
37
37
  isReady(): boolean;
38
38
  addSlashCommand(command: SlashCommandRuntime): void;
@@ -57,3 +57,4 @@ export declare class DiscordClient {
57
57
  }>;
58
58
  registerSlashCommands(): Promise<RESTPutAPIApplicationCommandsResult | PromiseSettledResult<APIApplicationCommand>[]>;
59
59
  }
60
+ export declare function isPromise(value: any): value is Promise<unknown>;
@@ -1,7 +1,7 @@
1
1
  import process from "node:process";
2
2
  import { ApplicationCommandOptionType, Events, Client as InternalClient, REST, Routes, SlashCommandBuilder } from "discord.js";
3
3
  import { useNitroApp } from "nitropack/runtime";
4
- import { logger } from "../internal/logger.js";
4
+ import { logger } from "../../../logger";
5
5
  let currentInteraction = null;
6
6
  export function useInteraction() {
7
7
  return currentInteraction;
@@ -30,9 +30,11 @@ export class DiscordClient {
30
30
  logger.error(error);
31
31
  });
32
32
  }
33
+ #clientOptions;
33
34
  async start(options) {
34
- await this.#nitro.hooks.callHook("discord:client:config", options);
35
- this.#client = new InternalClient(options);
35
+ this.#clientOptions = { ...options };
36
+ await this.#nitro.hooks.callHook("discord:client:config", this.#clientOptions);
37
+ this.#client = new InternalClient(this.#clientOptions);
36
38
  this.#client.on(Events.InteractionCreate, (interaction) => {
37
39
  if (!interaction.isChatInputCommand())
38
40
  return;
@@ -136,9 +138,12 @@ export class DiscordClient {
136
138
  }
137
139
  try {
138
140
  currentInteraction = interaction;
139
- const result = await command.execute(...args);
141
+ const result = command.execute(...args);
140
142
  currentInteraction = null;
141
- this.#handleSlashCommandReturn(result, interaction, command);
143
+ if (this.#clientOptions?.deferOnPromise && isPromise(result)) {
144
+ await interaction.deferReply();
145
+ }
146
+ await this.#handleSlashCommandReturn(result, interaction, command);
142
147
  } catch (error) {
143
148
  this.#nitro.hooks.callHook("discord:client:error", {
144
149
  type: "SlashCommandExecutionError",
@@ -150,6 +155,7 @@ export class DiscordClient {
150
155
  }
151
156
  }
152
157
  async #handleSlashCommandReturn(result, interaction, command) {
158
+ result = await result;
153
159
  if (!result) {
154
160
  return;
155
161
  }
@@ -158,7 +164,7 @@ export class DiscordClient {
158
164
  return interaction.reply({ content: result });
159
165
  } else if (typeof result === "function") {
160
166
  const newResult = result.call(this, interaction, this);
161
- return this.#handleSlashCommandReturn(await newResult, interaction, command);
167
+ return this.#handleSlashCommandReturn(newResult, interaction, command);
162
168
  } else if (Symbol.iterator in result && typeof result[Symbol.iterator] === "function") {
163
169
  const gen = result[Symbol.iterator]();
164
170
  let next = gen.next();
@@ -387,3 +393,6 @@ function optionEqual(a, b) {
387
393
  }
388
394
  return true;
389
395
  }
396
+ export function isPromise(value) {
397
+ return typeof value?.then === "function";
398
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-discord",
3
3
  "type": "module",
4
- "version": "0.0.8",
4
+ "version": "0.0.9",
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",
@@ -1,5 +0,0 @@
1
- export declare const logger: {
2
- log: (...args: unknown[]) => void;
3
- warn: (...args: unknown[]) => void;
4
- error: (...args: unknown[]) => void;
5
- };
@@ -1,7 +0,0 @@
1
- import ansis from "ansis";
2
- export const logger = {
3
- // eslint-disable-next-line no-console
4
- log: (...args) => console.log(ansis.hex("#5865F2").bold("[Discord]"), ...args),
5
- warn: (...args) => console.warn(ansis.yellow.bold("[Discord]"), ...args),
6
- error: (...args) => console.error(ansis.red.bold("[Discord]"), ...args)
7
- };