mini-interactions 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,6 +65,56 @@ await bot.syncCommands();
65
65
 
66
66
  `syncCommands()` uses Discord's bulk overwrite endpoint for the configured global or guild scope. Guild registration is recommended while developing because global commands can take time to propagate.
67
67
 
68
+ ## Modular file-based bots
69
+
70
+ For larger bots, keep one command/component/modal per file and generate static imports instead of using filesystem discovery at runtime:
71
+
72
+ ```text
73
+ src/
74
+ commands/ping.ts
75
+ components/ping_again.ts
76
+ modals/feedback.ts
77
+ mini-interactions.generated.ts
78
+ ```
79
+
80
+ ```bash
81
+ bunx mini-interactions generate
82
+ ```
83
+
84
+ ```ts
85
+ // src/commands/ping.ts
86
+ import { CommandBuilder, defineCommand } from "mini-interactions";
87
+
88
+ export const ping = defineCommand({
89
+ data: new CommandBuilder().setName("ping").setDescription("Ping"),
90
+ handler: (interaction) => interaction.reply({ content: "Pong!" }),
91
+ });
92
+ ```
93
+
94
+ ```ts
95
+ // src/modals/feedback.ts
96
+ import { defineModal } from "mini-interactions";
97
+
98
+ export const feedback = defineModal({
99
+ customId: "feedback",
100
+ handler: (interaction) => interaction.reply({ content: "Thanks!" }),
101
+ });
102
+ ```
103
+
104
+ Register the generated manifest once where the bot is created:
105
+
106
+ ```ts
107
+ import { createBot } from "mini-interactions";
108
+ import { registerMiniInteractions } from "./mini-interactions.generated.js";
109
+
110
+ const bot = createBot();
111
+ registerMiniInteractions(bot);
112
+
113
+ export const POST = bot.fetch;
114
+ ```
115
+
116
+ Use the same manifest in a deployment script before calling `bot.syncCommands()`. The generator scans `src/commands`, `src/components`, and `src/modals` by default; pass `--commands`, `--components`, `--modals`, or `--out` to customize paths. Generated imports are static, so edge/serverless bundlers can trace every handler without filesystem access. `defineCommand`, context-menu `define*Command` helpers, `defineComponent`, and `defineModal` provide typed handlers.
117
+
68
118
  ## Cloudflare Workers
69
119
 
70
120
  The core runtime is edge-safe. Credentials can come from the Worker environment at request time:
package/dist/bot.d.ts CHANGED
@@ -1,8 +1,28 @@
1
+ import { type RESTPostAPIChatInputApplicationCommandsJSONBody, type RESTPostAPIContextMenuApplicationCommandsJSONBody, type RESTPostAPIPrimaryEntryPointApplicationCommandJSONBody } from "discord-api-types/v10";
1
2
  import { CommandBuilder } from "./commands/CommandBuilder.js";
2
3
  import { AppCommandBuilder, MessageCommandBuilder, UserCommandBuilder } from "./commands/ContextMenuCommandBuilder.js";
3
4
  import { DiscordRestClient, type DiscordRestClientOptions } from "./core/http/DiscordRestClient.js";
4
5
  import { InteractionRouter, type AutocompleteHandler, type ChatInputHandler, type ComponentHandler, type EntryPointHandler, type MessageMenuHandler, type ModalHandler, type RouterErrorHandler, type RouterFallback, type RouterMiddleware, type UserMenuHandler } from "./router/InteractionRouter.js";
5
6
  export type BotEnvironment = Record<string, string | undefined>;
