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.
- 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 -60
- 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
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { readdir } from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { ROUTE_CONSTANTS } from '../utils/routing.js';
|
|
4
|
+
import { filePathToApiRoutePath } from '../utils/pathConversion.js';
|
|
5
|
+
import { resolveScanDir } from '../utils/fs.js';
|
|
6
|
+
import { assertConventionFile, isConventionFile, splitConventionName, } from './conventions.js';
|
|
7
|
+
/**
|
|
8
|
+
* Walks a route directory tree and produces a pure inventory of route
|
|
9
|
+
* directories — the first stage of the compiler pipeline.
|
|
10
|
+
*
|
|
11
|
+
* The scanner only enumerates files and computes route paths; it never calls
|
|
12
|
+
* `import()` (that is the Module Loader's job), keeping the walk cheap,
|
|
13
|
+
* deterministic, and side-effect free. Each route directory is
|
|
14
|
+
* self-contained — no group inheritance chain; groups only strip URL paths.
|
|
15
|
+
*
|
|
16
|
+
* Fail-fast rules:
|
|
17
|
+
* - Only recognized convention files are acknowledged; `middleware.ts` is forbidden.
|
|
18
|
+
* - At most one dynamic (`[param]`) and one wildcard (`[...]`) folder per
|
|
19
|
+
* level (they may coexist; priority is static > param > wildcard).
|
|
20
|
+
* - Named wildcard folders (`[...slug]`) are not supported yet.
|
|
21
|
+
*/
|
|
22
|
+
export class DirectoryScanner {
|
|
23
|
+
routesDir;
|
|
24
|
+
prefix;
|
|
25
|
+
constructor(routesDir, prefix = '') {
|
|
26
|
+
this.routesDir = routesDir;
|
|
27
|
+
this.prefix = prefix;
|
|
28
|
+
if (!routesDir) {
|
|
29
|
+
throw new Error('Routes directory path is required');
|
|
30
|
+
}
|
|
31
|
+
this.routesDir = resolveScanDir(routesDir, 'Routes', 'apiDir');
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Scans the tree and returns a {@link ScanResult} containing:
|
|
35
|
+
* - `routes`: one {@link ScannedRoute} per directory that contains a `route.ts`
|
|
36
|
+
* - `globalHooks`: path to `hooks.ts` at the root of the routes directory (if any)
|
|
37
|
+
* @throws on forbidden files or conflicting dynamic/wildcard folders.
|
|
38
|
+
*/
|
|
39
|
+
async scan() {
|
|
40
|
+
const routes = [];
|
|
41
|
+
await this.walk(this.routesDir, routes);
|
|
42
|
+
// App-level convention files (hooks.ts, openapi.config.ts, plugins.ts,
|
|
43
|
+
// providers.ts) are siblings of the entry point — the parent of the
|
|
44
|
+
// routes directory.
|
|
45
|
+
const appFiles = await collectAppConventionFiles(path.dirname(this.routesDir));
|
|
46
|
+
return { routes, ...appFiles };
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Recursively walks `dir` and emits a `ScannedRoute` whenever a `route.ts`
|
|
50
|
+
* is found. Group folders `(name)` are traversed for URL stripping but
|
|
51
|
+
* do NOT build an inheritance chain.
|
|
52
|
+
*/
|
|
53
|
+
async walk(dir, out) {
|
|
54
|
+
let dynamicFolderFound = false;
|
|
55
|
+
let wildcardFolderFound = false;
|
|
56
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
57
|
+
// Separate files from subdirectories so we can validate folder
|
|
58
|
+
// conflicts before recursing.
|
|
59
|
+
const subDirs = [];
|
|
60
|
+
// Collect convention files per stem (`route`, `schema`, …) across
|
|
61
|
+
// all accepted extensions (.ts/.js/.mjs).
|
|
62
|
+
const conventionByStem = new Map();
|
|
63
|
+
for (const entry of entries) {
|
|
64
|
+
if (entry.isDirectory()) {
|
|
65
|
+
subDirs.push(entry.name);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (!entry.isFile())
|
|
69
|
+
continue;
|
|
70
|
+
const split = splitConventionName(entry.name);
|
|
71
|
+
if (!split)
|
|
72
|
+
continue;
|
|
73
|
+
// Reject forbidden files (e.g. `middleware.ts`) regardless of
|
|
74
|
+
// whether they are a recognized convention file.
|
|
75
|
+
assertConventionFile(split.stem);
|
|
76
|
+
// Non-convention files (helpers, fixtures) are ignored.
|
|
77
|
+
if (!isConventionFile(split.stem))
|
|
78
|
+
continue;
|
|
79
|
+
const abs = path.resolve(path.join(dir, entry.name));
|
|
80
|
+
const existing = conventionByStem.get(split.stem);
|
|
81
|
+
if (existing) {
|
|
82
|
+
throw new Error(`Conflicting convention files "${existing}" and "${abs}" in "${dir}" — ` +
|
|
83
|
+
`a route directory must not contain both ${split.stem}.ts and ${split.stem}.js (or .mjs).`);
|
|
84
|
+
}
|
|
85
|
+
conventionByStem.set(split.stem, abs);
|
|
86
|
+
}
|
|
87
|
+
// Validate folder-level conflicts.
|
|
88
|
+
for (const name of subDirs) {
|
|
89
|
+
// Named wildcard folders (`[...slug]`) become literal path
|
|
90
|
+
// segments that can never match — fail loud instead of emitting
|
|
91
|
+
// a dead route.
|
|
92
|
+
if (name.startsWith(ROUTE_CONSTANTS.WILDCARD_START) &&
|
|
93
|
+
name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
|
|
94
|
+
throw new Error(`Named wildcard folder '${name}' is not supported — ` +
|
|
95
|
+
`use '${ROUTE_CONSTANTS.WILDCARD_SIMPLE}' (anonymous) instead.`);
|
|
96
|
+
}
|
|
97
|
+
const isDynamic = name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
98
|
+
name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
|
|
99
|
+
!name.startsWith(ROUTE_CONSTANTS.WILDCARD_START);
|
|
100
|
+
const isWildcard = name === ROUTE_CONSTANTS.WILDCARD_SIMPLE;
|
|
101
|
+
// Dynamic + wildcard siblings are legal — the trie resolves
|
|
102
|
+
// them by priority (static > `:param` > `*`, with backtracking).
|
|
103
|
+
if (isDynamic && dynamicFolderFound) {
|
|
104
|
+
throw new Error(`Multiple dynamic route folders found in the same directory: ` +
|
|
105
|
+
`'${name}' conflicts with another dynamic folder in '${dir}'.`);
|
|
106
|
+
}
|
|
107
|
+
if (isWildcard && wildcardFolderFound) {
|
|
108
|
+
throw new Error(`Multiple wildcard route folders found in the same directory: ` +
|
|
109
|
+
`'${name}' conflicts with another wildcard folder in '${dir}'.`);
|
|
110
|
+
}
|
|
111
|
+
if (isDynamic)
|
|
112
|
+
dynamicFolderFound = true;
|
|
113
|
+
if (isWildcard)
|
|
114
|
+
wildcardFolderFound = true;
|
|
115
|
+
}
|
|
116
|
+
// Gather this directory's convention files.
|
|
117
|
+
const localFiles = {};
|
|
118
|
+
let hasRoute = false;
|
|
119
|
+
for (const [stem, abs] of conventionByStem) {
|
|
120
|
+
localFiles[stem] = abs;
|
|
121
|
+
if (stem === 'route')
|
|
122
|
+
hasRoute = true;
|
|
123
|
+
}
|
|
124
|
+
if (hasRoute) {
|
|
125
|
+
const routeFilePath = localFiles.route;
|
|
126
|
+
// Convert from the path *relative to* the scanned root so that the
|
|
127
|
+
// absolute temp/working-directory prefix does not leak into the
|
|
128
|
+
// route path.
|
|
129
|
+
const relativeFilePath = path.relative(this.routesDir, routeFilePath);
|
|
130
|
+
const routePath = filePathToApiRoutePath(relativeFilePath, this.prefix);
|
|
131
|
+
out.push({
|
|
132
|
+
routePath,
|
|
133
|
+
routeDir: path.resolve(dir),
|
|
134
|
+
localFiles,
|
|
135
|
+
isWildcard: routePath.includes(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX),
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
// Recurse into subdirectories.
|
|
139
|
+
for (const name of subDirs) {
|
|
140
|
+
const childPath = path.join(dir, name);
|
|
141
|
+
// Named wildcard folders (`[...slug]`) are skipped for now.
|
|
142
|
+
if (name.startsWith(ROUTE_CONSTANTS.WILDCARD_START) &&
|
|
143
|
+
name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
await this.walk(childPath, out);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Discovers the app-level convention files (`hooks`, `openapi.config`,
|
|
152
|
+
* `plugins`, `providers`) in `appRoot`. Conflicting extensions for one stem
|
|
153
|
+
* fail loud.
|
|
154
|
+
*/
|
|
155
|
+
async function collectAppConventionFiles(appRoot) {
|
|
156
|
+
let rootEntries = [];
|
|
157
|
+
try {
|
|
158
|
+
rootEntries = await readdir(appRoot, { withFileTypes: true });
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
// Directory may not exist — ignore.
|
|
162
|
+
}
|
|
163
|
+
const rootFiles = {};
|
|
164
|
+
for (const entry of rootEntries) {
|
|
165
|
+
if (!entry.isFile())
|
|
166
|
+
continue;
|
|
167
|
+
const split = splitConventionName(entry.name);
|
|
168
|
+
if (!split)
|
|
169
|
+
continue;
|
|
170
|
+
const stem = split.stem;
|
|
171
|
+
if (stem !== 'hooks' &&
|
|
172
|
+
stem !== 'openapi.config' &&
|
|
173
|
+
stem !== 'plugins' &&
|
|
174
|
+
stem !== 'providers') {
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
const existing = rootFiles[stem];
|
|
178
|
+
if (existing) {
|
|
179
|
+
throw new Error(`Conflicting app-level convention files "${existing}" and "${path.join(appRoot, entry.name)}" — ` +
|
|
180
|
+
`use only one of .ts/.js/.mjs per convention file.`);
|
|
181
|
+
}
|
|
182
|
+
rootFiles[stem] = path.resolve(path.join(appRoot, entry.name));
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
globalHooks: rootFiles['hooks'],
|
|
186
|
+
openAPIConfigPath: rootFiles['openapi.config'],
|
|
187
|
+
pluginsPath: rootFiles['plugins'],
|
|
188
|
+
providersPath: rootFiles['providers'],
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* App-root convention files for apps with no API directory (pages-only).
|
|
193
|
+
* Returns a route-less {@link ScanResult} so the Module Loader can load
|
|
194
|
+
* hooks/plugins/providers exactly like it does for API apps.
|
|
195
|
+
*/
|
|
196
|
+
export async function scanAppRootConventions(appRoot) {
|
|
197
|
+
const appFiles = await collectAppConventionFiles(appRoot);
|
|
198
|
+
return { routes: [], ...appFiles };
|
|
199
|
+
}
|
|
200
|
+
/** Re-exported for convenience / symmetry with the module loader. */
|
|
201
|
+
export { CONVENTION_FILES } from './conventions.js';
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ContextSet } from './types.js';
|
|
2
|
+
/** Mutation flag: `set.status` was assigned. */
|
|
3
|
+
export declare const SET_STATUS = 1;
|
|
4
|
+
/** Mutation flag: `set.headers` was assigned. */
|
|
5
|
+
export declare const SET_HEADERS = 2;
|
|
6
|
+
/**
|
|
7
|
+
* The lazily allocated `ctx.set`. Accessors flip a flag on every assignment,
|
|
8
|
+
* so `applySet` knows what changed without re-scanning the object.
|
|
9
|
+
* Private fields keep the backing storage out of `Object.keys(ctx.set)`.
|
|
10
|
+
*/
|
|
11
|
+
export declare class TrackedContextSet implements ContextSet {
|
|
12
|
+
#private;
|
|
13
|
+
/** Bitmask of the fields that were assigned (`SET_STATUS` / `SET_HEADERS`). */
|
|
14
|
+
get flags(): number;
|
|
15
|
+
get status(): number | undefined;
|
|
16
|
+
set status(value: number | undefined);
|
|
17
|
+
/**
|
|
18
|
+
* Always defined: lazily creates the record on first access, so
|
|
19
|
+
* `ctx.set.headers['x-id'] = v` never throws. Reading it marks headers as
|
|
20
|
+
* mutated; `applySet` reads this only after the flag is set.
|
|
21
|
+
*/
|
|
22
|
+
get headers(): Record<string, string | string[]> | Headers;
|
|
23
|
+
set headers(value: Record<string, string | string[]> | Headers | undefined);
|
|
24
|
+
/** Keeps `JSON.stringify(ctx.set)` / logging as readable as a plain object. */
|
|
25
|
+
toJSON(): ContextSet;
|
|
26
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Mutation flag: `set.status` was assigned. */
|
|
2
|
+
export const SET_STATUS = 1;
|
|
3
|
+
/** Mutation flag: `set.headers` was assigned. */
|
|
4
|
+
export const SET_HEADERS = 2;
|
|
5
|
+
/**
|
|
6
|
+
* The lazily allocated `ctx.set`. Accessors flip a flag on every assignment,
|
|
7
|
+
* so `applySet` knows what changed without re-scanning the object.
|
|
8
|
+
* Private fields keep the backing storage out of `Object.keys(ctx.set)`.
|
|
9
|
+
*/
|
|
10
|
+
export class TrackedContextSet {
|
|
11
|
+
#flags = 0;
|
|
12
|
+
#status;
|
|
13
|
+
#headers;
|
|
14
|
+
/** Bitmask of the fields that were assigned (`SET_STATUS` / `SET_HEADERS`). */
|
|
15
|
+
get flags() {
|
|
16
|
+
return this.#flags;
|
|
17
|
+
}
|
|
18
|
+
get status() {
|
|
19
|
+
return this.#status;
|
|
20
|
+
}
|
|
21
|
+
set status(value) {
|
|
22
|
+
this.#status = value;
|
|
23
|
+
this.#flags |= SET_STATUS;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Always defined: lazily creates the record on first access, so
|
|
27
|
+
* `ctx.set.headers['x-id'] = v` never throws. Reading it marks headers as
|
|
28
|
+
* mutated; `applySet` reads this only after the flag is set.
|
|
29
|
+
*/
|
|
30
|
+
get headers() {
|
|
31
|
+
if (this.#headers === undefined) {
|
|
32
|
+
this.#headers = {};
|
|
33
|
+
this.#flags |= SET_HEADERS;
|
|
34
|
+
}
|
|
35
|
+
return this.#headers;
|
|
36
|
+
}
|
|
37
|
+
set headers(value) {
|
|
38
|
+
this.#headers = value;
|
|
39
|
+
this.#flags |= SET_HEADERS;
|
|
40
|
+
}
|
|
41
|
+
/** Keeps `JSON.stringify(ctx.set)` / logging as readable as a plain object. */
|
|
42
|
+
toJSON() {
|
|
43
|
+
return { status: this.#status, headers: this.#headers };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import type { ContextInit, ContextSet, RouteAccessInfo, RouteMeta } from './types.js';
|
|
2
|
+
import type { InferValidated } from '../types/inference.js';
|
|
3
|
+
import type { RouteMethodSchema } from '../types/inference.js';
|
|
4
|
+
import type { RouteConfig } from '../types/index.js';
|
|
5
|
+
/**
|
|
6
|
+
* Module augmentation target for `ctx.services`:
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* declare module "burger-api" {
|
|
10
|
+
* interface BurgerServices {
|
|
11
|
+
* db: Database;
|
|
12
|
+
* logger: Logger;
|
|
13
|
+
* }
|
|
14
|
+
* }
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
export interface BurgerServices {
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Module augmentation target for `ctx.validated`. Default slots match the
|
|
21
|
+
* validator: `params`, `query`, `body`, `headers`, `cookies`.
|
|
22
|
+
*
|
|
23
|
+
* `BurgerContext<typeof GET>` types it from `schema.ts` automatically;
|
|
24
|
+
* augmentation is the escape hatch for anything inference cannot express:
|
|
25
|
+
*
|
|
26
|
+
* ```ts
|
|
27
|
+
* declare module "burger-api" {
|
|
28
|
+
* interface BurgerValidated {
|
|
29
|
+
* body: { name: string };
|
|
30
|
+
* }
|
|
31
|
+
* }
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export interface BurgerValidated {
|
|
35
|
+
params?: unknown;
|
|
36
|
+
query?: unknown;
|
|
37
|
+
body?: unknown;
|
|
38
|
+
headers?: unknown;
|
|
39
|
+
cookies?: unknown;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Module augmentation target for deployment-platform bindings (`ctx.env`).
|
|
43
|
+
* `toFetchHandler(burger)` on WinterCG targets receives the platform `env`;
|
|
44
|
+
* plain Bun `serve()` leaves it `undefined`:
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* declare module "burger-api" {
|
|
48
|
+
* interface BurgerEnv {
|
|
49
|
+
* MY_DB: D1Database;
|
|
50
|
+
* SECRETS: { apiKey: string };
|
|
51
|
+
* }
|
|
52
|
+
* }
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export interface BurgerEnv {
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Minimal view of a platform execution context (third argument of a WinterCG
|
|
59
|
+
* `fetch(request, env, ctx)` handler). Only `waitUntil` is modeled.
|
|
60
|
+
*/
|
|
61
|
+
export interface BurgerExecutionContext {
|
|
62
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
63
|
+
}
|
|
64
|
+
/** A server handle that can report a request's peer address (Bun's `Server`). */
|
|
65
|
+
export interface RequestIPSource {
|
|
66
|
+
requestIP(request: Request): {
|
|
67
|
+
address: string;
|
|
68
|
+
} | null | undefined;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* A server handle that can publish to WebSocket topic subscribers (Bun's
|
|
72
|
+
* `Server`). Reached through the same per-app holder as {@link RequestIPSource}
|
|
73
|
+
* so `ctx.publish` resolves lazily without per-request bookkeeping.
|
|
74
|
+
*/
|
|
75
|
+
export interface PublishSource {
|
|
76
|
+
/**
|
|
77
|
+
* @returns Bun's send status: bytes sent, `0` when dropped, `-1` on
|
|
78
|
+
* backpressure.
|
|
79
|
+
*/
|
|
80
|
+
publish(topic: string, message: string | Uint8Array, compress?: boolean): number;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Per-app mutable reference to the serving runtime's server. The adapter
|
|
84
|
+
* writes the server once at startup (stable for the life of the server), so
|
|
85
|
+
* `ctx.ip` and `ctx.publish` resolve lazily with no per-request bookkeeping.
|
|
86
|
+
*/
|
|
87
|
+
export interface RequestIPHolder {
|
|
88
|
+
server?: RequestIPSource & Partial<PublishSource>;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Shared services object for apps without `burger.provide()` providers.
|
|
92
|
+
* Frozen: services are app-scoped singletons, never per-request scratch space.
|
|
93
|
+
*/
|
|
94
|
+
export declare const EMPTY_SERVICES: BurgerServices;
|
|
95
|
+
/**
|
|
96
|
+
* Resolves the app-level services for `ctx.services` once, at compile time.
|
|
97
|
+
* Providers are app-scoped singletons, so the resulting frozen bag is shared
|
|
98
|
+
* by every request; a prebuilt object passes through unchanged.
|
|
99
|
+
*/
|
|
100
|
+
export declare function createServices(providers?: Map<string, unknown> | BurgerServices): BurgerServices;
|
|
101
|
+
/**
|
|
102
|
+
* Records the client (socket peer) address for a request so `ctx.ip` can
|
|
103
|
+
* report it. Pass the address string (e.g. a Node adapter's
|
|
104
|
+
* `socket.remoteAddress`) or a server with `requestIP(request)` (Bun),
|
|
105
|
+
* resolved lazily on first read. Adapter-facing; apps read `ctx.ip`.
|
|
106
|
+
*/
|
|
107
|
+
export declare function setRequestIP(request: Request, source: string | RequestIPSource): void;
|
|
108
|
+
/** True when `value` looks like a server that can resolve peer addresses. */
|
|
109
|
+
export declare function isRequestIPSource(value: unknown): value is RequestIPSource;
|
|
110
|
+
/**
|
|
111
|
+
* Module augmentation target for the authenticated user's fields, shared by
|
|
112
|
+
* the auth plugins (basic-auth, jwt-auth, oidc) and typed on both `ctx.user`
|
|
113
|
+
* and `ws.user`:
|
|
114
|
+
*
|
|
115
|
+
* ```ts
|
|
116
|
+
* declare module "burger-api" {
|
|
117
|
+
* interface BurgerAuthUser {
|
|
118
|
+
* tenantId: string;
|
|
119
|
+
* }
|
|
120
|
+
* }
|
|
121
|
+
* ```
|
|
122
|
+
*
|
|
123
|
+
* Augment this (not `BurgerContext.user`) so user fields coexist with every
|
|
124
|
+
* auth plugin; the plugins merge their own fields here too.
|
|
125
|
+
*/
|
|
126
|
+
export interface BurgerAuthUser {
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Module augmentation target for custom properties on BurgerContext, e.g.
|
|
130
|
+
* request-scoped values set in `transform` hooks:
|
|
131
|
+
*
|
|
132
|
+
* ```ts
|
|
133
|
+
* declare module "burger-api" {
|
|
134
|
+
* interface BurgerContext {
|
|
135
|
+
* tenant: Tenant;
|
|
136
|
+
* }
|
|
137
|
+
* }
|
|
138
|
+
* ```
|
|
139
|
+
*
|
|
140
|
+
* `user` is declared here (typed via `BurgerAuthUser`) so auth plugins and
|
|
141
|
+
* apps always agree on one shape. The class is defined below; this interface
|
|
142
|
+
* exists for declaration merging.
|
|
143
|
+
*/
|
|
144
|
+
export interface BurgerContext {
|
|
145
|
+
/**
|
|
146
|
+
* The authenticated user, set by an auth plugin during the request
|
|
147
|
+
* lifecycle. `undefined` when no auth plugin ran (or it rejected).
|
|
148
|
+
*/
|
|
149
|
+
user?: BurgerAuthUser & Record<string, unknown>;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* `BurgerContext` — the public request context type.
|
|
153
|
+
*
|
|
154
|
+
* Exactly one instance is allocated per request via `BurgerContext.create()`;
|
|
155
|
+
* it is re-bound to the matched route, never re-allocated.
|
|
156
|
+
*
|
|
157
|
+
* Generic over the route's `schema.ts` method export for `ctx.validated`
|
|
158
|
+
* inference:
|
|
159
|
+
*
|
|
160
|
+
* ```ts
|
|
161
|
+
* // schema.ts
|
|
162
|
+
* export const GET = { query: z.object({ q: z.string() }) };
|
|
163
|
+
*
|
|
164
|
+
* // route.ts
|
|
165
|
+
* import type { GET as RouteSchema } from './schema';
|
|
166
|
+
* export async function GET(ctx: BurgerContext<typeof RouteSchema>) {
|
|
167
|
+
* ctx.validated.query; // { q: string } | undefined
|
|
168
|
+
* }
|
|
169
|
+
* ```
|
|
170
|
+
*
|
|
171
|
+
* The default type parameter keeps plain `BurgerContext` working (slots fall
|
|
172
|
+
* back to `unknown`, `BurgerValidated` augmentation applies).
|
|
173
|
+
*
|
|
174
|
+
* One shared frozen prototype carries every lazy getter and delegated
|
|
175
|
+
* `Request` member; instances hold only mutable state, so every instance has
|
|
176
|
+
* the same shape. Fields are parsed lazily and at most once — a field a route
|
|
177
|
+
* never reads is never parsed.
|
|
178
|
+
*/
|
|
179
|
+
export declare class BurgerContext<TRoute = unknown> {
|
|
180
|
+
/**
|
|
181
|
+
* The underlying `Request`; the standard `Request` surface delegates to
|
|
182
|
+
* it. Never copied.
|
|
183
|
+
*
|
|
184
|
+
* `declare` (never `!`) keeps the field type-only: a class-field
|
|
185
|
+
* initializer would re-define it on every `new BurgerContext()` and
|
|
186
|
+
* duplicate the assignments `create()` performs in declaration order.
|
|
187
|
+
*/
|
|
188
|
+
private _raw;
|
|
189
|
+
/**
|
|
190
|
+
* Route-specific data seeded at creation. Exposed via the `params` /
|
|
191
|
+
* `wildcardParams` / `route` getters.
|
|
192
|
+
*/
|
|
193
|
+
private _ctxInit;
|
|
194
|
+
/** Cached parsed query (lazy). `undefined` until first access. */
|
|
195
|
+
private _query;
|
|
196
|
+
/** Cached parsed cookies (lazy). `undefined` until first access. */
|
|
197
|
+
private _cookies;
|
|
198
|
+
/**
|
|
199
|
+
* Cached `json()` result. `undefined` until the body is parsed. Lets
|
|
200
|
+
* `ctx.json()` be called again after validation read the stream.
|
|
201
|
+
*/
|
|
202
|
+
private _json;
|
|
203
|
+
/**
|
|
204
|
+
* The raw body bytes, read at most once and cached. Body validation reads
|
|
205
|
+
* through this, so `ctx.text()` / `ctx.arrayBuffer()` still work after it
|
|
206
|
+
* (webhook signatures) and no cost is paid when nobody asks.
|
|
207
|
+
*/
|
|
208
|
+
private _bodyBuffer;
|
|
209
|
+
/** The body as text, cached alongside `_bodyBuffer` (see `text()`). */
|
|
210
|
+
private _bodyText;
|
|
211
|
+
/**
|
|
212
|
+
* Validated data attached by the validation hook. Starts `undefined` so
|
|
213
|
+
* the hook runs (it short-circuits when already truthy).
|
|
214
|
+
*
|
|
215
|
+
* Typed from `schema.ts` via `BurgerContext<typeof GET>`, falling back to
|
|
216
|
+
* `BurgerValidated`. When the route declares a schema the type is
|
|
217
|
+
* non-undefined: a failed validation throws 422 and the handler never
|
|
218
|
+
* runs. A plain `BurgerContext` keeps `| undefined` (no schema, no hook).
|
|
219
|
+
*/
|
|
220
|
+
validated: TRoute extends RouteMethodSchema ? InferValidated<TRoute> & BurgerValidated : (InferValidated<TRoute> & BurgerValidated) | undefined;
|
|
221
|
+
/**
|
|
222
|
+
* The response-mutation object exposed through `ctx.set`. Allocated
|
|
223
|
+
* lazily on first access (most requests never mutate the response) and
|
|
224
|
+
* merged into the response by `applySet` at the pipeline exit. `cookies`
|
|
225
|
+
* is reserved for a future release.
|
|
226
|
+
*/
|
|
227
|
+
private _set;
|
|
228
|
+
/** True once anything touched `ctx.set` (lazy allocation marker). */
|
|
229
|
+
hasSet(): boolean;
|
|
230
|
+
get set(): ContextSet;
|
|
231
|
+
set set(value: ContextSet);
|
|
232
|
+
/**
|
|
233
|
+
* Injected application services from `burger.provide()`, typed via
|
|
234
|
+
* augmentation of `BurgerServices`. Assigned once in `create()`: one
|
|
235
|
+
* frozen, shared object — never a per-request copy.
|
|
236
|
+
*/
|
|
237
|
+
services: BurgerServices;
|
|
238
|
+
/**
|
|
239
|
+
* Route-specific configuration from `config.ts`, read-only at runtime.
|
|
240
|
+
* Typed via augmentation of `RouteConfig`.
|
|
241
|
+
*/
|
|
242
|
+
private _config;
|
|
243
|
+
/**
|
|
244
|
+
* Deployment-platform bindings (`env.MY_KV`, secrets, …), populated by the
|
|
245
|
+
* serving entry point; `undefined` on runtimes without bindings.
|
|
246
|
+
*/
|
|
247
|
+
private _env;
|
|
248
|
+
/**
|
|
249
|
+
* Platform execution context (`waitUntil` and friends). Same lifecycle
|
|
250
|
+
* as `_env`: provided by the entry point, carried across re-binding.
|
|
251
|
+
*/
|
|
252
|
+
private _executionCtx;
|
|
253
|
+
/**
|
|
254
|
+
* Per-app server reference for resolving `ctx.ip` lazily. `undefined` on
|
|
255
|
+
* runtimes without a socket server (WinterCG).
|
|
256
|
+
*/
|
|
257
|
+
private _ipHolder;
|
|
258
|
+
/**
|
|
259
|
+
* Cached `ctx.ip` result. `null` records "resolved to undefined" so the
|
|
260
|
+
* runtime is queried at most once per request.
|
|
261
|
+
*/
|
|
262
|
+
private _ip;
|
|
263
|
+
/**
|
|
264
|
+
* The single context creation entry point.
|
|
265
|
+
*
|
|
266
|
+
* `meta` (a `RouteAccessInfo` hint) is accepted but ignored at runtime:
|
|
267
|
+
* every field is already available lazily on the stable prototype.
|
|
268
|
+
*/
|
|
269
|
+
static create(raw: Request, ctxInit?: ContextInit, _meta?: RouteAccessInfo, services?: Map<string, unknown> | BurgerServices, config?: RouteConfig | Record<string, unknown>, env?: BurgerEnv, executionCtx?: BurgerExecutionContext, ipHolder?: RequestIPHolder): BurgerContext;
|
|
270
|
+
/**
|
|
271
|
+
* @internal Re-bind route-specific state on an existing context.
|
|
272
|
+
*
|
|
273
|
+
* The router creates one context per request before routing (so
|
|
274
|
+
* `onRequest` hooks can seed request IDs, counters, …) and the dispatched
|
|
275
|
+
* handler binds that same instance to the matched route. Caches stay
|
|
276
|
+
* valid because the underlying `Request` is identical.
|
|
277
|
+
*/
|
|
278
|
+
bind(raw: Request, ctxInit?: ContextInit, _meta?: RouteAccessInfo, _services?: Map<string, unknown> | BurgerServices, config?: RouteConfig | Record<string, unknown>, env?: BurgerEnv, executionCtx?: BurgerExecutionContext, ipHolder?: RequestIPHolder): this;
|
|
279
|
+
/** Lazily parsed query record. Parsed once on first access, then cached. */
|
|
280
|
+
get query(): Record<string, string | string[]>;
|
|
281
|
+
/** Lazily parsed cookie record. Parsed once on first access, then cached. */
|
|
282
|
+
get cookies(): Record<string, string>;
|
|
283
|
+
/**
|
|
284
|
+
* The socket peer address (never a forwarded header — `X-Forwarded-For`
|
|
285
|
+
* and friends are client-controlled unless a trusted proxy sets them).
|
|
286
|
+
* `undefined` when the runtime does not expose it (WinterCG `fetch`).
|
|
287
|
+
*/
|
|
288
|
+
get ip(): string | undefined;
|
|
289
|
+
/**
|
|
290
|
+
* Publish a message to every WebSocket socket subscribed to `topic`
|
|
291
|
+
* (Bun only — `server.publish`). Unlike `ws.publish`, delivery is not
|
|
292
|
+
* tied to a publishing socket, so the sender is included when subscribed.
|
|
293
|
+
*
|
|
294
|
+
* @returns Bun's send status: bytes sent, `0` when the message was
|
|
295
|
+
* dropped, `-1` on backpressure.
|
|
296
|
+
* @throws when the app is not served by Bun (`app.serve()`), or before
|
|
297
|
+
* the server has started.
|
|
298
|
+
*/
|
|
299
|
+
publish(topic: string, message: string | Buffer): number;
|
|
300
|
+
/** The underlying raw `Request`. */
|
|
301
|
+
get request(): Request;
|
|
302
|
+
/**
|
|
303
|
+
* Route path params (seeded from `ctxInit`). Always an object — empty
|
|
304
|
+
* for routes without `[param]` segments — so `ctx.params.id` compiles.
|
|
305
|
+
*/
|
|
306
|
+
get params(): Record<string, string>;
|
|
307
|
+
/**
|
|
308
|
+
* Wildcard segments (seeded from `ctxInit`). Always an array — empty
|
|
309
|
+
* for non-wildcard routes.
|
|
310
|
+
*/
|
|
311
|
+
get wildcardParams(): string[];
|
|
312
|
+
/**
|
|
313
|
+
* The matched-route identity (seeded from `ctxInit`).
|
|
314
|
+
*
|
|
315
|
+
* Native dynamic routes seed only the `pattern`; the concrete requested
|
|
316
|
+
* `path` is derived here on first access and cached for the request.
|
|
317
|
+
*/
|
|
318
|
+
get route(): RouteMeta | undefined;
|
|
319
|
+
/** Route-specific configuration from `config.ts`. */
|
|
320
|
+
get config(): RouteConfig | undefined;
|
|
321
|
+
/**
|
|
322
|
+
* Deployment-platform bindings (`env.MY_KV`, secrets, …), typed via
|
|
323
|
+
* augmentation of `BurgerEnv`. `undefined` when the runtime provides none.
|
|
324
|
+
*/
|
|
325
|
+
get env(): BurgerEnv | undefined;
|
|
326
|
+
/**
|
|
327
|
+
* Platform execution context (`waitUntil`). `undefined` when the
|
|
328
|
+
* runtime does not supply one.
|
|
329
|
+
*/
|
|
330
|
+
get executionCtx(): BurgerExecutionContext | undefined;
|
|
331
|
+
get headers(): Headers;
|
|
332
|
+
get method(): string;
|
|
333
|
+
get url(): string;
|
|
334
|
+
get signal(): AbortSignal;
|
|
335
|
+
get body(): ReadableStream<Uint8Array> | null;
|
|
336
|
+
get bodyUsed(): boolean;
|
|
337
|
+
/**
|
|
338
|
+
* Parses the request body as JSON with the same semantics as the platform
|
|
339
|
+
* `Request.json()`. The default type is `any` because the shape of
|
|
340
|
+
* arbitrary JSON is unknown; callers can supply the expected shape:
|
|
341
|
+
*
|
|
342
|
+
* ```ts
|
|
343
|
+
* const body = await ctx.json<{ id: number }>();
|
|
344
|
+
* ```
|
|
345
|
+
*/
|
|
346
|
+
json<T = any>(): Promise<T>;
|
|
347
|
+
/**
|
|
348
|
+
* The body is read once, in the form first asked for. Text is the fast
|
|
349
|
+
* path (JSON parsing and validation use it); bytes asked for first stay
|
|
350
|
+
* byte-exact (webhook signatures over raw bytes).
|
|
351
|
+
*/
|
|
352
|
+
text(): Promise<string>;
|
|
353
|
+
arrayBuffer(): Promise<ArrayBuffer>;
|
|
354
|
+
blob(): Promise<Blob>;
|
|
355
|
+
formData(): Promise<FormData>;
|
|
356
|
+
clone(): Request;
|
|
357
|
+
}
|