burger-api 0.9.7 → 1.0.0-beta.1

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 +240 -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 +49 -0
  61. package/dist/src/errors/http-error.js +155 -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 +275 -50
  69. package/dist/src/index.js +974 -333
  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 +867 -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 +214 -0
  99. package/dist/src/router/router.js +670 -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 +189 -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 +6 -7
  130. package/dist/src/utils/wildcard.js +38 -55
  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 +85 -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 +230 -0
  154. package/dist/src/ws/adapter.js +660 -0
  155. package/dist/src/ws/compiler.d.ts +37 -0
  156. package/dist/src/ws/compiler.js +178 -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 +82 -0
  160. package/dist/src/ws/platform.js +122 -0
  161. package/dist/src/ws/router.d.ts +47 -0
  162. package/dist/src/ws/router.js +183 -0
  163. package/dist/src/ws/scanner.d.ts +97 -0
  164. package/dist/src/ws/scanner.js +253 -0
  165. package/dist/src/ws/types.d.ts +381 -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
@@ -1,4 +1,4 @@
1
- import type { PageDefinition, RouteDefinition, TrieNode } from '../types/index';
1
+ import type { PageDefinition, RouteDefinition, TrieNode } from '../types/index.js';
2
2
  /**
3
3
  * Constants for route handling.
4
4
  */
@@ -15,31 +15,50 @@ export declare const ROUTE_CONSTANTS: {
15
15
  WILDCARD_START: string;
16
16
  };
17
17
  /**
18
- * Supported HTTP methods
18
+ * Supported HTTP methods as a literal tuple; the names double as the
19
+ * `HTTPMethod` union.
19
20
  */
20
- export declare const HTTP_METHODS: string[];
21
+ export declare const HTTP_METHODS: readonly ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
21
22
  /**
22
- * Calculates the specificity of a route path based on the number of static segments.
23
- * Static segments increase the score, while dynamic segments (:param) do not.
24
- * Wildcard segments (*) have the lowest specificity (highest penalty).
23
+ * The closed set of HTTP methods a route can handle, uppercase as used in
24
+ * `RouteDefinition.handlers` and `request.method`.
25
+ */
26
+ export type HTTPMethod = (typeof HTTP_METHODS)[number];
27
+ /**
28
+ * Lowercase form of `HTTPMethod`, used by the lowercase-keyed maps
29
+ * (`RouteSchema`, `openapi`, compiled validators).
30
+ */
31
+ export type LowercaseHTTPMethod = Lowercase<HTTPMethod>;
32
+ /**
33
+ * Scores a route path by specificity: +1 per static segment, 0 per dynamic
34
+ * (`:param`, `[param]`), -1 per wildcard. Higher means more static; sorting by
35
+ * it puts static first, dynamic second, wildcard last.
25
36
  * @param path The route path to evaluate.
26
- * @returns The specificity score (higher means more static segments, lower priority for wildcard).
37
+ * @returns The specificity score.
27
38
  */
28
39
  export declare const getRouteSpecificity: (path: string) => number;
29
40
  /**
30
- * Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
31
- * Route prioritization: Static > Dynamic > Wildcard.
32
- * If specificity is equal, sorts alphabetically by path.
41
+ * Compares two routes for sorting: higher specificity first (Static >
42
+ * Dynamic > Wildcard), ties alphabetically by path.
33
43
  * @param a The first route to compare.
34
44
  * @param b The second route to compare.
35
- * @returns Negative if a comes before b, positive if b comes before a, zero if equal.
45
+ * @returns Negative if a comes first, positive if b does, zero if equal.
36
46
  */
37
47
  export declare const compareRoutes: (a: PageDefinition | RouteDefinition, b: PageDefinition | RouteDefinition) => number;
38
48
  /**
39
- * Collects all routes from the trie and returns them as an array of RouteDefinition objects.
49
+ * Collects all routes from the trie as `RouteDefinition` objects.
40
50
  * @param node The current node in the trie.
41
51
  * @param currentPath The current path being traversed.
42
52
  * @param routes The array of collected routes.
43
- * @returns An array of RouteDefinition objects.
53
+ * @returns The collected routes.
44
54
  */
45
55
  export declare function collectRoutes(node: TrieNode, currentPath?: string, routes?: RouteDefinition[]): RouteDefinition[];
