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,623 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Matches upgrade requests to routes and wires sockets to their handlers.
|
|
3
|
+
*/
|
|
4
|
+
import { BurgerWSContext } from './types.js';
|
|
5
|
+
import { HTTPError, renderHTTPError } from '../errors/http-error.js';
|
|
6
|
+
import { BurgerContext } from '../context/context.js';
|
|
7
|
+
import { applyTransform } from '../lifecycle/transform.js';
|
|
8
|
+
import { acceptWsUpgrade, detectWsPlatform, normalizeWsMessage, } from './platform.js';
|
|
9
|
+
import { RUNTIME_CAPABILITIES } from '../runtime/capabilities.js';
|
|
10
|
+
import { resolveDebug } from '../utils/env.js';
|
|
11
|
+
/** Internal socket-data slot holding the route matched at upgrade. */
|
|
12
|
+
const WS_ROUTE = Symbol('burger-api.ws.route');
|
|
13
|
+
/**
|
|
14
|
+
* WebSocket adapter: upgrade handoff, auth gate and per-connection contexts.
|
|
15
|
+
*/
|
|
16
|
+
export class WebSocketAdapter {
|
|
17
|
+
router;
|
|
18
|
+
config;
|
|
19
|
+
debug;
|
|
20
|
+
providers;
|
|
21
|
+
pluginTransform;
|
|
22
|
+
pluginBeforeRoute;
|
|
23
|
+
frameworkBeforeRoute;
|
|
24
|
+
onRequestHooks;
|
|
25
|
+
globalTransform;
|
|
26
|
+
globalBeforeRoute;
|
|
27
|
+
ipHolder;
|
|
28
|
+
runtimeTarget;
|
|
29
|
+
/** One context per connection, so `ws.data` mutations persist. */
|
|
30
|
+
wsContexts = new WeakMap();
|
|
31
|
+
/** Matched route per connection (see `getMatch`). */
|
|
32
|
+
wsMatches = new WeakMap();
|
|
33
|
+
/**
|
|
34
|
+
* Per-socket event chain: messages (and close/drain/ping/pong) are
|
|
35
|
+
* delivered in order and only after `open` finished. The first event runs
|
|
36
|
+
* synchronously; only queued events wait on the chain.
|
|
37
|
+
*/
|
|
38
|
+
wsChains = new WeakMap();
|
|
39
|
+
constructor(options) {
|
|
40
|
+
this.router = options.router;
|
|
41
|
+
this.config = options.config ?? {};
|
|
42
|
+
this.debug = resolveDebug(options.debug);
|
|
43
|
+
this.providers = options.providers;
|
|
44
|
+
this.pluginTransform = options.pluginTransform;
|
|
45
|
+
this.pluginBeforeRoute = options.pluginBeforeRoute;
|
|
46
|
+
this.frameworkBeforeRoute = options.frameworkBeforeRoute ?? [];
|
|
47
|
+
this.onRequestHooks = options.onRequestHooks ?? [];
|
|
48
|
+
this.globalTransform = options.globalTransform;
|
|
49
|
+
this.globalBeforeRoute = options.globalBeforeRoute ?? [];
|
|
50
|
+
this.ipHolder = options.ipHolder;
|
|
51
|
+
this.runtimeTarget = options.runtimeTarget;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Create the websocket option for Bun.serve()
|
|
55
|
+
*/
|
|
56
|
+
createWebSocketOption() {
|
|
57
|
+
const self = this;
|
|
58
|
+
// Forward only defined connection limits; Bun's defaults apply otherwise.
|
|
59
|
+
const option = {
|
|
60
|
+
open(ws) {
|
|
61
|
+
return self.handleOpen(ws);
|
|
62
|
+
},
|
|
63
|
+
message(ws, message) {
|
|
64
|
+
return self.handleMessage(ws, message);
|
|
65
|
+
},
|
|
66
|
+
close(ws, code, reason) {
|
|
67
|
+
return self.handleClose(ws, code, reason);
|
|
68
|
+
},
|
|
69
|
+
drain(ws) {
|
|
70
|
+
return self.handleDrain(ws);
|
|
71
|
+
},
|
|
72
|
+
ping(ws) {
|
|
73
|
+
return self.handlePing(ws);
|
|
74
|
+
},
|
|
75
|
+
pong(ws) {
|
|
76
|
+
return self.handlePong(ws);
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
if (this.config.maxPayloadLength !== undefined) {
|
|
80
|
+
option.maxPayloadLength = this.config.maxPayloadLength;
|
|
81
|
+
}
|
|
82
|
+
if (this.config.idleTimeout !== undefined) {
|
|
83
|
+
option.idleTimeout = this.config.idleTimeout;
|
|
84
|
+
}
|
|
85
|
+
if (this.config.backpressureLimit !== undefined) {
|
|
86
|
+
option.backpressureLimit = this.config.backpressureLimit;
|
|
87
|
+
}
|
|
88
|
+
if (this.config.closeOnBackpressureLimit !== undefined) {
|
|
89
|
+
option.closeOnBackpressureLimit =
|
|
90
|
+
this.config.closeOnBackpressureLimit;
|
|
91
|
+
}
|
|
92
|
+
if (this.config.compression !== undefined) {
|
|
93
|
+
option.compression = this.config.compression;
|
|
94
|
+
}
|
|
95
|
+
return option;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Serializes events per socket. The first event starts synchronously (a
|
|
99
|
+
* sync handler keeps its immediate behavior); queued events run in order
|
|
100
|
+
* after it. Handlers catch their own errors, so the chain never rejects.
|
|
101
|
+
*/
|
|
102
|
+
enqueue(ws, work) {
|
|
103
|
+
const previous = this.wsChains.get(ws);
|
|
104
|
+
if (previous === undefined) {
|
|
105
|
+
const result = work();
|
|
106
|
+
this.wsChains.set(ws, Promise.resolve(result).catch(() => { }));
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
const next = previous.then(() => work());
|
|
110
|
+
this.wsChains.set(ws, next.catch(() => { }));
|
|
111
|
+
return next;
|
|
112
|
+
}
|
|
113
|
+
handleOpen(ws) {
|
|
114
|
+
return this.enqueue(ws, () => this.runOpen(ws));
|
|
115
|
+
}
|
|
116
|
+
async runOpen(ws) {
|
|
117
|
+
const route = this.getRouteFromWs(ws);
|
|
118
|
+
if (!route) {
|
|
119
|
+
console.warn('[burger-api] WebSocket connection has no matched route (socket data missing) — handlers will not run.');
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const burgerWs = this.createBurgerWS(ws);
|
|
123
|
+
// Run hooks first
|
|
124
|
+
if (route.hooks?.onOpen) {
|
|
125
|
+
try {
|
|
126
|
+
await route.hooks.onOpen(burgerWs);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
console.error('[WebSocket] onOpen hook error:', error);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
// Run handler
|
|
133
|
+
if (route.handlers.open) {
|
|
134
|
+
try {
|
|
135
|
+
await route.handlers.open(burgerWs);
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
console.error('[WebSocket] open handler error:', error);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
handleMessage(ws, message) {
|
|
143
|
+
return this.enqueue(ws, () => this.runMessage(ws, message));
|
|
144
|
+
}
|
|
145
|
+
async runMessage(ws, message) {
|
|
146
|
+
const route = this.getRouteFromWs(ws);
|
|
147
|
+
if (!route)
|
|
148
|
+
return;
|
|
149
|
+
const burgerWs = this.createBurgerWS(ws);
|
|
150
|
+
// Run hooks first
|
|
151
|
+
if (route.hooks?.onMessage) {
|
|
152
|
+
try {
|
|
153
|
+
await route.hooks.onMessage(burgerWs, message);
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
console.error('[WebSocket] onMessage hook error:', error);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
// Run handler
|
|
160
|
+
if (route.handlers.message) {
|
|
161
|
+
try {
|
|
162
|
+
await route.handlers.message(burgerWs, message);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
console.error('[WebSocket] message handler error:', error);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
handleClose(ws, code, reason) {
|
|
170
|
+
return this.enqueue(ws, () => this.runClose(ws, code, reason));
|
|
171
|
+
}
|
|
172
|
+
async runClose(ws, code, reason) {
|
|
173
|
+
const route = this.getRouteFromWs(ws);
|
|
174
|
+
if (!route)
|
|
175
|
+
return;
|
|
176
|
+
const burgerWs = this.createBurgerWS(ws);
|
|
177
|
+
// Run hooks first
|
|
178
|
+
if (route.hooks?.onClose) {
|
|
179
|
+
try {
|
|
180
|
+
await route.hooks.onClose(burgerWs, code, reason);
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
console.error('[WebSocket] onClose hook error:', error);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
// Run handler
|
|
187
|
+
if (route.handlers.close) {
|
|
188
|
+
try {
|
|
189
|
+
await route.handlers.close(burgerWs, code, reason);
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
console.error('[WebSocket] close handler error:', error);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
// Connection is gone — drop the cached context and its chain.
|
|
196
|
+
this.wsContexts.delete(ws);
|
|
197
|
+
this.wsChains.delete(ws);
|
|
198
|
+
}
|
|
199
|
+
handleDrain(ws) {
|
|
200
|
+
return this.enqueue(ws, () => this.runDrain(ws));
|
|
201
|
+
}
|
|
202
|
+
async runDrain(ws) {
|
|
203
|
+
const route = this.getRouteFromWs(ws);
|
|
204
|
+
if (!route)
|
|
205
|
+
return;
|
|
206
|
+
const burgerWs = this.createBurgerWS(ws);
|
|
207
|
+
if (route.handlers.drain) {
|
|
208
|
+
try {
|
|
209
|
+
await route.handlers.drain(burgerWs);
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
console.error('[WebSocket] drain handler error:', error);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
handlePing(ws) {
|
|
217
|
+
return this.enqueue(ws, () => this.runPing(ws));
|
|
218
|
+
}
|
|
219
|
+
async runPing(ws) {
|
|
220
|
+
const route = this.getRouteFromWs(ws);
|
|
221
|
+
if (!route)
|
|
222
|
+
return;
|
|
223
|
+
const burgerWs = this.createBurgerWS(ws);
|
|
224
|
+
if (route.handlers.ping) {
|
|
225
|
+
try {
|
|
226
|
+
await route.handlers.ping(burgerWs);
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
console.error('[WebSocket] ping handler error:', error);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
handlePong(ws) {
|
|
234
|
+
return this.enqueue(ws, () => this.runPong(ws));
|
|
235
|
+
}
|
|
236
|
+
async runPong(ws) {
|
|
237
|
+
const route = this.getRouteFromWs(ws);
|
|
238
|
+
if (!route)
|
|
239
|
+
return;
|
|
240
|
+
const burgerWs = this.createBurgerWS(ws);
|
|
241
|
+
if (route.handlers.pong) {
|
|
242
|
+
try {
|
|
243
|
+
await route.handlers.pong(burgerWs);
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
console.error('[WebSocket] pong handler error:', error);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Entry point for WebSocket handling on every runtime: detects the
|
|
252
|
+
* platform, matches the route, runs the auth gate and performs the
|
|
253
|
+
* protocol handoff. Returns an explicit outcome so callers can never
|
|
254
|
+
* confuse "not an upgrade" with "socket taken over".
|
|
255
|
+
*
|
|
256
|
+
* @param request incoming request (upgrade or normal)
|
|
257
|
+
* @param server Bun serve handle when running under `Bun.serve`
|
|
258
|
+
* @param env platform bindings (bound onto the temporary auth context)
|
|
259
|
+
*/
|
|
260
|
+
async handleUpgrade(request, server, env, executionCtx) {
|
|
261
|
+
const upgradeHeader = request.headers.get('upgrade');
|
|
262
|
+
if (upgradeHeader?.toLowerCase() !== 'websocket') {
|
|
263
|
+
return { handled: false };
|
|
264
|
+
}
|
|
265
|
+
const result = await this.matchAndAuthorize(request, env, executionCtx);
|
|
266
|
+
if (!result.ok) {
|
|
267
|
+
return { handled: true, response: result.response };
|
|
268
|
+
}
|
|
269
|
+
if (this.runtimeTarget &&
|
|
270
|
+
!RUNTIME_CAPABILITIES[this.runtimeTarget].websocket) {
|
|
271
|
+
return this.capabilityUnsupportedResponse(this.runtimeTarget);
|
|
272
|
+
}
|
|
273
|
+
// A declared target resolves the handoff directly; otherwise fall back
|
|
274
|
+
// to live probing. `!== 'vercel'` is unreachable here (the capability
|
|
275
|
+
// guard above returned already) — it only narrows the type.
|
|
276
|
+
const platform = this.runtimeTarget && this.runtimeTarget !== 'vercel'
|
|
277
|
+
? this.runtimeTarget
|
|
278
|
+
: detectWsPlatform(server);
|
|
279
|
+
if (platform === 'node') {
|
|
280
|
+
return this.nodeFetchUpgradeUnsupported();
|
|
281
|
+
}
|
|
282
|
+
const response = acceptWsUpgrade({
|
|
283
|
+
platform,
|
|
284
|
+
request,
|
|
285
|
+
server,
|
|
286
|
+
data: result.data,
|
|
287
|
+
events: this.eventSink(),
|
|
288
|
+
});
|
|
289
|
+
return { handled: true, response };
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Route-match + auth, shared by every platform's upgrade handoff. The Node
|
|
293
|
+
* bridge cannot reuse {@link handleUpgrade} because that always routes
|
|
294
|
+
* through {@link detectWsPlatform}, which falls back to `'node'` there.
|
|
295
|
+
*/
|
|
296
|
+
async matchAndAuthorize(request, env, executionCtx) {
|
|
297
|
+
const url = new URL(request.url);
|
|
298
|
+
const match = this.router.match(url.pathname);
|
|
299
|
+
if (!match) {
|
|
300
|
+
return {
|
|
301
|
+
ok: false,
|
|
302
|
+
response: new Response('WebSocket route not found', {
|
|
303
|
+
status: 404,
|
|
304
|
+
}),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
const routeConfig = match.route.config;
|
|
308
|
+
const authResult = await this.runAuthHooks(request, routeConfig, env, executionCtx);
|
|
309
|
+
if (authResult.response) {
|
|
310
|
+
return { ok: false, response: authResult.response };
|
|
311
|
+
}
|
|
312
|
+
// The matched route rides in a non-enumerable symbol slot (invisible in
|
|
313
|
+
// `ws.data` copies/JSON) but travels with every platform that attaches
|
|
314
|
+
// `data` to the socket. The URL is stored once here so `ws.url` and
|
|
315
|
+
// `ws.query` parse lazily per socket, never per request.
|
|
316
|
+
const data = {};
|
|
317
|
+
Object.defineProperty(data, WS_ROUTE, {
|
|
318
|
+
value: {
|
|
319
|
+
route: match.route,
|
|
320
|
+
params: match.params,
|
|
321
|
+
wildcardParams: match.wildcardParams,
|
|
322
|
+
url: request.url,
|
|
323
|
+
},
|
|
324
|
+
enumerable: false,
|
|
325
|
+
});
|
|
326
|
+
if (authResult.user !== undefined) {
|
|
327
|
+
data.user = authResult.user;
|
|
328
|
+
}
|
|
329
|
+
return { ok: true, data };
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Node cannot complete a WebSocket handshake inside a fetch handler —
|
|
333
|
+
* surface an explicit 501 with remediation instead of a thrown error.
|
|
334
|
+
*/
|
|
335
|
+
nodeFetchUpgradeUnsupported() {
|
|
336
|
+
return {
|
|
337
|
+
handled: true,
|
|
338
|
+
response: new Response('WebSocket upgrades on Node require burger.createNodeWsBridge(...) ' +
|
|
339
|
+
"wired to node:http's 'upgrade' event.", { status: 501 }),
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Declared-target counterpart to {@link nodeFetchUpgradeUnsupported}: a
|
|
344
|
+
* target with `websocket: false` (only `vercel` today) gets a "not
|
|
345
|
+
* supported here" response — the Node bridge would be wrong advice, since
|
|
346
|
+
* that target has no persistent process.
|
|
347
|
+
*/
|
|
348
|
+
capabilityUnsupportedResponse(target) {
|
|
349
|
+
return {
|
|
350
|
+
handled: true,
|
|
351
|
+
response: new Response(`WebSocket is not supported on the "${target}" deployment ` +
|
|
352
|
+
'target: this platform has no persistent-connection ' +
|
|
353
|
+
'model for WebSocket upgrades. See the compatibility ' +
|
|
354
|
+
'docs for what each runtime supports.', { status: 501 }),
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
/** Shared event sink pushed into by non-Bun platforms. */
|
|
358
|
+
eventSink() {
|
|
359
|
+
return {
|
|
360
|
+
onOpen: (raw) => this.handleOpen(raw),
|
|
361
|
+
onMessage: (raw, message) => this.handleMessage(raw, message),
|
|
362
|
+
onClose: (raw, code, reason) => this.handleClose(raw, code, reason),
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Fetch-shaped wrapper around {@link handleUpgrade}, kept for backward
|
|
367
|
+
* compatibility. Returns `undefined` for BOTH "not an upgrade" and "socket
|
|
368
|
+
* taken over" — prefer {@link handleUpgrade} when the distinction matters.
|
|
369
|
+
*/
|
|
370
|
+
createFetchHandler() {
|
|
371
|
+
return async (request, server) => {
|
|
372
|
+
const outcome = await this.handleUpgrade(request, server);
|
|
373
|
+
return outcome.handled ? outcome.response : undefined;
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Node integration: bridges node:http's `'upgrade'` event into the framework
|
|
378
|
+
* pipeline using a framing library's `WebSocketServer` (e.g. the `ws`
|
|
379
|
+
* package). `fetchHandler()` must run at least once first — WS routes are
|
|
380
|
+
* processed there.
|
|
381
|
+
*
|
|
382
|
+
* ```ts
|
|
383
|
+
* import http from 'node:http';
|
|
384
|
+
* import { WebSocketServer } from 'ws';
|
|
385
|
+
*
|
|
386
|
+
* const fetchHandler = await burger.fetchHandler();
|
|
387
|
+
* const bridge = burger.createNodeWsBridge({ WebSocketServer });
|
|
388
|
+
* http.createServer((req, res) => { ... }) // bridge req/res <-> Request/Response
|
|
389
|
+
* .on('upgrade', (req, socket, head) => bridge.handleUpgrade(req, socket, head))
|
|
390
|
+
* .listen(3000);
|
|
391
|
+
* ```
|
|
392
|
+
*/
|
|
393
|
+
createNodeWsBridge(options) {
|
|
394
|
+
const wss = new options.WebSocketServer({ noServer: true });
|
|
395
|
+
const adapter = this;
|
|
396
|
+
return {
|
|
397
|
+
async handleUpgrade(req, socket, head) {
|
|
398
|
+
const destroy = () => socket.destroy?.();
|
|
399
|
+
const raw = req;
|
|
400
|
+
// Copy real headers, not just `host`: auth hooks may read
|
|
401
|
+
// cookies/Authorization, and the Upgrade check needs them.
|
|
402
|
+
const headers = new Headers();
|
|
403
|
+
for (const [key, value] of Object.entries(raw.headers)) {
|
|
404
|
+
if (value === undefined)
|
|
405
|
+
continue;
|
|
406
|
+
if (Array.isArray(value)) {
|
|
407
|
+
for (const v of value)
|
|
408
|
+
headers.append(key, v);
|
|
409
|
+
}
|
|
410
|
+
else {
|
|
411
|
+
headers.set(key, value);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
const host = String(raw.headers.host ?? 'localhost');
|
|
415
|
+
let request;
|
|
416
|
+
try {
|
|
417
|
+
request = new Request(`http://${host}${raw.url ?? '/'}`, {
|
|
418
|
+
headers,
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
catch {
|
|
422
|
+
// A malformed Host header throws here, inside an async
|
|
423
|
+
// 'upgrade' handler — an unhandled rejection would kill
|
|
424
|
+
// the Node process. Reject the socket instead.
|
|
425
|
+
destroy();
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const upgradeHeader = request.headers.get('upgrade');
|
|
429
|
+
if (upgradeHeader?.toLowerCase() !== 'websocket') {
|
|
430
|
+
destroy();
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
// Not `adapter.handleUpgrade()`: it would detect `'node'` and
|
|
434
|
+
// return a 501. Node's handoff happens below via
|
|
435
|
+
// `wss.handleUpgrade`.
|
|
436
|
+
const result = await adapter.matchAndAuthorize(request);
|
|
437
|
+
if (!result.ok) {
|
|
438
|
+
// Unmatched route or auth rejection — destroy the raw
|
|
439
|
+
// socket; there is no Response channel.
|
|
440
|
+
destroy();
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
444
|
+
// `ws` sockets do not carry `data` natively (Bun sets it via
|
|
445
|
+
// `server.upgrade`), so attach it for the handlers to find
|
|
446
|
+
// the matched route (and any resolved user).
|
|
447
|
+
ws.data = result.data;
|
|
448
|
+
ws.on('message', (...args) => {
|
|
449
|
+
void adapter.handleMessage(ws,
|
|
450
|
+
// `ws`'s `'message'` event signature is
|
|
451
|
+
// `(data: Buffer, isBinary: boolean)`.
|
|
452
|
+
normalizeWsMessage(args[0], args[1]));
|
|
453
|
+
});
|
|
454
|
+
ws.on('close', (...args) => {
|
|
455
|
+
void adapter.handleClose(ws, args[0] ?? 1005, args[1] ?? '');
|
|
456
|
+
});
|
|
457
|
+
void adapter.handleOpen(ws);
|
|
458
|
+
});
|
|
459
|
+
},
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Get route from WebSocket data
|
|
464
|
+
*/
|
|
465
|
+
getRouteFromWs(ws) {
|
|
466
|
+
return this.getMatch(ws)?.route ?? null;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* The route + params matched at upgrade, cached per socket so a handler
|
|
470
|
+
* replacing `ws.data` cannot orphan the connection from its route.
|
|
471
|
+
*/
|
|
472
|
+
getMatch(ws) {
|
|
473
|
+
let match = this.wsMatches.get(ws);
|
|
474
|
+
if (!match) {
|
|
475
|
+
match = ws?.data?.[WS_ROUTE];
|
|
476
|
+
// Hand-wired sockets (custom bridges, tests) may still carry the
|
|
477
|
+
// `data.route` shape.
|
|
478
|
+
const legacy = ws?.data?.route;
|
|
479
|
+
if (!match && legacy?.handlers) {
|
|
480
|
+
match = {
|
|
481
|
+
route: legacy,
|
|
482
|
+
params: legacy.params ?? {},
|
|
483
|
+
wildcardParams: [],
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
if (match)
|
|
487
|
+
this.wsMatches.set(ws, match);
|
|
488
|
+
}
|
|
489
|
+
return match;
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Creates (or reuses) the BurgerWS context for a connection: one per
|
|
493
|
+
* connection, so `ws.data` mutations in one handler persist into the next.
|
|
494
|
+
*/
|
|
495
|
+
createBurgerWS(ws) {
|
|
496
|
+
let burgerWs = this.wsContexts.get(ws);
|
|
497
|
+
if (!burgerWs) {
|
|
498
|
+
const match = this.getMatch(ws);
|
|
499
|
+
burgerWs = new BurgerWSContext(ws, this.providers, match?.params ?? {}, match?.url, match?.wildcardParams ?? []);
|
|
500
|
+
this.wsContexts.set(ws, burgerWs);
|
|
501
|
+
}
|
|
502
|
+
return burgerWs;
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Runs the upgrade request through the same pre-handler chain HTTP uses —
|
|
506
|
+
* onRequest → transform → beforeRoute (Framework → Plugin → Global) —
|
|
507
|
+
* then enforces `config.auth.required` / `roles`. Always runs: auth
|
|
508
|
+
* check must never depend on a plugin being registered. `env` /
|
|
509
|
+
* `executionCtx` are bound onto the context so hooks can read bindings.
|
|
510
|
+
*/
|
|
511
|
+
async runAuthHooks(request, routeConfig, env, executionCtx) {
|
|
512
|
+
// One temporary BurgerContext for the upgrade request. Needed even
|
|
513
|
+
// with no hooks, because `auth.required` / `roles` are enforced here.
|
|
514
|
+
const ctx = BurgerContext.create(request, {}, undefined, this.providers, routeConfig, env, executionCtx, this.ipHolder);
|
|
515
|
+
// Mappers registered by onRequest / beforeRoute still wrap rejections
|
|
516
|
+
// (e.g. a cors hook adds headers to the 401).
|
|
517
|
+
const mappers = [];
|
|
518
|
+
const reject = async (response) => ({
|
|
519
|
+
response: await this.applyMappers(response, mappers),
|
|
520
|
+
});
|
|
521
|
+
try {
|
|
522
|
+
// 1. onRequest — same ordered array the HTTP path runs.
|
|
523
|
+
for (const hook of this.onRequestHooks) {
|
|
524
|
+
const result = await hook(ctx);
|
|
525
|
+
if (result instanceof Response)
|
|
526
|
+
return reject(result);
|
|
527
|
+
if (typeof result === 'function')
|
|
528
|
+
mappers.push(result);
|
|
529
|
+
}
|
|
530
|
+
// 2. transform — plugin factories first, app-level hooks override.
|
|
531
|
+
if (this.pluginTransform) {
|
|
532
|
+
await applyTransform(ctx, this.pluginTransform);
|
|
533
|
+
}
|
|
534
|
+
if (this.globalTransform) {
|
|
535
|
+
await applyTransform(ctx, this.globalTransform);
|
|
536
|
+
}
|
|
537
|
+
// 3. beforeRoute — Framework → Plugin → Global.
|
|
538
|
+
for (const hook of this.frameworkBeforeRoute) {
|
|
539
|
+
const result = await hook(ctx);
|
|
540
|
+
if (result instanceof Response)
|
|
541
|
+
return reject(result);
|
|
542
|
+
if (typeof result === 'function')
|
|
543
|
+
mappers.push(result);
|
|
544
|
+
}
|
|
545
|
+
for (const hook of this.pluginBeforeRoute ?? []) {
|
|
546
|
+
const result = await hook(ctx);
|
|
547
|
+
if (result instanceof Response)
|
|
548
|
+
return reject(result);
|
|
549
|
+
}
|
|
550
|
+
for (const hook of this.globalBeforeRoute) {
|
|
551
|
+
const result = await hook(ctx);
|
|
552
|
+
if (result instanceof Response)
|
|
553
|
+
return reject(result);
|
|
554
|
+
if (typeof result === 'function')
|
|
555
|
+
mappers.push(result);
|
|
556
|
+
}
|
|
557
|
+
// Extract user from context (set by transform hooks)
|
|
558
|
+
const user = ctx.user;
|
|
559
|
+
const authConfig = routeConfig?.auth !== undefined &&
|
|
560
|
+
typeof routeConfig.auth === 'object'
|
|
561
|
+
? routeConfig.auth
|
|
562
|
+
: undefined;
|
|
563
|
+
// Auth is enforced regardless of whether any hook ran.
|
|
564
|
+
if (authConfig?.required && !user) {
|
|
565
|
+
return reject(renderHTTPError(new HTTPError(401, 'Authentication required'), this.debug));
|
|
566
|
+
}
|
|
567
|
+
// Role-scoped routes reject with 403 unless the user holds a role.
|
|
568
|
+
if (authConfig?.roles &&
|
|
569
|
+
authConfig.roles.length > 0 &&
|
|
570
|
+
!hasAnyRole(user, authConfig.roles)) {
|
|
571
|
+
return reject(renderHTTPError(new HTTPError(403, 'Insufficient permissions'), this.debug));
|
|
572
|
+
}
|
|
573
|
+
return { user };
|
|
574
|
+
}
|
|
575
|
+
catch (error) {
|
|
576
|
+
return reject(this.renderAuthError(error));
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* Renders a throw from the upgrade auth chain. Only framework
|
|
581
|
+
* `HTTPError`s keep their status; anything else is a server bug and
|
|
582
|
+
* renders a generic 500 (never a fake 401 echoing the thrown message).
|
|
583
|
+
*/
|
|
584
|
+
renderAuthError(error) {
|
|
585
|
+
if (this.debug) {
|
|
586
|
+
console.error('[WebSocket] Auth hook error:', error);
|
|
587
|
+
}
|
|
588
|
+
if (error instanceof HTTPError) {
|
|
589
|
+
return renderHTTPError(error, this.debug);
|
|
590
|
+
}
|
|
591
|
+
return renderHTTPError(new HTTPError(500, 'Internal Server Error', error instanceof Error ? { cause: error } : undefined), this.debug);
|
|
592
|
+
}
|
|
593
|
+
/** Applies collected mappers onion-style (last registered runs first). */
|
|
594
|
+
async applyMappers(response, mappers) {
|
|
595
|
+
let res = response;
|
|
596
|
+
for (let i = mappers.length - 1; i >= 0; i--) {
|
|
597
|
+
res = await mappers[i](res);
|
|
598
|
+
}
|
|
599
|
+
return res;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Checks whether an authenticated user holds at least one of the required
|
|
604
|
+
* roles. Supports three shapes: a plain role string, an array of roles, or
|
|
605
|
+
* an object with a `roles` array (e.g. JWT payloads).
|
|
606
|
+
*/
|
|
607
|
+
function hasAnyRole(user, required) {
|
|
608
|
+
if (user === null || user === undefined)
|
|
609
|
+
return false;
|
|
610
|
+
if (typeof user === 'string') {
|
|
611
|
+
return required.includes(user);
|
|
612
|
+
}
|
|
613
|
+
if (Array.isArray(user)) {
|
|
614
|
+
return user.some((role) => required.includes(role));
|
|
615
|
+
}
|
|
616
|
+
if (typeof user === 'object') {
|
|
617
|
+
const roles = user.roles;
|
|
618
|
+
if (Array.isArray(roles)) {
|
|
619
|
+
return roles.some((role) => required.includes(role));
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return false;
|
|
623
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compiles scanned WebSocket routes into executable form.
|
|
3
|
+
*/
|
|
4
|
+
import type { WebSocketHooks, WebSocketConfig, CompiledWebSocketRoute } from './types.js';
|
|
5
|
+
import type { ScannedWebSocketRoute } from './scanner.js';
|
|
6
|
+
/**
|
|
7
|
+
* WebSocket route compiler.
|
|
8
|
+
*/
|
|
9
|
+
export declare class WebSocketCompiler {
|
|
10
|
+
private globalHooks?;
|
|
11
|
+
private globalConfig;
|
|
12
|
+
/**
|
|
13
|
+
* Set global hooks (from src/hooks.ts or similar)
|
|
14
|
+
*/
|
|
15
|
+
setGlobalHooks(hooks: WebSocketHooks): void;
|
|
16
|
+
/**
|
|
17
|
+
* Set global config (from burger options)
|
|
18
|
+
*/
|
|
19
|
+
setGlobalConfig(config: WebSocketConfig): void;
|
|
20
|
+
/**
|
|
21
|
+
* Compile a scanned WebSocket route
|
|
22
|
+
*/
|
|
23
|
+
compile(scanned: ScannedWebSocketRoute): Promise<CompiledWebSocketRoute>;
|
|
24
|
+
/**
|
|
25
|
+
* Compile multiple scanned routes
|
|
26
|
+
*/
|
|
27
|
+
compileAll(scanned: ScannedWebSocketRoute[]): Promise<CompiledWebSocketRoute[]>;
|
|
28
|
+
/**
|
|
29
|
+
* Merge global and route-specific hooks
|
|
30
|
+
*/
|
|
31
|
+
private mergeHooks;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Merges app-level and route WS hooks — global runs first, then route.
|
|
35
|
+
* Shared by file-based, prebuilt (AOT) and programmatic routes.
|
|
36
|
+
*/
|
|
37
|
+
export declare function mergeWsHooks(global?: WebSocketHooks, route?: WebSocketHooks): WebSocketHooks | undefined;
|