UNPKG

@sapphire/framework

Version:

Discord bot framework built for advanced and amazing bots.

1 lines • 14.7 kB
{"version":3,"file":"ApplicationCommandRegistries.cjs","names":["RegisterBehavior","defaultGuildIds: ApplicationCommandRegistry.RegisterOptions['guildIds']","ApplicationCommandRegistry","Events","container","getNeededRegistryParameters","foundGlobalCommands: BulkOverwriteData[]","foundGuildCommands: Record<string, BulkOverwriteData[]>","ApplicationCommandType","InternalRegistryAPIType"],"sources":["../../../../../src/lib/utils/application-commands/ApplicationCommandRegistries.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/dot-notation */\nimport { container } from '@sapphire/pieces';\nimport { retry } from '@sapphire/utilities';\nimport type { RESTPostAPIApplicationCommandsJSONBody } from 'discord-api-types/v10';\nimport { ApplicationCommandType, type ApplicationCommandManager } from 'discord.js';\nimport type { Command } from '../../structures/Command';\nimport type { CommandStore } from '../../structures/CommandStore';\nimport { InternalRegistryAPIType, RegisterBehavior } from '../../types/Enums';\nimport { Events } from '../../types/Events';\nimport { ApplicationCommandRegistry } from './ApplicationCommandRegistry';\nimport { getNeededRegistryParameters } from './getNeededParameters';\nimport { emitBulkOverwriteError, emitPerRegistryError } from './registriesErrors';\nimport { bulkOverwriteDebug, bulkOverwriteWarn } from './registriesLog';\n\nexport let defaultBehaviorWhenNotIdentical = RegisterBehavior.Overwrite;\nexport let defaultGuildIds: ApplicationCommandRegistry.RegisterOptions['guildIds'] = undefined;\nlet bulkOVerwriteRetries = 1;\n\nexport const registries = new Map<string, ApplicationCommandRegistry>();\n\nexport const allGuildIdsToFetchCommandsFor = new Set<string>();\n\n/**\n * Acquires a registry for a command by its name.\n * @param commandName The name of the command.\n * @returns The application command registry for the command\n */\nexport function acquire(commandName: string) {\n\tconst existing = registries.get(commandName);\n\tif (existing) {\n\t\treturn existing;\n\t}\n\n\tconst newRegistry = new ApplicationCommandRegistry(commandName);\n\tregistries.set(commandName, newRegistry);\n\n\treturn newRegistry;\n}\n\n/**\n * Sets the default behavior when registered commands aren't identical to provided data.\n * @param behavior The default behavior to have. Set this to `null` to reset it to the default\n * of `RegisterBehavior.Overwrite`.\n */\nexport function setDefaultBehaviorWhenNotIdentical(behavior?: RegisterBehavior | null) {\n\tdefaultBehaviorWhenNotIdentical = behavior ?? RegisterBehavior.Overwrite;\n}\n\nexport function getDefaultBehaviorWhenNotIdentical() {\n\treturn defaultBehaviorWhenNotIdentical;\n}\n\n/**\n * Sets the default guild ids for registering commands. This is used when a command is registered _without_ providing\n * `guildIds` in that command's own {@link Command.registerApplicationCommands} method.\n * @param guildIds The default guildIds to set. Set this to `null` to reset it to the default\n * of `undefined`.\n */\nexport function setDefaultGuildIds(guildIds?: ApplicationCommandRegistry.RegisterOptions['guildIds'] | null) {\n\tdefaultGuildIds = guildIds ?? undefined;\n}\n\nexport function getDefaultGuildIds() {\n\treturn defaultGuildIds;\n}\n\n/**\n * Sets the amount of retries for when registering commands, only applies when {@link defaultBehaviorWhenNotIdentical}\n * is set to {@link RegisterBehavior.BulkOverwrite}. This is used if registering the commands times out.\n * The default value is `1`, which means no retries are performed.\n * @param newAmountOfRetries The new amount of retries to set. Set this to `null` to reset it to the default\n */\nexport function setBulkOverwriteRetries(newAmountOfRetries: number | null) {\n\tnewAmountOfRetries ??= 1;\n\n\tif (newAmountOfRetries <= 0) throw new RangeError('The amount of retries must be greater than 0');\n\n\tbulkOVerwriteRetries = newAmountOfRetries;\n}\n\nexport function getBulkOverwriteRetries() {\n\treturn bulkOVerwriteRetries;\n}\n\nexport async function handleRegistryAPICalls() {\n\tcontainer.client.emit(Events.ApplicationCommandRegistriesInitialising);\n\n\tconst commandStore = container.stores.get('commands');\n\n\tfor (const command of commandStore.values()) {\n\t\tif (command.registerApplicationCommands) {\n\t\t\ttry {\n\t\t\t\tawait command.registerApplicationCommands(command.applicationCommandRegistry);\n\t\t\t} catch (error) {\n\t\t\t\temitPerRegistryError(error, command);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (getDefaultBehaviorWhenNotIdentical() === RegisterBehavior.BulkOverwrite) {\n\t\tawait handleBulkOverwrite(commandStore, container.client.application!.commands);\n\t\treturn;\n\t}\n\n\tconst params = await getNeededRegistryParameters(allGuildIdsToFetchCommandsFor);\n\n\tawait handleAppendOrUpdate(commandStore, params);\n}\n\nexport async function handleBulkOverwrite(commandStore: CommandStore, applicationCommands: ApplicationCommandManager) {\n\tconst now = Date.now();\n\n\t// Map registries by guild, global, etc\n\tconst foundGlobalCommands: BulkOverwriteData[] = [];\n\tconst foundGuildCommands: Record<string, BulkOverwriteData[]> = {};\n\n\t// Collect all data\n\tfor (const command of commandStore.values()) {\n\t\tconst registry = command.applicationCommandRegistry;\n\n\t\tfor (const call of registry['apiCalls']) {\n\t\t\t// Guild only cmd\n\t\t\tif (call.registerOptions.guildIds?.length) {\n\t\t\t\tfor (const guildId of call.registerOptions.guildIds) {\n\t\t\t\t\tfoundGuildCommands[guildId] ??= [];\n\n\t\t\t\t\tfoundGuildCommands[guildId].push({ piece: command, data: call.builtData });\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Global command\n\t\t\tfoundGlobalCommands.push({ piece: command, data: call.builtData });\n\t\t}\n\t}\n\n\t// Handle global commands\n\tawait retry(() => handleBulkOverwriteGlobalCommands(commandStore, applicationCommands, foundGlobalCommands), bulkOVerwriteRetries);\n\n\t// Handle guild commands\n\tfor (const [guildId, guildCommands] of Object.entries(foundGuildCommands)) {\n\t\tawait retry(() => handleBulkOverwriteGuildCommands(commandStore, applicationCommands, guildId, guildCommands), bulkOVerwriteRetries);\n\t}\n\n\tcontainer.client.emit(Events.ApplicationCommandRegistriesRegistered, registries, Date.now() - now);\n}\n\nasync function handleBulkOverwriteGlobalCommands(\n\tcommandStore: CommandStore,\n\tapplicationCommands: ApplicationCommandManager,\n\tfoundGlobalCommands: BulkOverwriteData[]\n) {\n\ttry {\n\t\tbulkOverwriteDebug(`Overwriting global application commands, now at ${foundGlobalCommands.length} commands`);\n\t\tconst result = await applicationCommands.set(foundGlobalCommands.map((x) => x.data));\n\n\t\t// Go through each registered command, find its piece and alias it\n\t\tfor (const [id, globalCommand] of result.entries()) {\n\t\t\tconst piece = foundGlobalCommands.find((x) => x.data.name === globalCommand.name)?.piece;\n\n\t\t\tif (piece) {\n\t\t\t\tconst registry = piece.applicationCommandRegistry;\n\n\t\t\t\tswitch (globalCommand.type) {\n\t\t\t\t\tcase ApplicationCommandType.ChatInput: {\n\t\t\t\t\t\tregistry['handleIdAddition'](InternalRegistryAPIType.ChatInput, id);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase ApplicationCommandType.User:\n\t\t\t\t\tcase ApplicationCommandType.Message: {\n\t\t\t\t\t\tregistry['handleIdAddition'](InternalRegistryAPIType.ContextMenu, id);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// idHints are useless, and any manually added id or names could end up not being valid any longer if you use bulk overwrites\n\t\t\t\t// That said, this might be an issue, so we might need to do it like `handleAppendOrUpdate`\n\t\t\t\tcommandStore.aliases.set(id, piece);\n\t\t\t} else {\n\t\t\t\tbulkOverwriteWarn(\n\t\t\t\t\t`Registered global command \"${globalCommand.name}\" (${id}) but failed to find the piece in the command store. This should not happen`\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tcontainer.client.emit(Events.ApplicationCommandRegistriesBulkOverwrite, result, null);\n\t} catch (error) {\n\t\tif (error instanceof Error && error.name === 'AbortError') throw error;\n\n\t\temitBulkOverwriteError(error, null);\n\t}\n}\n\nasync function handleBulkOverwriteGuildCommands(\n\tcommandStore: CommandStore,\n\tapplicationCommands: ApplicationCommandManager,\n\tguildId: string,\n\tguildCommands: BulkOverwriteData[]\n) {\n\ttry {\n\t\tbulkOverwriteDebug(`Overwriting guild application commands for guild ${guildId}, now at ${guildCommands.length} commands`);\n\t\tconst result = await applicationCommands.set(\n\t\t\tguildCommands.map((x) => x.data),\n\t\t\tguildId\n\t\t);\n\n\t\t// Go through each registered command, find its piece and alias it\n\t\tfor (const [id, guildCommand] of result.entries()) {\n\t\t\t// I really hope nobody has a guild command with the same name as another command -.-\n\t\t\t// Not like they could anyways as Discord would throw an error for duplicate names\n\t\t\t// But yknow... If you're reading this and you did this... Why?\n\t\t\tconst piece = guildCommands.find((x) => x.data.name === guildCommand.name)?.piece;\n\n\t\t\tif (piece) {\n\t\t\t\tconst registry = piece.applicationCommandRegistry;\n\n\t\t\t\tswitch (guildCommand.type) {\n\t\t\t\t\tcase ApplicationCommandType.ChatInput: {\n\t\t\t\t\t\tregistry['handleIdAddition'](InternalRegistryAPIType.ChatInput, id, guildId);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase ApplicationCommandType.User:\n\t\t\t\t\tcase ApplicationCommandType.Message: {\n\t\t\t\t\t\tregistry['handleIdAddition'](InternalRegistryAPIType.ContextMenu, id, guildId);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// idHints are useless, and any manually added ids or names could no longer be valid if you use bulk overwrites.\n\t\t\t\t// That said, this might be an issue, so we might need to do it like `handleAppendOrUpdate`\n\t\t\t\tcommandStore.aliases.set(id, piece);\n\t\t\t} else {\n\t\t\t\tbulkOverwriteWarn(\n\t\t\t\t\t`Registered guild command \"${guildCommand.name}\" (${id}) but failed to find the piece in the command store. This should not happen`\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tcontainer.client.emit(Events.ApplicationCommandRegistriesBulkOverwrite, result, guildId);\n\t} catch (error) {\n\t\tif (error instanceof Error && error.name === 'AbortError') throw error;\n\n\t\temitBulkOverwriteError(error, guildId);\n\t}\n}\n\nasync function handleAppendOrUpdate(\n\tcommandStore: CommandStore,\n\t{ applicationCommands, globalCommands, guildCommands }: Awaited<ReturnType<typeof getNeededRegistryParameters>>\n) {\n\tconst now = Date.now();\n\n\tfor (const registry of registries.values()) {\n\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\tawait registry['runAPICalls'](applicationCommands, globalCommands, guildCommands);\n\n\t\tconst piece = registry.command;\n\n\t\tif (piece) {\n\t\t\tfor (const nameOrId of piece.applicationCommandRegistry.chatInputCommands) {\n\t\t\t\tcommandStore.aliases.set(nameOrId, piece);\n\t\t\t}\n\n\t\t\tfor (const nameOrId of piece.applicationCommandRegistry.contextMenuCommands) {\n\t\t\t\tcommandStore.aliases.set(nameOrId, piece);\n\t\t\t}\n\t\t}\n\t}\n\n\tcontainer.client.emit(Events.ApplicationCommandRegistriesRegistered, registries, Date.now() - now);\n}\n\ninterface BulkOverwriteData {\n\tpiece: Command;\n\tdata: RESTPostAPIApplicationCommandsJSONBody;\n}\n"],"mappings":";;;;;;;;;;;;AAcA,IAAW,kCAAkCA,yCAAiB;AAC9D,IAAWC,kBAA0E;AACrF,IAAI,uBAAuB;AAE3B,MAAa,6BAAa,IAAI,KAAyC;AAEvE,MAAa,gDAAgC,IAAI,KAAa;;;;;;AAO9D,SAAgB,QAAQ,aAAqB;CAC5C,MAAM,WAAW,WAAW,IAAI,YAAY;AAC5C,KAAI,SACH,QAAO;CAGR,MAAM,cAAc,IAAIC,6FAA2B,YAAY;AAC/D,YAAW,IAAI,aAAa,YAAY;AAExC,QAAO;;;;;;;AAQR,SAAgB,mCAAmC,UAAoC;AACtF,mCAAkC,YAAYF,yCAAiB;;AAGhE,SAAgB,qCAAqC;AACpD,QAAO;;;;;;;;AASR,SAAgB,mBAAmB,UAA0E;AAC5G,mBAAkB,YAAY;;AAG/B,SAAgB,qBAAqB;AACpC,QAAO;;;;;;;;AASR,SAAgB,wBAAwB,oBAAmC;AAC1E,wBAAuB;AAEvB,KAAI,sBAAsB,EAAG,OAAM,IAAI,WAAW,+CAA+C;AAEjG,wBAAuB;;AAGxB,SAAgB,0BAA0B;AACzC,QAAO;;AAGR,eAAsB,yBAAyB;AAC9C,6BAAU,OAAO,KAAKG,gCAAO,yCAAyC;CAEtE,MAAM,eAAeC,4BAAU,OAAO,IAAI,WAA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