burger-api 0.9.6 → 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.
- package/README.md +84 -241
- package/dist/src/adapter/bun/index.d.ts +14 -0
- package/dist/src/adapter/bun/index.js +73 -0
- package/dist/src/adapter/bun/types.d.ts +15 -0
- package/dist/src/adapter/bun/types.js +1 -0
- package/dist/src/adapter/index.d.ts +1 -0
- package/dist/src/adapter/index.js +1 -0
- package/dist/src/adapter/types.d.ts +49 -0
- package/dist/src/adapter/types.js +1 -0
- package/dist/src/adapter/web-standard/fetch-handler.d.ts +39 -0
- package/dist/src/adapter/web-standard/fetch-handler.js +54 -0
- package/dist/src/adapter/web-standard/index.d.ts +8 -0
- package/dist/src/adapter/web-standard/index.js +7 -0
- package/dist/src/analysis/route-access-analyzer.d.ts +10 -0
- package/dist/src/analysis/route-access-analyzer.js +287 -0
- package/dist/src/chain/chain.d.ts +16 -0
- package/dist/src/chain/chain.js +17 -0
- package/dist/src/chain/flattener.d.ts +3 -0
- package/dist/src/chain/flattener.js +78 -0
- package/dist/src/chain/node.d.ts +25 -0
- package/dist/src/chain/node.js +1 -0
- package/dist/src/compiler/conventions.d.ts +67 -0
- package/dist/src/compiler/conventions.js +129 -0
- package/dist/src/compiler/index.d.ts +13 -0
- package/dist/src/compiler/index.js +11 -0
- package/dist/src/compiler/module-loader.d.ts +75 -0
- package/dist/src/compiler/module-loader.js +276 -0
- package/dist/src/compiler/route-module.d.ts +97 -0
- package/dist/src/compiler/route-module.js +1 -0
- package/dist/src/compiler/route-tree.d.ts +19 -0
- package/dist/src/compiler/route-tree.js +28 -0
- package/dist/src/compiler/scanner.d.ts +42 -0
- package/dist/src/compiler/scanner.js +201 -0
- package/dist/src/context/context-set.d.ts +26 -0
- package/dist/src/context/context-set.js +45 -0
- package/dist/src/context/context.d.ts +357 -0
- package/dist/src/context/context.js +401 -0
- package/dist/src/context/query-parser.d.ts +23 -0
- package/dist/src/context/query-parser.js +132 -0
- package/dist/src/context/route-access.d.ts +7 -0
- package/dist/src/context/route-access.js +18 -0
- package/dist/src/context/types.d.ts +62 -0
- package/dist/src/context/types.js +5 -0
- package/dist/src/core/asset-mime.d.ts +9 -0
- package/dist/src/core/asset-mime.js +35 -0
- package/dist/src/core/assets.d.ts +30 -0
- package/dist/src/core/assets.js +67 -0
- package/dist/src/core/docs-providers.d.ts +13 -0
- package/dist/src/core/docs-providers.js +89 -0
- package/dist/src/core/embedded-assets.d.ts +18 -0
- package/dist/src/core/embedded-assets.js +13 -0
- package/dist/src/core/openapi.d.ts +9 -10
- package/dist/src/core/openapi.js +333 -127
- package/dist/src/core/page-router.d.ts +13 -17
- package/dist/src/core/page-router.js +86 -55
- package/dist/src/core/server.d.ts +20 -11
- package/dist/src/core/server.js +41 -45
- package/dist/src/errors/forbidden.d.ts +14 -0
- package/dist/src/errors/forbidden.js +16 -0
- package/dist/src/errors/http-error.d.ts +47 -0
- package/dist/src/errors/http-error.js +146 -0
- package/dist/src/errors/method-not-allowed.d.ts +13 -0
- package/dist/src/errors/method-not-allowed.js +15 -0
- package/dist/src/errors/not-found.d.ts +14 -0
- package/dist/src/errors/not-found.js +16 -0
- package/dist/src/errors/unauthorized.d.ts +14 -0
- package/dist/src/errors/unauthorized.js +16 -0
- package/dist/src/index.d.ts +263 -50
- package/dist/src/index.js +919 -332
- package/dist/src/lifecycle/executor.d.ts +64 -0
- package/dist/src/lifecycle/executor.js +201 -0
- package/dist/src/lifecycle/hook-runner.d.ts +11 -0
- package/dist/src/lifecycle/hook-runner.js +156 -0
- package/dist/src/lifecycle/jit.d.ts +50 -0
- package/dist/src/lifecycle/jit.js +258 -0
- package/dist/src/lifecycle/transform.d.ts +26 -0
- package/dist/src/lifecycle/transform.js +99 -0
- package/dist/src/lifecycle/types.d.ts +135 -0
- package/dist/src/lifecycle/types.js +1 -0
- package/dist/src/plugin/composer.d.ts +3 -0
- package/dist/src/plugin/composer.js +28 -0
- package/dist/src/plugin/registry.d.ts +25 -0
- package/dist/src/plugin/registry.js +107 -0
- package/dist/src/plugin/types.d.ts +20 -0
- package/dist/src/plugin/types.js +1 -0
- package/dist/src/router/allow-cache.d.ts +20 -0
- package/dist/src/router/allow-cache.js +26 -0
- package/dist/src/router/compiler.d.ts +39 -0
- package/dist/src/router/compiler.js +817 -0
- package/dist/src/router/define.d.ts +67 -0
- package/dist/src/router/define.js +34 -0
- package/dist/src/router/index.d.ts +6 -0
- package/dist/src/router/index.js +5 -0
- package/dist/src/router/param-extract.d.ts +33 -0
- package/dist/src/router/param-extract.js +87 -0
- package/dist/src/router/regex-matcher.d.ts +42 -0
- package/dist/src/router/regex-matcher.js +216 -0
- package/dist/src/router/router.d.ts +201 -0
- package/dist/src/router/router.js +600 -0
- package/dist/src/router/static-map.d.ts +39 -0
- package/dist/src/router/static-map.js +48 -0
- package/dist/src/router/trie.d.ts +69 -0
- package/dist/src/router/trie.js +572 -0
- package/dist/src/router/types.d.ts +104 -0
- package/dist/src/router/types.js +1 -0
- package/dist/src/runtime/capabilities.d.ts +29 -0
- package/dist/src/runtime/capabilities.js +48 -0
- package/dist/src/types/index.d.ts +260 -109
- package/dist/src/types/index.js +1 -1
- package/dist/src/types/inference.d.ts +78 -0
- package/dist/src/types/inference.js +20 -0
- package/dist/src/types/openapi-config.d.ts +164 -0
- package/dist/src/types/openapi-config.js +8 -0
- package/dist/src/utils/env.d.ts +13 -0
- package/dist/src/utils/env.js +24 -0
- package/dist/src/utils/fs.d.ts +29 -0
- package/dist/src/utils/fs.js +75 -0
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.js +2 -2
- package/dist/src/utils/pathConversion.js +13 -7
- package/dist/src/utils/response.d.ts +42 -6
- package/dist/src/utils/response.js +172 -7
- package/dist/src/utils/routing.d.ts +32 -13
- package/dist/src/utils/routing.js +41 -18
- package/dist/src/utils/thenable.d.ts +8 -0
- package/dist/src/utils/thenable.js +12 -0
- package/dist/src/utils/timing-safe.d.ts +9 -0
- package/dist/src/utils/timing-safe.js +20 -0
- package/dist/src/utils/wildcard.d.ts +2 -9
- package/dist/src/utils/wildcard.js +20 -58
- package/dist/src/validation/adapter.d.ts +54 -0
- package/dist/src/validation/adapter.js +75 -0
- package/dist/src/validation/adapters/standard.d.ts +11 -0
- package/dist/src/validation/adapters/standard.js +110 -0
- package/dist/src/validation/adapters/zod.d.ts +9 -0
- package/dist/src/validation/adapters/zod.js +128 -0
- package/dist/src/validation/cache.d.ts +26 -0
- package/dist/src/validation/cache.js +35 -0
- package/dist/src/validation/coerce.d.ts +28 -0
- package/dist/src/validation/coerce.js +176 -0
- package/dist/src/validation/compiler.d.ts +27 -0
- package/dist/src/validation/compiler.js +191 -0
- package/dist/src/validation/error.d.ts +69 -0
- package/dist/src/validation/error.js +137 -0
- package/dist/src/validation/index.d.ts +16 -0
- package/dist/src/validation/index.js +12 -0
- package/dist/src/validation/response.d.ts +25 -0
- package/dist/src/validation/response.js +79 -0
- package/dist/src/validation/types.d.ts +148 -0
- package/dist/src/validation/types.js +6 -0
- package/dist/src/validation/validator.d.ts +39 -0
- package/dist/src/validation/validator.js +441 -0
- package/dist/src/ws/adapter.d.ts +219 -0
- package/dist/src/ws/adapter.js +623 -0
- package/dist/src/ws/compiler.d.ts +37 -0
- package/dist/src/ws/compiler.js +156 -0
- package/dist/src/ws/index.d.ts +11 -0
- package/dist/src/ws/index.js +8 -0
- package/dist/src/ws/platform.d.ts +81 -0
- package/dist/src/ws/platform.js +113 -0
- package/dist/src/ws/router.d.ts +48 -0
- package/dist/src/ws/router.js +174 -0
- package/dist/src/ws/scanner.d.ts +97 -0
- package/dist/src/ws/scanner.js +193 -0
- package/dist/src/ws/types.d.ts +380 -0
- package/dist/src/ws/types.js +213 -0
- package/package.json +72 -59
- package/dist/src/core/api-router.d.ts +0 -65
- package/dist/src/core/api-router.js +0 -264
- package/dist/src/core/swagger-ui.d.ts +0 -1
- package/dist/src/core/swagger-ui.js +0 -33
- package/dist/src/middleware/validator.d.ts +0 -14
- package/dist/src/middleware/validator.js +0 -133
- package/dist/src/utils/error.d.ts +0 -17
- package/dist/src/utils/error.js +0 -63
|
@@ -1,17 +1,182 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The
|
|
2
|
+
* The 404 body is a constant (RFC 9457 Problem Details), so it is serialized
|
|
3
|
+
* once; every call builds a fresh `Response` over it.
|
|
3
4
|
*/
|
|
4
|
-
|
|
5
|
-
|
|
5
|
+
const NOT_FOUND_BODY = JSON.stringify({
|
|
6
|
+
type: 'about:blank',
|
|
7
|
+
title: 'Not Found',
|
|
8
|
+
status: 404,
|
|
9
|
+
detail: 'Not Found',
|
|
6
10
|
});
|
|
7
11
|
/**
|
|
8
|
-
*
|
|
12
|
+
* 404 init with a prebuilt `Headers`: the constructor copies it, which is
|
|
13
|
+
* much cheaper than parsing a plain headers object per call. Built on first
|
|
14
|
+
* use, never at module scope (Workers restrict work during module load).
|
|
9
15
|
*/
|
|
10
|
-
|
|
16
|
+
let notFoundInit;
|
|
11
17
|
/**
|
|
12
|
-
*
|
|
18
|
+
* Builds the framework's 404 response (RFC 9457 Problem Details). A fresh
|
|
19
|
+
* `Response` per call: a cached template cannot be cloned reliably — runtimes
|
|
20
|
+
* (workerd) lock a shared template's body stream once it has been served, so
|
|
21
|
+
* the next `clone()` throws and the request 500s.
|
|
13
22
|
*/
|
|
14
|
-
export const
|
|
23
|
+
export const notFound = () => new Response(NOT_FOUND_BODY, (notFoundInit ??= {
|
|
24
|
+
status: 404,
|
|
25
|
+
headers: new Headers({
|
|
26
|
+
'Content-Type': 'application/problem+json',
|
|
27
|
+
}),
|
|
28
|
+
}));
|
|
29
|
+
/**
|
|
30
|
+
* The OpenAPI error response. A factory — see {@link notFound}: never share a
|
|
31
|
+
* `Response` instance with a body across requests.
|
|
32
|
+
*/
|
|
33
|
+
export const openApiError = () => Response.json({
|
|
15
34
|
error: 'API Router not configured',
|
|
16
35
|
message: 'Please provide an apiDir option when initializing the Burger instance to enable OpenAPI documentation.',
|
|
17
36
|
});
|
|
37
|
+
/**
|
|
38
|
+
* Per-`Allow` 405 templates, built once and reused. Bodies are single-use, so
|
|
39
|
+
* each request gets a fresh `Response` over the same immutable init; the map
|
|
40
|
+
* is bounded by the route table's `Allow` values.
|
|
41
|
+
*/
|
|
42
|
+
const methodNotAllowedTemplates = new Map();
|
|
43
|
+
/**
|
|
44
|
+
* Builds a 405 (RFC 9457) with the `Allow` header listing the methods the
|
|
45
|
+
* matched route supports.
|
|
46
|
+
* @param allow - comma-separated allowed methods, e.g. "GET, POST"
|
|
47
|
+
*/
|
|
48
|
+
export function methodNotAllowed(allow) {
|
|
49
|
+
let template = methodNotAllowedTemplates.get(allow);
|
|
50
|
+
if (template === undefined) {
|
|
51
|
+
template = {
|
|
52
|
+
body: JSON.stringify({
|
|
53
|
+
type: 'about:blank',
|
|
54
|
+
title: 'Method Not Allowed',
|
|
55
|
+
status: 405,
|
|
56
|
+
detail: `Supported methods: ${allow}`,
|
|
57
|
+
}),
|
|
58
|
+
headers: new Headers({
|
|
59
|
+
Allow: allow,
|
|
60
|
+
'Content-Type': 'application/problem+json',
|
|
61
|
+
}),
|
|
62
|
+
};
|
|
63
|
+
methodNotAllowedTemplates.set(allow, template);
|
|
64
|
+
}
|
|
65
|
+
return new Response(template.body, {
|
|
66
|
+
status: 405,
|
|
67
|
+
headers: template.headers,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
export const createAutoOptionsHandler = (allowMethods) => {
|
|
71
|
+
const allowHeader = allowMethods.join(', ');
|
|
72
|
+
const handler = (() => new Response(null, {
|
|
73
|
+
status: 204,
|
|
74
|
+
headers: { Allow: allowHeader },
|
|
75
|
+
}));
|
|
76
|
+
handler.isAutoOptions = true;
|
|
77
|
+
handler.allowHeader = allowHeader;
|
|
78
|
+
return handler;
|
|
79
|
+
};
|
|
80
|
+
import { SET_HEADERS, TrackedContextSet, } from '../context/context-set.js';
|
|
81
|
+
/**
|
|
82
|
+
* Whether a `ContextSet` carries any response mutation. For the framework's
|
|
83
|
+
* `TrackedContextSet` it is one flag read; plain objects fall back to a scan.
|
|
84
|
+
* `applySet` uses this to skip rebuilding the `Response`.
|
|
85
|
+
*/
|
|
86
|
+
export function hasSetMutations(set) {
|
|
87
|
+
if (!set)
|
|
88
|
+
return false;
|
|
89
|
+
if (set instanceof TrackedContextSet)
|
|
90
|
+
return set.flags !== 0;
|
|
91
|
+
if (set.status !== undefined)
|
|
92
|
+
return true;
|
|
93
|
+
const headers = set.headers;
|
|
94
|
+
if (headers) {
|
|
95
|
+
if (headers instanceof Headers) {
|
|
96
|
+
// Bun's `Headers.size` typing is unreliable; iterate to detect content.
|
|
97
|
+
for (const _ of headers) {
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
else if (Object.keys(headers).length > 0) {
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Merges a `ContextSet` (`ctx.set`) into the outgoing `Response`:
|
|
109
|
+
* - `set.headers` is merged over the response's headers; explicitly set values
|
|
110
|
+
* win and other handler headers are kept.
|
|
111
|
+
* - `set.status` overrides the response status only when defined, and NEVER
|
|
112
|
+
* overrides an error status (>= 400) — errors stay errors.
|
|
113
|
+
* - Runs once at the pipeline exit, for every response path; returns the
|
|
114
|
+
* original `Response` unchanged when there is nothing to apply.
|
|
115
|
+
*/
|
|
116
|
+
export function applySet(response, set) {
|
|
117
|
+
if (!set)
|
|
118
|
+
return response;
|
|
119
|
+
// Errors are authoritative: `ctx.set.status` may only restyle successes.
|
|
120
|
+
const setStatus = response.status >= 400 ? undefined : set.status;
|
|
121
|
+
if (set instanceof TrackedContextSet) {
|
|
122
|
+
const flags = set.flags;
|
|
123
|
+
if (flags === 0)
|
|
124
|
+
return response;
|
|
125
|
+
if ((flags & SET_HEADERS) === 0) {
|
|
126
|
+
// Status-only mutation: the `Response` constructor copies the
|
|
127
|
+
// header list itself, so no explicit `new Headers(...)` copy is
|
|
128
|
+
// needed.
|
|
129
|
+
return new Response(response.body, {
|
|
130
|
+
status: setStatus ?? response.status,
|
|
131
|
+
statusText: response.statusText,
|
|
132
|
+
headers: response.headers,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
else if (!hasSetMutations(set)) {
|
|
137
|
+
return response;
|
|
138
|
+
}
|
|
139
|
+
const headers = new Headers(response.headers);
|
|
140
|
+
const setHeaders = set.headers;
|
|
141
|
+
if (setHeaders) {
|
|
142
|
+
if (setHeaders instanceof Headers) {
|
|
143
|
+
// Preserve every Set-Cookie value (iteration may combine them).
|
|
144
|
+
const getSetCookie = setHeaders.getSetCookie;
|
|
145
|
+
if (typeof getSetCookie === 'function') {
|
|
146
|
+
for (const cookie of getSetCookie.call(setHeaders)) {
|
|
147
|
+
headers.append('set-cookie', cookie);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
for (const entry of setHeaders) {
|
|
151
|
+
if (entry[0].toLowerCase() === 'set-cookie')
|
|
152
|
+
continue;
|
|
153
|
+
headers.set(entry[0], entry[1]);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
for (const key in setHeaders) {
|
|
158
|
+
const value = setHeaders[key];
|
|
159
|
+
if (value === undefined)
|
|
160
|
+
continue;
|
|
161
|
+
// Arrays append (multiple cookies); a scalar Set-Cookie is
|
|
162
|
+
// appended too, so a handler-set cookie survives. Other
|
|
163
|
+
// headers keep "ctx.set wins".
|
|
164
|
+
if (Array.isArray(value)) {
|
|
165
|
+
for (const item of value)
|
|
166
|
+
headers.append(key, item);
|
|
167
|
+
}
|
|
168
|
+
else if (key.toLowerCase() === 'set-cookie') {
|
|
169
|
+
headers.append(key, value);
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
headers.set(key, value);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return new Response(response.body, {
|
|
178
|
+
status: setStatus ?? response.status,
|
|
179
|
+
statusText: response.statusText,
|
|
180
|
+
headers,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
@@ -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:
|
|
21
|
+
export declare const HTTP_METHODS: readonly ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
|
|
21
22
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
|
|
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
|
|
37
|
+
* @returns The specificity score.
|
|
27
38
|
*/
|
|
28
39
|
export declare const getRouteSpecificity: (path: string) => number;
|
|
29
40
|
/**
|
|
30
|
-
* Compares two routes for sorting
|
|
31
|
-
*
|
|
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
|
|
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
|
|
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
|
|
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
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
|
53
|
-
*
|
|
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
|
|
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
|
|
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
|
|
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,7 @@
|
|
|
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
|
-
/**
|
|
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/*")
|
|
13
|
-
*/
|
|
14
|
-
export declare function extractWildcardParams(request: BurgerRequest, pathname: string, baseSegmentCount: number): void;
|
|
@@ -1,66 +1,28 @@
|
|
|
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
|
-
//
|
|
8
|
-
//
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
//
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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/*")
|
|
27
|
-
*/
|
|
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
|
-
}
|
|
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);
|
|
61
25
|
}
|
|
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
26
|
}
|
|
27
|
+
return url.slice(pathStart);
|
|
66
28
|
}
|
|
@@ -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
|
+
}
|