@replit/river 0.208.1 → 0.208.2

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 (50) hide show
  1. package/dist/{adapter-f2b6e211.d.ts → adapter-ChksXKVN.d.ts} +2 -2
  2. package/dist/adapter-Cuc4JtfV.d.cts +46 -0
  3. package/dist/{chunk-2WFRHXDZ.js → chunk-2OE32RBD.js} +11 -16
  4. package/dist/{chunk-2WFRHXDZ.js.map → chunk-2OE32RBD.js.map} +1 -1
  5. package/dist/{chunk-BXKBENJE.js → chunk-XB663LV7.js} +2 -2
  6. package/dist/{chunk-EVAQ2QMB.js → chunk-XS6CNYUH.js} +21 -25
  7. package/dist/{chunk-EVAQ2QMB.js.map → chunk-XS6CNYUH.js.map} +1 -1
  8. package/dist/codec/index.d.cts +3 -3
  9. package/dist/codec/index.d.ts +3 -3
  10. package/dist/codec/index.js +2 -2
  11. package/dist/connection-BF4zg6Qv.d.cts +35 -0
  12. package/dist/{connection-098d4aad.d.ts → connection-Donr3JRB.d.ts} +4 -4
  13. package/dist/index-C9tpZjBN.d.cts +37 -0
  14. package/dist/{index-02554794.d.ts → index-D8IOd3LG.d.ts} +2 -2
  15. package/dist/logging/index.d.cts +2 -2
  16. package/dist/logging/index.d.ts +2 -2
  17. package/dist/{message-01c3e85a.d.ts → message-Di94OL80.d.cts} +1 -1
  18. package/dist/message-Di94OL80.d.ts +108 -0
  19. package/dist/router/index.cjs +5 -9
  20. package/dist/router/index.cjs.map +1 -1
  21. package/dist/router/index.d.cts +7 -7
  22. package/dist/router/index.d.ts +7 -7
  23. package/dist/router/index.js +1 -1
  24. package/dist/testUtil/index.cjs +7 -13
  25. package/dist/testUtil/index.cjs.map +1 -1
  26. package/dist/testUtil/index.d.cts +5 -5
  27. package/dist/testUtil/index.d.ts +5 -5
  28. package/dist/testUtil/index.js +4 -5
  29. package/dist/testUtil/index.js.map +1 -1
  30. package/dist/transport/impls/ws/client.cjs +5 -9
  31. package/dist/transport/impls/ws/client.cjs.map +1 -1
  32. package/dist/transport/impls/ws/client.d.cts +6 -6
  33. package/dist/transport/impls/ws/client.d.ts +6 -6
  34. package/dist/transport/impls/ws/client.js +3 -3
  35. package/dist/transport/impls/ws/server.cjs +6 -11
  36. package/dist/transport/impls/ws/server.cjs.map +1 -1
  37. package/dist/transport/impls/ws/server.d.cts +6 -6
  38. package/dist/transport/impls/ws/server.d.ts +6 -6
  39. package/dist/transport/impls/ws/server.js +3 -3
  40. package/dist/transport/index.cjs +6 -11
  41. package/dist/transport/index.cjs.map +1 -1
  42. package/dist/transport/index.d.cts +6 -6
  43. package/dist/transport/index.d.ts +6 -6
  44. package/dist/transport/index.js +3 -3
  45. package/dist/transport-CCaWx1Rb.d.cts +1566 -0
  46. package/dist/{services-44be1b6b.d.ts → transport-CZb3vdB4.d.ts} +323 -323
  47. package/dist/{wslike-e0b32dd5.d.ts → wslike-Dng9H1C7.d.cts} +1 -1
  48. package/dist/wslike-Dng9H1C7.d.ts +40 -0
  49. package/package.json +2 -2
  50. /package/dist/{chunk-BXKBENJE.js.map → chunk-XB663LV7.js.map} +0 -0
