@warlock.js/core 5.35.0 → 5.37.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.
Files changed (133) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/esm/cli/commands/migrate.command.mjs +10 -0
  3. package/esm/cli/commands/migrate.command.mjs.map +1 -1
  4. package/esm/cli/commands/release/release-command.action.mjs +245 -0
  5. package/esm/cli/commands/release/release-command.action.mjs.map +1 -0
  6. package/esm/cli/commands/release.command.mjs +66 -0
  7. package/esm/cli/commands/release.command.mjs.map +1 -0
  8. package/esm/cli/framework-cli-commands.mjs +2 -0
  9. package/esm/cli/framework-cli-commands.mjs.map +1 -1
  10. package/esm/database/migrate-action.mjs +24 -2
  11. package/esm/database/migrate-action.mjs.map +1 -1
  12. package/esm/dev-server/loader/load-hook.d.mts.map +1 -1
  13. package/esm/dev-server/loader/load-hook.mjs +6 -0
  14. package/esm/dev-server/loader/load-hook.mjs.map +1 -1
  15. package/esm/dev-server/module-loader.mjs +1 -1
  16. package/esm/dev-server/parse-imports.mjs +1 -1
  17. package/esm/dev-server/type-generator.mjs +1 -1
  18. package/esm/e2e/cdp.d.mts.map +1 -1
  19. package/esm/e2e/cdp.mjs +9 -2
  20. package/esm/e2e/cdp.mjs.map +1 -1
  21. package/esm/e2e/page.d.mts +9 -1
  22. package/esm/e2e/page.d.mts.map +1 -1
  23. package/esm/e2e/page.mjs +45 -7
  24. package/esm/e2e/page.mjs.map +1 -1
  25. package/esm/e2e/types.d.mts +18 -0
  26. package/esm/e2e/types.d.mts.map +1 -1
  27. package/esm/e2e/types.mjs.map +1 -1
  28. package/esm/errors/error-codes.d.mts +24 -0
  29. package/esm/errors/error-codes.d.mts.map +1 -1
  30. package/esm/errors/error-codes.mjs +24 -0
  31. package/esm/errors/error-codes.mjs.map +1 -1
  32. package/esm/generations/features/test.feature.mjs +7 -7
  33. package/esm/generations/features/test.feature.mjs.map +1 -1
  34. package/esm/generations/features/web.feature.mjs +3 -3
  35. package/esm/generations/features/web.feature.mjs.map +1 -1
  36. package/esm/index.d.mts +6 -3
  37. package/esm/index.mjs +4 -2
  38. package/esm/localization/index.mjs +3 -1
  39. package/esm/localization/translation-usage-graph.d.mts +49 -0
  40. package/esm/localization/translation-usage-graph.d.mts.map +1 -0
  41. package/esm/localization/translation-usage-graph.mjs +128 -0
  42. package/esm/localization/translation-usage-graph.mjs.map +1 -0
  43. package/esm/localization/translation-usage.d.mts +85 -0
  44. package/esm/localization/translation-usage.d.mts.map +1 -0
  45. package/esm/localization/translation-usage.mjs +307 -0
  46. package/esm/localization/translation-usage.mjs.map +1 -0
  47. package/esm/production/build-budgets.d.mts +18 -0
  48. package/esm/production/build-budgets.d.mts.map +1 -1
  49. package/esm/production/build-budgets.mjs.map +1 -1
  50. package/esm/production/route-registration-snapshot.mjs +12 -3
  51. package/esm/production/route-registration-snapshot.mjs.map +1 -1
  52. package/esm/release/activate.mjs +261 -0
  53. package/esm/release/activate.mjs.map +1 -0
  54. package/esm/release/candidate.mjs +107 -0
  55. package/esm/release/candidate.mjs.map +1 -0
  56. package/esm/release/cascade-migration-provider.mjs +32 -0
  57. package/esm/release/cascade-migration-provider.mjs.map +1 -0
  58. package/esm/release/config.mjs +60 -0
  59. package/esm/release/config.mjs.map +1 -0
  60. package/esm/release/gate.mjs +67 -0
  61. package/esm/release/gate.mjs.map +1 -0
  62. package/esm/release/migrations-proof.mjs +100 -0
  63. package/esm/release/migrations-proof.mjs.map +1 -0
  64. package/esm/release/prune.mjs +42 -0
  65. package/esm/release/prune.mjs.map +1 -0
  66. package/esm/release/report.mjs +25 -0
  67. package/esm/release/report.mjs.map +1 -0
  68. package/esm/release/runner.mjs +55 -0
  69. package/esm/release/runner.mjs.map +1 -0
  70. package/esm/release/semver.mjs +53 -0
  71. package/esm/release/semver.mjs.map +1 -0
  72. package/esm/release/stage.mjs +122 -0
  73. package/esm/release/stage.mjs.map +1 -0
  74. package/esm/release/store.mjs +131 -0
  75. package/esm/release/store.mjs.map +1 -0
  76. package/esm/release/types.d.mts +102 -0
  77. package/esm/release/types.d.mts.map +1 -0
  78. package/esm/release/verify.mjs +94 -0
  79. package/esm/release/verify.mjs.map +1 -0
  80. package/esm/router/index.d.mts +2 -2
  81. package/esm/router/index.mjs +2 -2
  82. package/esm/router/router.d.mts +4 -0
  83. package/esm/router/router.d.mts.map +1 -1
  84. package/esm/router/router.mjs +14 -3
  85. package/esm/router/router.mjs.map +1 -1
  86. package/esm/router/types.d.mts +45 -0
  87. package/esm/router/types.d.mts.map +1 -1
  88. package/esm/router/unguarded-route-diagnostics.d.mts +6 -0
  89. package/esm/router/unguarded-route-diagnostics.d.mts.map +1 -1
  90. package/esm/router/unguarded-route-diagnostics.mjs +10 -2
  91. package/esm/router/unguarded-route-diagnostics.mjs.map +1 -1
  92. package/esm/tooling/check/api-route-references.d.mts +16 -0
  93. package/esm/tooling/check/api-route-references.d.mts.map +1 -0
  94. package/esm/tooling/check/api-route-references.mjs +146 -0
  95. package/esm/tooling/check/api-route-references.mjs.map +1 -0
  96. package/esm/tooling/check/conventions-step.d.mts +6 -3
  97. package/esm/tooling/check/conventions-step.d.mts.map +1 -1
  98. package/esm/tooling/check/conventions-step.mjs +19 -10
  99. package/esm/tooling/check/conventions-step.mjs.map +1 -1
  100. package/esm/tooling/check/run-check.d.mts.map +1 -1
  101. package/esm/tooling/check/run-check.mjs +4 -2
  102. package/esm/tooling/check/run-check.mjs.map +1 -1
  103. package/esm/tooling/check/security-conventions.mjs +19 -1
  104. package/esm/tooling/check/security-conventions.mjs.map +1 -1
  105. package/esm/tooling/check/translation-conventions.mjs +32 -0
  106. package/esm/tooling/check/translation-conventions.mjs.map +1 -0
  107. package/esm/tooling/inspect/collect-files.mjs +1 -1
  108. package/esm/tooling/inspect/collect-routes.mjs +3 -2
  109. package/esm/tooling/inspect/collect-routes.mjs.map +1 -1
  110. package/esm/upgrade/codemods/index.mjs +2 -0
  111. package/esm/upgrade/codemods/index.mjs.map +1 -1
  112. package/esm/upgrade/codemods/vite-vitest.mjs +170 -0
  113. package/esm/upgrade/codemods/vite-vitest.mjs.map +1 -0
  114. package/esm/upgrade/notes.mjs +4 -0
  115. package/esm/upgrade/notes.mjs.map +1 -1
  116. package/esm/validation/init.mjs +11 -4
  117. package/esm/validation/init.mjs.map +1 -1
  118. package/esm/validation/translate-rule.mjs +63 -0
  119. package/esm/validation/translate-rule.mjs.map +1 -0
  120. package/esm/warlock-config/index.d.mts +3 -2
  121. package/esm/warlock-config/types.d.mts +8 -0
  122. package/esm/warlock-config/types.d.mts.map +1 -1
  123. package/llms-full.txt +221 -18
  124. package/llms.txt +1 -0
  125. package/package.json +13 -13
  126. package/skills/deploy-release/SKILL.md +76 -0
  127. package/skills/index.md +1 -1
  128. package/skills/register-route/SKILL.md +25 -0
  129. package/skills/test-service/SKILL.md +8 -8
  130. package/skills/upgrade-from-5-29/SKILL.md +91 -0
  131. package/skills/use-localization/SKILL.md +4 -0
  132. package/skills/warlock-check/SKILL.md +11 -8
  133. package/skills/warlock-conventions/SKILL.md +1 -1
