dynamodb-reactive 0.2.4 → 0.4.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.
@@ -0,0 +1,95 @@
1
+ import { SubscribeRequest, SnapshotResponse, UnsubscribeRequest, JsonPatch } from './cluster.cjs';
2
+ import { HubSocket, HubPaths } from './hub.cjs';
3
+
4
+ /**
5
+ * Cloudflare Durable Object shell for the reactive hub. It is structural: it
6
+ * takes the Durable Object's `ctx` instead of extending `DurableObject`, so this
7
+ * entry imports nothing from `cloudflare:workers` and builds like every other
8
+ * entry. Your Durable Object class owns its name and migrations and delegates
9
+ * `fetch`, `webSocketMessage`, `webSocketClose` and `webSocketError` to it.
10
+ */
11
+ /** Set by the route handler on requests it forwards to the hub; never trusted from clients. */
12
+ declare const HUB_PRINCIPAL_HEADER = "x-reactive-principal";
13
+ /** A hibernatable Workers WebSocket, as far as the hub needs it. */
14
+ interface DurableObjectWebSocket extends HubSocket {
15
+ close(code?: number, reason?: string): void;
16
+ }
17
+ /** The parts of `DurableObjectState` the hub uses. */
18
+ interface DurableObjectStateLike {
19
+ acceptWebSocket(socket: DurableObjectWebSocket, tags?: string[]): void;
20
+ getWebSockets(tag?: string): DurableObjectWebSocket[];
21
+ setWebSocketAutoResponse?(pair?: unknown): void;
22
+ storage: {
23
+ get<T>(key: string): Promise<T | undefined>;
24
+ put<T>(key: string, value: T): Promise<void>;
25
+ };
26
+ }
27
+ /** Anything with a Durable Object stub's `fetch`. */
28
+ interface HubStub {
29
+ fetch(request: Request): Promise<Response>;
30
+ }
31
+ type WebSocketPairConstructor = new () => {
32
+ 0: DurableObjectWebSocket;
33
+ 1: DurableObjectWebSocket;
34
+ };
35
+ interface DurableObjectHubOptions {
36
+ paths: HubPaths;
37
+ /** Storage key for a path's version. Defaults to `version:<path>`. */
38
+ versionKey?: (path: string) => string;
39
+ maxAttachmentBytes?: number;
40
+ /**
41
+ * Answers the client's `ping` with `pong` without waking the Durable Object.
42
+ * Defaults to true.
43
+ */
44
+ autoPong?: boolean;
45
+ /** Workers' `WebSocketPair`; injectable for tests. */
46
+ WebSocketPair?: WebSocketPairConstructor;
47
+ /** Creates a connection id; injectable for tests. */
48
+ randomId?: () => string;
49
+ }
50
+ /** Wires the hub core to a Durable Object's hibernatable WebSockets and storage. */
51
+ declare function createDurableObjectHub(ctx: DurableObjectStateLike, options: DurableObjectHubOptions): {
52
+ hub: {
53
+ message(socket: HubSocket, raw: string): void;
54
+ subscribe(request: SubscribeRequest, principal: string): Promise<SnapshotResponse>;
55
+ unsubscribe(request: UnsubscribeRequest, principal: string): void;
56
+ notify(path: string): Promise<void>;
57
+ publish(path: string, patches: JsonPatch[]): Promise<void>;
58
+ };
59
+ /** The Durable Object's `fetch`: WebSocket upgrades and actions from `hubClient`. */
60
+ fetch(request: Request): Promise<Response>;
61
+ webSocketMessage(socket: DurableObjectWebSocket, message: string | ArrayBuffer): void;
62
+ webSocketClose(socket: DurableObjectWebSocket, code: number): void;
63
+ webSocketError(socket: DurableObjectWebSocket): void;
64
+ };
65
+ type DurableObjectHub = ReturnType<typeof createDurableObjectHub>;
66
+ /** Calls a hub Durable Object from the Worker. */
67
+ declare function hubClient(stub: HubStub): {
68
+ /** Forwards a reactive HTTP request and returns the hub's response unchanged. */
69
+ request: (body: SubscribeRequest | UnsubscribeRequest, principal: string) => Promise<Response>;
70
+ notify: (path: string) => Promise<void>;
71
+ publish: (path: string, patches: JsonPatch[]) => Promise<void>;
72
+ };
73
+ interface ReactiveRoutes {
74
+ /** `POST` exchanges a credential for a signed ticket. */
75
+ ticket: string;
76
+ /** WebSocket upgrade, authenticated by the ticket in the `token` query parameter. */
77
+ socket: string;
78
+ /** Reactive HTTP subscribe and unsubscribe, authenticated by the ticket as a bearer token. */
79
+ reactive: string;
80
+ }
81
+ interface ReactiveRoutesOptions {
82
+ routes: ReactiveRoutes;
83
+ /** Ticket signing secret. Requests get 503 when it is not configured. */
84
+ secret: string | undefined;
85
+ /** The hub Durable Object stub that serves these routes. */
86
+ hub: () => HubStub;
87
+ /** Returns the principal for a ticket request, or undefined to answer 401. */
88
+ authenticate(request: Request): string | undefined | Promise<string | undefined>;
89
+ ticketLifetimeSeconds?: number;
90
+ }
91
+ /** Serves the ticket, socket and reactive HTTP routes; `undefined` for any other path. */
92
+ declare function handleReactiveRoutes(request: Request, options: ReactiveRoutesOptions): Promise<Response | undefined>;
93
+
94
+ export { HUB_PRINCIPAL_HEADER, createDurableObjectHub, handleReactiveRoutes, hubClient };
95
+ export type { DurableObjectHub, DurableObjectHubOptions, DurableObjectStateLike, DurableObjectWebSocket, HubStub, ReactiveRoutes, ReactiveRoutesOptions };
@@ -0,0 +1,95 @@
1
+ import { SubscribeRequest, SnapshotResponse, UnsubscribeRequest, JsonPatch } from './cluster.js';
2
+ import { HubSocket, HubPaths } from './hub.js';
3
+
4
+ /**
5
+ * Cloudflare Durable Object shell for the reactive hub. It is structural: it
6
+ * takes the Durable Object's `ctx` instead of extending `DurableObject`, so this
7
+ * entry imports nothing from `cloudflare:workers` and builds like every other
8
+ * entry. Your Durable Object class owns its name and migrations and delegates
9
+ * `fetch`, `webSocketMessage`, `webSocketClose` and `webSocketError` to it.
10
+ */
11
+ /** Set by the route handler on requests it forwards to the hub; never trusted from clients. */
12
+ declare const HUB_PRINCIPAL_HEADER = "x-reactive-principal";
13
+ /** A hibernatable Workers WebSocket, as far as the hub needs it. */
14
+ interface DurableObjectWebSocket extends HubSocket {
15
+ close(code?: number, reason?: string): void;
16
+ }
17
+ /** The parts of `DurableObjectState` the hub uses. */
18
+ interface DurableObjectStateLike {
19
+ acceptWebSocket(socket: DurableObjectWebSocket, tags?: string[]): void;
20
+ getWebSockets(tag?: string): DurableObjectWebSocket[];
21
+ setWebSocketAutoResponse?(pair?: unknown): void;
22
+ storage: {
23
+ get<T>(key: string): Promise<T | undefined>;
24
+ put<T>(key: string, value: T): Promise<void>;
25
+ };
26
+ }
27
+ /** Anything with a Durable Object stub's `fetch`. */
28
+ interface HubStub {
29
+ fetch(request: Request): Promise<Response>;
30
+ }
31
+ type WebSocketPairConstructor = new () => {
32
+ 0: DurableObjectWebSocket;
33
+ 1: DurableObjectWebSocket;
34
+ };
35
+ interface DurableObjectHubOptions {
36
+ paths: HubPaths;
37
+ /** Storage key for a path's version. Defaults to `version:<path>`. */
38
+ versionKey?: (path: string) => string;
39
+ maxAttachmentBytes?: number;
40
+ /**
41
+ * Answers the client's `ping` with `pong` without waking the Durable Object.
42
+ * Defaults to true.
43
+ */
44
+ autoPong?: boolean;
45
+ /** Workers' `WebSocketPair`; injectable for tests. */
46
+ WebSocketPair?: WebSocketPairConstructor;
47
+ /** Creates a connection id; injectable for tests. */
48
+ randomId?: () => string;
49
+ }
50
+ /** Wires the hub core to a Durable Object's hibernatable WebSockets and storage. */
51
+ declare function createDurableObjectHub(ctx: DurableObjectStateLike, options: DurableObjectHubOptions): {
52
+ hub: {
53
+ message(socket: HubSocket, raw: string): void;
54
+ subscribe(request: SubscribeRequest, principal: string): Promise<SnapshotResponse>;
55
+ unsubscribe(request: UnsubscribeRequest, principal: string): void;
56
+ notify(path: string): Promise<void>;
57
+ publish(path: string, patches: JsonPatch[]): Promise<void>;
58
+ };
59
+ /** The Durable Object's `fetch`: WebSocket upgrades and actions from `hubClient`. */
60
+ fetch(request: Request): Promise<Response>;
61
+ webSocketMessage(socket: DurableObjectWebSocket, message: string | ArrayBuffer): void;
62
+ webSocketClose(socket: DurableObjectWebSocket, code: number): void;
63
+ webSocketError(socket: DurableObjectWebSocket): void;
64
+ };
65
+ type DurableObjectHub = ReturnType<typeof createDurableObjectHub>;
66
+ /** Calls a hub Durable Object from the Worker. */
67
+ declare function hubClient(stub: HubStub): {
68
+ /** Forwards a reactive HTTP request and returns the hub's response unchanged. */
69
+ request: (body: SubscribeRequest | UnsubscribeRequest, principal: string) => Promise<Response>;
70
+ notify: (path: string) => Promise<void>;
71
+ publish: (path: string, patches: JsonPatch[]) => Promise<void>;
72
+ };
73
+ interface ReactiveRoutes {
74
+ /** `POST` exchanges a credential for a signed ticket. */
75
+ ticket: string;
76
+ /** WebSocket upgrade, authenticated by the ticket in the `token` query parameter. */
77
+ socket: string;
78
+ /** Reactive HTTP subscribe and unsubscribe, authenticated by the ticket as a bearer token. */
79
+ reactive: string;
80
+ }
81
+ interface ReactiveRoutesOptions {
82
+ routes: ReactiveRoutes;
83
+ /** Ticket signing secret. Requests get 503 when it is not configured. */
84
+ secret: string | undefined;
85
+ /** The hub Durable Object stub that serves these routes. */
86
+ hub: () => HubStub;
87
+ /** Returns the principal for a ticket request, or undefined to answer 401. */
88
+ authenticate(request: Request): string | undefined | Promise<string | undefined>;
89
+ ticketLifetimeSeconds?: number;
90
+ }
91
+ /** Serves the ticket, socket and reactive HTTP routes; `undefined` for any other path. */
92
+ declare function handleReactiveRoutes(request: Request, options: ReactiveRoutesOptions): Promise<Response | undefined>;
93
+
94
+ export { HUB_PRINCIPAL_HEADER, createDurableObjectHub, handleReactiveRoutes, hubClient };
95
+ export type { DurableObjectHub, DurableObjectHubOptions, DurableObjectStateLike, DurableObjectWebSocket, HubStub, ReactiveRoutes, ReactiveRoutesOptions };
@@ -0,0 +1,374 @@
1
+ // ../client/src/cluster.ts
2
+ var DEFAULT_TICKET_LIFETIME_SECONDS = 60;
3
+ function isRecord(value) {
4
+ return typeof value === "object" && value !== null;
5
+ }
6
+ function parseClusterTicket(value) {
7
+ if (!isRecord(value) || typeof value.token !== "string" || value.token.length === 0 || typeof value.expiresAt !== "number" || !Number.isFinite(value.expiresAt) || typeof value.url !== "string") {
8
+ throw new Error("Cluster ticket response is invalid");
9
+ }
10
+ const url = new URL(value.url);
11
+ if (url.protocol !== "wss:") throw new Error("Cluster ticket URL must use WSS");
12
+ return { token: value.token, expiresAt: value.expiresAt, url: url.toString() };
13
+ }
14
+ var encoder = new TextEncoder();
15
+ function base64UrlEncode(bytes) {
16
+ let binary = "";
17
+ for (const byte of bytes) binary += String.fromCharCode(byte);
18
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
19
+ }
20
+ function base64UrlDecode(value) {
21
+ const padded = value.replaceAll("-", "+").replaceAll("_", "/");
22
+ const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
23
+ const bytes = new Uint8Array(new ArrayBuffer(binary.length));
24
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
25
+ return bytes;
26
+ }
27
+ function hmacKey(secret, usage) {
28
+ return crypto.subtle.importKey(
29
+ "raw",
30
+ encoder.encode(secret),
31
+ { name: "HMAC", hash: "SHA-256" },
32
+ false,
33
+ [usage]
34
+ );
35
+ }
36
+ async function createSignedClusterTicket(options) {
37
+ const expiresAt = Math.floor((options.now ?? Date.now()) / 1e3) + (options.lifetimeSeconds ?? DEFAULT_TICKET_LIFETIME_SECONDS);
38
+ const payload = base64UrlEncode(
39
+ encoder.encode(JSON.stringify({ p: options.principal, exp: expiresAt }))
40
+ );
41
+ const signature = new Uint8Array(
42
+ await crypto.subtle.sign("HMAC", await hmacKey(options.secret, "sign"), encoder.encode(payload))
43
+ );
44
+ return parseClusterTicket({
45
+ token: `${payload}.${base64UrlEncode(signature)}`,
46
+ expiresAt,
47
+ url: options.url
48
+ });
49
+ }
50
+ async function verifySignedClusterTicket(token, secret, now = Date.now()) {
51
+ const [payload, signature, extra] = token.split(".");
52
+ if (!payload || !signature || extra !== void 0) return void 0;
53
+ try {
54
+ const valid = await crypto.subtle.verify(
55
+ "HMAC",
56
+ await hmacKey(secret, "verify"),
57
+ base64UrlDecode(signature),
58
+ encoder.encode(payload)
59
+ );
60
+ if (!valid) return void 0;
61
+ const claims = JSON.parse(new TextDecoder().decode(base64UrlDecode(payload)));
62
+ if (!isRecord(claims) || typeof claims.p !== "string" || typeof claims.exp !== "number" || claims.exp <= Math.floor(now / 1e3)) {
63
+ return void 0;
64
+ }
65
+ return claims.p;
66
+ } catch {
67
+ return void 0;
68
+ }
69
+ }
70
+
71
+ // ../client/src/hub.ts
72
+ var DEFAULT_MAX_ATTACHMENT_BYTES = 2048;
73
+ var ReactiveHubError = class extends Error {
74
+ constructor(message) {
75
+ super(message);
76
+ this.name = "ReactiveHubError";
77
+ }
78
+ };
79
+ function isRecord2(value) {
80
+ return typeof value === "object" && value !== null;
81
+ }
82
+ function isHubRequest(value) {
83
+ if (!isRecord2(value)) return false;
84
+ return (value.type === "subscribe" || value.type === "unsubscribe") && typeof value.connectionId === "string" && typeof value.subscriptionId === "string" && typeof value.generation === "number" && (value.type === "unsubscribe" || typeof value.path === "string");
85
+ }
86
+ function bearerToken(request) {
87
+ const match = /^Bearer ([^\s]+)$/u.exec(request.headers.get("authorization") ?? "");
88
+ return match?.[1] ?? "";
89
+ }
90
+ function createHubSocketState(connectionId, principal) {
91
+ return { connectionId, principal, subscriptions: [] };
92
+ }
93
+ function socketState(socket) {
94
+ const state = socket.deserializeAttachment();
95
+ return { ...state, subscriptions: state.subscriptions.filter((entry) => entry.path) };
96
+ }
97
+ function send(socket, event) {
98
+ try {
99
+ socket.send(JSON.stringify(event));
100
+ } catch {
101
+ }
102
+ }
103
+ function createReactiveHub(options) {
104
+ const { sockets, versions } = options;
105
+ const maxAttachmentBytes = options.maxAttachmentBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES;
106
+ const resolve = (path) => typeof options.paths === "function" ? options.paths(path) : Object.hasOwn(options.paths, path) ? options.paths[path] : void 0;
107
+ const ownedSocket = (connectionId, principal) => {
108
+ const socket = sockets.byConnectionId(connectionId);
109
+ return socket && socketState(socket).principal === principal ? socket : void 0;
110
+ };
111
+ const subscribersOf = (path) => sockets.all().flatMap(
112
+ (socket) => socketState(socket).subscriptions.filter((subscription) => subscription.path === path).map((subscription) => ({ socket, subscription }))
113
+ );
114
+ const bump = async (path) => {
115
+ const fromVersion = await versions.get(path);
116
+ const toVersion = fromVersion + 1;
117
+ await versions.set(path, toVersion);
118
+ return { fromVersion, toVersion };
119
+ };
120
+ return {
121
+ /** Answers the client's `init` and `ping` frames. */
122
+ message(socket, raw) {
123
+ let frame;
124
+ try {
125
+ frame = JSON.parse(raw);
126
+ } catch {
127
+ return;
128
+ }
129
+ const type = isRecord2(frame) ? frame.type : void 0;
130
+ if (type === "init") {
131
+ send(socket, { type: "connected", connectionId: socketState(socket).connectionId });
132
+ } else if (type === "ping") {
133
+ send(socket, { type: "pong" });
134
+ }
135
+ },
136
+ async subscribe(request, principal) {
137
+ const handler = resolve(request.path);
138
+ if (!handler) throw new ReactiveHubError("Unknown subscription path");
139
+ if (!ownedSocket(request.connectionId, principal)) {
140
+ throw new ReactiveHubError("Unknown connection");
141
+ }
142
+ const context = { path: request.path, principal, input: request.input };
143
+ if (handler.authorize && !await handler.authorize(context)) {
144
+ throw new ReactiveHubError("Subscription not allowed");
145
+ }
146
+ const socket = ownedSocket(request.connectionId, principal);
147
+ if (!socket) throw new ReactiveHubError("Unknown connection");
148
+ const state = socketState(socket);
149
+ const next = {
150
+ ...state,
151
+ subscriptions: [
152
+ ...state.subscriptions.filter(
153
+ (entry) => entry.subscriptionId !== request.subscriptionId
154
+ ),
155
+ {
156
+ subscriptionId: request.subscriptionId,
157
+ generation: request.generation,
158
+ path: request.path
159
+ }
160
+ ]
161
+ };
162
+ if (new TextEncoder().encode(JSON.stringify(next)).length > maxAttachmentBytes) {
163
+ throw new ReactiveHubError("Too many subscriptions on this connection");
164
+ }
165
+ socket.serializeAttachment(next);
166
+ const version = await versions.get(request.path);
167
+ const data = await handler.snapshot(context);
168
+ return {
169
+ type: "snapshot",
170
+ subscriptionId: request.subscriptionId,
171
+ generation: request.generation,
172
+ version,
173
+ data
174
+ };
175
+ },
176
+ unsubscribe(request, principal) {
177
+ const socket = ownedSocket(request.connectionId, principal);
178
+ if (!socket) return;
179
+ const state = socketState(socket);
180
+ socket.serializeAttachment({
181
+ ...state,
182
+ subscriptions: state.subscriptions.filter(
183
+ (entry) => entry.subscriptionId !== request.subscriptionId
184
+ )
185
+ });
186
+ },
187
+ /** Bumps the path's version and asks each of its subscribers to re-fetch. */
188
+ async notify(path) {
189
+ const { fromVersion, toVersion } = await bump(path);
190
+ for (const { socket, subscription } of subscribersOf(path)) {
191
+ send(socket, {
192
+ type: "resync",
193
+ subscriptionId: subscription.subscriptionId,
194
+ generation: subscription.generation,
195
+ fromVersion,
196
+ toVersion,
197
+ messageId: crypto.randomUUID()
198
+ });
199
+ }
200
+ },
201
+ /**
202
+ * Bumps the path's version and sends the same JSON patches to each subscriber.
203
+ * Use it only when every subscriber of the path sees the same data.
204
+ */
205
+ async publish(path, patches) {
206
+ const { fromVersion, toVersion } = await bump(path);
207
+ for (const { socket, subscription } of subscribersOf(path)) {
208
+ send(socket, {
209
+ type: "patch",
210
+ subscriptionId: subscription.subscriptionId,
211
+ generation: subscription.generation,
212
+ fromVersion,
213
+ toVersion,
214
+ messageId: crypto.randomUUID(),
215
+ patches
216
+ });
217
+ }
218
+ }
219
+ };
220
+ }
221
+
222
+ // ../client/src/cloudflare.ts
223
+ var HUB_PRINCIPAL_HEADER = "x-reactive-principal";
224
+ var HUB_ACTION_URL = "https://reactive-hub/";
225
+ function json(value, status = 200) {
226
+ return Response.json(value, { status, headers: { "cache-control": "no-store" } });
227
+ }
228
+ function error(message, status) {
229
+ return json({ type: "error", message }, status);
230
+ }
231
+ function workersGlobal(name) {
232
+ return globalThis[name];
233
+ }
234
+ function createDurableObjectHub(ctx, options) {
235
+ const versionKey = options.versionKey ?? ((path) => `version:${path}`);
236
+ const randomId = options.randomId ?? (() => crypto.randomUUID());
237
+ const hub = createReactiveHub({
238
+ sockets: {
239
+ all: () => ctx.getWebSockets(),
240
+ // Tagging by connection id lets HTTP subscribes find the socket after hibernation.
241
+ byConnectionId: (connectionId) => ctx.getWebSockets(connectionId)[0]
242
+ },
243
+ versions: {
244
+ get: async (path) => await ctx.storage.get(versionKey(path)) ?? 0,
245
+ set: (path, version) => ctx.storage.put(versionKey(path), version)
246
+ },
247
+ paths: options.paths,
248
+ ...options.maxAttachmentBytes === void 0 ? {} : { maxAttachmentBytes: options.maxAttachmentBytes }
249
+ });
250
+ if (options.autoPong !== false) {
251
+ const Pair = workersGlobal("WebSocketRequestResponsePair");
252
+ if (Pair && ctx.setWebSocketAutoResponse) {
253
+ ctx.setWebSocketAutoResponse(
254
+ new Pair(JSON.stringify({ type: "ping" }), JSON.stringify({ type: "pong" }))
255
+ );
256
+ }
257
+ }
258
+ const accept = (request) => {
259
+ const principal = request.headers.get(HUB_PRINCIPAL_HEADER);
260
+ if (!principal) return error("Unauthorized", 401);
261
+ const Pair = options.WebSocketPair ?? workersGlobal("WebSocketPair");
262
+ if (!Pair) throw new Error("WebSocketPair is not available in this runtime");
263
+ const pair = new Pair();
264
+ const connectionId = randomId();
265
+ ctx.acceptWebSocket(pair[1], [connectionId]);
266
+ pair[1].serializeAttachment(createHubSocketState(connectionId, principal));
267
+ return new Response(null, { status: 101, webSocket: pair[0] });
268
+ };
269
+ const act = async (action) => {
270
+ try {
271
+ switch (action.action) {
272
+ case "subscribe":
273
+ return json(await hub.subscribe(action.body, action.principal));
274
+ case "unsubscribe":
275
+ hub.unsubscribe(action.body, action.principal);
276
+ return json({ type: "ok" });
277
+ case "notify":
278
+ await hub.notify(action.path);
279
+ return json({ type: "ok" });
280
+ case "publish":
281
+ await hub.publish(action.path, action.patches);
282
+ return json({ type: "ok" });
283
+ default:
284
+ return error("Unknown hub action", 400);
285
+ }
286
+ } catch (cause) {
287
+ if (cause instanceof ReactiveHubError) return error(cause.message, 400);
288
+ throw cause;
289
+ }
290
+ };
291
+ return {
292
+ hub,
293
+ /** The Durable Object's `fetch`: WebSocket upgrades and actions from `hubClient`. */
294
+ async fetch(request) {
295
+ if (request.headers.get("upgrade") === "websocket") return accept(request);
296
+ return act(await request.json());
297
+ },
298
+ webSocketMessage(socket, message) {
299
+ if (typeof message === "string") hub.message(socket, message);
300
+ },
301
+ webSocketClose(socket, code) {
302
+ try {
303
+ socket.close(code === 1005 ? 1e3 : code, "closed");
304
+ } catch {
305
+ }
306
+ },
307
+ webSocketError(socket) {
308
+ try {
309
+ socket.close(1011, "error");
310
+ } catch {
311
+ }
312
+ }
313
+ };
314
+ }
315
+ function hubClient(stub) {
316
+ const post = (action) => stub.fetch(new Request(HUB_ACTION_URL, { method: "POST", body: JSON.stringify(action) }));
317
+ const ok = async (response) => {
318
+ if (!response.ok) throw new Error(`Hub request failed: HTTP ${response.status}`);
319
+ };
320
+ return {
321
+ /** Forwards a reactive HTTP request and returns the hub's response unchanged. */
322
+ request: (body, principal) => post(
323
+ body.type === "subscribe" ? { action: "subscribe", principal, body } : { action: "unsubscribe", principal, body }
324
+ ),
325
+ notify: async (path) => ok(await post({ action: "notify", path })),
326
+ publish: async (path, patches) => ok(await post({ action: "publish", path, patches }))
327
+ };
328
+ }
329
+ async function handleReactiveRoutes(request, options) {
330
+ const url = new URL(request.url);
331
+ const { routes, secret } = options;
332
+ if (![routes.ticket, routes.socket, routes.reactive].includes(url.pathname)) return void 0;
333
+ if (!secret) return error("Reactive hub is not configured", 503);
334
+ if (url.pathname === routes.ticket) {
335
+ if (request.method !== "POST") return error("Method not allowed", 405);
336
+ const principal2 = await options.authenticate(request);
337
+ if (!principal2) return error("Unauthorized", 401);
338
+ const socketUrl = new URL(routes.socket, url);
339
+ socketUrl.protocol = "wss:";
340
+ return json(
341
+ await createSignedClusterTicket({
342
+ secret,
343
+ principal: principal2,
344
+ url: socketUrl.toString(),
345
+ ...options.ticketLifetimeSeconds === void 0 ? {} : { lifetimeSeconds: options.ticketLifetimeSeconds }
346
+ })
347
+ );
348
+ }
349
+ if (url.pathname === routes.socket) {
350
+ if (request.headers.get("upgrade") !== "websocket") {
351
+ return error("Expected a WebSocket upgrade", 426);
352
+ }
353
+ const principal2 = await verifySignedClusterTicket(url.searchParams.get("token") ?? "", secret);
354
+ if (!principal2) return new Response("Unauthorized", { status: 401 });
355
+ const forwarded = new Request(request);
356
+ forwarded.headers.set(HUB_PRINCIPAL_HEADER, principal2);
357
+ return options.hub().fetch(forwarded);
358
+ }
359
+ if (request.method !== "POST") return error("Method not allowed", 405);
360
+ const principal = await verifySignedClusterTicket(bearerToken(request), secret);
361
+ if (!principal) return error("Unauthorized", 401);
362
+ let body;
363
+ try {
364
+ body = await request.json();
365
+ } catch {
366
+ return error("Invalid JSON", 400);
367
+ }
368
+ if (!isHubRequest(body)) return error("Unsupported reactive request", 400);
369
+ return hubClient(options.hub()).request(body, principal);
370
+ }
371
+
372
+ export { HUB_PRINCIPAL_HEADER, createDurableObjectHub, handleReactiveRoutes, hubClient };
373
+ //# sourceMappingURL=cloudflare.js.map
374
+ //# sourceMappingURL=cloudflare.js.map