7
+ export type BotCommandModule = {
8
+ data: BotCommandPayload | {
9
+ toJSON(): BotCommandPayload;
10
+ };
11
+ handler: ChatInputHandler | UserMenuHandler | MessageMenuHandler | EntryPointHandler;
12
+ };
13
+ export type BotComponentModule = {
14
+ customId: string;
15
+ handler: ComponentHandler;
16
+ };
17
+ export type BotModalModule = {
18
+ customId: string;
19
+ handler: ModalHandler;
20
+ };
21
+ export type BotModuleManifest = {
22
+ commands?: readonly unknown[];
23
+ components?: readonly unknown[];
24
+ modals?: readonly unknown[];
25
+ };
6
26
  export type CreateBotOptions = {
7
27
  publicKey?: string;
8
28
  applicationId?: string;
@@ -13,6 +33,7 @@ export type CreateBotOptions = {
13
33
  maxRetries?: DiscordRestClientOptions["maxRetries"];
14
34
  fetchImplementation?: DiscordRestClientOptions["fetchImplementation"];
15
35
  };
36
+ type BotCommandPayload = RESTPostAPIChatInputApplicationCommandsJSONBody | RESTPostAPIContextMenuApplicationCommandsJSONBody | RESTPostAPIPrimaryEntryPointApplicationCommandJSONBody;
16
37
  /**
17
38
  * A small, edge-safe Discord interactions bot.
18
39
  *
@@ -34,6 +55,13 @@ export declare class MiniBot {
34
55
  messageCommand(command: MessageCommandBuilder, handler: MessageMenuHandler): this;
35
56
  entryPointCommand(name: string, handler: EntryPointHandler): this;
36
57
  entryPointCommand(command: AppCommandBuilder, handler: EntryPointHandler): this;
58
+ /**
59
+ * Registers a file-module command and stores its payload for `syncCommands()`.
60
+ * Generated manifests call this through {@link modules}.
61
+ */
62
+ commandModule(command: BotCommandModule): this;
63
+ /** Registers generated/discovered command, component, and modal modules. */
64
+ modules(manifest: BotModuleManifest): this;
37
65
  component(customIdOrPattern: string | RegExp, handler: ComponentHandler): this;
38
66
  modal(customId: string, handler: ModalHandler): this;
39
67
  autocomplete(commandName: string, handler: AutocompleteHandler): this;
@@ -50,9 +78,36 @@ export declare class MiniBot {
50
78
  * builder-defined commands registered on this bot.
51
79
  */
52
80
  syncCommands(env?: BotEnvironment): Promise<unknown>;
81
+ private isCommandModule;
82
+ private isHandlerModule;
53
83
  private setCommandPayload;
54
84
  private defaultResponse;
55
85
  private resolveCredentials;
56
86
  private getRestClient;
57
87
  }
58
88
  export declare function createBot(options?: CreateBotOptions): MiniBot;
89
+ /** Identity helper that gives file-based command modules contextual handler types. */
90
+ export declare function defineCommand(command: {
91
+ data: CommandBuilder | RESTPostAPIChatInputApplicationCommandsJSONBody;
92
+ handler: ChatInputHandler;
93
+ }): BotCommandModule;
94
+ /** Identity helper that gives file-based user context menu modules contextual handler types. */
95
+ export declare function defineUserCommand(command: {
96
+ data: UserCommandBuilder | RESTPostAPIContextMenuApplicationCommandsJSONBody;
97
+ handler: UserMenuHandler;
98
+ }): BotCommandModule;
99
+ /** Identity helper that gives file-based message context menu modules contextual handler types. */
100
+ export declare function defineMessageCommand(command: {
101
+ data: MessageCommandBuilder | RESTPostAPIContextMenuApplicationCommandsJSONBody;
102
+ handler: MessageMenuHandler;
103
+ }): BotCommandModule;
104
+ /** Identity helper that gives file-based entry point command modules contextual handler types. */
105
+ export declare function defineEntryPointCommand(command: {
106
+ data: AppCommandBuilder | RESTPostAPIPrimaryEntryPointApplicationCommandJSONBody;
107
+ handler: EntryPointHandler;
108
+ }): BotCommandModule;
109
+ /** Identity helper that gives file-based component modules contextual handler types. */
110
+ export declare function defineComponent(component: BotComponentModule): BotComponentModule;
111
+ /** Identity helper that gives file-based modal modules contextual handler types. */
112
+ export declare function defineModal(modal: BotModalModule): BotModalModule;
113
+ export {};
package/dist/bot.js CHANGED
@@ -64,6 +64,47 @@ export class MiniBot {
64
64
  this.router.onEntryPointCommand(payload.name, handler);
65
65
  return this;
66
66
  }
67
+ /**
68
+ * Registers a file-module command and stores its payload for `syncCommands()`.
69
+ * Generated manifests call this through {@link modules}.
70
+ */
71
+ commandModule(command) {
72
+ const data = command.data;
73
+ const payload = typeof data.toJSON === "function"
74
+ ? data.toJSON()
75
+ : data;
76
+ this.setCommandPayload(payload);
77
+ switch (payload.type ?? ApplicationCommandType.ChatInput) {
78
+ case ApplicationCommandType.User:
79
+ this.router.onUserCommand(payload.name, command.handler);
80
+ break;
81
+ case ApplicationCommandType.Message:
82
+ this.router.onMessageCommand(payload.name, command.handler);
83
+ break;
84
+ case ApplicationCommandType.PrimaryEntryPoint:
85
+ this.router.onEntryPointCommand(payload.name, command.handler);
86
+ break;
87
+ default:
88
+ this.router.onCommand(payload.name, command.handler);
89
+ }
90
+ return this;
91
+ }
92
+ /** Registers generated/discovered command, component, and modal modules. */
93
+ modules(manifest) {
94
+ for (const command of manifest.commands ?? []) {
95
+ if (this.isCommandModule(command))
96
+ this.commandModule(command);
97
+ }
98
+ for (const component of manifest.components ?? []) {
99
+ if (this.isHandlerModule(component))
100
+ this.component(component.customId, component.handler);
101
+ }
102
+ for (const modal of manifest.modals ?? []) {
103
+ if (this.isHandlerModule(modal))
104
+ this.modal(modal.customId, modal.handler);
105
+ }
106
+ return this;
107
+ }
67
108
  component(customIdOrPattern, handler) {
68
109
  this.router.onComponent(customIdOrPattern, handler);
69
110
  return this;
@@ -156,6 +197,17 @@ export class MiniBot {
156
197
  body: JSON.stringify([...this.commandPayloads.values()]),
157
198
  });
158
199
  }