@@ -1,9 +1,9 @@
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 { b as TelemetryInfo, T as TransportClientId, P as ProtocolVersion, O as OpaqueTransportMessage, a as PartialTransportMessage, c as TransportMessage, H as HandshakeErrorResponseCodes, d as HandshakeErrorCustomHandlerFatalResponseCodes } from './message-01c3e85a.js';
5
- import { M as MessageMetadata, L as Logger, T as Tags, a as LogFn, b as LoggingLevel } from './index-02554794.js';
6
- import { C as Codec, a as CodecMessageAdapter, S as SendResult, b as SendBufferResult } from './adapter-f2b6e211.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';
7
7
 
8
8
  /**
9
9
  * A connection is the actual raw underlying transport connection.
@@ -188,6 +188,100 @@ declare abstract class IdentifiedSessionWithGracePeriod extends IdentifiedSessio
188
188
  _handleClose(): void;
189
189
  }
190
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
+
191
285
  interface SessionConnectingListeners extends IdentifiedSessionWithGracePeriodListeners {
192
286
  onConnectionEstablished: (conn: Connection) => void;
193
287
  onConnectionFailed: (err: unknown) => void;
@@ -208,12 +302,6 @@ declare class SessionConnecting<ConnType extends Connection> extends IdentifiedS
208
302
  _handleClose(): void;
209
303
  }
210
304
 
211
- declare class SessionNoConnection extends IdentifiedSessionWithGracePeriod {
212
- readonly state: SessionState.NoConnection;
213
- _handleClose(): void;
214
- _handleStateExit(): void;
215
- }
216
-
217
305
  interface SessionHandshakingListeners extends IdentifiedSessionWithGracePeriodListeners {
218
306
  onConnectionErrored: (err: unknown) => void;
219
307
  onConnectionClosed: () => void;
@@ -258,322 +346,77 @@ declare class SessionHandshaking<ConnType extends Connection> extends Identified
258
346
  interface SessionConnectedListeners {
259
347
  onConnectionErrored: (err: unknown) => void;
260
348
  onConnectionClosed: () => void;
261
- onMessage: (msg: OpaqueTransportMessage) => void;
262
- onMessageSendFailure: (msg: PartialTransportMessage, reason: string) => void;
263
- onInvalidMessage: (reason: string) => void;
264
- }
265
- interface SessionConnectedProps<ConnType extends Connection> extends IdentifiedSessionProps {
266
- conn: ConnType;
267
- listeners: SessionConnectedListeners;
268
- }
269
- declare class SessionConnected<ConnType extends Connection> extends IdentifiedSession {
270
- readonly state: SessionState.Connected;
271
- conn: ConnType;
272
- listeners: SessionConnectedListeners;
273
- private heartbeatHandle?;
274
- private heartbeatMissTimeout?;
275
- private isActivelyHeartbeating;
276
- updateBookkeeping(ack: number, seq: number): void;
277
- private assertSendOrdering;
278
- send(msg: PartialTransportMessage): SendResult;
279
- constructor(props: SessionConnectedProps<ConnType>);
280
- sendBufferedMessages(): SendBufferResult;
281
- get loggingMetadata(): {
282
- protocolVersion?: ProtocolVersion | undefined;
283
- clientId?: string | undefined;
284
- connectedTo?: string | undefined;
285
- sessionId?: string | undefined;
286
- connId?: string | undefined;
287
- transportMessage?: Partial<OpaqueTransportMessage> | undefined;
288
- validationErrors?: {
289
- path: string;
290
- message: string;
291
- }[] | undefined;
292
- tags?: Tags[] | undefined;
293
- telemetry?: {
294
- traceId: string;
295
- spanId: string;
296
- } | undefined;
297
- extras?: Record<string, unknown> | undefined;
298
- };
299
- startMissingHeartbeatTimeout(): void;
300
- startActiveHeartbeat(): void;
301
- private sendHeartbeat;
302
- onMessageData: (msg: Uint8Array) => void;
303
- _handleStateExit(): void;
304
- _handleClose(): void;
305
- }
306
-
307
- interface SessionBackingOffListeners extends IdentifiedSessionWithGracePeriodListeners {
308
- onBackoffFinished: () => void;
309
- }
310
- interface SessionBackingOffProps extends IdentifiedSessionWithGracePeriodProps {
311
- backoffMs: number;
312
- listeners: SessionBackingOffListeners;
313
- }
314
- declare class SessionBackingOff extends IdentifiedSessionWithGracePeriod {
315
- readonly state: SessionState.BackingOff;
316
- listeners: SessionBackingOffListeners;
317
- backoffTimeout?: ReturnType<typeof setTimeout>;
318
- constructor(props: SessionBackingOffProps);
319
- _handleClose(): void;
320
- _handleStateExit(): void;
321
- }
322
-
323
- type ClientSession<ConnType extends Connection> = SessionNoConnection | SessionBackingOff | SessionConnecting<ConnType> | SessionHandshaking<ConnType> | SessionConnected<ConnType>;
324
- type ServerSession<ConnType extends Connection> = SessionConnected<ConnType> | SessionNoConnection;
325
- type Session<ConnType extends Connection> = ClientSession<ConnType> | ServerSession<ConnType>;
326
-
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
- readonly MessageSendFailure: "message_send_failure";
333
- };
334
- type ProtocolErrorType = (typeof ProtocolError)[keyof typeof ProtocolError];
335
- interface EventMap {
336
- message: OpaqueTransportMessage;
337
- sessionStatus: {
338
- status: 'created' | 'closing';
339
- session: Session<Connection>;
340
- } | {
341
- status: 'closed';
342
- session: Pick<Session<Connection>, 'id' | 'to'>;
343
- };
344
- sessionTransition: {
345
- state: SessionState.Connected;
346
- id: SessionId;
347
- } | {
348
- state: SessionState.Handshaking;
349
- id: SessionId;
350
- } | {
351
- state: SessionState.Connecting;
352
- id: SessionId;
353
- } | {
354
- state: SessionState.BackingOff;
355
- id: SessionId;
356
- } | {
357
- state: SessionState.NoConnection;
358
- id: SessionId;
359
- };
360
- protocolError: {
361
- type: (typeof ProtocolError)['HandshakeFailed'];
362
- code: Static<typeof HandshakeErrorResponseCodes>;
363
- message: string;
364
- } | {
365
- type: Omit<ProtocolErrorType, (typeof ProtocolError)['HandshakeFailed']>;
366
- message: string;
367
- };
368
- transportStatus: {
369
- status: TransportStatus;
370
- };
371
- }
372
- type EventTypes = keyof EventMap;
373
- type EventHandler<K extends EventTypes> = (event: EventMap[K]) => unknown;
374
- declare class EventDispatcher<T extends EventTypes> {
375
- private eventListeners;
376
- removeAllListeners(): void;
377
- numberOfListeners<K extends T>(eventType: K): number;
378
- addEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
379
- removeEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
380
- dispatchEvent<K extends T>(eventType: K, event: EventMap[K]): void;
381
- }
382
-
383
- /**
384
- * Options to control the backoff and retry behavior of the client transport's connection behaviour.
385
- *
386
- * River implements exponential backoff with jitter to prevent flooding the server
387
- * when there's an issue with connection establishment.
388
- *
389
- * The backoff is calculated via the following:
390
- * backOff = min(jitter + {@link baseIntervalMs} * 2 ^ budget_consumed, {@link maxBackoffMs})
391
- *
392
- * We use a leaky bucket rate limit with a budget of {@link attemptBudgetCapacity} reconnection attempts.
393
- * Budget only starts to restore after a successful handshake at a rate of one budget per {@link budgetRestoreIntervalMs}.
394
- */
395
- interface ConnectionRetryOptions {
396
- /**
397
- * The base interval to wait before retrying a connection.
398
- */
399
- baseIntervalMs: number;
400
- /**
401
- * The maximum random jitter to add to the total backoff time.
402
- */
403
- maxJitterMs: number;
404
- /**
405
- * The maximum amount of time to wait before retrying a connection.
406
- * This does not include the jitter.
407
- */
408
- maxBackoffMs: number;
409
- /**
410
- * The max number of times to attempt a connection before a successful handshake.
411
- * This persists across connections but starts restoring budget after a successful handshake.
412
- * The restoration interval depends on {@link budgetRestoreIntervalMs}
413
- */
414
- attemptBudgetCapacity: number;
415
- /**
416
- * After a successful connection attempt, how long to wait before we restore a single budget.
417
- */
418
- budgetRestoreIntervalMs: number;
419
- }
420
- declare class LeakyBucketRateLimit {
421
- private budgetConsumed;
422
- private intervalHandle?;
423
- private readonly options;
424
- constructor(options: ConnectionRetryOptions);
425
- getBackoffMs(): number;
426
- get totalBudgetRestoreTime(): number;
427
- consumeBudget(): void;
428
- getBudgetConsumed(): number;
429
- hasBudget(): boolean;
430
- startRestoringBudget(): void;
431
- private stopLeak;
432
- close(): void;
433
- }
434
-
435
- type TransportOptions = SessionOptions;
436
- type ProvidedTransportOptions = Partial<TransportOptions>;
437
- type ClientTransportOptions = TransportOptions & ConnectionRetryOptions;
438
- type ProvidedClientTransportOptions = Partial<ClientTransportOptions>;
439
- type ServerTransportOptions = TransportOptions;
440
- type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;
441
-
442
- /**
443
- * Represents the possible states of a transport.
444
- * @property {'open'} open - The transport is open and operational (note that this doesn't mean it is actively connected)
445
- * @property {'closed'} closed - The transport is permanently closed and cannot be reopened.
446
- */
447
- type TransportStatus = 'open' | 'closed';
448
- interface DeleteSessionOptions {
449
- unhealthy: boolean;
450
- }
451
- type SessionBoundSendFn = (msg: PartialTransportMessage) => string;
452
- /**
453
- * Transports manage the lifecycle (creation/deletion) of sessions
454
- *
455
- * ```plaintext
456
- * ▲
457
- * incoming │
458
- * messages │
459
- * ▼
460
- * ┌─────────────┐ 1:N ┌───────────┐ 1:1* ┌────────────┐
461
- * │ Transport │ ◄─────► │ Session │ ◄─────► │ Connection │
462
- * └─────────────┘ └───────────┘ └────────────┘
463
- * ▲ * (may or may not be initialized yet)
464
- * │
465
- * ▼
466
- * ┌───────────┐
467
- * │ Message │
468
- * │ Listeners │
469
- * └───────────┘
470
- * ```
471
- * @abstract
472
- */
473
- declare abstract class Transport<ConnType extends Connection> {
474
- /**
475
- * The status of the transport.
476
- */
477
- private status;
478
- /**
479
- * The client ID of this transport.
480
- */
481
- clientId: TransportClientId;
482
- /**
483
- * The event dispatcher for handling events of type EventTypes.
484
- */
485
- eventDispatcher: EventDispatcher<EventTypes>;
486
- /**
487
- * The options for this transport.
488
- */
489
- protected options: TransportOptions;
490
- log?: Logger;
491
- tracer: Tracer;
492
- sessions: Map<TransportClientId, Session<ConnType>>;
493
- /**
494
- * Creates a new Transport instance.
495
- * @param codec The codec used to encode and decode messages.
496
- * @param clientId The client ID of this transport.
497
- */
498
- constructor(clientId: TransportClientId, providedOptions?: ProvidedTransportOptions);
499
- bindLogger(fn: LogFn | Logger, level?: LoggingLevel): void;
500
- /**
501
- * Called when a message is received by this transport.
502
- * You generally shouldn't need to override this in downstream transport implementations.
503
- * @param message The received message.
504
- */
505
- protected handleMsg(message: OpaqueTransportMessage): void;
506
- /**
507
- * Adds a listener to this transport.
508
- * @param the type of event to listen for
509
- * @param handler The message handler to add.
510
- */
511
- addEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
512
- /**
513
- * Removes a listener from this transport.
514
- * @param the type of event to un-listen on
515
- * @param handler The message handler to remove.
516
- */
517
- removeEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
518
- protected protocolError(message: EventMap['protocolError']): void;
519
- /**
520
- * Default close implementation for transports. You should override this in the downstream
521
- * implementation if you need to do any additional cleanup and call super.close() at the end.
522
- * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
523
- */
524
- close(): void;
525
- getStatus(): TransportStatus;
526
- protected createSession<S extends Session<ConnType>>(session: S): void;
527
- protected updateSession<S extends Session<ConnType>>(session: S): void;
528
- protected deleteSession(session: Session<ConnType>, options?: DeleteSessionOptions): void;
529
- protected onSessionGracePeriodElapsed(session: Session<ConnType>): void;
530
- protected onConnectingFailed(session: SessionConnecting<ConnType>): SessionNoConnection;
531
- protected onConnClosed(session: SessionHandshaking<ConnType> | SessionConnected<ConnType>): SessionNoConnection;
532
- /**
533
- * Gets a send closure scoped to a specific session. Sending using the returned
534
- * closure after the session has transitioned to a different state will be a noop.
535
- *
536
- * Session objects themselves can become stale as they transition between
537
- * states. As stale sessions cannot be used again (and will throw), holding
538
- * onto a session object is not recommended.
539
- */
540
- getSessionBoundSendFn(to: TransportClientId, sessionId: SessionId): SessionBoundSendFn;
349
+ onMessage: (msg: OpaqueTransportMessage) => void;
350
+ onMessageSendFailure: (msg: PartialTransportMessage, reason: string) => void;
351
+ onInvalidMessage: (reason: string) => void;
352
+ }
353
+ interface SessionConnectedProps<ConnType extends Connection> extends IdentifiedSessionProps {
354
+ conn: ConnType;
355
+ listeners: SessionConnectedListeners;
356
+ }
357
+ declare class SessionConnected<ConnType extends Connection> extends IdentifiedSession {
358
+ readonly state: SessionState.Connected;
359
+ conn: ConnType;
360
+ listeners: SessionConnectedListeners;
361
+ private heartbeatHandle?;
362
+ private heartbeatMissTimeout?;
363
+ private isActivelyHeartbeating;
364
+ updateBookkeeping(ack: number, seq: number): void;
365
+ private assertSendOrdering;
366
+ send(msg: PartialTransportMessage): SendResult;
367
+ constructor(props: SessionConnectedProps<ConnType>);
368
+ sendBufferedMessages(): SendBufferResult;
369
+ get loggingMetadata(): {
370
+ protocolVersion?: ProtocolVersion | undefined;
371
+ clientId?: string | undefined;
372
+ connectedTo?: string | undefined;
373
+ sessionId?: string | undefined;
374
+ connId?: string | undefined;
375
+ transportMessage?: Partial<OpaqueTransportMessage> | undefined;
376
+ validationErrors?: {
377
+ path: string;
378
+ message: string;
379
+ }[] | undefined;
380
+ tags?: Tags[] | undefined;
381
+ telemetry?: {
382
+ traceId: string;
383
+ spanId: string;
384
+ } | undefined;
385
+ extras?: Record<string, unknown> | undefined;
386
+ };
387
+ startMissingHeartbeatTimeout(): void;
388
+ startActiveHeartbeat(): void;
389
+ private sendHeartbeat;
390
+ onMessageData: (msg: Uint8Array) => void;
391
+ _handleStateExit(): void;
392
+ _handleClose(): void;
541
393
  }
