@replit/river 0.207.2 → 0.208.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 (65) hide show
  1. package/dist/adapter-ChksXKVN.d.ts +46 -0
  2. package/dist/adapter-Cuc4JtfV.d.cts +46 -0
  3. package/dist/chunk-2JNVDUMN.js +2238 -0
  4. package/dist/chunk-2JNVDUMN.js.map +1 -0
  5. package/dist/{chunk-4HE7UYRL.js → chunk-DKW3GC3M.js} +6 -5
  6. package/dist/{chunk-4HE7UYRL.js.map → chunk-DKW3GC3M.js.map} +1 -1
  7. package/dist/{chunk-46IVOKJU.js → chunk-ETZAHFGQ.js} +80 -61
  8. package/dist/chunk-ETZAHFGQ.js.map +1 -0
  9. package/dist/codec/index.cjs +157 -23
  10. package/dist/codec/index.cjs.map +1 -1
  11. package/dist/codec/index.d.cts +5 -1
  12. package/dist/codec/index.d.ts +5 -1
  13. package/dist/codec/index.js +6 -20
  14. package/dist/codec/index.js.map +1 -1
  15. package/dist/connection-BF4zg6Qv.d.cts +35 -0
  16. package/dist/{connection-a18e31d5.d.ts → connection-Donr3JRB.d.ts} +4 -3
  17. package/dist/index-C9tpZjBN.d.cts +37 -0
  18. package/dist/index-D8IOd3LG.d.ts +37 -0
  19. package/dist/logging/index.d.cts +2 -1
  20. package/dist/logging/index.d.ts +2 -1
  21. package/dist/{message-ffacb98a.d.ts → message-Di94OL80.d.cts} +1 -35
  22. package/dist/message-Di94OL80.d.ts +108 -0
  23. package/dist/router/index.cjs +62 -43
  24. package/dist/router/index.cjs.map +1 -1
  25. package/dist/router/index.d.cts +27 -7
  26. package/dist/router/index.d.ts +27 -7
  27. package/dist/router/index.js +1 -1
  28. package/dist/testUtil/index.cjs +828 -725
  29. package/dist/testUtil/index.cjs.map +1 -1
  30. package/dist/testUtil/index.d.cts +5 -4
  31. package/dist/testUtil/index.d.ts +5 -4
  32. package/dist/testUtil/index.js +23 -25
  33. package/dist/testUtil/index.js.map +1 -1
  34. package/dist/transport/impls/ws/client.cjs +293 -233
  35. package/dist/transport/impls/ws/client.cjs.map +1 -1
  36. package/dist/transport/impls/ws/client.d.cts +6 -5
  37. package/dist/transport/impls/ws/client.d.ts +6 -5
  38. package/dist/transport/impls/ws/client.js +5 -7
  39. package/dist/transport/impls/ws/client.js.map +1 -1
  40. package/dist/transport/impls/ws/server.cjs +269 -200
  41. package/dist/transport/impls/ws/server.cjs.map +1 -1
  42. package/dist/transport/impls/ws/server.d.cts +6 -5
  43. package/dist/transport/impls/ws/server.d.ts +6 -5
  44. package/dist/transport/impls/ws/server.js +5 -7
  45. package/dist/transport/impls/ws/server.js.map +1 -1
  46. package/dist/transport/index.cjs +438 -342
  47. package/dist/transport/index.cjs.map +1 -1
  48. package/dist/transport/index.d.cts +7 -6
  49. package/dist/transport/index.d.ts +7 -6
  50. package/dist/transport/index.js +5 -10
  51. package/dist/transport-CCaWx1Rb.d.cts +1566 -0
  52. package/dist/{services-43528f4b.d.ts → transport-CZb3vdB4.d.ts} +294 -293
  53. package/dist/{wslike-e0b32dd5.d.ts → wslike-Dng9H1C7.d.cts} +1 -1
  54. package/dist/wslike-Dng9H1C7.d.ts +40 -0
  55. package/package.json +3 -3
  56. package/dist/chunk-24EWYOGK.js +0 -1287
  57. package/dist/chunk-24EWYOGK.js.map +0 -1
  58. package/dist/chunk-46IVOKJU.js.map +0 -1
  59. package/dist/chunk-A7RGOVRV.js +0 -438
  60. package/dist/chunk-A7RGOVRV.js.map +0 -1
  61. package/dist/chunk-AJGIY2UB.js +0 -56
  62. package/dist/chunk-AJGIY2UB.js.map +0 -1
  63. package/dist/chunk-XV4RQ62N.js +0 -377
  64. package/dist/chunk-XV4RQ62N.js.map +0 -1
  65. package/dist/types-3e5768ec.d.ts +0 -20
@@ -1,46 +1,44 @@
1
1
  import * as _sinclair_typebox from '@sinclair/typebox';
2
- import { Static, TSchema, TObject, TString, TUnion, TLiteral, TNever } from '@sinclair/typebox';
2
+ import { TSchema, Static, TNever, TObject, TLiteral, TString, TUnion } from '@sinclair/typebox';
3
3
  import { Tracer, Span } from '@opentelemetry/api';
