burger-api 0.9.7 → 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +240 -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 +49 -0
- package/dist/src/errors/http-error.js +155 -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 +275 -50
- package/dist/src/index.js +974 -333
- 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 +867 -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 +214 -0
- package/dist/src/router/router.js +670 -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 +189 -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 +6 -7
- package/dist/src/utils/wildcard.js +38 -55
- 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 +85 -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 +230 -0
- package/dist/src/ws/adapter.js +660 -0
- package/dist/src/ws/compiler.d.ts +37 -0
- package/dist/src/ws/compiler.js +178 -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 +82 -0
- package/dist/src/ws/platform.js +122 -0
- package/dist/src/ws/router.d.ts +47 -0
- package/dist/src/ws/router.js +183 -0
- package/dist/src/ws/scanner.d.ts +97 -0
- package/dist/src/ws/scanner.js +253 -0
- package/dist/src/ws/types.d.ts +381 -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,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compiles scanned WebSocket routes into executable form.
|
|
3
|
+
*/
|
|
4
|
+
/** Connection-level options — Bun.serve-wide, not per-route (see compile). */
|
|
5
|
+
const WS_TRANSPORT_KEYS = [
|
|
6
|
+
'maxPayloadLength',
|
|
7
|
+
'idleTimeout',
|
|
8
|
+
'backpressureLimit',
|
|
9
|
+
'closeOnBackpressureLimit',
|
|
10
|
+
'compression',
|
|
11
|
+
];
|
|
12
|
+
/**
|
|
13
|
+
* WebSocket route compiler.
|
|
14
|
+
*/
|
|
15
|
+
export class WebSocketCompiler {
|
|
16
|
+
globalHooks;
|
|
17
|
+
globalConfig = {};
|
|
18
|
+
/**
|
|
19
|
+
* Set global hooks (from src/hooks.ts or similar)
|
|
20
|
+
*/
|
|
21
|
+
setGlobalHooks(hooks) {
|
|
22
|
+
this.globalHooks = hooks;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Set global config (from burger options)
|
|
26
|
+
*/
|
|
27
|
+
setGlobalConfig(config) {
|
|
28
|
+
this.globalConfig = config;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Compile a scanned WebSocket route
|
|
32
|
+
*/
|
|
33
|
+
async compile(scanned) {
|
|
34
|
+
// Import ws.ts module
|
|
35
|
+
const wsModule = await importConvention(scanned.wsFile, 'route module', scanned.path);
|
|
36
|
+
// Build handlers from module exports
|
|
37
|
+
const handlers = {
|
|
38
|
+
open: wsModule.open,
|
|
39
|
+
message: wsModule.message,
|
|
40
|
+
close: wsModule.close,
|
|
41
|
+
drain: wsModule.drain,
|
|
42
|
+
ping: wsModule.ping,
|
|
43
|
+
pong: wsModule.pong,
|
|
44
|
+
};
|
|
45
|
+
// Import hooks if present
|
|
46
|
+
let hooks;
|
|
47
|
+
if (scanned.hooksFile) {
|
|
48
|
+
const hooksModule = await importConvention(scanned.hooksFile, 'hooks module', scanned.path);
|
|
49
|
+
hooks = {
|
|
50
|
+
onOpen: hooksModule.onOpen,
|
|
51
|
+
onMessage: hooksModule.onMessage,
|
|
52
|
+
onClose: hooksModule.onClose,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
// Import config if present
|
|
56
|
+
let routeConfig = {};
|
|
57
|
+
if (scanned.configFile) {
|
|
58
|
+
const configModule = await importConvention(scanned.configFile, 'config module', scanned.path);
|
|
59
|
+
routeConfig =
|
|
60
|
+
configModule.default ??
|
|
61
|
+
{ ...configModule };
|
|
62
|
+
// Connection-level options are Bun.serve-wide; a per-route value
|
|
63
|
+
// cannot override them, so warn loud instead of ignoring it.
|
|
64
|
+
for (const key of WS_TRANSPORT_KEYS) {
|
|
65
|
+
if (routeConfig[key] !== undefined) {
|
|
66
|
+
console.warn(`[burger-api] WebSocket route "${scanned.path}": config.${key} ` +
|
|
67
|
+
'is connection-level and can only be set globally via ' +
|
|
68
|
+
'burger.wsConfig() — the per-route value is ignored.');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
// `auth` is merged deeply so a route-level `auth.roles` keeps a global
|
|
73
|
+
// `auth.required`; either side being `false` disables auth.
|
|
74
|
+
const globalAuth = this.globalConfig.auth;
|
|
75
|
+
const routeAuth = routeConfig.auth;
|
|
76
|
+
const mergedConfig = {
|
|
77
|
+
...this.globalConfig,
|
|
78
|
+
...routeConfig,
|
|
79
|
+
};
|
|
80
|
+
if (globalAuth !== undefined || routeAuth !== undefined) {
|
|
81
|
+
mergedConfig.auth =
|
|
82
|
+
globalAuth === false || routeAuth === false
|
|
83
|
+
? false
|
|
84
|
+
: {
|
|
85
|
+
...(globalAuth === true
|
|
86
|
+
? { required: true }
|
|
87
|
+
: typeof globalAuth === 'object'
|
|
88
|
+
? globalAuth
|
|
89
|
+
: {}),
|
|
90
|
+
...(routeAuth === true
|
|
91
|
+
? { required: true }
|
|
92
|
+
: typeof routeAuth === 'object'
|
|
93
|
+
? routeAuth
|
|
94
|
+
: {}),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
// Merge global and route-specific hooks
|
|
98
|
+
const mergedHooks = this.mergeHooks(this.globalHooks, hooks);
|
|
99
|
+
return {
|
|
100
|
+
path: scanned.path,
|
|
101
|
+
params: scanned.params,
|
|
102
|
+
handlers,
|
|
103
|
+
hooks: mergedHooks,
|
|
104
|
+
config: mergedConfig,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Compile multiple scanned routes
|
|
109
|
+
*/
|
|
110
|
+
async compileAll(scanned) {
|
|
111
|
+
const compiled = [];
|
|
112
|
+
for (const route of scanned) {
|
|
113
|
+
try {
|
|
114
|
+
const compiledRoute = await this.compile(route);
|
|
115
|
+
compiled.push(compiledRoute);
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
119
|
+
throw new Error(`[WebSocket] Failed to compile route "${route.path}": ${detail}`, { cause: error });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return compiled;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Merge global and route-specific hooks
|
|
126
|
+
*/
|
|
127
|
+
mergeHooks(global, route) {
|
|
128
|
+
return mergeWsHooks(global, route);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Imports a convention module, naming both the route and file on failure so
|
|
133
|
+
* a broken module fails loud at startup instead of disappearing.
|
|
134
|
+
*/
|
|
135
|
+
async function importConvention(file, kind, routePath) {
|
|
136
|
+
try {
|
|
137
|
+
return (await import(file));
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
141
|
+
throw new Error(`[WebSocket] Failed to load ${kind} for route "${routePath}" from "${file}": ${detail}`, { cause: error });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Merges app-level and route WS hooks — global runs first, then route.
|
|
146
|
+
* Shared by file-based, prebuilt (AOT) and programmatic routes.
|
|
147
|
+
*/
|
|
148
|
+
export function mergeWsHooks(global, route) {
|
|
149
|
+
if (!global?.onOpen && !global?.onMessage && !global?.onClose) {
|
|
150
|
+
return route;
|
|
151
|
+
}
|
|
152
|
+
const merged = {};
|
|
153
|
+
if (global?.onOpen || route?.onOpen) {
|
|
154
|
+
merged.onOpen = async (ws) => {
|
|
155
|
+
if (global?.onOpen)
|
|
156
|
+
await global.onOpen(ws);
|
|
157
|
+
if (route?.onOpen)
|
|
158
|
+
await route.onOpen(ws);
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
if (global?.onMessage || route?.onMessage) {
|
|
162
|
+
merged.onMessage = async (ws, message) => {
|
|
163
|
+
if (global?.onMessage)
|
|
164
|
+
await global.onMessage(ws, message);
|
|
165
|
+
if (route?.onMessage)
|
|
166
|
+
await route.onMessage(ws, message);
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
if (global?.onClose || route?.onClose) {
|
|
170
|
+
merged.onClose = async (ws, code, reason) => {
|
|
171
|
+
if (global?.onClose)
|
|
172
|
+
await global.onClose(ws, code, reason);
|
|
173
|
+
if (route?.onClose)
|
|
174
|
+
await route.onClose(ws, code, reason);
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
return merged;
|
|
178
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebSocket module for BurgerAPI
|
|
3
|
+
*/
|
|
4
|
+
export type { WebSocketData, WebSocketConfig, WebSocketRouteDefinition, WebSocketHandlers, WebSocketHooks, CompiledWebSocketRoute, BurgerWS, WebSocketModule, WebSocketHooksModule, WebSocketConfigModule, } from './types.js';
|
|
5
|
+
export { WebSocketReadyState, WebSocketCloseCode, BurgerWSContext, } from './types.js';
|
|
6
|
+
export { WebSocketScanner } from './scanner.js';
|
|
7
|
+
export type { ScannedWebSocketRoute, WebSocketScanResult } from './scanner.js';
|
|
8
|
+
export { WebSocketCompiler } from './compiler.js';
|
|
9
|
+
export { WebSocketRouter } from './router.js';
|
|
10
|
+
export { WebSocketAdapter } from './adapter.js';
|
|
11
|
+
export type { WebSocketAdapterOptions } from './adapter.js';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebSocket module for BurgerAPI
|
|
3
|
+
*/
|
|
4
|
+
export { WebSocketReadyState, WebSocketCloseCode, BurgerWSContext, } from './types.js';
|
|
5
|
+
export { WebSocketScanner } from './scanner.js';
|
|
6
|
+
export { WebSocketCompiler } from './compiler.js';
|
|
7
|
+
export { WebSocketRouter } from './router.js';
|
|
8
|
+
export { WebSocketAdapter } from './adapter.js';
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebSocket platform seam. Each runtime has its own upgrade primitive (Bun's
|
|
3
|
+
* `server.upgrade`, Cloudflare's `WebSocketPair`, Deno's `upgradeWebSocket`,
|
|
4
|
+
* Node's `'upgrade'` event); {@link detectWsPlatform} and
|
|
5
|
+
* {@link acceptWsUpgrade} isolate those differences.
|
|
6
|
+
*
|
|
7
|
+
* Core stays free of Bun/platform imports: platform objects are reached
|
|
8
|
+
* structurally through `globalThis`.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Result of an upgrade attempt:
|
|
12
|
+
* - `{ handled: false }` — not an upgrade; run the normal HTTP pipeline.
|
|
13
|
+
* - `{ handled: true, response }` — the request was consumed. `response` is
|
|
14
|
+
* `undefined` when the runtime took over the socket directly (Bun);
|
|
15
|
+
* callers must NOT fall through to HTTP.
|
|
16
|
+
*/
|
|
17
|
+
export type WsUpgradeOutcome = {
|
|
18
|
+
handled: false;
|
|
19
|
+
} | {
|
|
20
|
+
handled: true;
|
|
21
|
+
response?: Response;
|
|
22
|
+
};
|
|
23
|
+
/** Shared event sink the platforms push socket events into. */
|
|
24
|
+
export interface WsEventSink {
|
|
25
|
+
onOpen(raw: unknown): void | Promise<void>;
|
|
26
|
+
onMessage(raw: unknown, message: string | Buffer): void | Promise<void>;
|
|
27
|
+
onClose(raw: unknown, code: number, reason: string): void | Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
export type WsPlatformName = 'bun' | 'cloudflare' | 'deno' | 'node';
|
|
30
|
+
/**
|
|
31
|
+
* Minimal shape of a framing-library socket on Node (`ws` package).
|
|
32
|
+
*
|
|
33
|
+
* `listener` is `(...args: any[]) => void` on purpose: `ws` declares concrete
|
|
34
|
+
* parameter types, which a rest-`never[]` listener would reject.
|
|
35
|
+
*/
|
|
36
|
+
export interface NodeWsLike {
|
|
37
|
+
on(event: 'message' | 'close' | 'error', listener: (...args: any[]) => void): void;
|
|
38
|
+
}
|
|
39
|
+
/** Minimal shape of a framing-library `WebSocketServer` in no-server mode. */
|
|
40
|
+
export interface NodeWebSocketServerLike {
|
|
41
|
+
handleUpgrade(req: unknown, socket: unknown, head: unknown, cb: (ws: NodeWsLike) => void): void;
|
|
42
|
+
}
|
|
43
|
+
export interface NodeWsBridgeOptions {
|
|
44
|
+
WebSocketServer: new (opts: {
|
|
45
|
+
noServer: true;
|
|
46
|
+
maxPayload?: number;
|
|
47
|
+
}) => NodeWebSocketServerLike;
|
|
48
|
+
}
|
|
49
|
+
export interface NodeWsBridge {
|
|
50
|
+
handleUpgrade(req: unknown, socket: unknown, head: unknown): Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Detects the WebSocket-capable runtime: an explicit Bun `server` handle wins,
|
|
54
|
+
* otherwise well-known globals are probed.
|
|
55
|
+
*/
|
|
56
|
+
export declare function detectWsPlatform(server?: unknown): WsPlatformName;
|
|
57
|
+
/**
|
|
58
|
+
* Performs the platform handoff for a matched + authorized upgrade request.
|
|
59
|
+
*
|
|
60
|
+
* @param platform detected runtime
|
|
61
|
+
* @param request the original upgrade Request
|
|
62
|
+
* @param server Bun serve handle (`platform === 'bun'` requires it)
|
|
63
|
+
* @param data per-connection payload attached to the socket (route/params/user)
|
|
64
|
+
* @param events shared event sink wired for push-style runtimes
|
|
65
|
+
* @returns the protocol Response where the platform produces one; `undefined`
|
|
66
|
+
* when the runtime took over the socket directly (Bun)
|
|
67
|
+
*/
|
|
68
|
+
export declare function acceptWsUpgrade(options: {
|
|
69
|
+
platform: WsPlatformName;
|
|
70
|
+
request: Request;
|
|
71
|
+
server?: unknown;
|
|
72
|
+
data: Record<string, unknown>;
|
|
73
|
+
events: WsEventSink;
|
|
74
|
+
}): Response | undefined;
|
|
75
|
+
/**
|
|
76
|
+
* Normalizes a socket message to `string` (text) or `Buffer` (binary).
|
|
77
|
+
*
|
|
78
|
+
* `isBinary` matters for `ws`-package callers: its `'message'` event always
|
|
79
|
+
* hands a Node `Buffer` plus a separate `isBinary` flag, so text frames are
|
|
80
|
+
* decoded as UTF-8. Cloudflare/Deno deliver text as `string` already.
|
|
81
|
+
*/
|
|
82
|
+
export declare function normalizeWsMessage(data: unknown, isBinary?: boolean): string | Buffer;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebSocket platform seam. Each runtime has its own upgrade primitive (Bun's
|
|
3
|
+
* `server.upgrade`, Cloudflare's `WebSocketPair`, Deno's `upgradeWebSocket`,
|
|
4
|
+
* Node's `'upgrade'` event); {@link detectWsPlatform} and
|
|
5
|
+
* {@link acceptWsUpgrade} isolate those differences.
|
|
6
|
+
*
|
|
7
|
+
* Core stays free of Bun/platform imports: platform objects are reached
|
|
8
|
+
* structurally through `globalThis`.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Detects the WebSocket-capable runtime: an explicit Bun `server` handle wins,
|
|
12
|
+
* otherwise well-known globals are probed.
|
|
13
|
+
*/
|
|
14
|
+
export function detectWsPlatform(server) {
|
|
15
|
+
if (server &&
|
|
16
|
+
typeof server.upgrade === 'function') {
|
|
17
|
+
return 'bun';
|
|
18
|
+
}
|
|
19
|
+
const g = globalThis;
|
|
20
|
+
if (typeof g.WebSocketPair !== 'undefined')
|
|
21
|
+
return 'cloudflare';
|
|
22
|
+
const deno = g.Deno;
|
|
23
|
+
if (deno && typeof deno.upgradeWebSocket === 'function')
|
|
24
|
+
return 'deno';
|
|
25
|
+
return 'node';
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Performs the platform handoff for a matched + authorized upgrade request.
|
|
29
|
+
*
|
|
30
|
+
* @param platform detected runtime
|
|
31
|
+
* @param request the original upgrade Request
|
|
32
|
+
* @param server Bun serve handle (`platform === 'bun'` requires it)
|
|
33
|
+
* @param data per-connection payload attached to the socket (route/params/user)
|
|
34
|
+
* @param events shared event sink wired for push-style runtimes
|
|
35
|
+
* @returns the protocol Response where the platform produces one; `undefined`
|
|
36
|
+
* when the runtime took over the socket directly (Bun)
|
|
37
|
+
*/
|
|
38
|
+
export function acceptWsUpgrade(options) {
|
|
39
|
+
const { platform, request, server, data, events } = options;
|
|
40
|
+
if (platform === 'bun') {
|
|
41
|
+
const upgrade = server;
|
|
42
|
+
if (typeof upgrade?.upgrade !== 'function') {
|
|
43
|
+
return new Response('WebSocket upgrade failed', { status: 500 });
|
|
44
|
+
}
|
|
45
|
+
// Bun refuses malformed handshakes (e.g. no Sec-WebSocket-Key):
|
|
46
|
+
// a client error, not a server failure.
|
|
47
|
+
if (!upgrade.upgrade(request, { data })) {
|
|
48
|
+
return new Response('Bad Request: invalid WebSocket upgrade request', { status: 400 });
|
|
49
|
+
}
|
|
50
|
+
// Socket handed off — the runtime owns the connection from here.
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
if (platform === 'cloudflare') {
|
|
54
|
+
const g = globalThis;
|
|
55
|
+
const pair = new g.WebSocketPair();
|
|
56
|
+
const serverSide = pair[0];
|
|
57
|
+
const fireOpen = wirePushListeners(serverSide, data, events);
|
|
58
|
+
serverSide.accept();
|
|
59
|
+
// workerd never fires 'open' on the server side after accept(), so
|
|
60
|
+
// deliver it here. The guard keeps runtimes that do emit it to one.
|
|
61
|
+
fireOpen();
|
|
62
|
+
// `webSocket` is the standard Workers/Deno response member; the
|
|
63
|
+
// base TS lib's ResponseInit does not model it yet.
|
|
64
|
+
return new Response(null, {
|
|
65
|
+
status: 101,
|
|
66
|
+
webSocket: pair[1],
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
if (platform === 'deno') {
|
|
70
|
+
const deno = globalThis.Deno;
|
|
71
|
+
const { response, socket } = deno.upgradeWebSocket(request);
|
|
72
|
+
wirePushListeners(socket, data, events);
|
|
73
|
+
return response;
|
|
74
|
+
}
|
|
75
|
+
// Node cannot complete a WebSocket handshake inside a fetch handler —
|
|
76
|
+
// it requires the `'upgrade'` event on node:http plus a framing library.
|
|
77
|
+
throw new Error('[burger-api] WebSocket upgrades are not supported through the ' +
|
|
78
|
+
'fetch entry on Node. Use burger.createNodeWsBridge(...) with a ' +
|
|
79
|
+
"WebSocketServer (e.g. the 'ws' package) wired to node:http's " +
|
|
80
|
+
"'upgrade' event.");
|
|
81
|
+
}
|
|
82
|
+
function wirePushListeners(socket, data, events) {
|
|
83
|
+
// Push-style sockets (Workers / Deno) need `data` attached explicitly,
|
|
84
|
+
// or the adapter cannot find the matched route (open/message never fire).
|
|
85
|
+
socket.data = data;
|
|
86
|
+
let openFired = false;
|
|
87
|
+
const fireOpen = () => {
|
|
88
|
+
if (openFired)
|
|
89
|
+
return;
|
|
90
|
+
openFired = true;
|
|
91
|
+
void events.onOpen(socket);
|
|
92
|
+
};
|
|
93
|
+
socket.addEventListener('open', fireOpen);
|
|
94
|
+
socket.addEventListener('message', (event) => {
|
|
95
|
+
void events.onMessage(socket, normalizeWsMessage(event.data));
|
|
96
|
+
});
|
|
97
|
+
socket.addEventListener('close', (event) => {
|
|
98
|
+
void events.onClose(socket, event.code ?? 1005, event.reason ?? '');
|
|
99
|
+
});
|
|
100
|
+
return fireOpen;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Normalizes a socket message to `string` (text) or `Buffer` (binary).
|
|
104
|
+
*
|
|
105
|
+
* `isBinary` matters for `ws`-package callers: its `'message'` event always
|
|
106
|
+
* hands a Node `Buffer` plus a separate `isBinary` flag, so text frames are
|
|
107
|
+
* decoded as UTF-8. Cloudflare/Deno deliver text as `string` already.
|
|
108
|
+
*/
|
|
109
|
+
export function normalizeWsMessage(data, isBinary) {
|
|
110
|
+
if (typeof data === 'string')
|
|
111
|
+
return data;
|
|
112
|
+
if (data instanceof ArrayBuffer) {
|
|
113
|
+
return isBinary === false
|
|
114
|
+
? Buffer.from(data).toString('utf-8')
|
|
115
|
+
: Buffer.from(data);
|
|
116
|
+
}
|
|
117
|
+
if (ArrayBuffer.isView(data)) {
|
|
118
|
+
const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
119
|
+
return isBinary === false ? buf.toString('utf-8') : buf;
|
|
120
|
+
}
|
|
121
|
+
return String(data ?? '');
|
|
122
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Matches WebSocket paths to compiled handlers.
|
|
3
|
+
*/
|
|
4
|
+
import type { CompiledWebSocketRoute } from './types.js';
|
|
5
|
+
/**
|
|
6
|
+
* WebSocket router: matches incoming paths to handlers.
|
|
7
|
+
*/
|
|
8
|
+
export declare class WebSocketRouter {
|
|
9
|
+
private routes;
|
|
10
|
+
private staticRoutes;
|
|
11
|
+
private dynamicRoutes;
|
|
12
|
+
/**
|
|
13
|
+
* Add a compiled route to the router
|
|
14
|
+
*/
|
|
15
|
+
addRoute(route: CompiledWebSocketRoute): void;
|
|
16
|
+
/**
|
|
17
|
+
* Add multiple compiled routes
|
|
18
|
+
*/
|
|
19
|
+
addRoutes(routes: CompiledWebSocketRoute[]): void;
|
|
20
|
+
/**
|
|
21
|
+
* Match a WebSocket path to a route. Static beats param beats wildcard;
|
|
22
|
+
* among param routes the most specific (leftmost static segment) wins.
|
|
23
|
+
*/
|
|
24
|
+
match(path: string): {
|
|
25
|
+
route: CompiledWebSocketRoute;
|
|
26
|
+
params: Record<string, string>;
|
|
27
|
+
wildcardParams: string[];
|
|
28
|
+
} | null;
|
|
29
|
+
/**
|
|
30
|
+
* Get all registered routes
|
|
31
|
+
*/
|
|
32
|
+
getRoutes(): CompiledWebSocketRoute[];
|
|
33
|
+
/**
|
|
34
|
+
* Get route count
|
|
35
|
+
*/
|
|
36
|
+
getRouteCount(): number;
|
|
37
|
+
/**
|
|
38
|
+
* Match path parameters (e.g., /chat/:room)
|
|
39
|
+
*/
|
|
40
|
+
private matchParams;
|
|
41
|
+
/**
|
|
42
|
+
* Match wildcard path (e.g., /files/*). Keeps `params['*']` as the raw
|
|
43
|
+
* remainder and adds the decoded per-segment `wildcardParams` array that
|
|
44
|
+
* mirrors HTTP `ctx.wildcardParams`.
|
|
45
|
+
*/
|
|
46
|
+
private matchWildcard;
|
|
47
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Matches WebSocket paths to compiled handlers.
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* WebSocket router: matches incoming paths to handlers.
|
|
6
|
+
*/
|
|
7
|
+
export class WebSocketRouter {
|
|
8
|
+
routes = [];
|
|
9
|
+
staticRoutes = new Map();
|
|
10
|
+
dynamicRoutes = [];
|
|
11
|
+
/**
|
|
12
|
+
* Add a compiled route to the router
|
|
13
|
+
*/
|
|
14
|
+
addRoute(route) {
|
|
15
|
+
this.routes.push(route);
|
|
16
|
+
// Dynamic routes are kept sorted by specificity (static segment >
|
|
17
|
+
// param > wildcard at the first differing segment), matching HTTP
|
|
18
|
+
// dispatch. The sort is stable, so equal patterns keep insertion
|
|
19
|
+
// order.
|
|
20
|
+
if (route.path.includes('*') || route.path.includes(':')) {
|
|
21
|
+
this.dynamicRoutes.push(route);
|
|
22
|
+
this.dynamicRoutes.sort(compareRouteSpecificity);
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
this.staticRoutes.set(route.path, route);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Add multiple compiled routes
|
|
30
|
+
*/
|
|
31
|
+
addRoutes(routes) {
|
|
32
|
+
for (const route of routes) {
|
|
33
|
+
this.addRoute(route);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Match a WebSocket path to a route. Static beats param beats wildcard;
|
|
38
|
+
* among param routes the most specific (leftmost static segment) wins.
|
|
39
|
+
*/
|
|
40
|
+
match(path) {
|
|
41
|
+
// A trailing slash is ignored, like HTTP routing (`/chat/` ≡ `/chat`).
|
|
42
|
+
if (path.length > 1 && path.endsWith('/')) {
|
|
43
|
+
path = path.replace(/\/+$/, '') || '/';
|
|
44
|
+
}
|
|
45
|
+
// Try static routes first (fastest)
|
|
46
|
+
const staticRoute = this.staticRoutes.get(path);
|
|
47
|
+
if (staticRoute) {
|
|
48
|
+
return { route: staticRoute, params: {}, wildcardParams: [] };
|
|
49
|
+
}
|
|
50
|
+
// Try dynamic routes in specificity order (params and wildcards mixed).
|
|
51
|
+
for (const route of this.dynamicRoutes) {
|
|
52
|
+
if (route.path.includes('*')) {
|
|
53
|
+
const result = this.matchWildcard(route.path, path);
|
|
54
|
+
if (result !== null) {
|
|
55
|
+
return {
|
|
56
|
+
route,
|
|
57
|
+
params: result.params,
|
|
58
|
+
wildcardParams: result.wildcardParams,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
const params = this.matchParams(route.path, path);
|
|
64
|
+
if (params !== null) {
|
|
65
|
+
return { route, params, wildcardParams: [] };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Get all registered routes
|
|
73
|
+
*/
|
|
74
|
+
getRoutes() {
|
|
75
|
+
return this.routes;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Get route count
|
|
79
|
+
*/
|
|
80
|
+
getRouteCount() {
|
|
81
|
+
return this.routes.length;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Match path parameters (e.g., /chat/:room)
|
|
85
|
+
*/
|
|
86
|
+
matchParams(pattern, path) {
|
|
87
|
+
const patternParts = pattern.split('/');
|
|
88
|
+
const pathParts = path.split('/');
|
|
89
|
+
if (patternParts.length !== pathParts.length) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
const params = {};
|
|
93
|
+
for (let i = 0; i < patternParts.length; i++) {
|
|
94
|
+
const patternPart = patternParts[i];
|
|
95
|
+
const pathPart = pathParts[i];
|
|
96
|
+
if (patternPart.startsWith(':')) {
|
|
97
|
+
// Parameter: never matches an empty segment; URL-decoded.
|
|
98
|
+
if (pathPart === '')
|
|
99
|
+
return null;
|
|
100
|
+
const paramName = patternPart.slice(1);
|
|
101
|
+
try {
|
|
102
|
+
params[paramName] = decodeURIComponent(pathPart);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
params[paramName] = pathPart;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
else if (patternPart !== pathPart) {
|
|
109
|
+
// Static mismatch
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return params;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Match wildcard path (e.g., /files/*). Keeps `params['*']` as the raw
|
|
117
|
+
* remainder and adds the decoded per-segment `wildcardParams` array that
|
|
118
|
+
* mirrors HTTP `ctx.wildcardParams`.
|
|
119
|
+
*/
|
|
120
|
+
matchWildcard(pattern, path) {
|
|
121
|
+
const patternParts = pattern.split('/');
|
|
122
|
+
const wildcardIndex = patternParts.indexOf('*');
|
|
123
|
+
if (wildcardIndex === -1)
|
|
124
|
+
return null;
|
|
125
|
+
const pathParts = path.split('/');
|
|
126
|
+
if (pathParts.length < wildcardIndex)
|
|
127
|
+
return null;
|
|
128
|
+
// Match the fixed prefix segment by segment, exactly like params.
|
|
129
|
+
const params = {};
|
|
130
|
+
for (let i = 0; i < wildcardIndex; i++) {
|
|
131
|
+
const patternPart = patternParts[i];
|
|
132
|
+
const pathPart = pathParts[i];
|
|
133
|
+
if (patternPart.startsWith(':')) {
|
|
134
|
+
if (pathPart === '')
|
|
135
|
+
return null;
|
|
136
|
+
params[patternPart.slice(1)] = decodeSegment(pathPart);
|
|
137
|
+
}
|
|
138
|
+
else if (patternPart !== pathPart) {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
// The wildcard keeps the raw remainder plus decoded per-segment values.
|
|
143
|
+
const wildcardValue = pathParts.slice(wildcardIndex).join('/');
|
|
144
|
+
const wildcardParams = wildcardValue === ''
|
|
145
|
+
? []
|
|
146
|
+
: wildcardValue.split('/').map(decodeSegment);
|
|
147
|
+
params['*'] = wildcardValue;
|
|
148
|
+
return { params, wildcardParams };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Decodes a path segment, falling back to the raw value on bad escapes. */
|
|
152
|
+
function decodeSegment(segment) {
|
|
153
|
+
if (segment === '' || segment.indexOf('%') === -1)
|
|
154
|
+
return segment;
|
|
155
|
+
try {
|
|
156
|
+
return decodeURIComponent(segment);
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return segment;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** Specificity rank: static 0, param 1, wildcard 2, missing 3. */
|
|
163
|
+
function segmentRank(segment) {
|
|
164
|
+
if (segment === undefined)
|
|
165
|
+
return 3;
|
|
166
|
+
if (segment === '*')
|
|
167
|
+
return 2;
|
|
168
|
+
if (segment.startsWith(':'))
|
|
169
|
+
return 1;
|
|
170
|
+
return 0;
|
|
171
|
+
}
|
|
172
|
+
/** Compares two param patterns; lower rank at the first difference wins. */
|
|
173
|
+
function compareRouteSpecificity(a, b) {
|
|
174
|
+
const aParts = a.path.split('/');
|
|
175
|
+
const bParts = b.path.split('/');
|
|
176
|
+
const length = Math.max(aParts.length, bParts.length);
|
|
177
|
+
for (let i = 0; i < length; i++) {
|
|
178
|
+
const diff = segmentRank(aParts[i]) - segmentRank(bParts[i]);
|
|
179
|
+
if (diff !== 0)
|
|
180
|
+
return diff;
|
|
181
|
+
}
|
|
182
|
+
return 0;
|
|
183
|
+
}
|