542
394
 
543
- type ConstructHandshake<T extends TSchema> = () => Static<T> | Promise<Static<T>>;
544
- type ValidateHandshake<T extends TSchema> = (metadata: Static<T>, previousParsedMetadata?: ParsedMetadata) => Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata | Promise<Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata>;
545
- interface ClientHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
546
- /**
547
- * Schema for the metadata that the client sends to the server
548
- * during the handshake.
549
- */
550
- schema: MetadataSchema;
551
- /**
552
- * Gets the {@link HandshakeRequestMetadata} to send to the server.
553
- */
554
- construct: ConstructHandshake<MetadataSchema>;
395
+ declare class SessionNoConnection extends IdentifiedSessionWithGracePeriod {
396
+ readonly state: SessionState.NoConnection;
397
+ _handleClose(): void;
398
+ _handleStateExit(): void;
555
399
  }
556
- interface ServerHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
557
- /**
558
- * Schema for the metadata that the server receives from the client
559
- * during the handshake.
560
- */
561
- schema: MetadataSchema;
562
- /**
563
- * Parses the {@link HandshakeRequestMetadata} sent by the client, transforming
564
- * it into {@link ParsedHandshakeMetadata}.
565
- *
566
- * May return `false` if the client should be rejected.
567
- *
568
- * @param metadata - The metadata sent by the client.
569
- * @param session - The session that the client would be associated with.
570
- * @param isReconnect - Whether the client is reconnecting to the session,
571
- * or if this is a new session.
572
- */
573
- validate: ValidateHandshake<MetadataSchema>;
400
+
401
+ interface SessionBackingOffListeners extends IdentifiedSessionWithGracePeriodListeners {
402
+ onBackoffFinished: () => void;
574
403
  }