4
- import { c as TelemetryInfo, M as MessageMetadata, T as TransportClientId, L as Logger, O as OpaqueTransportMessage, P as ProtocolVersion, b as PartialTransportMessage, d as TransportMessage, a as Tags, H as HandshakeErrorResponseCodes, e as LogFn, f as LoggingLevel, g as HandshakeErrorCustomHandlerFatalResponseCodes } from './message-ffacb98a.js';
5
- import { C as Codec } from './types-3e5768ec.js';
4
+ import { b as TelemetryInfo, T as TransportClientId, P as ProtocolVersion, O as OpaqueTransportMessage, a as PartialTransportMessage, c as TransportMessage, H as HandshakeErrorCustomHandlerFatalResponseCodes, d as HandshakeErrorResponseCodes } from './message-Di94OL80.js';
5
+ import { M as MessageMetadata, L as Logger, T as Tags, a as LogFn, b as LoggingLevel } from './index-D8IOd3LG.js';
6
+ import { C as Codec, a as CodecMessageAdapter, S as SendResult, b as SendBufferResult } from './adapter-ChksXKVN.js';
6
7
 
7
8
  /**
8
9
  * A connection is the actual raw underlying transport connection.
9
- * Its responsible for dispatching to/from the actual connection itself
10
+ * It's responsible for dispatching to/from the actual connection itself
10
11
  * This should be instantiated as soon as the client/server has a connection
11
- * Its tied to the lifecycle of the underlying transport connection (i.e. if the WS drops, this connection should be deleted)
12
+ * It's tied to the lifecycle of the underlying transport connection (i.e. if the WS drops, this connection should be deleted)
12
13
  */
