durability 5.3.0 → 5.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.
Files changed (53) hide show
  1. package/README.md +23 -14
  2. package/dist/alarms/index.d.ts +1 -1
  3. package/dist/alarms/index.js +6 -3
  4. package/dist/dev.d.ts +7 -3
  5. package/dist/dev.js +17 -11
  6. package/dist/durable-object-target.js +8 -4
  7. package/dist/errors.d.ts +13 -7
  8. package/dist/errors.js +34 -32
  9. package/dist/fanout/index.d.ts +1 -1
  10. package/dist/fanout/index.js +15 -13
  11. package/dist/lifecycle.d.ts +1 -0
  12. package/dist/lifecycle.js +2 -2
  13. package/dist/log/index.js +5 -2
  14. package/dist/memoize/index.js +6 -1
  15. package/dist/operations/index.js +8 -4
  16. package/dist/outbox/index.d.ts +1 -1
  17. package/dist/outbox/index.js +7 -4
  18. package/dist/policy.d.ts +1 -1
  19. package/dist/policy.js +2 -1
  20. package/dist/predicates.d.ts +9 -0
  21. package/dist/predicates.js +10 -0
  22. package/dist/routing/client.js +3 -4
  23. package/dist/routing/index.d.ts +1 -1
  24. package/dist/routing/index.js +14 -10
  25. package/dist/schedule/index.d.ts +2 -2
  26. package/dist/schedule/index.js +16 -12
  27. package/dist/scheduler/index.d.ts +16 -13
  28. package/dist/scheduler/index.js +39 -33
  29. package/dist/semaphore/client.js +2 -1
  30. package/dist/semaphore/index.d.ts +1 -1
  31. package/dist/semaphore/index.js +10 -5
  32. package/dist/semaphore/leases.d.ts +3 -2
  33. package/dist/semaphore/leases.js +3 -2
  34. package/dist/semaphore/queue-store.js +2 -1
  35. package/dist/semaphore/queue.d.ts +1 -1
  36. package/dist/semaphore/queue.js +34 -22
  37. package/dist/semaphore/server.js +31 -22
  38. package/dist/serialization.d.ts +3 -2
  39. package/dist/serialization.js +16 -13
  40. package/dist/socket/client.d.ts +21 -7
  41. package/dist/socket/client.js +12 -5
  42. package/dist/socket/index.d.ts +20 -13
  43. package/dist/socket/index.js +40 -18
  44. package/dist/socket/protocol.d.ts +37 -17
  45. package/dist/socket/protocol.js +30 -36
  46. package/dist/topology/client.js +9 -6
  47. package/dist/topology/index.d.ts +3 -3
  48. package/dist/topology/index.js +38 -33
  49. package/dist/topology/snapshot.d.ts +6 -5
  50. package/dist/topology/snapshot.js +5 -2
  51. package/dist/tracker/index.js +10 -2
  52. package/dist/tracker/source.d.ts +6 -2
  53. package/package.json +2 -2
@@ -1,5 +1,5 @@
1
1
  import { type SerializedError } from '../errors.js';
2
- import { type AnySocketShape, type InboundOf, type OutboundOf, type SocketInboundInput, type SocketInboundOutput, type SocketOutboundPayload } from './protocol.js';
2
+ import { type AnyDurabilitySocket, type InboundOf, type OutboundOf, type SocketInboundInput, type SocketInboundOutput, type SocketOutboundPayload } from './protocol.js';
3
3
  /** Rejection for calls still waiting when `close()` was called. */
