durability 3.0.1 → 4.1.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 type { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import type { SerializedError } from './errors.js';
3
+ export declare const socketProtocolVersion = 1;
4
+ /** Largest text frame either side accepts, in UTF-16 code units. */
5
+ export declare const socketMaxFrameLength: number;
6
+ /** Close code sent when the peer violates the wire protocol; clients must not retry. */
7
+ export declare const socketProtocolErrorCode = 4002;
8
+ /** Frames a client sends. `input` is omitted when the method takes none. */
9
+ export type SocketClientFrame = {
10
+ v: 1;
11
+ type: 'call';
12
+ id: string;
13
+ method: string;
14
+ input?: unknown;
15
+ } | {
16
+ v: 1;
17
+ type: 'subscribe';
18
+ id: string;
19
+ names: string[];
20
+ since?: number;
21
+ };
22
+ /** Frames a server sends. `output` and `payload` are omitted when undefined. */
23
+ export type SocketServerFrame = {
24
+ v: 1;
25
+ type: 'result';
26
+ id: string;
27
+ output?: unknown;
28
+ } | {
29
+ v: 1;
30
+ type: 'error';
31
+ id: string;
32
+ error: SerializedError;
33
+ } | {
34
+ v: 1;
35
+ type: 'subscribed';
36
+ id: string;
37
+ seq: number;
38
+ replayed: boolean;
39
+ } | {
40
+ v: 1;
41
+ type: 'event';
42
+ seq: number;
43
+ name: string;
44
+ payload?: unknown;
45
+ };
46
+ export declare const parseClientFrame: (text: string) => SocketClientFrame | undefined;
47
+ export declare const parseServerFrame: (text: string) => SocketServerFrame | undefined;
48
+ /** Per-call context passed to inbound handlers. */
49
+ export type SocketCall<Metadata> = {
50
+ /** Trusted data captured from the upgrade request by `metadata`. */
51
+ metadata: Metadata;
52
+ };
53
+ /**
54
+ * An inbound handler: a bare function that takes no input (or `unknown`
55
+ * input it validates itself), or a validated `{ input, handle }` pair.
56
+ */
57
+ export type SocketInboundHandler<Metadata> = ((input: unknown, call: SocketCall<Metadata>) => unknown) | {
58
+ input: StandardSchemaV1;
59
+ handle: (input: never, call: SocketCall<Metadata>) => unknown;
60
+ };
61
+ export type SocketInboundMap<Metadata = never> = Record<string, SocketInboundHandler<Metadata>>;
62
+ type HandlerMetadata<Handler> = Handler extends {
63
+ handle: (input: never, call: SocketCall<infer Metadata>) => unknown;
64
+ } ? Metadata : Handler extends (input: never, call: SocketCall<infer Metadata>) => unknown ? Metadata : unknown;
65
+ type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends (value: infer Intersection) => void ? Intersection : never;
66
+ /** The metadata every inbound handler in the map can accept. */
67
+ export type SocketInboundMetadata<Inbound> = UnionToIntersection<{
68
+ [Name in keyof Inbound]: HandlerMetadata<Inbound[Name]>;
69
+ }[keyof Inbound]>;
70
+ /** Marks an outbound event and carries its payload type. */
71
+ export type SocketOutboundEvent<Payload> = {
72
+ readonly payload?: Payload;
73
+ };
74
+ export type SocketOutboundMap = Record<string, SocketOutboundEvent<unknown>>;
75
+ /** Declares an outbound event with the given payload type. */
76
+ export declare const event: <Payload>() => SocketOutboundEvent<Payload>;
77
+ export type SocketInboundInput<Handler> = Handler extends {
78
+ input: infer Schema extends StandardSchemaV1;
79
+ } ? StandardSchemaV1.InferInput<Schema> : Handler extends (...args: infer Args) => unknown ? Args extends [] ? void : Args[0] : never;
80
+ export type SocketInboundOutput<Handler> = Handler extends {
81
+ handle: (...args: never[]) => infer Result;
82
+ } ? Awaited<Result> : Handler extends (...args: never[]) => infer Result ? Awaited<Result> : never;
83
+ export type SocketOutboundPayload<Event> = Event extends SocketOutboundEvent<infer Payload> ? Payload : never;
84
+ export declare const socketShape: unique symbol;
85
+ /** Phantom type a server socket carries so clients can derive its surface. */
86
+ export type SocketShape<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap> = {
87
+ inbound: Inbound;
88
+ outbound: Outbound;
89
+ };
90
+ export type AnySocketShape = {
91
+ readonly [socketShape]: SocketShape<SocketInboundMap, SocketOutboundMap>;
92
+ };
93
+ export type InboundOf<Socket extends AnySocketShape> = Socket[typeof socketShape]['inbound'];
94
+ export type OutboundOf<Socket extends AnySocketShape> = Socket[typeof socketShape]['outbound'];
95
+ export {};
@@ -0,0 +1,71 @@
1
+ export const socketProtocolVersion = 1;
2
+ /** Largest text frame either side accepts, in UTF-16 code units. */
3
+ export const socketMaxFrameLength = 1024 * 1024;
4
+ /** Close code sent when the peer violates the wire protocol; clients must not retry. */
5
+ export const socketProtocolErrorCode = 4002;
6
+ const isRecord = (value) => typeof value === 'object' && value !== null;
7
+ const isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === 'string');
8
+ const isSerializedError = (value) => isRecord(value) &&
9
+ typeof value['name'] === 'string' &&
10
+ typeof value['message'] === 'string';
11
+ const parseFrame = (text) => {
12
+ if (text.length > socketMaxFrameLength) {
13
+ return undefined;
14
+ }
15
+ let parsed;
16
+ try {
17
+ parsed = JSON.parse(text);
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ if (!isRecord(parsed) || parsed['v'] !== socketProtocolVersion) {
23
+ return undefined;
24
+ }
25
+ return parsed;
26
+ };
27
+ export const parseClientFrame = (text) => {
28
+ const frame = parseFrame(text);
29
+ if (!frame || typeof frame['id'] !== 'string') {
30
+ return undefined;
31
+ }
32
+ if (frame['type'] === 'call' && typeof frame['method'] === 'string') {
33
+ return frame;
34
+ }
35
+ if (frame['type'] === 'subscribe' &&
36
+ isStringArray(frame['names']) &&
37
+ (frame['since'] === undefined || Number.isSafeInteger(frame['since']))) {
38
+ return frame;
39
+ }
40
+ return undefined;
41
+ };
42
+ export const parseServerFrame = (text) => {
43
+ const frame = parseFrame(text);
44
+ if (!frame) {
45
+ return undefined;
46
+ }
47
+ if (frame['type'] === 'event') {
48
+ return Number.isSafeInteger(frame['seq']) &&
49
+ typeof frame['name'] === 'string'
50
+ ? frame
51
+ : undefined;
52
+ }
53
+ if (typeof frame['id'] !== 'string') {
54
+ return undefined;
55
+ }
56
+ if (frame['type'] === 'result') {
57
+ return frame;
58
+ }
59
+ if (frame['type'] === 'error' && isSerializedError(frame['error'])) {
60
+ return frame;
61
+ }
62
+ if (frame['type'] === 'subscribed' &&
63
+ Number.isSafeInteger(frame['seq']) &&
64
+ typeof frame['replayed'] === 'boolean') {
65
+ return frame;
66
+ }
67
+ return undefined;
68
+ };
69
+ /** Declares an outbound event with the given payload type. */
70
+ export const event = () => ({});
71
+ export const socketShape = Symbol('durability.socket');
@@ -0,0 +1,92 @@
1
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import { type DurabilityMigrationResult } from './migrations.js';
3
+ import { type SocketInboundMap, type SocketOutboundMap, type SocketOutboundPayload, type SocketInboundMetadata, type SocketShape, socketShape } from './socket-protocol.js';
4
+ /** The Durable Object state a socket needs: SQLite storage and hibernatable WebSockets. */
5
+ export type DurabilitySocketContext = Pick<DurableObjectState, 'storage' | 'acceptWebSocket' | 'getWebSockets' | 'setWebSocketAutoResponse'>;
6
+ export type DurabilitySocketConfig<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound>> = {
7
+ context: DurabilitySocketContext;
8
+ /** Methods clients may call, keyed by the names they become on the client. */
9
+ inbound: Inbound;
10
+ /** Events the object may push, keyed by the methods they become on this instance. */
11
+ outbound: Outbound;
12
+ /**
13
+ * Captures trusted per-connection data from the upgrade request. Stored in
14
+ * the WebSocket attachment, so it survives hibernation without re-auth.
15
+ */
16
+ metadata?: (request: Request) => Metadata | Promise<Metadata>;
17
+ /** Outbound events kept for replay to reconnecting clients. Defaults to 1000. */
18
+ retention?: number;
19
+ };
20
+ /** Thrown to the caller when an inbound payload fails its schema. */
21
+ export declare class SocketInputError extends Error {
22
+ readonly issues: readonly StandardSchemaV1.Issue[];
23
+ constructor(method: string, issues: readonly StandardSchemaV1.Issue[]);
24
+ }
25
+ declare class DurabilitySocketCore<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound>> {
26
+ #private;
27
+ readonly [socketShape]: SocketShape<Inbound, Outbound>;
28
+ constructor(config: DurabilitySocketConfig<Inbound, Outbound, Metadata>);
29
+ /** Applies or reverts the `durability_socket_events` schema. */
30
+ static migrate(context: Pick<DurableObjectState, 'storage'>, target?: string | null): DurabilityMigrationResult;
31
+ /** Accepts a WebSocket upgrade; call from the Durable Object's `fetch`. */
32
+ fetch(request: Request): Promise<Response>;
33
+ /** Handles one inbound frame; call from the Durable Object's `webSocketMessage`. */
34
+ webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void>;
35
+ /**
36
+ * Call from the Durable Object's `webSocketClose`. Subscriptions live in the
37
+ * socket's attachment, so nothing needs cleaning up; the runtime requires
38
+ * the method to exist for hibernatable WebSockets.
39
+ */
40
+ webSocketClose(_ws: WebSocket): void;
41
+ }
42
+ type OutboundMethods<Outbound extends SocketOutboundMap> = {
43
+ [Name in keyof Outbound]: (payload: SocketOutboundPayload<Outbound[Name]>) => void;
44
+ };
45
+ /**
46
+ * Typed WebSocket RPC and event push for one Durable Object, over hibernatable
47
+ * WebSockets.
48
+ *
49
+ * Every `outbound` event becomes a method on the instance that persists the
50
+ * event for replay and pushes it to subscribed clients. Clients call `inbound`
51
+ * handlers through `durability/client`.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * class TodoList extends DurableObject<Env> {
56
+ * readonly socket = new DurabilitySocket({
57
+ * context: this.ctx,
58
+ * inbound: {
59
+ * list: () => this.repo.list(),
60
+ * create: {
61
+ * input: TodoSchema,
62
+ * handle: async (todo: Todo) => {
63
+ * await this.repo.insert(todo);
64
+ * this.socket.created(todo);
65
+ * },
66
+ * },
67
+ * },
68
+ * outbound: { created: event<Todo>() },
69
+ * });
70
+ *
71
+ * fetch(request: Request) {
72
+ * return this.socket.fetch(request);
73
+ * }
74
+ *
75
+ * webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
76
+ * return this.socket.webSocketMessage(ws, message);
77
+ * }
78
+ *
79
+ * webSocketClose(ws: WebSocket) {
80
+ * this.socket.webSocketClose(ws);
81
+ * }
82
+ * }
83
+ * ```
84
+ */
85
+ export type DurabilitySocket<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound> = SocketInboundMetadata<Inbound>> = DurabilitySocketCore<Inbound, Outbound, Metadata> & OutboundMethods<Outbound>;
86
+ export interface DurabilitySocketConstructor {
87
+ new <Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound> = SocketInboundMetadata<Inbound>>(config: DurabilitySocketConfig<Inbound, Outbound, Metadata>): DurabilitySocket<Inbound, Outbound, Metadata>;
88
+ migrate: typeof DurabilitySocketCore.migrate;
89
+ }
90
+ export declare const DurabilitySocket: DurabilitySocketConstructor;
91
+ export { durabilitySocketMigrations } from './migrations.js';
92
+ export { event, type SocketCall, type SocketInboundHandler, type SocketInboundMap, type SocketOutboundEvent, type SocketOutboundMap, } from './socket-protocol.js';
package/dist/socket.js ADDED
@@ -0,0 +1,273 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _DurabilitySocketCore_instances, _DurabilitySocketCore_context, _DurabilitySocketCore_inbound, _DurabilitySocketCore_outboundNames, _DurabilitySocketCore_metadata, _DurabilitySocketCore_retention, _DurabilitySocketCore_call, _DurabilitySocketCore_validate, _DurabilitySocketCore_subscribe, _DurabilitySocketCore_replay, _DurabilitySocketCore_headSeq, _DurabilitySocketCore_publish;
13
+ import { reportFailure, serializeError } from './errors.js';
14
+ import { durabilitySocketMigrations, migrate, } from './migrations.js';
15
+ import { deserialize, serialize } from './serialization.js';
16
+ import { parseClientFrame, socketMaxFrameLength, socketProtocolErrorCode, socketProtocolVersion, } from './socket-protocol.js';
17
+ /** Thrown to the caller when an inbound payload fails its schema. */
18
+ export class SocketInputError extends Error {
19
+ constructor(method, issues) {
20
+ super(`Invalid input for "${method}": ${issues.map((issue) => issue.message).join('; ')}`);
21
+ this.name = 'SocketInputError';
22
+ this.issues = issues;
23
+ }
24
+ }
25
+ const reservedOutboundNames = new Set(['status', 'resync']);
26
+ const sendFrame = (ws, frame) => {
27
+ let text = JSON.stringify(frame);
28
+ if (text.length > socketMaxFrameLength) {
29
+ if (frame.type === 'event') {
30
+ reportFailure('durability.socket.event_too_large', { name: frame.name, seq: frame.seq }, new Error('Outbound event exceeds the frame limit'));
31
+ return;
32
+ }
33
+ text = JSON.stringify({
34
+ v: socketProtocolVersion,
35
+ type: 'error',
36
+ id: frame.id,
37
+ error: {
38
+ name: 'SocketFrameTooLargeError',
39
+ message: `Response to "${frame.type}" exceeds ${socketMaxFrameLength} characters`,
40
+ },
41
+ });
42
+ }
43
+ try {
44
+ ws.send(text);
45
+ }
46
+ catch (error) {
47
+ reportFailure('durability.socket.send_failed', { type: frame.type }, error);
48
+ }
49
+ };
50
+ const readAttachment = (ws) => {
51
+ const stored = ws.deserializeAttachment();
52
+ if (typeof stored !== 'object' || stored === null) {
53
+ return { metadata: undefined, names: [] };
54
+ }
55
+ const names = Reflect.get(stored, 'names');
56
+ return {
57
+ metadata: Reflect.get(stored, 'metadata'),
58
+ names: Array.isArray(names)
59
+ ? names.filter((name) => typeof name === 'string')
60
+ : [],
61
+ };
62
+ };
63
+ class DurabilitySocketCore {
64
+ constructor(config) {
65
+ _DurabilitySocketCore_instances.add(this);
66
+ _DurabilitySocketCore_context.set(this, void 0);
67
+ _DurabilitySocketCore_inbound.set(this, void 0);
68
+ _DurabilitySocketCore_outboundNames.set(this, void 0);
69
+ _DurabilitySocketCore_metadata.set(this, void 0);
70
+ _DurabilitySocketCore_retention.set(this, void 0);
71
+ const retention = config.retention ?? 1000;
72
+ if (!Number.isSafeInteger(retention) || retention <= 0) {
73
+ throw new RangeError('retention must be a positive safe integer');
74
+ }
75
+ __classPrivateFieldSet(this, _DurabilitySocketCore_context, config.context, "f");
76
+ // Only own keys are callable; nothing on the prototype chain is reachable.
77
+ __classPrivateFieldSet(this, _DurabilitySocketCore_inbound, new Map(Object.entries(config.inbound)), "f");
78
+ __classPrivateFieldSet(this, _DurabilitySocketCore_metadata, config.metadata, "f");
79
+ __classPrivateFieldSet(this, _DurabilitySocketCore_retention, retention, "f");
80
+ __classPrivateFieldSet(this, _DurabilitySocketCore_outboundNames, new Set(Object.keys(config.outbound)), "f");
81
+ const reserved = new Set([
82
+ ...Object.getOwnPropertyNames(DurabilitySocketCore.prototype),
83
+ ...reservedOutboundNames,
84
+ ]);
85
+ for (const name of __classPrivateFieldGet(this, _DurabilitySocketCore_outboundNames, "f")) {
86
+ if (reserved.has(name)) {
87
+ throw new Error(`"${name}" is reserved by DurabilitySocket`);
88
+ }
89
+ Object.defineProperty(this, name, {
90
+ value: (payload) => __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_publish).call(this, name, payload),
91
+ enumerable: true,
92
+ });
93
+ }
94
+ migrate(__classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage, 'socket', durabilitySocketMigrations, undefined);
95
+ // Keep-alive pings are answered by the runtime without waking a hibernated object.
96
+ __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").setWebSocketAutoResponse(new WebSocketRequestResponsePair(JSON.stringify({ v: socketProtocolVersion, type: 'ping' }), JSON.stringify({ v: socketProtocolVersion, type: 'pong' })));
97
+ }
98
+ /** Applies or reverts the `durability_socket_events` schema. */
99
+ static migrate(context, target) {
100
+ return migrate(context.storage, 'socket', durabilitySocketMigrations, target);
101
+ }
102
+ /** Accepts a WebSocket upgrade; call from the Durable Object's `fetch`. */
103
+ async fetch(request) {
104
+ if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket') {
105
+ return new Response('Expected a WebSocket upgrade', { status: 426 });
106
+ }
107
+ const metadata = await __classPrivateFieldGet(this, _DurabilitySocketCore_metadata, "f")?.call(this, request);
108
+ const pair = new WebSocketPair();
109
+ const client = pair[0];
110
+ const server = pair[1];
111
+ __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").acceptWebSocket(server);
112
+ server.serializeAttachment({
113
+ metadata,
114
+ names: [],
115
+ });
116
+ return new Response(null, { status: 101, webSocket: client });
117
+ }
118
+ /** Handles one inbound frame; call from the Durable Object's `webSocketMessage`. */
119
+ async webSocketMessage(ws, message) {
120
+ const text = typeof message === 'string' ? message : new TextDecoder().decode(message);
121
+ const frame = parseClientFrame(text);
122
+ if (!frame) {
123
+ ws.close(socketProtocolErrorCode, 'Invalid frame');
124
+ return;
125
+ }
126
+ if (frame.type === 'subscribe') {
127
+ __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_subscribe).call(this, ws, frame);
128
+ return;
129
+ }
130
+ await __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_call).call(this, ws, frame);
131
+ }
132
+ /**
133
+ * Call from the Durable Object's `webSocketClose`. Subscriptions live in the
134
+ * socket's attachment, so nothing needs cleaning up; the runtime requires
135
+ * the method to exist for hibernatable WebSockets.
136
+ */
137
+ webSocketClose(_ws) { }
138
+ }
139
+ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_inbound = new WeakMap(), _DurabilitySocketCore_outboundNames = new WeakMap(), _DurabilitySocketCore_metadata = new WeakMap(), _DurabilitySocketCore_retention = new WeakMap(), _DurabilitySocketCore_instances = new WeakSet(), _DurabilitySocketCore_call = async function _DurabilitySocketCore_call(ws, frame) {
140
+ const handler = __classPrivateFieldGet(this, _DurabilitySocketCore_inbound, "f").get(frame.method);
141
+ if (!handler) {
142
+ sendFrame(ws, {
143
+ v: socketProtocolVersion,
144
+ type: 'error',
145
+ id: frame.id,
146
+ error: {
147
+ name: 'SocketUnknownMethodError',
148
+ message: `Unknown method "${frame.method}"`,
149
+ },
150
+ });
151
+ return;
152
+ }
153
+ const call = {
154
+ metadata: readAttachment(ws).metadata,
155
+ };
156
+ try {
157
+ const output = typeof handler === 'function'
158
+ ? await handler(frame.input, call)
159
+ : await handler.handle((await __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_validate).call(this, frame.method, handler.input, frame.input)), call);
160
+ sendFrame(ws, {
161
+ v: socketProtocolVersion,
162
+ type: 'result',
163
+ id: frame.id,
164
+ output,
165
+ });
166
+ }
167
+ catch (error) {
168
+ sendFrame(ws, {
169
+ v: socketProtocolVersion,
170
+ type: 'error',
171
+ id: frame.id,
172
+ error: serializeError(error),
173
+ });
174
+ }
175
+ }, _DurabilitySocketCore_validate = async function _DurabilitySocketCore_validate(method, schema, input) {
176
+ const result = await schema['~standard'].validate(input);
177
+ if (result.issues) {
178
+ throw new SocketInputError(method, result.issues);
179
+ }
180
+ return result.value;
181
+ }, _DurabilitySocketCore_subscribe = function _DurabilitySocketCore_subscribe(ws, frame) {
182
+ const unknown = frame.names.find((name) => !__classPrivateFieldGet(this, _DurabilitySocketCore_outboundNames, "f").has(name));
183
+ if (unknown !== undefined) {
184
+ sendFrame(ws, {
185
+ v: socketProtocolVersion,
186
+ type: 'error',
187
+ id: frame.id,
188
+ error: {
189
+ name: 'SocketUnknownEventError',
190
+ message: `Unknown event "${unknown}"`,
191
+ },
192
+ });
193
+ return;
194
+ }
195
+ const attachment = readAttachment(ws);
196
+ ws.serializeAttachment({
197
+ ...attachment,
198
+ names: frame.names,
199
+ });
200
+ const head = __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_headSeq).call(this);
201
+ const replayed = __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_replay).call(this, ws, frame.names, frame.since, head);
202
+ sendFrame(ws, {
203
+ v: socketProtocolVersion,
204
+ type: 'subscribed',
205
+ id: frame.id,
206
+ seq: head,
207
+ replayed,
208
+ });
209
+ }, _DurabilitySocketCore_replay = function _DurabilitySocketCore_replay(ws, names, since, head) {
210
+ if (since === undefined || since > head) {
211
+ return false;
212
+ }
213
+ if (since === head) {
214
+ return true;
215
+ }
216
+ const oldest = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql
217
+ .exec('SELECT MIN(seq) AS seq FROM durability_socket_events')
218
+ .one().seq;
219
+ if (since + 1 < oldest) {
220
+ return false;
221
+ }
222
+ const rows = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql
223
+ .exec('SELECT seq, name, payload FROM durability_socket_events WHERE seq > ? ORDER BY seq', since)
224
+ .toArray();
225
+ const wanted = new Set(names);
226
+ for (const row of rows) {
227
+ if (!wanted.has(row.name)) {
228
+ continue;
229
+ }
230
+ sendFrame(ws, {
231
+ v: socketProtocolVersion,
232
+ type: 'event',
233
+ seq: row.seq,
234
+ name: row.name,
235
+ payload: deserialize(row.payload),
236
+ });
237
+ }
238
+ return true;
239
+ }, _DurabilitySocketCore_headSeq = function _DurabilitySocketCore_headSeq() {
240
+ const row = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql
241
+ .exec('SELECT MAX(seq) AS seq FROM durability_socket_events')
242
+ .one();
243
+ return row.seq ?? 0;
244
+ }, _DurabilitySocketCore_publish = function _DurabilitySocketCore_publish(name, payload) {
245
+ const serialized = serialize(payload);
246
+ const sql = __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").storage.sql;
247
+ const { seq } = sql
248
+ .exec('INSERT INTO durability_socket_events (name, payload, created_at) VALUES (?, ?, ?) RETURNING seq', name, serialized, Date.now())
249
+ .one();
250
+ sql.exec('DELETE FROM durability_socket_events WHERE seq <= ?', seq - __classPrivateFieldGet(this, _DurabilitySocketCore_retention, "f"));
251
+ const frame = {
252
+ v: socketProtocolVersion,
253
+ type: 'event',
254
+ seq,
255
+ name,
256
+ payload,
257
+ };
258
+ for (const ws of __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").getWebSockets()) {
259
+ if (ws.readyState !== WebSocket.OPEN) {
260
+ continue;
261
+ }
262
+ if (!readAttachment(ws).names.includes(name)) {
263
+ continue;
264
+ }
265
+ sendFrame(ws, frame);
266
+ }
267
+ };
268
+ // TypeScript cannot declare class members derived from a generic event map,
269
+ // so the constructor is typed separately; the constructor installs and
270
+ // reserves every outbound method at runtime.
271
+ export const DurabilitySocket = DurabilitySocketCore;
272
+ export { durabilitySocketMigrations } from './migrations.js';
273
+ export { event, } from './socket-protocol.js';