56
+ /**
57
+ * Copies a per-method map (`schema.ts` / `openapi.ts` / `config.ts` exports)
58
+ * with uppercase method keys (`GET`) lowercased (`get`) for the validation
59
+ * compiler, OpenAPI generator and route compiler. Non-method keys (e.g.
60
+ * `coerce`) pass through; never mutates the input (module namespaces are
61
+ * frozen). Returns the input unchanged when it has no uppercase method key,
62
+ * so default-only configs keep their object identity.
63
+ */
64
+ export declare function lowercaseMethodKeys(raw: Record<string, unknown> | object): Record<string, unknown>;
@@ -19,7 +19,8 @@ export const ROUTE_CONSTANTS = {
19
19
  WILDCARD_START: '[...',
20
20
  };
21
21
  /**
22
- * Supported HTTP methods
22
+ * Supported HTTP methods as a literal tuple; the names double as the
23
+ * `HTTPMethod` union.
23
24
  */
24
25
  export const HTTP_METHODS = [
25
26
  'GET',
@@ -31,30 +32,34 @@ export const HTTP_METHODS = [
31
32
  'OPTIONS',
32
33
  ];
33
34
  /**
34
- * Calculates the specificity of a route path based on the number of static segments.
35
- * Static segments increase the score, while dynamic segments (:param) do not.
36
- * Wildcard segments (*) have the lowest specificity (highest penalty).
35
+ * Scores a route path by specificity: +1 per static segment, 0 per dynamic
36
+ * (`:param`, `[param]`), -1 per wildcard. Higher means more static; sorting by
37
+ * it puts static first, dynamic second, wildcard last.
37
38
  * @param path The route path to evaluate.
38
- * @returns The specificity score (higher means more static segments, lower priority for wildcard).
39
+ * @returns The specificity score.
39
40
  */
40
41
  export const getRouteSpecificity = (path) => {
41
42
  const segments = path.split('/').filter(Boolean);
42
43
  return segments.reduce((score, segment) => {
43
- if (segment.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX)) {
44
- return score + 1000; // Wildcard routes get highest penalty (lowest priority)
44
+ if (segment.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX) ||
45
+ (segment.startsWith(ROUTE_CONSTANTS.WILDCARD_START) &&
46
+ segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END))) {
47
+ return score - 1; // Wildcard routes get the penalty (lowest priority)
45
48
  }
46
- return segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)
47
- ? score + 100 // Dynamic routes get medium penalty
48
- : score + 1; // Static routes get minimal penalty
49
+ if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX) ||
50
+ (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
51
+ segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END))) {
52
+ return score; // Dynamic routes get no static credit
53
+ }
54
+ return score + 1; // Static routes get the credit (highest priority)
49
55
  }, 0);
50
56
  };
51
57
  /**
52
- * Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
53
- * Route prioritization: Static > Dynamic > Wildcard.
54
- * If specificity is equal, sorts alphabetically by path.
58
+ * Compares two routes for sorting: higher specificity first (Static >
59
+ * Dynamic > Wildcard), ties alphabetically by path.
55
60
  * @param a The first route to compare.
56
61
  * @param b The second route to compare.
57
- * @returns Negative if a comes before b, positive if b comes before a, zero if equal.
62
+ * @returns Negative if a comes first, positive if b does, zero if equal.
58
63
  */
