@nectar-js/nectar 0.1.0 → 0.2.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.
@@ -91,6 +91,69 @@ function escapeValue(value) {
91
91
  }
92
92
  //#endregion
93
93
  //#region src/compiler/diagnostics.ts
94
+ /** Every code the compiler reports. Each has an entry in the diagnostics reference. */
95
+ const DIAGNOSTIC_CODES = [
96
+ "file-outside-category",
97
+ "unknown-category",
98
+ "file-in-wrong-category",
99
+ "invalid-segment",
100
+ "route-without-path",
101
+ "dynamic-segment-not-allowed",
102
+ "duplicate-param",
103
+ "catch-all-not-last",
104
+ "duplicate-route",
105
+ "module-load-failed",
106
+ "missing-handler",
107
+ "route-mismatch",
108
+ "missing-meta",
109
+ "invalid-meta",
110
+ "invalid-name",
111
+ "invalid-description",
112
+ "invalid-option",
113
+ "missing-route-meta",
114
+ "route-meta-without-path",
115
+ "unused-route-meta",
116
+ "mixed-command-and-subcommands",
117
+ "mixed-subcommand-and-group",
118
+ "command-too-deep",
119
+ "too-many-subcommands",
120
+ "context-menu-nested",
121
+ "top-level-field-on-group",
122
+ "top-level-field-on-subcommand",
123
+ "duplicate-command-name",
124
+ "too-many-commands",
125
+ "autocomplete-without-command",
126
+ "autocomplete-export-not-function",
127
+ "autocomplete-unknown-option",
128
+ "autocomplete-missing-handler",
129
+ "autocomplete-missing-file",
130
+ "missing-select-kind",
131
+ "invalid-select-kind",
132
+ "invalid-param-validator",
133
+ "catch-all-route",
134
+ "short-id-collision",
135
+ "duplicate-component-pattern",
136
+ "unknown-event",
137
+ "event-nested-path",
138
+ "event-mode-conflict",
139
+ "missing-intent",
140
+ "plugin-failed",
141
+ "plugin-invalid-change",
142
+ "plugin-unknown-route",
143
+ "plugin-missing-file"
144
+ ];
145
+ const REFERENCE = "https://nectar-js.github.io/nectar/reference/diagnostics";
146
+ /** The reference entry for a compiler code. Codes from plugins have none. */
147
+ function docsUrl(code) {
148
+ return DIAGNOSTIC_CODES.includes(code) ? `${REFERENCE}#${code}` : void 0;
149
+ }
150
+ /** A value's type as a message puts it: `missing`, `a number`, `an array`. */
151
+ function typeOf(value) {
152
+ if (value === void 0) return "missing";
153
+ if (value === null) return "null";
154
+ if (Array.isArray(value)) return "an array";
155
+ return typeof value === "object" ? "an object" : `a ${typeof value}`;
156
+ }
94
157
  var Diagnostics = class {
95
158
  items = [];
96
159
  error(code, message, location = {}) {
@@ -184,11 +247,11 @@ const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
184
247
  */
185
248
  function parseSegment(dirName) {
186
249
  if (dirName.startsWith("[") || dirName.endsWith("]")) {
187
- if (!dirName.startsWith("[") || !dirName.endsWith("]")) return fail(`"${dirName}" has an unmatched bracket. Dynamic segments look like [name].`);
250
+ if (!dirName.startsWith("[") || !dirName.endsWith("]")) return fail(`"${dirName}" has an unmatched bracket. Parameters look like [name].`);
188
251
  const inner = dirName.slice(1, -1);
189
252
  const isCatchAll = inner.startsWith("...");
190
253
  const name = isCatchAll ? inner.slice(3) : inner;
191
- if (!PARAM_NAME.test(name)) return fail(`"${dirName}" is not a valid parameter name. Use letters, digits, and underscores, and do not start with a digit.`);
254
+ if (!PARAM_NAME.test(name)) return fail(`"${dirName}" has an invalid parameter name. Parameters become keys of ctx.params, so use letters, digits, and underscores, and don't start with a digit.`);
192
255
  return ok({
193
256
  type: isCatchAll ? "catchAll" : "dynamic",
194
257
  name
@@ -197,13 +260,13 @@ function parseSegment(dirName) {
197
260
  if (dirName.startsWith("(") || dirName.endsWith(")")) {
198
261
  if (!dirName.startsWith("(") || !dirName.endsWith(")")) return fail(`"${dirName}" has an unmatched parenthesis. Route groups look like (name).`);
199
262
  const name = dirName.slice(1, -1);
200
- if (!STATIC_NAME.test(name)) return fail(`"${dirName}" is not a valid group name. Use letters, digits, hyphens, and underscores.`);
263
+ if (!STATIC_NAME.test(name)) return fail(`"${dirName}" isn't a valid group name. Use letters, digits, hyphens, and underscores.`);
201
264
  return ok({
202
265
  type: "group",
203
266
  name
204
267
  });
205
268
  }
206
- if (!STATIC_NAME.test(dirName)) return fail(`"${dirName}" is not a valid segment name. Use letters, digits, hyphens, and underscores, and start with a letter or digit.`);
269
+ if (!STATIC_NAME.test(dirName)) return fail(`"${dirName}" can't be part of a route path. Use letters, digits, hyphens, and underscores, and start with a letter or digit.`);
207
270
  return ok({
208
271
  type: "static",
209
272
  name: dirName
@@ -240,11 +303,11 @@ function fail(reason) {
240
303
  function paramValidatorsOf(handler, route) {
241
304
  const declared = handler.params;
242
305
  if (declared === void 0) return {};
243
- if (typeof declared !== "object" || declared === null || Array.isArray(declared)) throw new Error(`\`params\` must be an object of validators, got ${typeof declared}.`);
306
+ if (typeof declared !== "object" || declared === null || Array.isArray(declared)) throw new Error(`params is ${typeOf(declared)}, not an object of validators.`);
244
307
  const validators = {};
245
308
  for (const [name, validator] of Object.entries(declared)) {
246
- if (!route.params.includes(name)) throw new Error(`\`params\` validates "${name}", which is not a parameter of this route. ${route.params.length === 0 ? "It has none." : `It has: ${route.params.join(", ")}.`}`);
247
- if (!isValidator(validator)) throw new Error(`\`params.${name}\` must be a function or a Standard Schema, got ${typeof validator}.`);
309
+ if (!route.params.includes(name)) throw new Error(`params validates "${name}", which is not a parameter of this route. ${route.params.length === 0 ? "It has none." : `It has: ${route.params.join(", ")}.`}`);
310
+ if (!isValidator(validator)) throw new Error(`params.${name} is ${typeOf(validator)}. A validator is a function or a Standard Schema.`);
248
311
  validators[name] = validator;
249
312
  }
250
313
  return validators;
@@ -337,7 +400,7 @@ async function compileRoute(route, diagnostics) {
337
400
  const last = route.segments.at(-1);
338
401
  const catchAll = last?.type === "catchAll" ? last.name : null;
339
402
  const overhead = 8 + route.params.length;
340
- if (catchAll !== null) diagnostics.warn("catch-all-route", `${formatSegment(last)} accepts any number of values. Every value counts against Discord's 100 character custom ID limit, and generation throws when it is exceeded.`, {
403
+ if (catchAll !== null) diagnostics.warn("catch-all-route", `${formatSegment(last)} takes any number of values. They all count toward Discord's 100 character limit on custom IDs, and customId() throws when an ID goes over.`, {
341
404
  file: route.file,
342
405
  route: route.id
343
406
  });
@@ -345,17 +408,17 @@ async function compileRoute(route, diagnostics) {
345
408
  try {
346
409
  module = await loadModule(route.file);
347
410
  } catch (error) {
348
- diagnostics.error("module-load-failed", `Could not import this file: ${error instanceof Error ? error.message : String(error)}`, {
411
+ diagnostics.error("module-load-failed", `The compiler imports every route file to read its exports, and this one threw: ${error instanceof Error ? error.message : String(error)}`, {
349
412
  file: route.file,
350
413
  route: route.id
351
414
  });
352
415
  return null;
353
416
  }
354
- if (!checkDeclaredRoute(module, route, diagnostics)) return null;
417
+ if (!checkHandler(module, route, diagnostics)) return null;
355
418
  try {
356
419
  paramValidatorsOf(module.default, route);
357
420
  } catch (error) {
358
- diagnostics.error("invalid-param-validator", `${error instanceof Error ? error.message : String(error)} Pass validators as defineComponent's third argument: { params: { name: (value) => ... } }.`, {
421
+ diagnostics.error("invalid-param-validator", `${error instanceof Error ? error.message : String(error)} Validators go in defineComponent's third argument, like { params: { id: (value) => ... } }.`, {
359
422
  file: route.file,
360
423
  route: route.id
361
424
  });
@@ -375,13 +438,23 @@ async function compileRoute(route, diagnostics) {
375
438
  overhead
376
439
  };
377
440
  }
378
- /** A handler made with `defineComponent(path, ...)` must name the route its file sits in. */
379
- function checkDeclaredRoute(module, route, diagnostics, expected = route.path) {
441
+ /**
442
+ * The default export is the handler Nectar calls, and one made with `defineComponent(path, ...)`
443
+ * or the like must name the route its file sits in.
444
+ */
445
+ function checkHandler(module, route, diagnostics, expected = route.path) {
380
446
  const handler = module.default;
381
- if (typeof handler !== "function") return true;
447
+ if (typeof handler !== "function") {
448
+ const define = route.kind === "command" ? "defineCommand" : route.kind === "event" ? "defineEvent" : "defineComponent";
449
+ diagnostics.error("missing-handler", `This ${path.basename(route.file)} ${handler === void 0 ? "has no default export" : `exports ${typeOf(handler)} as its default`}. Nectar calls the default export when the route runs, so export the handler, like export default ${define}("${expected}", handler).`, {
450
+ file: route.file,
451
+ route: route.id
452
+ });
453
+ return false;
454
+ }
382
455
  const declared = handler.route;
383
456
  if (declared === void 0 || declared === expected) return true;
384
- diagnostics.error("route-mismatch", `This file is the route "${expected}" but its handler declares "${String(declared)}". Update the string or move the file.`, {
457
+ diagnostics.error("route-mismatch", `This file's route is "${expected}", but its handler says "${String(declared)}". The string types the handler, so it has to match where the file is. Change it to "${expected}", or move the file.`, {
385
458
  file: route.file,
386
459
  route: route.id
387
460
  });
@@ -390,14 +463,14 @@ function checkDeclaredRoute(module, route, diagnostics, expected = route.path) {
390
463
  function validateSelectKind(module, route, diagnostics) {
391
464
  const kind = module.kind;
392
465
  if (kind === void 0) {
393
- diagnostics.error("missing-select-kind", "select.ts must export `kind`: \"string\", \"user\", \"role\", \"channel\", or \"mentionable\".", {
466
+ diagnostics.error("missing-select-kind", "This select.ts doesn't export kind, which says what the select menu picks from: \"string\", \"user\", \"role\", \"channel\", or \"mentionable\". Add one, like export const kind = \"string\".", {
394
467
  file: route.file,
395
468
  route: route.id
396
469
  });
397
470
  return null;
398
471
  }
399
472
  if (typeof kind !== "string" || !SELECT_KINDS.has(kind)) {
400
- diagnostics.error("invalid-select-kind", `\`kind\` is ${describe$1(kind)}. Expected "string", "user", "role", "channel", or "mentionable".`, {
473
+ diagnostics.error("invalid-select-kind", `kind is ${describe$1(kind)}. Use "string", "user", "role", "channel", or "mentionable".`, {
401
474
  file: route.file,
402
475
  route: route.id
403
476
  });
@@ -413,7 +486,7 @@ function detectShortIdCollisions(routes, diagnostics) {
413
486
  seen.set(route.shortId, route);
414
487
  continue;
415
488
  }
416
- diagnostics.error("short-id-collision", `${route.id} and ${existing.id} hash to the same short ID "${route.shortId}", so their custom IDs would be indistinguishable. Rename one of the directories.`, {
489
+ diagnostics.error("short-id-collision", `${route.id} and ${existing.id} hash to the same short ID, "${route.shortId}", so Nectar can't tell their custom IDs apart. Rename a directory in one of them.`, {
417
490
  file: route.file,
418
491
  route: route.id
419
492
  });
@@ -421,7 +494,8 @@ function detectShortIdCollisions(routes, diagnostics) {
421
494
  }
422
495
  /**
423
496
  * Two routes of the same kind whose paths differ only in parameter names, like
424
- * `tickets/[id]/close` and `tickets/[ticketId]/close`, would both claim the same custom IDs.
497
+ * `tickets/[id]/close` and `tickets/[ticketId]/close`. Their hashes differ, but they take the
498
+ * same values in the same places, so they are one route split in two.
425
499
  */
426
500
  function detectDuplicatePatterns(routes, diagnostics) {
427
501
  const seen = /* @__PURE__ */ new Map();
@@ -434,7 +508,7 @@ function detectDuplicatePatterns(routes, diagnostics) {
434
508
  continue;
435
509
  }
436
510
  if (existing.id === route.id) continue;
437
- diagnostics.error("duplicate-component-pattern", `${route.id} has the same shape as ${existing.id} (${relative(existing.file)}). Parameter names do not make routes distinct.`, {
511
+ diagnostics.error("duplicate-component-pattern", `${route.id} is the same path as ${existing.id} in ${relative(existing.file)}, with a different parameter name. Parameter names don't make routes distinct. Merge the two and keep one name.`, {
438
512
  file: route.file,
439
513
  route: route.id
440
514
  });
@@ -591,23 +665,24 @@ async function applyPlugins(graph, plugins) {
591
665
  function apply(graph, plugin, change) {
592
666
  const type = isRecord(change) ? change.type : void 0;
593
667
  if (type !== "middleware" && type !== "diagnostic") {
594
- graph.diagnostics.error("plugin-invalid-change", `Plugin "${plugin}" returned a change of type ${JSON.stringify(type)}. Known types: middleware, diagnostic.`);
668
+ graph.diagnostics.error("plugin-invalid-change", `Plugin "${plugin}" returned a change with type ${JSON.stringify(type)}. A change's type is "middleware" or "diagnostic".`);
595
669
  return;
596
670
  }
597
671
  if (change.type === "diagnostic") {
598
672
  const { severity, code, message, file, route } = change;
599
- const where = {
673
+ graph.diagnostics.items.push({
674
+ code,
675
+ severity: severity === "error" ? "error" : "warning",
676
+ message,
600
677
  ...file === void 0 ? {} : { file },
601
678
  ...route === void 0 ? {} : { route }
602
- };
603
- if (severity === "error") graph.diagnostics.error(code, message, where);
604
- else graph.diagnostics.warn(code, message, where);
679
+ });
605
680
  return;
606
681
  }
607
682
  const routes = graph.routes.filter((r) => r.id === change.route && (change.kind === void 0 || r.kind === change.kind));
608
683
  const target = change.kind === void 0 ? change.route : `${change.route} (${change.kind})`;
609
684
  if (routes.length === 0) {
610
- graph.diagnostics.error("plugin-unknown-route", `Plugin "${plugin}" adds middleware to route "${target}", which does not exist.`);
685
+ graph.diagnostics.error("plugin-unknown-route", `Plugin "${plugin}" adds middleware to route "${target}", which does not exist. Route IDs look like "command:moderation/ban".`);
611
686
  return;
612
687
  }
613
688
  if (routes.some((r) => r.category === "event")) {
@@ -658,6 +733,6 @@ var PluginError = class extends Error {
658
733
  }
659
734
  };
660
735
  //#endregion
661
- export { MAX_CUSTOM_ID_LENGTH as C, CustomIdTooLongError as S, version as T, parseSegment as _, MANIFEST_FILE as a, loadModule as b, writeManifest as c, checkDeclaredRoute as d, compileComponents as f, formatSegment as g, paramValidatorsOf as h, pluginGraph as i, encodeComponentRoute as l, findInvalidParam as m, definePlugin as n, stableStringify as o, customIdFor as p, applyPlugins as r, toManifest as s, PluginError as t, registerComponentRoutes as u, enableModuleReloading as v, decodeCustomId as w, Diagnostics as x, invalidateModuleGraph as y };
736
+ export { typeOf as C, version as D, decodeCustomId as E, docsUrl as S, MAX_CUSTOM_ID_LENGTH as T, parseSegment as _, MANIFEST_FILE as a, loadModule as b, writeManifest as c, checkHandler as d, compileComponents as f, formatSegment as g, paramValidatorsOf as h, pluginGraph as i, encodeComponentRoute as l, findInvalidParam as m, definePlugin as n, stableStringify as o, customIdFor as p, applyPlugins as r, toManifest as s, PluginError as t, registerComponentRoutes as u, enableModuleReloading as v, CustomIdTooLongError as w, Diagnostics as x, invalidateModuleGraph as y };
662
737
 
663
- //# sourceMappingURL=plugins-CGvM19v9.js.map
738
+ //# sourceMappingURL=plugins-BCYwtuo-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugins-BCYwtuo-.js","names":["describe"],"sources":["../src/version.ts","../src/components/customId.ts","../src/compiler/diagnostics.ts","../src/compiler/load.ts","../src/compiler/segments.ts","../src/components/params.ts","../src/components/compile.ts","../src/components/registry.ts","../src/manifest/emit.ts","../src/plugins/transform.ts","../src/plugins/index.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\n\n/** From package.json, which sits one level up from both `src/` and `dist/`. */\nexport const { version } = createRequire(import.meta.url)(\"../package.json\") as {\n version: string;\n};\n","/** Discord rejects custom IDs longer than this. */\nexport const MAX_CUSTOM_ID_LENGTH = 100;\n\nconst PREFIX = \"n:\";\nconst SHORT_ID_LENGTH = 6;\n\n/** Characters a route with no parameters uses: the prefix and the short ID. */\nexport const BASE_OVERHEAD = PREFIX.length + SHORT_ID_LENGTH;\n\nexport class CustomIdTooLongError extends Error {\n constructor(\n readonly customId: string,\n readonly routeId: string,\n ) {\n super(\n `Custom ID for ${routeId} is ${customId.length} characters, Discord allows ${MAX_CUSTOM_ID_LENGTH}. Encode a shorter identifier instead of the full value.`,\n );\n this.name = \"CustomIdTooLongError\";\n }\n}\n\n/**\n * Builds `n:<shortId>:<v1>:<v2>...`. Values are escaped so they may contain `:` and `\\`.\n * Throws when the result is longer than Discord allows; it never truncates.\n */\nexport function encodeCustomId(shortId: string, values: readonly string[], routeId = shortId) {\n let out = PREFIX + shortId;\n for (const value of values) out += `:${escapeValue(value)}`;\n if (out.length > MAX_CUSTOM_ID_LENGTH) throw new CustomIdTooLongError(out, routeId);\n return out;\n}\n\nexport type DecodedCustomId =\n | { ok: true; shortId: string; values: string[] }\n | { ok: false; reason: \"not-nectar\" | \"malformed\" };\n\n/**\n * Splits a raw custom ID back into its short ID and positional values.\n * IDs without the Nectar prefix are reported as `not-nectar` so hand-built components pass through.\n */\nexport function decodeCustomId(raw: string): DecodedCustomId {\n if (!raw.startsWith(PREFIX)) return { ok: false, reason: \"not-nectar\" };\n\n const shortId = raw.slice(PREFIX.length, PREFIX.length + SHORT_ID_LENGTH);\n if (!/^[0-9a-z]{6}$/.test(shortId)) return { ok: false, reason: \"malformed\" };\n\n const values: string[] = [];\n let index = PREFIX.length + SHORT_ID_LENGTH;\n if (index === raw.length) return { ok: true, shortId, values };\n if (raw[index] !== \":\") return { ok: false, reason: \"malformed\" };\n index++;\n\n let current = \"\";\n while (index < raw.length) {\n const char = raw[index] as string;\n if (char === \"\\\\\") {\n const next = raw[index + 1];\n if (next !== \"\\\\\" && next !== \":\") return { ok: false, reason: \"malformed\" };\n current += next;\n index += 2;\n continue;\n }\n if (char === \":\") {\n values.push(current);\n current = \"\";\n index++;\n continue;\n }\n current += char;\n index++;\n }\n values.push(current);\n return { ok: true, shortId, values };\n}\n\nfunction escapeValue(value: string): string {\n return value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\":\", \"\\\\:\");\n}\n","export type Severity = \"error\" | \"warning\";\n\nexport interface Diagnostic {\n code: string;\n severity: Severity;\n message: string;\n /** Absolute path of the file or directory that caused the diagnostic. */\n file?: string;\n /** Canonical route identity, when the diagnostic is about a specific route. */\n route?: string;\n}\n\n/** Every code the compiler reports. Each has an entry in the diagnostics reference. */\nexport const DIAGNOSTIC_CODES = [\n \"file-outside-category\",\n \"unknown-category\",\n \"file-in-wrong-category\",\n \"invalid-segment\",\n \"route-without-path\",\n \"dynamic-segment-not-allowed\",\n \"duplicate-param\",\n \"catch-all-not-last\",\n \"duplicate-route\",\n \"module-load-failed\",\n \"missing-handler\",\n \"route-mismatch\",\n \"missing-meta\",\n \"invalid-meta\",\n \"invalid-name\",\n \"invalid-description\",\n \"invalid-option\",\n \"missing-route-meta\",\n \"route-meta-without-path\",\n \"unused-route-meta\",\n \"mixed-command-and-subcommands\",\n \"mixed-subcommand-and-group\",\n \"command-too-deep\",\n \"too-many-subcommands\",\n \"context-menu-nested\",\n \"top-level-field-on-group\",\n \"top-level-field-on-subcommand\",\n \"duplicate-command-name\",\n \"too-many-commands\",\n \"autocomplete-without-command\",\n \"autocomplete-export-not-function\",\n \"autocomplete-unknown-option\",\n \"autocomplete-missing-handler\",\n \"autocomplete-missing-file\",\n \"missing-select-kind\",\n \"invalid-select-kind\",\n \"invalid-param-validator\",\n \"catch-all-route\",\n \"short-id-collision\",\n \"duplicate-component-pattern\",\n \"unknown-event\",\n \"event-nested-path\",\n \"event-mode-conflict\",\n \"missing-intent\",\n \"plugin-failed\",\n \"plugin-invalid-change\",\n \"plugin-unknown-route\",\n \"plugin-missing-file\",\n] as const;\n\nexport type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[number];\n\nconst REFERENCE = \"https://nectar-js.github.io/nectar/reference/diagnostics\";\n\n/** The reference entry for a compiler code. Codes from plugins have none. */\nexport function docsUrl(code: string): string | undefined {\n return (DIAGNOSTIC_CODES as readonly string[]).includes(code)\n ? `${REFERENCE}#${code}`\n : undefined;\n}\n\n/** A value's type as a message puts it: `missing`, `a number`, `an array`. */\nexport function typeOf(value: unknown): string {\n if (value === undefined) return \"missing\";\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"an array\";\n return typeof value === \"object\" ? \"an object\" : `a ${typeof value}`;\n}\n\ninterface DiagnosticLocation {\n file?: string;\n route?: string;\n}\n\nexport class Diagnostics {\n readonly items: Diagnostic[] = [];\n\n error(code: DiagnosticCode, message: string, location: DiagnosticLocation = {}): void {\n this.push(\"error\", code, message, location);\n }\n\n warn(code: DiagnosticCode, message: string, location: DiagnosticLocation = {}): void {\n this.push(\"warning\", code, message, location);\n }\n\n get hasErrors(): boolean {\n return this.items.some((d) => d.severity === \"error\");\n }\n\n private push(\n severity: Severity,\n code: string,\n message: string,\n location: DiagnosticLocation,\n ): void {\n const item: Diagnostic = { code, severity, message };\n if (location.file !== undefined) item.file = location.file;\n if (location.route !== undefined) item.route = location.route;\n this.items.push(item);\n }\n}\n","import { createHash } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { registerHooks } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\n/**\n * Imports an application module by absolute path.\n *\n * Relies on Node's native TypeScript type stripping (unflagged since 22.18), so handler\n * files must use erasable syntax only: no enums, namespaces, or parameter properties.\n *\n * With reloading enabled (see `enableModuleReloading`) the URL carries a version query, so a\n * changed file evaluates again on the next import instead of coming back from the ESM cache.\n */\nexport async function loadModule(file: string): Promise<Record<string, unknown>> {\n const url = pathToFileURL(file).href;\n return (await import(reloading === null ? url : versioned(url))) as Record<string, unknown>;\n}\n\ninterface Reloading {\n /** Project root; only files under it (outside `node_modules`) are versioned. */\n root: string;\n /** Bumped by `invalidateModuleGraph` so every project module evaluates again. */\n generation: number;\n}\n\nlet reloading: Reloading | null = null;\n\n/**\n * Turns on cache busting for project files. Used by `nectar dev` only.\n *\n * Every import of a file under `root` gets `?nectar=<content hash>-<generation>` appended, the\n * direct ones here and the transitive ones through a resolve hook. A handler whose content\n * changed therefore gets a new URL and a fresh evaluation; its unchanged imports keep their\n * URL and are shared. Old instances stay in the ESM cache until the process exits.\n */\nexport function enableModuleReloading(root: string): void {\n if (reloading !== null) return;\n reloading = { root: path.resolve(root), generation: 0 };\n registerHooks({\n resolve(specifier, context, next) {\n const result = next(specifier, context);\n return { ...result, url: versioned(result.url) };\n },\n });\n}\n\n/**\n * Makes every project module evaluate again on its next import. For changes to files the\n * compiler does not track (helpers a handler imports), since nothing knows who imports them.\n */\nexport function invalidateModuleGraph(): void {\n if (reloading !== null) reloading.generation += 1;\n}\n\nfunction versioned(url: string): string {\n if (reloading === null || !url.startsWith(\"file:\") || url.includes(\"?\") || url.includes(\"#\")) {\n return url;\n }\n const file = fileURLToPath(url);\n const inside = !path.relative(reloading.root, file).startsWith(\"..\");\n if (!inside || file.split(path.sep).includes(\"node_modules\")) return url;\n let hash: string;\n try {\n hash = createHash(\"sha1\").update(readFileSync(file)).digest(\"base64url\").slice(0, 10);\n } catch {\n return url;\n }\n return `${url}?nectar=${hash}-${reloading.generation}`;\n}\n","export type Segment =\n | { type: \"static\"; name: string }\n | { type: \"dynamic\"; name: string }\n | { type: \"catchAll\"; name: string }\n | { type: \"group\"; name: string };\n\nexport type SegmentParseResult = { ok: true; segment: Segment } | { ok: false; reason: string };\n\nconst STATIC_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;\nconst PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Parses one directory name into a route segment.\n *\n * `name` static\n * `[name]` dynamic\n * `[...name]` catch-all\n * `(name)` group, organizational only\n */\nexport function parseSegment(dirName: string): SegmentParseResult {\n if (dirName.startsWith(\"[\") || dirName.endsWith(\"]\")) {\n if (!dirName.startsWith(\"[\") || !dirName.endsWith(\"]\")) {\n return fail(`\"${dirName}\" has an unmatched bracket. Parameters look like [name].`);\n }\n const inner = dirName.slice(1, -1);\n const isCatchAll = inner.startsWith(\"...\");\n const name = isCatchAll ? inner.slice(3) : inner;\n if (!PARAM_NAME.test(name)) {\n return fail(\n `\"${dirName}\" has an invalid parameter name. Parameters become keys of ctx.params, so use letters, digits, and underscores, and don't start with a digit.`,\n );\n }\n return ok({ type: isCatchAll ? \"catchAll\" : \"dynamic\", name });\n }\n\n if (dirName.startsWith(\"(\") || dirName.endsWith(\")\")) {\n if (!dirName.startsWith(\"(\") || !dirName.endsWith(\")\")) {\n return fail(`\"${dirName}\" has an unmatched parenthesis. Route groups look like (name).`);\n }\n const name = dirName.slice(1, -1);\n if (!STATIC_NAME.test(name)) {\n return fail(\n `\"${dirName}\" isn't a valid group name. Use letters, digits, hyphens, and underscores.`,\n );\n }\n return ok({ type: \"group\", name });\n }\n\n if (!STATIC_NAME.test(dirName)) {\n return fail(\n `\"${dirName}\" can't be part of a route path. Use letters, digits, hyphens, and underscores, and start with a letter or digit.`,\n );\n }\n return ok({ type: \"static\", name: dirName });\n}\n\n/** Renders a segment back into its directory form. Groups render as their directory name. */\nexport function formatSegment(segment: Segment): string {\n switch (segment.type) {\n case \"static\":\n return segment.name;\n case \"dynamic\":\n return `[${segment.name}]`;\n case \"catchAll\":\n return `[...${segment.name}]`;\n case \"group\":\n return `(${segment.name})`;\n }\n}\n\nfunction ok(segment: Segment): SegmentParseResult {\n return { ok: true, segment };\n}\n\nfunction fail(reason: string): SegmentParseResult {\n return { ok: false, reason };\n}\n","import { typeOf } from \"../compiler/diagnostics.js\";\n\n/**\n * A Standard Schema (https://standardschema.dev) validator, which zod, valibot, and arktype\n * all produce. Only the result's `issues` are looked at: a schema that transforms the value\n * does not change what the handler receives.\n */\nexport interface StandardSchemaLike<V = unknown> {\n \"~standard\": {\n validate(\n value: V,\n ):\n | { issues?: ReadonlyArray<unknown> | undefined }\n | Promise<{ issues?: ReadonlyArray<unknown> | undefined }>;\n };\n}\n\n/**\n * Checks one custom ID parameter. A function passes by returning anything but `false` and\n * fails by returning `false` or throwing. A schema fails by reporting issues.\n */\nexport type ParamValidator<V = string | string[]> = ((value: V) => unknown) | StandardSchemaLike<V>;\n\nexport type ParamValidators = Record<string, ParamValidator>;\n\n/**\n * Reads the validators `defineComponent` attached to a handler and checks them against the\n * route's parameters. Throws with a developer-facing message when the shape is wrong; the\n * compiler reports it as a diagnostic and the runtime as a load error.\n */\nexport function paramValidatorsOf(\n handler: unknown,\n route: { params: readonly string[] },\n): ParamValidators {\n const declared = (handler as { params?: unknown }).params;\n if (declared === undefined) return {};\n if (typeof declared !== \"object\" || declared === null || Array.isArray(declared)) {\n throw new Error(`params is ${typeOf(declared)}, not an object of validators.`);\n }\n const validators: ParamValidators = {};\n for (const [name, validator] of Object.entries(declared)) {\n if (!route.params.includes(name)) {\n throw new Error(\n `params validates \"${name}\", which is not a parameter of this route. ${\n route.params.length === 0 ? \"It has none.\" : `It has: ${route.params.join(\", \")}.`\n }`,\n );\n }\n if (!isValidator(validator)) {\n throw new Error(\n `params.${name} is ${typeOf(validator)}. A validator is a function or a Standard Schema.`,\n );\n }\n validators[name] = validator;\n }\n return validators;\n}\n\nfunction isValidator(value: unknown): value is ParamValidator {\n if (typeof value === \"function\") return true;\n if (typeof value !== \"object\" || value === null) return false;\n const standard = (value as Record<string, unknown>)[\"~standard\"];\n return (\n typeof standard === \"object\" &&\n standard !== null &&\n typeof (standard as Record<string, unknown>).validate === \"function\"\n );\n}\n\n/**\n * Runs every validator against the decoded parameters. Resolves to the first parameter that\n * failed, or `null` when all passed. A validator that throws counts as a failure; the\n * caller decides what to log, so the value never leaves this function.\n */\nexport async function findInvalidParam(\n validators: ParamValidators,\n params: Record<string, string | string[]>,\n): Promise<string | null> {\n for (const [name, validator] of Object.entries(validators)) {\n const value = params[name];\n if (value === undefined) return name;\n try {\n if (typeof validator === \"function\") {\n if ((await validator(value)) === false) return name;\n continue;\n }\n const result = await validator[\"~standard\"].validate(value);\n if (result.issues !== undefined && result.issues.length > 0) return name;\n } catch {\n return name;\n }\n }\n return null;\n}\n","import path from \"node:path\";\nimport { Diagnostics, typeOf } from \"../compiler/diagnostics.js\";\nimport { loadModule } from \"../compiler/load.js\";\nimport type { Route, RouteTable } from \"../compiler/routes.js\";\nimport { formatSegment } from \"../compiler/segments.js\";\nimport { BASE_OVERHEAD, encodeCustomId, MAX_CUSTOM_ID_LENGTH } from \"./customId.js\";\nimport { paramValidatorsOf } from \"./params.js\";\n\nexport type ComponentKind = \"button\" | \"select\" | \"modal\";\n\nexport type SelectKind = \"string\" | \"user\" | \"role\" | \"channel\" | \"mentionable\";\n\nconst SELECT_KINDS: ReadonlySet<string> = new Set([\n \"string\",\n \"user\",\n \"role\",\n \"channel\",\n \"mentionable\",\n]);\n\nexport interface ComponentRoute extends Route {\n category: \"component\";\n kind: ComponentKind;\n /** The `kind` export of a `select.ts`. `null` for buttons and modals. */\n selectKind: SelectKind | null;\n /** Name of the trailing catch-all parameter, if the route has one. */\n catchAll: string | null;\n /** Characters of the encoded custom ID taken by the prefix, short ID, and separators. */\n overhead: number;\n}\n\nexport interface CompiledComponents {\n routes: ComponentRoute[];\n diagnostics: Diagnostics;\n}\n\n/** Values for one route's parameters. A catch-all parameter takes an array. */\nexport type ComponentParams = Record<string, string | readonly string[]>;\n\n/** Validates the component routes of a route table and resolves their select kinds. */\nexport async function compileComponents(table: RouteTable): Promise<CompiledComponents> {\n const diagnostics = new Diagnostics();\n const candidates = table.routes.filter((r) => r.category === \"component\");\n\n // Each route reports into its own list, so diagnostics come out in route order rather than\n // in whatever order the imports finish.\n const results = await Promise.all(\n candidates.map(async (route) => {\n const own = new Diagnostics();\n return { route: await compileRoute(route, own), diagnostics: own };\n }),\n );\n const routes: ComponentRoute[] = [];\n for (const result of results) {\n diagnostics.items.push(...result.diagnostics.items);\n if (result.route !== null) routes.push(result.route);\n }\n\n detectShortIdCollisions(routes, diagnostics);\n detectDuplicatePatterns(routes, diagnostics);\n\n return { routes, diagnostics };\n}\n\n/** What the encoder needs from a route. Compiled, manifest, and registered routes all satisfy it. */\nexport interface EncodableRoute {\n id: string;\n shortId: string;\n params: string[];\n catchAll: string | null;\n}\n\n/**\n * Encodes a custom ID for a compiled route. Throws when a parameter is missing, a value is not\n * a string, or the result exceeds Discord's limit.\n */\nexport function customIdFor(route: EncodableRoute, params: ComponentParams = {}): string {\n const values: string[] = [];\n for (const name of route.params) {\n const value = params[name];\n if (name === route.catchAll) {\n if (value === undefined) continue;\n if (typeof value === \"string\") {\n values.push(value);\n continue;\n }\n values.push(...value);\n continue;\n }\n if (typeof value !== \"string\") {\n throw new TypeError(\n `Route ${route.id} needs a string for parameter \"${name}\", got ${describe(value)}.`,\n );\n }\n values.push(value);\n }\n for (const name of Object.keys(params)) {\n if (!route.params.includes(name)) {\n throw new TypeError(\n `Route ${route.id} has no parameter \"${name}\". ${route.params.length === 0 ? \"It takes none.\" : `It takes: ${route.params.join(\", \")}.`}`,\n );\n }\n }\n return encodeCustomId(route.shortId, values, route.id);\n}\n\nasync function compileRoute(\n route: Route,\n diagnostics: Diagnostics,\n): Promise<ComponentRoute | null> {\n const kind = route.kind as ComponentKind;\n const last = route.segments.at(-1);\n const catchAll = last?.type === \"catchAll\" ? last.name : null;\n const overhead = BASE_OVERHEAD + route.params.length;\n\n if (catchAll !== null) {\n diagnostics.warn(\n \"catch-all-route\",\n `${formatSegment(last as NonNullable<typeof last>)} takes any number of values. They all count toward Discord's ${MAX_CUSTOM_ID_LENGTH} character limit on custom IDs, and customId() throws when an ID goes over.`,\n { file: route.file, route: route.id },\n );\n }\n\n let module: Record<string, unknown>;\n try {\n module = await loadModule(route.file);\n } catch (error) {\n diagnostics.error(\n \"module-load-failed\",\n `The compiler imports every route file to read its exports, and this one threw: ${error instanceof Error ? error.message : String(error)}`,\n { file: route.file, route: route.id },\n );\n return null;\n }\n\n if (!checkHandler(module, route, diagnostics)) return null;\n try {\n paramValidatorsOf(module.default, route);\n } catch (error) {\n diagnostics.error(\n \"invalid-param-validator\",\n `${error instanceof Error ? error.message : String(error)} Validators go in defineComponent's third argument, like { params: { id: (value) => ... } }.`,\n { file: route.file, route: route.id },\n );\n return null;\n }\n\n let selectKind: SelectKind | null = null;\n if (kind === \"select\") {\n selectKind = validateSelectKind(module, route, diagnostics);\n if (selectKind === null) return null;\n }\n\n return { ...route, category: \"component\", kind, selectKind, catchAll, overhead };\n}\n\n/**\n * The default export is the handler Nectar calls, and one made with `defineComponent(path, ...)`\n * or the like must name the route its file sits in.\n */\nexport function checkHandler(\n module: Record<string, unknown>,\n route: Route,\n diagnostics: Diagnostics,\n expected = route.path,\n): boolean {\n const handler = module.default;\n if (typeof handler !== \"function\") {\n const define =\n route.kind === \"command\"\n ? \"defineCommand\"\n : route.kind === \"event\"\n ? \"defineEvent\"\n : \"defineComponent\";\n diagnostics.error(\n \"missing-handler\",\n `This ${path.basename(route.file)} ${handler === undefined ? \"has no default export\" : `exports ${typeOf(handler)} as its default`}. Nectar calls the default export when the route runs, so export the handler, like export default ${define}(\"${expected}\", handler).`,\n { file: route.file, route: route.id },\n );\n return false;\n }\n const declared = (handler as { route?: unknown }).route;\n if (declared === undefined || declared === expected) return true;\n diagnostics.error(\n \"route-mismatch\",\n `This file's route is \"${expected}\", but its handler says \"${String(declared)}\". The string types the handler, so it has to match where the file is. Change it to \"${expected}\", or move the file.`,\n { file: route.file, route: route.id },\n );\n return false;\n}\n\nfunction validateSelectKind(\n module: Record<string, unknown>,\n route: Route,\n diagnostics: Diagnostics,\n): SelectKind | null {\n const kind = module.kind;\n if (kind === undefined) {\n diagnostics.error(\n \"missing-select-kind\",\n 'This select.ts doesn\\'t export kind, which says what the select menu picks from: \"string\", \"user\", \"role\", \"channel\", or \"mentionable\". Add one, like export const kind = \"string\".',\n { file: route.file, route: route.id },\n );\n return null;\n }\n if (typeof kind !== \"string\" || !SELECT_KINDS.has(kind)) {\n diagnostics.error(\n \"invalid-select-kind\",\n `kind is ${describe(kind)}. Use \"string\", \"user\", \"role\", \"channel\", or \"mentionable\".`,\n { file: route.file, route: route.id },\n );\n return null;\n }\n return kind as SelectKind;\n}\n\nfunction detectShortIdCollisions(routes: ComponentRoute[], diagnostics: Diagnostics): void {\n const seen = new Map<string, ComponentRoute>();\n for (const route of routes) {\n const existing = seen.get(route.shortId);\n if (existing === undefined || existing.id === route.id) {\n seen.set(route.shortId, route);\n continue;\n }\n diagnostics.error(\n \"short-id-collision\",\n `${route.id} and ${existing.id} hash to the same short ID, \"${route.shortId}\", so Nectar can't tell their custom IDs apart. Rename a directory in one of them.`,\n { file: route.file, route: route.id },\n );\n }\n}\n\n/**\n * Two routes of the same kind whose paths differ only in parameter names, like\n * `tickets/[id]/close` and `tickets/[ticketId]/close`. Their hashes differ, but they take the\n * same values in the same places, so they are one route split in two.\n */\nfunction detectDuplicatePatterns(routes: ComponentRoute[], diagnostics: Diagnostics): void {\n const seen = new Map<string, ComponentRoute>();\n for (const route of routes) {\n const shape = route.segments\n .filter((s) => s.type !== \"group\")\n .map((s) => (s.type === \"static\" ? s.name : s.type === \"dynamic\" ? \"[]\" : \"[...]\"))\n .join(\"/\");\n const key = `${route.kind}#${shape}`;\n const existing = seen.get(key);\n if (existing === undefined) {\n seen.set(key, route);\n continue;\n }\n if (existing.id === route.id) continue;\n diagnostics.error(\n \"duplicate-component-pattern\",\n `${route.id} is the same path as ${existing.id} in ${relative(existing.file)}, with a different parameter name. Parameter names don't make routes distinct. Merge the two and keep one name.`,\n { file: route.file, route: route.id },\n );\n }\n}\n\nfunction describe(value: unknown): string {\n return typeof value === \"string\" ? JSON.stringify(value) : typeof value;\n}\n\nfunction relative(file: string): string {\n return path.relative(process.cwd(), file).split(path.sep).join(\"/\");\n}\n","import { type ComponentParams, customIdFor, type EncodableRoute } from \"./compile.js\";\n\nexport interface RegisteredComponentRoute extends EncodableRoute {\n path: string;\n}\n\n/**\n * Component routes the running app knows about, keyed by path. The runtime fills this from\n * the manifest before any handler runs, so `customId()` never needs the manifest itself.\n */\nconst routes = new Map<string, RegisteredComponentRoute>();\n\nexport function registerComponentRoutes(list: Iterable<RegisteredComponentRoute>): void {\n routes.clear();\n for (const route of list) routes.set(route.path, route);\n}\n\nexport function encodeComponentRoute(path: string, params: ComponentParams): string {\n const route = routes.get(path);\n if (route === undefined) {\n throw new Error(\n routes.size === 0\n ? `customId(\"${path}\") was called before the runtime registered any routes. Call it from a handler, or from code that runs after start().`\n : `No component route \"${path}\". Check the directory name under components/.`,\n );\n }\n return customIdFor(route, params);\n}\n","import { mkdirSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RouteGraph } from \"../compiler/graph.js\";\nimport type { Route } from \"../compiler/routes.js\";\nimport { version } from \"../version.js\";\nimport { MANIFEST_VERSION, type Manifest, type ManifestRoute } from \"./schema.js\";\n\nexport const MANIFEST_FILE = \"manifest.json\";\n\n/** Serializes a route graph. `outDir` is where the manifest will live; paths are made relative to it. */\nexport function toManifest(graph: RouteGraph, outDir: string): Manifest {\n const rel = (file: string) => posix(path.relative(graph.appDir, file));\n const base = (route: Route) => {\n const chains = graph.chains.get(route.file) ?? { middleware: [], errors: [] };\n return {\n id: route.id,\n category: route.category,\n path: route.path,\n file: rel(route.file),\n middleware: chains.middleware.map(rel),\n errors: chains.errors.map(rel),\n plugins: graph.plugins.get(route.file) ?? [],\n };\n };\n\n const routes: ManifestRoute[] = [];\n for (const command of graph.commands) {\n for (const route of Object.values(command.handlers))\n routes.push({ ...base(route), kind: \"command\" });\n }\n for (const entry of graph.autocomplete) {\n routes.push({ ...base(entry.route), kind: \"autocomplete\", options: entry.options });\n }\n for (const route of graph.components) {\n routes.push({\n ...base(route),\n kind: route.kind,\n shortId: route.shortId,\n params: route.params,\n catchAll: route.catchAll,\n selectKind: route.selectKind,\n overhead: route.overhead,\n });\n }\n for (const event of graph.events) {\n for (const handler of event.handlers) {\n routes.push({\n ...base(handler.route),\n kind: \"event\",\n event: event.name,\n once: handler.once,\n order: handler.order,\n });\n }\n }\n routes.sort((a, b) => a.kind.localeCompare(b.kind) || a.id.localeCompare(b.id));\n\n return {\n version: MANIFEST_VERSION,\n nectar: version,\n appDir: posix(path.relative(path.resolve(outDir), graph.appDir)),\n routes,\n commands: graph.commands.map((c) => ({\n name: c.name,\n type: c.type,\n payload: c.payload,\n handlers: Object.fromEntries(Object.entries(c.handlers).map(([k, r]) => [k, r.id])),\n })),\n events: graph.events.map((e) => ({\n name: e.name,\n mode: e.mode,\n handlers: e.handlers.map((h) => h.route.id),\n })),\n };\n}\n\n/** Writes `manifest.json` into `outDir` with sorted keys, so identical graphs give identical bytes. */\nexport function writeManifest(manifest: Manifest, outDir: string): string {\n mkdirSync(outDir, { recursive: true });\n const file = path.join(outDir, MANIFEST_FILE);\n writeFileSync(file, `${stableStringify(manifest)}\\n`);\n return file;\n}\n\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(value, (_key, v: unknown) => (isPlainObject(v) ? sortKeys(v) : v), 2);\n}\n\nfunction sortKeys(object: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(object).sort()) out[key] = object[key];\n return out;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction posix(file: string): string {\n return file.split(path.sep).join(\"/\");\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RouteGraph } from \"../compiler/graph.js\";\nimport { toManifest } from \"../manifest/emit.js\";\nimport type { NectarPlugin, PluginChange, PluginGraph } from \"./index.js\";\n\n/** A frozen copy of the graph in manifest shape, with absolute file paths. */\nexport function pluginGraph(graph: RouteGraph): PluginGraph {\n const manifest = toManifest(graph, graph.appDir);\n const absolute = (file: string) => path.join(graph.appDir, ...file.split(\"/\"));\n // Cloned because the manifest shares arrays and payloads with the graph itself.\n return deepFreeze(\n structuredClone({\n appDir: graph.appDir,\n routes: manifest.routes.map((route) => ({\n ...route,\n file: absolute(route.file),\n middleware: route.middleware.map(absolute),\n errors: route.errors.map(absolute),\n })),\n commands: manifest.commands,\n events: manifest.events,\n }),\n );\n}\n\n/**\n * Runs every plugin's `transform` in config order and applies the returned changes to the\n * graph. Problems become diagnostics; a plugin never mutates the graph directly.\n */\nexport async function applyPlugins(\n graph: RouteGraph,\n plugins: readonly NectarPlugin[],\n): Promise<void> {\n for (const plugin of plugins) {\n if (plugin.transform === undefined) continue;\n let changes: PluginChange[];\n try {\n changes = (await plugin.transform(pluginGraph(graph))) ?? [];\n } catch (error) {\n graph.diagnostics.error(\n \"plugin-failed\",\n `Plugin \"${plugin.name}\" threw while transforming routes: ${describe(error)}`,\n );\n continue;\n }\n if (!Array.isArray(changes)) {\n graph.diagnostics.error(\n \"plugin-invalid-change\",\n `Plugin \"${plugin.name}\" returned ${typeof changes} from transform. Return an array of changes, or nothing.`,\n );\n continue;\n }\n for (const change of changes) apply(graph, plugin.name, change);\n }\n}\n\nfunction apply(graph: RouteGraph, plugin: string, change: PluginChange): void {\n const type: unknown = isRecord(change) ? change.type : undefined;\n if (type !== \"middleware\" && type !== \"diagnostic\") {\n graph.diagnostics.error(\n \"plugin-invalid-change\",\n `Plugin \"${plugin}\" returned a change with type ${JSON.stringify(type)}. A change's type is \"middleware\" or \"diagnostic\".`,\n );\n return;\n }\n if (change.type === \"diagnostic\") {\n const { severity, code, message, file, route } = change;\n graph.diagnostics.items.push({\n code,\n severity: severity === \"error\" ? \"error\" : \"warning\",\n message,\n ...(file === undefined ? {} : { file }),\n ...(route === undefined ? {} : { route }),\n });\n return;\n }\n\n const routes = graph.routes.filter(\n (r) => r.id === change.route && (change.kind === undefined || r.kind === change.kind),\n );\n const target = change.kind === undefined ? change.route : `${change.route} (${change.kind})`;\n if (routes.length === 0) {\n graph.diagnostics.error(\n \"plugin-unknown-route\",\n `Plugin \"${plugin}\" adds middleware to route \"${target}\", which does not exist. Route IDs look like \"command:moderation/ban\".`,\n );\n return;\n }\n if (routes.some((r) => r.category === \"event\")) {\n graph.diagnostics.error(\n \"plugin-invalid-change\",\n `Plugin \"${plugin}\" adds middleware to route \"${target}\", but event handlers don't run middleware.`,\n { route: change.route },\n );\n return;\n }\n if (\n typeof change.file !== \"string\" ||\n !path.isAbsolute(change.file) ||\n !existsSync(change.file)\n ) {\n graph.diagnostics.error(\n \"plugin-missing-file\",\n `Plugin \"${plugin}\" adds middleware from ${JSON.stringify(change.file)}, which is not an absolute path to an existing file.`,\n { route: change.route },\n );\n return;\n }\n const file = path.normalize(change.file);\n for (const route of routes) {\n const chains = graph.chains.get(route.file);\n if (chains === undefined || chains.middleware.includes(file)) continue;\n if (change.position === \"inner\") chains.middleware.push(file);\n else chains.middleware.unshift(file);\n const touched = graph.plugins.get(route.file) ?? [];\n if (!touched.includes(plugin)) graph.plugins.set(route.file, [...touched, plugin]);\n }\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (typeof value === \"object\" && value !== null && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const inner of Object.values(value)) deepFreeze(inner);\n }\n return value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import type { Client } from \"discord.js\";\nimport type { Project } from \"../cli/project.js\";\nimport type { Severity } from \"../compiler/diagnostics.js\";\nimport type { RouteKind } from \"../compiler/routes.js\";\nimport type { NectarServices } from \"../index.js\";\nimport type {\n Manifest,\n ManifestCommand,\n ManifestEvent,\n ManifestRoute,\n} from \"../manifest/schema.js\";\nimport type { SignalEmitter } from \"../runtime/signals.js\";\nimport type { Env, Logger } from \"../runtime/types.js\";\n\n/**\n * A plugin takes part in compilation and the runtime lifecycle. A library that only exports\n * functions for handlers to call does not need to be one.\n */\nexport interface NectarPlugin {\n /** Unique among the configured plugins. Named in diagnostics and in the manifest. */\n name: string;\n version?: string;\n /**\n * Runs after the route graph is validated and before the manifest is written. The graph is\n * frozen; return changes and the compiler applies and checks them. Plugins run in config\n * order, each seeing the changes of the ones before it.\n */\n transform?(graph: PluginGraph): Maybe<PluginChange[]> | Promise<Maybe<PluginChange[]>>;\n /** Declarations appended to `.nectar/types.d.ts`. */\n types?(graph: PluginGraph): Maybe<string>;\n /** Extra `nectar <name>` commands. */\n commands?: PluginCommand[];\n /**\n * Runs when the runtime starts, before any handler is imported and before login. A sharded\n * bot runs it in every process. Returned services land on `ctx.services` for every handler\n * and middleware.\n */\n start?(app: PluginApp): Maybe<Partial<NectarServices>> | Promise<Maybe<Partial<NectarServices>>>;\n /** Runs on shutdown, after in-flight interactions drain and before the client is destroyed. */\n stop?(app: PluginApp): void | Promise<void>;\n /**\n * Runs once per application, in the process that runs shard 0, after every `start`. For work\n * that must not repeat per shard process: a scheduled job, a web server, posting stats.\n */\n startGlobal?(app: PluginApp): void | Promise<void>;\n /** Runs on shutdown in the process that ran `startGlobal`, before any `stop`. */\n stopGlobal?(app: PluginApp): void | Promise<void>;\n}\n\n/** A hook may return nothing, so a body without `return` type-checks. */\n// biome-ignore lint/suspicious/noConfusingVoidType: that is the point\ntype Maybe<T> = T | undefined | void;\n\nexport type PluginChange =\n | {\n type: \"middleware\";\n /** Route ID, `<category>:<path>`. */\n route: string;\n /**\n * Only the route of this kind. A command and its autocomplete share an ID; without\n * `kind`, both get the middleware, as they would from a `middleware.ts`.\n */\n kind?: RouteKind;\n /** Absolute path of a module whose default export is a middleware. */\n file: string;\n /** `outer` (default) runs before the app's own middleware, `inner` right before the handler. */\n position?: \"outer\" | \"inner\";\n }\n | {\n type: \"diagnostic\";\n severity: Severity;\n code: string;\n message: string;\n file?: string;\n route?: string;\n };\n\ntype DeepReadonly<T> = T extends (infer U)[]\n ? readonly DeepReadonly<U>[]\n : T extends object\n ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T;\n\n/** The compiled app as a plugin sees it: the manifest shape with absolute file paths, frozen. */\nexport interface PluginGraph {\n readonly appDir: string;\n readonly routes: DeepReadonly<ManifestRoute[]>;\n readonly commands: DeepReadonly<ManifestCommand[]>;\n readonly events: DeepReadonly<ManifestEvent[]>;\n}\n\nexport interface PluginApp {\n readonly client: Client;\n readonly env: Env;\n readonly logger: Logger;\n readonly signals: SignalEmitter;\n readonly manifest: Manifest;\n}\n\nexport interface PluginCommand {\n name: string;\n description: string;\n options?: Record<string, { type: \"boolean\" | \"string\"; description: string }>;\n /** Returns the exit code. */\n run(ctx: PluginCommandContext): number | Promise<number>;\n}\n\nexport interface PluginCommandContext {\n project: Project;\n flags: Record<string, string | boolean | undefined>;\n out(line: string): void;\n err(line: string): void;\n}\n\nexport function definePlugin(plugin: NectarPlugin): NectarPlugin {\n return plugin;\n}\n\n/** A plugin misbehaved: threw from a hook, or provided something that clashes. */\nexport class PluginError extends Error {\n constructor(\n readonly plugin: string,\n readonly detail: string,\n ) {\n super(`Plugin \"${plugin}\": ${detail}`);\n this.name = \"PluginError\";\n }\n}\n\nexport { applyPlugins, pluginGraph } from \"./transform.js\";\n"],"mappings":";;;;;;;AAGA,MAAa,EAAE,YAAY,cAAc,YAAY,GAAG,CAAC,CAAC,iBAAiB;;;;ACF3E,MAAa,uBAAuB;AAEpC,MAAM,SAAS;AAMf,IAAa,uBAAb,cAA0C,MAAM;CAEnC;CACA;CAFX,YACE,UACA,SACA;EACA,MACE,iBAAiB,QAAQ,MAAM,SAAS,OAAO,wFACjD;EALS,KAAA,WAAA;EACA,KAAA,UAAA;EAKT,KAAK,OAAO;CACd;AACF;;;;;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;CAC5D;CACA,OAAO;AACT;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,SAAS,OAAwB;CACxC,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;ACpBA,SAAgB,aAAa,QAAoC;CAC/D,OAAO;AACT;;AAGA,IAAa,cAAb,cAAiC,MAAM;CAE1B;CACA;CAFX,YACE,QACA,QACA;EACA,MAAM,WAAW,OAAO,KAAK,QAAQ;EAH5B,KAAA,SAAA;EACA,KAAA,SAAA;EAGT,KAAK,OAAO;CACd;AACF"}
@@ -1,4 +1,4 @@
1
- import { o as stableStringify } from "./plugins-CGvM19v9.js";
1
+ import { o as stableStringify } from "./plugins-BCYwtuo-.js";
2
2
  import path from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
@@ -37,6 +37,30 @@ const LEVELS = /* @__PURE__ */ new Set([
37
37
  "warn",
38
38
  "error"
39
39
  ]);
40
+ /** Every option, so a misspelled or removed one fails instead of being ignored. */
41
+ const OPTIONS = {
42
+ token: true,
43
+ applicationId: true,
44
+ intents: true,
45
+ partials: true,
46
+ client: true,
47
+ eager: true,
48
+ env: true,
49
+ logger: true,
50
+ observe: true,
51
+ plugins: true,
52
+ appDir: true,
53
+ outDir: true,
54
+ dev: true,
55
+ commands: true,
56
+ environments: true
57
+ };
58
+ const DEV_OPTIONS = { guilds: true };
59
+ const COMMANDS_OPTIONS = { target: true };
60
+ const LOGGER_OPTIONS = {
61
+ level: true,
62
+ sink: true
63
+ };
40
64
  /** Checks a loaded config's shape. Discord validates intent and partial values itself at login. */
41
65
  function validateConfig(value, file) {
42
66
  const fail = (detail) => {
@@ -44,6 +68,12 @@ function validateConfig(value, file) {
44
68
  };
45
69
  if (!isRecord(value)) fail("the default export must be an object. Use defineConfig({ ... }).");
46
70
  const config = value;
71
+ checkKeys(config, OPTIONS, "", fail);
72
+ for (const [key, options] of [
73
+ ["dev", DEV_OPTIONS],
74
+ ["commands", COMMANDS_OPTIONS],
75
+ ["logger", LOGGER_OPTIONS]
76
+ ]) if (isRecord(config[key])) checkKeys(config[key], options, `${key}.`, fail);
47
77
  for (const key of ["token", "applicationId"]) if (config[key] !== void 0 && typeof config[key] !== "string") fail(`\`${key}\` must be a string, usually read from process.env.`);
48
78
  if (config.intents === void 0) fail("`intents` is required. Use [] for none.");
49
79
  if (!isBitfield(config.intents)) fail("`intents` must be an array of intent names or bits, a single bit, or a bigint.");
@@ -134,6 +164,14 @@ function validatePlugins(value, fail) {
134
164
  }
135
165
  });
136
166
  }
167
+ /** Fails on the first key `options` doesn't have, naming a likely intended one when there is one. */
168
+ function checkKeys(value, options, prefix, fail) {
169
+ for (const key of Object.keys(value)) {
170
+ if (Object.hasOwn(options, key)) continue;
171
+ const near = Object.keys(options).find((option) => option.toLowerCase() === key.toLowerCase() || option === `${key}s` || `${option}s` === key);
172
+ fail(`\`${prefix}${key}\` isn't a config option.${near === void 0 ? " The options are listed at https://nectar-js.github.io/nectar/reference/config." : ` Did you mean \`${prefix}${near}\`?`}`);
173
+ }
174
+ }
137
175
  function isGuildList(value) {
138
176
  return Array.isArray(value) && value.every((g) => typeof g === "string" && /^\d+$/.test(g));
139
177
  }
@@ -248,7 +286,7 @@ function checkIntents(events, intents, configFile) {
248
286
  diagnostics.push({
249
287
  code: "missing-intent",
250
288
  severity: "warning",
251
- message: `"${event.name}" never fires without the ${names} intent. Add it to \`intents\` in ${configFile}.${privileged.length === 0 ? "" : ` ${privileged.map((i) => `"${i}"`).join(" and ")} is privileged: enable it under Bot in the Discord developer portal as well.`}`,
289
+ message: `"${event.name}" never fires without the ${names} intent. Add it to intents in ${configFile}.${privileged.length === 0 ? "" : ` ${privileged.map((i) => `"${i}"`).join(" and ")} is privileged, so also turn it on under Bot in the Discord Developer Portal.`}`,
252
290
  file: first.route.file,
253
291
  route: first.route.id
254
292
  });
@@ -368,8 +406,9 @@ function scopeKey(scope) {
368
406
  function scopeRoute(applicationId, scope) {
369
407
  return scope === "global" ? Routes.applicationCommands(applicationId) : Routes.applicationGuildCommands(applicationId, scope.guild);
370
408
  }
409
+ /** With full localization maps, which Discord leaves out unless asked. */
371
410
  async function fetchCommands(rest, applicationId, scope) {
372
- return await rest.get(scopeRoute(applicationId, scope));
411
+ return await rest.get(scopeRoute(applicationId, scope), { query: new URLSearchParams({ with_localizations: "true" }) });
373
412
  }
374
413
  /** Bulk overwrite: Discord replaces the scope's whole command set with `commands`. */
375
414
  async function putCommands(rest, applicationId, scope, commands) {
@@ -455,6 +494,16 @@ function problem(path, commands, message) {
455
494
  //#region src/registration/sync.ts
456
495
  const REGISTRATION_CACHE_FILE = "registration.json";
457
496
  const CACHE_VERSION = 1;
497
+ /**
498
+ * The command types an app declares. Other commands in a scope, like the Entry Point command
499
+ * Discord creates for Activities, go back unchanged in every overwrite: Discord rejects one
500
+ * that drops them, with error 50240.
501
+ */
502
+ const DECLARED_TYPES = /* @__PURE__ */ new Set([
503
+ ApplicationCommandType.ChatInput,
504
+ ApplicationCommandType.User,
505
+ ApplicationCommandType.Message
506
+ ]);
458
507
  /** Thrown instead of applying when the guard trips and `force` is not set. */
459
508
  var UnsafeSyncError = class extends Error {
460
509
  reasons;
@@ -477,6 +526,8 @@ async function syncCommands(options) {
477
526
  const targets = new Set(scopes.map(scopeKey));
478
527
  for (const key of Object.keys(cache?.scopes ?? {})) if (!targets.has(key)) unsafe.push(`${key} received commands last time but is no longer a target. Its commands stay registered on Discord until removed.`);
479
528
  const results = [];
529
+ /** Remote commands of other types, by scope key, to send back in the overwrite. */
530
+ const kept = /* @__PURE__ */ new Map();
480
531
  for (const scope of scopes) {
481
532
  const key = scopeKey(scope);
482
533
  if (cache !== null && cache.applicationId === applicationId && cache.scopes[key] === hash) {
@@ -488,8 +539,10 @@ async function syncCommands(options) {
488
539
  continue;
489
540
  }
490
541
  const remote = await fetchCommands(rest, applicationId, scope);
491
- const diff = diffCommands(commands, remote);
492
- if (commands.length === 0 && remote.length > 0) unsafe.push(`${key} has ${remote.length} command(s) registered and the app declares none.`);
542
+ const declared = remote.filter((c) => DECLARED_TYPES.has(c.type));
543
+ kept.set(key, remote.filter((c) => !DECLARED_TYPES.has(c.type)).map(resubmit));
544
+ const diff = diffCommands(commands, declared);
545
+ if (commands.length === 0 && declared.length > 0) unsafe.push(`${key} has ${declared.length} command(s) registered and the app declares none.`);
493
546
  results.push({
494
547
  scope,
495
548
  diff,
@@ -508,7 +561,8 @@ async function syncCommands(options) {
508
561
  };
509
562
  for (const result of results) {
510
563
  if (result.diff?.hasChanges) {
511
- await putCommands(rest, applicationId, result.scope, commands);
564
+ const body = [...commands, ...kept.get(scopeKey(result.scope)) ?? []];
565
+ await putCommands(rest, applicationId, result.scope, body);
512
566
  result.applied = true;
513
567
  }
514
568
  next.scopes[scopeKey(result.scope)] = hash;
@@ -519,6 +573,11 @@ async function syncCommands(options) {
519
573
  unsafe
520
574
  };
521
575
  }
576
+ /** A fetched command as an overwrite takes it, without the fields Discord fills in itself. */
577
+ function resubmit(command) {
578
+ const { id: _id, application_id: _application, guild_id: _guild, version: _version, name_localized: _name, description_localized: _description, ...body } = command;
579
+ return body;
580
+ }
522
581
  /** Order-insensitive, like the diff: reordering commands is not a change. */
523
582
  function hashCommands(commands) {
524
583
  const normalized = commands.map((c) => [commandKey(c), normalizeCommand(c)]).sort(([a], [b]) => a.localeCompare(b)).map(([, c]) => c);
@@ -542,4 +601,4 @@ function writeCache(dir, cache) {
542
601
  //#endregion
543
602
  export { checkIntents as a, configFor as c, scopeKey as i, defineConfig as l, syncCommands as n, requiredIntents as o, RegistrationError as r, ConfigError as s, UnsafeSyncError as t, validateConfig as u };
544
603
 
545
- //# sourceMappingURL=registration-CaE0QBT6.js.map
604
+ //# sourceMappingURL=registration-BN3P3MDg.js.map