nuxt-discord 0.0.8 → 0.0.10

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
@@ -1,4 +1,5 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
+ import * as __runtime_logger from '../dist/runtime/logger.js';
2
3
  import * as _nuxt_kit from '@nuxt/kit';
3
4
  import * as nuxt_schema from 'nuxt/schema';
4
5
  import { DiscordClient } from '/Users/jeffz/Dev/nuxt-discord/dist/runtime/server/utils/client.js';
@@ -8,13 +9,21 @@ import { ListenOptions } from 'listhen';
8
9
 
9
10
  interface NuxtDiscordOptions {
10
11
  /**
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.
12
+ * Options passed to the internal Discord client.
13
+ * Use the 'nitro:client:config' hook to configure
14
+ * client options in runtime.
14
15
  *
15
- * @default [GatewayIntentBits.Guilds]
16
+ * @default { intents: [GatewayIntentBits.Guilds] }
16
17
  */
17
- intents: ClientOptions['intents'];
18
+ client: ClientOptions & {
19
+ /**
20
+ * Whether to automatically defer the interaction reply
21
+ * on slash command execution if the command returns a promise.
22
+ *
23
+ * @default true
24
+ */
25
+ deferOnPromise?: boolean;
26
+ };
18
27
  /**
19
28
  * The directory to scan for nuxt-discord related
20
29
  * files, such as slash commands.
@@ -31,14 +40,13 @@ interface NuxtDiscordOptions {
31
40
  /**
32
41
  * HMR options
33
42
  */
34
- watch: {
43
+ watch: Partial<ListenOptions> & {
35
44
  /**
36
45
  * Enable or disable HMR for slash commands.
37
46
  *
38
47
  * @default true
39
48
  */
40
49
  enabled?: boolean;
41
- } & {
42
50
  /**
43
51
  * Whether to automatically register and update
44
52
  * slash commands on the Discord client.
@@ -52,10 +60,10 @@ interface NuxtDiscordOptions {
52
60
  */
53
61
  debounce?: number;
54
62
  };
55
- } & Partial<ListenOptions>;
63
+ };
56
64
  }
57
65
  interface DiscordRuntimeConfig {
58
- intents: ClientOptions['intents'];
66
+ client: NuxtDiscordOptions['client'];
59
67
  autoStart: boolean;
60
68
  sync: NuxtDiscordOptions['watch']['sync'];
61
69
  dir: string;
@@ -120,7 +128,7 @@ interface NuxtDiscordContext {
120
128
  root: _nuxt_kit.Resolver['resolve'];
121
129
  module: _nuxt_kit.Resolver['resolve'];
122
130
  };
123
- logger: ReturnType<typeof _nuxt_kit.useLogger>;
131
+ logger: typeof __runtime_logger.logger;
124
132
  }
125
133
 
126
134
  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.10",
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 { logger } from '../dist/runtime/logger.js';
3
4
  import { globSync, readFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
4
5
  import path from 'node:path';
5
6
  import ts from 'typescript';
@@ -19,7 +20,7 @@ function createContext(options, nuxt) {
19
20
  root: createResolver(nuxt.options.rootDir).resolve,
20
21
  module: createResolver(import.meta.url).resolve
21
22
  },
22
- logger: useLogger("nuxt-discord")
23
+ logger
23
24
  };
24
25
  }
25
26
 
@@ -308,11 +309,15 @@ function prepareHMR(ctx) {
308
309
  });
309
310
  }
310
311
  chokidar.watch(ctx.resolve.root(ctx.options.dir, "commands"), { ignoreInitial: true }).on("all", async (event, path2) => {
312
+ if (event === "all" || event === "error" || event === "raw") {
313
+ return;
314
+ }
311
315
  const fullPath = ctx.resolve.root(path2);
312
316
  if (fullPath.startsWith(commandsDir)) {
313
317
  path2 = ctx.resolve.root(path2);
314
318
  const command = processCommandFile(ctx, path2) ?? null;
315
319
  if (event === "add" || event === "change") {
320
+ ctx.logger.log(`Dynamically loading slash command at ${path2}`);
316
321
  await generateDynamicCommandBuild(path2, rollupConfig, ctx);
317
322
  }
318
323
  websocket?.broadcast({ event, path: path2, command });
@@ -403,7 +408,12 @@ function createWebSocket() {
403
408
  async function generateDynamicCommandBuild(file, config, ctx) {
404
409
  let bundle;
405
410
  try {
406
- bundle = await rollup({ ...config, input: file });
411
+ bundle = await rollup({
412
+ ...config,
413
+ input: file,
414
+ // externalize all modules except the command file itself
415
+ external: (id) => !id.includes(file)
416
+ });
407
417
  const { output } = await bundle.generate({ ...config.output, sourcemap: false });
408
418
  mkdirSync(path.join(ctx.nuxt.options.buildDir, "discord", "commands"), { recursive: true });
409
419
  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 +428,7 @@ function prepareRuntimeConfig(ctx) {
418
428
  ctx.nuxt.hook("nitro:config", (config) => {
419
429
  config.runtimeConfig ??= {};
420
430
  config.runtimeConfig.discord ??= {};
421
- config.runtimeConfig.discord.intents = ctx.options.intents;
431
+ config.runtimeConfig.discord.client = ctx.options.client;
422
432
  config.runtimeConfig.discord.autoStart = ctx.options.autoStart;
423
433
  config.runtimeConfig.discord.sync = ctx.options.watch.sync ?? false;
424
434
  config.runtimeConfig.discord.dir = ctx.resolve.root(ctx.options.dir);
@@ -458,7 +468,7 @@ type integer = import('nuxt-discord').integer
458
468
  declare global {
459
469
  declare module 'nitropack/types' {
460
470
  interface NitroRuntimeHooks {
461
- 'discord:client:config': (options: import('discord.js').ClientOptions) => void
471
+ 'discord:client:config': (options: import('nuxt-discord').NuxtDiscordOptions['client']) => void
462
472
  'discord:client:ready': (client: DiscordClient) => void
463
473
  'discord:client:error': (error: DiscordClientError) => void
464
474
  }
@@ -505,12 +515,15 @@ const module = defineNuxtModule({
505
515
  configKey: "discord"
506
516
  },
507
517
  defaults: {
508
- intents: [GatewayIntentBits.Guilds],
518
+ client: {
519
+ intents: [GatewayIntentBits.Guilds],
520
+ deferOnPromise: true
521
+ },
509
522
  dir: "discord",
510
523
  autoStart: true,
511
524
  watch: {
512
525
  enabled: true,
513
- port: 4222,
526
+ port: 5720,
514
527
  showURL: false,
515
528
  sync: {
516
529
  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.js";
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.js";
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.10",
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",