13
14
  declare abstract class Connection {
14
15
  id: string;
15
16
  telemetry?: TelemetryInfo;
16
17
  constructor();
17
18
  get loggingMetadata(): MessageMetadata;
18
- private _dataListeners;
19
- private _closeListeners;
20
- private _errorListeners;
21
- get dataListeners(): ((msg: Uint8Array) => void)[];
22
- get closeListeners(): (() => void)[];
23
- get errorListeners(): ((err: Error) => void)[];
19
+ dataListener?: (msg: Uint8Array) => void;
20
+ closeListener?: () => void;
21
+ errorListener?: (err: Error) => void;
24
22
  onData(msg: Uint8Array): void;
25
23
  onError(err: Error): void;
26
24
  onClose(): void;
27
25
  /**
28
- * Handle adding a callback for when a message is received.
29
- * @param msg The message that was received.
26
+ * Set the callback for when a message is received.
27
+ * @param cb The message handler callback.
30
28
  */
31
- addDataListener(cb: (msg: Uint8Array) => void): void;
32
- removeDataListener(cb: (msg: Uint8Array) => void): void;
29
+ setDataListener(cb: (msg: Uint8Array) => void): void;
30
+ removeDataListener(): void;
33
31
  /**
34
- * Handle adding a callback for when the connection is closed.
35
- * This should also be called if an error happens and after notifying all the error listeners.
32
+ * Set the callback for when the connection is closed.
33
+ * This should also be called if an error happens and after notifying the error listener.
36
34
  * @param cb The callback to call when the connection is closed.
37
35
  */
38
- addCloseListener(cb: () => void): void;
39
- removeCloseListener(cb: () => void): void;
36
+ setCloseListener(cb: () => void): void;
37
+ removeCloseListener(): void;
40
38
  /**
41
- * Handle adding a callback for when an error is received.
42
- * This should only be used for this.logging errors, all cleanup
43
- * should be delegated to addCloseListener.
39
+ * Set the callback for when an error is received.
40
+ * This should only be used for logging errors, all cleanup
41
+ * should be delegated to setCloseListener.
44
42
  *
45
43
  * The implementer should take care such that the implemented
46
44
  * connection will call both the close and error callbacks
@@ -48,8 +46,8 @@ declare abstract class Connection {
48
46
  *
49
47
  * @param cb The callback to call when an error is received.
50
48
  */
51
- addErrorListener(cb: (err: Error) => void): void;
52
- removeErrorListener(cb: (err: Error) => void): void;
49
+ setErrorListener(cb: (err: Error) => void): void;
50
+ removeErrorListener(): void;
53
51
  /**
54
52
  * Sends a message over the connection.
55
53
  * @param msg The message to send.
@@ -124,17 +122,18 @@ interface SessionOptions {
124
122
  interface CommonSessionProps {
125
123
  from: TransportClientId;
126
124
  options: SessionOptions;
125
+ codec: CodecMessageAdapter;
127
126
  tracer: Tracer;
128
127
  log: Logger | undefined;
129
128
  }
130
129
  declare abstract class CommonSession extends StateMachineState {
131
130
  readonly from: TransportClientId;
132
131
  readonly options: SessionOptions;
132
+ readonly codec: CodecMessageAdapter;
133
133
  tracer: Tracer;
134
134
  log?: Logger;
135
135
  abstract get loggingMetadata(): MessageMetadata;
136
- constructor({ from, options, log, tracer }: CommonSessionProps);
137
- parseMsg(msg: Uint8Array): OpaqueTransportMessage | null;
136
+ constructor({ from, options, log, tracer, codec }: CommonSessionProps);
138
137
  }
139
138
  type SessionId = string;
140
139
  interface IdentifiedSessionProps extends CommonSessionProps {
@@ -169,7 +168,7 @@ declare abstract class IdentifiedSession extends CommonSession {
169
168
  get loggingMetadata(): MessageMetadata;
170
169
  constructMsg<Payload>(partialMsg: PartialTransportMessage<Payload>): TransportMessage<Payload>;
171
170
  nextSeq(): number;
172
- send(msg: PartialTransportMessage): string;
171
+ send(msg: PartialTransportMessage): SendResult;
173
172
  _handleStateExit(): void;
174
173
  _handleClose(): void;
175
174
  }
@@ -189,6 +188,100 @@ declare abstract class IdentifiedSessionWithGracePeriod extends IdentifiedSessio
189
188
  _handleClose(): void;
190
189
  }
191
190
 
191
+ type ConstructHandshake<T extends TSchema> = () => Static<T> | Promise<Static<T>>;
192
+ type ValidateHandshake<T extends TSchema> = (metadata: Static<T>, previousParsedMetadata?: ParsedMetadata) => Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata | Promise<Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata>;
193
+ interface ClientHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
194
+ /**
195
+ * Schema for the metadata that the client sends to the server
196
+ * during the handshake.
197
+ */
198
+ schema: MetadataSchema;
199
+ /**
200
+ * Gets the {@link HandshakeRequestMetadata} to send to the server.
201
+ */
202
+ construct: ConstructHandshake<MetadataSchema>;
203
+ }
204
+ interface ServerHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
205
+ /**
206
+ * Schema for the metadata that the server receives from the client
207
+ * during the handshake.
208
+ */
209
+ schema: MetadataSchema;
210
+ /**
211
+ * Parses the {@link HandshakeRequestMetadata} sent by the client, transforming
212
+ * it into {@link ParsedHandshakeMetadata}.
213
+ *
214
+ * May return `false` if the client should be rejected.
215
+ *
216
+ * @param metadata - The metadata sent by the client.
217
+ * @param session - The session that the client would be associated with.
218
+ * @param isReconnect - Whether the client is reconnecting to the session,
219
+ * or if this is a new session.
220
+ */
221
+ validate: ValidateHandshake<MetadataSchema>;
222
+ }
223
+ declare function createClientHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, construct: ConstructHandshake<MetadataSchema>): ClientHandshakeOptions;
224
+ declare function createServerHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, validate: ValidateHandshake<MetadataSchema>): ServerHandshakeOptions;
225
+
226
+ /**
227
+ * Options to control the backoff and retry behavior of the client transport's connection behaviour.
228
+ *
229
+ * River implements exponential backoff with jitter to prevent flooding the server
230
+ * when there's an issue with connection establishment.
231
+ *
232
+ * The backoff is calculated via the following:
233
+ * backOff = min(jitter + {@link baseIntervalMs} * 2 ^ budget_consumed, {@link maxBackoffMs})
234
+ *
235
+ * We use a leaky bucket rate limit with a budget of {@link attemptBudgetCapacity} reconnection attempts.
236
+ * Budget only starts to restore after a successful handshake at a rate of one budget per {@link budgetRestoreIntervalMs}.
237
+ */
238
+ interface ConnectionRetryOptions {
239
+ /**
240
+ * The base interval to wait before retrying a connection.
241
+ */
242
+ baseIntervalMs: number;
243
+ /**
244
+ * The maximum random jitter to add to the total backoff time.
245
+ */
246
+ maxJitterMs: number;
247
+ /**
248
+ * The maximum amount of time to wait before retrying a connection.
249
+ * This does not include the jitter.
250
+ */
251
+ maxBackoffMs: number;
252
+ /**
253
+ * The max number of times to attempt a connection before a successful handshake.
254
+ * This persists across connections but starts restoring budget after a successful handshake.
255
+ * The restoration interval depends on {@link budgetRestoreIntervalMs}
256
+ */
257
+ attemptBudgetCapacity: number;
258
+ /**
259
+ * After a successful connection attempt, how long to wait before we restore a single budget.
260
+ */
261
+ budgetRestoreIntervalMs: number;
262
+ }
263
+ declare class LeakyBucketRateLimit {
264
+ private budgetConsumed;
265
+ private intervalHandle?;
266
+ private readonly options;
267
+ constructor(options: ConnectionRetryOptions);
268
+ getBackoffMs(): number;
269
+ get totalBudgetRestoreTime(): number;
270
+ consumeBudget(): void;
271
+ getBudgetConsumed(): number;
272
+ hasBudget(): boolean;
273
+ startRestoringBudget(): void;
274
+ private stopLeak;
275
+ close(): void;
276
+ }
277
+
278
+ type TransportOptions = SessionOptions;
279
+ type ProvidedTransportOptions = Partial<TransportOptions>;
280
+ type ClientTransportOptions = TransportOptions & ConnectionRetryOptions;
281
+ type ProvidedClientTransportOptions = Partial<ClientTransportOptions>;
282
+ type ServerTransportOptions = TransportOptions;
283
+ type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;
284
+
192
285
  interface SessionConnectingListeners extends IdentifiedSessionWithGracePeriodListeners {
193
286
  onConnectionEstablished: (conn: Connection) => void;
194
287
  onConnectionFailed: (err: unknown) => void;
@@ -209,12 +302,6 @@ declare class SessionConnecting<ConnType extends Connection> extends IdentifiedS
209
302
  _handleClose(): void;
210
303
  }
211
304
 
212
- declare class SessionNoConnection extends IdentifiedSessionWithGracePeriod {
213
- readonly state: SessionState.NoConnection;
214
- _handleClose(): void;
215
- _handleStateExit(): void;
216
- }
217
-
218
305
  interface SessionHandshakingListeners extends IdentifiedSessionWithGracePeriodListeners {
219
306
  onConnectionErrored: (err: unknown) => void;
220
307
  onConnectionClosed: () => void;
@@ -251,7 +338,7 @@ declare class SessionHandshaking<ConnType extends Connection> extends Identified
251
338
  extras?: Record<string, unknown> | undefined;
252
339
  };
