nuxt-discord 0.0.12 → 0.0.13

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
@@ -132,8 +132,6 @@ export default (name: string, style: string) => {
132
132
  }
133
133
  ```
134
134
 
135
- > **Coming Soon:** Support choices inferred from Typescript literal union types
136
-
137
135
  ## Web Interface
138
136
 
139
137
  Access the command management interface at `/discord/slash-commands` in your application. The interface provides:
@@ -272,12 +270,7 @@ Here's what's planned for future releases:
272
270
 
273
271
  ## Contribution
274
272
 
275
- <details>
276
- <summary>Local development</summary>
277
-
278
- Refer to the official [Module Author Guide](https://nuxt.com/docs/guide/going-further/modules)
279
-
280
- </details>
273
+ Refer to the official [Module Author Guide](https://nuxt.com/docs/guide/going-further/modules)
281
274
 
282
275
  ## Acknowledgement
283
276
 
package/dist/module.d.mts CHANGED
@@ -6,6 +6,7 @@ import { DiscordClient } from '/Users/jeffz/Dev/nuxt-discord/dist/runtime/server
6
6
  import { IntegerOption, NumberOption, StringOption } from '../dist/runtime/server/utils/describeOption.js';
7
7
  import { ClientOptions, ApplicationCommandOptionType, ChatInputCommandInteraction } from 'discord.js';
8
8
  import { ListenOptions } from 'listhen';
9
+ import { MaybeRef } from 'vue';
9
10
 
10
11
  interface NuxtDiscordOptions {
11
12
  /**
@@ -106,8 +107,8 @@ interface SlashCommandBooleanOption extends SlashCommandOptionBase {
106
107
  type: ApplicationCommandOptionType.Boolean;
107
108
  }
108
109
  type SlashCommandOption = SlashCommandIntegerOption | SlashCommandNumberOption | SlashCommandStringOption | SlashCommandBooleanOption;
109
- type SlashCommandCustomReturnHandler = (this: DiscordClient, interaction: ChatInputCommandInteraction, client: DiscordClient) => SlashCommandReturnType;
110
- type SlashCommandReturnType = void | string | SlashCommandCustomReturnHandler | Promise<SlashCommandReturnType> | Generator<SlashCommandReturnType> | AsyncGenerator<SlashCommandReturnType>;
110
+ type SlashCommandCustomReturnHandler = (this: DiscordClient, interaction: ChatInputCommandInteraction, client: DiscordClient) => unknown;
111
+ type SlashCommandReturnType = void | MaybeRef<string> | SlashCommandCustomReturnHandler | Promise<SlashCommandReturnType> | Generator<SlashCommandReturnType> | AsyncGenerator<SlashCommandReturnType>;
111
112
  interface SlashCommand {
112
113
  name: string;
113
114
  description: string;
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-discord",
3
3
  "configKey": "discord",
4
- "version": "0.0.12",
4
+ "version": "0.0.13",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.1",
7
7
  "unbuild": "3.5.0"
package/dist/module.mjs CHANGED
@@ -193,20 +193,102 @@ function processCommandFile(ctx, file) {
193
193
  ctx.logger.warn(`No body found for command definition in ${file}`);
194
194
  return;
195
195
  }
196
+ const whichLiteral = (node) => {
197
+ if (ts.isLiteralTypeNode(node)) {
198
+ if (ts.isStringLiteral(node.literal)) {
199
+ return "string";
200
+ }
201
+ if (ts.isNumericLiteral(node.literal)) {
202
+ return "number";
203
+ }
204
+ }
205
+ };
206
+ const getType = (type) => {
207
+ if (!type) {
208
+ ctx.logger.warn(`No type found for slash command option in ${file}, defaulting to string`);
209
+ return { type: "string" };
210
+ }
211
+ if (ts.isUnionTypeNode(type)) {
212
+ const types = new Set(type.types.map((t) => whichLiteral(t)));
213
+ if (types.size !== 1) {
214
+ ctx.logger.warn(`Union type with multiple conflicting types found in ${file}, defaulting to string`);
215
+ return { type: "string" };
216
+ }
217
+ const typeName2 = types.values().next().value;
218
+ if (!(typeName2 in typeIdentifierToEnum)) {
219
+ ctx.logger.warn(`Unrecognizable type ${type.getText(sourceFile)}, defaulting to string`);
220
+ return { type: "string" };
221
+ }
222
+ return {
223
+ type: typeName2,
224
+ choices: typeName2 === "string" ? type.types.map((t) => t.getText(sourceFile).slice(1, -1)) : type.types.map((t) => Number(t.getText(sourceFile)))
225
+ };
226
+ }
227
+ if (ts.isLiteralTypeNode(type)) {
228
+ const typeName2 = whichLiteral(type);
229
+ if (!typeName2) {
230
+ ctx.logger.warn(`Unrecognizable literal type ${type.getText(sourceFile)}, defaulting to string`);
231
+ return { type: "string" };
232
+ }
233
+ if (!(typeName2 in typeIdentifierToEnum)) {
234
+ ctx.logger.warn(`Unrecognizable literal type ${type.getText(sourceFile)}, defaulting to string`);
235
+ return { type: "string" };
236
+ }
237
+ return {
238
+ type: typeName2,
239
+ choices: typeName2 === "string" ? [type.literal.getText(sourceFile).slice(1, -1)] : [Number(type.literal.getText(sourceFile))]
240
+ };
241
+ }
242
+ const typeName = type.getText(sourceFile);
243
+ if (typeName && typeName in typeIdentifierToEnum) {
244
+ return { type: typeName };
245
+ }
246
+ ctx.logger.warn(`Unknown slash command option type: ${type.getText(sourceFile)} in ${file}, defaulting to string`);
247
+ return { type: "string" };
248
+ };
196
249
  for (const param of commandDefinition.parameters) {
197
250
  const name2 = param.name.getText(sourceFile);
198
- let type = param.type?.getText(sourceFile);
199
- if (!type || !(type in typeIdentifierToEnum)) {
200
- ctx.logger.warn(`Unknown slash command option type: ${type} for parameter ${name2} in ${file}, defaulting to string`);
201
- type = "string";
202
- }
203
- const jsdocDescription = jsDocTags.find((tag) => ts.isJSDocParameterTag(tag) && tag.name.getText() === name2)?.comment?.toString() ?? "";
251
+ let { type, choices } = getType(param.type);
252
+ const jsDocTagIdx = jsDocTags.findIndex((tag) => ts.isJSDocParameterTag(tag) && tag.name.getText() === name2);
253
+ const findModifiers = (modifiers2) => {
254
+ let idx = jsDocTagIdx;
255
+ const ret = {};
256
+ while (idx >= 0) {
257
+ const tag = jsDocTags[idx];
258
+ if (modifiers2.includes(tag.tagName.escapedText) && tag.comment) {
259
+ ret[tag.tagName.escapedText] = JSON.parse(tag.comment.toString());
260
+ } else {
261
+ return ret;
262
+ }
263
+ idx -= 1;
264
+ }
265
+ return ret;
266
+ };
267
+ const jsdocDescription = jsDocTagIdx !== -1 ? jsDocTags[jsDocTagIdx].comment?.toString() ?? "" : "";
268
+ const modifiersMap = {
269
+ string: ["minLength", "maxLength", "choices"],
270
+ number: ["min", "max", "choices"],
271
+ integer: ["min", "max", "choices"],
272
+ boolean: []
273
+ };
274
+ const modifiers = findModifiers(modifiersMap[type]);
275
+ choices = choices ?? modifiers.choices;
204
276
  command.options.push({
205
277
  name: name2,
206
278
  // TODO: remove this type assertion
207
279
  type: typeIdentifierToEnum[type],
208
280
  description: jsdocDescription,
209
- required: !param.questionToken
281
+ required: !param.questionToken,
282
+ ...modifiers,
283
+ ...choices ? {
284
+ choices: choices.map((choice) => {
285
+ if (typeof choice === "string") {
286
+ return { name: choice, value: choice };
287
+ }
288
+ return { name: String(choice), value: choice };
289
+ })
290
+ // hmm... is it possible to not use `any` here?
291
+ } : {}
210
292
  });
211
293
  }
212
294
  let macrosEnd = false;
@@ -104,7 +104,7 @@ const commandsWithStatus = computed(() => {
104
104
  name: cmd.name,
105
105
  description: cmd.description,
106
106
  path: "unknown",
107
- options: cmd.options,
107
+ options: cmd.options ?? [],
108
108
  status: "removed",
109
109
  remote: cmd
110
110
  })),
@@ -242,7 +242,6 @@ const statusClasses = {
242
242
  />
243
243
  </div>
244
244
 
245
- <!-- <UButton icon="i-lucide-circle" @click="test" /> -->
246
245
  <UButton
247
246
  v-if="!allSynced"
248
247
  :icon="pendingSync ? 'i-lucide-refresh-ccw' : 'i-lucide-cloud-upload'"
@@ -363,8 +362,12 @@ const statusClasses = {
363
362
  <!-- Choices dropdown -->
364
363
  <UDropdownMenu
365
364
  v-if="'choices' in option && option.choices && option.choices.length > 0"
366
- :items="option.choices.map((choice) => ({ label: choice.name }))"
365
+ :items="option.choices.map((choice) => ({
366
+ label: choice.name,
367
+ value: typeof choice.value === 'string' ? `\'${choice.value}\'` : choice.value
368
+ }))"
367
369
  :popper="{ placement: 'bottom-start' }"