59
64
  export const compareRoutes = (a, b) => {
60
65
  const aSpecificity = getRouteSpecificity(a.path);
@@ -66,14 +71,13 @@ export const compareRoutes = (a, b) => {
66
71
  return a.path.localeCompare(b.path);
67
72
  };
68
73
  /**
69
- * Collects all routes from the trie and returns them as an array of RouteDefinition objects.
74
+ * Collects all routes from the trie as `RouteDefinition` objects.
70
75
  * @param node The current node in the trie.
71
76
  * @param currentPath The current path being traversed.
72
77
  * @param routes The array of collected routes.
73
- * @returns An array of RouteDefinition objects.
78
+ * @returns The collected routes.
74
79
  */
75
80
  export function collectRoutes(node, currentPath = '', routes = []) {
76
- // If this node has a route definition, add it
77
81
  if (node.route) {
78
82
  routes.push({
79
83
  ...node.route,
@@ -91,9 +95,28 @@ export function collectRoutes(node, currentPath = '', routes = []) {
91
95
  }
92
96
  // Traverse wildcard child if exists (lowest priority)
93
97
  if (node.wildcardChild) {
94
- // const wildcardPath = `${currentPath}/${node.wildcardChild.wildcardParamName}`;
95
98
  const wildcardPath = `${currentPath}/${ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX}`;
96
99
  collectRoutes(node.wildcardChild, wildcardPath, routes);
97
100
  }
98
101
  return routes;
99
102
  }
103
+ /**
104
+ * Copies a per-method map (`schema.ts` / `openapi.ts` / `config.ts` exports)
105
+ * with uppercase method keys (`GET`) lowercased (`get`) for the validation
106
+ * compiler, OpenAPI generator and route compiler. Non-method keys (e.g.
107
+ * `coerce`) pass through; never mutates the input (module namespaces are
108
+ * frozen). Returns the input unchanged when it has no uppercase method key,
109
+ * so default-only configs keep their object identity.
110
+ */
111
+ export function lowercaseMethodKeys(raw) {
112
+ const entries = Object.entries(raw);
113
+ if (!entries.some(([key]) => HTTP_METHODS.includes(key))) {
114
+ return raw;
115
+ }
116
+ const out = {};
117
+ for (const [key, value] of entries) {
118
+ const isMethod = HTTP_METHODS.includes(key);
119
+ out[isMethod ? key.toLowerCase() : key] = value;
120
+ }
121
+ return out;
122
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Hot-path thenable probe used by the sync-first lifecycle stages.
3
+ *
4
+ * `await` on a synchronous value still costs a microtask; checking
5
+ * `typeof value.then === 'function'` first lets a step that returned a plain
6
+ * value continue without suspending.
7
+ */
8
+ export declare function isThenable(value: unknown): value is PromiseLike<unknown>;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Hot-path thenable probe used by the sync-first lifecycle stages.
3
+ *
4
+ * `await` on a synchronous value still costs a microtask; checking
5
+ * `typeof value.then === 'function'` first lets a step that returned a plain
6
+ * value continue without suspending.
7
+ */
8
+ export function isThenable(value) {
9
+ return (value !== null &&
10
+ value !== undefined &&
11
+ typeof value.then === 'function');
12
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Portable constant-time string comparison (WinterCG-safe, no `node:crypto`).
3
+ *
4
+ * XORs UTF-8 bytes over the longer length, so comparison time does not depend
5
+ * on match position. Length is still observable via the iteration bound —
6
+ * acceptable for server-controlled credentials; equal-length values (e.g.
7
+ * hashed credentials) leak nothing.
8
+ */
9
+ export declare function timingSafeEqual(a: string, b: string): boolean;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Portable constant-time string comparison (WinterCG-safe, no `node:crypto`).
3
+ *
4
+ * XORs UTF-8 bytes over the longer length, so comparison time does not depend
5
+ * on match position. Length is still observable via the iteration bound —
6
+ * acceptable for server-controlled credentials; equal-length values (e.g.
7
+ * hashed credentials) leak nothing.
8
+ */
9
+ export function timingSafeEqual(a, b) {
10
+ const aBytes = new TextEncoder().encode(a);
11
+ const bBytes = new TextEncoder().encode(b);
12
+ const maxLen = Math.max(aBytes.length, bBytes.length);
13
+ let diff = aBytes.length ^ bBytes.length;
14
+ for (let i = 0; i < maxLen; i++) {
15
+ const av = i < aBytes.length ? aBytes[i] : 0;
16
+ const bv = i < bBytes.length ? bBytes[i] : 0;
17
+ diff |= av ^ bv;
18
+ }
19
+ return diff === 0;
20
+ }
@@ -1,14 +1,13 @@
1
- import type { BurgerRequest } from '../types/index';
2
1
  /**
3
- * Extracts the pathname from a full URL string, removing query parameters.
2
+ * Extracts the pathname from a full URL string, removing query parameters and
3
+ * fragments.
4
4
  * @param url - The full URL string (e.g., "http://localhost:4000/api/users/123/profile?id=1")
5
5
  * @returns The extracted pathname (e.g., "/api/users/123/profile")
6
6
  */
7
7
  export declare function extractPathnameFromUrl(url: string): string;
8
8
  /**
9
- * Extracts wildcard parameters from a request pathname and sets them on the request object.
10
- * @param request - The request object to modify
11
- * @param pathname - The pathname extracted from the URL (e.g., "/api/users/123/profile")
12
- * @param baseSegmentCount - Number of segments before the wildcard (e.g., 3 for "/api/users/:userId/*")
9
+ * True when the pathname of a full URL string ends with `/`, without
10
+ * allocating the pathname. Needed where Bun's native wildcard handler does not
11
+ * expose `request.params['*']`.
13
12
  */
14
- export declare function extractWildcardParams(request: BurgerRequest, pathname: string, baseSegmentCount: number): void;
13
+ export declare function urlPathnameEndsWithSlash(url: string): boolean;
@@ -1,66 +1,49 @@
1
1
  /**
2
- * Extracts the pathname from a full URL string, removing query parameters.
2
+ * Extracts the pathname from a full URL string, removing query parameters and
3
+ * fragments.
3
4
  * @param url - The full URL string (e.g., "http://localhost:4000/api/users/123/profile?id=1")
4
5
  * @returns The extracted pathname (e.g., "/api/users/123/profile")
5
6
  */
6
7
  export function extractPathnameFromUrl(url) {
7
- // Find where the path starts (after protocol and domain)
8
- // Example: "http://localhost:4000/api/..." → protocolEnd = 4 (after "http")
9
- const protocolEnd = url.indexOf('://');
10
- // Find first "/" after the domain
11
- // Example: "http://localhost:4000/api/..." → pathStart = 21 (the "/" before "api")
12
- const pathStart = url.indexOf('/', protocolEnd + 3);
13
- // Find where query parameters start (if any)
14
- // Example: "/api/users/123?id=1" → pathEnd = 15 (at the "?")
15
- const pathEnd = url.indexOf('?', pathStart);
16
- // Extract just the pathname without query parameters
17
- // Example: "/api/users/123/profile"
18
- return pathEnd === -1
19
- ? url.substring(pathStart) // No query params
20
- : url.substring(pathStart, pathEnd); // Has query params, stop at "?"
8
+ // Where the authority ends. The charCode checks fast-path http/https
9
+ // instead of scanning for '://'.
10
+ const authorityEnd = url.charCodeAt(4) === 58 /* : */
11
+ ? 7
12
+ : url.charCodeAt(5) === 58 /* : */
13
+ ? 8
14
+ : url.indexOf('://') + 3;
15
+ // Path starts at the first "/" after the authority; no path segment
16
+ // falls back to index 0.
17
+ const found = url.indexOf('/', authorityEnd);
18
+ const pathStart = found === -1 ? 0 : found;
19
+ // Single scan for `?` or `#`. Raw URL strings may still carry a fragment
20
+ // even though the URL parser strips it.
21
+ for (let i = pathStart; i < url.length; i++) {
22
+ const code = url.charCodeAt(i);
23
+ if (code === 63 /* ? */ || code === 35 /* # */) {
24
+ return url.slice(pathStart, i);
25
+ }
26
+ }
27
+ return url.slice(pathStart);
21
28
  }
22
29
  /**
23
- * Extracts wildcard parameters from a request pathname and sets them on the request object.
24
- * @param request - The request object to modify
25
- * @param pathname - The pathname extracted from the URL (e.g., "/api/users/123/profile")
26
- * @param baseSegmentCount - Number of segments before the wildcard (e.g., 3 for "/api/users/:userId/*")
30
+ * True when the pathname of a full URL string ends with `/`, without
31
+ * allocating the pathname. Needed where Bun's native wildcard handler does not
32
+ * expose `request.params['*']`.
27
33
  */
28
- export function extractWildcardParams(request, pathname, baseSegmentCount) {
29
- if (baseSegmentCount === 0) {
30
- // Fast path: The entire path is wildcard
31
- // Example: "/api/docs/*" where all segments after domain are wildcards
32
- // Just split everything and we're done!
33
- request.wildcardParams = pathname.split('/').filter(Boolean);
34
- }
35
- else {
36
- // Optimized path: Skip base segments and only collect wildcard segments
37
- // Example: "/api/users/123/settings/privacy"
38
- // - We need to skip 3 segments (api, users, 123)
39
- // - Only collect: ["settings", "privacy"]
40
- const wildcardParams = [];
41
- let segmentCount = 0; // Counts how many segments we've seen
42
- let start = pathname[0] === '/' ? 1 : 0; // Start after leading "/" if present
43
- // Loop through each character in the pathname
44
- // When we hit "/" or end of string, we know we found a segment
45
- for (let i = start; i <= pathname.length; i++) {
46
- // Found end of a segment (either "/" or end of string)
47
- if (i === pathname.length || pathname[i] === '/') {
48
- // Make sure it's not an empty segment (from double slashes)
49
- if (i > start) {
50
- // Only save segments AFTER we've skipped the base segments
51
- // Example: If baseSegmentCount=3, save segment 3, 4, 5, etc.
52
- if (segmentCount >= baseSegmentCount) {
53
- // Extract this segment from the pathname
54
- // Example: pathname.substring(5, 13) might give "settings"
55
- wildcardParams.push(pathname.substring(start, i));
56
- }
57
- segmentCount++; // Increment count for next segment
58
- }
59
- start = i + 1; // Move start position to character after "/"
60
- }
34
+ export function urlPathnameEndsWithSlash(url) {
35
+ const authorityEnd = url.charCodeAt(4) === 58 /* : */
36
+ ? 7
37
+ : url.charCodeAt(5) === 58 /* : */
38
+ ? 8
39
+ : url.indexOf('://') + 3;
40
+ const found = url.indexOf('/', authorityEnd);
41
+ const pathStart = found === -1 ? 0 : found;
42
+ for (let i = pathStart; i < url.length; i++) {
43
+ const code = url.charCodeAt(i);
44
+ if (code === 63 /* ? */ || code === 35 /* # */) {
45
+ return url.charCodeAt(i - 1) === 47;
61
46
  }
62
- // Done! wildcardParams now contains only the wildcard segments
63
- // Example: ["settings", "privacy"] instead of ["api", "users", "123", "settings", "privacy"]
64
- request.wildcardParams = wildcardParams;
65
47
  }
48
+ return url.charCodeAt(url.length - 1) === 47;
66
49
  }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The validator adapter layer — the only place that decides which schema
3
+ * library a schema uses.
4
+ *
5
+ * Defines the `ValidatorAdapter` interface, detects which adapter a schema
6
+ * belongs to (Zod first, then Standard), and allows registering additional
7
+ * adapters. Detection runs when the app starts only; never when a request
8
+ * comes in. Schema-check logic lives in each adapter implementation.
9
+ */
10
+ import { z } from 'zod';
11
+ import type { SchemaInput, ValidationSlot, CompiledValidator } from './types.js';
12
+ /**
13
+ * A stable connector between BurgerAPI's request flow and a concrete schema
14
+ * library. The coordinator and cache depend only on this interface, never on
15
+ * a concrete library.
16
+ */
17
+ export interface ValidatorAdapter {
18
+ /** Stable identity for a schema; drives cache sharing. */
19
+ identity(schema: SchemaInput): string;
20
+ /**
21
+ * Prepare a schema slot into a reusable `CompiledValidator`. The
22
+ * `validate` call is the sole runtime entry point.
23
+ */
24
+ compile(schema: SchemaInput, slot: ValidationSlot): CompiledValidator;
25
+ /** Whether this adapter can handle the given schema. */
26
+ supports(schema: SchemaInput): boolean;
27
+ /**
28
+ * Whether a compiled validator for this schema is safe to cache and
29
+ * share. Adapters return false when the structural identity cannot
30
+ * capture the schema's runtime semantics (e.g. refinements with function
31
+ * checks, self-coercing schemas) — such schemas compile fresh per route.
32
+ */
33
+ cacheable?(schema: SchemaInput): boolean;
34
+ }
35
+ /**
36
+ * True when the value is a Zod 4 schema. Detection is structural — the `_zod`
37
+ * internals marker — so schemas from a second zod copy (a duplicate install)
38
+ * are recognized too, not only instances of this package's `z.ZodType`.
39
+ */
40
+ export declare function isZodSchema(value: unknown): value is z.ZodTypeAny;
41
+ /** The Zod adapter registers itself here at module load. */
42
+ export declare function __setZodAdapter(adapter: ValidatorAdapter): void;
43
+ /** The Standard Schema adapter registers itself here at module load. */
44
+ export declare function __setStandardAdapter(adapter: ValidatorAdapter): void;
45
+ /** Register an additional adapter (checked after the built-in Zod check). */
46
+ export declare function registerAdapter(adapter: ValidatorAdapter): void;
47
+ /**
48
+ * Returns the adapter that should handle `schema`.
49
+ *
50
+ * Detection order: Zod brand first (default provider), then any registered
51
+ * adapter, then the built-in Standard Schema adapter. Throws on unknown
52
+ * schemas to fail fast at compile time — never a request-time surprise.
53
+ */
54
+ export declare function detectAdapter(schema: SchemaInput): ValidatorAdapter;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The validator adapter layer — the only place that decides which schema
3
+ * library a schema uses.
4
+ *
5
+ * Defines the `ValidatorAdapter` interface, detects which adapter a schema
6
+ * belongs to (Zod first, then Standard), and allows registering additional
7
+ * adapters. Detection runs when the app starts only; never when a request
8
+ * comes in. Schema-check logic lives in each adapter implementation.
9
+ */
10
+ import { z } from 'zod';
11
+ /**
12
+ * True when the value is a Zod 4 schema. Detection is structural — the `_zod`
13
+ * internals marker — so schemas from a second zod copy (a duplicate install)
14
+ * are recognized too, not only instances of this package's `z.ZodType`.
15
+ */
16
+ export function isZodSchema(value) {
17
+ if (typeof value !== 'object' || value === null)
18
+ return false;
19
+ const internals = value._zod;
20
+ return typeof internals === 'object' && internals !== null;
21
+ }
22
+ /**
23
+ * True when the value carries the Standard Schema v1 `~standard` contract.
24
+ * Some libraries make schemas callable, so functions count too.
25
+ */
26
+ function isStandardSchema(value) {
27
+ return ((typeof value === 'object' || typeof value === 'function') &&
28
+ value !== null &&
29
+ '~standard' in value &&
30
+ typeof value['~standard']?.validate === 'function');
31
+ }
32
+ /** Registered additional adapters (checked after the built-in Zod check). */
33
+ const registered = [];
34
+ /** The Zod adapter singleton, set by the Zod adapter module on load. */
35
+ let zodAdapterInstance;
36
+ /** The Standard Schema adapter singleton, set on load. */
37
+ let standardAdapterInstance;
38
+ /** The Zod adapter registers itself here at module load. */
39
+ export function __setZodAdapter(adapter) {
40
+ zodAdapterInstance = adapter;
41
+ }
42
+ /** The Standard Schema adapter registers itself here at module load. */
43
+ export function __setStandardAdapter(adapter) {
44
+ standardAdapterInstance = adapter;
45
+ }
46
+ /** Register an additional adapter (checked after the built-in Zod check). */
47
+ export function registerAdapter(adapter) {
48
+ registered.push(adapter);
49
+ }
50
+ /**
51
+ * Returns the adapter that should handle `schema`.
52
+ *
53
+ * Detection order: Zod brand first (default provider), then any registered
54
+ * adapter, then the built-in Standard Schema adapter. Throws on unknown
55
+ * schemas to fail fast at compile time — never a request-time surprise.
56
+ */
57
+ export function detectAdapter(schema) {
58
+ if (isZodSchema(schema) && zodAdapterInstance) {
59
+ return zodAdapterInstance;
60
+ }
61
+ for (const adapter of registered) {
62
+ if (adapter.supports(schema))
63
+ return adapter;
64
+ }
65
+ if (isStandardSchema(schema) && standardAdapterInstance) {
66
+ return standardAdapterInstance;
67
+ }
68
+ if (isStandardSchema(schema)) {
69
+ throw new Error('[burger-api] Standard Schema adapter is not loaded. ' +
70
+ 'This is an internal wiring error (Standard Schema adapter missing).');
71
+ }
72
+ throw new Error('[burger-api] Unsupported schema: not a Zod schema and not a ' +
73
+ 'Standard Schema (missing "~standard" contract). ' +
74
+ 'Wrap the value with a supported provider.');
75
+ }
@@ -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;