@nectar-js/nectar 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registration-CaE0QBT6.js","names":[],"sources":["../src/config.ts","../src/events/intents.ts","../src/registration/normalize.ts","../src/registration/diff.ts","../src/registration/remote.ts","../src/registration/errors.ts","../src/registration/sync.ts"],"sourcesContent":["import type { ClientOptions } from \"discord.js\";\nimport type { NectarPlugin } from \"./plugins/index.js\";\nimport type { LoggerOptions } from \"./runtime/logger.js\";\nimport type { Signal } from \"./runtime/signals.js\";\nimport type { Env } from \"./runtime/types.js\";\n\n/** `nectar.config.ts`: `export default defineConfig({ ... })`. */\nexport interface NectarConfig {\n /**\n * Bot token. Usually `process.env.DISCORD_TOKEN`; the CLI falls back to that variable when\n * this is omitted or empty.\n */\n token?: string | undefined;\n /** Application ID, for command registration. Falls back to `DISCORD_APPLICATION_ID`. */\n applicationId?: string | undefined;\n intents: ClientOptions[\"intents\"];\n partials?: ClientOptions[\"partials\"];\n /** Extra discord.js client options. `intents` and `partials` above take precedence. */\n client?: Partial<ClientOptions>;\n /** Import every handler at startup. Defaults to `true` in production, `false` otherwise. */\n eager?: boolean;\n /** Overrides `NODE_ENV`. */\n env?: Env;\n /**\n * Framework log level and sink. The default sink prints to the console; pass `sink` to hand\n * records to your own logger. Handlers are free to log however they like.\n */\n logger?: LoggerOptions;\n /** Called with every framework signal: interaction lifecycle, failures, gateway state, shutdown. */\n observe?: (signal: Signal) => void;\n /** Plugins, in the order their hooks run. This is the only way to register one. */\n plugins?: NectarPlugin[];\n /** Route directory, relative to the project root. Defaults to `app`. */\n appDir?: string;\n /** Build output, relative to the project root. Defaults to `.nectar`. */\n outDir?: string;\n dev?: {\n /** Guilds that receive commands instantly while developing. */\n guilds?: string[];\n };\n commands?: {\n /**\n * Where commands are registered outside development: everywhere, or only in the listed\n * guilds. Defaults to `\"global\"`. Development always uses `dev.guilds`.\n */\n target?: \"global\" | string[];\n };\n /**\n * Overrides for one environment, applied once the environment is known. Each key replaces\n * the value above it; nested objects are not merged.\n */\n environments?: Partial<Record<Env, Partial<Omit<NectarConfig, \"env\" | \"environments\">>>>;\n}\n\nexport function defineConfig(config: NectarConfig): NectarConfig {\n return config;\n}\n\n/** The config one environment runs with: `environments[env]` over the rest. */\nexport function configFor(config: NectarConfig, env: Env): NectarConfig {\n const { environments, ...base } = config;\n return { ...base, ...environments?.[env] };\n}\n\nexport class ConfigError extends Error {\n constructor(\n readonly file: string,\n readonly detail: string,\n ) {\n super(`${file}: ${detail}`);\n this.name = \"ConfigError\";\n }\n}\n\nconst ENVS = new Set<string>([\"development\", \"test\", \"production\"]);\nconst LEVELS = new Set<string>([\"debug\", \"info\", \"warn\", \"error\"]);\n\n/** Checks a loaded config's shape. Discord validates intent and partial values itself at login. */\nexport function validateConfig(value: unknown, file: string): NectarConfig {\n const fail = (detail: string): never => {\n throw new ConfigError(file, detail);\n };\n if (!isRecord(value)) fail(\"the default export must be an object. Use defineConfig({ ... }).\");\n const config = value as Record<string, unknown>;\n\n for (const key of [\"token\", \"applicationId\"] as const) {\n if (config[key] !== undefined && typeof config[key] !== \"string\") {\n fail(`\\`${key}\\` must be a string, usually read from process.env.`);\n }\n }\n if (config.intents === undefined) fail(\"`intents` is required. Use [] for none.\");\n if (!isBitfield(config.intents)) {\n fail(\"`intents` must be an array of intent names or bits, a single bit, or a bigint.\");\n }\n if (config.partials !== undefined && !Array.isArray(config.partials)) {\n fail(\"`partials` must be an array.\");\n }\n if (config.client !== undefined && !isRecord(config.client)) fail(\"`client` must be an object.\");\n if (config.eager !== undefined && typeof config.eager !== \"boolean\") {\n fail(\"`eager` must be a boolean.\");\n }\n if (config.env !== undefined && (typeof config.env !== \"string\" || !ENVS.has(config.env))) {\n fail('`env` must be \"development\", \"test\", or \"production\".');\n }\n if (config.logger !== undefined) {\n if (!isRecord(config.logger)) fail(\"`logger` must be an object.\");\n const { level, sink } = config.logger as Record<string, unknown>;\n if (level !== undefined && (typeof level !== \"string\" || !LEVELS.has(level))) {\n fail('`logger.level` must be \"debug\", \"info\", \"warn\", or \"error\".');\n }\n if (sink !== undefined && typeof sink !== \"function\") {\n fail(\"`logger.sink` must be a function that receives log records.\");\n }\n }\n if (config.observe !== undefined && typeof config.observe !== \"function\") {\n fail(\"`observe` must be a function that receives signals.\");\n }\n if (config.plugins !== undefined) validatePlugins(config.plugins, fail);\n for (const key of [\"appDir\", \"outDir\"] as const) {\n const dir = config[key];\n if (dir !== undefined && (typeof dir !== \"string\" || dir === \"\")) {\n fail(`\\`${key}\\` must be a non-empty string.`);\n }\n }\n if (config.dev !== undefined) {\n if (!isRecord(config.dev)) fail(\"`dev` must be an object.\");\n const guilds = (config.dev as Record<string, unknown>).guilds;\n if (guilds !== undefined && !isGuildList(guilds)) {\n fail(\"`dev.guilds` must be an array of guild ID strings.\");\n }\n }\n if (config.commands !== undefined) {\n if (!isRecord(config.commands)) fail(\"`commands` must be an object.\");\n const target = (config.commands as Record<string, unknown>).target;\n if (target !== undefined && target !== \"global\" && !isGuildList(target)) {\n fail('`commands.target` must be \"global\" or an array of guild ID strings.');\n }\n }\n if (config.environments !== undefined) validateEnvironments(config, file, fail);\n return config as unknown as NectarConfig;\n}\n\n/** Each override must name an environment, and the config it produces must be valid. */\nfunction validateEnvironments(\n config: Record<string, unknown>,\n file: string,\n fail: (detail: string) => never,\n): void {\n if (!isRecord(config.environments)) fail(\"`environments` must be an object.\");\n for (const [name, override] of Object.entries(config.environments as Record<string, unknown>)) {\n const where = `\\`environments.${name}\\``;\n if (!ENVS.has(name)) fail(`${where}: use \"development\", \"test\", or \"production\" as the key.`);\n if (!isRecord(override)) fail(`${where} must be an object.`);\n for (const key of [\"env\", \"environments\"]) {\n if (key in (override as Record<string, unknown>)) fail(`${where} cannot set \\`${key}\\`.`);\n }\n try {\n validateConfig(configFor(config as unknown as NectarConfig, name as Env), file);\n } catch (error) {\n if (error instanceof ConfigError) fail(`${where}: ${error.detail}`);\n throw error;\n }\n }\n}\n\n/** Names `nectar` already answers to. A plugin command cannot take one. */\nconst BUILTIN_COMMANDS = new Set([\n \"dev\",\n \"build\",\n \"check\",\n \"routes\",\n \"manifest\",\n \"sync\",\n \"start\",\n \"clean\",\n \"info\",\n \"help\",\n]);\n\nfunction validatePlugins(value: unknown, fail: (detail: string) => never): void {\n if (!Array.isArray(value)) fail(\"`plugins` must be an array of plugins.\");\n const names = new Set<string>();\n const commands = new Map<string, string>();\n value.forEach((plugin: unknown, index) => {\n if (!isRecord(plugin) || typeof plugin.name !== \"string\" || plugin.name === \"\") {\n fail(\n `\\`plugins[${index}]\\` must be an object with a non-empty \\`name\\`. Use definePlugin({ ... }).`,\n );\n }\n const name = plugin.name as string;\n if (names.has(name)) fail(`Plugin \"${name}\" is listed twice.`);\n names.add(name);\n for (const hook of [\"transform\", \"types\", \"start\", \"stop\", \"startGlobal\", \"stopGlobal\"]) {\n if (plugin[hook] !== undefined && typeof plugin[hook] !== \"function\") {\n fail(`Plugin \"${name}\": \\`${hook}\\` must be a function.`);\n }\n }\n if (plugin.commands === undefined) return;\n if (!Array.isArray(plugin.commands)) fail(`Plugin \"${name}\": \\`commands\\` must be an array.`);\n for (const command of plugin.commands as unknown[]) {\n if (\n !isRecord(command) ||\n typeof command.name !== \"string\" ||\n !/^[a-z][a-z0-9-]*$/.test(command.name) ||\n typeof command.description !== \"string\" ||\n typeof command.run !== \"function\"\n ) {\n fail(\n `Plugin \"${name}\": every command needs a lowercase \\`name\\`, a \\`description\\`, and a \\`run\\` function.`,\n );\n }\n const commandName = command.name as string;\n if (BUILTIN_COMMANDS.has(commandName)) {\n fail(`Plugin \"${name}\": command \"${commandName}\" is built into nectar. Pick another name.`);\n }\n const owner = commands.get(commandName);\n if (owner !== undefined && owner !== name) {\n fail(`Plugins \"${owner}\" and \"${name}\" both define the command \"${commandName}\".`);\n }\n commands.set(commandName, name);\n }\n });\n}\n\nfunction isGuildList(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((g) => typeof g === \"string\" && /^\\d+$/.test(g));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isBitfield(value: unknown): boolean {\n if (typeof value === \"number\" || typeof value === \"bigint\" || typeof value === \"string\") {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(\n (v) => typeof v === \"number\" || typeof v === \"string\" || typeof v === \"bigint\",\n );\n }\n return isRecord(value) && \"bitfield\" in value;\n}\n","import { type BitFieldResolvable, GatewayIntentBits, IntentsBitField } from \"discord.js\";\nimport type { Diagnostic } from \"../compiler/diagnostics.js\";\nimport type { CompiledEvent } from \"./compile.js\";\n\ntype Intent = keyof typeof GatewayIntentBits;\n\nconst PRIVILEGED: ReadonlySet<Intent> = new Set([\n \"GuildMembers\",\n \"GuildPresences\",\n \"MessageContent\",\n]);\n\nconst guildOrDm = (guild: Intent, dm: Intent): Intent[] => [guild, dm];\n\n/**\n * Which intent a gateway event needs. A list means any one of them is enough: message events\n * arrive with either the guild or the direct message intent. Events missing here need none.\n */\nconst REQUIRED: Record<string, Intent[]> = {\n guildCreate: [\"Guilds\"],\n guildUpdate: [\"Guilds\"],\n guildDelete: [\"Guilds\"],\n guildAvailable: [\"Guilds\"],\n guildUnavailable: [\"Guilds\"],\n channelCreate: [\"Guilds\"],\n channelUpdate: [\"Guilds\"],\n channelDelete: [\"Guilds\"],\n channelPinsUpdate: [\"Guilds\"],\n threadCreate: [\"Guilds\"],\n threadUpdate: [\"Guilds\"],\n threadDelete: [\"Guilds\"],\n threadListSync: [\"Guilds\"],\n threadMemberUpdate: [\"Guilds\"],\n threadMembersUpdate: [\"GuildMembers\"],\n stageInstanceCreate: [\"Guilds\"],\n stageInstanceUpdate: [\"Guilds\"],\n stageInstanceDelete: [\"Guilds\"],\n roleCreate: [\"Guilds\"],\n roleUpdate: [\"Guilds\"],\n roleDelete: [\"Guilds\"],\n guildMemberAdd: [\"GuildMembers\"],\n guildMemberUpdate: [\"GuildMembers\"],\n guildMemberRemove: [\"GuildMembers\"],\n guildMemberAvailable: [\"GuildMembers\"],\n guildMembersChunk: [\"GuildMembers\"],\n userUpdate: [\"GuildMembers\"],\n guildBanAdd: [\"GuildModeration\"],\n guildBanRemove: [\"GuildModeration\"],\n guildAuditLogEntryCreate: [\"GuildModeration\"],\n emojiCreate: [\"GuildExpressions\"],\n emojiUpdate: [\"GuildExpressions\"],\n emojiDelete: [\"GuildExpressions\"],\n stickerCreate: [\"GuildExpressions\"],\n stickerUpdate: [\"GuildExpressions\"],\n stickerDelete: [\"GuildExpressions\"],\n guildSoundboardSoundCreate: [\"GuildExpressions\"],\n guildSoundboardSoundUpdate: [\"GuildExpressions\"],\n guildSoundboardSoundDelete: [\"GuildExpressions\"],\n guildSoundboardSoundsUpdate: [\"GuildExpressions\"],\n guildIntegrationsUpdate: [\"GuildIntegrations\"],\n webhooksUpdate: [\"GuildWebhooks\"],\n inviteCreate: [\"GuildInvites\"],\n inviteDelete: [\"GuildInvites\"],\n voiceStateUpdate: [\"GuildVoiceStates\"],\n voiceChannelEffectSend: [\"GuildVoiceStates\"],\n presenceUpdate: [\"GuildPresences\"],\n messageCreate: guildOrDm(\"GuildMessages\", \"DirectMessages\"),\n messageUpdate: guildOrDm(\"GuildMessages\", \"DirectMessages\"),\n messageDelete: guildOrDm(\"GuildMessages\", \"DirectMessages\"),\n messageDeleteBulk: [\"GuildMessages\"],\n messageReactionAdd: guildOrDm(\"GuildMessageReactions\", \"DirectMessageReactions\"),\n messageReactionRemove: guildOrDm(\"GuildMessageReactions\", \"DirectMessageReactions\"),\n messageReactionRemoveAll: guildOrDm(\"GuildMessageReactions\", \"DirectMessageReactions\"),\n messageReactionRemoveEmoji: guildOrDm(\"GuildMessageReactions\", \"DirectMessageReactions\"),\n typingStart: guildOrDm(\"GuildMessageTyping\", \"DirectMessageTyping\"),\n messagePollVoteAdd: guildOrDm(\"GuildMessagePolls\", \"DirectMessagePolls\"),\n messagePollVoteRemove: guildOrDm(\"GuildMessagePolls\", \"DirectMessagePolls\"),\n guildScheduledEventCreate: [\"GuildScheduledEvents\"],\n guildScheduledEventUpdate: [\"GuildScheduledEvents\"],\n guildScheduledEventDelete: [\"GuildScheduledEvents\"],\n guildScheduledEventUserAdd: [\"GuildScheduledEvents\"],\n guildScheduledEventUserRemove: [\"GuildScheduledEvents\"],\n autoModerationRuleCreate: [\"AutoModerationConfiguration\"],\n autoModerationRuleUpdate: [\"AutoModerationConfiguration\"],\n autoModerationRuleDelete: [\"AutoModerationConfiguration\"],\n autoModerationActionExecution: [\"AutoModerationExecution\"],\n};\n\n/** The intents an event route depends on, for tooling. Empty when it needs none. */\nexport function requiredIntents(event: string): readonly Intent[] {\n return REQUIRED[event] ?? [];\n}\n\n/**\n * One warning per event whose handlers can never fire with the configured intents. Never\n * changes the config: privileged intents in particular must be a deliberate choice, made here\n * and in the developer portal.\n */\nexport function checkIntents(\n events: readonly CompiledEvent[],\n intents: BitFieldResolvable<Intent, number>,\n configFile: string,\n): Diagnostic[] {\n const enabled = new IntentsBitField(IntentsBitField.resolve(intents));\n const diagnostics: Diagnostic[] = [];\n for (const event of events) {\n const needed = requiredIntents(event.name);\n if (needed.length === 0 || needed.some((intent) => enabled.has(GatewayIntentBits[intent]))) {\n continue;\n }\n const first = event.handlers[0];\n if (first === undefined) continue;\n const names = needed.map((i) => `\"${i}\"`).join(\" or \");\n const privileged = needed.filter((i) => PRIVILEGED.has(i));\n diagnostics.push({\n code: \"missing-intent\",\n severity: \"warning\",\n message: `\"${event.name}\" never fires without the ${names} intent. Add it to \\`intents\\` in ${configFile}.${\n privileged.length === 0\n ? \"\"\n : ` ${privileged.map((i) => `\"${i}\"`).join(\" and \")} is privileged: enable it under Bot in the Discord developer portal as well.`\n }`,\n file: first.route.file,\n route: first.route.id,\n });\n }\n return diagnostics;\n}\n","import type {\n APIApplicationCommand,\n APIApplicationCommandOption,\n RESTPostAPIApplicationCommandsJSONBody,\n} from \"discord-api-types/v10\";\nimport { ApplicationCommandType, ApplicationIntegrationType } from \"discord-api-types/v10\";\n\n/**\n * A command reduced to the fields that decide whether Discord would consider it changed.\n *\n * Discord fills in defaults (`nsfw: false`, `integration_types: [0]`, `required: false`, empty\n * localization maps as `null`) and adds bookkeeping (`id`, `version`, `application_id`,\n * `dm_permission`) when it echoes a command back. Both sides pass through here so a no-op sync\n * produces an empty diff.\n */\nexport type NormalizedCommand = Record<string, unknown>;\n\nexport type AnyCommand = RESTPostAPIApplicationCommandsJSONBody | APIApplicationCommand;\n\n/** `<type>:<name>`. Discord allows the same name across command types. */\nexport function commandKey(command: { type?: number | undefined; name: string }): string {\n return `${command.type ?? ApplicationCommandType.ChatInput}:${command.name}`;\n}\n\nexport function normalizeCommand(command: AnyCommand): NormalizedCommand {\n const c = command as unknown as Record<string, unknown>;\n const type = (c.type as number | undefined) ?? ApplicationCommandType.ChatInput;\n return compact({\n type,\n name: c.name,\n name_localizations: localizations(c.name_localizations),\n description: type === ApplicationCommandType.ChatInput ? (c.description ?? \"\") : \"\",\n description_localizations: localizations(c.description_localizations),\n options: options(c.options),\n default_member_permissions:\n c.default_member_permissions == null ? undefined : String(c.default_member_permissions),\n nsfw: c.nsfw === true ? true : undefined,\n contexts: numbers(c.contexts),\n integration_types: numbers(c.integration_types) ?? [ApplicationIntegrationType.GuildInstall],\n });\n}\n\nfunction options(value: unknown): NormalizedCommand[] | undefined {\n if (!Array.isArray(value) || value.length === 0) return undefined;\n return (value as APIApplicationCommandOption[]).map((option) => {\n const o = option as unknown as Record<string, unknown>;\n return compact({\n type: o.type,\n name: o.name,\n name_localizations: localizations(o.name_localizations),\n description: o.description,\n description_localizations: localizations(o.description_localizations),\n required: o.required === true ? true : undefined,\n autocomplete: o.autocomplete === true ? true : undefined,\n choices: choices(o.choices),\n options: options(o.options),\n channel_types: numbers(o.channel_types),\n min_value: number(o.min_value),\n max_value: number(o.max_value),\n min_length: number(o.min_length),\n max_length: number(o.max_length),\n });\n });\n}\n\nfunction choices(value: unknown): NormalizedCommand[] | undefined {\n if (!Array.isArray(value) || value.length === 0) return undefined;\n return value.map((choice: Record<string, unknown>) =>\n compact({\n name: choice.name,\n value: choice.value,\n name_localizations: localizations(choice.name_localizations),\n }),\n );\n}\n\nfunction localizations(value: unknown): Record<string, string> | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const entries = Object.entries(value as Record<string, unknown>).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\",\n );\n if (entries.length === 0) return undefined;\n entries.sort(([a], [b]) => a.localeCompare(b));\n return Object.fromEntries(entries);\n}\n\n/** Sorted, deduplicated. Discord treats these as sets. */\nfunction numbers(value: unknown): number[] | undefined {\n if (!Array.isArray(value)) return undefined;\n return [...new Set(value as number[])].sort((a, b) => a - b);\n}\n\nfunction number(value: unknown): number | undefined {\n return typeof value === \"number\" ? value : undefined;\n}\n\nfunction compact(object: Record<string, unknown>): NormalizedCommand {\n const out: NormalizedCommand = {};\n for (const [key, value] of Object.entries(object)) {\n if (value !== undefined) out[key] = value;\n }\n return out;\n}\n","import { stableStringify } from \"../manifest/emit.js\";\nimport { type AnyCommand, commandKey, normalizeCommand } from \"./normalize.js\";\n\nexport interface CommandDiff {\n /** Command names, `type:name` when the type is not chat input. */\n added: string[];\n removed: string[];\n changed: string[];\n unchanged: string[];\n hasChanges: boolean;\n}\n\n/** Compares what the app wants registered with what Discord currently has. */\nexport function diffCommands(desired: AnyCommand[], remote: AnyCommand[]): CommandDiff {\n const want = new Map(desired.map((c) => [commandKey(c), stableStringify(normalizeCommand(c))]));\n const have = new Map(remote.map((c) => [commandKey(c), stableStringify(normalizeCommand(c))]));\n\n const diff: CommandDiff = {\n added: [],\n removed: [],\n changed: [],\n unchanged: [],\n hasChanges: false,\n };\n for (const [key, body] of want) {\n const current = have.get(key);\n if (current === undefined) diff.added.push(label(key));\n else if (current === body) diff.unchanged.push(label(key));\n else diff.changed.push(label(key));\n }\n for (const key of have.keys()) {\n if (!want.has(key)) diff.removed.push(label(key));\n }\n for (const list of [diff.added, diff.removed, diff.changed, diff.unchanged]) list.sort();\n diff.hasChanges = diff.added.length + diff.removed.length + diff.changed.length > 0;\n return diff;\n}\n\nfunction label(key: string): string {\n return key.startsWith(\"1:\") ? key.slice(2) : key;\n}\n","import type {\n APIApplicationCommand,\n RESTPostAPIApplicationCommandsJSONBody,\n} from \"discord-api-types/v10\";\nimport { Routes } from \"discord-api-types/v10\";\nimport { RegistrationError } from \"./errors.js\";\n\n/** The two calls registration needs. discord.js's `REST` satisfies this. */\nexport interface CommandRest {\n get(route: `/${string}`): Promise<unknown>;\n put(route: `/${string}`, options: { body: unknown }): Promise<unknown>;\n}\n\nexport type Scope = \"global\" | { guild: string };\n\n/** `global` or `guild:<id>`. Used for cache keys and messages. */\nexport function scopeKey(scope: Scope): string {\n return scope === \"global\" ? \"global\" : `guild:${scope.guild}`;\n}\n\nfunction scopeRoute(applicationId: string, scope: Scope): `/${string}` {\n return scope === \"global\"\n ? Routes.applicationCommands(applicationId)\n : Routes.applicationGuildCommands(applicationId, scope.guild);\n}\n\nexport async function fetchCommands(\n rest: CommandRest,\n applicationId: string,\n scope: Scope,\n): Promise<APIApplicationCommand[]> {\n return (await rest.get(scopeRoute(applicationId, scope))) as APIApplicationCommand[];\n}\n\n/** Bulk overwrite: Discord replaces the scope's whole command set with `commands`. */\nexport async function putCommands(\n rest: CommandRest,\n applicationId: string,\n scope: Scope,\n commands: RESTPostAPIApplicationCommandsJSONBody[],\n): Promise<void> {\n try {\n await rest.put(scopeRoute(applicationId, scope), { body: commands });\n } catch (error) {\n throw RegistrationError.from(error, scope, commands) ?? error;\n }\n}\n","import type { RESTPostAPIApplicationCommandsJSONBody } from \"discord-api-types/v10\";\nimport { type Scope, scopeKey } from \"./remote.js\";\n\nexport interface RegistrationProblem {\n /** Command name, or `null` when Discord rejected the request as a whole. */\n command: string | null;\n /** Dotted path inside the command, with option and choice indices replaced by their names. */\n field: string;\n message: string;\n}\n\n/** Discord rejected a bulk overwrite. Wraps the `DiscordAPIError` with per-command detail. */\nexport class RegistrationError extends Error {\n constructor(\n readonly scope: Scope,\n readonly problems: RegistrationProblem[],\n override readonly cause: unknown,\n ) {\n super(\n `Discord rejected the ${scopeKey(scope)} command registration:\\n${problems\n .map(\n (p) =>\n ` ${p.command ?? \"(request)\"}${p.field === \"\" ? \"\" : ` ${p.field}`}: ${p.message}`,\n )\n .join(\"\\n\")}`,\n );\n this.name = \"RegistrationError\";\n }\n\n /** `null` when `error` is not a Discord API error. */\n static from(\n error: unknown,\n scope: Scope,\n commands: RESTPostAPIApplicationCommandsJSONBody[],\n ): RegistrationError | null {\n if (!isDiscordApiError(error)) return null;\n const problems: RegistrationProblem[] = [];\n if (error.rawError.errors !== undefined) {\n collect(error.rawError.errors, [], commands, problems);\n }\n if (problems.length === 0) {\n problems.push({ command: null, field: \"\", message: error.rawError.message });\n }\n return new RegistrationError(scope, problems, error);\n }\n}\n\ninterface DiscordApiErrorLike {\n rawError: { message: string; errors?: unknown };\n}\n\nfunction isDiscordApiError(error: unknown): error is DiscordApiErrorLike {\n if (typeof error !== \"object\" || error === null || !(\"rawError\" in error)) return false;\n const raw = (error as { rawError: unknown }).rawError;\n return (\n typeof raw === \"object\" &&\n raw !== null &&\n typeof (raw as { message?: unknown }).message === \"string\"\n );\n}\n\n/**\n * Discord nests errors by request path, `{ \"0\": { options: { \"1\": { description: { _errors } } } } }`.\n * The top-level index is the command in the bulk body; deeper indices are options and choices.\n */\nfunction collect(\n node: unknown,\n path: (string | number)[],\n commands: RESTPostAPIApplicationCommandsJSONBody[],\n out: RegistrationProblem[],\n) {\n if (typeof node === \"string\") {\n out.push(problem(path, commands, node));\n return;\n }\n if (typeof node !== \"object\" || node === null) return;\n for (const [key, value] of Object.entries(node)) {\n if (key === \"_errors\" && Array.isArray(value)) {\n for (const entry of value) {\n const message =\n typeof entry === \"object\" && entry !== null && \"message\" in entry\n ? String((entry as { message: unknown }).message)\n : String(entry);\n out.push(problem(path, commands, message));\n }\n } else {\n collect(value, [...path, /^\\d+$/.test(key) ? Number(key) : key], commands, out);\n }\n }\n}\n\nfunction problem(\n path: (string | number)[],\n commands: RESTPostAPIApplicationCommandsJSONBody[],\n message: string,\n): RegistrationProblem {\n const [first, ...rest] = path;\n const command = typeof first === \"number\" ? commands[first] : undefined;\n if (command === undefined) return { command: null, field: path.join(\".\"), message };\n\n const field: string[] = [];\n let cursor: unknown = command;\n for (const segment of rest) {\n if (typeof segment === \"number\" && Array.isArray(cursor)) {\n cursor = cursor[segment];\n const name = (cursor as { name?: unknown } | undefined)?.name;\n field.push(typeof name === \"string\" ? name : String(segment));\n } else {\n cursor = (cursor as Record<string, unknown> | undefined)?.[segment];\n field.push(String(segment));\n }\n }\n return { command: command.name, field: field.join(\".\"), message };\n}\n","import { createHash } from \"node:crypto\";\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RESTPostAPIApplicationCommandsJSONBody } from \"discord-api-types/v10\";\nimport { stableStringify } from \"../manifest/emit.js\";\nimport { type CommandDiff, diffCommands } from \"./diff.js\";\nimport { commandKey, normalizeCommand } from \"./normalize.js\";\nimport { type CommandRest, fetchCommands, putCommands, type Scope, scopeKey } from \"./remote.js\";\n\nexport const REGISTRATION_CACHE_FILE = \"registration.json\";\nconst CACHE_VERSION = 1;\n\n/** What the last successful sync sent, so an unchanged app skips the remote read. */\ninterface RegistrationCache {\n version: typeof CACHE_VERSION;\n applicationId: string;\n /** Scope key to hash of the normalized payloads registered there. */\n scopes: Record<string, string>;\n}\n\nexport interface SyncOptions {\n rest: CommandRest;\n applicationId: string;\n commands: RESTPostAPIApplicationCommandsJSONBody[];\n scopes: Scope[];\n /** Directory holding `registration.json`. No cache when omitted. */\n cacheDir?: string;\n /** Compute diffs and report, but write nothing to Discord or the cache. */\n dryRun?: boolean;\n /** Proceed past the safety guard. */\n force?: boolean;\n}\n\nexport interface ScopeSync {\n scope: Scope;\n /** `null` when the cache proved nothing changed and Discord was not consulted. */\n diff: CommandDiff | null;\n /** A bulk overwrite was sent. */\n applied: boolean;\n}\n\nexport interface SyncResult {\n scopes: ScopeSync[];\n /** Why the guard would block this sync. Empty when it is safe. */\n unsafe: string[];\n}\n\n/** Thrown instead of applying when the guard trips and `force` is not set. */\nexport class UnsafeSyncError extends Error {\n constructor(readonly reasons: string[]) {\n super(\n `Refusing to register commands:\\n${reasons.map((r) => ` ${r}`).join(\"\\n\")}\\nPass force to do it anyway.`,\n );\n this.name = \"UnsafeSyncError\";\n }\n}\n\n/**\n * Reconciles every scope: read remote, diff, bulk overwrite only when something differs.\n * All scopes are read and checked before any is written, so a guard failure changes nothing.\n */\nexport async function syncCommands(options: SyncOptions): Promise<SyncResult> {\n const {\n rest,\n applicationId,\n commands,\n scopes,\n cacheDir,\n dryRun = false,\n force = false,\n } = options;\n const cache = cacheDir === undefined ? null : readCache(cacheDir);\n const hash = hashCommands(commands);\n const unsafe: string[] = [];\n\n if (cache !== null && cache.applicationId !== applicationId) {\n unsafe.push(\n `The application ID changed from ${cache.applicationId} to ${applicationId}. Commands registered under the old application are left as they are.`,\n );\n }\n const targets = new Set(scopes.map(scopeKey));\n for (const key of Object.keys(cache?.scopes ?? {})) {\n if (!targets.has(key)) {\n unsafe.push(\n `${key} received commands last time but is no longer a target. Its commands stay registered on Discord until removed.`,\n );\n }\n }\n\n const results: ScopeSync[] = [];\n for (const scope of scopes) {\n const key = scopeKey(scope);\n const cached =\n cache !== null && cache.applicationId === applicationId && cache.scopes[key] === hash;\n if (cached) {\n results.push({ scope, diff: null, applied: false });\n continue;\n }\n const remote = await fetchCommands(rest, applicationId, scope);\n const diff = diffCommands(commands, remote);\n if (commands.length === 0 && remote.length > 0) {\n unsafe.push(`${key} has ${remote.length} command(s) registered and the app declares none.`);\n }\n results.push({ scope, diff, applied: false });\n }\n\n if (dryRun) return { scopes: results, unsafe };\n if (unsafe.length > 0 && !force) throw new UnsafeSyncError(unsafe);\n\n const next: RegistrationCache = { version: CACHE_VERSION, applicationId, scopes: {} };\n for (const result of results) {\n if (result.diff?.hasChanges) {\n await putCommands(rest, applicationId, result.scope, commands);\n result.applied = true;\n }\n next.scopes[scopeKey(result.scope)] = hash;\n // Persist after every scope so a failure halfway does not forget the ones already done.\n if (cacheDir !== undefined) writeCache(cacheDir, next);\n }\n return { scopes: results, unsafe };\n}\n\n/** Order-insensitive, like the diff: reordering commands is not a change. */\nfunction hashCommands(commands: RESTPostAPIApplicationCommandsJSONBody[]): string {\n const normalized = commands\n .map((c) => [commandKey(c), normalizeCommand(c)] as const)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([, c]) => c);\n return createHash(\"sha256\").update(stableStringify(normalized)).digest(\"hex\");\n}\n\nfunction readCache(dir: string): RegistrationCache | null {\n let text: string;\n try {\n text = readFileSync(path.join(dir, REGISTRATION_CACHE_FILE), \"utf8\");\n } catch {\n return null;\n }\n const parsed: unknown = JSON.parse(text);\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n (parsed as { version?: unknown }).version !== CACHE_VERSION\n ) {\n return null;\n }\n return parsed as RegistrationCache;\n}\n\nfunction writeCache(dir: string, cache: RegistrationCache) {\n mkdirSync(dir, { recursive: true });\n writeFileSync(path.join(dir, REGISTRATION_CACHE_FILE), `${stableStringify(cache)}\\n`);\n}\n"],"mappings":";;;;;;;AAsDA,SAAgB,aAAa,QAAoC;CAC/D,OAAO;AACT;;AAGA,SAAgB,UAAU,QAAsB,KAAwB;CACtE,MAAM,EAAE,cAAc,GAAG,SAAS;CAClC,OAAO;EAAE,GAAG;EAAM,GAAG,eAAe;CAAK;AAC3C;AAEA,IAAa,cAAb,cAAiC,MAAM;CAE1B;CACA;CAFX,YACE,MACA,QACA;EACA,MAAM,GAAG,KAAK,IAAI,QAAQ;EAHjB,KAAA,OAAA;EACA,KAAA,SAAA;EAGT,KAAK,OAAO;CACd;AACF;AAEA,MAAM,uBAAO,IAAI,IAAY;CAAC;CAAe;CAAQ;AAAY,CAA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