370
+ :ui="{ itemTrailing: 'text-sm text-gray-500 dark:text-gray-400' }"
368
371
  >
369
372
  <UBadge
370
373
  v-if="'choices' in option && option.choices && option.choices.length > 0"
@@ -374,6 +377,9 @@ const statusClasses = {
374
377
  size="sm"
375
378
  class="hover:cursor-pointer"
376
379
  />
380
+ <template #item-trailing="{ item: { value } }">
381
+ {{ value }}
382
+ </template>
377
383
  </UDropdownMenu>
378
384
  </div>
379
385
 
@@ -34,6 +34,8 @@ export declare class DiscordClient {
34
34
  constructor();
35
35
  start(options: NuxtDiscordOptions['client']): Promise<undefined>;
36
36
  stop(): Promise<void>;
37
+ startScope(): void;
38
+ stopScope(): void;
37
39
  isReady(): boolean;
38
40
  addSlashCommand(command: SlashCommandRuntime): void;
39
41
  addSlashCommands(commands: SlashCommandRuntime[]): void;
@@ -1,7 +1,9 @@
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 { effectScope, isRef } from "vue";
4
5
  import { logger } from "../../logger.js";
6
+ import { reply } from "./reply.js";
5
7
  let currentInteraction = null;
6
8
  export function useInteraction() {
7
9
  return currentInteraction;
@@ -40,6 +42,7 @@ export class DiscordClient {
40
42
  return;
41
43
  this.#handleSlashCommand(interaction);
42
44
  });
45
+ this.startScope();
43
46
  const { resolve, promise } = Promise.withResolvers();
44
47
  this.#client.once(Events.ClientReady, (readyClient) => {
45
48
  logger.log(`Discord client is ready! Logged in as ${readyClient.user?.tag}`);
@@ -54,6 +57,22 @@ export class DiscordClient {
54
57
  await this.#client.destroy();
55
58
  this.#client = null;
56
59
  }
60
+ this.stopScope();
61
+ }
62
+ #scope;
63
+ startScope() {
64
+ if (this.#scope)
65
+ return;
66
+ this.#scope = effectScope(
67
+ /* detached */
68
+ true
69
+ );
70
+ }
71
+ stopScope() {
72
+ if (!this.#scope)
73
+ return;
74
+ this.#scope.stop();
75
+ this.#scope = void 0;
57
76
  }
58
77
  isReady() {
59
78
  return this.#client?.isReady() ?? false;
@@ -86,6 +105,8 @@ export class DiscordClient {
86
105
  getSlashCommand(name) {
87
106
  return this.#slashCommands.find((cmd) => cmd.name === name);
88
107
  }
108
+ #interactionScopes = /* @__PURE__ */ new WeakMap();
109
+ #commandFinalizationRegistry = new FinalizationRegistry((scope) => scope.stop());
89
110
  async #handleSlashCommand(interaction) {
90
111
  const name = interaction.commandName;
91
112
  const command = this.#slashCommands.find((cmd) => cmd.name === name);
@@ -136,10 +157,22 @@ export class DiscordClient {
136
157
  return;
137
158
  }
138
159
  }
160
+ let scope;
161
+ if (this.#scope) {
162
+ this.#scope.run(() => scope = effectScope());
163
+ } else {
164
+ scope = effectScope();
165
+ }
166
+ this.#interactionScopes.set(interaction, scope);
167
+ if (import.meta.dev)
168
+ this.#commandFinalizationRegistry.register(command, scope);
139
169
  try {
140
- currentInteraction = interaction;
141
- const result = command.execute(...args);
142
- currentInteraction = null;
170
+ let result;
171
+ scope.run(() => {
172
+ currentInteraction = interaction;
173
+ result = command.execute(...args);
174
+ currentInteraction = null;
175
+ });
143
176
  if (this.#clientOptions?.deferOnPromise && isPromise(result)) {
144
177
  await interaction.deferReply();
145
178
  }
@@ -160,15 +193,15 @@ export class DiscordClient {
160
193
  return;
161
194
  }
162
195
  try {
163
- if (typeof result === "string") {
164
- if (interaction.deferred || interaction.replied) {
165
- return interaction.editReply({ content: result });
196
+ if (typeof result === "string" || isRef(result)) {
197
+ return this.#handleSlashCommandReturn(reply(result), interaction, command);
198
+ } else if (typeof result === "function") {
199
+ const scope = this.#interactionScopes.get(interaction);
200
+ if (!scope) {
201
+ return result.call(this, interaction, this);
166
202
  } else {
167
- return interaction.reply({ content: result });
203
+ return scope.run(() => result.call(this, interaction, this));
168
204
  }
169
- } else if (typeof result === "function") {
170
- const newResult = result.call(this, interaction, this);
171
- return this.#handleSlashCommandReturn(newResult, interaction, command);
172
205
  } else if (Symbol.iterator in result && typeof result[Symbol.iterator] === "function") {
173
206
  const gen = result[Symbol.iterator]();
174
207
  let next = gen.next();
@@ -6,31 +6,52 @@ export interface DescribeOptionOptionsBase {
6
6
  /** A brief description of the command. */
7
7
  description?: string;
8
8
  }
9
- export interface IntegerOption extends DescribeOptionOptionsBase {
9
+ export interface IntegerOption<T extends number = number> extends DescribeOptionOptionsBase {
10
10
  /** The minimum value for the integer option. */
11
11
  min?: number;
12
12
  /** The maximum value for the integer option. */
13
13
  max?: number;
14
14
  /** An array of choices for the integer option. */
15
- choices?: APIApplicationCommandOptionChoice<number>[];
15
+ choices?: APIApplicationCommandOptionChoice<T>[];
16
16
  }
17
- export interface NumberOption extends DescribeOptionOptionsBase {
17
+ export interface NumberOption<T extends number = number> extends DescribeOptionOptionsBase {
18
18
  /** The minimum value for the number option. */
19
19
  min?: number;
20
20
  /** The maximum value for the number option. */
21
21
  max?: number;
22
22
  /** An array of choices for the number option. */
23
- choices?: APIApplicationCommandOptionChoice<number>[];
23
+ choices?: APIApplicationCommandOptionChoice<T>[];
24
24
  }
25
- export interface StringOption extends DescribeOptionOptionsBase {
25
+ export interface StringOption<T extends string = string> extends DescribeOptionOptionsBase {
26
26
  /** The minimum length of the string option. */
27
27
  minLength?: number;
28
28
  /** The maximum length of the string option. */
29
29
  maxLength?: number;
30
30
  /** An array of choices for the string option. */
31
- choices?: APIApplicationCommandOptionChoice<string>[];
31
+ choices?: APIApplicationCommandOptionChoice<T>[];
32
32
  }
33
33
  export type DescribeOptionOptions = IntegerOption | NumberOption | StringOption;
34
34
  /**
35
+ * A compiler macro that describes a slash command option. Used for defining
36
+ * metadata for registering slash command options. Options defined here will
37
+ * take higher precedence over the inferred ones from the function signature
38
+ * and JSDoc tags.
39
+ *
40
+ * @param _option - The type of the option, used for type inference.
41
+ * @param _options - The options for the command option.
42
+ * @example
43
+ * // this will describe the name option as a string with a minimum length of 1 and a maximum length of 32
44
+ * describeOption(name, {
45
+ * minLength: 1,
46
+ * maxLength: 32,
47
+ * })
48
+ * // this will describe the style option as a string with three choices
49
+ * describeOption(style, {
50
+ * choices: [
51
+ * { name: 'Formal', value: 'formal' },
52
+ * { name: 'Casual', value: 'casual' },
53
+ * { name: 'Enthusiastic', value: 'enthusiastic' },
54
+ * ],
55
+ * })
35
56
  */
36
- export declare function describeOption<const T extends SlashCommandOptionType>(_option: T | undefined, _options: T extends integer ? IntegerOption : T extends number ? NumberOption : T extends string ? StringOption : DescribeOptionOptionsBase): void;
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;
@@ -1,22 +1,22 @@
1
- import type { BaseMessageOptions, InteractionEditReplyOptions, InteractionReplyOptions } from 'discord.js';
1
+ import type { BaseMessageOptions, InteractionCallbackResponse, InteractionReplyOptions, InteractionResponse, Message } from 'discord.js';
2
+ import type { MaybeRef } from 'vue';
2
3
  import type { SlashCommandCustomReturnHandler } from '../../../types.js';
3
4
  type OmitPreservingCallSignature<T, K extends keyof T = keyof T> = Omit<T, K> & (T extends (...args: infer R) => infer S ? (...args: R) => S : unknown);
4
5
  type File = NonNullable<BaseMessageOptions['files']>[number];
5
6
  type ReplyFunction = SlashCommandCustomReturnHandler & {
6
- (text?: string, options?: InteractionReplyOptions): SlashCommandCustomReturnHandler;
7
- edit: EditReplyFunction;
8
- ephemeral: OmitPreservingCallSignature<ReplyFunction, 'edit' | 'ephemeral'>;
9
- flags: (flags: InteractionReplyOptions['flags']) => OmitPreservingCallSignature<ReplyFunction, 'edit'>;
10
- file: (file: File) => OmitPreservingCallSignature<ReplyFunction, 'edit'>;
11
- files: (files: File[]) => OmitPreservingCallSignature<ReplyFunction, 'edit'>;
7
+ (text?: MaybeRef<string>, options?: InteractionReplyOptions): SlashCommandCustomReturnHandler & {
8
+ [Symbol.iterator]: () => {
9
+ next: (...args: ReadonlyArray<any>) => IteratorResult<ReplyFunction, Message | InteractionResponse | InteractionCallbackResponse>;
10
+ };
11
+ };
12
+ [Symbol.iterator]: () => {
13
+ next: (...args: ReadonlyArray<any>) => IteratorResult<never, Promise<Message | InteractionResponse | InteractionCallbackResponse>>;
14
+ };
15
+ ephemeral: OmitPreservingCallSignature<ReplyFunction, 'ephemeral'>;
16
+ flags: (flags: MaybeRef<InteractionReplyOptions['flags']>) => ReplyFunction;
17
+ file: (file: MaybeRef<File>) => ReplyFunction;
18
+ files: (files: MaybeRef<File[]>) => ReplyFunction;
12
19
  send: ReplyFunction;
13
20
  };
14
- type EditReplyFunction = SlashCommandCustomReturnHandler & {
15
- (text?: string, options?: InteractionEditReplyOptions): SlashCommandCustomReturnHandler;
16
- flags: (flags: InteractionEditReplyOptions['flags']) => EditReplyFunction;
17
- file: (file: File) => EditReplyFunction;
18
- files: (files: File[]) => EditReplyFunction;
19
- send: EditReplyFunction;
20
- };
21
21
  export declare const reply: ReplyFunction;
22
22
  export {};
@@ -1,34 +1,63 @@
1
1
  import { MessageFlags } from "discord.js";
2
- function createReplyFunction({ editReply, ...defaultOptions } = {}) {
2
+ import { isRef, reactive, watch } from "vue";
3
+ function createReplyFunction({ ...defaultOptions } = {}) {
3
4
  const reply2 = (...args) => {
4
- if (typeof args[0] === "string" || typeof args[0] === "undefined") {
5
+ if (typeof args[0] === "string" || typeof args[0] === "undefined" || isRef(args[0]) || typeof args[0] === "function") {
5
6
  const [text, options] = args;
6
- return async (interaction) => {
7
- if (editReply || interaction.deferred || interaction.replied) {
8
- await interaction.editReply({
9
- content: text,
10
- ...defaultOptions,
11
- ...options
12
- });
13
- } else {
14
- await interaction.reply({
15
- content: text,
16
- ...defaultOptions,
17
- ...options
18
- });
19
- }
7
+ let message;
8
+ const replyOptions = reactive({
9
+ content: text,
10
+ ...defaultOptions,
11
+ ...options
12
+ });
13
+ const handler = (interaction) => {
14
+ const method = interaction.replied ? "followUp" : interaction.deferred ? "editReply" : "reply";
15
+ message = interaction[method](
16
+ replyOptions
17
+ ).catch((err) => err);
18
+ return message;
20
19
  };
20
+ Object.defineProperty(handler, Symbol.iterator, {
21
+ value: () => ({
22
+ next: () => message !== void 0 ? {
23
+ done: true,
24
+ value: message
25
+ } : {
26
+ done: false,
27
+ value: handler
28
+ }
29
+ })
30
+ });
31
+ watch(replyOptions, async (options2) => {
32
+ const msg = await message;
33
+ if ("edit" in msg)
34
+ msg.edit(options2);
35
+ else
36
+ msg.resource?.message?.edit(options2);
37
+ }, { deep: true, flush: "sync" });
38
+ return handler;
21
39
  } else {
22
40
  const interaction = args[0];
23
- if (editReply || interaction.deferred || interaction.replied) {
24
- return interaction.editReply({
25
- ...defaultOptions
26
- }).then(() => void 0);
27
- } else {
28
- return interaction.reply({
29
- ...defaultOptions
30
- }).then(() => void 0);
31
- }
41
+ const method = interaction.replied ? "followUp" : interaction.deferred ? "editReply" : "reply";
42
+ const options = reactive(defaultOptions);
43
+ const messagePromise = interaction[method](options).catch((err) => err);
44
+ watch(options, async (opts) => {
45
+ const message = await messagePromise;
46
+ if (!message)
47
+ return;
48
+ if ("edit" in message)
49
+ message.edit(opts);
50
+ else
51
+ message.resource?.message?.edit(opts);
52
+ }, { deep: true, flush: "sync" });
53
+ return {
54
+ [Symbol.iterator]: () => ({
55
+ next: () => ({
56
+ done: true,
57
+ value: messagePromise
58
+ })
59
+ })
60
+ };
32
61
  }
33
62
  };
34
63
  Object.defineProperties(reply2, {
@@ -48,14 +77,6 @@ function createReplyFunction({ editReply, ...defaultOptions } = {}) {
48
77
  });
49
78
  }
50
79
  },
51
- edit: {
52
- get() {
53
- return createReplyFunction({
54
- ...defaultOptions,
55
- editReply: true
56
- });
57
- }
58
- },
59
80
  file: {
60
81
  get() {
61
82
  return (file) => createReplyFunction({
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-discord",
3
3
  "type": "module",
4
- "version": "0.0.12",
4
+ "version": "0.0.13",
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",