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,11 @@
1
+ /**
2
+ * The Standard Schema adapter — supports Valibot/ArkType/`~standard`
3
+ * libraries with no framework change.
4
+ *
5
+ * Computes identity from the `~standard` contract and compiles into a
6
+ * `CompiledValidator` whose `validate` calls `schema['~standard'].validate`
7
+ * and normalizes the result into the common `ValidationResult` shape. Depends
8
+ * only on the `~standard` contract, never on a specific library.
9
+ */
10
+ import type { ValidatorAdapter } from '../adapter.js';
11
+ export declare const StandardAdapter: ValidatorAdapter;
@@ -0,0 +1,110 @@
1
+ /**
2
+ * The Standard Schema adapter — supports Valibot/ArkType/`~standard`
3
+ * libraries with no framework change.
4
+ *
5
+ * Computes identity from the `~standard` contract and compiles into a
6
+ * `CompiledValidator` whose `validate` calls `schema['~standard'].validate`
7
+ * and normalizes the result into the common `ValidationResult` shape. Depends
8
+ * only on the `~standard` contract, never on a specific library.
9
+ */
10
+ /** Flattens a Standard Schema issue path into `(string | number)[]`. */
11
+ function normalizePath(path) {
12
+ if (!path)
13
+ return [];
14
+ return path.map((p) => typeof p === 'object' && p !== null && 'key' in p
15
+ ? p.key
16
+ : p);
17
+ }
18
+ function normalizeIssues(issues) {
19
+ return issues.map((issue) => ({
20
+ path: normalizePath(issue.path),
21
+ message: issue.message,
22
+ }));
23
+ }
24
+ export const StandardAdapter = {
25
+ identity(schema) {
26
+ const std = schema;
27
+ const vendor = std['~standard'].vendor ?? 'unknown';
28
+ // Fingerprint from the `~standard.types`, falling back to a stable
29
+ // stringification of the schema.
30
+ let fingerprint;
31
+ try {
32
+ const types = std['~standard'].types;
33
+ fingerprint = JSON.stringify(types ?? String(std));
34
+ }
35
+ catch {
36
+ fingerprint = String(std);
37
+ }
38
+ return 'standard:' + vendor + ':' + fingerprint;
39
+ },
40
+ supports(schema) {
41
+ return ((typeof schema === 'object' || typeof schema === 'function') &&
42
+ schema !== null &&
43
+ '~standard' in schema &&
44
+ typeof schema['~standard']?.validate ===
45
+ 'function');
46
+ },
47
+ /**
48
+ * Standard Schema vendors expose no reliable structural identity —
49
+ * `~standard.types` often serializes the same for different schemas, so
50
+ * cache sharing could validate a slot with the WRONG schema (silently
51
+ * stripping fields). Correctness first: always compile fresh; the cost is
52
+ * trivial.
53
+ */
54
+ cacheable() {
55
+ return false;
56
+ },
57
+ compile(schema, slot) {
58
+ const std = schema;
59
+ const identity = this.identity(schema);
60
+ // `~standard.validate` may be sync or async; the pipeline validates
61
+ // synchronously per slot. Probe here so a bad schema fails fast at
62
+ // startup instead of throwing a 500 on the first matching request.
63
+ let isAsync = false;
64
+ try {
65
+ const probe = std['~standard'].validate(undefined);
66
+ if (probe instanceof Promise) {
67
+ isAsync = true;
68
+ probe.catch(() => { });
69
+ }
70
+ }
71
+ catch {
72
+ // A sync throw on the probe is fine — the real call re-runs it.
73
+ }
74
+ if (isAsync) {
75
+ throw new Error('[burger-api] Standard Schema validator for slot "' +
76
+ slot +
77
+ '" is async (`~standard.validate` returned a Promise). ' +
78
+ 'BurgerAPI validation is synchronous; use a sync ' +
79
+ '`~standard` validator for request validation.');
80
+ }
81
+ const validate = (value) => {
82
+ const result = std['~standard'].validate(value);
83
+ if (result instanceof Promise) {
84
+ // Defensive: should never happen after the compile-time probe,
85
+ // but guard so we never return a Promise where a sync result is
86
+ // expected.
87
+ throw new Error('[burger-api] Standard Schema validator for slot "' +
88
+ slot +
89
+ '" returned a Promise at request time. Use a sync ' +
90
+ '`~standard` validator for request validation.');
91
+ }
92
+ if ('issues' in result && result.issues) {
93
+ return {
94
+ success: false,
95
+ issues: normalizeIssues(result.issues),
96
+ };
97
+ }
98
+ return { success: true, data: result.value };
99
+ };
100
+ return {
101
+ kind: 'standard',
102
+ slot,
103
+ identity,
104
+ validate,
105
+ // `~standard.coercible` marks schemas that transform their own input
106
+ // during validate — framework coercion must not run on them.
107
+ coercible: std['~standard'].coercible === true,
108
+ };
109
+ },
110
+ };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The Zod adapter — the default schema provider for BurgerAPI.
3
+ *
4
+ * Computes a stable identity, compiles a Zod schema into a reusable
5
+ * `CompiledValidator`, and normalizes Zod `issues` into `ValidationIssue[]`.
6
+ * Delegates validation to `safeParse` and leaves coercion to the coercer.
7
+ */
8
+ import type { ValidatorAdapter } from '../adapter.js';
9
+ export declare const ZodAdapter: ValidatorAdapter;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * The Zod adapter — the default schema provider for BurgerAPI.
3
+ *
4
+ * Computes a stable identity, compiles a Zod schema into a reusable
5
+ * `CompiledValidator`, and normalizes Zod `issues` into `ValidationIssue[]`.
6
+ * Delegates validation to `safeParse` and leaves coercion to the coercer.
7
+ */
8
+ import { z } from 'zod';
9
+ import { isZodSchema } from '../adapter.js';
10
+ /** Maps a Zod issue path to the normalized `(string | number)[]`. */
11
+ function normalizePath(path) {
12
+ return path.map((p) => (typeof p === 'bigint' ? Number(p) : p));
13
+ }
14
+ /** Bounded deep scan for function values inside a check descriptor. */
15
+ function hasFunctionValue(value, depth = 0) {
16
+ if (typeof value === 'function') {
17
+ return true;
18
+ }
19
+ if (depth >= 4 || typeof value !== 'object' || value === null) {
20
+ return false;
21
+ }
22
+ for (const v of Object.values(value)) {
23
+ if (hasFunctionValue(v, depth + 1)) {
24
+ return true;
25
+ }
26
+ }
27
+ return false;
28
+ }
29
+ /** Normalizes Zod's `ZodError.issues` into `ValidationIssue[]`. */
30
+ function normalizeIssues(error) {
31
+ return error.issues.map((issue) => ({
32
+ path: normalizePath(issue.path),
33
+ message: issue.message,
34
+ code: issue.code,
35
+ }));
36
+ }
37
+ /** Monotonic ids for schemas with no computable JSON Schema fingerprint. */
38
+ const uniqueSchemaIds = new WeakMap();
39
+ let nextUniqueSchemaId = 0;
40
+ /**
41
+ * Root-level wrappers whose validation semantics the JSON Schema fingerprint
42
+ * cannot capture. `z.string().optional()` and `z.string()` serialize
43
+ * identically, so sharing a cached validator would validate the wrong
44
+ * schema (e.g. `undefined` rejected for an optional body).
45
+ */
46
+ const LOSSY_ROOT_TYPES = new Set([
47
+ 'optional',
48
+ 'prefault',
49
+ 'nonoptional',
50
+ 'default',
51
+ 'catch',
52
+ 'pipe',
53
+ 'lazy',
54
+ ]);
55
+ export const ZodAdapter = {
56
+ identity(schema) {
57
+ // Zod v4's `toString()` is not stable for object schemas, so use a
58
+ // deterministic JSON Schema fingerprint as the structural identity.
59
+ // Prefix it to namespace under the Zod provider.
60
+ const zodSchema = schema;
61
+ let fingerprint;
62
+ try {
63
+ fingerprint = JSON.stringify(z.toJSONSchema(zodSchema));
64
+ }
65
+ catch {
66
+ // No computable fingerprint (transforms, dates, custom, bigint):
67
+ // key by object identity so distinct schemas can never share.
68
+ let id = uniqueSchemaIds.get(zodSchema);
69
+ if (id === undefined) {
70
+ id = ++nextUniqueSchemaId;
71
+ uniqueSchemaIds.set(zodSchema, id);
72
+ }
73
+ return 'zod:object:' + id;
74
+ }
75
+ return 'zod:' + fingerprint;
76
+ },
77
+ cacheable(schema) {
78
+ const zodSchema = schema;
79
+ const def = zodSchema._zod?.def;
80
+ // Self-coercing schemas (z.coerce.*) validate differently than their
81
+ // plain counterparts even though their JSON Schema fingerprints are
82
+ // identical — never let one route's coercion leak into another's.
83
+ if (def?.coerce === true) {
84
+ return false;
85
+ }
86
+ // Root wrappers invisible to the fingerprint (optional/default/pipe/
87
+ // …) change what counts as valid input — compile fresh.
88
+ if (def?.type !== undefined && LOSSY_ROOT_TYPES.has(def.type)) {
89
+ return false;
90
+ }
91
+ // Function-valued checks (refinements) are invisible to the JSON
92
+ // Schema fingerprint, so structurally identical refinements would
93
+ // collide in the cache. Compile them fresh instead.
94
+ const checks = def?.checks;
95
+ if (Array.isArray(checks) && checks.some((c) => hasFunctionValue(c))) {
96
+ return false;
97
+ }
98
+ return true;
99
+ },
100
+ supports(schema) {
101
+ return isZodSchema(schema);
102
+ },
103
+ compile(schema, slot) {
104
+ const zodSchema = schema;
105
+ const identity = this.identity(schema);
106
+ // Zod 4 marks self-coercing schemas (`z.coerce.*`) with
107
+ // `_zod.def.coerce === true`. Such schemas transform their input
108
+ // during validate, so framework coercion must not run on them.
109
+ const coercible = zodSchema
110
+ ?._zod?.def?.coerce === true;
111
+ const validate = (value) => {
112
+ const result = zodSchema.safeParse(value);
113
+ if (result.success) {
114
+ // Zod's success result already has the `{ success, data }` shape —
115
+ // return it directly instead of re-wrapping.
116
+ return result;
117
+ }
118
+ return { success: false, issues: normalizeIssues(result.error) };
119
+ };
120
+ return {
121
+ kind: 'zod',
122
+ slot,
123
+ identity,
124
+ validate,
125
+ coercible,
126
+ };
127
+ },
128
+ };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The validator cache — process-lifetime memoization of compiled validators
3
+ * keyed by schema identity.
4
+ *
5
+ * Lookup / insert / clear on dev hot reload (the next compile pass repopulates
6
+ * it wholesale). Must NOT retain build-time serialization artifacts at runtime
7
+ * and must NOT mutate during a production request. The storage mechanism
8
+ * (`Map`) is an implementation detail.
9
+ */
10
+ import type { CompiledValidator } from './types.js';
11
+ export declare class ValidatorCache {
12
+ private store;
13
+ /** Returns the cached validator for `identity`, or undefined on miss. */
14
+ get(identity: string): CompiledValidator | undefined;
15
+ /** Inserts a compiled validator keyed by its identity. */
16
+ set(identity: string, validator: CompiledValidator): void;
17
+ /** True when `identity` is already cached. */
18
+ has(identity: string): boolean;
19
+ /**
20
+ * Clears all cached validators. Called on dev hot reload; the next
21
+ * `compile()` pass repopulates it wholesale.
22
+ */
23
+ clear(): void;
24
+ /** Number of currently cached (unique) validators. */
25
+ get size(): number;
26
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The validator cache — process-lifetime memoization of compiled validators
3
+ * keyed by schema identity.
4
+ *
5
+ * Lookup / insert / clear on dev hot reload (the next compile pass repopulates
6
+ * it wholesale). Must NOT retain build-time serialization artifacts at runtime
7
+ * and must NOT mutate during a production request. The storage mechanism
8
+ * (`Map`) is an implementation detail.
9
+ */
10
+ export class ValidatorCache {
11
+ store = new Map();
12
+ /** Returns the cached validator for `identity`, or undefined on miss. */
13
+ get(identity) {
14
+ return this.store.get(identity);
15
+ }
16
+ /** Inserts a compiled validator keyed by its identity. */
17
+ set(identity, validator) {
18
+ this.store.set(identity, validator);
19
+ }
20
+ /** True when `identity` is already cached. */
21
+ has(identity) {
22
+ return this.store.has(identity);
23
+ }
24
+ /**
25
+ * Clears all cached validators. Called on dev hot reload; the next
26
+ * `compile()` pass repopulates it wholesale.
27
+ */
28
+ clear() {
29
+ this.store.clear();
30
+ }
31
+ /** Number of currently cached (unique) validators. */
32
+ get size() {
33
+ return this.store.size;
34
+ }
35
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The coercer — builds and applies precomputed value-conversion plans.
3
+ * "Coercion" means automatic type conversion: `"42"` → the number `42`,
4
+ * `"true"` → the boolean `true`.
5
+ *
6
+ * `buildPlan` records only the fields that need conversion
7
+ * (number/boolean/date) and returns undefined when there is nothing to
8
+ * convert. `apply` transforms a raw string record in a single linear pass;
9
+ * fields not in the plan are copied unchanged.
10
+ *
11
+ * Conversion is opt-in (default OFF, planned at startup and applied only when
12
+ * present). It never converts the body and never leaks `NaN` — a bad
13
+ * conversion stays a string so the validator reports the real input.
14
+ */
15
+ import type { CoercionPlan, SchemaInput } from './types.js';
16
+ /**
17
+ * Builds a coercion plan for a schema slot. Returns undefined when the slot
18
+ * has no coercible fields (so the orchestrator can skip coercion entirely).
19
+ *
20
+ * Currently inspects Zod object shapes (the default provider).
21
+ * Other adapters can be extended by detecting their intent here.
22
+ */
23
+ export declare function buildPlan(slotSchema: SchemaInput, slot: 'query' | 'params' | 'headers' | 'cookies'): CoercionPlan | undefined;
24
+ /**
25
+ * Applies a coercion plan to a raw record. Fields not in the plan are copied
26
+ * as-is. The output is a new record; the input is not mutated.
27
+ */
28
+ export declare function apply(plan: CoercionPlan, raw: Record<string, string | string[]>): Record<string, unknown>;
@@ -0,0 +1,176 @@
1
+ /**
2
+ * The coercer — builds and applies precomputed value-conversion plans.
3
+ * "Coercion" means automatic type conversion: `"42"` → the number `42`,
4
+ * `"true"` → the boolean `true`.
5
+ *
6
+ * `buildPlan` records only the fields that need conversion
7
+ * (number/boolean/date) and returns undefined when there is nothing to
8
+ * convert. `apply` transforms a raw string record in a single linear pass;
9
+ * fields not in the plan are copied unchanged.
10
+ *
11
+ * Conversion is opt-in (default OFF, planned at startup and applied only when
12
+ * present). It never converts the body and never leaks `NaN` — a bad
13
+ * conversion stays a string so the validator reports the real input.
14
+ */
15
+ import { isZodSchema } from './adapter.js';
16
+ /** Unwraps optional/nullable/default wrappers to reach the inner type. */
17
+ function unwrap(def) {
18
+ let current = def;
19
+ // Up to a few levels of wrapping (optional/nullable/default).
20
+ for (let i = 0; i < 4 && current; i++) {
21
+ const inner = current?._zod?.def?.innerType;
22
+ if (inner === undefined)
23
+ break;
24
+ current = inner;
25
+ }
26
+ return current;
27
+ }
28
+ /** Returns the coercion op for a Zod field def, or 'none'. */
29
+ function opForZodField(def) {
30
+ // Self-coercing fields (`z.coerce.*`, marked `_zod.def.coerce: true`)
31
+ // transform their input during validate — never pre-coerce them.
32
+ if (def?._zod?.def?.coerce === true)
33
+ return 'none';
34
+ const name = def?.constructor?.name;
35
+ if (name === 'ZodNumber')
36
+ return 'number';
37
+ if (name === 'ZodBoolean')
38
+ return 'boolean';
39
+ if (name === 'ZodDate')
40
+ return 'date';
41
+ // Try unwrapping optional/nullable/default.
42
+ const inner = unwrap(def);
43
+ if (inner && inner !== def)
44
+ return opForZodField(inner);
45
+ return 'none';
46
+ }
47
+ function coerceValue(op, raw) {
48
+ switch (op) {
49
+ case 'number': {
50
+ // Strict decimal form only: no empty/whitespace, hex, exponent,
51
+ // Infinity or NaN. Anything else stays a string.
52
+ if (!/^\s*[+-]?\d+(\.\d+)?\s*$/.test(raw)) {
53
+ return raw;
54
+ }
55
+ const n = Number(raw);
56
+ // Never leak NaN: keep the raw string so the validator reports
57
+ // the actual bad input.
58
+ return Number.isNaN(n) ? raw : n;
59
+ }
60
+ case 'boolean': {
61
+ if (raw === 'true' || raw === '1')
62
+ return true;
63
+ if (raw === 'false' || raw === '0')
64
+ return false;
65
+ // Unknown boolean string -> leave as-is; the validator will reject.
66
+ return raw;
67
+ }
68
+ case 'date': {
69
+ const d = tryParseDate(raw);
70
+ return d ?? raw;
71
+ }
72
+ default:
73
+ return raw;
74
+ }
75
+ }
76
+ /**
77
+ * Strict ISO-8601 date parse.
78
+ *
79
+ * Rejects numeric strings ("42"), non-ISO formats, and impossible calendar
80
+ * dates ("2026-02-30" rolls over in `new Date()` unless checked). Date-only
81
+ * values are validated against the calendar directly; full timestamps must
82
+ * carry a time and a zone.
83
+ */
84
+ function tryParseDate(raw) {
85
+ const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(raw);
86
+ if (dateOnly) {
87
+ const [, y, mo, da] = dateOnly;
88
+ const day = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(da)));
89
+ if (day.toISOString().slice(0, 10) !== `${y}-${mo}-${da}`) {
90
+ return null;
91
+ }
92
+ return day;
93
+ }
94
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/.test(raw)) {
95
+ return null;
96
+ }
97
+ // Full timestamp: verify the calendar day too (the parse alone would
98
+ // roll "2026-02-30T10:00:00Z" forward).
99
+ if (tryParseDate(raw.slice(0, 10)) === null) {
100
+ return null;
101
+ }
102
+ const d = new Date(raw);
103
+ return isNaN(d.getTime()) ? null : d;
104
+ }
105
+ /**
106
+ * Builds a coercion plan for a schema slot. Returns undefined when the slot
107
+ * has no coercible fields (so the orchestrator can skip coercion entirely).
108
+ *
109
+ * Currently inspects Zod object shapes (the default provider).
110
+ * Other adapters can be extended by detecting their intent here.
111
+ */
112
+ export function buildPlan(slotSchema, slot) {
113
+ if (!isZodSchema(slotSchema))
114
+ return undefined;
115
+ const shape = slotSchema.shape;
116
+ if (!shape || typeof shape !== 'object')
117
+ return undefined;
118
+ const fieldMap = shape;
119
+ const fields = {};
120
+ const arrays = {};
121
+ for (const key of Object.keys(fieldMap)) {
122
+ // `z.array(x)`: repeated keys (`?tag=a&tag=b`) already arrive as an
123
+ // array; a single occurrence is wrapped. Elements use x's op.
124
+ const inner = unwrap(fieldMap[key]);
125
+ if (inner?.constructor?.name === 'ZodArray') {
126
+ arrays[key] = opForZodField(inner._zod?.def?.element);
127
+ continue;
128
+ }
129
+ const op = opForZodField(fieldMap[key]);
130
+ if (op !== 'none')
131
+ fields[key] = op;
132
+ }
133
+ const hasArrays = Object.keys(arrays).length > 0;
134
+ if (Object.keys(fields).length === 0 && !hasArrays)
135
+ return undefined;
136
+ return hasArrays ? { slot, fields, arrays } : { slot, fields };
137
+ }
138
+ /**
139
+ * Applies a coercion plan to a raw record. Fields not in the plan are copied
140
+ * as-is. The output is a new record; the input is not mutated.
141
+ */
142
+ export function apply(plan, raw) {
143
+ // Null prototype: input keys are attacker-controlled.
144
+ const out = Object.create(null);
145
+ for (const key of Object.keys(raw)) {
146
+ const op = plan.fields[key];
147
+ const value = raw[key];
148
+ const elementOp = plan.arrays?.[key];
149
+ if (elementOp !== undefined) {
150
+ const list = Array.isArray(value) ? value : [value];
151
+ if (elementOp === 'none') {
152
+ out[key] = list;
153
+ continue;
154
+ }
155
+ // Plain loop: element coercion runs per request, no `map` closure.
156
+ const coerced = new Array(list.length);
157
+ for (let i = 0; i < list.length; i++) {
158
+ coerced[i] = coerceValue(elementOp, list[i]);
159
+ }
160
+ out[key] = coerced;
161
+ continue;
162
+ }
163
+ if (!op) {
164
+ out[key] = value;
165
+ continue;
166
+ }
167
+ // Arrays (duplicate keys) are not coerced field-by-field; pass through
168
+ // unchanged so the validator sees the same shape.
169
+ if (Array.isArray(value)) {
170
+ out[key] = value;
171
+ continue;
172
+ }
173
+ out[key] = coerceValue(op, value);
174
+ }
175
+ return out;
176
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The schema preparation component — compiles a `RouteSchema` into
3
+ * `CompiledRouteValidators`.
4
+ *
5
+ * Walks each slot, detects its adapter, computes identity, and consults the
6
+ * cache; builds coercion plans and response validators when present. Runs
7
+ * ONCE per route when it is set up (before `serve()`), never per request.
8
+ * Identical schemas (by reference) share one cached validator.
9
+ */
10
+ import type { RouteSchema } from '../types/index.js';
11
+ import { ValidatorCache } from './cache.js';
12
+ import type { CompiledRouteValidators, ValidatorConfig } from './types.js';
13
+ /** The shared, process-lifetime validator cache. */
14
+ export declare const validatorCache: ValidatorCache;
15
+ /**
16
+ * Compiles a route's `schema` into `CompiledRouteValidators`.
17
+ *
18
+ * @param schema - the raw route schema.
19
+ * @param config - the validator configuration (coercion / response flags).
20
+ * @param cache - the validator cache (shared instance by default).
21
+ */
22
+ export declare function compileRouteSchema(schema: RouteSchema, config?: ValidatorConfig, cache?: ValidatorCache, route?: string): CompiledRouteValidators;
23
+ /**
24
+ * Clears the shared cache (dev hot reload). The next compile pass repopulates
25
+ * it wholesale.
26
+ */
27
+ export declare function clearValidatorCache(): void;