@helyx/bot 0.4.33 → 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.
@@ -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
package/dist/modules.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { orderModuleManifests, parseModuleManifest, } from "@helyx/module-manifest";
2
+ import { NEXUS_COMMAND_SPECS, NEXUS_ROOT_MODULE_ID } from "@helyx/sdk";
2
3
  import { createHmac } from "node:crypto";
3
4
  import { readFile } from "node:fs/promises";
4
5
  import { createRequire } from "node:module";
@@ -102,6 +103,28 @@ export function validateContributionParity(definition) {
102
103
  throw new Error("Module requests an unsupported or duplicate Discord capability");
103
104
  }
104
105
  const executableCommands = (definition.interactions?.commands ?? []).map(({ name }) => name);
106
+ const nexusCommandPaths = new Set();
107
+ for (const command of definition.nexusCommands ?? []) {
108
+ const spec = NEXUS_COMMAND_SPECS.find(({ path }) => path === command.path);
109
+ if (!spec || spec.ownerModuleId !== definition.manifest.id) {
110
+ throw new Error(`Module ${definition.manifest.id} cannot contribute Nexus command ${command.path}`);
111
+ }
112
+ if (nexusCommandPaths.has(command.path)) {
113
+ throw new Error(`Duplicate Nexus command path for ${definition.manifest.id}: ${command.path}`);
114
+ }
115
+ nexusCommandPaths.add(command.path);
116
+ }
117
+ if (definition.manifest.id !== NEXUS_ROOT_MODULE_ID) {
118
+ executableCommands.push(...[...nexusCommandPaths].map((path) => `nexus.${path}`));
119
+ if (nexusCommandPaths.size > 0 &&
120
+ !definition.manifest.dependencies.some(({ id }) => id === NEXUS_ROOT_MODULE_ID)) {
121
+ throw new Error(`Module ${definition.manifest.id} contributes Nexus commands without depending on Nexus Core`);
122
+ }
123
+ }
124
+ if (definition.manifest.id !== NEXUS_ROOT_MODULE_ID &&
125
+ definition.interactions?.commands?.some(({ name }) => name === "nexus")) {
126
+ throw new Error("Nexus Core must be the sole owner of /nexus");
127
+ }
105
128
  const executableEvents = [
106
129
  ...(definition.events?.privilegedMessageCreate ?? []),
107
130
  ...(definition.events?.guildMessageCreate ?? []),
@@ -135,7 +158,7 @@ export function validateContributionParity(definition) {
135
158
  function validatePrivacyParity(definition) {
136
159
  if (definition.manifest.manifestVersion === "0.1") {
137
160
  if (definition.privacy !== undefined) {
138
- throw new Error("Module executable privacy provider requires manifest version 0.2");
161
+ throw new Error("Module executable privacy provider requires manifest version 0.2 or later");
139
162
  }
140
163
  return;
141
164
  }
@@ -0,0 +1,13 @@
1
+ import { type CommandContribution, type ModuleDefinition } from "@helyx/sdk";
2
+ export interface CommandRouteOwner {
3
+ moduleId: string;
4
+ moduleName: string;
5
+ }
6
+ export interface RegisteredCommand {
7
+ moduleId: string;
8
+ moduleName: string;
9
+ contribution: CommandContribution;
10
+ routeOwners?: ReadonlyMap<string, CommandRouteOwner>;
11
+ }
12
+ export declare function collectCommandRegistrations(modules: readonly ModuleDefinition[]): Map<string, RegisteredCommand>;
13
+ //# sourceMappingURL=nexus-commands.d.ts.map
@@ -0,0 +1,100 @@
1
+ import { NEXUS_COMMAND_SPECS, NEXUS_ROOT_MODULE_ID, } from "@helyx/sdk";
2
+ export function collectCommandRegistrations(modules) {
3
+ const registrations = modules.flatMap((module) => (module.interactions?.commands ?? []).map((contribution) => ({
4
+ moduleId: module.manifest.id,
5
+ moduleName: module.manifest.name,
6
+ contribution,
7
+ })));
8
+ const nexusContributions = modules.flatMap((module) => (module.nexusCommands ?? []).map((contribution) => ({
9
+ moduleId: module.manifest.id,
10
+ moduleName: module.manifest.name,
11
+ contribution,
12
+ })));
13
+ if (nexusContributions.length > 0) {
14
+ const roots = registrations.filter(({ contribution }) => contribution.name === "nexus");
15
+ if (roots.length !== 1 || roots[0].moduleId !== NEXUS_ROOT_MODULE_ID) {
16
+ throw new Error("Nexus Core must be the sole owner of /nexus");
17
+ }
18
+ const root = roots[0];
19
+ if (root.contribution.execute ||
20
+ root.contribution.options?.length ||
21
+ root.contribution.subcommands?.length ||
22
+ root.contribution.subcommandGroups?.length) {
23
+ throw new Error("Nexus Core /nexus must be composed from Nexus commands");
24
+ }
25
+ const composed = composeNexusCommand(root, nexusContributions);
26
+ registrations.splice(registrations.indexOf(root), 1, composed);
27
+ }
28
+ return uniqueRegistrations(registrations);
29
+ }
30
+ function composeNexusCommand(root, contributions) {
31
+ const byPath = new Map(contributions.map((item) => {
32
+ const spec = NEXUS_COMMAND_SPECS.find(({ path }) => path === item.contribution.path);
33
+ if (!spec || spec.ownerModuleId !== item.moduleId) {
34
+ throw new Error(`Module ${item.moduleId} cannot contribute Nexus command ${item.contribution.path}`);
35
+ }
36
+ return [item.contribution.path, item];
37
+ }));
38
+ if (byPath.size !== contributions.length) {
39
+ throw new Error("Duplicate Nexus command path");
40
+ }
41
+ const subcommands = [];
42
+ const groups = new Map();
43
+ const routeOwners = new Map();
44
+ for (const spec of NEXUS_COMMAND_SPECS) {
45
+ const item = byPath.get(spec.path);
46
+ if (!item)
47
+ continue;
48
+ routeOwners.set(spec.path, {
49
+ moduleId: item.moduleId,
50
+ moduleName: item.moduleName,
51
+ });
52
+ const [first, second] = spec.path.split(".");
53
+ const command = toSubcommand(item.contribution, second ?? first);
54
+ if (!second) {
55
+ subcommands.push(command);
56
+ continue;
57
+ }
58
+ const current = groups.get(first);
59
+ const group = current ?? {
60
+ name: first,
61
+ description: "groupDescription" in spec
62
+ ? spec.groupDescription
63
+ : `Manage Nexus ${first}`,
64
+ subcommands: [],
65
+ };
66
+ groups.set(first, {
67
+ ...group,
68
+ subcommands: [...group.subcommands, command],
69
+ });
70
+ }
71
+ return {
72
+ ...root,
73
+ contribution: {
74
+ ...root.contribution,
75
+ subcommands,
76
+ subcommandGroups: [...groups.values()],
77
+ },
78
+ routeOwners,
79
+ };
80
+ }
81
+ function toSubcommand(contribution, name) {
82
+ const subcommand = {
83
+ ...contribution,
84
+ name,
85
+ permissionId: `nexus.${contribution.path}`,
86
+ };
87
+ delete subcommand.path;
88
+ return subcommand;
89
+ }
90
+ function uniqueRegistrations(items) {
91
+ const result = new Map();
92
+ for (const item of items) {
93
+ const key = item.contribution.name;
94
+ if (result.has(key))
95
+ throw new Error(`Duplicate command name: ${key}`);
96
+ result.set(key, item);
97
+ }
98
+ return result;
99
+ }
100
+ //# sourceMappingURL=nexus-commands.js.map
@@ -43,6 +43,7 @@ export function createOAuthModule() {
43
43
  {
44
44
  name: "revoke",
45
45
  description: "Revoke a service and delete the OAuth details Helyx stores for you.",
46
+ acknowledgement: "immediate-modal",
46
47
  rateLimit: { scope: "user", limit: 5, windowSeconds: 60 },
47
48
  execute: async (context) => {
48
49
  const oauth = context.services.get(HELYX_SERVICE_NAMES.oauth);