@helyx/bot 0.4.32 → 0.4.35

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/dist/events.js CHANGED
@@ -3,6 +3,20 @@ import { ChannelType, Events, GatewayIntentBits, GuildMemberFlags, PermissionFla
3
3
  import { toReplyOptions } from "./interactions.js";
4
4
  import { createHash } from "node:crypto";
5
5
  import { classifyGuildMessage, unavailableGuildMessageClassification, } from "./message-classification.js";
6
+ function availabilityAwareInstallations(services) {
7
+ const installations = services.get(HELYX_SERVICE_NAMES.installations);
8
+ const candidate = typeof services.has === "function" &&
9
+ services.has(HELYX_SERVICE_NAMES.moduleAvailability)
10
+ ? services.get(HELYX_SERVICE_NAMES.moduleAvailability)
11
+ : null;
12
+ const availability = typeof candidate?.isAvailable === "function" ? candidate : null;
13
+ return {
14
+ async isModuleEnabled(guildId, moduleId) {
15
+ return ((!availability || (await availability.isAvailable(moduleId))) &&
16
+ installations.isModuleEnabled(guildId, moduleId));
17
+ },
18
+ };
19
+ }
6
20
  export function installModuleEvents(client, modules, logger, services) {
7
21
  const privilegedMessageContributions = modules.flatMap((module) => (module.events?.privilegedMessageCreate ?? []).map((contribution) => ({
8
22
  moduleId: module.manifest.id,
@@ -113,7 +127,7 @@ export function installModuleEvents(client, modules, logger, services) {
113
127
  if (!message.guildId || !privilegedEligibilityQueue)
114
128
  return;
115
129
  privilegedEligibilityQueue.enqueue(message.guildId, async () => {
116
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
130
+ const installations = availabilityAwareInstallations(services);
117
131
  const eligible = [];
118
132
  for (const item of privilegedMessageContributions) {
119
133
  try {
@@ -260,7 +274,7 @@ export function installModuleEvents(client, modules, logger, services) {
260
274
  });
261
275
  }
262
276
  async function handleResourceLifecycle(contributions, serverId, identifier, resourceId, eventName) {
263
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
277
+ const installations = availabilityAwareInstallations(services);
264
278
  for (const { moduleId, contribution } of contributions) {
265
279
  try {
266
280
  if (!(await installations.isModuleEnabled(serverId, moduleId))) {
@@ -316,7 +330,7 @@ export function installModuleEvents(client, modules, logger, services) {
316
330
  async function handleGuildMessageCreate(message) {
317
331
  if (!message.guildId || !message.channelId)
318
332
  return;
319
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
333
+ const installations = availabilityAwareInstallations(services);
320
334
  const parentChannelId = message.channel.isThread()
321
335
  ? (message.channel.parentId ?? undefined)
322
336
  : undefined;
@@ -410,7 +424,7 @@ export function installModuleEvents(client, modules, logger, services) {
410
424
  : reaction.message;
411
425
  if (!message.guildId || !message.channelId)
412
426
  return;
413
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
427
+ const installations = availabilityAwareInstallations(services);
414
428
  const member = await message.guild?.members.fetch(user.id);
415
429
  const userRoleIds = member ? [...member.roles.cache.keys()] : [];
416
430
  const parentChannelId = messageParentChannelId(message);
@@ -467,7 +481,7 @@ export function installModuleEvents(client, modules, logger, services) {
467
481
  async function handleMemberAdd(member) {
468
482
  if (!member.joinedAt)
469
483
  throw new Error("Discord member join timestamp is unavailable");
470
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
484
+ const installations = availabilityAwareInstallations(services);
471
485
  for (const { moduleId, contribution } of memberAddContributions) {
472
486
  try {
473
487
  if (!(await installations.isModuleEnabled(member.guild.id, moduleId))) {
@@ -498,7 +512,7 @@ export function installModuleEvents(client, modules, logger, services) {
498
512
  }
499
513
  }
500
514
  async function handleMemberRemove(member) {
501
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
515
+ const installations = availabilityAwareInstallations(services);
502
516
  for (const { moduleId, contribution } of memberRemoveContributions) {
503
517
  try {
504
518
  if (!(await installations.isModuleEnabled(member.guild.id, moduleId))) {
@@ -536,7 +550,7 @@ export function installModuleEvents(client, modules, logger, services) {
536
550
  : reaction.message;
537
551
  if (!message.guildId || !message.channelId)
538
552
  return;
539
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
553
+ const installations = availabilityAwareInstallations(services);
540
554
  const parentChannelId = messageParentChannelId(message);
541
555
  for (const { moduleId, contribution } of reactionRemoveContributions) {
542
556
  if (!(await installations.isModuleEnabled(message.guildId, moduleId))) {
@@ -580,7 +594,7 @@ export function installModuleEvents(client, modules, logger, services) {
580
594
  : receivedMessage;
581
595
  if (!message.guildId || !message.channelId)
582
596
  return;
583
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
597
+ const installations = availabilityAwareInstallations(services);
584
598
  for (const { moduleId, contribution } of reactionRemoveAllContributions) {
585
599
  try {
586
600
  if (!(await installations.isModuleEnabled(message.guildId, moduleId)))
@@ -610,7 +624,7 @@ export function installModuleEvents(client, modules, logger, services) {
610
624
  const message = reaction.message;
611
625
  if (!message.guildId || !message.channelId)
612
626
  return;
613
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
627
+ const installations = availabilityAwareInstallations(services);
614
628
  for (const { moduleId, contribution } of reactionRemoveEmojiContributions) {
615
629
  try {
616
630
  if (!(await installations.isModuleEnabled(message.guildId, moduleId)))
@@ -638,7 +652,7 @@ export function installModuleEvents(client, modules, logger, services) {
638
652
  async function handleMessageUpdate(receivedMessage) {
639
653
  if (!receivedMessage.guildId || !receivedMessage.channelId)
640
654
  return;
641
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
655
+ const installations = availabilityAwareInstallations(services);
642
656
  for (const { moduleId, contribution } of messageUpdateContributions) {
643
657
  try {
644
658
  if (!(await installations.isModuleEnabled(receivedMessage.guildId, moduleId)))
@@ -672,7 +686,7 @@ export function installModuleEvents(client, modules, logger, services) {
672
686
  async function handleMessageDelete(message) {
673
687
  if (!message.guildId || !message.channelId)
674
688
  return;
675
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
689
+ const installations = availabilityAwareInstallations(services);
676
690
  for (const { moduleId, contribution } of messageDeleteContributions) {
677
691
  try {
678
692
  if (!(await installations.isModuleEnabled(message.guildId, moduleId))) {
@@ -699,7 +713,7 @@ export function installModuleEvents(client, modules, logger, services) {
699
713
  async function handleMessageDeleteBulk(guildId, channelId, messageIds) {
700
714
  if (messageIds.length === 0)
701
715
  return;
702
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
716
+ const installations = availabilityAwareInstallations(services);
703
717
  const boundedIds = messageIds.slice(0, 100);
704
718
  for (const { moduleId, contribution } of messageDeleteBulkContributions) {
705
719
  try {
@@ -733,7 +747,7 @@ export function installModuleEvents(client, modules, logger, services) {
733
747
  voiceSessions.delete(key);
734
748
  const endedAt = new Date();
735
749
  const durationSeconds = Math.max(1, Math.floor((endedAt.getTime() - previous.startedAt.getTime()) / 1_000));
736
- const installations = services.get(HELYX_SERVICE_NAMES.installations);
750
+ const installations = availabilityAwareInstallations(services);
737
751
  for (const { moduleId, contribution } of guildVoiceSessionContributions) {
738
752
  try {
739
753
  if (!(await installations.isModuleEnabled(previous.guildId, moduleId)))
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { parseBotEnvironment } from "@helyx/config";
2
+ import { StatusHeartbeatReporter } from "@helyx/status-client";
2
3
  import { safeError, ServiceRegistry } from "@helyx/core";
3
4
  import { checkDatabaseConnection, createDatabasePool, AuditRepository, InteractionSessionRepository, RateLimitRepository, runCoreMigrations, runConfiguredModuleMigrations, } from "@helyx/database";
4
5
  import { createRuntime } from "@helyx/framework";
@@ -44,9 +45,45 @@ export async function startBot(processEnvironment = process.env) {
44
45
  return startShardWorker(processEnvironment, parseShardWorkerLaunchContract(processEnvironment.HELYX_SHARD_WORKER_CONTRACT));
45
46
  const environment = parseBotEnvironment(processEnvironment);
46
47
  bootstrapLogger.level = environment.LOG_LEVEL;
47
- if (environment.HELYX_SHARD_MODE !== "off")
48
- return startShardSupervisor(environment, processEnvironment, resolveBotWorkerEntryPoint());
49
- return startUnshardedBot(processEnvironment);
48
+ const handle = environment.HELYX_SHARD_MODE !== "off"
49
+ ? await startShardSupervisor(environment, processEnvironment, resolveBotWorkerEntryPoint())
50
+ : await startUnshardedBot(processEnvironment);
51
+ if (!environment.HELYX_STATUS_ENABLED)
52
+ return handle;
53
+ const processStartedAt = new Date().toISOString();
54
+ const reporter = new StatusHeartbeatReporter({
55
+ producer: "bot",
56
+ baseUrl: environment.HELYX_STATUS_URL,
57
+ secret: environment.HELYX_STATUS_HEARTBEAT_SECRET,
58
+ accessClientId: environment.CF_ACCESS_CLIENT_ID,
59
+ accessClientSecret: environment.CF_ACCESS_CLIENT_SECRET,
60
+ intervalSeconds: environment.HELYX_STATUS_HEARTBEAT_INTERVAL_SECONDS,
61
+ services: () => [
62
+ {
63
+ key: "discord-bot",
64
+ state: "operational",
65
+ processStartedAt,
66
+ release: readBotVersion(),
67
+ },
68
+ {
69
+ key: "creator-connections",
70
+ state: environment.HELYX_OAUTH_ENABLED ? "operational" : "major_outage",
71
+ reasonCode: environment.HELYX_OAUTH_ENABLED ? null : "feature_disabled",
72
+ processStartedAt,
73
+ release: readBotVersion(),
74
+ },
75
+ ],
76
+ onError(error) {
77
+ bootstrapLogger.warn({ event: "status.heartbeat_failed", reason: error.message }, "Status heartbeat could not be delivered");
78
+ },
79
+ });
80
+ reporter.start();
81
+ return {
82
+ async shutdown(reason) {
83
+ await reporter.stop();
84
+ await handle.shutdown(reason);
85
+ },
86
+ };
50
87
  }
51
88
  export function resolveBotWorkerEntryPoint(entryUrl = import.meta.url) {
52
89
  return fileURLToPath(entryUrl);
@@ -254,6 +291,9 @@ async function startUnshardedBot(processEnvironment) {
254
291
  })) {
255
292
  platformServices.set(name, service);
256
293
  }
294
+ await serviceAccess
295
+ .get(HELYX_SERVICE_NAMES.moduleAvailability)
296
+ .refresh();
257
297
  if (environment.HELYX_VERIFICATION_ENABLED &&
258
298
  environment.HELYX_VERIFICATION_URL &&
259
299
  environment.HELYX_VERIFICATION_INTERNAL_SECRET) {
@@ -1,5 +1,6 @@
1
1
  import type { CommandContribution, MessageResponse, ModalDefinition, ModuleDefinition, ServiceAccess } from "@helyx/sdk";
2
2
  import { ModalBuilder, type ChatInputCommandInteraction, type Client, type InteractionReplyOptions, type InteractionUpdateOptions } from "discord.js";
3
+ export declare const GLOBAL_MODULE_UNAVAILABLE_MESSAGE = "This module is temporarily unavailable for all hosted servers.";
3
4
  export interface InteractionLogger {
4
5
  info(fields: Record<string, unknown>, message: string): void;
5
6
  warn(fields: Record<string, unknown>, message: string): void;
@@ -16,7 +17,7 @@ export declare function buildApplicationCommandDefinitions(modules: readonly Mod
16
17
  global: ReturnType<typeof toCommandDefinition>[];
17
18
  guild: ReturnType<typeof toCommandDefinition>[];
18
19
  };
19
- export declare function resolveCommandExecutor(command: CommandContribution, subcommandName: string | null): CommandContribution["execute"];
20
+ export declare function resolveCommandExecutor(command: CommandContribution, subcommandName: string | null, groupName?: string | null): CommandContribution["execute"];
20
21
  export declare function toCommandDefinition(registered: {
21
22
  contribution: CommandContribution;
22
23
  }): import("discord.js").RESTPostAPIChatInputApplicationCommandsJSONBody;
@@ -27,7 +28,7 @@ export declare function sendToChannel(client: Client, channelId: string, respons
27
28
  export declare function deleteChannelMessage(client: Client, channelId: string, messageId: string): Promise<void>;
28
29
  export declare function editChannelMessage(client: Client, channelId: string, messageId: string, response: MessageResponse): Promise<void>;
29
30
  export declare function addChannelMessageReaction(client: Client, channelId: string, messageId: string, emojiIdentifier: string): Promise<void>;
30
- export declare function authorizeCommand(interaction: ChatInputCommandInteraction, moduleId: string, commandId: string, rateLimit: CommandContribution["rateLimit"], services: ServiceAccess, selfAuthorizingGuildCommand: boolean, resourceScopedCommand?: boolean): Promise<boolean>;
31
+ export declare function authorizeCommand(interaction: ChatInputCommandInteraction, moduleId: string, commandId: string, rateLimit: CommandContribution["rateLimit"], services: ServiceAccess, selfAuthorizingGuildCommand: boolean, resourceScopedCommand?: boolean, requiredModuleName?: string): Promise<boolean>;
31
32
  export declare function normalizeDiscordPermission(permission: string): string;
32
33
  export declare function toReplyOptions(response: MessageResponse): InteractionReplyOptions;
33
34
  export declare function toUpdateOptions(response: MessageResponse): InteractionUpdateOptions;
@@ -1,6 +1,7 @@
1
1
  import { HELYX_SERVICE_NAMES } from "@helyx/sdk";
2
2
  import { canUseCommand } from "@helyx/core";
3
3
  import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelSelectMenuBuilder, EmbedBuilder, Events, GuildMember, ApplicationIntegrationType, ChannelType, InteractionContextType, LabelBuilder, MessageFlags, MentionableSelectMenuBuilder, ModalBuilder, RoleSelectMenuBuilder, StringSelectMenuBuilder, SlashCommandBuilder, TextInputBuilder, TextInputStyle, UserSelectMenuBuilder, TextDisplayBuilder, PermissionFlagsBits, escapeMarkdown, } from "discord.js";
4
+ import { collectCommandRegistrations, } from "./nexus-commands.js";
4
5
  const buttonStyles = {
5
6
  primary: ButtonStyle.Primary,
6
7
  secondary: ButtonStyle.Secondary,
@@ -8,11 +9,18 @@ const buttonStyles = {
8
9
  danger: ButtonStyle.Danger,
9
10
  link: ButtonStyle.Link,
10
11
  };
12
+ export const GLOBAL_MODULE_UNAVAILABLE_MESSAGE = "This module is temporarily unavailable for all hosted servers.";
13
+ async function moduleIsGloballyAvailable(services, moduleId) {
14
+ if (typeof services.has !== "function" ||
15
+ !services.has(HELYX_SERVICE_NAMES.moduleAvailability))
16
+ return true;
17
+ const availability = services.get(HELYX_SERVICE_NAMES.moduleAvailability);
18
+ return typeof availability?.isAvailable !== "function"
19
+ ? true
20
+ : availability.isAvailable(moduleId);
21
+ }
11
22
  export function installInteractions(client, modules, registration, logger, services) {
12
- const commands = uniqueMap(modules.flatMap((module) => (module.interactions?.commands ?? []).map((contribution) => ({
13
- moduleId: module.manifest.id,
14
- contribution,
15
- }))), ({ contribution }) => contribution.name, "command name");
23
+ const commands = collectCommandRegistrations(modules);
16
24
  const globalCommands = [...commands.values()].filter(({ contribution }) => contribution.registration === "global");
17
25
  const guildCommands = [...commands.values()].filter(({ contribution }) => contribution.registration === "guild");
18
26
  if (guildCommands.length > 0 && !registration.internalGuildId) {
@@ -74,16 +82,20 @@ export function installInteractions(client, modules, registration, logger, servi
74
82
  try {
75
83
  if (interaction.isAutocomplete()) {
76
84
  const registered = commands.get(interaction.commandName);
77
- const subcommandName = registered?.contribution.subcommands?.length
85
+ const groupName = registered?.contribution.subcommandGroups?.length
86
+ ? interaction.options.getSubcommandGroup(false)
87
+ : null;
88
+ const subcommandName = hasNestedCommands(registered?.contribution)
78
89
  ? interaction.options.getSubcommand(false)
79
90
  : null;
80
- const subcommand = subcommandName
81
- ? registered?.contribution.subcommands?.find(({ name }) => name === subcommandName)
82
- : undefined;
91
+ const subcommand = resolveCommandSubcommand(registered?.contribution, subcommandName, groupName);
92
+ const owner = resolveCommandOwner(registered, subcommandName, groupName);
83
93
  if (!registered ||
84
94
  !subcommand?.autocomplete ||
85
- !(await authorizeAutocomplete(interaction, registered.moduleId, subcommand.permissionId ??
86
- `${registered.contribution.name}.${subcommand.name}`, services, registration.selfAuthorizingGuildModuleIds?.has(registered.moduleId) ?? false, subcommand.authorization === "resource-scoped"))) {
95
+ !(await authorizeAutocomplete(interaction, owner?.moduleId ?? registered.moduleId, subcommand.permissionId ??
96
+ [registered.contribution.name, groupName, subcommand.name]
97
+ .filter(Boolean)
98
+ .join("."), services, registration.selfAuthorizingGuildModuleIds?.has(owner?.moduleId ?? registered.moduleId) ?? false, subcommand.authorization === "resource-scoped"))) {
87
99
  await interaction.respond([]);
88
100
  return;
89
101
  }
@@ -91,24 +103,35 @@ export function installInteractions(client, modules, registration, logger, servi
91
103
  }
92
104
  else if (interaction.isChatInputCommand()) {
93
105
  const registered = commands.get(interaction.commandName);
94
- if (registered) {
106
+ if (!registered) {
107
+ logger.warn({
108
+ event: "interaction.stale_command",
109
+ commandName: interaction.commandName,
110
+ }, "Interaction used a command that is no longer loaded");
111
+ await interaction.reply({
112
+ content: "This command is no longer available. Refresh Discord and try again.",
113
+ flags: MessageFlags.Ephemeral,
114
+ });
115
+ return;
116
+ }
117
+ {
95
118
  const { contribution: command, moduleId } = registered;
96
- const subcommandName = command.subcommands?.length
119
+ const groupName = command.subcommandGroups?.length
120
+ ? interaction.options.getSubcommandGroup(false)
121
+ : null;
122
+ const subcommandName = hasNestedCommands(command)
97
123
  ? interaction.options.getSubcommand(false)
98
124
  : null;
99
- const subcommand = subcommandName
100
- ? command.subcommands?.find(({ name }) => name === subcommandName)
101
- : undefined;
102
- const execute = resolveCommandExecutor(command, subcommandName);
125
+ const subcommand = resolveCommandSubcommand(command, subcommandName, groupName);
126
+ const execute = resolveCommandExecutor(command, subcommandName, groupName);
103
127
  if (!execute) {
104
128
  logger.warn({
105
129
  event: "interaction.stale_command",
106
130
  commandName: command.name,
107
131
  ...(subcommandName ? { subcommandName } : {}),
132
+ ...(groupName ? { groupName } : {}),
108
133
  }, "Interaction used an outdated command definition");
109
- const choices = (command.subcommands ?? [])
110
- .map(({ name }) => `\`/${command.name} ${name}\``)
111
- .join(" or ");
134
+ const choices = commandChoices(command).join(" or ");
112
135
  await interaction.reply({
113
136
  content: choices
114
137
  ? `This command was recently updated. Refresh Discord, then use ${choices}.`
@@ -118,11 +141,19 @@ export function installInteractions(client, modules, registration, logger, servi
118
141
  return;
119
142
  }
120
143
  const commandId = subcommandName
121
- ? `${command.name}.${subcommandName}`
144
+ ? [command.name, groupName, subcommandName]
145
+ .filter(Boolean)
146
+ .join(".")
122
147
  : command.name;
123
148
  const permissionId = subcommand?.permissionId ?? command.permissionId ?? commandId;
124
- if (await authorizeCommand(interaction, moduleId, permissionId, subcommand?.rateLimit ?? command.rateLimit, services, registration.selfAuthorizingGuildModuleIds?.has(moduleId) ??
125
- false, subcommand?.authorization === "resource-scoped")) {
149
+ const owner = resolveCommandOwner(registered, subcommandName, groupName);
150
+ const ownerModuleId = owner?.moduleId ?? moduleId;
151
+ const acknowledgement = subcommand?.acknowledgement ?? command.acknowledgement;
152
+ if (acknowledgement === "deferred-ephemeral") {
153
+ await interaction.deferReply({ flags: MessageFlags.Ephemeral });
154
+ }
155
+ if (await authorizeCommand(interaction, ownerModuleId, permissionId, subcommand?.rateLimit ?? command.rateLimit, services, registration.selfAuthorizingGuildModuleIds?.has(ownerModuleId) ??
156
+ false, subcommand?.authorization === "resource-scoped", owner?.moduleName)) {
126
157
  const context = createCommandContext(interaction, services);
127
158
  await execute(context);
128
159
  }
@@ -187,10 +218,7 @@ export function installInteractions(client, modules, registration, logger, servi
187
218
  return registrationReady;
188
219
  }
189
220
  export function buildApplicationCommandDefinitions(modules, internalGuildId) {
190
- const commands = uniqueMap(modules.flatMap((module) => (module.interactions?.commands ?? []).map((contribution) => ({
191
- moduleId: module.manifest.id,
192
- contribution,
193
- }))), ({ contribution }) => contribution.name, "command name");
221
+ const commands = collectCommandRegistrations(modules);
194
222
  const global = [...commands.values()]
195
223
  .filter(({ contribution }) => contribution.registration === "global")
196
224
  .map(toCommandDefinition);
@@ -201,11 +229,11 @@ export function buildApplicationCommandDefinitions(modules, internalGuildId) {
201
229
  throw new Error("DISCORD_INTERNAL_GUILD_ID is required when guild commands are loaded");
202
230
  return { global, guild };
203
231
  }
204
- export function resolveCommandExecutor(command, subcommandName) {
205
- if (command.subcommands?.length) {
232
+ export function resolveCommandExecutor(command, subcommandName, groupName = null) {
233
+ if (hasNestedCommands(command)) {
206
234
  if (!subcommandName)
207
235
  return undefined;
208
- const subcommand = command.subcommands.find(({ name }) => name === subcommandName);
236
+ const subcommand = resolveCommandSubcommand(command, subcommandName, groupName);
209
237
  return subcommand ? (context) => subcommand.execute(context) : undefined;
210
238
  }
211
239
  return command.execute
@@ -214,11 +242,25 @@ export function resolveCommandExecutor(command, subcommandName) {
214
242
  }
215
243
  export function toCommandDefinition(registered) {
216
244
  const command = registered.contribution;
217
- if (!!command.execute === !!command.subcommands?.length) {
218
- throw new Error(`Command ${command.name} must define either execute or subcommands`);
245
+ const hasNested = Boolean(command.subcommands?.length || command.subcommandGroups?.length);
246
+ if (Number(command.execute !== undefined) + Number(hasNested) !== 1) {
247
+ throw new Error(`Command ${command.name} must define exactly one of execute, subcommands or subcommand groups`);
248
+ }
249
+ if (command.execute && !command.acknowledgement) {
250
+ throw new Error(`Command ${command.name} must declare acknowledgement`);
251
+ }
252
+ for (const subcommand of command.subcommands ?? []) {
253
+ if (!subcommand.acknowledgement && !command.acknowledgement)
254
+ throw new Error(`Command ${command.name}.${subcommand.name} must declare acknowledgement`);
255
+ }
256
+ for (const group of command.subcommandGroups ?? []) {
257
+ for (const subcommand of group.subcommands) {
258
+ if (!subcommand.acknowledgement && !command.acknowledgement)
259
+ throw new Error(`Command ${command.name}.${group.name}.${subcommand.name} must declare acknowledgement`);
260
+ }
219
261
  }
220
- if (command.options?.length && command.subcommands?.length) {
221
- throw new Error(`Command ${command.name} cannot define both direct options and subcommands`);
262
+ if (command.options?.length && hasNested) {
263
+ throw new Error(`Command ${command.name} cannot define both direct options and nested commands`);
222
264
  }
223
265
  const contextTypes = {
224
266
  guild: InteractionContextType.Guild,
@@ -248,8 +290,50 @@ export function toCommandDefinition(registered) {
248
290
  return subcommandBuilder;
249
291
  });
250
292
  }
293
+ for (const group of command.subcommandGroups ?? []) {
294
+ builder.addSubcommandGroup((groupBuilder) => {
295
+ groupBuilder.setName(group.name).setDescription(group.description);
296
+ for (const subcommand of group.subcommands) {
297
+ groupBuilder.addSubcommand((subcommandBuilder) => {
298
+ subcommandBuilder
299
+ .setName(subcommand.name)
300
+ .setDescription(subcommand.description);
301
+ for (const option of subcommand.options ?? []) {
302
+ addCommandOption(subcommandBuilder, option);
303
+ }
304
+ return subcommandBuilder;
305
+ });
306
+ }
307
+ return groupBuilder;
308
+ });
309
+ }
251
310
  return builder.toJSON();
252
311
  }
312
+ function hasNestedCommands(command) {
313
+ return Boolean(command?.subcommands?.length || command?.subcommandGroups?.length);
314
+ }
315
+ function resolveCommandSubcommand(command, subcommandName, groupName) {
316
+ if (!command || !subcommandName)
317
+ return undefined;
318
+ if (!groupName) {
319
+ return command.subcommands?.find(({ name }) => name === subcommandName);
320
+ }
321
+ return command.subcommandGroups
322
+ ?.find(({ name }) => name === groupName)
323
+ ?.subcommands.find(({ name }) => name === subcommandName);
324
+ }
325
+ function resolveCommandOwner(registered, subcommandName, groupName) {
326
+ if (!registered?.routeOwners || !subcommandName)
327
+ return undefined;
328
+ const path = groupName ? `${groupName}.${subcommandName}` : subcommandName;
329
+ return registered.routeOwners.get(path);
330
+ }
331
+ function commandChoices(command) {
332
+ return [
333
+ ...(command.subcommands ?? []).map(({ name }) => `\`/${command.name} ${name}\``),
334
+ ...(command.subcommandGroups ?? []).flatMap((group) => group.subcommands.map(({ name }) => `\`/${command.name} ${group.name} ${name}\``)),
335
+ ];
336
+ }
253
337
  function addCommandOption(builder, option) {
254
338
  if (option.type === "string") {
255
339
  if (option.autocomplete && option.choices?.length)
@@ -610,14 +694,20 @@ export async function addChannelMessageReaction(client, channelId, messageId, em
610
694
  const message = await channel.messages.fetch(messageId);
611
695
  await message.react(emojiIdentifier);
612
696
  }
613
- async function authorizeComponent(interaction, moduleId, services) {
697
+ async function authorizeComponent(interaction, moduleId, services, requiredModuleName) {
698
+ if (!(await moduleIsGloballyAvailable(services, moduleId))) {
699
+ await replyEphemeralText(interaction, GLOBAL_MODULE_UNAVAILABLE_MESSAGE);
700
+ return false;
701
+ }
614
702
  if (!interaction.guildId)
615
703
  return true;
616
704
  const installations = services.get(HELYX_SERVICE_NAMES.installations);
617
705
  if (await installations.isModuleEnabled(interaction.guildId, moduleId)) {
618
706
  return true;
619
707
  }
620
- await replyEphemeralText(interaction, "This module is disabled in this server. Ask a server administrator to enable it with `/helyx` or in the Helyx dashboard.");
708
+ await replyEphemeralText(interaction, requiredModuleName
709
+ ? `This command needs ${requiredModuleName}. Ask a server administrator to enable it in the Helyx dashboard.`
710
+ : "This module is disabled in this server. Ask a server administrator to enable it with `/helyx` or in the Helyx dashboard.");
621
711
  return false;
622
712
  }
623
713
  async function replyEphemeralText(interaction, content) {
@@ -627,11 +717,11 @@ async function replyEphemeralText(interaction, content) {
627
717
  }
628
718
  await interaction.reply({ content, flags: MessageFlags.Ephemeral });
629
719
  }
630
- export async function authorizeCommand(interaction, moduleId, commandId, rateLimit, services, selfAuthorizingGuildCommand, resourceScopedCommand = false) {
720
+ export async function authorizeCommand(interaction, moduleId, commandId, rateLimit, services, selfAuthorizingGuildCommand, resourceScopedCommand = false, requiredModuleName) {
631
721
  if (!interaction.guildId)
632
722
  return true;
633
723
  if (!selfAuthorizingGuildCommand) {
634
- if (!(await authorizeComponent(interaction, moduleId, services)))
724
+ if (!(await authorizeComponent(interaction, moduleId, services, requiredModuleName)))
635
725
  return false;
636
726
  if (!resourceScopedCommand) {
637
727
  const permissions = services.get(HELYX_SERVICE_NAMES.permissions);
@@ -639,10 +729,7 @@ export async function authorizeCommand(interaction, moduleId, commandId, rateLim
639
729
  const actor = permissionActor(interaction);
640
730
  const guildAccess = await permissions.getGuildAccessPolicy?.(interaction.guildId);
641
731
  if (!canUseCommand(actor, policy, guildAccess)) {
642
- await interaction.reply({
643
- content: "You do not have permission to use this command.",
644
- flags: MessageFlags.Ephemeral,
645
- });
732
+ await replyEphemeralText(interaction, "You do not have permission to use this command.");
646
733
  return false;
647
734
  }
648
735
  }
@@ -657,16 +744,15 @@ export async function authorizeCommand(interaction, moduleId, commandId, rateLim
657
744
  windowSeconds: rateLimit.windowSeconds,
658
745
  });
659
746
  if (!result.allowed) {
660
- await interaction.reply({
661
- content: `This command is temporarily rate limited. Try again <t:${Math.ceil(result.resetsAt.getTime() / 1_000)}:R>.`,
662
- flags: MessageFlags.Ephemeral,
663
- });
747
+ await replyEphemeralText(interaction, `This command is temporarily rate limited. Try again <t:${Math.ceil(result.resetsAt.getTime() / 1_000)}:R>.`);
664
748
  return false;
665
749
  }
666
750
  }
667
751
  return true;
668
752
  }
669
753
  async function authorizeAutocomplete(interaction, moduleId, commandId, services, selfAuthorizingGuildCommand, resourceScopedCommand) {
754
+ if (!(await moduleIsGloballyAvailable(services, moduleId)))
755
+ return false;
670
756
  if (!interaction.guildId || selfAuthorizingGuildCommand)
671
757
  return true;
672
758
  const installations = services.get(HELYX_SERVICE_NAMES.installations);
@@ -1023,6 +1109,7 @@ function interactionLogContext(interaction) {
1023
1109
  ...(interaction.isChatInputCommand()
1024
1110
  ? {
1025
1111
  commandName: interaction.commandName,
1112
+ subcommandGroupName: interaction.options.getSubcommandGroup(false) ?? undefined,
1026
1113
  subcommandName: interaction.options.getSubcommand(false) ?? undefined,
1027
1114
  }
1028
1115
  : "customId" in interaction && typeof interaction.customId === "string"
@@ -1,3 +1,4 @@
1
+ import { isCustomerSelectableModule, } from "@helyx/module-manifest";
1
2
  import { defineModule, HELYX_SERVICE_NAMES, ModuleStateValidationError, } from "@helyx/sdk";
2
3
  const MODULE_SELECT_ID = "helyx.management.module";
3
4
  const SETTING_SELECT_ID = "helyx.management.setting";
@@ -24,7 +25,9 @@ const VIOLET = 0x7c3aed;
24
25
  const SUCCESS = 0x16a34a;
25
26
  const DANGER = 0xdc2626;
26
27
  export function createManagementModule(configurableModules, resources) {
27
- const modules = [...configurableModules].sort((left, right) => left.manifest.name.localeCompare(right.manifest.name, "en-GB"));
28
+ const modules = configurableModules
29
+ .filter((module) => isCustomerSelectableModule(module.manifest))
30
+ .sort((left, right) => left.manifest.name.localeCompare(right.manifest.name, "en-GB"));
28
31
  const byId = new Map(modules.map((module) => [module.manifest.id, module]));
29
32
  return defineModule({
30
33
  manifest: {
@@ -49,6 +52,7 @@ export function createManagementModule(configurableModules, resources) {
49
52
  {
50
53
  name: "helyx",
51
54
  description: "Manage Helyx modules and settings",
55
+ acknowledgement: "deferred-ephemeral",
52
56
  registration: "global",
53
57
  contexts: ["guild"],
54
58
  integrationTypes: ["guild_install"],
@@ -0,0 +1,24 @@
1
+ import { type ModuleAvailabilityService, type ModuleAvailabilityState, type ModuleDefinition, type ServiceAccess } from "@helyx/sdk";
2
+ export interface AvailabilityModuleDefinition {
3
+ id: string;
4
+ name: string;
5
+ version: string;
6
+ releaseStatus: "planned" | "testing" | "beta" | "live";
7
+ }
8
+ export interface AvailabilityModuleCatalogue {
9
+ catalogueDigest: string;
10
+ modules: AvailabilityModuleDefinition[];
11
+ }
12
+ export declare function availabilityCatalogueDefinitions(modules: readonly ModuleDefinition[]): AvailabilityModuleDefinition[];
13
+ export declare function availabilityCatalogueSnapshot(definitions: readonly AvailabilityModuleDefinition[]): AvailabilityModuleCatalogue;
14
+ export declare function availabilityCatalogue(definitions: readonly AvailabilityModuleDefinition[]): Promise<AvailabilityModuleCatalogue>;
15
+ export declare function moduleAvailabilityService(services: ServiceAccess): ModuleAvailabilityService | undefined;
16
+ export declare function moduleAvailabilityStates(services: ServiceAccess, moduleIds: readonly string[]): Promise<ModuleAvailabilityState[]>;
17
+ export declare function dashboardModuleStatus(globallyDisabled: ReadonlySet<string>, moduleId: string, installation: {
18
+ enabled: boolean;
19
+ } | undefined): "enabled" | "disabled" | "unavailable";
20
+ export declare function disabledModuleSummary(states: readonly ModuleAvailabilityState[]): {
21
+ ids: string[];
22
+ set: ReadonlySet<string>;
23
+ };
24
+ //# sourceMappingURL=module-availability-control.d.ts.map
@@ -0,0 +1,61 @@
1
+ import { isCustomerSelectableModule } from "@helyx/module-manifest";
2
+ import { HELYX_SERVICE_NAMES, } from "@helyx/sdk";
3
+ import { createHash } from "node:crypto";
4
+ export function availabilityCatalogueDefinitions(modules) {
5
+ return modules
6
+ .filter((module) => isCustomerSelectableModule(module.manifest))
7
+ .map(({ manifest }) => ({
8
+ id: manifest.id,
9
+ name: manifest.name,
10
+ version: manifest.version,
11
+ releaseStatus: manifest.releaseStatus,
12
+ }))
13
+ .sort((left, right) => left.name.localeCompare(right.name, "en-GB"));
14
+ }
15
+ export function availabilityCatalogueSnapshot(definitions) {
16
+ const modules = definitions.map((module) => ({ ...module }));
17
+ return {
18
+ catalogueDigest: createHash("sha256")
19
+ .update(JSON.stringify(modules))
20
+ .digest("hex"),
21
+ modules,
22
+ };
23
+ }
24
+ export function availabilityCatalogue(definitions) {
25
+ return Promise.resolve(availabilityCatalogueSnapshot(definitions));
26
+ }
27
+ export function moduleAvailabilityService(services) {
28
+ if (!services.has(HELYX_SERVICE_NAMES.moduleAvailability))
29
+ return undefined;
30
+ const service = services.get(HELYX_SERVICE_NAMES.moduleAvailability);
31
+ return typeof service?.get === "function" &&
32
+ typeof service.isAvailable === "function"
33
+ ? service
34
+ : undefined;
35
+ }
36
+ export function moduleAvailabilityStates(services, moduleIds) {
37
+ const availability = moduleAvailabilityService(services);
38
+ return Promise.all(moduleIds.map((moduleId) => availability
39
+ ? availability.get(moduleId)
40
+ : Promise.resolve({
41
+ moduleId,
42
+ globallyDisabled: false,
43
+ revision: 0n,
44
+ generation: 0n,
45
+ updatedAt: null,
46
+ })));
47
+ }
48
+ export function dashboardModuleStatus(globallyDisabled, moduleId, installation) {
49
+ if (globallyDisabled.has(moduleId))
50
+ return "unavailable";
51
+ if (!installation)
52
+ return "unavailable";
53
+ return installation.enabled ? "enabled" : "disabled";
54
+ }
55
+ export function disabledModuleSummary(states) {
56
+ const ids = states
57
+ .filter(({ globallyDisabled }) => globallyDisabled)
58
+ .map(({ moduleId }) => moduleId);
59
+ return { ids, set: new Set(ids) };
60
+ }
61
+ //# sourceMappingURL=module-availability-control.js.map