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,156 @@
|
|
|
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 import(scanned.wsFile));
|
|
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 import(scanned.hooksFile));
|
|
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 import(scanned.configFile));
|
|
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
|
+
...(typeof globalAuth === 'object' ? globalAuth : {}),
|
|
86
|
+
...(typeof routeAuth === 'object' ? routeAuth : {}),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
// Merge global and route-specific hooks
|
|
90
|
+
const mergedHooks = this.mergeHooks(this.globalHooks, hooks);
|
|
91
|
+
return {
|
|
92
|
+
path: scanned.path,
|
|
93
|
+
params: scanned.params,
|
|
94
|
+
handlers,
|
|
95
|
+
hooks: mergedHooks,
|
|
96
|
+
config: mergedConfig,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Compile multiple scanned routes
|
|
101
|
+
*/
|
|
102
|
+
async compileAll(scanned) {
|
|
103
|
+
const compiled = [];
|
|
104
|
+
for (const route of scanned) {
|
|
105
|
+
try {
|
|
106
|
+
const compiledRoute = await this.compile(route);
|
|
107
|
+
compiled.push(compiledRoute);
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
console.error(`[WebSocket] Failed to compile route: ${route.path}`, error);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return compiled;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Merge global and route-specific hooks
|
|
117
|
+
*/
|
|
118
|
+
mergeHooks(global, route) {
|
|
119
|
+
return mergeWsHooks(global, route);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Merges app-level and route WS hooks — global runs first, then route.
|
|
124
|
+
* Shared by file-based, prebuilt (AOT) and programmatic routes.
|
|
125
|
+
*/
|
|
126
|
+
export function mergeWsHooks(global, route) {
|
|
127
|
+
if (!global?.onOpen && !global?.onMessage && !global?.onClose) {
|
|
128
|
+
return route;
|
|
129
|
+
}
|
|
130
|
+
const merged = {};
|
|
131
|
+
if (global?.onOpen || route?.onOpen) {
|
|
132
|
+
merged.onOpen = async (ws) => {
|
|
133
|
+
if (global?.onOpen)
|
|
134
|
+
await global.onOpen(ws);
|
|
135
|
+
if (route?.onOpen)
|
|
136
|
+
await route.onOpen(ws);
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
if (global?.onMessage || route?.onMessage) {
|
|
140
|
+
merged.onMessage = async (ws, message) => {
|
|
141
|
+
if (global?.onMessage)
|
|
142
|
+
await global.onMessage(ws, message);
|
|
143
|
+
if (route?.onMessage)
|
|
144
|
+
await route.onMessage(ws, message);
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
if (global?.onClose || route?.onClose) {
|
|
148
|
+
merged.onClose = async (ws, code, reason) => {
|
|
149
|
+
if (global?.onClose)
|
|
150
|
+
await global.onClose(ws, code, reason);
|
|
151
|
+
if (route?.onClose)
|
|
152
|
+
await route.onClose(ws, code, reason);
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
return merged;
|
|
156
|
+
}
|
|
@@ -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,81 @@
|
|
|
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', 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
|
+
}) => NodeWebSocketServerLike;
|
|
47
|
+
}
|
|
48
|
+
export interface NodeWsBridge {
|
|
49
|
+
handleUpgrade(req: unknown, socket: unknown, head: unknown): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Detects the WebSocket-capable runtime: an explicit Bun `server` handle wins,
|
|
53
|
+
* otherwise well-known globals are probed.
|
|
54
|
+
*/
|
|
55
|
+
export declare function detectWsPlatform(server?: unknown): WsPlatformName;
|
|
56
|
+
/**
|
|
57
|
+
* Performs the platform handoff for a matched + authorized upgrade request.
|
|
58
|
+
*
|
|
59
|
+
* @param platform detected runtime
|
|
60
|
+
* @param request the original upgrade Request
|
|
61
|
+
* @param server Bun serve handle (`platform === 'bun'` requires it)
|
|
62
|
+
* @param data per-connection payload attached to the socket (route/params/user)
|
|
63
|
+
* @param events shared event sink wired for push-style runtimes
|
|
64
|
+
* @returns the protocol Response where the platform produces one; `undefined`
|
|
65
|
+
* when the runtime took over the socket directly (Bun)
|
|
66
|
+
*/
|
|
67
|
+
export declare function acceptWsUpgrade(options: {
|
|
68
|
+
platform: WsPlatformName;
|
|
69
|
+
request: Request;
|
|
70
|
+
server?: unknown;
|
|
71
|
+
data: Record<string, unknown>;
|
|
72
|
+
events: WsEventSink;
|
|
73
|
+
}): Response | undefined;
|
|
74
|
+
/**
|
|
75
|
+
* Normalizes a socket message to `string` (text) or `Buffer` (binary).
|
|
76
|
+
*
|
|
77
|
+
* `isBinary` matters for `ws`-package callers: its `'message'` event always
|
|
78
|
+
* hands a Node `Buffer` plus a separate `isBinary` flag, so text frames are
|
|
79
|
+
* decoded as UTF-8. Cloudflare/Deno deliver text as `string` already.
|
|
80
|
+
*/
|
|
81
|
+
export declare function normalizeWsMessage(data: unknown, isBinary?: boolean): string | Buffer;
|
|
@@ -0,0 +1,113 @@
|
|
|
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
|
+
wirePushListeners(serverSide, data, events);
|
|
58
|
+
serverSide.accept();
|
|
59
|
+
// `webSocket` is the standard Workers/Deno response member; the
|
|
60
|
+
// base TS lib's ResponseInit does not model it yet.
|
|
61
|
+
return new Response(null, {
|
|
62
|
+
status: 101,
|
|
63
|
+
webSocket: pair[1],
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
if (platform === 'deno') {
|
|
67
|
+
const deno = globalThis.Deno;
|
|
68
|
+
const { response, socket } = deno.upgradeWebSocket(request);
|
|
69
|
+
wirePushListeners(socket, data, events);
|
|
70
|
+
return response;
|
|
71
|
+
}
|
|
72
|
+
// Node cannot complete a WebSocket handshake inside a fetch handler —
|
|
73
|
+
// it requires the `'upgrade'` event on node:http plus a framing library.
|
|
74
|
+
throw new Error('[burger-api] WebSocket upgrades are not supported through the ' +
|
|
75
|
+
'fetch entry on Node. Use burger.createNodeWsBridge(...) with a ' +
|
|
76
|
+
"WebSocketServer (e.g. the 'ws' package) wired to node:http's " +
|
|
77
|
+
"'upgrade' event.");
|
|
78
|
+
}
|
|
79
|
+
function wirePushListeners(socket, data, events) {
|
|
80
|
+
// Push-style sockets (Workers / Deno) need `data` attached explicitly,
|
|
81
|
+
// or the adapter cannot find the matched route (open/message never fire).
|
|
82
|
+
socket.data = data;
|
|
83
|
+
socket.addEventListener('open', () => {
|
|
84
|
+
void events.onOpen(socket);
|
|
85
|
+
});
|
|
86
|
+
socket.addEventListener('message', (event) => {
|
|
87
|
+
void events.onMessage(socket, normalizeWsMessage(event.data));
|
|
88
|
+
});
|
|
89
|
+
socket.addEventListener('close', (event) => {
|
|
90
|
+
void events.onClose(socket, event.code ?? 1005, event.reason ?? '');
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Normalizes a socket message to `string` (text) or `Buffer` (binary).
|
|
95
|
+
*
|
|
96
|
+
* `isBinary` matters for `ws`-package callers: its `'message'` event always
|
|
97
|
+
* hands a Node `Buffer` plus a separate `isBinary` flag, so text frames are
|
|
98
|
+
* decoded as UTF-8. Cloudflare/Deno deliver text as `string` already.
|
|
99
|
+
*/
|
|
100
|
+
export function normalizeWsMessage(data, isBinary) {
|
|
101
|
+
if (typeof data === 'string')
|
|
102
|
+
return data;
|
|
103
|
+
if (data instanceof ArrayBuffer) {
|
|
104
|
+
return isBinary === false
|
|
105
|
+
? Buffer.from(data).toString('utf-8')
|
|
106
|
+
: Buffer.from(data);
|
|
107
|
+
}
|
|
108
|
+
if (ArrayBuffer.isView(data)) {
|
|
109
|
+
const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
110
|
+
return isBinary === false ? buf.toString('utf-8') : buf;
|
|
111
|
+
}
|
|
112
|
+
return String(data ?? '');
|
|
113
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
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 paramRoutes;
|
|
12
|
+
private wildcardRoutes;
|
|
13
|
+
/**
|
|
14
|
+
* Add a compiled route to the router
|
|
15
|
+
*/
|
|
16
|
+
addRoute(route: CompiledWebSocketRoute): void;
|
|
17
|
+
/**
|
|
18
|
+
* Add multiple compiled routes
|
|
19
|
+
*/
|
|
20
|
+
addRoutes(routes: CompiledWebSocketRoute[]): void;
|
|
21
|
+
/**
|
|
22
|
+
* Match a WebSocket path to a route. Static beats param beats wildcard;
|
|
23
|
+
* among param routes the most specific (leftmost static segment) wins.
|
|
24
|
+
*/
|
|
25
|
+
match(path: string): {
|
|
26
|
+
route: CompiledWebSocketRoute;
|
|
27
|
+
params: Record<string, string>;
|
|
28
|
+
wildcardParams: string[];
|
|
29
|
+
} | null;
|
|
30
|
+
/**
|
|
31
|
+
* Get all registered routes
|
|
32
|
+
*/
|
|
33
|
+
getRoutes(): CompiledWebSocketRoute[];
|
|
34
|
+
/**
|
|
35
|
+
* Get route count
|
|
36
|
+
*/
|
|
37
|
+
getRouteCount(): number;
|
|
38
|
+
/**
|
|
39
|
+
* Match path parameters (e.g., /chat/:room)
|
|
40
|
+
*/
|
|
41
|
+
private matchParams;
|
|
42
|
+
/**
|
|
43
|
+
* Match wildcard path (e.g., /files/*). Keeps `params['*']` as the raw
|
|
44
|
+
* remainder and adds the decoded per-segment `wildcardParams` array that
|
|
45
|
+
* mirrors HTTP `ctx.wildcardParams`.
|
|
46
|
+
*/
|
|
47
|
+
private matchWildcard;
|
|
48
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
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
|
+
paramRoutes = [];
|
|
11
|
+
wildcardRoutes = [];
|
|
12
|
+
/**
|
|
13
|
+
* Add a compiled route to the router
|
|
14
|
+
*/
|
|
15
|
+
addRoute(route) {
|
|
16
|
+
this.routes.push(route);
|
|
17
|
+
// Categorize routes. Param and wildcard routes are kept sorted by
|
|
18
|
+
// specificity (static segment > param > wildcard at the first
|
|
19
|
+
// differing segment; longer wildcard prefix first), matching HTTP
|
|
20
|
+
// dispatch. The sort is stable, so equal patterns keep insertion order.
|
|
21
|
+
if (route.path.includes('*')) {
|
|
22
|
+
this.wildcardRoutes.push(route);
|
|
23
|
+
this.wildcardRoutes.sort(compareWildcardSpecificity);
|
|
24
|
+
}
|
|
25
|
+
else if (route.path.includes(':')) {
|
|
26
|
+
this.paramRoutes.push(route);
|
|
27
|
+
this.paramRoutes.sort(compareRouteSpecificity);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
this.staticRoutes.set(route.path, route);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Add multiple compiled routes
|
|
35
|
+
*/
|
|
36
|
+
addRoutes(routes) {
|
|
37
|
+
for (const route of routes) {
|
|
38
|
+
this.addRoute(route);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Match a WebSocket path to a route. Static beats param beats wildcard;
|
|
43
|
+
* among param routes the most specific (leftmost static segment) wins.
|
|
44
|
+
*/
|
|
45
|
+
match(path) {
|
|
46
|
+
// A trailing slash is ignored, like HTTP routing (`/chat/` ≡ `/chat`).
|
|
47
|
+
if (path.length > 1 && path.endsWith('/')) {
|
|
48
|
+
path = path.replace(/\/+$/, '') || '/';
|
|
49
|
+
}
|
|
50
|
+
// Try static routes first (fastest)
|
|
51
|
+
const staticRoute = this.staticRoutes.get(path);
|
|
52
|
+
if (staticRoute) {
|
|
53
|
+
return { route: staticRoute, params: {}, wildcardParams: [] };
|
|
54
|
+
}
|
|
55
|
+
// Try parameterized routes
|
|
56
|
+
for (const route of this.paramRoutes) {
|
|
57
|
+
const params = this.matchParams(route.path, path);
|
|
58
|
+
if (params !== null) {
|
|
59
|
+
return { route, params, wildcardParams: [] };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// Try wildcard routes
|
|
63
|
+
for (const route of this.wildcardRoutes) {
|
|
64
|
+
const result = this.matchWildcard(route.path, path);
|
|
65
|
+
if (result !== null) {
|
|
66
|
+
return { route, params: result.params, wildcardParams: result.wildcardParams };
|
|
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
|
+
// Remove trailing * for comparison
|
|
122
|
+
const basePattern = pattern.replace(/\*$/, '');
|
|
123
|
+
const basePath = path.slice(0, basePattern.length);
|
|
124
|
+
if (basePath !== basePattern) {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
// Extract wildcard value
|
|
128
|
+
const wildcardValue = path.slice(basePattern.length);
|
|
129
|
+
const wildcardParams = [];
|
|
130
|
+
if (wildcardValue !== '') {
|
|
131
|
+
for (const segment of wildcardValue.split('/')) {
|
|
132
|
+
wildcardParams.push(decodeSegment(segment));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { params: { '*': wildcardValue }, wildcardParams };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** Decodes a path segment, falling back to the raw value on bad escapes. */
|
|
139
|
+
function decodeSegment(segment) {
|
|
140
|
+
if (segment === '' || segment.indexOf('%') === -1)
|
|
141
|
+
return segment;
|
|
142
|
+
try {
|
|
143
|
+
return decodeURIComponent(segment);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return segment;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/** Specificity rank: static 0, param 1, wildcard 2, missing 3. */
|
|
150
|
+
function segmentRank(segment) {
|
|
151
|
+
if (segment === undefined)
|
|
152
|
+
return 3;
|
|
153
|
+
if (segment === '*')
|
|
154
|
+
return 2;
|
|
155
|
+
if (segment.startsWith(':'))
|
|
156
|
+
return 1;
|
|
157
|
+
return 0;
|
|
158
|
+
}
|
|
159
|
+
/** Compares two param patterns; lower rank at the first difference wins. */
|
|
160
|
+
function compareRouteSpecificity(a, b) {
|
|
161
|
+
const aParts = a.path.split('/');
|
|
162
|
+
const bParts = b.path.split('/');
|
|
163
|
+
const length = Math.max(aParts.length, bParts.length);
|
|
164
|
+
for (let i = 0; i < length; i++) {
|
|
165
|
+
const diff = segmentRank(aParts[i]) - segmentRank(bParts[i]);
|
|
166
|
+
if (diff !== 0)
|
|
167
|
+
return diff;
|
|
168
|
+
}
|
|
169
|
+
return 0;
|
|
170
|
+
}
|
|
171
|
+
/** Longer wildcard prefix is more specific. */
|
|
172
|
+
function compareWildcardSpecificity(a, b) {
|
|
173
|
+
return b.path.replace(/\*$/, '').length - a.path.replace(/\*$/, '').length;
|
|
174
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scans a directory tree for WebSocket convention files.
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* Scanned WebSocket route
|
|
6
|
+
*/
|
|
7
|
+
export interface ScannedWebSocketRoute {
|
|
8
|
+
/**
|
|
9
|
+
* Route path (e.g., "/chat", "/notifications/:room")
|
|
10
|
+
*/
|
|
11
|
+
path: string;
|
|
12
|
+
/**
|
|
13
|
+
* Absolute path to ws.ts / ws.js / ws.mjs file
|
|
14
|
+
*/
|
|
15
|
+
wsFile: string;
|
|
16
|
+
/**
|
|
17
|
+
* Absolute path to hooks file (if any)
|
|
18
|
+
*/
|
|
19
|
+
hooksFile?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Absolute path to config file (if any)
|
|
22
|
+
*/
|
|
23
|
+
configFile?: string;
|
|
24
|
+
/**
|
|
25
|
+
* Route parameters
|
|
26
|
+
*/
|
|
27
|
+
params?: Record<string, string>;
|
|
28
|
+
/**
|
|
29
|
+
* Whether this is a wildcard route
|
|
30
|
+
*/
|
|
31
|
+
isWildcard?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Whether this is a group directory (URL only, no inheritance)
|
|
34
|
+
*/
|
|
35
|
+
isGroup?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Group name (if isGroup)
|
|
38
|
+
*/
|
|
39
|
+
groupName?: string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* WebSocket scan result
|
|
43
|
+
*/
|
|
44
|
+
export interface WebSocketScanResult {
|
|
45
|
+
/**
|
|
46
|
+
* Scanned WebSocket routes
|
|
47
|
+
*/
|
|
48
|
+
routes: ScannedWebSocketRoute[];
|
|
49
|
+
/**
|
|
50
|
+
* Global hooks file path (if any)
|
|
51
|
+
*/
|
|
52
|
+
globalHooks?: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* WebSocket directory scanner
|
|
56
|
+
*/
|
|
57
|
+
export declare class WebSocketScanner {
|
|
58
|
+
private readonly wsDir;
|
|
59
|
+
private readonly prefix;
|
|
60
|
+
constructor(wsDir: string, prefix?: string);
|
|
61
|
+
/**
|
|
62
|
+
* Scans the WebSocket directory tree and returns scanned routes
|
|
63
|
+
*/
|
|
64
|
+
scan(): Promise<WebSocketScanResult>;
|
|
65
|
+
/**
|
|
66
|
+
* Recursively walks the directory, emitting a route per ws file found.
|
|
67
|
+
*/
|
|
68
|
+
private walk;
|
|
69
|
+
/**
|
|
70
|
+
* Builds the route path from the directory structure
|
|
71
|
+
*/
|
|
72
|
+
private buildRoutePath;
|
|
73
|
+
/**
|
|
74
|
+
* Extracts route parameters from the path
|
|
75
|
+
*/
|
|
76
|
+
private extractParams;
|
|
77
|
+
/**
|
|
78
|
+
* Checks if a directory name is a dynamic parameter folder
|
|
79
|
+
*/
|
|
80
|
+
private isDynamicDir;
|
|
81
|
+
/**
|
|
82
|
+
* Extracts the parameter name from a dynamic folder
|
|
83
|
+
*/
|
|
84
|
+
private extractParamName;
|
|
85
|
+
/**
|
|
86
|
+
* Checks if a directory name is a wildcard folder
|
|
87
|
+
*/
|
|
88
|
+
private isWildcardDir;
|
|
89
|
+
/**
|
|
90
|
+
* Checks if a directory name is a group folder
|
|
91
|
+
*/
|
|
92
|
+
private isGroupDir;
|
|
93
|
+
/**
|
|
94
|
+
* Extracts the group name from a group folder
|
|
95
|
+
*/
|
|
96
|
+
private extractGroupName;
|
|
97
|
+
}
|