575
- declare function createClientHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, construct: ConstructHandshake<MetadataSchema>): ClientHandshakeOptions;
576
- declare function createServerHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, validate: ValidateHandshake<MetadataSchema>): ServerHandshakeOptions;
404
+ interface SessionBackingOffProps extends IdentifiedSessionWithGracePeriodProps {
405
+ backoffMs: number;
406
+ listeners: SessionBackingOffListeners;
407
+ }
408
+ declare class SessionBackingOff extends IdentifiedSessionWithGracePeriod {
409
+ readonly state: SessionState.BackingOff;
410
+ listeners: SessionBackingOffListeners;
411
+ backoffTimeout?: ReturnType<typeof setTimeout>;
412
+ constructor(props: SessionBackingOffProps);
413
+ _handleClose(): void;
414
+ _handleStateExit(): void;
415
+ }
416
+
417
+ type ClientSession<ConnType extends Connection> = SessionNoConnection | SessionBackingOff | SessionConnecting<ConnType> | SessionHandshaking<ConnType> | SessionConnected<ConnType>;
418
+ type ServerSession<ConnType extends Connection> = SessionConnected<ConnType> | SessionNoConnection;
419
+ type Session<ConnType extends Connection> = ClientSession<ConnType> | ServerSession<ConnType>;
577
420
 