@@ -0,0 +1,102 @@
1
+ //#region ../../packages/core/src/release/types.d.ts
2
+ /**
3
+ * One named command in the release gate. Checks run in order and the gate
4
+ * stops at the first one that fails.
5
+ */
6
+ export type ReleaseCheck = {
7
+ /** Name shown in the report and recorded in the manifest */
8
+ name: string;
9
+ /** Shell command, run inside the candidate's frozen source */
10
+ command: string;
11
+ /** Kill the check after this many milliseconds. @default 1_800_000 */
12
+ timeoutMs?: number;
13
+ };
14
+ /**
15
+ * Release settings, read from the `release` key of `warlock.config.ts`.
16
+ *
17
+ * Every field is optional; the defaults describe a plain Warlock app that
18
+ * builds into `dist`.
19
+ */
20
+ export type ReleaseConfig = {
21
+ /**
22
+ * Base directory for releases and the `current` / `previous` pointers,
23
+ * relative to the project root.
24
+ *
25
+ * @default ".warlock"
26
+ */
27
+ directory?: string;
28
+ /**
29
+ * Build output directory, relative to the candidate's source.
30
+ *
31
+ * @default "dist"
32
+ */
33
+ distDir?: string;
34
+ /**
35
+ * Extra files or directories (relative to the candidate's source) copied
36
+ * next to the build output when staging. `package.json` and the lockfile
37
+ * are always copied.
38
+ */
39
+ include?: string[];
40
+ /**
41
+ * Link the project's `node_modules` into the frozen source so gate checks
42
+ * and the build can run without a second install.
43
+ *
44
+ * @default true
45
+ */
46
+ linkNodeModules?: boolean;
47
+ /** The ordered gate checks. Replaces the defaults when set. */
48
+ gate?: {
49
+ checks?: ReleaseCheck[];
50
+ };
51
+ /** Migration proof settings */
52
+ migrations?: {
53
+ /**
54
+ * Named targets. `--target <name>` applies the target's `env` to this
55
+ * process before the database connects, so the proof runs against that
56
+ * database instead of the one the local environment points to.
57
+ */
58
+ targets?: Record<string, {
59
+ env?: Record<string, string>;
60
+ }>;
61
+ /**
62
+ * Migration names that must be the ones executed, in order. Defaults to
63
+ * the pending set computed before the run.
64
+ */
65
+ expected?: string[];
66
+ /** Tables or collections that must exist after the run. */
67
+ expectedTables?: string[];
68
+ };
69
+ /**
70
+ * Command that makes the running application pick up the new release.
71
+ * Warlock never restarts anything on its own: leave it unset and activation
72
+ * only switches the pointer.
73
+ *
74
+ * It runs through the shell with `WARLOCK_RELEASE_ID`,
75
+ * `WARLOCK_RELEASE_DIR` and `WARLOCK_RELEASE_CURRENT` in its environment.
76
+ */
77
+ restart?: {
78
+ command?: string;
79
+ timeoutMs?: number;
80
+ };
81
+ /** Post-activation health verification */
82
+ verify?: {
83
+ /** Health URL. Required by `release verify`. */
84
+ url?: string;
85
+ /** @default 200 */
86
+ expectedStatus?: number;
87
+ /** Attempts after the first one. @default 5 */
88
+ retries?: number;
89
+ /** Wait between attempts in milliseconds. @default 2000 */
90
+ intervalMs?: number;
91
+ /** Per-request timeout in milliseconds. @default 5000 */
92
+ timeoutMs?: number;
93
+ /** Dotted JSON path of the reported version. @default "version" */
94
+ versionPath?: string;
95
+ /** Dotted JSON path of the reported commit. @default "commit" */
96
+ commitPath?: string;
97
+ /** Which reported fields must match the active release. @default ["version", "commit"] */
98
+ match?: Array<"version" | "commit">;
99
+ };
100
+ };
101
+ //#endregion
102
+ //# sourceMappingURL=types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/release/types.ts"],"mappings":";;;;;YAIY;;EAEV;;EAEA;;EAEA;;;;;;;;YASU;;;;;;;EAOV;;;;;;EAMA;;;;;;EAMA;;;;;;;EAOA;;EAEA;IAAS,SAAS;;;EAElB;;;;;;IAME,UAAU;MAAiB,MAAM;;;;;;IAKjC;;IAEA;;;;;;;;;;EAUF;IAAY;IAAkB;;;EAE9B;;IAEE;;IAEA;;IAEA;;IAEA;;IAEA;;IAEA;;IAEA;;IAEA,QAAQ"}
@@ -0,0 +1,94 @@
1
+ import { appendLog, readManifest, readPointer, writeManifest } from "./store.mjs";
2
+
3
+ //#region ../../packages/core/src/release/verify.ts
4
+ function readPath(value, dotted) {
5
+ let current = value;
6
+ for (const key of dotted.split(".")) {
7
+ if (typeof current !== "object" || current === null) return void 0;
8
+ current = current[key];
9
+ }
10
+ return current;
11
+ }
12
+ function sleep(ms) {
13
+ return new Promise((resolve) => setTimeout(resolve, ms));
14
+ }
15
+ /** Why one attempt failed, or `null` when it matched the release. */
16
+ async function attempt(context, url, expected) {
17
+ const { verify } = context.config;
18
+ const controller = new AbortController();
19
+ const timer = setTimeout(() => controller.abort(), verify.timeoutMs);
20
+ try {
21
+ const response = await fetch(url, { signal: controller.signal });
22
+ if (response.status !== verify.expectedStatus) return `status ${response.status}, expected ${verify.expectedStatus}`;
23
+ if (verify.match.length === 0) return null;
24
+ let body;
25
+ try {
26
+ body = await response.json();
27
+ } catch {
28
+ return "the response is not JSON, so the version cannot be compared";
29
+ }
30
+ for (const field of verify.match) {
31
+ const reported = readPath(body, field === "version" ? verify.versionPath : verify.commitPath);
32
+ const wanted = expected[field];
33
+ if (reported === void 0) return `the response reports no ${field} (looked at "${field === "version" ? verify.versionPath : verify.commitPath}")`;
34
+ if (!(field === "commit" && typeof reported === "string" ? reported.length >= 7 && wanted.startsWith(reported) : reported === wanted)) return `reported ${field} ${String(reported)}, expected ${wanted}`;
35
+ }
36
+ return null;
37
+ } catch (error) {
38
+ return error.name === "AbortError" ? `no response within ${verify.timeoutMs}ms` : error.message;
39
+ } finally {
40
+ clearTimeout(timer);
41
+ }
42
+ }
43
+ /**
44
+ * GET the health URL until it answers with the expected status and reports
45
+ * the active release's version and commit, retrying with a pause between
46
+ * attempts. The outcome is recorded in the active release's manifest.
47
+ *
48
+ * @example
49
+ * const result = await verifyRelease(context);
50
+ */
51
+ async function verifyRelease(context) {
52
+ const { verify } = context.config;
53
+ const id = await readPointer(context, "current");
54
+ if (!id) throw new Error("No active release to verify.");
55
+ if (!verify.url) throw new Error("Set release.verify.url to the health URL first.");
56
+ const manifest = await readManifest(context, id);
57
+ let reason = "not attempted";
58
+ let attempts = 0;
59
+ for (let index = 0; index <= verify.retries; index++) {
60
+ if (index > 0) await sleep(verify.intervalMs);
61
+ attempts += 1;
62
+ reason = await attempt(context, verify.url, {
63
+ version: manifest.version,
64
+ commit: manifest.commit
65
+ });
66
+ if (reason === null) break;
67
+ }
68
+ const ok = reason === null;
69
+ await writeManifest(context, {
70
+ ...manifest,
71
+ verification: {
72
+ at: context.now().toISOString(),
73
+ ok,
74
+ attempts,
75
+ ...ok ? {} : { reason: reason ?? void 0 }
76
+ }
77
+ });
78
+ await appendLog(context, {
79
+ event: "verify",
80
+ release: id,
81
+ ok,
82
+ detail: ok ? `${attempts} attempt(s)` : reason ?? void 0
83
+ });
84
+ return {
85
+ id,
86
+ ok,
87
+ attempts,
88
+ ...ok ? {} : { reason: reason ?? void 0 }
89
+ };
90
+ }
91
+
92
+ //#endregion
93
+ export { verifyRelease };
94
+ //# sourceMappingURL=verify.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.mjs","names":[],"sources":["../../../../../../../../packages/core/src/release/verify.ts"],"sourcesContent":["import { appendLog, readManifest, readPointer, writeManifest, type ReleaseContext } from \"./store\";\n\nexport type VerifyResult = {\n id: string;\n ok: boolean;\n attempts: number;\n reason?: string;\n};\n\nfunction readPath(value: unknown, dotted: string): unknown {\n let current: unknown = value;\n\n for (const key of dotted.split(\".\")) {\n if (typeof current !== \"object\" || current === null) return undefined;\n current = (current as Record<string, unknown>)[key];\n }\n\n return current;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Why one attempt failed, or `null` when it matched the release. */\nasync function attempt(\n context: ReleaseContext,\n url: string,\n expected: { version: string; commit: string },\n): Promise<string | null> {\n const { verify } = context.config;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), verify.timeoutMs);\n\n try {\n const response = await fetch(url, { signal: controller.signal });\n\n if (response.status !== verify.expectedStatus) {\n return `status ${response.status}, expected ${verify.expectedStatus}`;\n }\n\n if (verify.match.length === 0) return null;\n\n let body: unknown;\n\n try {\n body = await response.json();\n } catch {\n return \"the response is not JSON, so the version cannot be compared\";\n }\n\n for (const field of verify.match) {\n const reported = readPath(body, field === \"version\" ? verify.versionPath : verify.commitPath);\n const wanted = expected[field];\n\n if (reported === undefined) {\n return `the response reports no ${field} (looked at \"${\n field === \"version\" ? verify.versionPath : verify.commitPath\n }\")`;\n }\n\n // A reported short commit counts when it is a prefix of the full one.\n const matches =\n field === \"commit\" && typeof reported === \"string\"\n ? reported.length >= 7 && wanted.startsWith(reported)\n : reported === wanted;\n\n if (!matches) return `reported ${field} ${String(reported)}, expected ${wanted}`;\n }\n\n return null;\n } catch (error) {\n return (error as Error).name === \"AbortError\"\n ? `no response within ${verify.timeoutMs}ms`\n : (error as Error).message;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * GET the health URL until it answers with the expected status and reports\n * the active release's version and commit, retrying with a pause between\n * attempts. The outcome is recorded in the active release's manifest.\n *\n * @example\n * const result = await verifyRelease(context);\n */\nexport async function verifyRelease(context: ReleaseContext): Promise<VerifyResult> {\n const { verify } = context.config;\n const id = await readPointer(context, \"current\");\n\n if (!id) throw new Error(\"No active release to verify.\");\n if (!verify.url) throw new Error(\"Set release.verify.url to the health URL first.\");\n\n const manifest = await readManifest(context, id);\n let reason: string | null = \"not attempted\";\n let attempts = 0;\n\n for (let index = 0; index <= verify.retries; index++) {\n if (index > 0) await sleep(verify.intervalMs);\n\n attempts += 1;\n reason = await attempt(context, verify.url, {\n version: manifest.version,\n commit: manifest.commit,\n });\n\n if (reason === null) break;\n }\n\n const ok = reason === null;\n\n await writeManifest(context, {\n ...manifest,\n verification: {\n at: context.now().toISOString(),\n ok,\n attempts,\n ...(ok ? {} : { reason: reason ?? undefined }),\n },\n });\n await appendLog(context, {\n event: \"verify\",\n release: id,\n ok,\n detail: ok ? `${attempts} attempt(s)` : (reason ?? undefined),\n });\n\n return { id, ok, attempts, ...(ok ? {} : { reason: reason ?? undefined }) };\n}\n"],"mappings":";;;AASA,SAAS,SAAS,OAAgB,QAAyB;CACzD,IAAI,UAAmB;CAEvB,KAAK,MAAM,OAAO,OAAO,MAAM,GAAG,GAAG;EACnC,IAAI,OAAO,YAAY,YAAY,YAAY,MAAM,OAAO;EAC5D,UAAW,QAAoC;CACjD;CAEA,OAAO;AACT;AAEA,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;;AAGA,eAAe,QACb,SACA,KACA,UACwB;CACxB,MAAM,EAAE,WAAW,QAAQ;CAC3B,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,QAAQ,iBAAiB,WAAW,MAAM,GAAG,OAAO,SAAS;CAEnE,IAAI;EACF,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,QAAQ,WAAW,OAAO,CAAC;EAE/D,IAAI,SAAS,WAAW,OAAO,gBAC7B,OAAO,UAAU,SAAS,OAAO,aAAa,OAAO;EAGvD,IAAI,OAAO,MAAM,WAAW,GAAG,OAAO;EAEtC,IAAI;EAEJ,I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9B;GACA;GACA,GAAI,KAAK,CAAC,IAAI,EAAE,QAAQ,UAAU,OAAU;EAC9C;CACF,CAAC;CACD,MAAM,UAAU,SAAS;EACvB,OAAO;EACP,SAAS;EACT;EACA,QAAQ,KAAK,GAAG,SAAS,eAAgB,UAAU;CACrD,CAAC;CAED,OAAO;EAAE;EAAI;EAAI;EAAU,GAAI,KAAK,CAAC,IAAI,EAAE,QAAQ,UAAU,OAAU;CAAG;AAC5E"}
@@ -6,5 +6,5 @@ import { matchesDerivedRouteName, routeNameMethodSuffix } from "./route-name-met
6
6
  import { RouteNameTakenError } from "./route-name-taken-error.mjs";
7
7
  import { RouteRegistry } from "./route-registry.mjs";
8
8
  import { Router, router } from "./router.mjs";
9
- import { AUTH_GUARD_MARKER, isAuthGuardMiddleware, isUnguardedMutatingRoute, markAuthGuard, reportUnguardedMutatingRoutes, resetUnguardedRouteReports } from "./unguarded-route-diagnostics.mjs";
10
- export { AUTH_GUARD_MARKER, GroupedRoutesOptions, HttpContext, Middleware, MiddlewareResponse, NamedApiRoute, NamedApiRoutesOptions, PartialPick, PositionalHandlerSuspect, RequestControllerContract, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestMethod, ResourceMethod, RestfulMiddleware, Route, RouteNameTakenError, RouteOptions, RouteRateLimitOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, StaticMountOptions, ValidationFailureContext, ValidationFailureHandler, ValidationFailureResponse, clearPositionalHandlerSuspects, describePositionalHandlerSuspect, forgetPositionalHandlerSuspects, inspectHandlerSignature, isAuthGuardMiddleware, isUnguardedMutatingRoute, listPositionalHandlerSuspects, looksLikePositionalHandler, markAuthGuard, matchesDerivedRouteName, normalizeRequestPath, normalizeRoutePath, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, resetUnguardedRouteReports, routeNameMethodSuffix, router };
9
+ import { AUTH_GUARD_MARKER, isAuthGuardMiddleware, isRequiredGuardRoute, isUnguardedMutatingRoute, markAuthGuard, reportUnguardedMutatingRoutes, resetUnguardedRouteReports } from "./unguarded-route-diagnostics.mjs";
10
+ export { AUTH_GUARD_MARKER, GroupedRoutesOptions, HttpContext, Middleware, MiddlewareResponse, NamedApiRoute, NamedApiRoutesOptions, PartialPick, PositionalHandlerSuspect, RequestControllerContract, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestMethod, ResourceMethod, RestfulMiddleware, Route, RouteNameTakenError, RouteOptions, RouteRateLimitOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, StaticMountOptions, ValidationFailureContext, ValidationFailureHandler, ValidationFailureResponse, clearPositionalHandlerSuspects, describePositionalHandlerSuspect, forgetPositionalHandlerSuspects, inspectHandlerSignature, isAuthGuardMiddleware, isRequiredGuardRoute, isUnguardedMutatingRoute, listPositionalHandlerSuspects, looksLikePositionalHandler, markAuthGuard, matchesDerivedRouteName, normalizeRequestPath, normalizeRoutePath, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, resetUnguardedRouteReports, routeNameMethodSuffix, router };
@@ -4,7 +4,7 @@ import { clearPositionalHandlerSuspects, describePositionalHandlerSuspect, forge
4
4
  import { matchesDerivedRouteName, routeNameMethodSuffix } from "./route-name-method-suffix.mjs";
5
5
  import { RouteNameTakenError } from "./route-name-taken-error.mjs";
6
6
  import { RouteRegistry } from "./route-registry.mjs";
7
- import { AUTH_GUARD_MARKER, isAuthGuardMiddleware, isUnguardedMutatingRoute, markAuthGuard, reportUnguardedMutatingRoutes, resetUnguardedRouteReports } from "./unguarded-route-diagnostics.mjs";
7
+ import { AUTH_GUARD_MARKER, isAuthGuardMiddleware, isRequiredGuardRoute, isUnguardedMutatingRoute, markAuthGuard, reportUnguardedMutatingRoutes, resetUnguardedRouteReports } from "./unguarded-route-diagnostics.mjs";
8
8
  import { Router, router } from "./router.mjs";
9
9
 
10
- export { AUTH_GUARD_MARKER, RouteNameTakenError, RouteRegistry, Router, clearPositionalHandlerSuspects, describePositionalHandlerSuspect, forgetPositionalHandlerSuspects, inspectHandlerSignature, isAuthGuardMiddleware, isUnguardedMutatingRoute, listPositionalHandlerSuspects, looksLikePositionalHandler, markAuthGuard, matchesDerivedRouteName, normalizeRequestPath, normalizeRoutePath, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, resetUnguardedRouteReports, routeNameMethodSuffix, router };
10
+ export { AUTH_GUARD_MARKER, RouteNameTakenError, RouteRegistry, Router, clearPositionalHandlerSuspects, describePositionalHandlerSuspect, forgetPositionalHandlerSuspects, inspectHandlerSignature, isAuthGuardMiddleware, isRequiredGuardRoute, isUnguardedMutatingRoute, listPositionalHandlerSuspects, looksLikePositionalHandler, markAuthGuard, matchesDerivedRouteName, normalizeRequestPath, normalizeRoutePath, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, resetUnguardedRouteReports, routeNameMethodSuffix, router };
@@ -221,6 +221,10 @@ export declare class Router {
221
221
  *
222
222
  * Names are the registered names, including method suffixes. `all` stays
223
223
  * intact as route metadata; consumers decide whether their use supports it.
224
+ * A route that opted out with `clientVisible: false` carries that flag so
225
+ * browser-facing consumers can leave it out. `sites` is present only on a
226
+ * route that declared some, and `guarded: true` only on a route with an auth
227
+ * guard in its middleware chain (group middleware included).
224
228
  */
225
229
  getNamedApiRoutes(options?: NamedApiRoutesOptions): readonly NamedApiRoute[];
226
230
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"router.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/router/router.ts"],"mappings":";;;;;;qBAqKa;;;;UAIH;;;;;;;;;UAUA;;;;;UAMA;;;;;UAUA;;;;iBAKO;;;;YAKL;IACR,SAAS;IACT,WAAW;;;;;YAMH,gBAAgB,iBAAiB,QAAQ,QAAQ,QAAQ;;;;;YAOzD,QAAQ;;;;SASJ,eAAW;UAQlB;;;;EAOA,eAAe,WAAW,QAAQ,QAAQ,QAAQ;;;;EASlD,cAAc,WAAW,QAAQ,QAAQ,QAAQ;;;;EASjD,SAAS,cAAc,YAAY;;;;;;;;;;;;;;EAmBnC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,eAAiB;;;;;;;;;;;EAc9C,gBACL,cACA,UAAU,eACV,UAAS;IACP,OAAO;IACP,SAAS;IACT,UAAU,QAAQ,OAAO,gBAAgB;MACvC,aAAa;;;;;;EAsGZ,MAAM,SAAS,sBAAsB,UAAU;;;;EAqE/C,OAAO,gBAAgB;;;;;;;;;;;;;EAgBvB,QAAQ,0BAA0B;;;;;;;EAU5B,eAAe,SAC1B,oBACA,gBAAgB,IAAI,QAAQ,KAC3B,QAAQ;;;;;;EAiCJ,yBAAyB;;;;;;;;;EA0BnB,2BAA2B,GACtC,aAAa,kBACb,eAAe,IAAI,QAAQ,KAC1B,QAAQ;;;;UAoDH;;;;EA4ED,QAAI;;;;;;;;;;;EAcJ,kBAAkB,UAAS,iCAAsC;;;;;;;;;EAkCjE;;;;EAOA,KAAK,QAAQ;;;;;EAqDb,cAAc,QAAQ;;;;EAiKtB,SAAS,cAAc,SAAQ;;;;UAkC9B;;qBA+EG,QAAM"}
@@ -15,7 +15,7 @@ import { buildRequestLogSnapshot } from "../http/request-log-snapshot.mjs";
15
15
  import { Request } from "../http/request.mjs";
