@velajs/cloudflare 1.30.0 → 1.31.0
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/CHANGELOG.md +112 -0
- package/README.md +260 -74
- package/dist/bindings.js +77 -0
- package/dist/bindings.js.map +1 -0
- package/dist/cloudflare-application.js +7 -34
- package/dist/cloudflare-application.js.map +1 -1
- package/dist/cloudflare-factory-eGiet0mg.d.ts +288 -0
- package/dist/cloudflare-factory.js +84 -28
- package/dist/cloudflare-factory.js.map +1 -1
- package/dist/diagnostics.js +18 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/durable-objects.d.ts +6 -2
- package/dist/index.d.ts +160 -455
- package/dist/index.js +7 -13
- package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
- package/dist/platform.js +22 -0
- package/dist/platform.js.map +1 -0
- package/dist/queue/cloudflare-queues.js +7 -7
- package/dist/queue/cloudflare-queues.js.map +1 -1
- package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
- package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
- package/dist/root-module-C23bUwt_.d.ts +11 -0
- package/dist/schedule-diagnostics.js +8 -15
- package/dist/schedule-diagnostics.js.map +1 -1
- package/dist/services/kv-cache.store.js +33 -7
- package/dist/services/kv-cache.store.js.map +1 -1
- package/dist/storage/r2-storage.js +30 -0
- package/dist/storage/r2-storage.js.map +1 -0
- package/dist/storage.d.ts +28 -0
- package/dist/storage.js +2 -0
- package/dist/testing.d.ts +96 -0
- package/dist/testing.js +111 -0
- package/dist/testing.js.map +1 -0
- package/dist/websocket/binding-gateways.js +33 -0
- package/dist/websocket/binding-gateways.js.map +1 -0
- package/dist/websocket/cf-room-registry.js +3 -1
- package/dist/websocket/cf-room-registry.js.map +1 -1
- package/dist/websocket/do-bootstrap.js +36 -15
- package/dist/websocket/do-bootstrap.js.map +1 -1
- package/dist/websocket/do-live.js +49 -90
- package/dist/websocket/do-live.js.map +1 -1
- package/dist/websocket/do-state.js.map +1 -1
- package/dist/websocket/live-driver.js +149 -0
- package/dist/websocket/live-driver.js.map +1 -0
- package/dist/websocket/room-id.js +11 -1
- package/dist/websocket/room-id.js.map +1 -1
- package/dist/websocket/websocket.durable-object.js +14 -10
- package/dist/websocket/websocket.durable-object.js.map +1 -1
- package/dist/websocket/worker-transport.js +80 -0
- package/dist/websocket/worker-transport.js.map +1 -0
- package/package.json +23 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
- package/dist/storage/r2-storage.driver.js +0 -67
- package/dist/storage/r2-storage.driver.js.map +0 -1
- package/dist/storage/storage-key-claim.js +0 -74
- package/dist/storage/storage-key-claim.js.map +0 -1
- package/dist/storage/storage-manager.service.js +0 -38
- package/dist/storage/storage-manager.service.js.map +0 -1
- package/dist/storage/storage.controller.js +0 -64
- package/dist/storage/storage.controller.js.map +0 -1
- package/dist/storage/storage.module.js +0 -25
- package/dist/storage/storage.module.js.map +0 -1
- package/dist/storage/storage.service.js +0 -64
- package/dist/storage/storage.service.js.map +0 -1
- package/dist/storage/storage.tokens.js +0 -7
- package/dist/storage/storage.tokens.js.map +0 -1
- package/dist/websocket/broadcast.js +0 -32
- package/dist/websocket/broadcast.js.map +0 -1
- package/dist/websocket/cloudflare-websocket.module.js +0 -25
- package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
- package/dist/websocket/websocket-routing.js +0 -133
- package/dist/websocket/websocket-routing.js.map +0 -1
- package/dist/websocket/ws-server-holder.js +0 -38
- package/dist/websocket/ws-server-holder.js.map +0 -1
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { WsServerHolder } from "./ws-server-holder.js";
|
|
2
|
-
import { defineProvider } from "@velajs/vela";
|
|
3
|
-
import { WS_SERVER, WsDispatcher } from "@velajs/vela/websocket";
|
|
4
|
-
//#region src/websocket/cloudflare-websocket.module.ts
|
|
5
|
-
/**
|
|
6
|
-
* Cloudflare counterpart to the core `WebSocketModule.forRoot()`. Import this in
|
|
7
|
-
* your `AppModule` instead: it provides the gateway dispatcher plus a late-bound
|
|
8
|
-
* `WS_SERVER` (`WsServerHolder`) that the WebSocket Durable Object wires to a
|
|
9
|
-
* ctx-backed server per instance. `useClass` ensures a fresh holder per DI
|
|
10
|
-
* container so colocated DO instances never share a server.
|
|
11
|
-
*/
|
|
12
|
-
var CloudflareWebSocketModule = class CloudflareWebSocketModule {
|
|
13
|
-
static forRoot() {
|
|
14
|
-
const providers = [defineProvider(WS_SERVER, { useClass: WsServerHolder }), WsDispatcher];
|
|
15
|
-
return {
|
|
16
|
-
module: CloudflareWebSocketModule,
|
|
17
|
-
providers,
|
|
18
|
-
exports: [WS_SERVER, WsDispatcher]
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
};
|
|
22
|
-
//#endregion
|
|
23
|
-
export { CloudflareWebSocketModule };
|
|
24
|
-
|
|
25
|
-
//# sourceMappingURL=cloudflare-websocket.module.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-websocket.module.js","names":[],"sources":["../../src/websocket/cloudflare-websocket.module.ts"],"sourcesContent":["import { defineProvider, type DynamicModule } from '@velajs/vela';\nimport { WsDispatcher, WS_SERVER } from '@velajs/vela/websocket';\nimport { WsServerHolder } from './ws-server-holder';\n\n/**\n * Cloudflare counterpart to the core `WebSocketModule.forRoot()`. Import this in\n * your `AppModule` instead: it provides the gateway dispatcher plus a late-bound\n * `WS_SERVER` (`WsServerHolder`) that the WebSocket Durable Object wires to a\n * ctx-backed server per instance. `useClass` ensures a fresh holder per DI\n * container so colocated DO instances never share a server.\n */\nexport class CloudflareWebSocketModule {\n static forRoot(): DynamicModule {\n const providers = [defineProvider(WS_SERVER, { useClass: WsServerHolder }), WsDispatcher];\n\n return {\n module: CloudflareWebSocketModule,\n providers,\n exports: [WS_SERVER, WsDispatcher],\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,4BAAb,MAAa,0BAA0B;CACrC,OAAO,UAAyB;EAC9B,MAAM,YAAY,CAAC,eAAe,WAAW,EAAE,UAAU,eAAe,CAAC,GAAG,YAAY;EAExF,OAAO;GACL,QAAQ;GACR;GACA,SAAS,CAAC,WAAW,YAAY;EACnC;CACF;AACF"}
|
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
import { durableObjectRoomName } from "./room-id.js";
|
|
2
|
-
import { getMetadata, getTrustedRequestIdentity } from "@velajs/vela/module-kit";
|
|
3
|
-
import { WS_GATEWAY_METADATA, createWebSocketUpgradeGate, resolveGatewayRoomId, resolveGatewayRoomParam, resolveMaxFrameBytes } from "@velajs/vela/websocket";
|
|
4
|
-
//#region src/websocket/websocket-routing.ts
|
|
5
|
-
const MAX_IDENTITY_FIELD_BYTES = 2048;
|
|
6
|
-
const encoder = new TextEncoder();
|
|
7
|
-
function isIdentityField(value) {
|
|
8
|
-
return typeof value === "string" && value.length > 0 && !value.includes("\r") && !value.includes("\n") && encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES;
|
|
9
|
-
}
|
|
10
|
-
/** `null` means an identity was present but violated the transport contract. */
|
|
11
|
-
function accessIdentity(c) {
|
|
12
|
-
const value = getTrustedRequestIdentity(c.req.raw);
|
|
13
|
-
if (!value) return void 0;
|
|
14
|
-
const { principal, tenantId, expiresAtMs } = value;
|
|
15
|
-
if (!isIdentityField(principal.issuer) || !isIdentityField(principal.subject) || !isIdentityField(tenantId) || typeof expiresAtMs !== "number" || !Number.isSafeInteger(expiresAtMs) || expiresAtMs <= 0) return null;
|
|
16
|
-
return {
|
|
17
|
-
principal,
|
|
18
|
-
tenantId,
|
|
19
|
-
expiresAtMs
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
/** `null` means two independently verified identities disagree. */
|
|
23
|
-
function combineIdentities(requestIdentity, upgradeIdentity) {
|
|
24
|
-
if (!requestIdentity && !upgradeIdentity) return void 0;
|
|
25
|
-
if (!requestIdentity) return upgradeIdentity;
|
|
26
|
-
if (!upgradeIdentity) return requestIdentity;
|
|
27
|
-
if (requestIdentity.principal.issuer !== upgradeIdentity.principal.issuer || requestIdentity.principal.subject !== upgradeIdentity.principal.subject || requestIdentity.principal.principalType !== upgradeIdentity.principal.principalType || requestIdentity.tenantId !== upgradeIdentity.tenantId) return null;
|
|
28
|
-
return {
|
|
29
|
-
principal: { ...upgradeIdentity.principal },
|
|
30
|
-
tenantId: upgradeIdentity.tenantId,
|
|
31
|
-
expiresAtMs: Math.min(requestIdentity.expiresAtMs, upgradeIdentity.expiresAtMs)
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
/** An instance's constructor is the class token its module registered. */
|
|
35
|
-
function isClass(value) {
|
|
36
|
-
return typeof value === "function";
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Read `@WebSocketGateway({ path, binding })` off a resolved instance (CF-hosted
|
|
40
|
-
* gateways only). The application container names the module that declares the
|
|
41
|
-
* gateway when exactly one module registers it.
|
|
42
|
-
*/
|
|
43
|
-
function collectWsGatewayRoutes(instance, container) {
|
|
44
|
-
const options = getMetadata(WS_GATEWAY_METADATA, instance.constructor);
|
|
45
|
-
if (!options?.path || !options?.binding) return [];
|
|
46
|
-
resolveGatewayRoomParam(options);
|
|
47
|
-
resolveMaxFrameBytes(options);
|
|
48
|
-
const gateway = instance.constructor;
|
|
49
|
-
const owners = isClass(gateway) ? container.getOwnerModuleIds(gateway) : [];
|
|
50
|
-
return [{
|
|
51
|
-
path: options.path,
|
|
52
|
-
binding: options.binding,
|
|
53
|
-
options: { ...options },
|
|
54
|
-
...owners.length === 1 ? { moduleId: owners[0] } : {}
|
|
55
|
-
}];
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Registers the upgrade routes on the Worker's Hono app. Each route validates
|
|
59
|
-
* the `Upgrade` header, authenticates through the gateway's authenticator
|
|
60
|
-
* (resolved once from `container`, the application's DI container), resolves
|
|
61
|
-
* the room's Durable Object, and forwards the raw request — injecting
|
|
62
|
-
* spoof-safe `x-vela-*` headers the DO reads. The DO returns the `101` with the
|
|
63
|
-
* client socket.
|
|
64
|
-
*/
|
|
65
|
-
function registerWebSocketRoutes(hono, routes, container) {
|
|
66
|
-
for (const route of routes) {
|
|
67
|
-
const authenticate = createWebSocketUpgradeGate(container, route);
|
|
68
|
-
hono.get(route.path, async (c) => {
|
|
69
|
-
if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return c.text("Expected WebSocket upgrade", 426);
|
|
70
|
-
const headers = new Headers(c.req.raw.headers);
|
|
71
|
-
headers.delete("x-vela-room");
|
|
72
|
-
headers.delete("x-vela-path");
|
|
73
|
-
headers.delete("x-vela-user");
|
|
74
|
-
headers.delete("x-vela-expires-at");
|
|
75
|
-
headers.delete("x-vela-expires-at-ms");
|
|
76
|
-
headers.delete("x-vela-issuer");
|
|
77
|
-
headers.delete("x-vela-subject");
|
|
78
|
-
headers.delete("x-vela-principal-type");
|
|
79
|
-
headers.delete("x-vela-tenant");
|
|
80
|
-
const sanitizedRequest = new Request(c.req.raw, { headers });
|
|
81
|
-
let roomId;
|
|
82
|
-
try {
|
|
83
|
-
roomId = resolveGatewayRoomId(route.options, (name) => c.req.param(name));
|
|
84
|
-
} catch {
|
|
85
|
-
return c.text("Invalid WebSocket room", 400);
|
|
86
|
-
}
|
|
87
|
-
const upgrade = await authenticate(sanitizedRequest, roomId);
|
|
88
|
-
if (upgrade === false) return c.text("WebSocket upgrade forbidden", 403);
|
|
89
|
-
const requestIdentity = accessIdentity(c);
|
|
90
|
-
if (requestIdentity === null) return c.text("Invalid WebSocket identity", 403);
|
|
91
|
-
const identity = combineIdentities(requestIdentity, upgrade.identity);
|
|
92
|
-
if (identity === null) return c.text("Conflicting WebSocket identities", 403);
|
|
93
|
-
if (identity && identity.expiresAtMs <= Date.now()) return c.text("WebSocket identity expired", 403);
|
|
94
|
-
const forwardHeaders = new Headers(upgrade.request.headers);
|
|
95
|
-
forwardHeaders.set("x-vela-room", roomId);
|
|
96
|
-
forwardHeaders.set("x-vela-path", route.path);
|
|
97
|
-
if (identity) {
|
|
98
|
-
forwardHeaders.set("x-vela-user", identity.principal.subject);
|
|
99
|
-
forwardHeaders.set("x-vela-issuer", identity.principal.issuer);
|
|
100
|
-
forwardHeaders.set("x-vela-subject", identity.principal.subject);
|
|
101
|
-
forwardHeaders.set("x-vela-principal-type", identity.principal.principalType);
|
|
102
|
-
forwardHeaders.set("x-vela-tenant", identity.tenantId);
|
|
103
|
-
forwardHeaders.set("x-vela-expires-at-ms", String(identity.expiresAtMs));
|
|
104
|
-
}
|
|
105
|
-
return forwardToRoom(c.env, route.binding, route.path, roomId, new Request(upgrade.request, { headers: forwardHeaders }));
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Gateway metadata contains a runtime binding name, so the native type is
|
|
111
|
-
* erased. Validate only the operations consumed here and their observable
|
|
112
|
-
* results; never assert that an arbitrary value implements a native namespace.
|
|
113
|
-
*/
|
|
114
|
-
async function forwardToRoom(env, binding, path, room, request) {
|
|
115
|
-
if (typeof env !== "object" || env === null) throw new Error("Worker environment is missing");
|
|
116
|
-
const namespace = Reflect.get(env, binding);
|
|
117
|
-
if (typeof namespace !== "object" || namespace === null) return new Response(`Durable Object binding '${binding}' is not configured`, { status: 500 });
|
|
118
|
-
const idFromName = Reflect.get(namespace, "idFromName");
|
|
119
|
-
const get = Reflect.get(namespace, "get");
|
|
120
|
-
if (typeof idFromName !== "function" || typeof get !== "function") throw new Error("Invalid Durable Object namespace");
|
|
121
|
-
const id = Reflect.apply(idFromName, namespace, [durableObjectRoomName(path, room)]);
|
|
122
|
-
const stub = Reflect.apply(get, namespace, [id]);
|
|
123
|
-
if (typeof stub !== "object" || stub === null) throw new Error("Invalid Durable Object stub");
|
|
124
|
-
const fetch = Reflect.get(stub, "fetch");
|
|
125
|
-
if (typeof fetch !== "function") throw new Error("Durable Object stub has no fetch operation");
|
|
126
|
-
const response = await Reflect.apply(fetch, stub, [request]);
|
|
127
|
-
if (!(response instanceof Response)) throw new Error("Durable Object returned an invalid response");
|
|
128
|
-
return response;
|
|
129
|
-
}
|
|
130
|
-
//#endregion
|
|
131
|
-
export { collectWsGatewayRoutes, registerWebSocketRoutes };
|
|
132
|
-
|
|
133
|
-
//# sourceMappingURL=websocket-routing.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"websocket-routing.js","names":[],"sources":["../../src/websocket/websocket-routing.ts"],"sourcesContent":["import type { Type, VelaContext as Context, VelaHono as Hono } from '@velajs/vela';\nimport type { Container } from '@velajs/vela/module-kit';\nimport { getMetadata, getTrustedRequestIdentity } from '@velajs/vela/module-kit';\nimport {\n createWebSocketUpgradeGate,\n resolveGatewayRoomId,\n resolveGatewayRoomParam,\n resolveMaxFrameBytes,\n WS_GATEWAY_METADATA,\n type WebSocketGatewayOptions,\n type WebSocketUpgradeIdentity,\n} from '@velajs/vela/websocket';\nimport { durableObjectRoomName } from './room-id';\n\nexport interface WsGatewayRoute {\n path: string;\n binding: string;\n options: WebSocketGatewayOptions;\n /** Container module that declares the gateway; its authenticator resolves from here. */\n moduleId?: string;\n}\n\nconst MAX_IDENTITY_FIELD_BYTES = 2048;\nconst encoder = new TextEncoder();\n\ntype PrincipalType = 'user' | 'service';\n\ninterface ForwardedIdentity extends WebSocketUpgradeIdentity {\n principal: {\n issuer: string;\n subject: string;\n principalType: PrincipalType;\n };\n tenantId: string;\n expiresAtMs: number;\n}\n\nfunction isIdentityField(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length > 0 &&\n !value.includes('\\r') &&\n !value.includes('\\n') &&\n encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES\n );\n}\n\n/** `null` means an identity was present but violated the transport contract. */\nfunction accessIdentity(c: Context): ForwardedIdentity | null | undefined {\n const value = getTrustedRequestIdentity(c.req.raw);\n if (!value) return undefined;\n const { principal, tenantId, expiresAtMs } = value;\n if (\n !isIdentityField(principal.issuer) ||\n !isIdentityField(principal.subject) ||\n !isIdentityField(tenantId) ||\n typeof expiresAtMs !== 'number' ||\n !Number.isSafeInteger(expiresAtMs) ||\n expiresAtMs <= 0\n )\n return null;\n return { principal, tenantId, expiresAtMs };\n}\n\n/** `null` means two independently verified identities disagree. */\nfunction combineIdentities(\n requestIdentity: ForwardedIdentity | undefined,\n upgradeIdentity: WebSocketUpgradeIdentity | undefined,\n): ForwardedIdentity | null | undefined {\n if (!requestIdentity && !upgradeIdentity) return undefined;\n if (!requestIdentity) return upgradeIdentity;\n if (!upgradeIdentity) return requestIdentity;\n if (\n requestIdentity.principal.issuer !== upgradeIdentity.principal.issuer ||\n requestIdentity.principal.subject !== upgradeIdentity.principal.subject ||\n requestIdentity.principal.principalType !== upgradeIdentity.principal.principalType ||\n requestIdentity.tenantId !== upgradeIdentity.tenantId\n ) {\n return null;\n }\n return {\n principal: { ...upgradeIdentity.principal },\n tenantId: upgradeIdentity.tenantId,\n expiresAtMs: Math.min(requestIdentity.expiresAtMs, upgradeIdentity.expiresAtMs),\n };\n}\n\n/** An instance's constructor is the class token its module registered. */\nfunction isClass(value: unknown): value is Type {\n return typeof value === 'function';\n}\n\n/**\n * Read `@WebSocketGateway({ path, binding })` off a resolved instance (CF-hosted\n * gateways only). The application container names the module that declares the\n * gateway when exactly one module registers it.\n */\nexport function collectWsGatewayRoutes(instance: object, container: Container): WsGatewayRoute[] {\n // Decorator metadata is the framework's explicit reflection boundary.\n const options = getMetadata<WebSocketGatewayOptions>(WS_GATEWAY_METADATA, instance.constructor);\n if (!options?.path || !options?.binding) return [];\n resolveGatewayRoomParam(options);\n resolveMaxFrameBytes(options);\n const gateway: unknown = instance.constructor;\n const owners = isClass(gateway) ? container.getOwnerModuleIds(gateway) : [];\n return [\n {\n path: options.path,\n binding: options.binding,\n options: { ...options },\n ...(owners.length === 1 ? { moduleId: owners[0] } : {}),\n },\n ];\n}\n\n/**\n * Registers the upgrade routes on the Worker's Hono app. Each route validates\n * the `Upgrade` header, authenticates through the gateway's authenticator\n * (resolved once from `container`, the application's DI container), resolves\n * the room's Durable Object, and forwards the raw request — injecting\n * spoof-safe `x-vela-*` headers the DO reads. The DO returns the `101` with the\n * client socket.\n */\nexport function registerWebSocketRoutes(\n hono: Hono,\n routes: WsGatewayRoute[],\n container: Container,\n): void {\n for (const route of routes) {\n const authenticate = createWebSocketUpgradeGate(container, route);\n hono.get(route.path, async (c: Context) => {\n if (c.req.header('upgrade')?.toLowerCase() !== 'websocket') {\n return c.text('Expected WebSocket upgrade', 426);\n }\n\n // Internal transport headers are never application credentials. Remove\n // client-supplied values before even the pre-allocation authorization\n // hook sees the request, then populate trusted values below.\n const headers = new Headers(c.req.raw.headers);\n headers.delete('x-vela-room');\n headers.delete('x-vela-path');\n headers.delete('x-vela-user');\n headers.delete('x-vela-expires-at');\n headers.delete('x-vela-expires-at-ms');\n headers.delete('x-vela-issuer');\n headers.delete('x-vela-subject');\n headers.delete('x-vela-principal-type');\n headers.delete('x-vela-tenant');\n const sanitizedRequest = new Request(c.req.raw, { headers });\n\n let roomId: string;\n try {\n roomId = resolveGatewayRoomId(route.options, (name) => c.req.param(name));\n } catch {\n return c.text('Invalid WebSocket room', 400);\n }\n\n // Origin, application authorization, and ticket/cookie authentication\n // all complete before the gateway Durable Object id is resolved.\n const upgrade = await authenticate(sanitizedRequest, roomId);\n if (upgrade === false) return c.text('WebSocket upgrade forbidden', 403);\n\n const requestIdentity = accessIdentity(c);\n if (requestIdentity === null) return c.text('Invalid WebSocket identity', 403);\n const identity = combineIdentities(requestIdentity, upgrade.identity);\n if (identity === null) return c.text('Conflicting WebSocket identities', 403);\n if (identity && identity.expiresAtMs <= Date.now()) {\n return c.text('WebSocket identity expired', 403);\n }\n\n // Populate the ticket-free forwarding request with trusted server values.\n const forwardHeaders = new Headers(upgrade.request.headers);\n forwardHeaders.set('x-vela-room', roomId);\n forwardHeaders.set('x-vela-path', route.path);\n if (identity) {\n forwardHeaders.set('x-vela-user', identity.principal.subject);\n forwardHeaders.set('x-vela-issuer', identity.principal.issuer);\n forwardHeaders.set('x-vela-subject', identity.principal.subject);\n forwardHeaders.set('x-vela-principal-type', identity.principal.principalType);\n forwardHeaders.set('x-vela-tenant', identity.tenantId);\n forwardHeaders.set('x-vela-expires-at-ms', String(identity.expiresAtMs));\n }\n\n return forwardToRoom(\n c.env,\n route.binding,\n route.path,\n roomId,\n new Request(upgrade.request, { headers: forwardHeaders }),\n );\n });\n }\n}\n\n/**\n * Gateway metadata contains a runtime binding name, so the native type is\n * erased. Validate only the operations consumed here and their observable\n * results; never assert that an arbitrary value implements a native namespace.\n */\nasync function forwardToRoom(\n env: unknown,\n binding: string,\n path: string,\n room: string,\n request: Request,\n): Promise<Response> {\n if (typeof env !== 'object' || env === null) throw new Error('Worker environment is missing');\n const namespace: unknown = Reflect.get(env, binding);\n if (typeof namespace !== 'object' || namespace === null) {\n return new Response(`Durable Object binding '${binding}' is not configured`, { status: 500 });\n }\n const idFromName: unknown = Reflect.get(namespace, 'idFromName');\n const get: unknown = Reflect.get(namespace, 'get');\n if (typeof idFromName !== 'function' || typeof get !== 'function') {\n throw new Error('Invalid Durable Object namespace');\n }\n const id: unknown = Reflect.apply(idFromName, namespace, [durableObjectRoomName(path, room)]);\n const stub: unknown = Reflect.apply(get, namespace, [id]);\n if (typeof stub !== 'object' || stub === null) throw new Error('Invalid Durable Object stub');\n const fetch: unknown = Reflect.get(stub, 'fetch');\n if (typeof fetch !== 'function') throw new Error('Durable Object stub has no fetch operation');\n const response: unknown = await Reflect.apply(fetch, stub, [request]);\n if (!(response instanceof Response))\n throw new Error('Durable Object returned an invalid response');\n return response;\n}\n"],"mappings":";;;;AAsBA,MAAM,2BAA2B;AACjC,MAAM,UAAU,IAAI,YAAY;AAchC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MAAM,YAAY,WAAW,CAAC,sBAAsB,MAAM,IAAI,CAAC,CAAC;CAC5F,MAAM,OAAgB,QAAQ,MAAM,KAAK,WAAW,CAAC,EAAE,CAAC;CACxD,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM,MAAM,IAAI,MAAM,6BAA6B;CAC5F,MAAM,QAAiB,QAAQ,IAAI,MAAM,OAAO;CAChD,IAAI,OAAO,UAAU,YAAY,MAAM,IAAI,MAAM,4CAA4C;CAC7F,MAAM,WAAoB,MAAM,QAAQ,MAAM,OAAO,MAAM,CAAC,OAAO,CAAC;CACpE,IAAI,EAAE,oBAAoB,WACxB,MAAM,IAAI,MAAM,6CAA6C;CAC/D,OAAO;AACT"}
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import __decorate from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
|
|
2
|
-
import { Injectable } from "@velajs/vela";
|
|
3
|
-
import { resolveMaxFrameBytes } from "@velajs/vela/websocket";
|
|
4
|
-
//#region src/websocket/ws-server-holder.ts
|
|
5
|
-
let WsServerHolder = class WsServerHolder {
|
|
6
|
-
target;
|
|
7
|
-
maxFrameBytes;
|
|
8
|
-
setTarget(server) {
|
|
9
|
-
this.target = server;
|
|
10
|
-
if (this.maxFrameBytes !== void 0) server.setOutboundFrameLimit?.(this.maxFrameBytes);
|
|
11
|
-
}
|
|
12
|
-
setOutboundFrameLimit(maxFrameBytes) {
|
|
13
|
-
const resolved = resolveMaxFrameBytes({ maxFrameBytes });
|
|
14
|
-
this.maxFrameBytes = this.maxFrameBytes === void 0 ? resolved : Math.max(this.maxFrameBytes, resolved);
|
|
15
|
-
this.target?.setOutboundFrameLimit?.(this.maxFrameBytes);
|
|
16
|
-
}
|
|
17
|
-
get resolved() {
|
|
18
|
-
if (!this.target) throw new Error("WebSocket server is only available inside a WebSocket Durable Object. To push from a Worker HTTP handler, use broadcastToRoom(namespace, gatewayPath, room, ...).");
|
|
19
|
-
return this.target;
|
|
20
|
-
}
|
|
21
|
-
emit(event, data) {
|
|
22
|
-
return this.resolved.emit(event, data);
|
|
23
|
-
}
|
|
24
|
-
to(room) {
|
|
25
|
-
return this.resolved.to(room);
|
|
26
|
-
}
|
|
27
|
-
in(room) {
|
|
28
|
-
return this.resolved.in(room);
|
|
29
|
-
}
|
|
30
|
-
except(room) {
|
|
31
|
-
return this.resolved.except(room);
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
WsServerHolder = __decorate([Injectable()], WsServerHolder);
|
|
35
|
-
//#endregion
|
|
36
|
-
export { WsServerHolder };
|
|
37
|
-
|
|
38
|
-
//# sourceMappingURL=ws-server-holder.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ws-server-holder.js","names":[],"sources":["../../src/websocket/ws-server-holder.ts"],"sourcesContent":["import { Injectable } from '@velajs/vela';\nimport { resolveMaxFrameBytes } from '@velajs/vela/websocket';\nimport type { BroadcastOperator, WsServer } from '@velajs/vela/websocket';\n\n/**\n * Late-bound `WsServer`. Provided as `WS_SERVER` (one per DI container, i.e. per\n * Durable Object instance), then pointed at the ctx-backed server once the DO\n * builds. Gateways inject it via `@WebSocketServer()`; it throws if used before\n * a runtime binds it (e.g. from the stateless Worker isolate).\n */\n@Injectable()\nexport class WsServerHolder implements WsServer {\n private target?: WsServer;\n private maxFrameBytes?: number;\n\n setTarget(server: WsServer): void {\n this.target = server;\n if (this.maxFrameBytes !== undefined) server.setOutboundFrameLimit?.(this.maxFrameBytes);\n }\n\n setOutboundFrameLimit(maxFrameBytes: number): void {\n const resolved = resolveMaxFrameBytes({ maxFrameBytes });\n this.maxFrameBytes =\n this.maxFrameBytes === undefined ? resolved : Math.max(this.maxFrameBytes, resolved);\n this.target?.setOutboundFrameLimit?.(this.maxFrameBytes);\n }\n\n private get resolved(): WsServer {\n if (!this.target) {\n throw new Error(\n 'WebSocket server is only available inside a WebSocket Durable Object. To ' +\n 'push from a Worker HTTP handler, use broadcastToRoom(namespace, gatewayPath, room, ...).',\n );\n }\n return this.target;\n }\n\n emit(event: string, data?: unknown): void | Promise<void> {\n return this.resolved.emit(event, data);\n }\n to(room: string): BroadcastOperator {\n return this.resolved.to(room);\n }\n in(room: string): BroadcastOperator {\n return this.resolved.in(room);\n }\n except(room: string): BroadcastOperator {\n return this.resolved.except(room);\n }\n}\n"],"mappings":";;;;AAWO,IAAM,iBAAN,MAAM,eAAmC;CAC9C;CACA;CAEA,UAAU,QAAwB;EAChC,KAAK,SAAS;EACd,IAAI,KAAK,kBAAkB,KAAA,GAAW,OAAO,wBAAwB,KAAK,aAAa;CACzF;CAEA,sBAAsB,eAA6B;EACjD,MAAM,WAAW,qBAAqB,EAAE,cAAc,CAAC;EACvD,KAAK,gBACH,KAAK,kBAAkB,KAAA,IAAY,WAAW,KAAK,IAAI,KAAK,eAAe,QAAQ;EACrF,KAAK,QAAQ,wBAAwB,KAAK,aAAa;CACzD;CAEA,IAAY,WAAqB;EAC/B,IAAI,CAAC,KAAK,QACR,MAAM,IAAI,MACR,mKAEF;EAEF,OAAO,KAAK;CACd;CAEA,KAAK,OAAe,MAAsC;EACxD,OAAO,KAAK,SAAS,KAAK,OAAO,IAAI;CACvC;CACA,GAAG,MAAiC;EAClC,OAAO,KAAK,SAAS,GAAG,IAAI;CAC9B;CACA,GAAG,MAAiC;EAClC,OAAO,KAAK,SAAS,GAAG,IAAI;CAC9B;CACA,OAAO,MAAiC;EACtC,OAAO,KAAK,SAAS,OAAO,IAAI;CAClC;AACF;AAvCC,iBAAA,WAAA,CAAA,WAAW,CAAA,GAAA,cAAA"}
|