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
package/dist/src/index.js
CHANGED
|
@@ -1,421 +1,1008 @@
|
|
|
1
|
-
// Import stuff
|
|
2
|
-
import { Server } from './core/server';
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
1
|
+
// Import stuff from core
|
|
2
|
+
import { Server } from './core/server.js';
|
|
3
|
+
import { timingSafeEqual } from './utils/timing-safe.js';
|
|
4
|
+
// Import router
|
|
5
|
+
import { Router } from './router/index.js';
|
|
6
|
+
import { compilePatternSegments, extractCtxInitWithSegments, } from './router/param-extract.js';
|
|
7
|
+
import { BurgerContext } from './context/context.js';
|
|
7
8
|
// Import utils
|
|
8
|
-
import { collectRoutes, compareRoutes } from './utils/index';
|
|
9
|
-
import {
|
|
10
|
-
import { extractPathnameFromUrl
|
|
11
|
-
|
|
12
|
-
import {
|
|
9
|
+
import { collectRoutes, compareRoutes, setDir } from './utils/index.js';
|
|
10
|
+
import { applySet, methodNotAllowed, notFound, openApiError, } from './utils/response.js';
|
|
11
|
+
import { extractPathnameFromUrl } from './utils/wildcard.js';
|
|
12
|
+
import { lowercaseMethodKeys } from './utils/routing.js';
|
|
13
|
+
import { requireDefaultFunctionExport, warnUnknownHookExports, } from './compiler/conventions.js';
|
|
14
|
+
// Import plugin system
|
|
15
|
+
import { PluginRegistry } from './plugin/registry.js';
|
|
16
|
+
import { assertTransformKeys } from './lifecycle/transform.js';
|
|
17
|
+
// Import WebSocket router/adapter (scanner/compiler load lazily on the dev
|
|
18
|
+
// filesystem path only).
|
|
19
|
+
import { WebSocketRouter } from './ws/router.js';
|
|
20
|
+
import { WebSocketAdapter } from './ws/adapter.js';
|
|
13
21
|
export class Burger {
|
|
14
22
|
options;
|
|
15
23
|
/**
|
|
16
24
|
* The server instance
|
|
17
25
|
*/
|
|
18
26
|
server;
|
|
27
|
+
/** The resolved API directory (dev path). */
|
|
28
|
+
apiDir;
|
|
19
29
|
/**
|
|
20
|
-
* The API
|
|
30
|
+
* The API path prefix (dev path).
|
|
21
31
|
*/
|
|
22
|
-
|
|
32
|
+
apiPrefix = 'api';
|
|
33
|
+
/** Page router (dev path only, created lazily). */
|
|
34
|
+
pageRouter;
|
|
35
|
+
/** The page directory (dev path). */
|
|
36
|
+
pageDir;
|
|
23
37
|
/**
|
|
24
|
-
* The page
|
|
38
|
+
* The page path prefix (dev path).
|
|
25
39
|
*/
|
|
26
|
-
|
|
40
|
+
pagePrefix = '';
|
|
41
|
+
/**
|
|
42
|
+
* The compiled API router: static dispatch (Bun map) plus dynamic and
|
|
43
|
+
* wildcard dispatch (trie).
|
|
44
|
+
*/
|
|
45
|
+
dynamicRouter;
|
|
46
|
+
/** Structural route tree for introspection/ordering; not on the hot path. */
|
|
47
|
+
routeTree;
|
|
48
|
+
/** Plugin registry, populated via `.usePlugin()` before `serve()`. */
|
|
49
|
+
pluginRegistry = new PluginRegistry();
|
|
50
|
+
/**
|
|
51
|
+
* Pre-routing onRequest hooks (Framework → Plugin → Global) resolved at
|
|
52
|
+
* compile time; shared with the WebSocket upgrade chain so both paths run
|
|
53
|
+
* the same hooks.
|
|
54
|
+
*/
|
|
55
|
+
onRequestHooks = [];
|
|
27
56
|
/**
|
|
28
|
-
*
|
|
57
|
+
* App-level (`src/hooks.ts`) route hooks, retained so WebSocket upgrades
|
|
58
|
+
* run the same transform/beforeRoute chain as HTTP.
|
|
29
59
|
*/
|
|
30
|
-
|
|
60
|
+
globalRouteHooks;
|
|
61
|
+
/** Services from `burger.provide()`, injected into `ctx.services`. */
|
|
62
|
+
providers = new Map();
|
|
31
63
|
/**
|
|
32
64
|
* The OpenAPI document
|
|
33
65
|
*/
|
|
34
66
|
openApiDoc = null;
|
|
35
67
|
/**
|
|
36
|
-
* The
|
|
68
|
+
* The loaded OpenAPI configuration from openapi.config.ts.
|
|
69
|
+
*/
|
|
70
|
+
openAPIConfig;
|
|
71
|
+
/**
|
|
72
|
+
* The routes object. API routes are per-method objects (`{ GET, … }`);
|
|
73
|
+
* page/asset/docs routes are plain request handlers.
|
|
37
74
|
*/
|
|
38
75
|
routes = {};
|
|
76
|
+
/** Origin of every registered route path, for collision errors. */
|
|
77
|
+
routeSources = new Map();
|
|
78
|
+
/**
|
|
79
|
+
* Every compiled API path (static + dynamic). Used by `fetchHandler()`
|
|
80
|
+
* to tell API routes apart from Bun-only page entries in `routes`.
|
|
81
|
+
*/
|
|
82
|
+
apiRoutePaths;
|
|
39
83
|
/**
|
|
40
|
-
*
|
|
84
|
+
* WebSocket directory (dev path)
|
|
41
85
|
*/
|
|
42
|
-
|
|
86
|
+
wsDir;
|
|
87
|
+
/**
|
|
88
|
+
* WebSocket router
|
|
89
|
+
*/
|
|
90
|
+
wsRouter;
|
|
91
|
+
/**
|
|
92
|
+
* WebSocket adapter
|
|
93
|
+
*/
|
|
94
|
+
wsAdapter;
|
|
95
|
+
/**
|
|
96
|
+
* WebSocket config
|
|
97
|
+
*/
|
|
98
|
+
wsConfigOptions;
|
|
99
|
+
/**
|
|
100
|
+
* Programmatic WebSocket routes
|
|
101
|
+
*/
|
|
102
|
+
programmaticWsRoutes = new Map();
|
|
43
103
|
/**
|
|
44
104
|
* The not found response
|
|
45
105
|
*/
|
|
46
|
-
|
|
106
|
+
notFound = notFound;
|
|
47
107
|
/**
|
|
48
108
|
* The OpenAPI error response
|
|
49
109
|
*/
|
|
50
|
-
|
|
110
|
+
openApiError = openApiError;
|
|
51
111
|
/**
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
112
|
+
* Set once API routes have been compiled. Guards `processApiRoutes()` from
|
|
113
|
+
* re-running when both `serve()` and `fetchHandler()` are used.
|
|
114
|
+
*/
|
|
115
|
+
routesProcessed = false;
|
|
116
|
+
/** Set once page + asset routes are registered (serve / fetchHandler). */
|
|
117
|
+
pagesProcessed;
|
|
118
|
+
/** Set when the scanned API directory contained no route files. */
|
|
119
|
+
emptyApiDir;
|
|
120
|
+
/** Set once convention directory defaults were applied. */
|
|
121
|
+
conventionDefaultsApplied = false;
|
|
122
|
+
/**
|
|
123
|
+
* App-level WebSocket hooks (`onOpen` / `onMessage` / `onClose`),
|
|
124
|
+
* applied to every WS route.
|
|
125
|
+
*/
|
|
126
|
+
globalWsHooks;
|
|
127
|
+
/**
|
|
128
|
+
* @param options Server + router options (port, apiDir, pageDir, wsDir, …).
|
|
59
129
|
*/
|
|
60
130
|
constructor(options) {
|
|
61
131
|
this.options = options;
|
|
62
|
-
//
|
|
63
|
-
this.server = new Server(options);
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
//
|
|
67
|
-
this.
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
132
|
+
// Adapter seam: injectable for tests/embed, else Bun loads lazily.
|
|
133
|
+
this.server = new Server(options, options.adapter);
|
|
134
|
+
const { apiDir, apiPrefix, wsDir } = options;
|
|
135
|
+
this.apiDir = apiDir;
|
|
136
|
+
// `??`, not `||`: an explicit `apiPrefix: ''` mounts routes at `/`.
|
|
137
|
+
this.apiPrefix = apiPrefix ?? 'api';
|
|
138
|
+
// Pages resolve lazily on the dev scan path, keeping AOT bundles small.
|
|
139
|
+
this.pageDir = options.pageDir;
|
|
140
|
+
this.pagePrefix = options.pagePrefix ?? '';
|
|
141
|
+
this.wsDir = wsDir;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Registers a plugin; its hooks compile into every route's hook chain with
|
|
145
|
+
* the plugin's scope. Duplicate registrations (same name + seed) are
|
|
146
|
+
* ignored with a warning.
|
|
147
|
+
*
|
|
148
|
+
* @param plugin The plugin object or a factory function returning one.
|
|
149
|
+
* @param scope Optional scope override (default: `'plugin'`).
|
|
150
|
+
* @param seed Optional disambiguation string (e.g. two JWT plugins).
|
|
151
|
+
* @returns `this` for chaining.
|
|
152
|
+
*/
|
|
153
|
+
usePlugin(plugin, scope, seed) {
|
|
154
|
+
this.pluginRegistry.register(plugin, scope ?? 'plugin', seed);
|
|
155
|
+
return this;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Registers an application service, injected into `ctx.services` for every
|
|
159
|
+
* request.
|
|
160
|
+
*
|
|
161
|
+
* @param name Service name (accessed as `ctx.services[name]`).
|
|
162
|
+
* @param service The service instance.
|
|
163
|
+
* @returns `this` for chaining.
|
|
164
|
+
*/
|
|
165
|
+
provide(name, service) {
|
|
166
|
+
this.providers.set(name, service);
|
|
167
|
+
return this;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Register a WebSocket route programmatically.
|
|
171
|
+
* @param path Route path (e.g., "/chat", "/notifications/:room")
|
|
172
|
+
* @param handlers WebSocket handler functions
|
|
173
|
+
* @returns `this` for chaining.
|
|
174
|
+
*/
|
|
175
|
+
websocket(path, handlers) {
|
|
176
|
+
this.programmaticWsRoutes.set(path, { path, handlers });
|
|
177
|
+
return this;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Set global WebSocket configuration.
|
|
181
|
+
* @param config WebSocket configuration options
|
|
182
|
+
* @returns `this` for chaining.
|
|
183
|
+
*/
|
|
184
|
+
wsConfig(config) {
|
|
185
|
+
this.wsConfigOptions = config;
|
|
186
|
+
return this;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Filesystem mode only (no prebuilt `apiRoutes`): unconfigured directories
|
|
190
|
+
* default to the CLI build conventions (`src/api`, `src/pages`,
|
|
191
|
+
* `src/websocket`) when they exist, so dev and production match. Resolved
|
|
192
|
+
* lazily — `node:fs` is never loaded by AOT bundles.
|
|
193
|
+
*/
|
|
194
|
+
async applyConventionDefaults() {
|
|
195
|
+
if (this.conventionDefaultsApplied)
|
|
196
|
+
return;
|
|
197
|
+
this.conventionDefaultsApplied = true;
|
|
198
|
+
if (Array.isArray(this.options.apiRoutes))
|
|
199
|
+
return;
|
|
200
|
+
const needsApi = !this.apiDir;
|
|
201
|
+
const needsPages = !this.pageDir && !Array.isArray(this.options.pageRoutes);
|
|
202
|
+
const needsWs = !this.wsDir && !Array.isArray(this.options.wsRoutes);
|
|
203
|
+
if (!needsApi && !needsPages && !needsWs)
|
|
204
|
+
return;
|
|
205
|
+
const { resolveConventionDir } = await import('./utils/fs.js');
|
|
206
|
+
if (needsApi)
|
|
207
|
+
this.apiDir = resolveConventionDir('api');
|
|
208
|
+
if (needsPages)
|
|
209
|
+
this.pageDir = resolveConventionDir('pages');
|
|
210
|
+
if (needsWs)
|
|
211
|
+
this.wsDir = resolveConventionDir('websocket');
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Wraps a non-API handler (page, asset, OpenAPI spec, docs UI) so
|
|
215
|
+
* global/plugin `onRequest` hooks run for it like for API routes.
|
|
216
|
+
* Registered on the native routes map → invoked with the raw `Request`.
|
|
217
|
+
*/
|
|
218
|
+
withOnRequest(handler) {
|
|
219
|
+
// Non-function values (Bun HTML-import bundles) are served natively,
|
|
220
|
+
// not wrapped.
|
|
221
|
+
const wrapped = this.dynamicRouter && typeof handler === 'function'
|
|
222
|
+
? this.dynamicRouter.wrapWithOnRequest(handler)
|
|
223
|
+
: handler;
|
|
224
|
+
return wrapped;
|
|
80
225
|
}
|
|
81
226
|
/**
|
|
82
|
-
*
|
|
83
|
-
*
|
|
227
|
+
* Registers one route path, failing loud when two sources (API route,
|
|
228
|
+
* page, asset, docs UI, spec) resolve to the same path. Silent overwrites
|
|
229
|
+
* would make one of them unreachable.
|
|
84
230
|
*/
|
|
231
|
+
registerRoute(key, handler, source) {
|
|
232
|
+
const existing = this.routeSources.get(key);
|
|
233
|
+
if (existing !== undefined) {
|
|
234
|
+
throw new Error(`[burger-api] Route collision: "${key}" is registered by both ` +
|
|
235
|
+
`${existing} and ${source}. Rename one of them.`);
|
|
236
|
+
}
|
|
237
|
+
this.routeSources.set(key, source);
|
|
238
|
+
this.routes[key] = handler;
|
|
239
|
+
}
|
|
240
|
+
/** Registers page + asset routes once (shared by serve and fetchHandler). */
|
|
241
|
+
processPageRoutesOnce() {
|
|
242
|
+
return (this.pagesProcessed ??= this.processPageRoutes());
|
|
243
|
+
}
|
|
244
|
+
/** Loads prebuilt or filesystem page routes. */
|
|
85
245
|
async processPageRoutes() {
|
|
86
246
|
// Production path: use pre-built page routes (no filesystem scan)
|
|
87
247
|
const prebuiltPages = this.options.pageRoutes;
|
|
248
|
+
let hasPages = false;
|
|
88
249
|
if (Array.isArray(prebuiltPages)) {
|
|
89
|
-
// Sort the prebuilt pages
|
|
90
250
|
const sorted = [...prebuiltPages].sort((a, b) => compareRoutes(a, b));
|
|
91
251
|
for (let i = 0; i < sorted.length; i++) {
|
|
92
252
|
const page = sorted[i];
|
|
93
|
-
this.
|
|
253
|
+
this.registerRoute(page.path, this.withOnRequest(this.restrictToGetHead(this.wrapPageHandler(page.handler, page.path))), page.source ? `page "${page.source}"` : `page route`);
|
|
94
254
|
}
|
|
95
|
-
|
|
255
|
+
hasPages = sorted.length > 0;
|
|
96
256
|
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
for (let i = 0; i < pageCount; i++) {
|
|
111
|
-
// Get the current page
|
|
112
|
-
const page = pages[i];
|
|
113
|
-
// Add the page to the routes
|
|
114
|
-
this.routes[page.path] = page.handler;
|
|
257
|
+
else if (this.pageDir) {
|
|
258
|
+
// Dev path: lazy-load the page router (AOT bundles ship prebuilt
|
|
259
|
+
// pageRoutes, so this module is never evaluated).
|
|
260
|
+
const { PageRouter } = await import('./core/page-router.js');
|
|
261
|
+
const pageRouter = new PageRouter(this.pageDir, this.pagePrefix);
|
|
262
|
+
this.pageRouter = pageRouter;
|
|
263
|
+
await pageRouter.loadPages();
|
|
264
|
+
const pages = pageRouter.pages;
|
|
265
|
+
for (let i = 0; i < pages.length; i++) {
|
|
266
|
+
const page = pages[i];
|
|
267
|
+
this.registerRoute(page.path, this.withOnRequest(this.restrictToGetHead(this.wrapPageHandler(page.handler, page.path))), page.source ? `page "${page.source}"` : `page route`);
|
|
268
|
+
}
|
|
269
|
+
hasPages = pages.length > 0;
|
|
115
270
|
}
|
|
116
|
-
//
|
|
117
|
-
|
|
271
|
+
// Static assets under `<pageDir>/assets/` — embedded table from the
|
|
272
|
+
// AOT build, or read-from-disk when running with `pageDir`.
|
|
273
|
+
await this.processAssetRoutes();
|
|
274
|
+
return hasPages;
|
|
118
275
|
}
|
|
119
276
|
/**
|
|
120
|
-
*
|
|
121
|
-
*
|
|
277
|
+
* Wraps every page handler with a real per-request `BurgerContext` — the
|
|
278
|
+
* same object API routes get — so `ctx.services`, `ctx.query`, `ctx.set`
|
|
279
|
+
* and the delegated `Request` surface work on static pages too. Dynamic
|
|
280
|
+
* pages (`:param`) also get `ctx.params`; static pages seed only the
|
|
281
|
+
* route pattern (`ctx.route.path` derives lazily).
|
|
282
|
+
*
|
|
283
|
+
* Cost per page request: one `BurgerContext` allocation (no parsing).
|
|
284
|
+
* When an onRequest/global-hook wrapper already created the context, the
|
|
285
|
+
* existing instance is re-bound instead of allocated.
|
|
286
|
+
*/
|
|
287
|
+
wrapPageHandler(handler, path) {
|
|
288
|
+
// Compile the pattern's segments once per route, not per request.
|
|
289
|
+
const compiledPattern = path.includes(':')
|
|
290
|
+
? compilePatternSegments(path)
|
|
291
|
+
: undefined;
|
|
292
|
+
// Invoked with the raw `Request`, like `fetchHandler`'s static dispatch.
|
|
293
|
+
const wrapped = async (request, _ctxInit, prebuilt, env, executionCtx) => {
|
|
294
|
+
const ctxInit = compiledPattern
|
|
295
|
+
? extractCtxInitWithSegments(request, path, compiledPattern)
|
|
296
|
+
: { pattern: path };
|
|
297
|
+
const ctx = prebuilt
|
|
298
|
+
? prebuilt.bind(request, ctxInit)
|
|
299
|
+
: BurgerContext.create(request, ctxInit, undefined, this.dynamicRouter?.getAppServices(), undefined, env, executionCtx, this.dynamicRouter?.getRequestIPHolder());
|
|
300
|
+
const response = await handler(ctx);
|
|
301
|
+
// With no outer onRequest/global-hook wrapper there is nobody
|
|
302
|
+
// else to apply `ctx.set`; do it here.
|
|
303
|
+
return prebuilt
|
|
304
|
+
? response
|
|
305
|
+
: ctx.hasSet()
|
|
306
|
+
? applySet(response, ctx.set)
|
|
307
|
+
: response;
|
|
308
|
+
};
|
|
309
|
+
return wrapped;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Pages, assets, the docs UI and the OpenAPI spec answer GET and HEAD
|
|
313
|
+
* only. Every other method gets a 405 with `Allow: GET, HEAD` and the
|
|
314
|
+
* same RFC 9457 body route 405s use. Global/plugin response hooks and
|
|
315
|
+
* onRequest mappers still apply (this runs inside `withOnRequest`).
|
|
316
|
+
*/
|
|
317
|
+
restrictToGetHead(handler) {
|
|
318
|
+
const restricted = (arg, ...rest) => {
|
|
319
|
+
if (arg.method !== 'GET' && arg.method !== 'HEAD') {
|
|
320
|
+
return methodNotAllowed('GET, HEAD');
|
|
321
|
+
}
|
|
322
|
+
return handler(arg, ...rest);
|
|
323
|
+
};
|
|
324
|
+
return restricted;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Registers static asset routes under `{pagePrefix}/assets/*`.
|
|
328
|
+
*
|
|
329
|
+
* Production AOT embeds base64 contents (`assetRoutes` from the CLI
|
|
330
|
+
* build); dev reads files from disk per request so edits show.
|
|
331
|
+
*/
|
|
332
|
+
async processAssetRoutes() {
|
|
333
|
+
const prebuiltAssets = this.options.assetRoutes;
|
|
334
|
+
if (Array.isArray(prebuiltAssets)) {
|
|
335
|
+
const { embeddedAssetHandler } = await import('./core/embedded-assets.js');
|
|
336
|
+
for (const asset of prebuiltAssets) {
|
|
337
|
+
this.registerRoute(asset.path, this.withOnRequest(this.restrictToGetHead(embeddedAssetHandler(asset))), `asset "${asset.path}"`);
|
|
338
|
+
}
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
if (!this.pageDir)
|
|
342
|
+
return;
|
|
343
|
+
const { collectDiskAssetRoutes, diskAssetHandler } = await import('./core/assets.js');
|
|
344
|
+
const routes = await collectDiskAssetRoutes(this.pageDir, this.pagePrefix);
|
|
345
|
+
for (const route of routes) {
|
|
346
|
+
this.registerRoute(route.routePath, this.withOnRequest(this.restrictToGetHead(diskAssetHandler(route))), `asset "${route.file}"`);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Compiles the API routes and merges them into the routes map. Static and
|
|
351
|
+
* dynamic (`:param` / `*`) routes both go on Bun's native map; unmatched or
|
|
352
|
+
* loose-trailing-slash requests fall through to `Router.fetch` (the trie).
|
|
353
|
+
* Both paths run the same compiled handler, so dispatch behavior is
|
|
354
|
+
* identical.
|
|
122
355
|
*/
|
|
123
356
|
async processApiRoutes() {
|
|
357
|
+
if (this.routesProcessed)
|
|
358
|
+
return true;
|
|
124
359
|
// Production path: use pre-built API routes (no filesystem scan)
|
|
125
360
|
let apiRoutes;
|
|
361
|
+
let globalOnRequest;
|
|
362
|
+
// Global hooks other than onRequest — compiled into every route with
|
|
363
|
+
// scope 'global' (identical ordering in dev and AOT).
|
|
364
|
+
let globalRouteHooks;
|
|
126
365
|
if (Array.isArray(this.options.apiRoutes)) {
|
|
127
|
-
|
|
366
|
+
// AOT routes may carry uppercase method keys (GET/POST) in
|
|
367
|
+
// `schema` / `openapi`; normalize once for the compiler and
|
|
368
|
+
// OpenAPI generator. `config` keeps its uppercase method keys.
|
|
369
|
+
apiRoutes = this.options.apiRoutes
|
|
370
|
+
.map((def) => ({
|
|
371
|
+
...def,
|
|
372
|
+
schema: def.schema
|
|
373
|
+
? lowercaseMethodKeys(def.schema)
|
|
374
|
+
: def.schema,
|
|
375
|
+
openapi: def.openapi
|
|
376
|
+
? lowercaseMethodKeys(def.openapi)
|
|
377
|
+
: def.openapi,
|
|
378
|
+
}))
|
|
379
|
+
.sort((a, b) => compareRoutes(a, b));
|
|
380
|
+
// Production: accept config from ServerOptions if provided
|
|
381
|
+
this.openAPIConfig = this.options.openapi;
|
|
382
|
+
// Production: resolve global hooks from options (a module
|
|
383
|
+
// namespace or its default-export object, like the dev loader).
|
|
384
|
+
const rawGlobal = this.options.globalHooks;
|
|
385
|
+
const globalHooks = rawGlobal &&
|
|
386
|
+
typeof rawGlobal.default === 'object' &&
|
|
387
|
+
rawGlobal.default !== null
|
|
388
|
+
? rawGlobal.default
|
|
389
|
+
: rawGlobal;
|
|
390
|
+
if (globalHooks) {
|
|
391
|
+
warnUnknownHookExports(globalHooks, 'src/hooks', 'global');
|
|
392
|
+
const { onRequest, ...rest } = globalHooks;
|
|
393
|
+
if (onRequest) {
|
|
394
|
+
globalOnRequest = Array.isArray(onRequest)
|
|
395
|
+
? onRequest
|
|
396
|
+
: [onRequest];
|
|
397
|
+
}
|
|
398
|
+
globalRouteHooks = rest;
|
|
399
|
+
this.globalWsHooks = pickWsHooks(globalHooks);
|
|
400
|
+
}
|
|
401
|
+
for (const def of apiRoutes) {
|
|
402
|
+
warnUnknownHookExports(def.hooks, `${def.path} hooks`, 'route');
|
|
403
|
+
}
|
|
128
404
|
}
|
|
129
405
|
else {
|
|
130
|
-
// Dev path:
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
await this.
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
// If there are no API routes, return false
|
|
139
|
-
if (routeCount === 0)
|
|
140
|
-
return false;
|
|
141
|
-
// Generate OpenAPI document and cache it
|
|
142
|
-
this.openApiDoc = generateOpenAPIDocument(apiRoutes, this.options);
|
|
143
|
-
// Cache frequently accessed properties
|
|
144
|
-
const routes = this.routes;
|
|
145
|
-
// Get the global middleware
|
|
146
|
-
const globalMiddleware = this.globalMiddleware;
|
|
147
|
-
// Get the length of the global middleware
|
|
148
|
-
const globalMiddlewareLen = globalMiddleware.length;
|
|
149
|
-
// Process each route with optimized handler creation
|
|
150
|
-
for (let i = 0; i < routeCount; i++) {
|
|
151
|
-
/**
|
|
152
|
-
* ================================================
|
|
153
|
-
* Pre-compute the required functionality start
|
|
154
|
-
* ================================================
|
|
155
|
-
*/
|
|
156
|
-
// Get the current route object
|
|
157
|
-
const route = apiRoutes[i];
|
|
158
|
-
// Destructure the route object
|
|
159
|
-
const { path, schema, middleware: routeMiddleware, handlers, } = route;
|
|
160
|
-
// Get length of route specific middleware
|
|
161
|
-
const routeMiddlewareLen = routeMiddleware?.length || 0;
|
|
162
|
-
// Check if schema exists
|
|
163
|
-
const hasSchema = !!schema;
|
|
164
|
-
// Optimize middleware array initialization by pre-allocating size
|
|
165
|
-
const totalMiddlewareCount = globalMiddlewareLen + (hasSchema ? 1 : 0) + routeMiddlewareLen;
|
|
166
|
-
// Pre-compute wildcard info once (used in all paths)
|
|
167
|
-
const isWildcard = route.isWildcard;
|
|
168
|
-
const baseSegmentCount = isWildcard
|
|
169
|
-
? path.split('/').filter(Boolean).length - 1
|
|
170
|
-
: 0;
|
|
171
|
-
// Create optimized route handler based on middleware count
|
|
172
|
-
if (totalMiddlewareCount === 0) {
|
|
173
|
-
// Ultra-fast path: no middleware at all
|
|
174
|
-
// Inline everything for maximum speed
|
|
175
|
-
if (isWildcard) {
|
|
176
|
-
// Wildcard route with no middleware
|
|
177
|
-
routes[path] = (request) => {
|
|
178
|
-
const pathname = extractPathnameFromUrl(request.url);
|
|
179
|
-
extractWildcardParams(request, pathname, baseSegmentCount);
|
|
180
|
-
const handler = handlers[request.method];
|
|
181
|
-
return handler
|
|
182
|
-
? handler(request)
|
|
183
|
-
: this.METHOD_NOT_ALLOWED;
|
|
184
|
-
};
|
|
185
|
-
}
|
|
186
|
-
else {
|
|
187
|
-
// Regular route with no middleware (most common case)
|
|
188
|
-
routes[path] = (request) => {
|
|
189
|
-
const handler = handlers[request.method];
|
|
190
|
-
return handler
|
|
191
|
-
? handler(request)
|
|
192
|
-
: this.METHOD_NOT_ALLOWED;
|
|
193
|
-
};
|
|
194
|
-
}
|
|
406
|
+
// Dev path: Scanner → Module Loader → RouteModule → Compiler,
|
|
407
|
+
// loaded lazily (AOT builds ship prebuilt apiRoutes). App-level
|
|
408
|
+
// convention files load even for pages-only apps (no apiDir).
|
|
409
|
+
await this.applyConventionDefaults();
|
|
410
|
+
let scanned;
|
|
411
|
+
if (this.apiDir) {
|
|
412
|
+
const { DirectoryScanner } = await import('./compiler/scanner.js');
|
|
413
|
+
scanned = await new DirectoryScanner(this.apiDir, this.apiPrefix).scan();
|
|
195
414
|
}
|
|
196
415
|
else {
|
|
197
|
-
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
}
|
|
416
|
+
const { scanAppRootConventions } = await import('./compiler/scanner.js');
|
|
417
|
+
const { resolveAppRootDir } = await import('./utils/fs.js');
|
|
418
|
+
const appRoot = resolveAppRootDir();
|
|
419
|
+
if (appRoot)
|
|
420
|
+
scanned = await scanAppRootConventions(appRoot);
|
|
421
|
+
}
|
|
422
|
+
if (scanned) {
|
|
423
|
+
const { ModuleLoader } = await import('./compiler/module-loader.js');
|
|
424
|
+
const loader = new ModuleLoader();
|
|
425
|
+
const modules = await loader.load(scanned);
|
|
426
|
+
globalOnRequest = scanned.globalOnRequest;
|
|
427
|
+
globalRouteHooks = scanned.globalRouteHooks;
|
|
428
|
+
this.globalWsHooks = pickWsHooks(scanned.globalRouteHooks);
|
|
429
|
+
if (this.apiDir && modules.length === 0) {
|
|
430
|
+
this.emptyApiDir = this.apiDir;
|
|
213
431
|
}
|
|
214
|
-
//
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
extractWildcardParams(request, pathname, baseSegmentCount);
|
|
222
|
-
const handler = handlers[request.method];
|
|
223
|
-
if (!handler)
|
|
224
|
-
return this.METHOD_NOT_ALLOWED;
|
|
225
|
-
return this.processSingleMiddleware(request, singleMiddleware, handler);
|
|
226
|
-
};
|
|
227
|
-
}
|
|
228
|
-
else {
|
|
229
|
-
routes[path] = (request) => {
|
|
230
|
-
const handler = handlers[request.method];
|
|
231
|
-
if (!handler)
|
|
232
|
-
return this.METHOD_NOT_ALLOWED;
|
|
233
|
-
return this.processSingleMiddleware(request, singleMiddleware, handler);
|
|
234
|
-
};
|
|
235
|
-
}
|
|
432
|
+
// Load openapi.config.ts if discovered
|
|
433
|
+
this.openAPIConfig = await loader.loadOpenAPIConfig(scanned);
|
|
434
|
+
// Load and execute plugins.ts / providers.ts (app root). A
|
|
435
|
+
// present file with no default function export fails loud.
|
|
436
|
+
const pluginsMod = await loader.loadPlugins(scanned);
|
|
437
|
+
if (pluginsMod) {
|
|
438
|
+
await pluginsMod.default(this);
|
|
236
439
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
routes[path] = (request) => {
|
|
241
|
-
const pathname = extractPathnameFromUrl(request.url);
|
|
242
|
-
extractWildcardParams(request, pathname, baseSegmentCount);
|
|
243
|
-
const handler = handlers[request.method];
|
|
244
|
-
if (!handler)
|
|
245
|
-
return this.METHOD_NOT_ALLOWED;
|
|
246
|
-
return this.processMiddleware(request, middlewares, handler);
|
|
247
|
-
};
|
|
248
|
-
}
|
|
249
|
-
else {
|
|
250
|
-
routes[path] = (request) => {
|
|
251
|
-
const handler = handlers[request.method];
|
|
252
|
-
if (!handler)
|
|
253
|
-
return this.METHOD_NOT_ALLOWED;
|
|
254
|
-
return this.processMiddleware(request, middlewares, handler);
|
|
255
|
-
};
|
|
256
|
-
}
|
|
440
|
+
const providersMod = await loader.loadProviders(scanned);
|
|
441
|
+
if (providersMod) {
|
|
442
|
+
await providersMod.default(this);
|
|
257
443
|
}
|
|
444
|
+
// Retained for introspection (deterministic ordering, no dispatch).
|
|
445
|
+
const { RouteTree } = await import('./compiler/route-tree.js');
|
|
446
|
+
this.routeTree = new RouteTree(modules);
|
|
447
|
+
apiRoutes = modules.map((m) => ({
|
|
448
|
+
path: m.path,
|
|
449
|
+
handlers: m.handlers,
|
|
450
|
+
schema: m.schema,
|
|
451
|
+
openapi: m.openapi,
|
|
452
|
+
hooks: m.hooks,
|
|
453
|
+
config: m.config,
|
|
454
|
+
isWildcard: m.isWildcard,
|
|
455
|
+
}));
|
|
258
456
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
if (route.isWildcard && path.endsWith('/*')) {
|
|
262
|
-
const basePath = path.slice(0, -2); // Remove "/*" to get base path
|
|
263
|
-
// Only register base path if no static route exists (preserve priority)
|
|
264
|
-
// Static routes have highest priority: Static > Dynamic > Wildcard
|
|
265
|
-
if (!routes[basePath]) {
|
|
266
|
-
// No static route found, register wildcard for base path
|
|
267
|
-
routes[basePath] = routes[path];
|
|
268
|
-
}
|
|
269
|
-
// If static route exists, it takes priority (correct behavior)
|
|
457
|
+
else {
|
|
458
|
+
apiRoutes = [];
|
|
270
459
|
}
|
|
271
460
|
}
|
|
272
|
-
//
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
461
|
+
// Production: execute the pre-resolved plugins/providers modules.
|
|
462
|
+
// Runs for pages-only AOT apps too (no apiRoutes array). A module
|
|
463
|
+
// present without a default function export fails loud.
|
|
464
|
+
if (this.options.pluginsModule) {
|
|
465
|
+
const fn = requireDefaultFunctionExport(this.options.pluginsModule, 'plugins.ts');
|
|
466
|
+
await fn(this);
|
|
467
|
+
}
|
|
468
|
+
if (this.options.providersModule) {
|
|
469
|
+
const fn = requireDefaultFunctionExport(this.options.providersModule, 'providers.ts');
|
|
470
|
+
await fn(this);
|
|
471
|
+
}
|
|
472
|
+
// API routes are optional: the router is still built so hooks, the `ip`
|
|
473
|
+
// holder and app services reach pages, assets and docs.
|
|
474
|
+
const hasApiRoutes = apiRoutes.length > 0;
|
|
475
|
+
const config = this.openAPIConfig;
|
|
476
|
+
const openapiEnabled = config?.enabled !== false;
|
|
477
|
+
// Generate the OpenAPI document lazily and only when docs are enabled.
|
|
478
|
+
if (hasApiRoutes && openapiEnabled) {
|
|
479
|
+
const { generateOpenAPIDocument } = await import('./core/openapi.js');
|
|
480
|
+
this.openApiDoc = generateOpenAPIDocument(apiRoutes, this.options, this.openAPIConfig);
|
|
481
|
+
}
|
|
482
|
+
// Compile routes into the Hybrid Router.
|
|
483
|
+
const router = new Router({
|
|
484
|
+
debug: this.options.debug,
|
|
485
|
+
validation: this.options.validation ?? {},
|
|
486
|
+
jit: this.options.jit !== false,
|
|
487
|
+
engine: this.options.engine,
|
|
279
488
|
});
|
|
489
|
+
// Resolve plugins into a single list for the compiler.
|
|
490
|
+
const allHooks = await this.pluginRegistry.resolveAll();
|
|
491
|
+
// onRequest hooks run before routing, not as per-route HookPlan
|
|
492
|
+
// entries. Order: Framework → Plugin → Global (src/hooks.ts) → Route.
|
|
493
|
+
const onRequestHooks = [];
|
|
494
|
+
for (const plugin of allHooks) {
|
|
495
|
+
const h = plugin.hooks.onRequest;
|
|
496
|
+
if (h) {
|
|
497
|
+
if (Array.isArray(h))
|
|
498
|
+
onRequestHooks.push(...h);
|
|
499
|
+
else
|
|
500
|
+
onRequestHooks.push(h);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
onRequestHooks.push(...(globalOnRequest ?? []));
|
|
504
|
+
this.onRequestHooks = onRequestHooks;
|
|
505
|
+
this.globalRouteHooks = globalRouteHooks;
|
|
506
|
+
router.compile(apiRoutes, allHooks, this.providers, onRequestHooks, globalRouteHooks);
|
|
507
|
+
this.dynamicRouter = router;
|
|
508
|
+
// Only the onRequest machinery was needed (pages/assets/docs); there
|
|
509
|
+
// is no route table to merge and no OpenAPI document to serve.
|
|
510
|
+
if (!hasApiRoutes) {
|
|
511
|
+
this.routesProcessed = true;
|
|
512
|
+
return false;
|
|
513
|
+
}
|
|
514
|
+
// Merge static and dynamic routes onto Bun's native routes map (Bun
|
|
515
|
+
// matches `:param` / `*` directly); unmatched requests fall through to
|
|
516
|
+
// `Router.fetch` (the trie). Collisions with pages/assets/docs throw.
|
|
517
|
+
for (const [key, handlers] of Object.entries(router.staticRoutes())) {
|
|
518
|
+
this.registerRoute(key, handlers, `API route "${key}"`);
|
|
519
|
+
}
|
|
520
|
+
for (const [key, handlers] of Object.entries(router.nativeRoutes())) {
|
|
521
|
+
this.registerRoute(key, handlers, `API route "${key}"`);
|
|
522
|
+
}
|
|
523
|
+
this.apiRoutePaths = new Set([
|
|
524
|
+
...Object.keys(router.staticRoutes()),
|
|
525
|
+
...Object.keys(router.nativeRoutes()),
|
|
526
|
+
]);
|
|
527
|
+
// Register OpenAPI and docs routes based on config
|
|
528
|
+
if (openapiEnabled) {
|
|
529
|
+
const specPath = config?.path ?? '/openapi.json';
|
|
530
|
+
const docsPath = config?.docsPath ?? '/docs';
|
|
531
|
+
const expectedAuth = config?.docsAuth
|
|
532
|
+
? 'Basic ' +
|
|
533
|
+
base64Utf8(`${config.docsAuth.username}:${config.docsAuth.password}`)
|
|
534
|
+
: null;
|
|
535
|
+
// docsAuth guards the spec as well as the UI: protecting only the
|
|
536
|
+
// HTML page would leave the API description public.
|
|
537
|
+
const unauthorized = (ctx) => {
|
|
538
|
+
if (expectedAuth === null)
|
|
539
|
+
return null;
|
|
540
|
+
const authHeader = ctx?.headers?.get?.('authorization') ?? '';
|
|
541
|
+
if (timingSafeEqual(authHeader, expectedAuth))
|
|
542
|
+
return null;
|
|
543
|
+
return new Response('Unauthorized', {
|
|
544
|
+
status: 401,
|
|
545
|
+
headers: {
|
|
546
|
+
'WWW-Authenticate': 'Basic realm="Documentation"',
|
|
547
|
+
},
|
|
548
|
+
});
|
|
549
|
+
};
|
|
550
|
+
// Invoked with the raw `Request` (native routes map); wrapped so
|
|
551
|
+
// global/plugin onRequest hooks (CORS, auth, …) apply here too.
|
|
552
|
+
this.registerRoute(specPath, this.withOnRequest(this.restrictToGetHead((request) => unauthorized(request) ??
|
|
553
|
+
(this.openApiDoc
|
|
554
|
+
? Response.json(this.openApiDoc)
|
|
555
|
+
: this.openApiError()))), 'openapi.json route');
|
|
556
|
+
// Docs UI: configured provider, or Swagger UI by default (loaded
|
|
557
|
+
// lazily).
|
|
558
|
+
const { swaggerDocs } = await import('./core/docs-providers.js');
|
|
559
|
+
const provider = config?.provider ?? swaggerDocs();
|
|
560
|
+
this.registerRoute(docsPath, this.withOnRequest(this.restrictToGetHead((request) => {
|
|
561
|
+
const denied = unauthorized(request);
|
|
562
|
+
if (denied)
|
|
563
|
+
return denied;
|
|
564
|
+
const result = provider(this.openApiDoc, {
|
|
565
|
+
specUrl: specPath,
|
|
566
|
+
});
|
|
567
|
+
if (result instanceof Response)
|
|
568
|
+
return result;
|
|
569
|
+
return new Response(result, {
|
|
570
|
+
headers: { 'Content-Type': 'text/html' },
|
|
571
|
+
});
|
|
572
|
+
})), 'docs UI');
|
|
573
|
+
}
|
|
574
|
+
this.routesProcessed = true;
|
|
280
575
|
return true;
|
|
281
576
|
}
|
|
282
|
-
/**
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
577
|
+
/** Loads WebSocket routes (programmatic, prebuilt or file-based). */
|
|
578
|
+
async processWebSocketRoutes() {
|
|
579
|
+
this.wsRouter = new WebSocketRouter();
|
|
580
|
+
// Extract auth hooks from resolved plugins for WebSocket upgrade.
|
|
581
|
+
// beforeRoute follows the HTTP order: Framework → Plugin → Global.
|
|
582
|
+
const resolvedPlugins = await this.pluginRegistry.resolveAll();
|
|
583
|
+
let pluginTransform;
|
|
584
|
+
const pluginBeforeRoute = [];
|
|
585
|
+
const frameworkBeforeRoute = [];
|
|
586
|
+
const toHookArray = (value) => Array.isArray(value) ? value : [value];
|
|
587
|
+
for (const plugin of resolvedPlugins) {
|
|
588
|
+
// Collect transform hooks
|
|
589
|
+
if (plugin.hooks.transform) {
|
|
590
|
+
if (!pluginTransform)
|
|
591
|
+
pluginTransform = {};
|
|
592
|
+
Object.assign(pluginTransform, plugin.hooks.transform);
|
|
593
|
+
}
|
|
594
|
+
// Collect beforeRoute hooks, bucketed by scope.
|
|
595
|
+
if (plugin.hooks.beforeRoute) {
|
|
596
|
+
const hooks = toHookArray(plugin.hooks.beforeRoute);
|
|
597
|
+
if (plugin.scope === 'framework') {
|
|
598
|
+
frameworkBeforeRoute.push(...hooks);
|
|
599
|
+
}
|
|
600
|
+
else {
|
|
601
|
+
pluginBeforeRoute.push(...hooks);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
// Same startup guard as HTTP: a reserved transform key fails loud.
|
|
606
|
+
assertTransformKeys(pluginTransform, 'plugin transform (WebSocket)');
|
|
607
|
+
assertTransformKeys(this.globalRouteHooks?.transform, 'global transform (WebSocket)');
|
|
608
|
+
const globalBeforeRoute = this.globalRouteHooks?.beforeRoute
|
|
609
|
+
? toHookArray(this.globalRouteHooks.beforeRoute)
|
|
610
|
+
: undefined;
|
|
611
|
+
this.wsAdapter = new WebSocketAdapter({
|
|
612
|
+
router: this.wsRouter,
|
|
613
|
+
config: this.wsConfigOptions,
|
|
614
|
+
debug: this.options.debug,
|
|
615
|
+
providers: this.providers,
|
|
616
|
+
pluginTransform,
|
|
617
|
+
pluginBeforeRoute: pluginBeforeRoute.length > 0 ? pluginBeforeRoute : undefined,
|
|
618
|
+
frameworkBeforeRoute: frameworkBeforeRoute.length > 0
|
|
619
|
+
? frameworkBeforeRoute
|
|
620
|
+
: undefined,
|
|
621
|
+
onRequestHooks: this.onRequestHooks,
|
|
622
|
+
globalTransform: this.globalRouteHooks?.transform,
|
|
623
|
+
globalBeforeRoute,
|
|
624
|
+
ipHolder: this.dynamicRouter?.getRequestIPHolder(),
|
|
625
|
+
runtimeTarget: this.options.runtimeTarget,
|
|
626
|
+
});
|
|
627
|
+
// App-level WS hooks apply to every WS route (programmatic,
|
|
628
|
+
// prebuilt and file-based alike).
|
|
629
|
+
const globalWs = this.globalWsHooks;
|
|
630
|
+
const mergeWsHooks = globalWs
|
|
631
|
+
? (await import('./ws/compiler.js')).mergeWsHooks
|
|
632
|
+
: undefined;
|
|
633
|
+
const withGlobalWs = (hooks) => (mergeWsHooks ? mergeWsHooks(globalWs, hooks) : hooks);
|
|
634
|
+
// Add programmatic routes
|
|
635
|
+
for (const [path, route] of this.programmaticWsRoutes) {
|
|
636
|
+
this.wsRouter.addRoute({
|
|
637
|
+
path,
|
|
638
|
+
handlers: route.handlers,
|
|
639
|
+
hooks: withGlobalWs(undefined),
|
|
640
|
+
config: this.wsConfigOptions ?? {},
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
// Production path: use pre-built WebSocket routes (no filesystem scan)
|
|
644
|
+
const prebuiltWsRoutes = this.options.wsRoutes;
|
|
645
|
+
if (Array.isArray(prebuiltWsRoutes)) {
|
|
646
|
+
for (const route of prebuiltWsRoutes) {
|
|
647
|
+
warnTransportLevelWsConfig(route.path, route.config);
|
|
648
|
+
this.wsRouter.addRoute({
|
|
649
|
+
path: route.path,
|
|
650
|
+
handlers: route.handlers,
|
|
651
|
+
hooks: withGlobalWs(route.hooks),
|
|
652
|
+
// Deep-merge `auth`, keeping the global `auth.required`.
|
|
653
|
+
config: mergeWsConfig(this.wsConfigOptions, route.config),
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
return this.wsRouter.getRouteCount() > 0;
|
|
294
657
|
}
|
|
295
|
-
//
|
|
296
|
-
if (
|
|
297
|
-
|
|
658
|
+
// Scan file-based routes if wsDir is provided
|
|
659
|
+
if (this.wsDir) {
|
|
660
|
+
// Dev path — the scanner/compiler are loaded lazily so production
|
|
661
|
+
// AOT builds (prebuilt wsRoutes) never evaluate them.
|
|
662
|
+
const { WebSocketScanner } = await import('./ws/scanner.js');
|
|
663
|
+
const scanner = new WebSocketScanner(this.wsDir);
|
|
664
|
+
const scanResult = await scanner.scan();
|
|
665
|
+
if (scanResult.routes.length > 0) {
|
|
666
|
+
const { WebSocketCompiler } = await import('./ws/compiler.js');
|
|
667
|
+
const compiler = new WebSocketCompiler();
|
|
668
|
+
// Set global hooks if found (the hooks.ts beside wsDir, else
|
|
669
|
+
// the app-level hooks already loaded for API routes).
|
|
670
|
+
if (!scanResult.globalHooks && globalWs) {
|
|
671
|
+
compiler.setGlobalHooks(globalWs);
|
|
672
|
+
}
|
|
673
|
+
if (scanResult.globalHooks) {
|
|
674
|
+
try {
|
|
675
|
+
const hooksModule = await import(scanResult.globalHooks);
|
|
676
|
+
compiler.setGlobalHooks({
|
|
677
|
+
onOpen: hooksModule.onOpen,
|
|
678
|
+
onMessage: hooksModule.onMessage,
|
|
679
|
+
onClose: hooksModule.onClose,
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
catch (error) {
|
|
683
|
+
console.error('[WebSocket] Failed to load global hooks:', error);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
if (this.wsConfigOptions) {
|
|
687
|
+
compiler.setGlobalConfig(this.wsConfigOptions);
|
|
688
|
+
}
|
|
689
|
+
const compiledRoutes = await compiler.compileAll(scanResult.routes);
|
|
690
|
+
this.wsRouter.addRoutes(compiledRoutes);
|
|
691
|
+
}
|
|
298
692
|
}
|
|
299
|
-
|
|
300
|
-
return handler(request);
|
|
693
|
+
return this.wsRouter.getRouteCount() > 0;
|
|
301
694
|
}
|
|
302
695
|
/**
|
|
303
|
-
*
|
|
696
|
+
* Builds the Web-Standard fetch handler for this app.
|
|
304
697
|
*
|
|
305
|
-
*
|
|
306
|
-
*
|
|
307
|
-
*
|
|
308
|
-
*
|
|
309
|
-
* 4. If middleware returns function → save it to transform the final response later
|
|
310
|
-
* 5. After all middlewares, run the handler
|
|
311
|
-
* 6. Apply all saved "after" functions to the response (in reverse order)
|
|
698
|
+
* Dispatches the raw `Request` through the compiled routes (static map
|
|
699
|
+
* first, then the trie fallback for dynamic/wildcard and loose
|
|
700
|
+
* trailing-slash variants). API routes must be provided AOT (`apiRoutes`)
|
|
701
|
+
* or discovered from the filesystem on first call — never per request.
|
|
312
702
|
*
|
|
313
|
-
*
|
|
314
|
-
*
|
|
315
|
-
* -
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
703
|
+
* Runtime-agnostic: Bun.serve, Deno.serve, Vercel, Cloudflare Workers and
|
|
704
|
+
* Node 24+. WinterCG bindings (`env`, `executionCtx`) are bound onto the
|
|
705
|
+
* per-request `BurgerContext`. Pages (Bun-only) are not served here.
|
|
706
|
+
*
|
|
707
|
+
* ```ts
|
|
708
|
+
* import { Burger, toFetchHandler } from 'burger-api';
|
|
709
|
+
* const burger = new Burger({ apiRoutes });
|
|
710
|
+
* export default { fetch: toFetchHandler(burger) };
|
|
711
|
+
* ```
|
|
712
|
+
*/
|
|
713
|
+
async fetchHandler() {
|
|
714
|
+
await this.processApiRoutes();
|
|
715
|
+
await this.processPageRoutesOnce();
|
|
716
|
+
// Prepare WebSocket handling for WinterCG runtimes (Cloudflare /
|
|
717
|
+
// Deno consume upgrades right here). Bun's `serve()` path wires the
|
|
718
|
+
// same adapter itself; plain Node needs createNodeWsBridge instead.
|
|
719
|
+
const hasWsSources = Array.isArray(this.options.wsRoutes) ||
|
|
720
|
+
this.programmaticWsRoutes.size > 0 ||
|
|
721
|
+
!!this.wsDir;
|
|
722
|
+
if (!this.wsAdapter && hasWsSources) {
|
|
723
|
+
await this.processWebSocketRoutes();
|
|
724
|
+
}
|
|
725
|
+
const wsAdapter = this.wsAdapter;
|
|
726
|
+
// Direct lookups are exact static paths: page/asset/docs handlers and
|
|
727
|
+
// static API routes. Native pattern keys (`:param`, `*`) must never
|
|
728
|
+
// match literally. Bun-only page values and dynamic pages are not
|
|
729
|
+
// portable: warn instead of silently 404ing.
|
|
730
|
+
const routes = new Map();
|
|
731
|
+
const bunOnlyPages = [];
|
|
732
|
+
const apiPaths = this.apiRoutePaths;
|
|
733
|
+
for (const [key, handler] of Object.entries(this.routes)) {
|
|
734
|
+
if (typeof handler === 'function' &&
|
|
735
|
+
!key.includes(':') &&
|
|
736
|
+
!key.includes('*')) {
|
|
737
|
+
// Exact static path (page / asset / docs route).
|
|
738
|
+
routes.set(key, handler);
|
|
739
|
+
continue;
|
|
342
740
|
}
|
|
343
|
-
|
|
344
|
-
|
|
741
|
+
// API routes are per-method objects and dispatch through
|
|
742
|
+
// `router.fetch`; anything else non-callable is Bun-only.
|
|
743
|
+
if (apiPaths?.has(key) !== true)
|
|
744
|
+
bunOnlyPages.push(key);
|
|
745
|
+
}
|
|
746
|
+
if (bunOnlyPages.length > 0) {
|
|
747
|
+
console.warn(`[burger-api] ${bunOnlyPages.length} page route(s) are only served by serve() on Bun ` +
|
|
748
|
+
`(HTML-import bundles / dynamic pages) and will 404 through fetchHandler()/toFetchHandler(): ` +
|
|
749
|
+
bunOnlyPages.join(', '));
|
|
750
|
+
}
|
|
751
|
+
const router = this.dynamicRouter;
|
|
752
|
+
// Static API routes join the same table: one Map.get resolves any
|
|
753
|
+
// exact static path (page, asset, docs, or API), no second lookup.
|
|
754
|
+
if (router) {
|
|
755
|
+
for (const [path, dispatch] of router.staticDispatchMap()) {
|
|
756
|
+
routes.set(path, dispatch);
|
|
345
757
|
}
|
|
346
|
-
return response;
|
|
347
758
|
}
|
|
348
|
-
//
|
|
349
|
-
//
|
|
350
|
-
const
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
759
|
+
// No direct entries: skip the lookup entirely and let the router parse
|
|
760
|
+
// the pathname once in `fetch` (dynamic-only apps, 404s).
|
|
761
|
+
const hasPageRoutes = routes.size > 0;
|
|
762
|
+
/**
|
|
763
|
+
* Shared HTTP dispatch: the direct static table (pages, assets, docs,
|
|
764
|
+
* static API routes) first, then the API router for dynamic /
|
|
765
|
+
* loose-trailing-slash / `/`+`//` requests and 404s. The pathname is
|
|
766
|
+
* extracted once and reused for both lookups.
|
|
767
|
+
*/
|
|
768
|
+
const dispatchHttp = (request, env, executionCtx) => {
|
|
769
|
+
if (hasPageRoutes) {
|
|
770
|
+
const pathname = extractPathnameFromUrl(request.url);
|
|
771
|
+
const handler = routes.get(pathname);
|
|
772
|
+
if (handler) {
|
|
773
|
+
return handler(request, undefined, undefined, env, executionCtx);
|
|
774
|
+
}
|
|
775
|
+
if (router) {
|
|
776
|
+
return router.fetchWithPath(request, pathname, env, executionCtx);
|
|
366
777
|
}
|
|
367
|
-
return
|
|
778
|
+
return this.notFound();
|
|
368
779
|
}
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
780
|
+
if (router)
|
|
781
|
+
return router.fetch(request, env, executionCtx);
|
|
782
|
+
return this.notFound();
|
|
783
|
+
};
|
|
784
|
+
/** Async-only path: a WebSocket upgrade must be awaited. */
|
|
785
|
+
const handleWsUpgrade = async (request, env, executionCtx) => {
|
|
786
|
+
const outcome = await wsAdapter.handleUpgrade(request, undefined, env, executionCtx);
|
|
787
|
+
if (outcome.handled) {
|
|
788
|
+
return (outcome.response ??
|
|
789
|
+
new Response(null, { status: 101 }));
|
|
372
790
|
}
|
|
373
|
-
//
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
response = await afterStack[1](response);
|
|
385
|
-
return afterStack[0](response);
|
|
386
|
-
}
|
|
387
|
-
// General case: 3+ after functions
|
|
388
|
-
for (let i = afterCount - 1; i >= 0; i--) {
|
|
389
|
-
response = await afterStack[i](response);
|
|
791
|
+
// Not consumed: fall through to the normal HTTP dispatch.
|
|
792
|
+
return dispatchHttp(request, env, executionCtx);
|
|
793
|
+
};
|
|
794
|
+
// No WebSocket adapter: no upgrade probe is needed at all.
|
|
795
|
+
if (!wsAdapter) {
|
|
796
|
+
// API-only app: the router's `fetch` is the entry point (the
|
|
797
|
+
// public contract still returns a Promise).
|
|
798
|
+
if (!hasPageRoutes && router) {
|
|
799
|
+
return (request, env, executionCtx) => Promise.resolve(router.fetch(request, env, executionCtx));
|
|
800
|
+
}
|
|
801
|
+
return (request, env, executionCtx) => Promise.resolve(dispatchHttp(request, env, executionCtx));
|
|
390
802
|
}
|
|
391
|
-
return
|
|
803
|
+
return (request, env, executionCtx) => {
|
|
804
|
+
// WebSocket upgrades are consumed before HTTP dispatch.
|
|
805
|
+
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
|
806
|
+
return handleWsUpgrade(request, env, executionCtx);
|
|
807
|
+
}
|
|
808
|
+
return Promise.resolve(dispatchHttp(request, env, executionCtx));
|
|
809
|
+
};
|
|
392
810
|
}
|
|
393
811
|
/**
|
|
394
|
-
* Starts the server and
|
|
395
|
-
* @param port
|
|
396
|
-
* @param cb
|
|
397
|
-
* @returns A Promise that resolves when the server has started listening.
|
|
812
|
+
* Starts the server and listens for requests.
|
|
813
|
+
* @param port Port to listen on (default `4000`).
|
|
814
|
+
* @param cb Called when the server is listening.
|
|
398
815
|
*/
|
|
399
816
|
async serve(port = 4000, cb) {
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
817
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
818
|
+
throw new Error(`[burger-api] Invalid port ${JSON.stringify(port)} — expected an integer from 0 to 65535.`);
|
|
819
|
+
}
|
|
820
|
+
// Process API routes first so convention files (plugins.ts, providers.ts)
|
|
821
|
+
// are loaded before WebSocket reads the registries (avoids race).
|
|
822
|
+
const apiConfigured = await this.processApiRoutes();
|
|
823
|
+
const [pagesConfigured, wsConfigured] = await Promise.all([
|
|
824
|
+
this.processPageRoutesOnce(),
|
|
825
|
+
this.processWebSocketRoutes(),
|
|
404
826
|
]);
|
|
405
|
-
|
|
406
|
-
const routesConfigured = pagesConfigured || apiConfigured;
|
|
407
|
-
// If routes were configured, start the server
|
|
827
|
+
const routesConfigured = pagesConfigured || apiConfigured || wsConfigured;
|
|
408
828
|
if (routesConfigured) {
|
|
409
|
-
//
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
829
|
+
// The adapter records its server handle as the lazy `ctx.ip`
|
|
830
|
+
// source (see the `onServer` hook below) — no per-request work.
|
|
831
|
+
const fetchHandler = this.dynamicRouter
|
|
832
|
+
? (request) => this.dynamicRouter.fetch(request)
|
|
833
|
+
: () => this.notFound();
|
|
834
|
+
const wsOptions = this.wsAdapter?.createWebSocketOption();
|
|
835
|
+
const wsAdapter = this.wsAdapter;
|
|
836
|
+
// Combined fetch handler: try the WebSocket upgrade first, then
|
|
837
|
+
// fall through to HTTP only when the request was not consumed.
|
|
838
|
+
const combinedFetch = wsAdapter
|
|
839
|
+
? async (request, server) => {
|
|
840
|
+
// Cheap header probe first: plain HTTP requests (no
|
|
841
|
+
// `upgrade: websocket`) skip the async upgrade path.
|
|
842
|
+
if (request.headers.get('upgrade')?.toLowerCase() !==
|
|
843
|
+
'websocket') {
|
|
844
|
+
return fetchHandler(request, server);
|
|
845
|
+
}
|
|
846
|
+
const outcome = await wsAdapter.handleUpgrade(request, server);
|
|
847
|
+
if (outcome.handled) {
|
|
848
|
+
// Socket taken over (Bun returns 101 itself) or a
|
|
849
|
+
// protocol response (404 / auth rejection) — the
|
|
850
|
+
// HTTP pipeline must NOT run.
|
|
851
|
+
return outcome.response;
|
|
852
|
+
}
|
|
853
|
+
return fetchHandler(request, server);
|
|
854
|
+
}
|
|
855
|
+
: fetchHandler;
|
|
856
|
+
// A WS route on the same path as a static HTTP route is
|
|
857
|
+
// unreachable: Bun's static routes answer before the upgrade.
|
|
858
|
+
for (const wsRoute of this.wsRouter?.getRoutes() ?? []) {
|
|
859
|
+
if (this.routes[wsRoute.path]) {
|
|
860
|
+
console.warn(`[burger-api] WebSocket route "${wsRoute.path}" is shadowed by an HTTP route on the same path — upgrades never reach it. Move one of them.`);
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
await this.server.start({
|
|
864
|
+
staticRoutes: this.routes,
|
|
865
|
+
fetch: combinedFetch,
|
|
866
|
+
websocket: wsOptions,
|
|
867
|
+
port,
|
|
868
|
+
onListen: cb,
|
|
869
|
+
onServer: (server) => this.dynamicRouter?.setRequestIPSource(server),
|
|
870
|
+
});
|
|
413
871
|
}
|
|
414
872
|
else {
|
|
415
|
-
//
|
|
416
|
-
|
|
873
|
+
// Nothing to serve is a startup error, never a silent no-op.
|
|
874
|
+
throw new Error(this.emptyApiDir
|
|
875
|
+
? `[burger-api] No routes configured — the API directory "${this.emptyApiDir}" has no route files. ` +
|
|
876
|
+
'Each endpoint is a folder with a route.ts, e.g. src/api/hello/route.ts: ' +
|
|
877
|
+
'export async function GET(ctx) { return Response.json({ hello: "world" }); }'
|
|
878
|
+
: '[burger-api] No routes configured! Please provide apiDir/pageDir (for dev) or apiRoutes/pageRoutes (for production builds) when initializing the Burger class.');
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* The underlying `Server` instance, exposed so callers can stop the
|
|
883
|
+
* server cleanly.
|
|
884
|
+
*/
|
|
885
|
+
getServer() {
|
|
886
|
+
return this.server;
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* Node WebSocket integration: returns a bridge that plugs the framework
|
|
890
|
+
* pipeline into node:http's `'upgrade'` event using a framing library's
|
|
891
|
+
* `WebSocketServer` (e.g. the `ws` package). Call `fetchHandler()` (or
|
|
892
|
+
* `serve()`) first — WebSocket routes are processed there.
|
|
893
|
+
*
|
|
894
|
+
* ```ts
|
|
895
|
+
* import http from 'node:http';
|
|
896
|
+
* import { WebSocketServer } from 'ws';
|
|
897
|
+
*
|
|
898
|
+
* const fetchHandler = await burger.fetchHandler();
|
|
899
|
+
* const bridge = burger.createNodeWsBridge({ WebSocketServer });
|
|
900
|
+
* http.createServer((req, res) => { ... })
|
|
901
|
+
* .on('upgrade', (req, socket, head) =>
|
|
902
|
+
* bridge.handleUpgrade(req, socket, head))
|
|
903
|
+
* .listen(3000);
|
|
904
|
+
* ```
|
|
905
|
+
*/
|
|
906
|
+
createNodeWsBridge(options) {
|
|
907
|
+
if (!this.wsAdapter) {
|
|
908
|
+
throw new Error(this.routesProcessed
|
|
909
|
+
? '[burger-api] createNodeWsBridge(): no WebSocket routes are configured — ' +
|
|
910
|
+
'add wsDir / wsRoutes / burger.websocket() first.'
|
|
911
|
+
: '[burger-api] createNodeWsBridge() was called too early. Call it after ' +
|
|
912
|
+
'`const fetch = await burger.fetchHandler();` (or `await burger.serve()`) — ' +
|
|
913
|
+
'WebSocket routes are processed there.');
|
|
417
914
|
}
|
|
915
|
+
return this.wsAdapter.createNodeWsBridge(options);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Connection-level WebSocket options (`maxPayloadLength`, `idleTimeout`,
|
|
920
|
+
* `compression`, …) are Bun.serve-wide: a route-level value cannot override
|
|
921
|
+
* what Bun enforces for the whole server, so warn loud instead of ignoring it.
|
|
922
|
+
*/
|
|
923
|
+
const WS_TRANSPORT_KEYS = [
|
|
924
|
+
'maxPayloadLength',
|
|
925
|
+
'idleTimeout',
|
|
926
|
+
'backpressureLimit',
|
|
927
|
+
'closeOnBackpressureLimit',
|
|
928
|
+
'compression',
|
|
929
|
+
];
|
|
930
|
+
/**
|
|
931
|
+
* Base64 of the UTF-8 bytes. `btoa` alone throws on non-Latin1 input, so a
|
|
932
|
+
* password with accents/emoji would break startup.
|
|
933
|
+
*/
|
|
934
|
+
function base64Utf8(value) {
|
|
935
|
+
const bytes = new TextEncoder().encode(value);
|
|
936
|
+
let binary = '';
|
|
937
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
938
|
+
binary += String.fromCharCode(bytes[i]);
|
|
939
|
+
}
|
|
940
|
+
return btoa(binary);
|
|
941
|
+
}
|
|
942
|
+
/** Picks the WebSocket hooks out of an app-level hooks object. */
|
|
943
|
+
function pickWsHooks(hooks) {
|
|
944
|
+
if (!hooks)
|
|
945
|
+
return undefined;
|
|
946
|
+
const { onOpen, onMessage, onClose } = hooks;
|
|
947
|
+
if (!onOpen && !onMessage && !onClose)
|
|
948
|
+
return undefined;
|
|
949
|
+
return { onOpen, onMessage, onClose };
|
|
950
|
+
}
|
|
951
|
+
function warnTransportLevelWsConfig(path, config) {
|
|
952
|
+
if (!config)
|
|
953
|
+
return;
|
|
954
|
+
for (const key of WS_TRANSPORT_KEYS) {
|
|
955
|
+
if (config[key] !== undefined) {
|
|
956
|
+
console.warn(`[burger-api] WebSocket route "${path}": config.${key} is ` +
|
|
957
|
+
'connection-level and can only be set globally via ' +
|
|
958
|
+
'burger.wsConfig() — the per-route value is ignored.');
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* Merges global and per-route config. `auth` is merged deeply so a route-level
|
|
964
|
+
* `auth.roles` keeps a global `auth.required`; either side `false` disables it.
|
|
965
|
+
*/
|
|
966
|
+
function mergeWsConfig(globalConfig, routeConfig) {
|
|
967
|
+
const merged = {
|
|
968
|
+
...globalConfig,
|
|
969
|
+
...routeConfig,
|
|
970
|
+
};
|
|
971
|
+
const globalAuth = globalConfig?.auth;
|
|
972
|
+
const routeAuth = routeConfig?.auth;
|
|
973
|
+
if (globalAuth !== undefined || routeAuth !== undefined) {
|
|
974
|
+
merged.auth =
|
|
975
|
+
globalAuth === false || routeAuth === false
|
|
976
|
+
? false
|
|
977
|
+
: {
|
|
978
|
+
...(typeof globalAuth === 'object' ? globalAuth : {}),
|
|
979
|
+
...(typeof routeAuth === 'object' ? routeAuth : {}),
|
|
980
|
+
};
|
|
418
981
|
}
|
|
982
|
+
return merged;
|
|
419
983
|
}
|
|
420
|
-
// Export
|
|
421
|
-
export {
|
|
984
|
+
// Export BurgerContext (the public request context type)
|
|
985
|
+
export { BurgerContext, setRequestIP } from './context/context.js';
|
|
986
|
+
// Export the schema-typed route/hooks helpers
|
|
987
|
+
export { defineRoute, defineHooks } from './router/define.js';
|
|
988
|
+
// Export the runtime-capability model (used by the CLI build and docs).
|
|
989
|
+
export { RUNTIME_CAPABILITIES } from './runtime/capabilities.js';
|
|
990
|
+
// Export utils used by examples and CLI build pipeline
|
|
991
|
+
export { setDir } from './utils/index.js';
|
|
992
|
+
export { cleanPrefix, normalizePath } from './utils/index.js';
|
|
993
|
+
// Export constant-time comparison (used by ecosystem auth plugins)
|
|
994
|
+
export { timingSafeEqual } from './utils/timing-safe.js';
|
|
995
|
+
// Export error classes
|
|
996
|
+
export { HTTPError, renderHTTPError } from './errors/http-error.js';
|
|
997
|
+
export { ASSET_MIME, contentTypeFor } from './core/asset-mime.js';
|
|
998
|
+
export { ValidationError } from './validation/error.js';
|
|
999
|
+
export { NotFoundError } from './errors/not-found.js';
|
|
1000
|
+
export { UnauthorizedError } from './errors/unauthorized.js';
|
|
1001
|
+
export { ForbiddenError } from './errors/forbidden.js';
|
|
1002
|
+
export { MethodNotAllowedError } from './errors/method-not-allowed.js';
|
|
1003
|
+
// Export docs providers
|
|
1004
|
+
export { scalarDocs, swaggerDocs, redocDocs } from './core/docs-providers.js';
|
|
1005
|
+
// Export the Web-Standard (WinterCG) fetch entry
|
|
1006
|
+
export { toFetchHandler } from './adapter/web-standard/index.js';
|
|
1007
|
+
export { WebSocketReadyState, WebSocketCloseCode, BurgerWSContext, } from './ws/types.js';
|
|
1008
|
+
export { WebSocketAdapter } from './ws/adapter.js';
|