16
16
  import { describeRouteForLog } from "./describe-route-for-log.mjs";
17
17
  import { logRequestLifecycle } from "./log-request-lifecycle.mjs";
18
- import { reportUnguardedMutatingRoutes } from "./unguarded-route-diagnostics.mjs";
18
+ import { isRequiredGuardRoute, reportUnguardedMutatingRoutes } from "./unguarded-route-diagnostics.mjs";
19
19
  import { RouteBuilder } from "./route-builder.mjs";
20
20
  import { resolveRouteRateLimit, resolveStaticRateLimit } from "./resolve-route-rate-limit.mjs";
21
21
  import { DEV_DISPATCH_METHODS, buildNotFoundBody, createDevRateLimiter } from "./dev-dispatch.mjs";
@@ -229,6 +229,8 @@ var Router = class Router {
229
229
  if (middlewarePrecedence === "before") options.middleware = [...options.middleware || [], ...this.stacks.middleware];
230
230
  else options.middleware = [...this.stacks.middleware, ...options.middleware || []];
231
231
  if (options.public === void 0 && (this.stacks.public ?? 0) > 0) options.public = true;
232
+ const groupSites = this.stacks.sites?.at(-1);
233
+ if (options.sites === void 0 && groupSites !== void 0) options.sites = groupSites;
232
234
  if (Array.isArray(handler)) {
233
235
  const [controller, action] = handler;
234
236
  if (typeof controller[action] !== "function") throw new WarlockError("WL3002", `Invalid controller action "${action}" for controller "${controller.constructor.name}"`);
@@ -391,7 +393,8 @@ var Router = class Router {
391
393
  * Group routes with options
392
394
  */
393
395
  group(options, callback) {
394
- const { prefix, name = prefix ? trim(prefix.replace(/\//g, "."), ".") : void 0, middleware, public: isPublic } = options;
396
+ const { prefix, name = prefix ? trim(prefix.replace(/\//g, "."), ".") : void 0, middleware, public: isPublic, sites } = options;
397
+ if (sites) (this.stacks.sites ??= []).push(sites);
395
398
  if (isPublic) this.stacks.public = (this.stacks.public ?? 0) + 1;
396
399
  if (prefix) this.stacks.prefix.push(prefix);
397
400
  if (name) this.stacks.name.push(name);
@@ -403,6 +406,7 @@ var Router = class Router {
403
406
  if (name) this.stacks.name.pop();
404
407
  if (middleware) this.stacks.middleware.splice(this.stacks.middleware.length - middleware.length, middleware.length);
405
408
  if (isPublic) this.stacks.public = (this.stacks.public ?? 1) - 1;
409
+ if (sites) this.stacks.sites?.pop();
406
410
  }
407
411
  return this;
408
412
  }
@@ -554,13 +558,20 @@ var Router = class Router {
554
558
  *
555
559
  * Names are the registered names, including method suffixes. `all` stays
556
560
  * intact as route metadata; consumers decide whether their use supports it.
561
+ * A route that opted out with `clientVisible: false` carries that flag so
562
+ * browser-facing consumers can leave it out. `sites` is present only on a
563
+ * route that declared some, and `guarded: true` only on a route with an auth
564
+ * guard in its middleware chain (group middleware included).
557
565
  */
558
566
  getNamedApiRoutes(options = {}) {
559
567
  return Object.freeze(this.routes.filter((route) => !route.isPage && typeof route.name === "string" && route.name.length > 0).map((route) => {
560
568
  const snapshot = {
561
569
  name: route.name,
562
570
  path: route.path,
563
- method: route.method
571
+ method: route.method,
572
+ ...route.clientVisible === false ? { clientVisible: false } : {},
573
+ ...route.sites === void 0 ? {} : { sites: Object.freeze([...route.sites]) },
574
+ ...isRequiredGuardRoute(route) ? { guarded: true } : {}
564
575
  };
565
576
  const schema = route.handler?.responseSchema;
566
577
  const response = schema ? options.resolveResponse?.(schema, route) : void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"router.mjs","names":["configAccessor","config"],"sources":["../../../../../../../../packages/core/src/router/router.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport proxy, { type FastifyHttpProxyOptions } from \"@fastify/http-proxy\";\nimport { WarlockError } from \"../errors/warlock-error\";\nimport type { FastifyStaticOptions } from \"@fastify/static\";\nimport { ltrim, merge, toCamelCase, trim } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport { log } from \"@warlock.js/logger\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport { container } from \"../container\";\nimport { registerLazyStatic } from \"../http/lazy-static\";\nimport { buildCorsOptions } from \"../http/build-cors-options\";\nimport { Request } from \"../http/request\";\nimport { buildRequestLogSnapshot } from \"../http/request-log-snapshot\";\nimport { Response } from \"../http/response\";\nimport { type FastifyInstance } from \"../http/server\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../http/tracing\";\nimport { describeRouteForLog } from \"./describe-route-for-log\";\nimport { logRequestLifecycle } from \"./log-request-lifecycle\";\nimport {\n forgetPositionalHandlerSuspects,\n inspectHandlerSignature,\n reportPositionalHandlerSuspects,\n} from \"./positional-handler-diagnostics\";\nimport { reportUnguardedMutatingRoutes } from \"./unguarded-route-diagnostics\";\nimport { config as configAccessor } from \"../config/config-getter\";\nimport { normalizeRoutePath } from \"./normalize-route-path\";\nimport { RouteBuilder } from \"./route-builder\";\nimport { resolveRouteRateLimit, resolveStaticRateLimit } from \"./resolve-route-rate-limit\";\nimport { RouteNameTakenError } from \"./route-name-taken-error\";\nimport { DEV_DISPATCH_METHODS, buildNotFoundBody, createDevRateLimiter } from \"./dev-dispatch\";\nimport { RouteRegistry } from \"./route-registry\";\nimport { routeNameMethodSuffix } from \"./route-name-method-suffix\";\nimport type {\n GroupedRoutesOptions,\n HttpContext,\n NamedApiRoute,\n NamedApiRoutesOptions,\n RequestHandler,\n RequestHandlerType,\n RequestHandlerValidation,\n ResourceMethod,\n Route,\n RouteOptions,\n RouteResource,\n RouterGroupCallback,\n RouterStacks,\n StaticMountOptions,\n} from \"./types\";\n\n/**\n * A Fastify lifecycle hook as it may be declared in a route's `serverOptions`.\n * Fastify accepts a single hook or an array in either position.\n */\ntype RouteLifecycleHook = (\n request: FastifyRequest,\n reply: FastifyReply,\n) => unknown | Promise<unknown>;\n\n/**\n * The pre-handler phases the dev server forwards from a route's `serverOptions`.\n *\n * These are the admission-control phases and they share the `(request, reply)`\n * signature. `preParsing` is deliberately absent — it must return the payload\n * stream, so forwarding it generically would corrupt the body rather than\n * guard it. `bodyLimit` cannot be forwarded at all; Fastify reads it at\n * registration time and no hook can bound a body already being parsed.\n */\nconst FORWARDED_ROUTE_PHASES = [\"onRequest\", \"preValidation\", \"preHandler\"] as const;\n\ntype ForwardedRoutePhase = (typeof FORWARDED_ROUTE_PHASES)[number];\n\n/**\n * The route the dev dispatcher matched, stashed on the request so the hooks and\n * the wildcard handler all act on one match rather than each matching again.\n */\ntype DevMatchedRoute = { route: Route; params: Record<string, string> };\n\ntype DevDispatchRequest = FastifyRequest & {\n matchedDevRoute?: DevMatchedRoute;\n};\n\nfunction toHookList(\n hook: RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n): RouteLifecycleHook[] {\n if (!hook) {\n return [];\n }\n\n return Array.isArray(hook) ? hook : [hook];\n}\n\n/**\n * Run a matched route's hooks for one phase.\n *\n * Returning the reply is how an async Fastify hook signals that it has answered\n * the request; the chain must stop there, so the value is propagated rather\n * than discarded.\n */\nasync function runRouteHooks(\n route: Route,\n phase: ForwardedRoutePhase,\n request: FastifyRequest,\n reply: FastifyReply,\n) {\n const hooks = toHookList(\n route.serverOptions?.[phase] as RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n );\n\n for (const hook of hooks) {\n const outcome = await hook(request, reply);\n\n if (outcome === reply) {\n return reply;\n }\n }\n\n return undefined;\n}\n\n/**\n * Bound functions do not inherit static properties, so the handler metadata that\n * documentation and typings read (`responseSchema`) is copied onto the bound copy.\n */\nfunction copyResponseSchema(source: unknown, target: RequestHandler): void {\n const responseSchema = (source as RequestHandler | undefined)?.responseSchema;\n\n if (responseSchema) {\n target.responseSchema = responseSchema;\n }\n}\n\n/**\n * Bind a restful resource method to its resource, keeping its `responseSchema`.\n */\nfunction bindResourceHandler(\n resource: RouteResource,\n method: ResourceMethod | \"bulkDelete\",\n): RequestHandler {\n const source = resource[method];\n const handler = source?.bind(resource) as RequestHandler;\n\n copyResponseSchema(source, handler);\n\n return handler;\n}\n\n/**\n * Describe one claimant of a route name, for the duplicate-name error.\n *\n * `warlock dev` registers SSR page routes on the same router as API routes, so\n * the two share a single route-name namespace and collide across kinds. The\n * error is only actionable if it says which claimant is which, so `isPage` —\n * the router's only route-kind discriminator — is what separates them here.\n *\n * `sourceFile` is stamped only on routes registered through `withSourceFile`.\n * Routes registered without that scope have no owner, so say the source is\n * unknown rather than printing an empty string.\n */\nfunction describeRouteClaimant(route: Route) {\n const type = route.isPage ? \"page route\" : \"API route\";\n const source = route.sourceFile ? `declared in ${route.sourceFile}` : \"source file unknown\";\n\n return `${type} ${route.method} ${route.path} (${source})`;\n}\n\nexport class Router {\n /**\n * Routes list\n */\n private routes: Route[] = [];\n\n /**\n * Bumped on every mutation of {@link routes}.\n *\n * The dev dispatcher caches a route registry and needs to know when it is\n * stale. Comparing `routes.length` would miss an HMR reload that replaces a\n * route without changing the count — the registry would then keep matching\n * paths that no longer exist. A version counter cannot miss that.\n */\n private routesVersion = 0;\n\n /**\n * In-progress atomic replacement, when one exists. Reads continue to use\n * {@link routes}; mutations and collision checks use this isolated draft.\n */\n private routeReplacementTransaction?: {\n routes: Route[];\n removedSourceFiles: Set<string>;\n addedRoutes: Route[];\n };\n\n /**\n * Set by the dev server: whether to warn about mutating routes that have no\n * auth middleware and no `public: true` (`http.warnUnguardedRoutes`).\n */\n private warnUnguardedRoutes = false;\n\n /**\n * Router Instance\n */\n private static instance: Router;\n\n /**\n * Static paths\n */\n protected staticDirectories: {\n options: FastifyStaticOptions;\n rateLimit: StaticMountOptions[\"rateLimit\"];\n }[] = [];\n\n /**\n * Event listeners\n */\n protected eventListeners: Record<string, ((router: Router, server: FastifyInstance) => void)[]> =\n {};\n\n /**\n * Stacks\n * Stacks will be used for grouping routes to add prefix, name or middleware\n */\n protected stacks: RouterStacks = {\n prefix: [],\n name: [],\n middleware: [],\n };\n\n /**\n * Get router instance\n */\n public static getInstance() {\n if (!Router.instance) {\n Router.instance = new Router();\n }\n\n return Router.instance;\n }\n\n private constructor() {\n //\n }\n\n /**\n * Listen to router before scan\n */\n public beforeScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.beforeScan = [...(this.eventListeners.beforeScan || []), callback];\n\n return this;\n }\n\n /**\n * Listen to router after scanning\n */\n public afterScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.afterScanning = [...(this.eventListeners.afterScanning || []), callback];\n\n return this;\n }\n\n /**\n * Redirect path to another path\n */\n public redirect(from: string, to: string, redirectMode: \"temporary\" | \"permanent\" = \"temporary\") {\n return this.get(from, ({ response }) => {\n response.redirect(to, redirectMode === \"temporary\" ? 302 : 301);\n });\n }\n\n /**\n * Serve a static folder.\n *\n * Static mounts are exempt from the global rate limiter by default; set\n * `http.rateLimit.staticFiles: true` to count every mount, or pass\n * `{ rateLimit }` to decide for this mount alone: `true` counts it against\n * the global limiter, `false` exempts it, and an object gives it its own\n * limit and bucket.\n *\n * @example\n * router.directory({ root: rootPath(\"docs\"), prefix: \"/docs/\" });\n * router.directory({ root: rootPath(\"exports\"), prefix: \"/exports/\" }, { rateLimit: true });\n */\n public directory(options: FastifyStaticOptions, mountOptions: StaticMountOptions = {}) {\n this.staticDirectories.push({ options, rateLimit: mountOptions.rateLimit });\n\n return this;\n }\n\n /** Declare static routes at boot; load the upstream sender on the first file request. */\n protected registerStaticDirectories(server: FastifyInstance) {\n for (const directory of this.staticDirectories) {\n registerLazyStatic(\n server,\n { ...directory.options, decorateReply: false },\n { rateLimit: resolveStaticRateLimit(directory.rateLimit) },\n );\n }\n }\n\n /**\n * Register a GET route that serves a static file. Like `directory()`, it is\n * exempt from the global rate limiter unless `http.rateLimit.staticFiles`\n * or its own `rateLimit` says otherwise.\n */\n protected addStaticFileRoute(\n path: string,\n handler: RequestHandler,\n mountOptions: StaticMountOptions = {},\n ) {\n this.get(\n path,\n handler,\n mountOptions.rateLimit === undefined ? {} : { rateLimit: mountOptions.rateLimit },\n );\n\n const routes = this.routeReplacementTransaction?.routes ?? this.routes;\n const route = routes[routes.length - 1];\n\n if (route) route.$staticFile = true;\n\n return this;\n }\n\n /**\n * Serve file\n */\n public file(\n path: string,\n location: string,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n return this.addStaticFileRoute(\n path,\n ({ response }) => {\n response.sendFile(location, cacheTime);\n },\n mountOptions,\n );\n }\n\n /**\n * Serve cached file, it will cache the file to 1 year by default\n */\n public cachedFile(\n path: string,\n location: string,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n return this.addStaticFileRoute(\n path,\n ({ response }) => {\n response.sendCachedFile(location, cacheTime);\n },\n mountOptions,\n );\n }\n\n /**\n * Serve list of files\n */\n public files(\n files: Record<string, string>,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n for (const [path, location] of Object.entries(files)) {\n this.file(path, location, cacheTime, mountOptions);\n }\n }\n\n /**\n * Serve list of cached files, it will cache the file to 1 year by default\n */\n public cachedFiles(\n files: Record<string, string>,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n for (const [path, location] of Object.entries(files)) {\n this.cachedFile(path, location, cacheTime, mountOptions);\n }\n }\n\n /**\n * Add proxy route\n */\n public proxy(\n path: string,\n baseUrl: string,\n options?: Omit<FastifyHttpProxyOptions, \"prefix\" | \"upstream\">,\n ): this;\n public proxy(options: FastifyHttpProxyOptions): this;\n public proxy(...args: any[]) {\n this.beforeScanning((_router, server) => {\n if (args.length === 1) {\n server.register(proxy, args[0]);\n } else {\n server.register(proxy, {\n prefix: args[0],\n upstream: args[1],\n ...args[2],\n });\n }\n });\n\n return this;\n }\n\n /**\n * Add route to routes list\n */\n public add(\n method: Route[\"method\"],\n path: string | string[],\n handler: RequestHandlerType,\n options: RouteOptions = {},\n ) {\n if (Array.isArray(path)) {\n path.forEach((p) => this.add(method, p, handler, options));\n return this;\n }\n\n const prefix = this.stacks.prefix.reduce((path, prefix) => {\n return normalizeRoutePath(path, prefix);\n }, \"\");\n\n const name = this.stacks.name.reduceRight(\n (name, prefixName) => {\n return trim(prefixName + \".\" + name, \".\");\n },\n options.name || trim(path.replace(/\\//g, \".\"), \".\"),\n );\n\n // The one place a route path becomes canonical. `normalizeRoutePath` is\n // exported so the build-time page-route manifest can produce the very same\n // string without registering anything.\n path = normalizeRoutePath(prefix, path);\n\n const middlewarePrecedence = options.middlewarePrecedence || \"after\";\n\n // Work on a copy: the caller may reuse one options object for several\n // routes, and merging the group stack into it would compound per route.\n options = { ...options };\n\n if (middlewarePrecedence === \"before\") {\n options.middleware = [...(options.middleware || []), ...this.stacks.middleware];\n } else {\n options.middleware = [...this.stacks.middleware, ...(options.middleware || [])];\n }\n\n // An enclosing `router.group({ public: true })` makes the route public\n // unless it says otherwise itself.\n if (options.public === undefined && (this.stacks.public ?? 0) > 0) {\n options.public = true;\n }\n\n if (Array.isArray(handler)) {\n const [controller, action] = handler;\n\n if (typeof controller[action] !== \"function\") {\n throw new WarlockError(\n \"WL3002\",\n `Invalid controller action \"${action}\" for controller \"${controller.constructor.name}\"`,\n );\n }\n\n handler = controller[action].bind(controller) as RequestHandler;\n copyResponseSchema(controller[action], handler);\n\n if (!handler.validation) {\n handler.validation = {};\n if (controller[`${action}ValidationSchema`]) {\n handler.validation.schema = controller[`${action}ValidationSchema`]();\n }\n\n if (controller[`${action}Validate`]) {\n handler.validation.validate = controller[`${action}Validate`];\n }\n }\n }\n\n const routeData: Route = {\n method,\n path,\n handler,\n ...options,\n name,\n rateLimit: options.rateLimit,\n $prefix: prefix || \"/\",\n // it must be a new array to avoid modifying the original array\n $prefixStack: [...this.stacks.prefix],\n // Inject source file from stacks if set\n sourceFile: this.stacks.sourceFile || \"\",\n };\n\n const routes = this.routeReplacementTransaction?.routes ?? this.routes;\n\n if (routeData.name) {\n // check if the name exists\n const route = routes.find((route) => route.name === routeData.name);\n\n if (route) {\n // check again if the route name exists with the same method\n if (route.method === routeData.method) {\n throw new RouteNameTakenError(\n routeData.name,\n `Route name \"${routeData.name}\" is already taken.\\n` +\n ` already registered: ${describeRouteClaimant(route)}\\n` +\n ` now being added: ${describeRouteClaimant(routeData)}\\n` +\n `Pages and API routes share one route-name namespace, so a name can only be ` +\n `claimed once. Rename one of them via the \"name\" route option.`,\n );\n } else {\n routeData.name += routeNameMethodSuffix(routeData.method);\n }\n }\n }\n\n // Registration-time only — nothing here runs per request. Suspects are\n // collected now and reported together at boot (see `scan`), so a route file\n // written against v4 produces one legible list instead of a mystery 500 per\n // request. Recorded after the collision check so a route that never lands\n // is never reported.\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.addedRoutes.push(routeData);\n } else {\n inspectHandlerSignature(routeData.handler, routeData);\n }\n\n routes.push(routeData);\n\n if (!this.routeReplacementTransaction) {\n this.routesVersion++;\n }\n\n return this;\n }\n\n /**\n * Add a request that accepts all methods\n */\n public any(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"all\" as Route[\"method\"], path, handler, options);\n }\n\n /**\n * Add get request method\n */\n public get(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"GET\", path, handler, options);\n }\n\n /**\n * Add post request method\n */\n public post(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"POST\", path, handler, options);\n }\n\n /**\n * Add put request method\n */\n public put(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PUT\", path, handler, options);\n }\n\n /**\n * Add delete request method\n */\n public delete(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"DELETE\", path, handler, options);\n }\n\n /**\n * Add patch request method\n */\n public patch(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PATCH\", path, handler, options);\n }\n\n /**\n * Add head request method\n */\n public head(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"HEAD\", path, handler, options);\n }\n\n /**\n * Add options request method\n */\n public options(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"OPTIONS\", path, handler, options);\n }\n\n /**\n * Get a chainable route builder for the same route path\n */\n public route(path: string, options: RouteOptions = {}) {\n return new RouteBuilder(this, path, options);\n }\n\n /**\n * Add full restful resource routes\n * This method will generate the following routes:\n * 1. GET /path: list all resources\n * 2. GET /path/:id: get a single resource\n * 3. POST /path: create a new resource\n * 4. PUT /path/:id: update a resource\n * 5. DELETE /path/:id: delete a resource\n * 6. PATCH /path/:id: update a resource partially\n */\n public restfulResource(\n path: string,\n resource: RouteResource,\n options: RouteOptions & {\n only?: ResourceMethod[];\n except?: ResourceMethod[];\n replace?: Partial<Record<ResourceMethod, RequestHandler>> & {\n bulkDelete?: RequestHandler;\n };\n } = {},\n ) {\n // Derive the base resource name from the path before the group below\n // clears it for use as the routes' relative path. `options.name`, when\n // given, replaces the path-derived name entirely (see the explicit\n // `name` passed to `group()`) rather than composing with it.\n const baseResourceName = options.name || toCamelCase(ltrim(path, \"/\"));\n\n return this.group({ prefix: path, name: baseResourceName }, () => {\n const path = \"\";\n\n // clone the resource so we don't mess up with it\n const routeResource = resource;\n\n const isAcceptableResource = (type: ResourceMethod) => {\n return Boolean(\n // check if the route is not excluded\n (!options.except || !options.except.includes(type)) &&\n // check if the only option is set and the route is included\n (!options.only || options.only.includes(type)),\n );\n };\n\n if (routeResource.list && isAcceptableResource(\"list\")) {\n this.get(path, options.replace?.list || bindResourceHandler(routeResource, \"list\"), {\n ...options,\n name: \"list\",\n restful: true,\n });\n }\n\n if (routeResource.get && isAcceptableResource(\"get\")) {\n this.get(path + \"/:id\", options.replace?.get || bindResourceHandler(routeResource, \"get\"), {\n ...options,\n name: \"single\",\n restful: true,\n });\n }\n\n if (routeResource.create && isAcceptableResource(\"create\")) {\n const handler = options.replace?.create || this.manageValidation(routeResource, \"create\");\n\n this.post(path, handler, {\n ...options,\n name: \"create\",\n restful: true,\n });\n }\n\n if (routeResource.update && isAcceptableResource(\"update\")) {\n const handler = options.replace?.update || this.manageValidation(routeResource, \"update\");\n\n this.put(path + \"/:id\", handler, {\n ...options,\n name: \"update\",\n restful: true,\n });\n }\n\n if (routeResource.patch && isAcceptableResource(\"patch\")) {\n const handler = options.replace?.patch || this.manageValidation(routeResource, \"patch\");\n\n this.patch(path + \"/:id\", handler, {\n ...options,\n name: \"patch\",\n restful: true,\n });\n }\n\n if (routeResource.delete && isAcceptableResource(\"delete\")) {\n this.delete(\n path + \"/:id\",\n options.replace?.delete || bindResourceHandler(routeResource, \"delete\"),\n {\n ...options,\n name: \"delete\",\n restful: true,\n },\n );\n }\n\n if (routeResource.bulkDelete && isAcceptableResource(\"delete\")) {\n this.delete(\n path,\n options.replace?.bulkDelete || bindResourceHandler(routeResource, \"bulkDelete\"),\n {\n ...options,\n name: \"bulkDelete\",\n restful: true,\n },\n );\n }\n\n return this;\n });\n }\n\n /**\n * Group routes with options\n */\n public group(options: GroupedRoutesOptions, callback: RouterGroupCallback) {\n const {\n prefix,\n // name must always be defined because\n // if there are multiple groups without name\n // they might generate the same route name\n // thus causing an error\n // in this case we need always to make sure that\n // the name is always defined.\n name = prefix ? trim(prefix.replace(/\\//g, \".\"), \".\") : undefined,\n middleware,\n public: isPublic,\n } = options;\n\n if (isPublic) {\n this.stacks.public = (this.stacks.public ?? 0) + 1;\n }\n\n if (prefix) {\n this.stacks.prefix.push(prefix);\n }\n\n if (name) {\n this.stacks.name.push(name);\n }\n\n if (middleware) {\n this.stacks.middleware.push(...middleware);\n }\n\n try {\n callback();\n } finally {\n // Always pop/splice this group's stacks, even if the callback throws,\n // so a throwing group never leaks state onto the process-global singleton.\n if (prefix) {\n this.stacks.prefix.pop();\n }\n\n if (name) {\n this.stacks.name.pop();\n }\n\n if (middleware) {\n this.stacks.middleware.splice(\n this.stacks.middleware.length - middleware.length,\n middleware.length,\n );\n }\n if (isPublic) {\n this.stacks.public = (this.stacks.public ?? 1) - 1;\n }\n }\n\n return this;\n }\n\n /**\n * Add prefix to all routes in the given callback\n */\n public prefix(prefix: string, callback: () => void) {\n return this.group({ prefix }, callback);\n }\n\n /**\n * Add API version prefix to all routes in the given callback\n * Automatically formats the version as /v{version}\n * @example\n * router.version(\"1\", () => {\n * router.get(\"/users\", getUsersV1); // /v1/users\n * });\n *\n * router.version(\"2\", () => {\n * router.get(\"/users\", getUsersV2); // /v2/users\n * });\n */\n public version(version: string | number, callback: () => void) {\n return this.prefix(`/v${version}`, callback);\n }\n\n /**\n * Wrap route additions with a source file path\n * Used for tracking which routes come from which file (for HMR)\n * @param sourceFile Relative path to the source file (e.g., \"src/app/users/routes.ts\")\n * @param callback Function that adds routes (will have sourceFile injected)\n */\n public async withSourceFile<T = any>(\n sourceFile: string,\n callback: () => T | Promise<T>,\n ): Promise<T | undefined> {\n // Set source file in stacks\n this.stacks.sourceFile = sourceFile;\n\n try {\n // Execute callback (routes added here will have sourceFile injected)\n return await callback();\n } catch (error) {\n // Log loudly, then RETHROW. Swallowing here silently dropped a whole\n // route file (duplicate name, invalid action, import error) so the\n // surface 404'd with no boot error. The caller decides what a throw\n // means: at boot it aborts the boot, during HMR the dev server's\n // batch-reload handler catches it, prints it, and keeps serving.\n log.error({\n module: \"router\",\n action: \"registerRoutes\",\n message: `Failed to register routes from \"${sourceFile}\"`,\n context: { sourceFile, error },\n });\n\n throw error;\n } finally {\n // Always clear source file from stacks so a throwing file never leaks\n // its sourceFile onto the process-global singleton.\n delete this.stacks.sourceFile;\n }\n }\n\n /**\n * Remove all routes that belong to a specific source file\n * Used when reloading routes files via HMR\n * @param sourceFile Relative path to the source file\n */\n public removeRoutesBySourceFile(sourceFile: string): void {\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.routes = this.routeReplacementTransaction.routes.filter(\n (route) => route.sourceFile !== sourceFile,\n );\n this.routeReplacementTransaction.removedSourceFiles.add(sourceFile);\n return;\n }\n\n this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);\n\n // Keep the signature diagnostics in step, so a reload that fixes a handler\n // stops reporting the version it replaced.\n forgetPositionalHandlerSuspects(sourceFile);\n\n this.routesVersion++;\n }\n\n /**\n * Atomically replace every route owned by the given exact source-file keys.\n *\n * The installer mutates an isolated draft. Public reads keep seeing the old\n * live table across awaits, and a failed installer discards every draft\n * mutation. A successful installer swaps the whole draft in one synchronous\n * commit and invalidates the dev route registry exactly once.\n */\n public async replaceRoutesBySourceFiles<T>(\n sourceFiles: Iterable<string>,\n install: () => T | Promise<T>,\n ): Promise<T> {\n if (this.routeReplacementTransaction) {\n throw new Error(\"Cannot nest route replacement transactions\");\n }\n\n const removedSourceFiles = new Set(sourceFiles);\n\n this.routeReplacementTransaction = {\n routes: this.routes.filter((route) => !removedSourceFiles.has(route.sourceFile)),\n removedSourceFiles,\n addedRoutes: [],\n };\n\n try {\n const result = await install();\n const transaction = this.routeReplacementTransaction!;\n\n this.routes = transaction.routes;\n this.routeReplacementTransaction = undefined;\n\n // Diagnostic state follows the same commit boundary as the route table.\n // Added routes were deliberately not inspected while still speculative.\n for (const sourceFile of transaction.removedSourceFiles) {\n forgetPositionalHandlerSuspects(sourceFile);\n }\n\n const committedRoutes = new Set(transaction.routes);\n\n for (const route of transaction.addedRoutes) {\n if (committedRoutes.has(route)) {\n inspectHandlerSignature(route.handler, route);\n }\n }\n\n if (this.warnUnguardedRoutes) {\n reportUnguardedMutatingRoutes(\n transaction.addedRoutes.filter((route) => committedRoutes.has(route)),\n );\n }\n\n this.routesVersion++;\n\n return result;\n } catch (error) {\n this.routeReplacementTransaction = undefined;\n throw error;\n }\n }\n\n /**\n * Manage validation system for the given resource\n */\n private manageValidation(resource: RouteResource, method: \"create\" | \"update\" | \"patch\") {\n const handler = bindResourceHandler(resource, method);\n\n const methodValidation = resource?.validation?.[method];\n\n if (method === \"patch\") {\n handler.validation = methodValidation;\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n\n if (resource.validation?.patch) {\n handler.validation = merge(resource.validation.patch, handler.validation);\n }\n\n return handler;\n }\n\n if (!resource.validation || (!methodValidation && !resource.validation.all)) return handler;\n\n if (resource.validation.all) {\n const validationMethods = {\n all: resource?.validation?.all?.validate,\n [method]: methodValidation?.validate,\n };\n\n const validation: RequestHandlerValidation = {};\n\n if (resource.validation.all.schema || methodValidation?.schema) {\n if (!methodValidation?.schema && resource.validation.all.schema) {\n // Case 2: Only all.schema exists - clone it for this method\n validation.schema = resource.validation.all.schema;\n } else if (methodValidation?.schema && resource.validation.all.schema) {\n // Case 3: Both exist - merge them (all is base, method overrides)\n validation.schema = resource.validation.all.schema.merge(methodValidation.schema);\n } else if (methodValidation?.schema && !resource.validation.all.schema) {\n // Case 1: Only method schema exists - use it directly\n validation.schema = methodValidation.schema;\n }\n // Case 4: Neither exists - handled by outer if being false\n }\n\n if (validationMethods.all || validationMethods[method]) {\n validation.validate = async ({ request, response }: HttpContext) => {\n if (validationMethods.all) {\n const output = await validationMethods.all.call(resource, { request, response });\n\n if (output) return output;\n }\n\n if (validationMethods[method]) {\n return await validationMethods[method]?.call(resource, { request, response });\n }\n\n return;\n };\n }\n\n if (!isEmpty(validation)) {\n handler.validation = validation;\n }\n } else {\n handler.validation = resource.validation[method];\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n }\n\n return handler;\n }\n\n /**\n * Get all routes list\n */\n public list() {\n return this.routes;\n }\n\n /**\n * Return fresh browser-safe snapshots of named, non-page routes.\n *\n * Names are the registered names, including method suffixes. `all` stays\n * intact as route metadata; consumers decide whether their use supports it.\n */\n public getNamedApiRoutes(options: NamedApiRoutesOptions = {}): readonly NamedApiRoute[] {\n return Object.freeze(\n this.routes\n .filter((route) => !route.isPage && typeof route.name === \"string\" && route.name.length > 0)\n .map((route) => {\n const snapshot = { name: route.name!, path: route.path, method: route.method };\n const schema = route.handler?.responseSchema;\n const response = schema ? options.resolveResponse?.(schema, route) : undefined;\n\n // A route without a declared schema keeps exactly the three-key record.\n if (!response || Object.keys(response).length === 0) return Object.freeze(snapshot);\n\n return Object.freeze({ ...snapshot, response: Object.freeze({ ...response }) });\n }),\n );\n }\n\n /**\n * Number of routes currently registered on the singleton.\n *\n * Used as a readiness signal: a successful boot that ends up with zero\n * routes almost always means a route module failed to register silently\n * (see `withSourceFile`), so callers can surface that instead of letting\n * the whole surface 404.\n */\n public routeCount(): number {\n return this.routes.length;\n }\n\n /**\n * Register routes to the server\n */\n public scan(server: FastifyInstance) {\n // Every route is registered by the time we scan, so this is the first\n // moment the whole list can be reported at once — and it is still before a\n // single request is served.\n reportPositionalHandlerSuspects();\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n // Fastify automatically exposes HEAD for every GET route. When an app\n // declares its own HEAD route at the same path, suppress only that GET\n // route's implicit registration so the explicit handler owns HEAD,\n // regardless of declaration order.\n const explicitHeadPaths = new Set(\n this.routes\n .filter((route) => route.method.toLowerCase() === \"head\")\n .map((route) => route.path),\n );\n\n this.routes.forEach((route) => {\n const requestMethod = route.method.toLowerCase();\n const requestMethodFunction = server[requestMethod].bind(server);\n\n const options = {\n ...route.serverOptions,\n ...(requestMethod === \"get\" &&\n explicitHeadPaths.has(route.path) && { exposeHeadRoute: false }),\n config: {\n ...route.serverOptions?.config,\n // `undefined` keeps the global policy; `false` exempts the route.\n rateLimit: resolveRouteRateLimit(route),\n },\n };\n\n requestMethodFunction(\n route.path,\n options,\n async (baseRequest: FastifyRequest, reply: FastifyReply) => {\n const { output, response } = await this.handleRoute(route)(baseRequest, reply);\n\n return output || response.baseResponse;\n },\n );\n });\n\n this.registerStaticDirectories(server);\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Scan routes for the development server\n * Uses wildcard routing with find-my-way for HMR support\n */\n public scanDevServer(server: FastifyInstance) {\n // Same boot-time report as production `scan`. Routes reloaded later by HMR\n // are still recorded, but only surface on the next scan or via\n // `warlock doctor`.\n reportPositionalHandlerSuspects();\n\n // Development only: list mutating routes nobody guarded. Routes added by a\n // later HMR reload are reported when their replacement commits.\n this.warnUnguardedRoutes =\n configAccessor.key<boolean>(\"http.warnUnguardedRoutes\", true) !== false;\n if (this.warnUnguardedRoutes) {\n reportUnguardedMutatingRoutes(this.routes);\n }\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n let routeRegistry: RouteRegistry | undefined;\n let registryVersion = -1;\n\n const applyDevRateLimit = createDevRateLimiter(\n server,\n config.get(\"http.rateLimit.global\") !== false,\n );\n\n // Rebuilt when the route table changes rather than per request. Building it\n // inside the handler re-registered every route on every hit — and `all`\n // routes expand into seven registrations each. Keyed on `routesVersion`\n // rather than on the route count, so an HMR reload that swaps a route\n // without changing the count still invalidates.\n const resolveRouteRegistry = () => {\n if (routeRegistry && registryVersion === this.routesVersion) {\n return routeRegistry;\n }\n\n routeRegistry = new RouteRegistry();\n\n routeRegistry.register(this.routes);\n\n registryVersion = this.routesVersion;\n\n return routeRegistry;\n };\n\n // Matching happens here, in Fastify's own onRequest phase, so a route's\n // `serverOptions.onRequest` still runs BEFORE body parsing. Production\n // `scan()` gets that from per-route registration; the wildcard dispatcher\n // has no per-route slot, so without this the hook silently never runs.\n server.addHook(\n \"onRequest\",\n async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n // Only requests Fastify routed to the dev wildcard belong to the app's\n // router. A plugin's own route (devtools' `/__warlock/api/requests/:id`)\n // must keep its params even when an app catch-all matches the URL too.\n if (fastifyRequest.routeOptions.url !== \"*\") {\n return undefined;\n }\n\n const match = resolveRouteRegistry().find(fastifyRequest.method, fastifyRequest.url);\n\n if (!match) {\n return undefined;\n }\n\n (fastifyRequest as DevDispatchRequest).matchedDevRoute = match;\n\n fastifyRequest.params = match.params;\n\n // Same slot production gives it: the limiter runs first in onRequest,\n // ahead of the route's own hooks.\n await applyDevRateLimit(match.route, fastifyRequest, fastifyReply);\n\n if (fastifyReply.sent) {\n return fastifyReply;\n }\n\n return runRouteHooks(match.route, \"onRequest\", fastifyRequest, fastifyReply);\n },\n );\n\n for (const phase of FORWARDED_ROUTE_PHASES.filter((name) => name !== \"onRequest\")) {\n server.addHook(phase, async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n if (!match) {\n return undefined;\n }\n\n return runRouteHooks(match.route, phase, fastifyRequest, fastifyReply);\n });\n }\n\n // Shared handler for wildcard routing\n const wildcardHandler = async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n // No match found - return 404\n if (!match) {\n return fastifyReply\n .code(404)\n .send(buildNotFoundBody(fastifyRequest.method, fastifyRequest.url));\n }\n\n try {\n // Call the matched route handler\n const { output, response } = await this.handleRoute(match.route)(\n fastifyRequest,\n fastifyReply,\n );\n\n return output || response.baseResponse;\n } catch (error) {\n log.error(\"router\", \"dev-dispatch\", error as Error, {\n method: fastifyRequest.method,\n url: buildRequestLogSnapshot({\n id: fastifyRequest.id,\n method: fastifyRequest.method,\n url: fastifyRequest.url,\n route: match.route,\n }).url,\n });\n\n throw error;\n }\n };\n\n // Every verb production can register. Fastify's implicit HEAD for the GET\n // wildcard is switched off so the HEAD wildcard owns it (the registry falls\n // back to the GET route, exactly as production's implicit HEAD does).\n // `@fastify/cors` registers its own OPTIONS \"*\" catch-all whenever\n // preflight is on. Use the plugin's options as well as hasRoute so this\n // dispatcher works both after HTTP plugin boot and before queued plugins.\n const corsOwnsPreflight = buildCorsOptions().preflight !== false;\n\n for (const method of DEV_DISPATCH_METHODS) {\n if (\n method === \"OPTIONS\" &&\n (corsOwnsPreflight || server.hasRoute({ method: \"OPTIONS\", url: \"*\" }))\n ) {\n continue;\n }\n\n server.route({\n method,\n url: \"*\",\n ...(method === \"GET\" && { exposeHeadRoute: false }),\n // The dispatcher limits each matched route itself (see\n // `createDevRateLimiter`), so the plugin must not limit the wildcard:\n // that would count exempt routes and unmatched URLs too.\n config: { rateLimit: false },\n handler: wildcardHandler,\n });\n }\n\n this.registerStaticDirectories(server);\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Get the route path for the given route name\n */\n public getRoute(name: string, params: Record<string, any> = {}) {\n const route = this.routes.find((route) => route.name === name);\n\n if (!route) {\n throw new WarlockError(\"WL3003\", `Route name \"${name}\" not found`);\n }\n\n const used = new Set<string>();\n\n const path = route.path.replace(/:([A-Za-z0-9_]+)(\\?)?/g, (_match, key: string, optional) => {\n const value = params[key];\n\n if (value === undefined || value === null) {\n if (optional) return \"\";\n\n throw new WarlockError(\"WL3004\", `Route \"${name}\" is missing the \"${key}\" param`);\n }\n\n used.add(key);\n\n return encodeURIComponent(String(value));\n });\n\n const query = Object.keys(params)\n .filter((key) => !used.has(key) && params[key] !== undefined && params[key] !== null)\n .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(String(params[key]))}`)\n .join(\"&\");\n\n return query ? `${path}?${query}` : path;\n }\n\n /**\n * Handle the given route\n */\n private handleRoute(route: Route) {\n return async (fastifyRequest: FastifyRequest, fastifyResponse: FastifyReply) => {\n const request = new Request();\n const response = new Response();\n response.setResponse(fastifyResponse);\n request.response = response;\n\n response.request = request;\n\n // \"route.match\" tracing phase: the pattern is\n // already known here (`route.path`), so this brackets the cost of\n // stamping the request/route onto the `Request` instance rather than\n // route-registry matching itself, which happens upstream of this\n // function for both the production `scan()` path and the dev wildcard\n // dispatcher (both funnel into `handleRoute`).\n const tracingEnabled = isTracingEnabled();\n const routeMatchStartedAt = tracingEnabled ? performance.now() : 0;\n\n request.setRequest(fastifyRequest).setRoute(route);\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"route.match\",\n durationMs: performance.now() - routeMatchStartedAt,\n attrs: { route: route.path },\n });\n }\n\n /*\n Both ends of the entry, not just the start — see\n `log-request-lifecycle.ts`. A start line on its own made a hung request\n and an instant one look identical, and the completion line is what makes\n a MISSING one legible as a hang.\n */\n const result = await logRequestLifecycle(\n {\n info: (entry) => log.info(entry),\n warn: (entry) => log.warn(entry),\n error: (entry) => log.error(entry),\n now: () => performance.now(),\n },\n {\n module: \"route\",\n action: describeRouteForLog(route.method, route.path),\n requestId: request.id,\n // A bounded snapshot, built once with the route's logging policy\n // applied — never the Request/Response instances, whose native\n // request, reply and URL graphs would reach every log channel.\n context: { request: request.toLogSnapshot() },\n request,\n // Read after the run: the status is decided during the request.\n statusCode: () => fastifyResponse.statusCode,\n },\n () => request.execute(),\n );\n\n // A handler may return a plain object (`ReturnedResponse`). Route it\n // through `Response.send` so status, events and hooks apply, exactly as\n // middleware outputs already do.\n let output = result;\n\n if (\n output !== undefined &&\n output !== null &&\n !(output instanceof Response) &&\n (output as unknown) !== fastifyResponse\n ) {\n output = await response.send(output);\n }\n\n return {\n output,\n response,\n request,\n };\n };\n }\n}\n\nexport const router = Router.getInstance();\n\ncontainer.set(\"router\", router);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAM,yBAAyB;CAAC;CAAa;CAAiB;AAAY;AAc1E,SAAS,WACP,MACsB;CACtB,IAAI,CAAC,MACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;AAC3C;;;;;;;;AASA,eAAe,cACb,OACA,OACA,SACA,OACA;CACA,MAAM,QAAQ,WACZ,M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A,MAAa,SAAS,OAAO,YAAY;AAEzC,UAAU,IAAI,UAAU,MAAM"}
1
+ {"version":3,"file":"router.mjs","names":["configAccessor","config"],"sources":["../../../../../../../../packages/core/src/router/router.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport proxy, { type FastifyHttpProxyOptions } from \"@fastify/http-proxy\";\nimport { WarlockError } from \"../errors/warlock-error\";\nimport type { FastifyStaticOptions } from \"@fastify/static\";\nimport { ltrim, merge, toCamelCase, trim } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport { log } from \"@warlock.js/logger\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport { container } from \"../container\";\nimport { registerLazyStatic } from \"../http/lazy-static\";\nimport { buildCorsOptions } from \"../http/build-cors-options\";\nimport { Request } from \"../http/request\";\nimport { buildRequestLogSnapshot } from \"../http/request-log-snapshot\";\nimport { Response } from \"../http/response\";\nimport { type FastifyInstance } from \"../http/server\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../http/tracing\";\nimport { describeRouteForLog } from \"./describe-route-for-log\";\nimport { logRequestLifecycle } from \"./log-request-lifecycle\";\nimport {\n forgetPositionalHandlerSuspects,\n inspectHandlerSignature,\n reportPositionalHandlerSuspects,\n} from \"./positional-handler-diagnostics\";\nimport { isRequiredGuardRoute, reportUnguardedMutatingRoutes } from \"./unguarded-route-diagnostics\";\nimport { config as configAccessor } from \"../config/config-getter\";\nimport { normalizeRoutePath } from \"./normalize-route-path\";\nimport { RouteBuilder } from \"./route-builder\";\nimport { resolveRouteRateLimit, resolveStaticRateLimit } from \"./resolve-route-rate-limit\";\nimport { RouteNameTakenError } from \"./route-name-taken-error\";\nimport { DEV_DISPATCH_METHODS, buildNotFoundBody, createDevRateLimiter } from \"./dev-dispatch\";\nimport { RouteRegistry } from \"./route-registry\";\nimport { routeNameMethodSuffix } from \"./route-name-method-suffix\";\nimport type {\n GroupedRoutesOptions,\n HttpContext,\n NamedApiRoute,\n NamedApiRoutesOptions,\n RequestHandler,\n RequestHandlerType,\n RequestHandlerValidation,\n ResourceMethod,\n Route,\n RouteOptions,\n RouteResource,\n RouterGroupCallback,\n RouterStacks,\n StaticMountOptions,\n} from \"./types\";\n\n/**\n * A Fastify lifecycle hook as it may be declared in a route's `serverOptions`.\n * Fastify accepts a single hook or an array in either position.\n */\ntype RouteLifecycleHook = (\n request: FastifyRequest,\n reply: FastifyReply,\n) => unknown | Promise<unknown>;\n\n/**\n * The pre-handler phases the dev server forwards from a route's `serverOptions`.\n *\n * These are the admission-control phases and they share the `(request, reply)`\n * signature. `preParsing` is deliberately absent — it must return the payload\n * stream, so forwarding it generically would corrupt the body rather than\n * guard it. `bodyLimit` cannot be forwarded at all; Fastify reads it at\n * registration time and no hook can bound a body already being parsed.\n */\nconst FORWARDED_ROUTE_PHASES = [\"onRequest\", \"preValidation\", \"preHandler\"] as const;\n\ntype ForwardedRoutePhase = (typeof FORWARDED_ROUTE_PHASES)[number];\n\n/**\n * The route the dev dispatcher matched, stashed on the request so the hooks and\n * the wildcard handler all act on one match rather than each matching again.\n */\ntype DevMatchedRoute = { route: Route; params: Record<string, string> };\n\ntype DevDispatchRequest = FastifyRequest & {\n matchedDevRoute?: DevMatchedRoute;\n};\n\nfunction toHookList(\n hook: RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n): RouteLifecycleHook[] {\n if (!hook) {\n return [];\n }\n\n return Array.isArray(hook) ? hook : [hook];\n}\n\n/**\n * Run a matched route's hooks for one phase.\n *\n * Returning the reply is how an async Fastify hook signals that it has answered\n * the request; the chain must stop there, so the value is propagated rather\n * than discarded.\n */\nasync function runRouteHooks(\n route: Route,\n phase: ForwardedRoutePhase,\n request: FastifyRequest,\n reply: FastifyReply,\n) {\n const hooks = toHookList(\n route.serverOptions?.[phase] as RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n );\n\n for (const hook of hooks) {\n const outcome = await hook(request, reply);\n\n if (outcome === reply) {\n return reply;\n }\n }\n\n return undefined;\n}\n\n/**\n * Bound functions do not inherit static properties, so the handler metadata that\n * documentation and typings read (`responseSchema`) is copied onto the bound copy.\n */\nfunction copyResponseSchema(source: unknown, target: RequestHandler): void {\n const responseSchema = (source as RequestHandler | undefined)?.responseSchema;\n\n if (responseSchema) {\n target.responseSchema = responseSchema;\n }\n}\n\n/**\n * Bind a restful resource method to its resource, keeping its `responseSchema`.\n */\nfunction bindResourceHandler(\n resource: RouteResource,\n method: ResourceMethod | \"bulkDelete\",\n): RequestHandler {\n const source = resource[method];\n const handler = source?.bind(resource) as RequestHandler;\n\n copyResponseSchema(source, handler);\n\n return handler;\n}\n\n/**\n * Describe one claimant of a route name, for the duplicate-name error.\n *\n * `warlock dev` registers SSR page routes on the same router as API routes, so\n * the two share a single route-name namespace and collide across kinds. The\n * error is only actionable if it says which claimant is which, so `isPage` —\n * the router's only route-kind discriminator — is what separates them here.\n *\n * `sourceFile` is stamped only on routes registered through `withSourceFile`.\n * Routes registered without that scope have no owner, so say the source is\n * unknown rather than printing an empty string.\n */\nfunction describeRouteClaimant(route: Route) {\n const type = route.isPage ? \"page route\" : \"API route\";\n const source = route.sourceFile ? `declared in ${route.sourceFile}` : \"source file unknown\";\n\n return `${type} ${route.method} ${route.path} (${source})`;\n}\n\nexport class Router {\n /**\n * Routes list\n */\n private routes: Route[] = [];\n\n /**\n * Bumped on every mutation of {@link routes}.\n *\n * The dev dispatcher caches a route registry and needs to know when it is\n * stale. Comparing `routes.length` would miss an HMR reload that replaces a\n * route without changing the count — the registry would then keep matching\n * paths that no longer exist. A version counter cannot miss that.\n */\n private routesVersion = 0;\n\n /**\n * In-progress atomic replacement, when one exists. Reads continue to use\n * {@link routes}; mutations and collision checks use this isolated draft.\n */\n private routeReplacementTransaction?: {\n routes: Route[];\n removedSourceFiles: Set<string>;\n addedRoutes: Route[];\n };\n\n /**\n * Set by the dev server: whether to warn about mutating routes that have no\n * auth middleware and no `public: true` (`http.warnUnguardedRoutes`).\n */\n private warnUnguardedRoutes = false;\n\n /**\n * Router Instance\n */\n private static instance: Router;\n\n /**\n * Static paths\n */\n protected staticDirectories: {\n options: FastifyStaticOptions;\n rateLimit: StaticMountOptions[\"rateLimit\"];\n }[] = [];\n\n /**\n * Event listeners\n */\n protected eventListeners: Record<string, ((router: Router, server: FastifyInstance) => void)[]> =\n {};\n\n /**\n * Stacks\n * Stacks will be used for grouping routes to add prefix, name or middleware\n */\n protected stacks: RouterStacks = {\n prefix: [],\n name: [],\n middleware: [],\n };\n\n /**\n * Get router instance\n */\n public static getInstance() {\n if (!Router.instance) {\n Router.instance = new Router();\n }\n\n return Router.instance;\n }\n\n private constructor() {\n //\n }\n\n /**\n * Listen to router before scan\n */\n public beforeScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.beforeScan = [...(this.eventListeners.beforeScan || []), callback];\n\n return this;\n }\n\n /**\n * Listen to router after scanning\n */\n public afterScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.afterScanning = [...(this.eventListeners.afterScanning || []), callback];\n\n return this;\n }\n\n /**\n * Redirect path to another path\n */\n public redirect(from: string, to: string, redirectMode: \"temporary\" | \"permanent\" = \"temporary\") {\n return this.get(from, ({ response }) => {\n response.redirect(to, redirectMode === \"temporary\" ? 302 : 301);\n });\n }\n\n /**\n * Serve a static folder.\n *\n * Static mounts are exempt from the global rate limiter by default; set\n * `http.rateLimit.staticFiles: true` to count every mount, or pass\n * `{ rateLimit }` to decide for this mount alone: `true` counts it against\n * the global limiter, `false` exempts it, and an object gives it its own\n * limit and bucket.\n *\n * @example\n * router.directory({ root: rootPath(\"docs\"), prefix: \"/docs/\" });\n * router.directory({ root: rootPath(\"exports\"), prefix: \"/exports/\" }, { rateLimit: true });\n */\n public directory(options: FastifyStaticOptions, mountOptions: StaticMountOptions = {}) {\n this.staticDirectories.push({ options, rateLimit: mountOptions.rateLimit });\n\n return this;\n }\n\n /** Declare static routes at boot; load the upstream sender on the first file request. */\n protected registerStaticDirectories(server: FastifyInstance) {\n for (const directory of this.staticDirectories) {\n registerLazyStatic(\n server,\n { ...directory.options, decorateReply: false },\n { rateLimit: resolveStaticRateLimit(directory.rateLimit) },\n );\n }\n }\n\n /**\n * Register a GET route that serves a static file. Like `directory()`, it is\n * exempt from the global rate limiter unless `http.rateLimit.staticFiles`\n * or its own `rateLimit` says otherwise.\n */\n protected addStaticFileRoute(\n path: string,\n handler: RequestHandler,\n mountOptions: StaticMountOptions = {},\n ) {\n this.get(\n path,\n handler,\n mountOptions.rateLimit === undefined ? {} : { rateLimit: mountOptions.rateLimit },\n );\n\n const routes = this.routeReplacementTransaction?.routes ?? this.routes;\n const route = routes[routes.length - 1];\n\n if (route) route.$staticFile = true;\n\n return this;\n }\n\n /**\n * Serve file\n */\n public file(\n path: string,\n location: string,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n return this.addStaticFileRoute(\n path,\n ({ response }) => {\n response.sendFile(location, cacheTime);\n },\n mountOptions,\n );\n }\n\n /**\n * Serve cached file, it will cache the file to 1 year by default\n */\n public cachedFile(\n path: string,\n location: string,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n return this.addStaticFileRoute(\n path,\n ({ response }) => {\n response.sendCachedFile(location, cacheTime);\n },\n mountOptions,\n );\n }\n\n /**\n * Serve list of files\n */\n public files(\n files: Record<string, string>,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n for (const [path, location] of Object.entries(files)) {\n this.file(path, location, cacheTime, mountOptions);\n }\n }\n\n /**\n * Serve list of cached files, it will cache the file to 1 year by default\n */\n public cachedFiles(\n files: Record<string, string>,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n for (const [path, location] of Object.entries(files)) {\n this.cachedFile(path, location, cacheTime, mountOptions);\n }\n }\n\n /**\n * Add proxy route\n */\n public proxy(\n path: string,\n baseUrl: string,\n options?: Omit<FastifyHttpProxyOptions, \"prefix\" | \"upstream\">,\n ): this;\n public proxy(options: FastifyHttpProxyOptions): this;\n public proxy(...args: any[]) {\n this.beforeScanning((_router, server) => {\n if (args.length === 1) {\n server.register(proxy, args[0]);\n } else {\n server.register(proxy, {\n prefix: args[0],\n upstream: args[1],\n ...args[2],\n });\n }\n });\n\n return this;\n }\n\n /**\n * Add route to routes list\n */\n public add(\n method: Route[\"method\"],\n path: string | string[],\n handler: RequestHandlerType,\n options: RouteOptions = {},\n ) {\n if (Array.isArray(path)) {\n path.forEach((p) => this.add(method, p, handler, options));\n return this;\n }\n\n const prefix = this.stacks.prefix.reduce((path, prefix) => {\n return normalizeRoutePath(path, prefix);\n }, \"\");\n\n const name = this.stacks.name.reduceRight(\n (name, prefixName) => {\n return trim(prefixName + \".\" + name, \".\");\n },\n options.name || trim(path.replace(/\\//g, \".\"), \".\"),\n );\n\n // The one place a route path becomes canonical. `normalizeRoutePath` is\n // exported so the build-time page-route manifest can produce the very same\n // string without registering anything.\n path = normalizeRoutePath(prefix, path);\n\n const middlewarePrecedence = options.middlewarePrecedence || \"after\";\n\n // Work on a copy: the caller may reuse one options object for several\n // routes, and merging the group stack into it would compound per route.\n options = { ...options };\n\n if (middlewarePrecedence === \"before\") {\n options.middleware = [...(options.middleware || []), ...this.stacks.middleware];\n } else {\n options.middleware = [...this.stacks.middleware, ...(options.middleware || [])];\n }\n\n // An enclosing `router.group({ public: true })` makes the route public\n // unless it says otherwise itself.\n if (options.public === undefined && (this.stacks.public ?? 0) > 0) {\n options.public = true;\n }\n\n // An enclosing `router.group({ sites })` scopes the route's browser table\n // entry unless the route names its own sites.\n const groupSites = this.stacks.sites?.at(-1);\n\n if (options.sites === undefined && groupSites !== undefined) {\n options.sites = groupSites;\n }\n\n if (Array.isArray(handler)) {\n const [controller, action] = handler;\n\n if (typeof controller[action] !== \"function\") {\n throw new WarlockError(\n \"WL3002\",\n `Invalid controller action \"${action}\" for controller \"${controller.constructor.name}\"`,\n );\n }\n\n handler = controller[action].bind(controller) as RequestHandler;\n copyResponseSchema(controller[action], handler);\n\n if (!handler.validation) {\n handler.validation = {};\n if (controller[`${action}ValidationSchema`]) {\n handler.validation.schema = controller[`${action}ValidationSchema`]();\n }\n\n if (controller[`${action}Validate`]) {\n handler.validation.validate = controller[`${action}Validate`];\n }\n }\n }\n\n const routeData: Route = {\n method,\n path,\n handler,\n ...options,\n name,\n rateLimit: options.rateLimit,\n $prefix: prefix || \"/\",\n // it must be a new array to avoid modifying the original array\n $prefixStack: [...this.stacks.prefix],\n // Inject source file from stacks if set\n sourceFile: this.stacks.sourceFile || \"\",\n };\n\n const routes = this.routeReplacementTransaction?.routes ?? this.routes;\n\n if (routeData.name) {\n // check if the name exists\n const route = routes.find((route) => route.name === routeData.name);\n\n if (route) {\n // check again if the route name exists with the same method\n if (route.method === routeData.method) {\n throw new RouteNameTakenError(\n routeData.name,\n `Route name \"${routeData.name}\" is already taken.\\n` +\n ` already registered: ${describeRouteClaimant(route)}\\n` +\n ` now being added: ${describeRouteClaimant(routeData)}\\n` +\n `Pages and API routes share one route-name namespace, so a name can only be ` +\n `claimed once. Rename one of them via the \"name\" route option.`,\n );\n } else {\n routeData.name += routeNameMethodSuffix(routeData.method);\n }\n }\n }\n\n // Registration-time only — nothing here runs per request. Suspects are\n // collected now and reported together at boot (see `scan`), so a route file\n // written against v4 produces one legible list instead of a mystery 500 per\n // request. Recorded after the collision check so a route that never lands\n // is never reported.\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.addedRoutes.push(routeData);\n } else {\n inspectHandlerSignature(routeData.handler, routeData);\n }\n\n routes.push(routeData);\n\n if (!this.routeReplacementTransaction) {\n this.routesVersion++;\n }\n\n return this;\n }\n\n /**\n * Add a request that accepts all methods\n */\n public any(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"all\" as Route[\"method\"], path, handler, options);\n }\n\n /**\n * Add get request method\n */\n public get(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"GET\", path, handler, options);\n }\n\n /**\n * Add post request method\n */\n public post(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"POST\", path, handler, options);\n }\n\n /**\n * Add put request method\n */\n public put(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PUT\", path, handler, options);\n }\n\n /**\n * Add delete request method\n */\n public delete(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"DELETE\", path, handler, options);\n }\n\n /**\n * Add patch request method\n */\n public patch(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PATCH\", path, handler, options);\n }\n\n /**\n * Add head request method\n */\n public head(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"HEAD\", path, handler, options);\n }\n\n /**\n * Add options request method\n */\n public options(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"OPTIONS\", path, handler, options);\n }\n\n /**\n * Get a chainable route builder for the same route path\n */\n public route(path: string, options: RouteOptions = {}) {\n return new RouteBuilder(this, path, options);\n }\n\n /**\n * Add full restful resource routes\n * This method will generate the following routes:\n * 1. GET /path: list all resources\n * 2. GET /path/:id: get a single resource\n * 3. POST /path: create a new resource\n * 4. PUT /path/:id: update a resource\n * 5. DELETE /path/:id: delete a resource\n * 6. PATCH /path/:id: update a resource partially\n */\n public restfulResource(\n path: string,\n resource: RouteResource,\n options: RouteOptions & {\n only?: ResourceMethod[];\n except?: ResourceMethod[];\n replace?: Partial<Record<ResourceMethod, RequestHandler>> & {\n bulkDelete?: RequestHandler;\n };\n } = {},\n ) {\n // Derive the base resource name from the path before the group below\n // clears it for use as the routes' relative path. `options.name`, when\n // given, replaces the path-derived name entirely (see the explicit\n // `name` passed to `group()`) rather than composing with it.\n const baseResourceName = options.name || toCamelCase(ltrim(path, \"/\"));\n\n return this.group({ prefix: path, name: baseResourceName }, () => {\n const path = \"\";\n\n // clone the resource so we don't mess up with it\n const routeResource = resource;\n\n const isAcceptableResource = (type: ResourceMethod) => {\n return Boolean(\n // check if the route is not excluded\n (!options.except || !options.except.includes(type)) &&\n // check if the only option is set and the route is included\n (!options.only || options.only.includes(type)),\n );\n };\n\n if (routeResource.list && isAcceptableResource(\"list\")) {\n this.get(path, options.replace?.list || bindResourceHandler(routeResource, \"list\"), {\n ...options,\n name: \"list\",\n restful: true,\n });\n }\n\n if (routeResource.get && isAcceptableResource(\"get\")) {\n this.get(path + \"/:id\", options.replace?.get || bindResourceHandler(routeResource, \"get\"), {\n ...options,\n name: \"single\",\n restful: true,\n });\n }\n\n if (routeResource.create && isAcceptableResource(\"create\")) {\n const handler = options.replace?.create || this.manageValidation(routeResource, \"create\");\n\n this.post(path, handler, {\n ...options,\n name: \"create\",\n restful: true,\n });\n }\n\n if (routeResource.update && isAcceptableResource(\"update\")) {\n const handler = options.replace?.update || this.manageValidation(routeResource, \"update\");\n\n this.put(path + \"/:id\", handler, {\n ...options,\n name: \"update\",\n restful: true,\n });\n }\n\n if (routeResource.patch && isAcceptableResource(\"patch\")) {\n const handler = options.replace?.patch || this.manageValidation(routeResource, \"patch\");\n\n this.patch(path + \"/:id\", handler, {\n ...options,\n name: \"patch\",\n restful: true,\n });\n }\n\n if (routeResource.delete && isAcceptableResource(\"delete\")) {\n this.delete(\n path + \"/:id\",\n options.replace?.delete || bindResourceHandler(routeResource, \"delete\"),\n {\n ...options,\n name: \"delete\",\n restful: true,\n },\n );\n }\n\n if (routeResource.bulkDelete && isAcceptableResource(\"delete\")) {\n this.delete(\n path,\n options.replace?.bulkDelete || bindResourceHandler(routeResource, \"bulkDelete\"),\n {\n ...options,\n name: \"bulkDelete\",\n restful: true,\n },\n );\n }\n\n return this;\n });\n }\n\n /**\n * Group routes with options\n */\n public group(options: GroupedRoutesOptions, callback: RouterGroupCallback) {\n const {\n prefix,\n // name must always be defined because\n // if there are multiple groups without name\n // they might generate the same route name\n // thus causing an error\n // in this case we need always to make sure that\n // the name is always defined.\n name = prefix ? trim(prefix.replace(/\\//g, \".\"), \".\") : undefined,\n middleware,\n public: isPublic,\n sites,\n } = options;\n\n if (sites) {\n (this.stacks.sites ??= []).push(sites);\n }\n\n if (isPublic) {\n this.stacks.public = (this.stacks.public ?? 0) + 1;\n }\n\n if (prefix) {\n this.stacks.prefix.push(prefix);\n }\n\n if (name) {\n this.stacks.name.push(name);\n }\n\n if (middleware) {\n this.stacks.middleware.push(...middleware);\n }\n\n try {\n callback();\n } finally {\n // Always pop/splice this group's stacks, even if the callback throws,\n // so a throwing group never leaks state onto the process-global singleton.\n if (prefix) {\n this.stacks.prefix.pop();\n }\n\n if (name) {\n this.stacks.name.pop();\n }\n\n if (middleware) {\n this.stacks.middleware.splice(\n this.stacks.middleware.length - middleware.length,\n middleware.length,\n );\n }\n if (isPublic) {\n this.stacks.public = (this.stacks.public ?? 1) - 1;\n }\n\n if (sites) {\n this.stacks.sites?.pop();\n }\n }\n\n return this;\n }\n\n /**\n * Add prefix to all routes in the given callback\n */\n public prefix(prefix: string, callback: () => void) {\n return this.group({ prefix }, callback);\n }\n\n /**\n * Add API version prefix to all routes in the given callback\n * Automatically formats the version as /v{version}\n * @example\n * router.version(\"1\", () => {\n * router.get(\"/users\", getUsersV1); // /v1/users\n * });\n *\n * router.version(\"2\", () => {\n * router.get(\"/users\", getUsersV2); // /v2/users\n * });\n */\n public version(version: string | number, callback: () => void) {\n return this.prefix(`/v${version}`, callback);\n }\n\n /**\n * Wrap route additions with a source file path\n * Used for tracking which routes come from which file (for HMR)\n * @param sourceFile Relative path to the source file (e.g., \"src/app/users/routes.ts\")\n * @param callback Function that adds routes (will have sourceFile injected)\n */\n public async withSourceFile<T = any>(\n sourceFile: string,\n callback: () => T | Promise<T>,\n ): Promise<T | undefined> {\n // Set source file in stacks\n this.stacks.sourceFile = sourceFile;\n\n try {\n // Execute callback (routes added here will have sourceFile injected)\n return await callback();\n } catch (error) {\n // Log loudly, then RETHROW. Swallowing here silently dropped a whole\n // route file (duplicate name, invalid action, import error) so the\n // surface 404'd with no boot error. The caller decides what a throw\n // means: at boot it aborts the boot, during HMR the dev server's\n // batch-reload handler catches it, prints it, and keeps serving.\n log.error({\n module: \"router\",\n action: \"registerRoutes\",\n message: `Failed to register routes from \"${sourceFile}\"`,\n context: { sourceFile, error },\n });\n\n throw error;\n } finally {\n // Always clear source file from stacks so a throwing file never leaks\n // its sourceFile onto the process-global singleton.\n delete this.stacks.sourceFile;\n }\n }\n\n /**\n * Remove all routes that belong to a specific source file\n * Used when reloading routes files via HMR\n * @param sourceFile Relative path to the source file\n */\n public removeRoutesBySourceFile(sourceFile: string): void {\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.routes = this.routeReplacementTransaction.routes.filter(\n (route) => route.sourceFile !== sourceFile,\n );\n this.routeReplacementTransaction.removedSourceFiles.add(sourceFile);\n return;\n }\n\n this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);\n\n // Keep the signature diagnostics in step, so a reload that fixes a handler\n // stops reporting the version it replaced.\n forgetPositionalHandlerSuspects(sourceFile);\n\n this.routesVersion++;\n }\n\n /**\n * Atomically replace every route owned by the given exact source-file keys.\n *\n * The installer mutates an isolated draft. Public reads keep seeing the old\n * live table across awaits, and a failed installer discards every draft\n * mutation. A successful installer swaps the whole draft in one synchronous\n * commit and invalidates the dev route registry exactly once.\n */\n public async replaceRoutesBySourceFiles<T>(\n sourceFiles: Iterable<string>,\n install: () => T | Promise<T>,\n ): Promise<T> {\n if (this.routeReplacementTransaction) {\n throw new Error(\"Cannot nest route replacement transactions\");\n }\n\n const removedSourceFiles = new Set(sourceFiles);\n\n this.routeReplacementTransaction = {\n routes: this.routes.filter((route) => !removedSourceFiles.has(route.sourceFile)),\n removedSourceFiles,\n addedRoutes: [],\n };\n\n try {\n const result = await install();\n const transaction = this.routeReplacementTransaction!;\n\n this.routes = transaction.routes;\n this.routeReplacementTransaction = undefined;\n\n // Diagnostic state follows the same commit boundary as the route table.\n // Added routes were deliberately not inspected while still speculative.\n for (const sourceFile of transaction.removedSourceFiles) {\n forgetPositionalHandlerSuspects(sourceFile);\n }\n\n const committedRoutes = new Set(transaction.routes);\n\n for (const route of transaction.addedRoutes) {\n if (committedRoutes.has(route)) {\n inspectHandlerSignature(route.handler, route);\n }\n }\n\n if (this.warnUnguardedRoutes) {\n reportUnguardedMutatingRoutes(\n transaction.addedRoutes.filter((route) => committedRoutes.has(route)),\n );\n }\n\n this.routesVersion++;\n\n return result;\n } catch (error) {\n this.routeReplacementTransaction = undefined;\n throw error;\n }\n }\n\n /**\n * Manage validation system for the given resource\n */\n private manageValidation(resource: RouteResource, method: \"create\" | \"update\" | \"patch\") {\n const handler = bindResourceHandler(resource, method);\n\n const methodValidation = resource?.validation?.[method];\n\n if (method === \"patch\") {\n handler.validation = methodValidation;\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n\n if (resource.validation?.patch) {\n handler.validation = merge(resource.validation.patch, handler.validation);\n }\n\n return handler;\n }\n\n if (!resource.validation || (!methodValidation && !resource.validation.all)) return handler;\n\n if (resource.validation.all) {\n const validationMethods = {\n all: resource?.validation?.all?.validate,\n [method]: methodValidation?.validate,\n };\n\n const validation: RequestHandlerValidation = {};\n\n if (resource.validation.all.schema || methodValidation?.schema) {\n if (!methodValidation?.schema && resource.validation.all.schema) {\n // Case 2: Only all.schema exists - clone it for this method\n validation.schema = resource.validation.all.schema;\n } else if (methodValidation?.schema && resource.validation.all.schema) {\n // Case 3: Both exist - merge them (all is base, method overrides)\n validation.schema = resource.validation.all.schema.merge(methodValidation.schema);\n } else if (methodValidation?.schema && !resource.validation.all.schema) {\n // Case 1: Only method schema exists - use it directly\n validation.schema = methodValidation.schema;\n }\n // Case 4: Neither exists - handled by outer if being false\n }\n\n if (validationMethods.all || validationMethods[method]) {\n validation.validate = async ({ request, response }: HttpContext) => {\n if (validationMethods.all) {\n const output = await validationMethods.all.call(resource, { request, response });\n\n if (output) return output;\n }\n\n if (validationMethods[method]) {\n return await validationMethods[method]?.call(resource, { request, response });\n }\n\n return;\n };\n }\n\n if (!isEmpty(validation)) {\n handler.validation = validation;\n }\n } else {\n handler.validation = resource.validation[method];\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n }\n\n return handler;\n }\n\n /**\n * Get all routes list\n */\n public list() {\n return this.routes;\n }\n\n /**\n * Return fresh browser-safe snapshots of named, non-page routes.\n *\n * Names are the registered names, including method suffixes. `all` stays\n * intact as route metadata; consumers decide whether their use supports it.\n * A route that opted out with `clientVisible: false` carries that flag so\n * browser-facing consumers can leave it out. `sites` is present only on a\n * route that declared some, and `guarded: true` only on a route with an auth\n * guard in its middleware chain (group middleware included).\n */\n public getNamedApiRoutes(options: NamedApiRoutesOptions = {}): readonly NamedApiRoute[] {\n return Object.freeze(\n this.routes\n .filter((route) => !route.isPage && typeof route.name === \"string\" && route.name.length > 0)\n .map((route) => {\n // `clientVisible: false` is the only key this flag ever adds, and it is\n // present only then: the common snapshot keeps its exact shape.\n const snapshot = {\n name: route.name!,\n path: route.path,\n method: route.method,\n ...(route.clientVisible === false ? { clientVisible: false as const } : {}),\n ...(route.sites === undefined ? {} : { sites: Object.freeze([...route.sites]) }),\n ...(isRequiredGuardRoute(route) ? { guarded: true as const } : {}),\n };\n const schema = route.handler?.responseSchema;\n const response = schema ? options.resolveResponse?.(schema, route) : undefined;\n\n // A route without a declared schema keeps exactly the three-key record.\n if (!response || Object.keys(response).length === 0) return Object.freeze(snapshot);\n\n return Object.freeze({ ...snapshot, response: Object.freeze({ ...response }) });\n }),\n );\n }\n\n /**\n * Number of routes currently registered on the singleton.\n *\n * Used as a readiness signal: a successful boot that ends up with zero\n * routes almost always means a route module failed to register silently\n * (see `withSourceFile`), so callers can surface that instead of letting\n * the whole surface 404.\n */\n public routeCount(): number {\n return this.routes.length;\n }\n\n /**\n * Register routes to the server\n */\n public scan(server: FastifyInstance) {\n // Every route is registered by the time we scan, so this is the first\n // moment the whole list can be reported at once — and it is still before a\n // single request is served.\n reportPositionalHandlerSuspects();\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n // Fastify automatically exposes HEAD for every GET route. When an app\n // declares its own HEAD route at the same path, suppress only that GET\n // route's implicit registration so the explicit handler owns HEAD,\n // regardless of declaration order.\n const explicitHeadPaths = new Set(\n this.routes\n .filter((route) => route.method.toLowerCase() === \"head\")\n .map((route) => route.path),\n );\n\n this.routes.forEach((route) => {\n const requestMethod = route.method.toLowerCase();\n const requestMethodFunction = server[requestMethod].bind(server);\n\n const options = {\n ...route.serverOptions,\n ...(requestMethod === \"get\" &&\n explicitHeadPaths.has(route.path) && { exposeHeadRoute: false }),\n config: {\n ...route.serverOptions?.config,\n // `undefined` keeps the global policy; `false` exempts the route.\n rateLimit: resolveRouteRateLimit(route),\n },\n };\n\n requestMethodFunction(\n route.path,\n options,\n async (baseRequest: FastifyRequest, reply: FastifyReply) => {\n const { output, response } = await this.handleRoute(route)(baseRequest, reply);\n\n return output || response.baseResponse;\n },\n );\n });\n\n this.registerStaticDirectories(server);\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Scan routes for the development server\n * Uses wildcard routing with find-my-way for HMR support\n */\n public scanDevServer(server: FastifyInstance) {\n // Same boot-time report as production `scan`. Routes reloaded later by HMR\n // are still recorded, but only surface on the next scan or via\n // `warlock doctor`.\n reportPositionalHandlerSuspects();\n\n // Development only: list mutating routes nobody guarded. Routes added by a\n // later HMR reload are reported when their replacement commits.\n this.warnUnguardedRoutes =\n configAccessor.key<boolean>(\"http.warnUnguardedRoutes\", true) !== false;\n if (this.warnUnguardedRoutes) {\n reportUnguardedMutatingRoutes(this.routes);\n }\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n let routeRegistry: RouteRegistry | undefined;\n let registryVersion = -1;\n\n const applyDevRateLimit = createDevRateLimiter(\n server,\n config.get(\"http.rateLimit.global\") !== false,\n );\n\n // Rebuilt when the route table changes rather than per request. Building it\n // inside the handler re-registered every route on every hit — and `all`\n // routes expand into seven registrations each. Keyed on `routesVersion`\n // rather than on the route count, so an HMR reload that swaps a route\n // without changing the count still invalidates.\n const resolveRouteRegistry = () => {\n if (routeRegistry && registryVersion === this.routesVersion) {\n return routeRegistry;\n }\n\n routeRegistry = new RouteRegistry();\n\n routeRegistry.register(this.routes);\n\n registryVersion = this.routesVersion;\n\n return routeRegistry;\n };\n\n // Matching happens here, in Fastify's own onRequest phase, so a route's\n // `serverOptions.onRequest` still runs BEFORE body parsing. Production\n // `scan()` gets that from per-route registration; the wildcard dispatcher\n // has no per-route slot, so without this the hook silently never runs.\n server.addHook(\n \"onRequest\",\n async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n // Only requests Fastify routed to the dev wildcard belong to the app's\n // router. A plugin's own route (devtools' `/__warlock/api/requests/:id`)\n // must keep its params even when an app catch-all matches the URL too.\n if (fastifyRequest.routeOptions.url !== \"*\") {\n return undefined;\n }\n\n const match = resolveRouteRegistry().find(fastifyRequest.method, fastifyRequest.url);\n\n if (!match) {\n return undefined;\n }\n\n (fastifyRequest as DevDispatchRequest).matchedDevRoute = match;\n\n fastifyRequest.params = match.params;\n\n // Same slot production gives it: the limiter runs first in onRequest,\n // ahead of the route's own hooks.\n await applyDevRateLimit(match.route, fastifyRequest, fastifyReply);\n\n if (fastifyReply.sent) {\n return fastifyReply;\n }\n\n return runRouteHooks(match.route, \"onRequest\", fastifyRequest, fastifyReply);\n },\n );\n\n for (const phase of FORWARDED_ROUTE_PHASES.filter((name) => name !== \"onRequest\")) {\n server.addHook(phase, async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n if (!match) {\n return undefined;\n }\n\n return runRouteHooks(match.route, phase, fastifyRequest, fastifyReply);\n });\n }\n\n // Shared handler for wildcard routing\n const wildcardHandler = async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n // No match found - return 404\n if (!match) {\n return fastifyReply\n .code(404)\n .send(buildNotFoundBody(fastifyRequest.method, fastifyRequest.url));\n }\n\n try {\n // Call the matched route handler\n const { output, response } = await this.handleRoute(match.route)(\n fastifyRequest,\n fastifyReply,\n );\n\n return output || response.baseResponse;\n } catch (error) {\n log.error(\"router\", \"dev-dispatch\", error as Error, {\n method: fastifyRequest.method,\n url: buildRequestLogSnapshot({\n id: fastifyRequest.id,\n method: fastifyRequest.method,\n url: fastifyRequest.url,\n route: match.route,\n }).url,\n });\n\n throw error;\n }\n };\n\n // Every verb production can register. Fastify's implicit HEAD for the GET\n // wildcard is switched off so the HEAD wildcard owns it (the registry falls\n // back to the GET route, exactly as production's implicit HEAD does).\n // `@fastify/cors` registers its own OPTIONS \"*\" catch-all whenever\n // preflight is on. Use the plugin's options as well as hasRoute so this\n // dispatcher works both after HTTP plugin boot and before queued plugins.\n const corsOwnsPreflight = buildCorsOptions().preflight !== false;\n\n for (const method of DEV_DISPATCH_METHODS) {\n if (\n method === \"OPTIONS\" &&\n (corsOwnsPreflight || server.hasRoute({ method: \"OPTIONS\", url: \"*\" }))\n ) {\n continue;\n }\n\n server.route({\n method,\n url: \"*\",\n ...(method === \"GET\" && { exposeHeadRoute: false }),\n // The dispatcher limits each matched route itself (see\n // `createDevRateLimiter`), so the plugin must not limit the wildcard:\n // that would count exempt routes and unmatched URLs too.\n config: { rateLimit: false },\n handler: wildcardHandler,\n });\n }\n\n this.registerStaticDirectories(server);\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Get the route path for the given route name\n */\n public getRoute(name: string, params: Record<string, any> = {}) {\n const route = this.routes.find((route) => route.name === name);\n\n if (!route) {\n throw new WarlockError(\"WL3003\", `Route name \"${name}\" not found`);\n }\n\n const used = new Set<string>();\n\n const path = route.path.replace(/:([A-Za-z0-9_]+)(\\?)?/g, (_match, key: string, optional) => {\n const value = params[key];\n\n if (value === undefined || value === null) {\n if (optional) return \"\";\n\n throw new WarlockError(\"WL3004\", `Route \"${name}\" is missing the \"${key}\" param`);\n }\n\n used.add(key);\n\n return encodeURIComponent(String(value));\n });\n\n const query = Object.keys(params)\n .filter((key) => !used.has(key) && params[key] !== undefined && params[key] !== null)\n .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(String(params[key]))}`)\n .join(\"&\");\n\n return query ? `${path}?${query}` : path;\n }\n\n /**\n * Handle the given route\n */\n private handleRoute(route: Route) {\n return async (fastifyRequest: FastifyRequest, fastifyResponse: FastifyReply) => {\n const request = new Request();\n const response = new Response();\n response.setResponse(fastifyResponse);\n request.response = response;\n\n response.request = request;\n\n // \"route.match\" tracing phase: the pattern is\n // already known here (`route.path`), so this brackets the cost of\n // stamping the request/route onto the `Request` instance rather than\n // route-registry matching itself, which happens upstream of this\n // function for both the production `scan()` path and the dev wildcard\n // dispatcher (both funnel into `handleRoute`).\n const tracingEnabled = isTracingEnabled();\n const routeMatchStartedAt = tracingEnabled ? performance.now() : 0;\n\n request.setRequest(fastifyRequest).setRoute(route);\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"route.match\",\n durationMs: performance.now() - routeMatchStartedAt,\n attrs: { route: route.path },\n });\n }\n\n /*\n Both ends of the entry, not just the start — see\n `log-request-lifecycle.ts`. A start line on its own made a hung request\n and an instant one look identical, and the completion line is what makes\n a MISSING one legible as a hang.\n */\n const result = await logRequestLifecycle(\n {\n info: (entry) => log.info(entry),\n warn: (entry) => log.warn(entry),\n error: (entry) => log.error(entry),\n now: () => performance.now(),\n },\n {\n module: \"route\",\n action: describeRouteForLog(route.method, route.path),\n requestId: request.id,\n // A bounded snapshot, built once with the route's logging policy\n // applied — never the Request/Response instances, whose native\n // request, reply and URL graphs would reach every log channel.\n context: { request: request.toLogSnapshot() },\n request,\n // Read after the run: the status is decided during the request.\n statusCode: () => fastifyResponse.statusCode,\n },\n () => request.execute(),\n );\n\n // A handler may return a plain object (`ReturnedResponse`). Route it\n // through `Response.send` so status, events and hooks apply, exactly as\n // middleware outputs already do.\n let output = result;\n\n if (\n output !== undefined &&\n output !== null &&\n !(output instanceof Response) &&\n (output as unknown) !== fastifyResponse\n ) {\n output = await response.send(output);\n }\n\n return {\n output,\n response,\n request,\n };\n };\n }\n}\n\nexport const router = Router.getInstance();\n\ncontainer.set(\"router\", router);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAM,yBAAyB;CAAC;CAAa;CAAiB;AAAY;AAc1E,SAAS,WACP,MACsB;CACtB,IAAI,CAAC,MACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;AAC3C;;;;;;;;AASA,eAAe,cACb,OACA,OACA,SACA,OACA;CACA,MAAM,QAAQ,WACZ,MAAM,gBAAgB,MACxB;CAEA,KAAK,MAAM,QAAQ,OAGjB,IAAI,MAFkB,KAAK,SAAS,KAAK,MAEzB,OACd,OAAO;AAKb;;;;;AAMA,SAAS,mBAAmB,QAAiB,QAA8B;CACzE,MAAM,iBAAkB,QAAuC;CAE/D,IAAI,gBACF,OAAO,iBAAiB;AAE5B;;;;AAKA,SAAS,oBACP,UACA,QACgB;CAChB,MAAM,SAAS,SAAS;CACxB,MAAM,UAAU,QAAQ,KAAK,QAAQ;CAErC,mBAAmB,QAAQ,OAAO;CAElC,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAS,sBAAsB,OAAc;CAC3C,MAAM,OAAO,MAAM,SAAS,eAAe;CAC3C,MAAM,SAAS,MAAM,aAAa,eAAe,MAAM,eAAe;CAEtE,OAAO,GAAG,KAAK,GAAG,MAAM,OAAO,GAAG,MAAM,KAAK,IAAI,OAAO;AAC1D;AAEA,IAAa,SAAb,MAAa,OAAO;;;;CAgElB,OAAc,cAAc;EAC1B,IAAI,CAAC,OAAO,UACV,OAAO,WAAW,IAAI,OAAO;EAG/B,OAAO,OAAO;CAChB;CAEA,AAAQ,cAAc;gBApEI,CAAC;uBAUH;6BAgBM;2BAaxB,CAAC;wBAML,CAAC;gBAM8B;GAC/B,QAAQ,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