253
340
  onHandshakeData: (msg: Uint8Array) => void;
254
- sendHandshake(msg: TransportMessage): boolean;
341
+ sendHandshake(msg: TransportMessage): SendResult;
255
342
  _handleStateExit(): void;
256
343
  _handleClose(): void;
257
344
  }
@@ -260,6 +347,7 @@ interface SessionConnectedListeners {
260
347
  onConnectionErrored: (err: unknown) => void;
261
348
  onConnectionClosed: () => void;
262
349
  onMessage: (msg: OpaqueTransportMessage) => void;
350
+ onMessageSendFailure: (msg: PartialTransportMessage, reason: string) => void;
263
351
  onInvalidMessage: (reason: string) => void;
264
352
  }
265
353
  interface SessionConnectedProps<ConnType extends Connection> extends IdentifiedSessionProps {
@@ -271,14 +359,13 @@ declare class SessionConnected<ConnType extends Connection> extends IdentifiedSe
271
359
  conn: ConnType;
272
360
  listeners: SessionConnectedListeners;
273
361
  private heartbeatHandle?;
274
- private heartbeatMisses;
275
- isActivelyHeartbeating: boolean;
276
- private lastConstructedMsgs;
277
- private pushLastConstructedMsgs;
362
+ private heartbeatMissTimeout?;
363
+ private isActivelyHeartbeating;
278
364
  updateBookkeeping(ack: number, seq: number): void;
279
365
  private assertSendOrdering;
280
- send(msg: PartialTransportMessage): string;
366
+ send(msg: PartialTransportMessage): SendResult;
281
367
  constructor(props: SessionConnectedProps<ConnType>);
368
+ sendBufferedMessages(): SendBufferResult;
282
369
  get loggingMetadata(): {
283
370
  protocolVersion?: ProtocolVersion | undefined;
284
371
  clientId?: string | undefined;
@@ -297,6 +384,7 @@ declare class SessionConnected<ConnType extends Connection> extends IdentifiedSe
297
384
  } | undefined;
298
385
  extras?: Record<string, unknown> | undefined;
299
386
  };
387
+ startMissingHeartbeatTimeout(): void;
300
388
  startActiveHeartbeat(): void;
301
389
  private sendHeartbeat;
302
390
  onMessageData: (msg: Uint8Array) => void;
@@ -304,6 +392,12 @@ declare class SessionConnected<ConnType extends Connection> extends IdentifiedSe
304
392
  _handleClose(): void;
305
393
  }
306
394
 
395
+ declare class SessionNoConnection extends IdentifiedSessionWithGracePeriod {
396
+ readonly state: SessionState.NoConnection;
397
+ _handleClose(): void;
398
+ _handleStateExit(): void;
399
+ }
400
+
307
401
  interface SessionBackingOffListeners extends IdentifiedSessionWithGracePeriodListeners {
308
402
  onBackoffFinished: () => void;
309
403
  }
@@ -324,256 +418,6 @@ type ClientSession<ConnType extends Connection> = SessionNoConnection | SessionB
324
418
  type ServerSession<ConnType extends Connection> = SessionConnected<ConnType> | SessionNoConnection;
325
419
  type Session<ConnType extends Connection> = ClientSession<ConnType> | ServerSession<ConnType>;
326
420
 