200
+ isCommandModule(value) {
201
+ return typeof value === "object" && value !== null && "data" in value && "handler" in value;
202
+ }
203
+ isHandlerModule(value) {
204
+ return (typeof value === "object" &&
205
+ value !== null &&
206
+ "customId" in value &&
207
+ "handler" in value &&
208
+ typeof value.customId === "string" &&
209
+ typeof value.handler === "function");
210
+ }
159
211
  setCommandPayload(payload) {
160
212
  const type = payload.type ?? ApplicationCommandType.ChatInput;
161
213
  this.commandPayloads.set(`${type}:${payload.name}`, payload);
@@ -215,3 +267,27 @@ export class MiniBot {
215
267
  export function createBot(options = {}) {
216
268
  return new MiniBot(options);
217
269
  }
270
+ /** Identity helper that gives file-based command modules contextual handler types. */
271
+ export function defineCommand(command) {
272
+ return command;
273
+ }
274
+ /** Identity helper that gives file-based user context menu modules contextual handler types. */
275
+ export function defineUserCommand(command) {
276
+ return command;
277
+ }
278
+ /** Identity helper that gives file-based message context menu modules contextual handler types. */
279
+ export function defineMessageCommand(command) {
280
+ return command;
281
+ }
282
+ /** Identity helper that gives file-based entry point command modules contextual handler types. */
283
+ export function defineEntryPointCommand(command) {
284
+ return command;
285
+ }
286
+ /** Identity helper that gives file-based component modules contextual handler types. */
287
+ export function defineComponent(component) {
288
+ return component;
289
+ }
290
+ /** Identity helper that gives file-based modal modules contextual handler types. */
291
+ export function defineModal(modal) {
292
+ return modal;
293
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, readdir, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ function parseArgs(argv) {
5
+ const options = {
6
+ commands: "src/commands",
7
+ components: "src/components",
8
+ modals: "src/modals",
9
+ out: "src/mini-interactions.generated.ts",
10
+ };
11
+ for (let index = 0; index < argv.length; index += 1) {
12
+ const arg = argv[index];
13
+ if (arg === "generate")
14
+ continue;
15
+ if (!arg.startsWith("--"))
16
+ continue;
17
+ const key = arg.slice(2);
18
+ const value = argv[index + 1];
19
+ if (!value || !(key in options))
20
+ throw new Error(`Unknown or incomplete option: ${arg}`);
21
+ options[key] = value;
22
+ index += 1;
23
+ }
24
+ return options;
25
+ }
26
+ async function walk(directory) {
27
+ let entries;
28
+ try {
29
+ entries = await readdir(directory, { withFileTypes: true });
30
+ }
31
+ catch {
32
+ return [];
33
+ }
34
+ const files = await Promise.all(entries.map(async (entry) => {
35
+ const resolved = path.join(directory, entry.name);
36
+ return entry.isDirectory() ? walk(resolved) : [resolved];
37
+ }));
38
+ return files.flat().filter((file) => file.endsWith(".ts") && !file.endsWith(".d.ts") && !file.includes(".test."));
39
+ }
40
+ function importPath(outFile, sourceFile) {
41
+ let relative = path.relative(path.dirname(outFile), sourceFile).split(path.sep).join("/");
42
+ if (!relative.startsWith("."))
43
+ relative = `./${relative}`;
44
+ return relative.replace(/\.ts$/, ".js");
45
+ }
46
+ async function generate(options) {
47
+ const cwd = process.cwd();
48
+ const outFile = path.resolve(cwd, options.out);
49
+ const groups = await Promise.all([
50
+ ["commands", options.commands],
51
+ ["components", options.components],
52
+ ["modals", options.modals],
53
+ ].map(async ([name, directory]) => [
54
+ name,
55
+ (await walk(path.resolve(cwd, directory))).filter((file) => path.resolve(file) !== outFile).sort(),
56
+ ]));
57
+ const imports = [];
58
+ const arrays = [];
59
+ for (const [name, files] of groups) {
60
+ imports.push(...files.map((file, index) => `import * as ${name}${index} from "${importPath(outFile, file)}";`));
61
+ arrays.push(`export const ${name} = [\n${files.map((_, index) => `\t...Object.values(${name}${index}),`).join("\n")}\n];`);
62
+ }
63
+ const output = `// Generated by mini-interactions. Run \`mini-interactions generate\` after adding modules.\nimport type { MiniBot } from "mini-interactions";\n${imports.join("\n")}\n\n${arrays.join("\n\n")}\n\nexport function registerMiniInteractions(bot: MiniBot): void {\n\tbot.modules({ commands, components, modals });\n}\n`;
64
+ await mkdir(path.dirname(outFile), { recursive: true });
65
+ await writeFile(outFile, output);
66
+ console.log(`[mini-interactions] generated ${path.relative(cwd, outFile)} (${groups.map(([n, f]) => `${n}=${f.length}`).join(" ")})`);
67
+ }
68
+ generate(parseArgs(process.argv.slice(2))).catch((error) => {
69
+ console.error(error instanceof Error ? error.message : error);
70
+ process.exit(1);
71
+ });
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { MiniBot, createBot } from "./bot.js";
2
- export type { BotEnvironment, CreateBotOptions } from "./bot.js";
1
+ export { MiniBot, createBot, defineCommand, defineUserCommand, defineMessageCommand, defineEntryPointCommand, defineComponent, defineModal } from "./bot.js";
2
+ export type { BotCommandModule, BotComponentModule, BotEnvironment, BotModalModule, BotModuleManifest, CreateBotOptions, } from "./bot.js";
3
3
  export { CommandBuilder, CommandContext, IntegrationType, } from "./commands/CommandBuilder.js";
4
4
  export { UserCommandBuilder, MessageCommandBuilder, AppCommandBuilder, } from "./commands/ContextMenuCommandBuilder.js";
5
5
  export type { AttachmentOptionBuilder, ChannelOptionBuilder, MentionableOptionBuilder, NumberOptionBuilder, RoleOptionBuilder, StringOptionBuilder, SubcommandBuilder, SubcommandGroupBuilder, UserOptionBuilder, } from "./commands/CommandBuilder.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { MiniBot, createBot } from "./bot.js";
1
+ export { MiniBot, createBot, defineCommand, defineUserCommand, defineMessageCommand, defineEntryPointCommand, defineComponent, defineModal } from "./bot.js";
2
2
  export { CommandBuilder, CommandContext, IntegrationType, } from "./commands/CommandBuilder.js";
3
3
  export { UserCommandBuilder, MessageCommandBuilder, AppCommandBuilder, } from "./commands/ContextMenuCommandBuilder.js";
4
4
  export { CommandInteractionOptionResolver, createCommandInteraction, } from "./utils/CommandInteractionOptions.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mini-interactions",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "Edge-first, type-safe Discord interactions for modern TypeScript bots.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -88,5 +88,8 @@
88
88
  "engines": {
89
89
  "node": ">=20",
90
90
  "bun": ">=1.2"
91
+ },
92
+ "bin": {
93
+ "mini-interactions": "dist/cli.js"
91
94
  }
92
95
  }