burger-api 0.9.7 → 1.0.0-beta

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 (175) hide show
  1. package/README.md +84 -241
  2. package/dist/src/adapter/bun/index.d.ts +14 -0
  3. package/dist/src/adapter/bun/index.js +73 -0
  4. package/dist/src/adapter/bun/types.d.ts +15 -0
  5. package/dist/src/adapter/bun/types.js +1 -0
  6. package/dist/src/adapter/index.d.ts +1 -0
  7. package/dist/src/adapter/index.js +1 -0
  8. package/dist/src/adapter/types.d.ts +49 -0
  9. package/dist/src/adapter/types.js +1 -0
  10. package/dist/src/adapter/web-standard/fetch-handler.d.ts +39 -0
  11. package/dist/src/adapter/web-standard/fetch-handler.js +54 -0
  12. package/dist/src/adapter/web-standard/index.d.ts +8 -0
  13. package/dist/src/adapter/web-standard/index.js +7 -0
  14. package/dist/src/analysis/route-access-analyzer.d.ts +10 -0
  15. package/dist/src/analysis/route-access-analyzer.js +287 -0
  16. package/dist/src/chain/chain.d.ts +16 -0
  17. package/dist/src/chain/chain.js +17 -0
  18. package/dist/src/chain/flattener.d.ts +3 -0
  19. package/dist/src/chain/flattener.js +78 -0
  20. package/dist/src/chain/node.d.ts +25 -0
  21. package/dist/src/chain/node.js +1 -0
  22. package/dist/src/compiler/conventions.d.ts +67 -0
  23. package/dist/src/compiler/conventions.js +129 -0
  24. package/dist/src/compiler/index.d.ts +13 -0
  25. package/dist/src/compiler/index.js +11 -0
  26. package/dist/src/compiler/module-loader.d.ts +75 -0
  27. package/dist/src/compiler/module-loader.js +276 -0
  28. package/dist/src/compiler/route-module.d.ts +97 -0
  29. package/dist/src/compiler/route-module.js +1 -0
  30. package/dist/src/compiler/route-tree.d.ts +19 -0
  31. package/dist/src/compiler/route-tree.js +28 -0
  32. package/dist/src/compiler/scanner.d.ts +42 -0
  33. package/dist/src/compiler/scanner.js +201 -0
  34. package/dist/src/context/context-set.d.ts +26 -0
  35. package/dist/src/context/context-set.js +45 -0
  36. package/dist/src/context/context.d.ts +357 -0
  37. package/dist/src/context/context.js +401 -0
  38. package/dist/src/context/query-parser.d.ts +23 -0
  39. package/dist/src/context/query-parser.js +132 -0
  40. package/dist/src/context/route-access.d.ts +7 -0
  41. package/dist/src/context/route-access.js +18 -0
  42. package/dist/src/context/types.d.ts +62 -0
  43. package/dist/src/context/types.js +5 -0
  44. package/dist/src/core/asset-mime.d.ts +9 -0
  45. package/dist/src/core/asset-mime.js +35 -0
  46. package/dist/src/core/assets.d.ts +30 -0
  47. package/dist/src/core/assets.js +67 -0
  48. package/dist/src/core/docs-providers.d.ts +13 -0
  49. package/dist/src/core/docs-providers.js +89 -0
  50. package/dist/src/core/embedded-assets.d.ts +18 -0
  51. package/dist/src/core/embedded-assets.js +13 -0
  52. package/dist/src/core/openapi.d.ts +9 -10
  53. package/dist/src/core/openapi.js +333 -127
  54. package/dist/src/core/page-router.d.ts +13 -17
  55. package/dist/src/core/page-router.js +86 -55
  56. package/dist/src/core/server.d.ts +20 -11
  57. package/dist/src/core/server.js +41 -45
  58. package/dist/src/errors/forbidden.d.ts +14 -0
  59. package/dist/src/errors/forbidden.js +16 -0
  60. package/dist/src/errors/http-error.d.ts +47 -0
  61. package/dist/src/errors/http-error.js +146 -0
  62. package/dist/src/errors/method-not-allowed.d.ts +13 -0
  63. package/dist/src/errors/method-not-allowed.js +15 -0
  64. package/dist/src/errors/not-found.d.ts +14 -0
  65. package/dist/src/errors/not-found.js +16 -0
  66. package/dist/src/errors/unauthorized.d.ts +14 -0
  67. package/dist/src/errors/unauthorized.js +16 -0
  68. package/dist/src/index.d.ts +263 -50
  69. package/dist/src/index.js +919 -332
  70. package/dist/src/lifecycle/executor.d.ts +64 -0
  71. package/dist/src/lifecycle/executor.js +201 -0
  72. package/dist/src/lifecycle/hook-runner.d.ts +11 -0
  73. package/dist/src/lifecycle/hook-runner.js +156 -0
  74. package/dist/src/lifecycle/jit.d.ts +50 -0
  75. package/dist/src/lifecycle/jit.js +258 -0
  76. package/dist/src/lifecycle/transform.d.ts +26 -0
  77. package/dist/src/lifecycle/transform.js +99 -0
  78. package/dist/src/lifecycle/types.d.ts +135 -0
  79. package/dist/src/lifecycle/types.js +1 -0
  80. package/dist/src/plugin/composer.d.ts +3 -0
  81. package/dist/src/plugin/composer.js +28 -0
  82. package/dist/src/plugin/registry.d.ts +25 -0
  83. package/dist/src/plugin/registry.js +107 -0
  84. package/dist/src/plugin/types.d.ts +20 -0
  85. package/dist/src/plugin/types.js +1 -0
  86. package/dist/src/router/allow-cache.d.ts +20 -0
  87. package/dist/src/router/allow-cache.js +26 -0
  88. package/dist/src/router/compiler.d.ts +39 -0
  89. package/dist/src/router/compiler.js +817 -0
  90. package/dist/src/router/define.d.ts +67 -0
  91. package/dist/src/router/define.js +34 -0
  92. package/dist/src/router/index.d.ts +6 -0
  93. package/dist/src/router/index.js +5 -0
  94. package/dist/src/router/param-extract.d.ts +33 -0
  95. package/dist/src/router/param-extract.js +87 -0
  96. package/dist/src/router/regex-matcher.d.ts +42 -0
  97. package/dist/src/router/regex-matcher.js +216 -0
  98. package/dist/src/router/router.d.ts +201 -0
  99. package/dist/src/router/router.js +600 -0
  100. package/dist/src/router/static-map.d.ts +39 -0
  101. package/dist/src/router/static-map.js +48 -0
  102. package/dist/src/router/trie.d.ts +69 -0
  103. package/dist/src/router/trie.js +572 -0
  104. package/dist/src/router/types.d.ts +104 -0
  105. package/dist/src/router/types.js +1 -0
  106. package/dist/src/runtime/capabilities.d.ts +29 -0
  107. package/dist/src/runtime/capabilities.js +48 -0
  108. package/dist/src/types/index.d.ts +260 -109
  109. package/dist/src/types/index.js +1 -1
  110. package/dist/src/types/inference.d.ts +78 -0
  111. package/dist/src/types/inference.js +20 -0
  112. package/dist/src/types/openapi-config.d.ts +164 -0
  113. package/dist/src/types/openapi-config.js +8 -0
  114. package/dist/src/utils/env.d.ts +13 -0
  115. package/dist/src/utils/env.js +24 -0
  116. package/dist/src/utils/fs.d.ts +29 -0
  117. package/dist/src/utils/fs.js +75 -0
  118. package/dist/src/utils/index.d.ts +1 -1
  119. package/dist/src/utils/index.js +2 -2
  120. package/dist/src/utils/pathConversion.js +13 -7
  121. package/dist/src/utils/response.d.ts +42 -6
  122. package/dist/src/utils/response.js +172 -7
  123. package/dist/src/utils/routing.d.ts +32 -13
  124. package/dist/src/utils/routing.js +41 -18
  125. package/dist/src/utils/thenable.d.ts +8 -0
  126. package/dist/src/utils/thenable.js +12 -0
  127. package/dist/src/utils/timing-safe.d.ts +9 -0
  128. package/dist/src/utils/timing-safe.js +20 -0
  129. package/dist/src/utils/wildcard.d.ts +2 -9
  130. package/dist/src/utils/wildcard.js +20 -58
  131. package/dist/src/validation/adapter.d.ts +54 -0
  132. package/dist/src/validation/adapter.js +75 -0
  133. package/dist/src/validation/adapters/standard.d.ts +11 -0
  134. package/dist/src/validation/adapters/standard.js +110 -0
  135. package/dist/src/validation/adapters/zod.d.ts +9 -0
  136. package/dist/src/validation/adapters/zod.js +128 -0
  137. package/dist/src/validation/cache.d.ts +26 -0
  138. package/dist/src/validation/cache.js +35 -0
  139. package/dist/src/validation/coerce.d.ts +28 -0
  140. package/dist/src/validation/coerce.js +176 -0
  141. package/dist/src/validation/compiler.d.ts +27 -0
  142. package/dist/src/validation/compiler.js +191 -0
  143. package/dist/src/validation/error.d.ts +69 -0
  144. package/dist/src/validation/error.js +137 -0
  145. package/dist/src/validation/index.d.ts +16 -0
  146. package/dist/src/validation/index.js +12 -0
  147. package/dist/src/validation/response.d.ts +25 -0
  148. package/dist/src/validation/response.js +79 -0
  149. package/dist/src/validation/types.d.ts +148 -0
  150. package/dist/src/validation/types.js +6 -0
  151. package/dist/src/validation/validator.d.ts +39 -0
  152. package/dist/src/validation/validator.js +441 -0
  153. package/dist/src/ws/adapter.d.ts +219 -0
  154. package/dist/src/ws/adapter.js +623 -0
  155. package/dist/src/ws/compiler.d.ts +37 -0
  156. package/dist/src/ws/compiler.js +156 -0
  157. package/dist/src/ws/index.d.ts +11 -0
  158. package/dist/src/ws/index.js +8 -0
  159. package/dist/src/ws/platform.d.ts +81 -0
  160. package/dist/src/ws/platform.js +113 -0
  161. package/dist/src/ws/router.d.ts +48 -0
  162. package/dist/src/ws/router.js +174 -0
  163. package/dist/src/ws/scanner.d.ts +97 -0
  164. package/dist/src/ws/scanner.js +193 -0
  165. package/dist/src/ws/types.d.ts +380 -0
  166. package/dist/src/ws/types.js +213 -0
  167. package/package.json +72 -60
  168. package/dist/src/core/api-router.d.ts +0 -65
  169. package/dist/src/core/api-router.js +0 -264
  170. package/dist/src/core/swagger-ui.d.ts +0 -1
  171. package/dist/src/core/swagger-ui.js +0 -33
  172. package/dist/src/middleware/validator.d.ts +0 -14
  173. package/dist/src/middleware/validator.js +0 -133
  174. package/dist/src/utils/error.d.ts +0 -17
  175. package/dist/src/utils/error.js +0 -63
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Central type definitions for the validation subsystem.
3
+ *
4
+ * Types only — no runtime logic, no adapter implementations, no I/O.
5
+ */
6
+ export {};
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The validation coordinator — builds the framework's validation hook from
3
+ * precompiled route validators.
4
+ *
5
+ * Runs `cv.validate(value)` once per slot — no walk over the raw schema, no
6
+ * adapter selection, no preparing at request time. Skips work when
7
+ * `ctx.validated` is already set and validates
8
+ * params/query/headers/cookies/body with the same checks.
9
+ *
10
+ * Throws `ValidationError` (422, RFC 9457 problem details) on failure, or
11
+ * `HTTPError(415)` when a body schema is declared but the request body is not
12
+ * JSON (never skips validation).
13
+ */
14
+ import type { LowercaseHTTPMethod } from '../utils/routing.js';
15
+ import type { ForwardHook } from '../lifecycle/types.js';
16
+ import type { CompiledRouteValidators, ValidatorConfig } from './types.js';
17
+ /** Parses a `Cookie` header value into a flat record (cookie slot). */
18
+ export declare function parseCookies(header: string | null | undefined): Record<string, string>;
19
+ /**
20
+ * True when a raw `Content-Type` header value is JSON (`application/json` or
21
+ * `application/…+json`). Shared by request-body and response validation.
22
+ */
23
+ export declare function isJsonContentType(raw: string): boolean;
24
+ /**
25
+ * Builds the validation hook from precompiled route validators.
26
+ *
27
+ * On failure, throws a `ValidationError` (status 422, or
28
+ * `ValidatorConfig.status` when set) into the `onError` pipeline. The
29
+ * framework's default onError handler renders the RFC 9457 response.
30
+ *
31
+ * @param validators - the compiled validators for this route (may be empty).
32
+ * @param config - validation configuration (custom status, error format).
33
+ * @param isDev - reserved for future use (dev diagnostics).
34
+ * @param method - when given, the hook is specialized for that lowercase
35
+ * method at compile time (no per-request method lookup).
36
+ * @param skipValidatedBag - when true, a method without validators does not
37
+ * allocate the empty `{}` bag (only legal with `method` given).
38
+ */
39
+ export declare function createValidationHook(validators: CompiledRouteValidators, config?: ValidatorConfig, isDev?: boolean, method?: LowercaseHTTPMethod, skipValidatedBag?: boolean): ForwardHook;
@@ -0,0 +1,441 @@
1
+ /**
2
+ * The validation coordinator — builds the framework's validation hook from
3
+ * precompiled route validators.
4
+ *
5
+ * Runs `cv.validate(value)` once per slot — no walk over the raw schema, no
6
+ * adapter selection, no preparing at request time. Skips work when
7
+ * `ctx.validated` is already set and validates
8
+ * params/query/headers/cookies/body with the same checks.
9
+ *
10
+ * Throws `ValidationError` (422, RFC 9457 problem details) on failure, or
11
+ * `HTTPError(415)` when a body schema is declared but the request body is not
12
+ * JSON (never skips validation).
13
+ */
14
+ import { apply as applyCoercion } from './coerce.js';
15
+ import { ValidationError } from './error.js';
16
+ import { HTTPError } from '../errors/http-error.js';
17
+ /**
18
+ * Splits a `Cookie` header into `name=value` pairs, following RFC 6265 quoted
19
+ * cookie-values. A quoted value may contain `;` or `=` without terminating the
20
+ * pair (e.g. `session="a;b=c"`). The surrounding DQUOTES are stripped from the
21
+ * value; the inner content is preserved verbatim.
22
+ */
23
+ function splitCookiePairs(header) {
24
+ const pairs = [];
25
+ let i = 0;
26
+ while (i < header.length) {
27
+ // Skip leading whitespace/separators between pairs.
28
+ while (i < header.length && (header[i] === ' ' || header[i] === ';'))
29
+ i++;
30
+ if (i >= header.length)
31
+ break;
32
+ const eq = header.indexOf('=', i);
33
+ if (eq === -1)
34
+ break; // Malformed trailing token; stop.
35
+ const key = header.slice(i, eq).trim();
36
+ i = eq + 1;
37
+ let value;
38
+ if (header[i] === '"') {
39
+ // Quoted value: consume until the closing unescaped DQUOTE.
40
+ i++; // past opening quote
41
+ let end = i;
42
+ while (end < header.length && header[end] !== '"')
43
+ end++;
44
+ value = header.slice(i, end);
45
+ i = end + 1; // past closing quote
46
+ // Advance to the next ';' (or end) so the loop skips the rest.
47
+ const semi = header.indexOf(';', i);
48
+ i = semi === -1 ? header.length : semi + 1;
49
+ }
50
+ else {
51
+ const semi = header.indexOf(';', i);
52
+ if (semi === -1) {
53
+ value = header.slice(i);
54
+ i = header.length;
55
+ }
56
+ else {
57
+ value = header.slice(i, semi);
58
+ i = semi + 1;
59
+ }
60
+ }
61
+ if (key)
62
+ pairs.push([key, value.trim()]);
63
+ }
64
+ return pairs;
65
+ }
66
+ /** Parses a `Cookie` header value into a flat record (cookie slot). */
67
+ export function parseCookies(header) {
68
+ // Null prototype: cookie names are attacker-controlled and must never
69
+ // touch the object prototype (`__proto__` / `constructor`).
70
+ const out = Object.create(null);
71
+ if (!header)
72
+ return out;
73
+ for (const [key, rawValue] of splitCookiePairs(header)) {
74
+ try {
75
+ out[key] = decodeURIComponent(rawValue);
76
+ }
77
+ catch {
78
+ // Malformed percent-encoding (e.g. "%ZZ") — keep the raw value
79
+ // rather than throwing inside the validator.
80
+ out[key] = rawValue;
81
+ }
82
+ }
83
+ return out;
84
+ }
85
+ /**
86
+ * Resolves the validators for a lowercase method, reusing GET's validators
87
+ * for HEAD (auto-HEAD: a GET route implies HEAD is allowed; the body slot is
88
+ * skipped by the caller).
89
+ */
90
+ function resolveMethodValidators(validators, method) {
91
+ // Runtime method strings are lowercased before lookup; only methods in
92
+ // the union can be keys of the compiled map, so widening is safe.
93
+ let methodValidators = validators.methods[method];
94
+ if (!methodValidators && method === 'head') {
95
+ methodValidators = validators.methods['get'];
96
+ }
97
+ return methodValidators;
98
+ }
99
+ /**
100
+ * Lowercases an HTTP method without allocating when it is already lowercase
101
+ * (Bun hands the uppercase form in). Returns an empty string for anything
102
+ * that cannot be a compiled method key, so the caller takes the "no
103
+ * validators" path.
104
+ */
105
+ function toLowerMethod(method) {
106
+ const len = method.length;
107
+ if (len < 3 || len > 7)
108
+ return '';
109
+ for (let i = 0; i < len; i++) {
110
+ const code = method.charCodeAt(i);
111
+ if (code >= 65 && code <= 90)
112
+ return method.toLowerCase();
113
+ }
114
+ return method;
115
+ }
116
+ /**
117
+ * Extracts the media type from a raw `Content-Type` header value without
118
+ * `split`/`trim`/`toLowerCase` when the value is already a plain lowercase
119
+ * token (the common case).
120
+ */
121
+ function mediaTypeOf(raw) {
122
+ const semi = raw.indexOf(';');
123
+ let start = 0;
124
+ let end = semi === -1 ? raw.length : semi;
125
+ while (start < end) {
126
+ const c = raw.charCodeAt(start);
127
+ if (c !== 32 && c !== 9)
128
+ break;
129
+ start++;
130
+ }
131
+ while (end > start) {
132
+ const c = raw.charCodeAt(end - 1);
133
+ if (c !== 32 && c !== 9)
134
+ break;
135
+ end--;
136
+ }
137
+ const slice = start === 0 && end === raw.length ? raw : raw.slice(start, end);
138
+ // Lowercase only when the value actually carries uppercase characters
139
+ // (the already-lowercase common case allocates nothing).
140
+ for (let i = 0; i < slice.length; i++) {
141
+ const c = slice.charCodeAt(i);
142
+ if (c >= 65 && c <= 90)
143
+ return slice.toLowerCase();
144
+ }
145
+ return slice;
146
+ }
147
+ /** True when the media type (lowercased) is JSON (`application/json`/`+json`). */
148
+ function isJsonMediaType(mediaType) {
149
+ if (mediaType === 'application/json')
150
+ return true;
151
+ // `application/…+json` (e.g. `application/vnd.api+json`). Shortest form
152
+ // `application/+json` is 17 chars.
153
+ const len = mediaType.length;
154
+ if (len < 17)
155
+ return false;
156
+ if (mediaType.charCodeAt(0) !== 97 /* a */)
157
+ return false;
158
+ return mediaType.startsWith('application/') && mediaType.endsWith('+json');
159
+ }
160
+ /**
161
+ * True when a raw `Content-Type` header value is JSON (`application/json` or
162
+ * `application/…+json`). Shared by request-body and response validation.
163
+ */
164
+ export function isJsonContentType(raw) {
165
+ return isJsonMediaType(mediaTypeOf(raw));
166
+ }
167
+ /** True when the value is empty or whitespace only (no `trim()` allocation). */
168
+ function isBlank(value) {
169
+ for (let i = 0; i < value.length; i++) {
170
+ const c = value.charCodeAt(i);
171
+ if (c !== 32 && c !== 9 && c !== 10 && c !== 13)
172
+ return false;
173
+ }
174
+ return true;
175
+ }
176
+ /**
177
+ * Runs every declared slot for one method. Params/query/headers/cookies are
178
+ * synchronous; only a declared body slot returns a promise.
179
+ */
180
+ function validateMethodSlots(ctx, methodValidators, isHead, config) {
181
+ // The validated bag matches the `BurgerValidated` slots, so it is
182
+ // assignable to `ctx.validated` without an assertion.
183
+ const validated = {};
184
+ // Track errors per slot — only populated on failure.
185
+ let errorsBySlot = null;
186
+ const coercion = methodValidators.coercion;
187
+ // Params
188
+ const paramsValidator = methodValidators.params;
189
+ if (paramsValidator) {
190
+ const input = coercion?.params
191
+ ? applyCoercion(coercion.params, ctx.params)
192
+ : ctx.params;
193
+ const result = paramsValidator.validate(input);
194
+ if (result.success) {
195
+ validated.params = result.data;
196
+ }
197
+ else {
198
+ if (!errorsBySlot)
199
+ errorsBySlot = {};
200
+ errorsBySlot.params = result.issues;
201
+ }
202
+ }
203
+ // Query
204
+ const queryValidator = methodValidators.query;
205
+ if (queryValidator) {
206
+ const queryParams = (ctx.query ?? {});
207
+ const input = coercion?.query
208
+ ? applyCoercion(coercion.query, queryParams)
209
+ : queryParams;
210
+ const result = queryValidator.validate(input);
211
+ if (result.success) {
212
+ validated.query = result.data;
213
+ }
214
+ else {
215
+ if (!errorsBySlot)
216
+ errorsBySlot = {};
217
+ errorsBySlot.query = result.issues;
218
+ }
219
+ }
220
+ // Headers
221
+ const headersValidator = methodValidators.headers;
222
+ if (headersValidator) {
223
+ // Null prototype: header names are attacker-controlled.
224
+ const headerRecord = Object.create(null);
225
+ const headers = ctx.headers;
226
+ // Bun exposes `Headers.toJSON()` (a plain record) — much cheaper than
227
+ // iterating the Headers object. WinterCG runtimes fall back to a
228
+ // manual key/value walk.
229
+ const toJSON = headers.toJSON;
230
+ if (typeof toJSON === 'function') {
231
+ const flat = toJSON.call(headers);
232
+ for (const key in flat) {
233
+ headerRecord[key.toLowerCase()] = flat[key];
234
+ }
235
+ }
236
+ else {
237
+ for (const entry of headers) {
238
+ headerRecord[entry[0].toLowerCase()] = entry[1];
239
+ }
240
+ }
241
+ const input = coercion?.headers
242
+ ? applyCoercion(coercion.headers, headerRecord)
243
+ : headerRecord;
244
+ const result = headersValidator.validate(input);
245
+ if (result.success) {
246
+ validated.headers = result.data;
247
+ }
248
+ else {
249
+ if (!errorsBySlot)
250
+ errorsBySlot = {};
251
+ errorsBySlot.headers = result.issues;
252
+ }
253
+ }
254
+ // Cookies — reuse the context's cached parse (`ctx.cookies`) when the
255
+ // caller passed a real BurgerContext; duck-typed contexts (tests, embedded
256
+ // callers) fall back to parsing the header directly.
257
+ const cookiesValidator = methodValidators.cookies;
258
+ if (cookiesValidator) {
259
+ const cached = ctx.cookies;
260
+ const cookieRecord = cached !== undefined && cached !== null
261
+ ? cached
262
+ : parseCookies(ctx.headers.get('cookie'));
263
+ const input = coercion?.cookies
264
+ ? applyCoercion(coercion.cookies, cookieRecord)
265
+ : cookieRecord;
266
+ const result = cookiesValidator.validate(input);
267
+ if (result.success) {
268
+ validated.cookies = result.data;
269
+ }
270
+ else {
271
+ if (!errorsBySlot)
272
+ errorsBySlot = {};
273
+ errorsBySlot.cookies = result.issues;
274
+ }
275
+ }
276
+ /** Throws a `ValidationError` on failure, else stores `validated`. */
277
+ const finish = () => {
278
+ if (errorsBySlot) {
279
+ // Throw into the onError pipeline — the framework renders the
280
+ // RFC 9457 response via the default onError fallback.
281
+ const allIssues = [];
282
+ let firstSlot;
283
+ for (const slot in errorsBySlot) {
284
+ if (firstSlot === undefined) {
285
+ firstSlot = slot;
286
+ }
287
+ const issues = errorsBySlot[slot];
288
+ for (let i = 0; i < issues.length; i++) {
289
+ allIssues.push(issues[i]);
290
+ }
291
+ }
292
+ throw new ValidationError(firstSlot, allIssues, {
293
+ errorsBySlot,
294
+ status: config.status,
295
+ });
296
+ }
297
+ ctx.validated = validated;
298
+ };
299
+ // Body (gated on the JSON media type; skipped for HEAD, which carries
300
+ // no body). The gate reads the raw header, so casing
301
+ // (`Application/JSON`) and parameters (`; charset=utf-8`) cannot bypass
302
+ // it.
303
+ const bodyValidator = methodValidators.body;
304
+ if (bodyValidator && !isHead) {
305
+ const rawContentType = ctx.headers.get('content-type') ?? '';
306
+ const mediaType = mediaTypeOf(rawContentType);
307
+ /** Validates one body value; failures land in `errorsBySlot.body`. */
308
+ const validateBodyValue = (bodyData) => {
309
+ try {
310
+ const result = bodyValidator.validate(bodyData);
311
+ if (result.success) {
312
+ validated.body = result.data;
313
+ }
314
+ else {
315
+ if (!errorsBySlot)
316
+ errorsBySlot = {};
317
+ errorsBySlot.body = result.issues;
318
+ }
319
+ }
320
+ catch (error) {
321
+ const msg = error instanceof Error ? error.message : String(error);
322
+ if (!errorsBySlot)
323
+ errorsBySlot = {};
324
+ errorsBySlot.body = [{ path: [], message: msg }];
325
+ }
326
+ };
327
+ if (isJsonMediaType(mediaType)) {
328
+ // Read once through `ctx.text()` (bytes are cached), so
329
+ // `ctx.text()` / `ctx.arrayBuffer()` still work in the handler.
330
+ // An empty body validates as `undefined`; malformed JSON is a
331
+ // client error (400) and passes through onError, never 422.
332
+ return ctx.text().then((raw) => {
333
+ if (isBlank(raw)) {
334
+ validateBodyValue(undefined);
335
+ }
336
+ else {
337
+ let bodyData;
338
+ try {
339
+ bodyData = JSON.parse(raw);
340
+ }
341
+ catch (error) {
342
+ throw new HTTPError(400, `Malformed JSON body: ${error.message}`, { cause: error });
343
+ }
344
+ validateBodyValue(bodyData);
345
+ }
346
+ finish();
347
+ }, (error) => {
348
+ // Body read failure — surface as a body validation issue.
349
+ const msg = error instanceof Error ? error.message : String(error);
350
+ if (!errorsBySlot)
351
+ errorsBySlot = {};
352
+ errorsBySlot.body = [{ path: [], message: msg }];
353
+ finish();
354
+ });
355
+ }
356
+ else if (isBlank(rawContentType)) {
357
+ // No media type: an empty body validates as `undefined` (optional
358
+ // schemas work); a non-empty body is rejected rather than
359
+ // silently skipping validation.
360
+ return ctx.text().then((raw) => {
361
+ if (isBlank(raw)) {
362
+ validateBodyValue(undefined);
363
+ }
364
+ else {
365
+ if (!errorsBySlot)
366
+ errorsBySlot = {};
367
+ errorsBySlot.body = [
368
+ {
369
+ path: [],
370
+ message: 'Content-Type header required for body validation',
371
+ },
372
+ ];
373
+ }
374
+ finish();
375
+ });
376
+ }
377
+ else {
378
+ // A body schema is declared but the body is not JSON (form,
379
+ // text, …). Never let unvalidated data reach the handler:
380
+ // 415 Unsupported Media Type (RFC 9457 via onError).
381
+ throw new HTTPError(415, `Unsupported Media Type "${mediaType}" — this endpoint expects application/json`);
382
+ }
383
+ }
384
+ finish();
385
+ return undefined;
386
+ }
387
+ /**
388
+ * Builds the validation hook from precompiled route validators.
389
+ *
390
+ * On failure, throws a `ValidationError` (status 422, or
391
+ * `ValidatorConfig.status` when set) into the `onError` pipeline. The
392
+ * framework's default onError handler renders the RFC 9457 response.
393
+ *
394
+ * @param validators - the compiled validators for this route (may be empty).
395
+ * @param config - validation configuration (custom status, error format).
396
+ * @param isDev - reserved for future use (dev diagnostics).
397
+ * @param method - when given, the hook is specialized for that lowercase
398
+ * method at compile time (no per-request method lookup).
399
+ * @param skipValidatedBag - when true, a method without validators does not
400
+ * allocate the empty `{}` bag (only legal with `method` given).
401
+ */
402
+ export function createValidationHook(validators, config = {}, isDev = false, method, skipValidatedBag = false) {
403
+ void isDev;
404
+ if (method !== undefined) {
405
+ const methodValidators = resolveMethodValidators(validators, method);
406
+ const isHead = method === 'head';
407
+ if (!methodValidators) {
408
+ if (skipValidatedBag)
409
+ return () => undefined;
410
+ // Methods without a schema still get an (empty) validated bag, so
411
+ // route hooks typed via `defineHooks` can read slots safely.
412
+ return (ctx) => {
413
+ if (!ctx.validated)
414
+ ctx.validated = {};
415
+ return undefined;
416
+ };
417
+ }
418
+ // NOT an `async` function: body-less schemas validate synchronously,
419
+ // and the pipeline awaits the result only when a Promise is returned.
420
+ return (ctx) => {
421
+ if (ctx.validated)
422
+ return undefined;
423
+ return validateMethodSlots(ctx, methodValidators, isHead, config);
424
+ };
425
+ }
426
+ // General path: resolve the method at request time (kept for callers
427
+ // that build a route-agnostic hook).
428
+ return (ctx) => {
429
+ // If the request has already been validated, continue.
430
+ if (ctx.validated) {
431
+ return undefined;
432
+ }
433
+ const methodLower = toLowerMethod(ctx.method || 'get');
434
+ const methodValidators = resolveMethodValidators(validators, methodLower);
435
+ if (!methodValidators) {
436
+ ctx.validated = {};
437
+ return undefined;
438
+ }
439
+ return validateMethodSlots(ctx, methodValidators, methodLower === 'head', config);
440
+ };
441
+ }