327
- declare const ProtocolError: {
328
- readonly RetriesExceeded: "conn_retry_exceeded";
329
- readonly HandshakeFailed: "handshake_failed";
330
- readonly MessageOrderingViolated: "message_ordering_violated";
331
- readonly InvalidMessage: "invalid_message";
332
- };
333
- type ProtocolErrorType = (typeof ProtocolError)[keyof typeof ProtocolError];
334
- interface EventMap {
335
- message: OpaqueTransportMessage;
336
- sessionStatus: {
337
- status: 'created' | 'closing';
338
- session: Session<Connection>;
339
- } | {
340
- status: 'closed';
341
- session: Pick<Session<Connection>, 'id' | 'to'>;
342
- };
343
- sessionTransition: {
344
- state: SessionState.Connected;
345
- id: SessionId;
346
- } | {
347
- state: SessionState.Handshaking;
348
- id: SessionId;
349
- } | {
350
- state: SessionState.Connecting;
351
- id: SessionId;
352
- } | {
353
- state: SessionState.BackingOff;
354
- id: SessionId;
355
- } | {
356
- state: SessionState.NoConnection;
357
- id: SessionId;
358
- };
359
- protocolError: {
360
- type: (typeof ProtocolError)['HandshakeFailed'];
361
- code: Static<typeof HandshakeErrorResponseCodes>;
362
- message: string;
363
- } | {
364
- type: Omit<ProtocolErrorType, (typeof ProtocolError)['HandshakeFailed']>;
365
- message: string;
366
- };
367
- transportStatus: {
368
- status: TransportStatus;
369
- };
370
- }
371
- type EventTypes = keyof EventMap;
372
- type EventHandler<K extends EventTypes> = (event: EventMap[K]) => unknown;
373
- declare class EventDispatcher<T extends EventTypes> {
374
- private eventListeners;
375
- removeAllListeners(): void;
376
- numberOfListeners<K extends T>(eventType: K): number;
377
- addEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
378
- removeEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
379
- dispatchEvent<K extends T>(eventType: K, event: EventMap[K]): void;
380
- }
381
-
382
- /**
383
- * Options to control the backoff and retry behavior of the client transport's connection behaviour.
384
- *
385
- * River implements exponential backoff with jitter to prevent flooding the server
386
- * when there's an issue with connection establishment.
387
- *
388
- * The backoff is calculated via the following:
389
- * backOff = min(jitter + {@link baseIntervalMs} * 2 ^ budget_consumed, {@link maxBackoffMs})
390
- *
391
- * We use a leaky bucket rate limit with a budget of {@link attemptBudgetCapacity} reconnection attempts.
392
- * Budget only starts to restore after a successful handshake at a rate of one budget per {@link budgetRestoreIntervalMs}.
393
- */
394
- interface ConnectionRetryOptions {
395
- /**
396
- * The base interval to wait before retrying a connection.
397
- */
398
- baseIntervalMs: number;
399
- /**
400
- * The maximum random jitter to add to the total backoff time.
401
- */
402
- maxJitterMs: number;
403
- /**
404
- * The maximum amount of time to wait before retrying a connection.
405
- * This does not include the jitter.
406
- */
407
- maxBackoffMs: number;
408
- /**
409
- * The max number of times to attempt a connection before a successful handshake.
410
- * This persists across connections but starts restoring budget after a successful handshake.
411
- * The restoration interval depends on {@link budgetRestoreIntervalMs}
412
- */
413
- attemptBudgetCapacity: number;
414
- /**
415
- * After a successful connection attempt, how long to wait before we restore a single budget.
416
- */
417
- budgetRestoreIntervalMs: number;
418
- }
419
- declare class LeakyBucketRateLimit {
420
- private budgetConsumed;
421
- private intervalHandle?;
422
- private readonly options;
423
- constructor(options: ConnectionRetryOptions);
424
- getBackoffMs(): number;
425
- get totalBudgetRestoreTime(): number;
426
- consumeBudget(): void;
427
- getBudgetConsumed(): number;
428
- hasBudget(): boolean;
429
- startRestoringBudget(): void;
430
- private stopLeak;
431
- close(): void;
432
- }
433
-
434
- type TransportOptions = SessionOptions;
435
- type ProvidedTransportOptions = Partial<TransportOptions>;
436
- type ClientTransportOptions = TransportOptions & ConnectionRetryOptions;
437
- type ProvidedClientTransportOptions = Partial<ClientTransportOptions>;
438
- type ServerTransportOptions = TransportOptions;
439
- type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;
440
-
441
- /**
442
- * Represents the possible states of a transport.
443
- * @property {'open'} open - The transport is open and operational (note that this doesn't mean it is actively connected)
444
- * @property {'closed'} closed - The transport is permanently closed and cannot be reopened.
445
- */
446
- type TransportStatus = 'open' | 'closed';
447
- interface DeleteSessionOptions {
448
- unhealthy: boolean;
449
- }
450
- type SessionBoundSendFn = (msg: PartialTransportMessage) => string | undefined;
451
- /**
452
- * Transports manage the lifecycle (creation/deletion) of sessions
453
- *
454
- * ```plaintext
455
- * ▲
456
- * incoming │
457
- * messages │
458
- * ▼
459
- * ┌─────────────┐ 1:N ┌───────────┐ 1:1* ┌────────────┐
460
- * │ Transport │ ◄─────► │ Session │ ◄─────► │ Connection │
461
- * └─────────────┘ └───────────┘ └────────────┘
462
- * ▲ * (may or may not be initialized yet)
463
- * │
464
- * ▼
465
- * ┌───────────┐
466
- * │ Message │
467
- * │ Listeners │
468
- * └───────────┘
469
- * ```
470
- * @abstract
471
- */
472
- declare abstract class Transport<ConnType extends Connection> {
473
- /**
474
- * The status of the transport.
475
- */
476
- private status;
477
- /**
478
- * The client ID of this transport.
479
- */
480
- clientId: TransportClientId;
481
- /**
482
- * The event dispatcher for handling events of type EventTypes.
483
- */
484
- eventDispatcher: EventDispatcher<EventTypes>;
485
- /**
486
- * The options for this transport.
487
- */
488
- protected options: TransportOptions;
489
- log?: Logger;
490
- tracer: Tracer;
491
- sessions: Map<TransportClientId, Session<ConnType>>;
492
- /**
493
- * Creates a new Transport instance.
494
- * @param codec The codec used to encode and decode messages.
495
- * @param clientId The client ID of this transport.
496
- */
497
- constructor(clientId: TransportClientId, providedOptions?: ProvidedTransportOptions);
498
- bindLogger(fn: LogFn | Logger, level?: LoggingLevel): void;
499
- /**
500
- * Called when a message is received by this transport.
501
- * You generally shouldn't need to override this in downstream transport implementations.
502
- * @param message The received message.
503
- */
504
- protected handleMsg(message: OpaqueTransportMessage): void;
505
- /**
506
- * Adds a listener to this transport.
507
- * @param the type of event to listen for
508
- * @param handler The message handler to add.
509
- */
510
- addEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
511
- /**
512
- * Removes a listener from this transport.
513
- * @param the type of event to un-listen on
514
- * @param handler The message handler to remove.
515
- */
516
- removeEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
517
- protected protocolError(message: EventMap['protocolError']): void;
518
- /**
519
- * Default close implementation for transports. You should override this in the downstream
520
- * implementation if you need to do any additional cleanup and call super.close() at the end.
521
- * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
522
- */
523
- close(): void;
524
- getStatus(): TransportStatus;
525
- protected createSession<S extends Session<ConnType>>(session: S): void;
526
- protected updateSession<S extends Session<ConnType>>(session: S): void;
527
- protected deleteSession(session: Session<ConnType>, options?: DeleteSessionOptions): void;
528
- protected onSessionGracePeriodElapsed(session: Session<ConnType>): void;
529
- protected onConnectingFailed(session: SessionConnecting<ConnType>): SessionNoConnection;
530
- protected onConnClosed(session: SessionHandshaking<ConnType> | SessionConnected<ConnType>): SessionNoConnection;
531
- /**
532
- * Gets a send closure scoped to a specific session. Sending using the returned
533
- * closure after the session has transitioned to a different state will be a noop.
534
- *
535
- * Session objects themselves can become stale as they transition between
536
- * states. As stale sessions cannot be used again (and will throw), holding
537
- * onto a session object is not recommended.
538
- */
539
- getSessionBoundSendFn(to: TransportClientId, sessionId: SessionId): SessionBoundSendFn;
540
- }
541
-
542
- type ConstructHandshake<T extends TSchema> = () => Static<T> | Promise<Static<T>>;
543
- type ValidateHandshake<T extends TSchema> = (metadata: Static<T>, previousParsedMetadata?: ParsedMetadata) => Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata | Promise<Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata>;
544
- interface ClientHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
545
- /**
546
- * Schema for the metadata that the client sends to the server
547
- * during the handshake.
548
- */
549
- schema: MetadataSchema;
550
- /**
551
- * Gets the {@link HandshakeRequestMetadata} to send to the server.
552
- */
553
- construct: ConstructHandshake<MetadataSchema>;
554
- }
555
- interface ServerHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
556
- /**
557
- * Schema for the metadata that the server receives from the client
558
- * during the handshake.
559
- */
560
- schema: MetadataSchema;
561
- /**
562
- * Parses the {@link HandshakeRequestMetadata} sent by the client, transforming
563
- * it into {@link ParsedHandshakeMetadata}.
564
- *
565
- * May return `false` if the client should be rejected.
566
- *
567
- * @param metadata - The metadata sent by the client.
568
- * @param session - The session that the client would be associated with.
569
- * @param isReconnect - Whether the client is reconnecting to the session,
570
- * or if this is a new session.
571
- */
572
- validate: ValidateHandshake<MetadataSchema>;
573
- }
574
- declare function createClientHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, construct: ConstructHandshake<MetadataSchema>): ClientHandshakeOptions;
575
- declare function createServerHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, validate: ValidateHandshake<MetadataSchema>): ServerHandshakeOptions;
576
-
577
421
  declare abstract class ClientTransport<ConnType extends Connection> extends Transport<ConnType> {
578
422
  /**
579
423
  * The options for this transport.
@@ -654,7 +498,7 @@ type BaseErrorSchemaType = TObject<{
654
498
  /**
655
499
  * A schema for cancel payloads sent from the client
656
500
  */
657
- declare const CancelResultSchema: TObject<{
501
+ declare const CancelErrorSchema: TObject<{
658
502
  code: TLiteral<"CANCEL">;
659
503
  message: TString;
660
504
  }>;
@@ -974,7 +818,7 @@ type ProcedureHandlerContext<State> = ServiceContext & {
974
818
  * Cancelling is not the same as closing procedure calls gracefully, please refer to
975
819
  * the river documentation to understand the difference between the two concepts.
976
820
  */
977
- cancel: (message?: string) => ErrResult<Static<typeof CancelResultSchema>>;
821
+ cancel: (message?: string) => ErrResult<Static<typeof CancelErrorSchema>>;
978
822
  /**
979
823
  * This signal is a standard [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
980
824
  * triggered when the procedure invocation is done. This signal tracks the invocation/request finishing
@@ -1018,7 +862,7 @@ type ValidProcType = 'rpc' | 'upload' | 'subscription' | 'stream';
1018
862
  * Represents the payload type for {@link Procedure}s.
1019
863
  */
1020
864
  type PayloadType = TSchema;
1021
- type Cancellable<T> = T | Static<typeof CancelResultSchema>;
865
+ type Cancellable<T> = T | Static<typeof CancelErrorSchema>;
1022
866
  /**
1023
867
  * Procedure for a single message in both directions (1:1).
1024
868
  *
@@ -1562,4 +1406,161 @@ declare class ServiceScaffold<State extends object> {
1562
1406
  }>;
1563
1407
  }
1564
1408
 
1565
- export { ResultUnwrapOk as $, AnyServiceSchemaMap as A, Readable as B, ClientTransport as C, Procedure as D, ProcedureErrorSchemaType as E, flattenErrorType as F, UNCAUGHT_ERROR_CODE as G, UNEXPECTED_DISCONNECT_CODE as H, InstantiatedServiceSchemaMap as I, INVALID_REQUEST_CODE as J, CANCEL_CODE as K, ReaderErrorSchema as L, BaseErrorSchemaType as M, createClient as N, Client as O, ProvidedClientTransportOptions as P, ProcedureHandlerContext as Q, RpcProcedure as R, ServerHandshakeOptions as S, Ok as T, UploadProcedure as U, ValidProcType as V, Writable as W, Err as X, Result as Y, ErrResult as Z, OkResult as _, ProvidedServerTransportOptions as a, ResultUnwrapErr as a0, ResponseData as a1, createClientHandshakeOptions as a2, createServerHandshakeOptions as a3, ClientHandshakeOptions as a4, ReadableIterator as a5, ReadableResult as a6, Transport as a7, SessionOptions as a8, ClientTransportOptions as a9, SessionNoConnection as aa, SessionBoundSendFn as ab, CommonSession as ac, SessionState as ad, CommonSessionProps as ae, ServerTransportOptions as af, ServerSession as ag, DeleteSessionOptions as ah, TransportStatus as ai, ProvidedTransportOptions as aj, Session as ak, SessionConnecting as al, SessionHandshaking as am, SessionConnected as an, EventMap as ao, EventTypes as ap, EventHandler as aq, ProtocolError as ar, ProtocolErrorType as as, Connection as b, ParsedMetadata as c, AnyProcedure as d, ServiceContext as e, Service as f, ServiceConfiguration as g, ProcHandler as h, ProcInit as i, ProcRequest as j, ProcResponse as k, ProcErrors as l, ProcType as m, ServiceSchema as n, SerializedServerSchema as o, SerializedServiceSchema as p, SerializedProcedureSchema as q, serializeSchemaV1Compat as r, serializeSchema as s, SerializedServerSchemaProtocolv1 as t, SerializedServiceSchemaProtocolv1 as u, SerializedProcedureSchemaProtocolv1 as v, PayloadType as w, ProcedureMap as x, SubscriptionProcedure as y, StreamProcedure as z };
1409
+ declare const ProtocolError: {
1410
+ readonly RetriesExceeded: "conn_retry_exceeded";
1411
+ readonly HandshakeFailed: "handshake_failed";
1412
+ readonly MessageOrderingViolated: "message_ordering_violated";
1413
+ readonly InvalidMessage: "invalid_message";
1414
+ readonly MessageSendFailure: "message_send_failure";
1415
+ };
1416
+ type ProtocolErrorType = (typeof ProtocolError)[keyof typeof ProtocolError];
1417
+ interface EventMap {
1418
+ message: OpaqueTransportMessage;
1419
+ sessionStatus: {
1420
+ status: 'created' | 'closing';
1421
+ session: Session<Connection>;
1422
+ } | {
1423
+ status: 'closed';
1424
+ session: Pick<Session<Connection>, 'id' | 'to'>;
1425
+ };
1426
+ sessionTransition: {
1427
+ state: SessionState.Connected;
1428
+ id: SessionId;
1429
+ } | {
1430
+ state: SessionState.Handshaking;
1431
+ id: SessionId;
1432
+ } | {
1433
+ state: SessionState.Connecting;
1434
+ id: SessionId;
1435
+ } | {
1436
+ state: SessionState.BackingOff;
1437
+ id: SessionId;
1438
+ } | {
1439
+ state: SessionState.NoConnection;
1440
+ id: SessionId;
1441
+ };
1442
+ protocolError: {
1443
+ type: (typeof ProtocolError)['HandshakeFailed'];
1444
+ code: Static<typeof HandshakeErrorResponseCodes>;
1445
+ message: string;
1446
+ } | {
1447
+ type: Omit<ProtocolErrorType, (typeof ProtocolError)['HandshakeFailed']>;
1448
+ message: string;
1449
+ };
1450
+ transportStatus: {
1451
+ status: TransportStatus;
1452
+ };
1453
+ }
1454
+ type EventTypes = keyof EventMap;
1455
+ type EventHandler<K extends EventTypes> = (event: EventMap[K]) => unknown;
1456
+ declare class EventDispatcher<T extends EventTypes> {
1457
+ private eventListeners;
1458
+ removeAllListeners(): void;
1459
+ numberOfListeners<K extends T>(eventType: K): number;
1460
+ addEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
1461
+ removeEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
1462
+ dispatchEvent<K extends T>(eventType: K, event: EventMap[K]): void;
1463
+ }
1464
+
1465
+ /**
1466
+ * Represents the possible states of a transport.
1467
+ * @property {'open'} open - The transport is open and operational (note that this doesn't mean it is actively connected)
1468
+ * @property {'closed'} closed - The transport is permanently closed and cannot be reopened.
1469
+ */
1470
+ type TransportStatus = 'open' | 'closed';
1471
+ interface DeleteSessionOptions {
1472
+ unhealthy: boolean;
1473
+ }
1474
+ type SessionBoundSendFn = (msg: PartialTransportMessage) => string;
1475
+ /**
1476
+ * Transports manage the lifecycle (creation/deletion) of sessions
1477
+ *
1478
+ * ```plaintext
1479
+ * ▲
1480
+ * incoming │
1481
+ * messages │
1482
+ * ▼
1483
+ * ┌─────────────┐ 1:N ┌───────────┐ 1:1* ┌────────────┐
1484
+ * │ Transport │ ◄─────► │ Session │ ◄─────► │ Connection │
1485
+ * └─────────────┘ └───────────┘ └────────────┘
1486
+ * ▲ * (may or may not be initialized yet)
1487
+ * │
1488
+ * ▼
1489
+ * ┌───────────┐
1490
+ * │ Message │
1491
+ * │ Listeners │
1492
+ * └───────────┘
1493
+ * ```
1494
+ * @abstract
1495
+ */
1496
+ declare abstract class Transport<ConnType extends Connection> {
1497
+ /**
1498
+ * The status of the transport.
1499
+ */
1500
+ private status;
1501
+ /**
1502
+ * The client ID of this transport.
1503
+ */
1504
+ clientId: TransportClientId;
1505
+ /**
1506
+ * The event dispatcher for handling events of type EventTypes.
1507
+ */
1508
+ eventDispatcher: EventDispatcher<EventTypes>;
1509
+ /**
1510
+ * The options for this transport.
1511
+ */
1512
+ protected options: TransportOptions;
1513
+ log?: Logger;
1514
+ tracer: Tracer;
1515
+ sessions: Map<TransportClientId, Session<ConnType>>;
1516
+ /**
1517
+ * Creates a new Transport instance.
1518
+ * @param codec The codec used to encode and decode messages.
1519
+ * @param clientId The client ID of this transport.
1520
+ */
1521
+ constructor(clientId: TransportClientId, providedOptions?: ProvidedTransportOptions);
1522
+ bindLogger(fn: LogFn | Logger, level?: LoggingLevel): void;
1523
+ /**
1524
+ * Called when a message is received by this transport.
1525
+ * You generally shouldn't need to override this in downstream transport implementations.
1526
+ * @param message The received message.
1527
+ */
1528
+ protected handleMsg(message: OpaqueTransportMessage): void;
1529
+ /**
1530
+ * Adds a listener to this transport.
1531
+ * @param the type of event to listen for
1532
+ * @param handler The message handler to add.
1533
+ */
1534
+ addEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
1535
+ /**
1536
+ * Removes a listener from this transport.
1537
+ * @param the type of event to un-listen on
1538
+ * @param handler The message handler to remove.
1539
+ */
1540
+ removeEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
1541
+ protected protocolError(message: EventMap['protocolError']): void;
1542
+ /**
1543
+ * Default close implementation for transports. You should override this in the downstream
1544
+ * implementation if you need to do any additional cleanup and call super.close() at the end.
1545
+ * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
1546
+ */
1547
+ close(): void;
1548
+ getStatus(): TransportStatus;
1549
+ protected createSession<S extends Session<ConnType>>(session: S): void;
1550
+ protected updateSession<S extends Session<ConnType>>(session: S): void;
1551
+ protected deleteSession(session: Session<ConnType>, options?: DeleteSessionOptions): void;
1552
+ protected onSessionGracePeriodElapsed(session: Session<ConnType>): void;
1553
+ protected onConnectingFailed(session: SessionConnecting<ConnType>): SessionNoConnection;
1554
+ protected onConnClosed(session: SessionHandshaking<ConnType> | SessionConnected<ConnType>): SessionNoConnection;
1555
+ /**
1556
+ * Gets a send closure scoped to a specific session. Sending using the returned
1557
+ * closure after the session has transitioned to a different state will be a noop.
1558
+ *
1559
+ * Session objects themselves can become stale as they transition between
1560
+ * states. As stale sessions cannot be used again (and will throw), holding
1561
+ * onto a session object is not recommended.
1562
+ */
1563
+ getSessionBoundSendFn(to: TransportClientId, sessionId: SessionId): SessionBoundSendFn;
1564
+ }
1565
+
1566
+ export { type ResultUnwrapOk as $, type AnyServiceSchemaMap as A, type StreamProcedure as B, ClientTransport as C, type Readable as D, Procedure as E, type ProcedureErrorSchemaType as F, flattenErrorType as G, UNCAUGHT_ERROR_CODE as H, type InstantiatedServiceSchemaMap as I, UNEXPECTED_DISCONNECT_CODE as J, INVALID_REQUEST_CODE as K, CANCEL_CODE as L, ReaderErrorSchema as M, type BaseErrorSchemaType as N, createClient as O, type ProvidedClientTransportOptions as P, type Client as Q, type RpcProcedure as R, type ServerHandshakeOptions as S, Ok as T, type UploadProcedure as U, type ValidProcType as V, type Writable as W, Err as X, type Result as Y, type ErrResult as Z, type OkResult as _, type ProvidedServerTransportOptions as a, type ResultUnwrapErr as a0, type ResponseData as a1, createClientHandshakeOptions as a2, createServerHandshakeOptions as a3, type ClientHandshakeOptions as a4, type ReadableIterator as a5, type ReadableResult as a6, Transport as a7, type SessionOptions as a8, type ClientTransportOptions as a9, SessionNoConnection as aa, type SessionBoundSendFn as ab, CommonSession as ac, SessionState as ad, type CommonSessionProps as ae, type ServerTransportOptions as af, type ServerSession as ag, type DeleteSessionOptions as ah, type TransportStatus as ai, type ProvidedTransportOptions as aj, type Session as ak, SessionConnecting as al, SessionHandshaking as am, SessionConnected as an, type EventMap as ao, type EventTypes as ap, type EventHandler as aq, ProtocolError as ar, type ProtocolErrorType as as, Connection as b, type ServiceContext as c, type ProcedureHandlerContext as d, type PayloadType as e, type ParsedMetadata as f, type AnyProcedure as g, type Service as h, type ServiceConfiguration as i, type ProcHandler as j, type ProcInit as k, type ProcRequest as l, type ProcResponse as m, type ProcErrors as n, type ProcType as o, ServiceSchema as p, type SerializedServerSchema as q, type SerializedServiceSchema as r, serializeSchema as s, type SerializedProcedureSchema as t, serializeSchemaV1Compat as u, type SerializedServerSchemaProtocolv1 as v, type SerializedServiceSchemaProtocolv1 as w, type SerializedProcedureSchemaProtocolv1 as x, type ProcedureMap as y, type SubscriptionProcedure as z };