4
4
  export declare class SocketClosedError extends Error {
5
5
  constructor();
@@ -30,6 +30,8 @@ export type SocketTransform = (call: {
30
30
  input: unknown;
31
31
  next: (input?: unknown) => Promise<unknown>;
32
32
  }) => Promise<unknown>;
33
+ /** The part of a `WebSocket` the client uses. */
34
+ type SocketClientWebSocket = Pick<WebSocket, 'addEventListener' | 'close' | 'send'>;
33
35
  export type DurabilitySocketClientConfig = {
34
36
  /** Builds the WebSocket URL for one Durable Object. */
35
37
  url: (id: string) => string;
@@ -38,9 +40,9 @@ export type DurabilitySocketClientConfig = {
38
40
  /** Interval between keep-alive pings; a silent connection is dropped after two. Defaults to 30 seconds. */
39
41
  pingIntervalMs?: number;
40
42
  /** WebSocket implementation. Defaults to the global `WebSocket`. */
41
- webSocket?: new (url: string) => WebSocket;
43
+ webSocket?: new (url: string) => SocketClientWebSocket;
42
44
  };
43
- type RpcMethod<Input, Output> = [Input] extends [void] ? () => Promise<Output> : unknown extends Input ? (input?: unknown) => Promise<Output> : (input: Input) => Promise<Output>;
45
+ type RpcMethod<Input, Output> = [Input] extends [void] ? () => Promise<Output> : (input: Input) => Promise<Output>;
44
46
  type RpcMethods<Inbound> = {
45
47
  [Method in keyof Inbound]: RpcMethod<SocketInboundInput<Inbound[Method]>, SocketInboundOutput<Inbound[Method]>>;
46
48
  };
@@ -60,7 +62,7 @@ export type SocketResync = {
60
62
  names: string[];
61
63
  };
62
64
  /** One connection to one Durable Object. */
63
- export type SocketConnection<Socket extends AnySocketShape> = {
65
+ export type SocketConnection<Socket extends AnyDurabilitySocket> = {
64
66
  rpc: RpcMethods<InboundOf<Socket>>;
65
67
  on: EventHandlers<OutboundOf<Socket>>;
66
68
  readonly status: SocketStatus;
@@ -82,13 +84,25 @@ export type SocketConnection<Socket extends AnySocketShape> = {
82
84
  * conn.on.resync(() => reload());
83
85
  * ```
84
86
  */
85
- export declare class DurabilitySocketClient<Socket extends AnySocketShape> {
87
+ export declare class DurabilitySocketClient<Socket extends AnyDurabilitySocket> {
86
88
  #private;
87
89
  constructor(config: DurabilitySocketClientConfig, transforms?: readonly SocketTransform[]);
88
90
  /** Returns a client that also applies `transform` around every call. */
89
91
  with(transform: SocketTransform): DurabilitySocketClient<Socket>;
90
92
  connect(id: string): SocketConnection<Socket>;
91
93
  }
94
+ /** One call recorded by {@link logging}: its output if it resolved, or its error. */
95
+ export type SocketCallLog = {
96
+ method: string;
97
+ input: unknown;
98
+ output: unknown;
99
+ durationMs: number;
100
+ } | {
101
+ method: string;
102
+ input: unknown;
103
+ error: unknown;
104
+ durationMs: number;
105
+ };
92
106
  /** Logs every call's input, output or error, and duration. */
93
- export declare const logging: (log?: (entry: Record<string, unknown>) => void) => SocketTransform;
94
- export { socketShape, type AnySocketShape, type InboundOf, type OutboundOf, type SocketInboundInput, type SocketInboundOutput, type SocketOutboundPayload, type SocketShape, } from './protocol.js';
107
+ export declare const logging: (log?: (entry: SocketCallLog) => void) => SocketTransform;
108
+ export { socketMessageMaps, type AnyDurabilitySocket, type InboundOf, type OutboundOf, type SocketInboundInput, type SocketInboundOutput, type SocketMessageMaps, type SocketOutboundPayload, } from './protocol.js';
@@ -11,6 +11,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
11
11
  };
12
12
  var _Connection_instances, _Connection_config, _Connection_url, _Connection_transforms, _Connection_pending, _Connection_handlers, _Connection_statusHandlers, _Connection_resyncHandlers, _Connection_subscribes, _Connection_acknowledged, _Connection_status, _Connection_ws, _Connection_generation, _Connection_nextId, _Connection_lastSeq, _Connection_attempt, _Connection_timer, _Connection_cancelRetry, _Connection_cancelPing, _Connection_lastReceivedAt, _Connection_send, _Connection_subscribe, _Connection_subscribed, _Connection_flush, _Connection_connect, _Connection_receive, _Connection_settle, _Connection_dispatch, _Connection_invoke, _Connection_disconnected, _Connection_abandon, _Connection_startPing, _Connection_stopTimers, _Connection_setStatus, _DurabilitySocketClient_config, _DurabilitySocketClient_transforms;
13
13
  import { reportFailure } from '../errors.js';
14
+ import { isString } from '../predicates.js';
14
15
  import { parseServerFrame, socketProtocolErrorCode, socketProtocolVersion, } from './protocol.js';
15
16
  import { SharedTimer } from '../shared-timer.js';
16
17
  import { exponential, jitter } from '../utils.js';
@@ -186,8 +187,10 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
186
187
  type: 'subscribe',
187
188
  id: `subscribe:${__classPrivateFieldSet(this, _Connection_nextId, (_a = __classPrivateFieldGet(this, _Connection_nextId, "f"), ++_a), "f")}`,
188
189
  names,
189
- ...(__classPrivateFieldGet(this, _Connection_lastSeq, "f") === undefined ? {} : { since: __classPrivateFieldGet(this, _Connection_lastSeq, "f") }),
190
190
  };
191
+ if (__classPrivateFieldGet(this, _Connection_lastSeq, "f") !== undefined) {
192
+ frame.since = __classPrivateFieldGet(this, _Connection_lastSeq, "f");
193
+ }
191
194
  __classPrivateFieldGet(this, _Connection_subscribes, "f").set(frame.id, names);
192
195
  __classPrivateFieldGet(this, _Connection_ws, "f")?.send(JSON.stringify(frame));
193
196
  }, _Connection_subscribed = function _Connection_subscribed(frame) {
@@ -243,7 +246,7 @@ _Connection_config = new WeakMap(), _Connection_url = new WeakMap(), _Connection
243
246
  if (!current()) {
244
247
  return;
245
248
  }
246
- __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_receive).call(this, typeof message.data === 'string' ? message.data : '');
249
+ __classPrivateFieldGet(this, _Connection_instances, "m", _Connection_receive).call(this, isString(message.data) ? message.data : '');
247
250
  });
248
251
  ws.addEventListener('close', (closed) => {
249
252
  if (!current()) {
@@ -403,11 +406,15 @@ export class DurabilitySocketClient {
403
406
  }
404
407
  connect(id) {
405
408
  const connection = new Connection(__classPrivateFieldGet(this, _DurabilitySocketClient_config, "f"), id, __classPrivateFieldGet(this, _DurabilitySocketClient_transforms, "f"));
409
+ // SAFETY: the get trap returns a method for every string key, so the
410
+ // empty target is never read.
406
411
  const rpc = new Proxy({}, {
407
- get: (_target, method) => typeof method === 'string'
412
+ get: (_target, method) => isString(method)
408
413
  ? (input) => connection.call(method, input)
409
414
  : undefined,
410
415
  });
416
+ // SAFETY: the get trap returns a subscriber for every string key, so the
417
+ // empty target is never read.
411
418
  const on = new Proxy({}, {
412
419
  get: (_target, name) => {
413
420
  if (name === 'status') {
@@ -416,7 +423,7 @@ export class DurabilitySocketClient {
416
423
  if (name === 'resync') {
417
424
  return (handler) => connection.onResync(handler);
418
425
  }
419
- return typeof name === 'string'
426
+ return isString(name)
420
427
  ? (handler) => connection.on(name, handler)
421
428
  : undefined;
422
429
  },
@@ -445,4 +452,4 @@ export const logging = (log = console.log) => async ({ method, input, next }) =>
445
452
  throw error;
446
453
  }
447
454
  };
448
- export { socketShape, } from './protocol.js';
455
+ export { socketMessageMaps, } from './protocol.js';
@@ -1,19 +1,17 @@
1
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
2
  import { type DurabilityMigrationResult } from '../migrations.js';
3
- import { type SocketInboundMap, type SocketOutboundMap, type SocketOutboundPayload, type SocketInboundMetadata, type SocketShape, socketShape } from './protocol.js';
3
+ import { type SocketInboundMap, type SocketInboundSchemas, type SocketOutboundMap, type SocketOutboundPayload, type SocketInboundMetadata, type SocketMessageMaps, type SocketValidatedInbound, socketMessageMaps } from './protocol.js';
4
4
  /** The Durable Object state a socket needs: SQLite storage and hibernatable WebSockets. */
5
5
  export type DurabilitySocketContext = Pick<DurableObjectState, 'storage' | 'acceptWebSocket' | 'getWebSockets' | 'setWebSocketAutoResponse'>;
6
- export type DurabilitySocketConfig<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound>> = {
6
+ export type DurabilitySocketConfig<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound>, Schemas extends Record<keyof Inbound, StandardSchemaV1> = SocketInboundSchemas<Inbound>> = {
7
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
8
  /**
13
- * Captures trusted per-connection data from the upgrade request. Stored in
14
- * the WebSocket attachment, so it survives hibernation without re-auth.
9
+ * Methods clients may call, keyed by the names they become on the client.
10
+ * Each validates its input with a Standard Schema before `handle` runs.
15
11
  */
16
- metadata?: (request: Request) => Metadata | Promise<Metadata>;
12
+ inbound: Inbound & SocketValidatedInbound<Inbound, Schemas>;
13
+ /** Events the object may push, keyed by the methods they become on this instance. */
14
+ outbound: Outbound;
17
15
  /** Outbound events kept for replay to reconnecting clients. Defaults to 1000. */
18
16
  retention?: number;
19
17
  /**
@@ -23,7 +21,16 @@ export type DurabilitySocketConfig<Inbound extends SocketInboundMap, Outbound ex
23
21
  * whichever instance `webSocketMessage` delegates to.
24
22
  */
25
23
  channel?: string;
24
+ } & SocketMetadataOption<Metadata>;
25
+ type SocketMetadataConfig<Metadata> = {
26
+ /**
27
+ * Captures trusted per-connection data from the upgrade request. Stored in
28
+ * the WebSocket attachment, so it survives hibernation without re-auth.
29
+ * Required when a handler's `SocketCall<…>` metadata excludes `undefined`.
30
+ */
31
+ metadata: (request: Request) => Metadata | Promise<Metadata>;
26
32
  };
33
+ type SocketMetadataOption<Metadata> = undefined extends Metadata ? Partial<SocketMetadataConfig<Metadata>> : SocketMetadataConfig<Metadata>;
27
34
  /** Thrown to the caller when an inbound payload fails its schema. */
28
35
  export declare class SocketInputError extends Error {
29
36
  readonly issues: readonly StandardSchemaV1.Issue[];
@@ -31,7 +38,7 @@ export declare class SocketInputError extends Error {
31
38
  }
32
39
  declare class DurabilitySocketCore<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound>> {
33
40
  #private;
34
- readonly [socketShape]: SocketShape<Inbound, Outbound>;
41
+ readonly [socketMessageMaps]: SocketMessageMaps<Inbound, Outbound>;
35
42
  constructor(config: DurabilitySocketConfig<Inbound, Outbound, Metadata>);
36
43
  /** Applies or reverts the `durability_socket_events` schema. */
37
44
  static migrate(context: Pick<DurableObjectState, 'storage'>, target?: string | null): DurabilityMigrationResult;
@@ -67,10 +74,10 @@ type OutboundMethods<Outbound extends SocketOutboundMap> = {
67
74
  * readonly socket = new DurabilitySocket({
68
75
  * context: this.ctx,
69
76
  * inbound: {
70
- * list: () => this.repo.list(),
77
+ * list: { input: v.undefined(), handle: () => this.repo.list() },
71
78
  * create: {
72
79
  * input: TodoSchema,
73
- * handle: async (todo: Todo) => {
80
+ * handle: async (todo) => {
74
81
  * await this.repo.insert(todo);
75
82
  * this.socket.created(todo);
76
83
  * },
@@ -95,7 +102,7 @@ type OutboundMethods<Outbound extends SocketOutboundMap> = {
95
102
  */
96
103
  export type DurabilitySocket<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound> = SocketInboundMetadata<Inbound>> = DurabilitySocketCore<Inbound, Outbound, Metadata> & OutboundMethods<Outbound>;
97
104
  export interface DurabilitySocketConstructor {
98
- new <Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound> = SocketInboundMetadata<Inbound>>(config: DurabilitySocketConfig<Inbound, Outbound, Metadata>): DurabilitySocket<Inbound, Outbound, Metadata>;
105
+ new <Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap, Metadata extends SocketInboundMetadata<Inbound> = SocketInboundMetadata<Inbound>, Schemas extends Record<keyof Inbound, StandardSchemaV1> = SocketInboundSchemas<Inbound>>(config: DurabilitySocketConfig<Inbound, Outbound, Metadata, Schemas>): DurabilitySocket<Inbound, Outbound, Metadata>;
99
106
  migrate: typeof DurabilitySocketCore.migrate;
100
107
  }
101
108
  export declare const DurabilitySocket: DurabilitySocketConstructor;
@@ -15,6 +15,7 @@ import { reportFailure, serializeError } from '../errors.js';
15
15
  import { durabilitySocketMigrations } from './migrations.js';
16
16
  import { migrateCapability, } from '../migrations.js';
17
17
  import { assertChannel, defaultChannel, engineFor, } from '../scheduler/index.js';
18
+ import { isObject, isString } from '../predicates.js';
18
19
  import { deserialize, serialize } from '../serialization.js';
19
20
  import { parseClientFrame, socketMaxFrameLength, socketProtocolErrorCode, socketProtocolVersion, } from './protocol.js';
20
21
  /** Thrown to the caller when an inbound payload fails its schema. */
@@ -29,6 +30,8 @@ export class SocketInputError extends Error {
29
30
  const frameHandlersByObject = new WeakMap();
30
31
  // A configuration problem rather than a protocol violation, so clients reconnect.
31
32
  const channelMissingCloseCode = 1011;
33
+ // Service Restart: the client reconnects, and the new upgrade captures metadata.
34
+ const metadataMissingCloseCode = 1012;
32
35
  const reservedOutboundNames = new Set(['status', 'resync']);
33
36
  const sendFrame = (ws, frame) => {
34
37
  trace('socket.send', { frame });
@@ -57,22 +60,26 @@ const sendFrame = (ws, frame) => {
57
60
  };
58
61
  const readAttachment = (ws) => {
59
62
  const stored = ws.deserializeAttachment();
60
- if (typeof stored !== 'object' || stored === null) {
63
+ if (!isObject(stored)) {
61
64
  return {
62
65
  metadata: undefined,
66
+ hasMetadata: false,
63
67
  names: [],
64
68
  channel: defaultChannel,
65
69
  };
66
70
  }
67
- const names = Reflect.get(stored, 'names');
71
+ const metadata = 'metadata' in stored ? stored.metadata : undefined;
72
+ const names = 'names' in stored ? stored.names : undefined;
68
73
  // Connections accepted before channels existed carry no channel.
69
- const channel = Reflect.get(stored, 'channel');
74
+ const channel = 'channel' in stored ? stored.channel : undefined;
70
75
  return {
71
- metadata: Reflect.get(stored, 'metadata'),
72
- names: Array.isArray(names)
73
- ? names.filter((name) => typeof name === 'string')
74
- : [],
75
- channel: typeof channel === 'string' ? channel : defaultChannel,
76
+ metadata,
77
+ // Attachments written before `hasMetadata` existed captured metadata if they hold any.
78
+ hasMetadata: 'hasMetadata' in stored
79
+ ? stored.hasMetadata === true
80
+ : metadata !== undefined,
81
+ names: Array.isArray(names) ? names.filter(isString) : [],
82
+ channel: isString(channel) ? channel : defaultChannel,
76
83
  };
77
84
  };
78
85
  class DurabilitySocketCore {
@@ -137,6 +144,7 @@ class DurabilitySocketCore {
137
144
  __classPrivateFieldGet(this, _DurabilitySocketCore_context, "f").acceptWebSocket(server);
138
145
  server.serializeAttachment({
139
146
  metadata,
147
+ hasMetadata: __classPrivateFieldGet(this, _DurabilitySocketCore_metadata, "f") !== undefined,
140
148
  names: [],
141
149
  channel: __classPrivateFieldGet(this, _DurabilitySocketCore_channel, "f"),
142
150
  });
@@ -148,7 +156,9 @@ class DurabilitySocketCore {
148
156
  * channel, which need not be this one.
149
157
  */
150
158
  async webSocketMessage(ws, message) {
151
- const text = typeof message === 'string' ? message : new TextDecoder().decode(message);
159
+ const text = isString(message)
160
+ ? message
161
+ : new TextDecoder().decode(message);
152
162
  const frame = parseClientFrame(text);
153
163
  if (!frame) {
154
164
  trace('socket.close', {
@@ -179,6 +189,16 @@ class DurabilitySocketCore {
179
189
  webSocketClose(_ws) { }
180
190
  }
181
191
  _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = new WeakMap(), _DurabilitySocketCore_inbound = new WeakMap(), _DurabilitySocketCore_outboundNames = new WeakMap(), _DurabilitySocketCore_metadata = new WeakMap(), _DurabilitySocketCore_retention = new WeakMap(), _DurabilitySocketCore_channel = new WeakMap(), _DurabilitySocketCore_frameHandlers = new WeakMap(), _DurabilitySocketCore_instances = new WeakSet(), _DurabilitySocketCore_handle = async function _DurabilitySocketCore_handle(ws, frame) {
192
+ // A connection accepted before this socket captured metadata, such as
193
+ // before a deploy added it, must not reach a handler without it.
194
+ if (__classPrivateFieldGet(this, _DurabilitySocketCore_metadata, "f") !== undefined && !readAttachment(ws).hasMetadata) {
195
+ trace('socket.close', {
196
+ code: metadataMissingCloseCode,
197
+ reason: 'Socket metadata was not captured',
198
+ });
199
+ ws.close(metadataMissingCloseCode, 'Socket metadata was not captured');
200
+ return;
201
+ }
182
202
  if (frame.type === 'subscribe') {
183
203
  __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_subscribe).call(this, ws, frame);
184
204
  return;
@@ -199,12 +219,15 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = n
199
219
  return;
200
220
  }
201
221
  const call = {
222
+ // SAFETY: #inbound erases each handler's metadata type to never. With
223
+ // config.metadata set, #handle closed every connection whose attachment
224
+ // lacks its result; without it, the handlers' metadata admits undefined.
202
225
  metadata: readAttachment(ws).metadata,
203
226
  };
204
227
  try {
205
- const output = typeof handler === 'function'
206
- ? await handler(frame.input, call)
207
- : await handler.handle((await __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_validate).call(this, frame.method, handler.input, frame.input)), call);
228
+ // SAFETY: the input passed handler.input, and SocketValidatedInbound
229
+ // requires each handle to accept its own schema's output.
230
+ const output = await handler.handle((await __classPrivateFieldGet(this, _DurabilitySocketCore_instances, "m", _DurabilitySocketCore_validate).call(this, frame, handler.input)), call);
208
231
  sendFrame(ws, {
209
232
  v: socketProtocolVersion,
210
233
  type: 'result',
@@ -220,10 +243,10 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = n
220
243
  error: serializeError(error),
221
244
  });
222
245
  }
223
- }, _DurabilitySocketCore_validate = async function _DurabilitySocketCore_validate(method, schema, input) {
224
- const result = await schema['~standard'].validate(input);
246
+ }, _DurabilitySocketCore_validate = async function _DurabilitySocketCore_validate(frame, schema) {
247
+ const result = await schema['~standard'].validate(frame.input);
225
248
  if (result.issues) {
226
- throw new SocketInputError(method, result.issues);
249
+ throw new SocketInputError(frame.method, result.issues);
227
250
  }
228
251
  return result.value;
229
252
  }, _DurabilitySocketCore_subscribe = function _DurabilitySocketCore_subscribe(ws, frame) {
@@ -320,9 +343,8 @@ _DurabilitySocketCore_context = new WeakMap(), _DurabilitySocketCore_storage = n
320
343
  }
321
344
  };
322
345
  traceMethods(DurabilitySocketCore.prototype, 'DurabilitySocket');
323
- // TypeScript cannot declare class members derived from a generic event map,
324
- // so the constructor is typed separately; the constructor installs and
325
- // reserves every outbound method at runtime.
346
+ // SAFETY: the constructor defines a method for every outbound event name on the
347
+ // instance, members TypeScript cannot declare from a generic event map.
326
348
  export const DurabilitySocket = DurabilitySocketCore;
327
349
  export { durabilitySocketMigrations } from './migrations.js';
328
350
  export { event, } from './protocol.js';
@@ -51,22 +51,28 @@ export type SocketCall<Metadata> = {
51
51
  metadata: Metadata;
52
52
  };
53
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.
54
+ * An inbound handler: a Standard Schema that validates the call's input, and
55
+ * `handle`, which receives the validated value.
56
56
  */
57
- export type SocketInboundHandler<Metadata> = ((input: unknown, call: SocketCall<Metadata>) => unknown) | {
57
+ export type SocketInboundHandler<Metadata> = {
58
58
  input: StandardSchemaV1;
59
59
  handle: (input: never, call: SocketCall<Metadata>) => unknown;
60
60
  };
61
61
  export type SocketInboundMap<Metadata = never> = Record<string, SocketInboundHandler<Metadata>>;
62
+ /** An unannotated `call` is `SocketCall<never>`, which constrains nothing. */
62
63
  type HandlerMetadata<Handler> = Handler extends {
63
64
  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]>;
65
+ } ? [Metadata] extends [never] ? unknown : Metadata : unknown;
66
+ type MetadataSinks<Inbound> = {
67
+ [Name in keyof Inbound]: (metadata: HandlerMetadata<Inbound[Name]>) => void;
68
+ }[keyof Inbound];
69
+ /**
70
+ * The metadata every inbound handler in the map can accept: the intersection
71
+ * of each handler's metadata, keeping a union such as `User | undefined` whole.
72
+ */
73
+ export type SocketInboundMetadata<Inbound> = [MetadataSinks<Inbound>] extends [
74
+ (metadata: infer Metadata) => void
75
+ ] ? Metadata : unknown;
70
76
  /** Marks an outbound event and carries its payload type. */
71
77
  export type SocketOutboundEvent<Payload> = {
72
78
  readonly payload?: Payload;
@@ -74,22 +80,36 @@ export type SocketOutboundEvent<Payload> = {
74
80
  export type SocketOutboundMap = Record<string, SocketOutboundEvent<unknown>>;
75
81
  /** Declares an outbound event with the given payload type. */
76
82
  export declare const event: <Payload>() => SocketOutboundEvent<Payload>;
83
+ /** The schema of each inbound handler, by method. */
84
+ export type SocketInboundSchemas<Inbound extends SocketInboundMap> = {
85
+ [Name in keyof Inbound]: Inbound[Name]['input'];
86
+ };
87
+ /**
88
+ * Requires each handler to accept its schema's output. `Schemas` is inferred
89
+ * from the schemas alone, so `handle` parameters need no annotation.
90
+ */
91
+ export type SocketValidatedInbound<Inbound extends SocketInboundMap, Schemas extends Record<keyof Inbound, StandardSchemaV1>> = {
92
+ [Name in keyof Schemas]: {
93
+ input: Schemas[Name];
94
+ handle: (input: StandardSchemaV1.InferOutput<Schemas[Name]>, call: SocketCall<never>) => ReturnType<Inbound[Name & keyof Inbound]['handle']>;
95
+ };
96
+ };
77
97
  export type SocketInboundInput<Handler> = Handler extends {
78
98
  input: infer Schema extends StandardSchemaV1;
79
- } ? StandardSchemaV1.InferInput<Schema> : Handler extends (...args: infer Args) => unknown ? Args extends [] ? void : Args[0] : never;
99
+ } ? StandardSchemaV1.InferInput<Schema> : never;
80
100
  export type SocketInboundOutput<Handler> = Handler extends {
81
101
  handle: (...args: never[]) => infer Result;
82
- } ? Awaited<Result> : Handler extends (...args: never[]) => infer Result ? Awaited<Result> : never;
102
+ } ? Awaited<Result> : never;
83
103
  export type SocketOutboundPayload<Event> = Event extends SocketOutboundEvent<infer Payload> ? Payload : never;
84
- export declare const socketShape: unique symbol;
104
+ export declare const socketMessageMaps: unique symbol;
85
105
  /** Phantom type a server socket carries so clients can derive its surface. */
86
- export type SocketShape<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap> = {
106
+ export type SocketMessageMaps<Inbound extends SocketInboundMap, Outbound extends SocketOutboundMap> = {
87
107
  inbound: Inbound;
88
108
  outbound: Outbound;
89
109
  };
90
- export type AnySocketShape = {
91
- readonly [socketShape]: SocketShape<SocketInboundMap, SocketOutboundMap>;
110
+ export type AnyDurabilitySocket = {
111
+ readonly [socketMessageMaps]: SocketMessageMaps<SocketInboundMap, SocketOutboundMap>;
92
112
  };
93
- export type InboundOf<Socket extends AnySocketShape> = Socket[typeof socketShape]['inbound'];
94
- export type OutboundOf<Socket extends AnySocketShape> = Socket[typeof socketShape]['outbound'];
113
+ export type InboundOf<Socket extends AnyDurabilitySocket> = Socket[typeof socketMessageMaps]['inbound'];
114
+ export type OutboundOf<Socket extends AnyDurabilitySocket> = Socket[typeof socketMessageMaps]['outbound'];
95
115
  export {};
@@ -1,11 +1,11 @@
1
+ import { isJsonObject, isString } from '../predicates.js';
1
2
  export const socketProtocolVersion = 1;
2
3
  /** Largest text frame either side accepts, in UTF-16 code units. */
3
4
  export const socketMaxFrameLength = 1024 * 1024;
4
5
  /** Close code sent when the peer violates the wire protocol; clients must not retry. */
5
6
  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) &&
7
+ const isStringArray = (value) => Array.isArray(value) && value.every(isString);
8
+ const isSerializedError = (value) => isJsonObject(value) &&
9
9
  typeof value['name'] === 'string' &&
10
10
  typeof value['message'] === 'string';
11
11
  const parseFrame = (text) => {
@@ -19,53 +19,47 @@ const parseFrame = (text) => {
19
19
  catch {
20
20
  return undefined;
21
21
  }
22
- if (!isRecord(parsed) || parsed['v'] !== socketProtocolVersion) {
22
+ if (!isJsonObject(parsed) || parsed['v'] !== socketProtocolVersion) {
23
23
  return undefined;
24
24
  }
25
25
  return parsed;
26
26
  };
27
- export const parseClientFrame = (text) => {
28
- const frame = parseFrame(text);
29
- if (!frame || typeof frame['id'] !== 'string') {
30
- return undefined;
27
+ // `parseFrame` has already checked the protocol version.
28
+ const isClientFrame = (frame) => {
29
+ if (typeof frame['id'] !== 'string') {
30
+ return false;
31
31
  }
32
- if (frame['type'] === 'call' && typeof frame['method'] === 'string') {
33
- return frame;
32
+ if (frame['type'] === 'call') {
33
+ return typeof frame['method'] === 'string';
34
34
  }
35
- if (frame['type'] === 'subscribe' &&
35
+ return (frame['type'] === 'subscribe' &&
36
36
  isStringArray(frame['names']) &&
37
- (frame['since'] === undefined || Number.isSafeInteger(frame['since']))) {
38
- return frame;
39
- }
40
- return undefined;
37
+ (frame['since'] === undefined || Number.isSafeInteger(frame['since'])));
41
38
  };
42
- export const parseServerFrame = (text) => {
43
- const frame = parseFrame(text);
44
- if (!frame) {
45
- return undefined;
46
- }
39
+ const isServerFrame = (frame) => {
47
40
  if (frame['type'] === 'event') {
48
- return Number.isSafeInteger(frame['seq']) &&
49
- typeof frame['name'] === 'string'
50
- ? frame
51
- : undefined;
41
+ return (Number.isSafeInteger(frame['seq']) && typeof frame['name'] === 'string');
52
42
  }
53
43
  if (typeof frame['id'] !== 'string') {
54
- return undefined;
55
- }
56
- if (frame['type'] === 'result') {
57
- return frame;
44
+ return false;
58
45
  }
59
- if (frame['type'] === 'error' && isSerializedError(frame['error'])) {
60
- return frame;
46
+ if (frame['type'] === 'error') {
47
+ return isSerializedError(frame['error']);
61
48
  }
62
- if (frame['type'] === 'subscribed' &&
63
- Number.isSafeInteger(frame['seq']) &&
64
- typeof frame['replayed'] === 'boolean') {
65
- return frame;
49
+ if (frame['type'] === 'subscribed') {
50
+ return (Number.isSafeInteger(frame['seq']) &&
51
+ typeof frame['replayed'] === 'boolean');
66
52
  }
67
- return undefined;
53
+ return frame['type'] === 'result';
54
+ };
55
+ export const parseClientFrame = (text) => {
56
+ const frame = parseFrame(text);
57
+ return frame && isClientFrame(frame) ? frame : undefined;
58
+ };
59
+ export const parseServerFrame = (text) => {
60
+ const frame = parseFrame(text);
61
+ return frame && isServerFrame(frame) ? frame : undefined;
68
62
  };
69
63
  /** Declares an outbound event with the given payload type. */
70
64
  export const event = () => ({});
71
- export const socketShape = Symbol('durability.socket');
65
+ export const socketMessageMaps = Symbol('durability.socket');
@@ -12,6 +12,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
12
12
  var _TopologyClient_instances, _TopologyClient_config, _TopologyClient_readTimeoutMs, _TopologyClient_ttlMs, _TopologyClient_negativeTtlMs, _TopologyClient_cache, _TopologyClient_inflight, _TopologyClient_load, _TopologyClient_read, _TopologyClient_fallback, _TopologyClient_remember;
13
13
  import { TopologyUnavailableError, } from '../errors.js';
14
14
  import { assertPositiveInteger } from '../policy.js';
15
+ import { isFunction } from '../predicates.js';
15
16
  import { decodeSnapshot, } from './snapshot.js';
16
17
  // High-cardinality groups (one per tenant) must not grow an isolate without bound; the least recently used go first.
17
18
  const maxCachedGroups = 1024;
@@ -28,7 +29,7 @@ export class TopologyClient {
28
29
  _TopologyClient_negativeTtlMs.set(this, void 0);
29
30
  _TopologyClient_cache.set(this, new Map());
30
31
  _TopologyClient_inflight.set(this, new Map());
31
- if (typeof config.read !== 'function') {
32
+ if (!isFunction(config.read)) {
32
33
  throw new TypeError('A topology client needs a read function');
33
34
  }
34
35
  __classPrivateFieldSet(this, _TopologyClient_readTimeoutMs, config.readTimeoutMs ?? 1000, "f");
@@ -106,15 +107,17 @@ _TopologyClient_config = new WeakMap(), _TopologyClient_readTimeoutMs = new Weak
106
107
  failure = result.failure;
107
108
  }
108
109
  const entry = {
109
- // A missing group is not an error, so nothing stale may be served for it.
110
- ...(failure.reason === 'missing' || !previous?.view
111
- ? {}
112
- : { view: previous.view }),
113
- ...(previous?.newestSeen ? { newestSeen: previous.newestSeen } : {}),
114
110
  staleUntil: previous?.staleUntil ?? 0,
115
111
  expiresAt: now + jittered(__classPrivateFieldGet(this, _TopologyClient_negativeTtlMs, "f")),
116
112
  failure,
117
113
  };
114
+ // A missing group is not an error, so nothing stale may be served for it.
115
+ if (failure.reason !== 'missing' && previous?.view) {
116
+ entry.view = previous.view;
117
+ }
118
+ if (previous?.newestSeen) {
119
+ entry.newestSeen = previous.newestSeen;
120
+ }
118
121
  __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_remember).call(this, group, entry);
119
122
  return __classPrivateFieldGet(this, _TopologyClient_instances, "m", _TopologyClient_fallback).call(this, group, entry);
120
123
  }, _TopologyClient_read = async function _TopologyClient_read(group) {
@@ -23,13 +23,13 @@ export type TopologyStateUpdate<Value> = {
23
23
  };
24
24
  export type TopologyPublisher<Meta> = TopologyRetryOptions & {
25
25
  /** Must be idempotent. Store `encoded` as is: it is what the client reads. */
26
- write(snapshot: TopologySnapshot<Meta>, encoded: string): Promise<unknown>;
27
- delete(group: string, version: number): Promise<unknown>;
26
+ write(snapshot: TopologySnapshot<Meta>, encoded: string): Promise<void>;
27
+ delete(group: string, version: number): Promise<void>;
28
28
  };
29
29
  export type TopologyChannel<Value, Meta> = TopologyRetryOptions & {
30
30
  /** Defaults to `write`. */
31
31
  members?: TopologyRole;
32
- deliver(member: TopologyMember<Meta>, update: TopologyStateUpdate<Value>): unknown;
32
+ deliver(member: TopologyMember<Meta>, update: TopologyStateUpdate<Value>): void | Promise<void>;
33
33
  };
34
34
  /**
35
35
  * Publication and sync run on outbox channels keyed by group and by