578
421
  declare abstract class ClientTransport<ConnType extends Connection> extends Transport<ConnType> {
579
422
  /**
@@ -1563,4 +1406,161 @@ declare class ServiceScaffold<State extends object> {
1563
1406
  }>;
1564
1407
  }
1565
1408
 
1566
- export { ResultUnwrapOk as $, AnyServiceSchemaMap as A, StreamProcedure as B, ClientTransport as C, Readable as D, Procedure as E, ProcedureErrorSchemaType as F, flattenErrorType as G, UNCAUGHT_ERROR_CODE as H, InstantiatedServiceSchemaMap as I, UNEXPECTED_DISCONNECT_CODE as J, INVALID_REQUEST_CODE as K, CANCEL_CODE as L, ReaderErrorSchema as M, BaseErrorSchemaType as N, createClient as O, ProvidedClientTransportOptions as P, Client 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, ProcedureHandlerContext as e, PayloadType as f, ServiceContext as g, Service as h, ServiceConfiguration as i, ProcHandler as j, ProcInit as k, ProcRequest as l, ProcResponse as m, ProcErrors as n, ProcType as o, ServiceSchema as p, SerializedServerSchema as q, SerializedServiceSchema as r, serializeSchema as s, SerializedProcedureSchema as t, serializeSchemaV1Compat as u, SerializedServerSchemaProtocolv1 as v, SerializedServiceSchemaProtocolv1 as w, SerializedProcedureSchemaProtocolv1 as x, ProcedureMap as y, SubscriptionProcedure 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 };