@replit/river 0.208.4 → 0.209.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 (59) hide show
  1. package/README.md +36 -1
  2. package/dist/{adapter-ChksXKVN.d.ts → adapter-Cp7_gIVA.d.ts} +1 -1
  3. package/dist/{adapter-Cuc4JtfV.d.cts → adapter-DjiEwOYi.d.cts} +1 -1
  4. package/dist/{chunk-NJNR3MK5.js → chunk-LPWARXI3.js} +2 -2
  5. package/dist/{chunk-N62U4PDY.js → chunk-RATCBAZE.js} +174 -168
  6. package/dist/chunk-RATCBAZE.js.map +1 -0
  7. package/dist/{chunk-7TKRCDKJ.js → chunk-TVN2TB6X.js} +2 -2
  8. package/dist/{chunk-7TKRCDKJ.js.map → chunk-TVN2TB6X.js.map} +1 -1
  9. package/dist/client-BzJwq-hg.d.ts +54 -0
  10. package/dist/client-aETS93z1.d.cts +54 -0
  11. package/dist/codec/index.d.cts +3 -3
  12. package/dist/codec/index.d.ts +3 -3
  13. package/dist/codec/index.js +2 -2
  14. package/dist/{connection-Donr3JRB.d.ts → connection-b1wd5XrC.d.ts} +3 -3
  15. package/dist/{connection-BF4zg6Qv.d.cts → connection-hUWlS-hg.d.cts} +3 -3
  16. package/dist/{index-D8IOd3LG.d.ts → index-CSM8soK7.d.ts} +1 -1
  17. package/dist/{index-C9tpZjBN.d.cts → index-D9R6UTMl.d.cts} +1 -1
  18. package/dist/logging/index.d.cts +2 -2
  19. package/dist/logging/index.d.ts +2 -2
  20. package/dist/{message-Di94OL80.d.cts → message-Dlsh5WDF.d.cts} +1 -1
  21. package/dist/{message-Di94OL80.d.ts → message-Dlsh5WDF.d.ts} +1 -1
  22. package/dist/router/index.cjs +174 -168
  23. package/dist/router/index.cjs.map +1 -1
  24. package/dist/router/index.d.cts +21 -18
  25. package/dist/router/index.d.ts +21 -18
  26. package/dist/router/index.js +3 -3
  27. package/dist/server-BBgDVOzk.d.cts +72 -0
  28. package/dist/server-DZ0Yzmpf.d.ts +72 -0
  29. package/dist/services-DBvjc-Mq.d.ts +1010 -0
  30. package/dist/services-DC_uol9A.d.cts +1010 -0
  31. package/dist/testUtil/index.cjs +1 -1
  32. package/dist/testUtil/index.cjs.map +1 -1
  33. package/dist/testUtil/index.d.cts +9 -7
  34. package/dist/testUtil/index.d.ts +9 -7
  35. package/dist/testUtil/index.js +2 -2
  36. package/dist/testUtil/index.js.map +1 -1
  37. package/dist/transport/impls/ws/client.cjs +1 -1
  38. package/dist/transport/impls/ws/client.cjs.map +1 -1
  39. package/dist/transport/impls/ws/client.d.cts +6 -5
  40. package/dist/transport/impls/ws/client.d.ts +6 -5
  41. package/dist/transport/impls/ws/client.js +3 -3
  42. package/dist/transport/impls/ws/server.cjs +1 -1
  43. package/dist/transport/impls/ws/server.cjs.map +1 -1
  44. package/dist/transport/impls/ws/server.d.cts +8 -8
  45. package/dist/transport/impls/ws/server.d.ts +8 -8
  46. package/dist/transport/impls/ws/server.js +3 -3
  47. package/dist/transport/impls/ws/server.js.map +1 -1
  48. package/dist/transport/index.cjs +1 -1
  49. package/dist/transport/index.cjs.map +1 -1
  50. package/dist/transport/index.d.cts +7 -74
  51. package/dist/transport/index.d.ts +7 -74
  52. package/dist/transport/index.js +2 -2
  53. package/dist/transport-CxjUaGhi.d.cts +577 -0
  54. package/dist/transport-DwEB67zY.d.ts +577 -0
  55. package/package.json +1 -1
  56. package/dist/chunk-N62U4PDY.js.map +0 -1
  57. package/dist/transport-CCaWx1Rb.d.cts +0 -1566
  58. package/dist/transport-CZb3vdB4.d.ts +0 -1566
  59. /package/dist/{chunk-NJNR3MK5.js.map → chunk-LPWARXI3.js.map} +0 -0
@@ -0,0 +1,577 @@
1
+ import { TSchema, Static } from '@sinclair/typebox';
2
+ import { f as TelemetryInfo, c as TransportClientId, P as ProtocolVersion, b as OpaqueTransportMessage, e as PartialTransportMessage, a as TransportMessage, g as HandshakeErrorCustomHandlerFatalResponseCodes, H as HandshakeErrorResponseCodes } from './message-Dlsh5WDF.cjs';
3
+ import { M as MessageMetadata, L as Logger, T as Tags, a as LogFn, b as LoggingLevel } from './index-D9R6UTMl.cjs';
4
+ import { C as Codec, a as CodecMessageAdapter, S as SendResult, b as SendBufferResult } from './adapter-DjiEwOYi.cjs';
5
+ import { Tracer } from '@opentelemetry/api';
6
+
7
+ /**
8
+ * A connection is the actual raw underlying transport connection.
9
+ * It's responsible for dispatching to/from the actual connection itself
10
+ * This should be instantiated as soon as the client/server has a connection
11
+ * It's tied to the lifecycle of the underlying transport connection (i.e. if the WS drops, this connection should be deleted)
12
+ */
13
+ declare abstract class Connection {
14
+ id: string;
15
+ telemetry?: TelemetryInfo;
16
+ constructor();
17
+ get loggingMetadata(): MessageMetadata;
18
+ dataListener?: (msg: Uint8Array) => void;
19
+ closeListener?: () => void;
20
+ errorListener?: (err: Error) => void;
21
+ onData(msg: Uint8Array): void;
22
+ onError(err: Error): void;
23
+ onClose(): void;
24
+ /**
25
+ * Set the callback for when a message is received.
26
+ * @param cb The message handler callback.
27
+ */
28
+ setDataListener(cb: (msg: Uint8Array) => void): void;
29
+ removeDataListener(): void;
30
+ /**
31
+ * Set the callback for when the connection is closed.
32
+ * This should also be called if an error happens and after notifying the error listener.
33
+ * @param cb The callback to call when the connection is closed.
34
+ */
35
+ setCloseListener(cb: () => void): void;
36
+ removeCloseListener(): void;
37
+ /**
38
+ * Set the callback for when an error is received.
39
+ * This should only be used for logging errors, all cleanup
40
+ * should be delegated to setCloseListener.
41
+ *
42
+ * The implementer should take care such that the implemented
43
+ * connection will call both the close and error callbacks
44
+ * on an error.
45
+ *
46
+ * @param cb The callback to call when an error is received.
47
+ */
48
+ setErrorListener(cb: (err: Error) => void): void;
49
+ removeErrorListener(): void;
50
+ /**
51
+ * Sends a message over the connection.
52
+ * @param msg The message to send.
53
+ * @returns true if the message was sent, false otherwise.
54
+ */
55
+ abstract send(msg: Uint8Array): boolean;
56
+ /**
57
+ * Closes the connection.
58
+ */
59
+ abstract close(): void;
60
+ }
61
+
62
+ declare const enum SessionState {
63
+ NoConnection = "NoConnection",
64
+ BackingOff = "BackingOff",
65
+ Connecting = "Connecting",
66
+ Handshaking = "Handshaking",
67
+ Connected = "Connected",
68
+ WaitingForHandshake = "WaitingForHandshake"
69
+ }
70
+ declare abstract class StateMachineState {
71
+ abstract readonly state: SessionState;
72
+ _isConsumed: boolean;
73
+ abstract _handleStateExit(): void;
74
+ abstract _handleClose(): void;
75
+ /**
76
+ * Cleanup this state machine state and mark it as consumed.
77
+ * After calling close, it is an error to access any properties on the state.
78
+ * You should never need to call this as a consumer.
79
+ *
80
+ * If you're looking to close the session from the client,
81
+ * use `.hardDisconnect` on the client transport.
82
+ */
83
+ close(): void;
84
+ constructor();
85
+ }
86
+ interface SessionOptions {
87
+ /**
88
+ * Frequency at which to send heartbeat acknowledgements
89
+ */
90
+ heartbeatIntervalMs: number;
91
+ /**
92
+ * Number of elapsed heartbeats without a response message before we consider
93
+ * the connection dead.
94
+ */
95
+ heartbeatsUntilDead: number;
96
+ /**
97
+ * Max duration that a session can be without a connection before we consider
98
+ * it dead. This deadline is carried between states and is used to determine
99
+ * when to consider the session a lost cause and delete it entirely.
100
+ * Generally, this should be strictly greater than the sum of
101
+ * {@link connectionTimeoutMs} and {@link handshakeTimeoutMs}.
102
+ */
103
+ sessionDisconnectGraceMs: number;
104
+ /**
105
+ * Connection timeout in milliseconds
106
+ */
107
+ connectionTimeoutMs: number;
108
+ /**
109
+ * Handshake timeout in milliseconds
110
+ */
111
+ handshakeTimeoutMs: number;
112
+ /**
113
+ * Whether to enable transparent session reconnects
114
+ */
115
+ enableTransparentSessionReconnects: boolean;
116
+ /**
117
+ * The codec to use for encoding/decoding messages over the wire
118
+ */
119
+ codec: Codec;
120
+ }
121
+ interface CommonSessionProps {
122
+ from: TransportClientId;
123
+ options: SessionOptions;
124
+ codec: CodecMessageAdapter;
125
+ tracer: Tracer;
126
+ log: Logger | undefined;
127
+ }
128
+ declare abstract class CommonSession extends StateMachineState {
129
+ readonly from: TransportClientId;
130
+ readonly options: SessionOptions;
131
+ readonly codec: CodecMessageAdapter;
132
+ tracer: Tracer;
133
+ log?: Logger;
134
+ abstract get loggingMetadata(): MessageMetadata;
135
+ constructor({ from, options, log, tracer, codec }: CommonSessionProps);
136
+ }
137
+ type SessionId = string;
138
+ interface IdentifiedSessionProps extends CommonSessionProps {
139
+ id: SessionId;
140
+ to: TransportClientId;
141
+ seq: number;
142
+ ack: number;
143
+ seqSent: number;
144
+ sendBuffer: Array<OpaqueTransportMessage>;
145
+ telemetry: TelemetryInfo;
146
+ protocolVersion: ProtocolVersion;
147
+ }
148
+ declare abstract class IdentifiedSession extends CommonSession {
149
+ readonly id: SessionId;
150
+ readonly telemetry: TelemetryInfo;
151
+ readonly to: TransportClientId;
152
+ readonly protocolVersion: ProtocolVersion;
153
+ /**
154
+ * Index of the message we will send next (excluding handshake)
155
+ */
156
+ seq: number;
157
+ /**
158
+ * Last seq we sent over the wire this session (excluding handshake) and retransmissions
159
+ */
160
+ seqSent: number;
161
+ /**
162
+ * Number of unique messages we've received this session (excluding handshake)
163
+ */
164
+ ack: number;
165
+ sendBuffer: Array<OpaqueTransportMessage>;
166
+ constructor(props: IdentifiedSessionProps);
167
+ get loggingMetadata(): MessageMetadata;
168
+ constructMsg<Payload>(partialMsg: PartialTransportMessage<Payload>): TransportMessage<Payload>;
169
+ nextSeq(): number;
170
+ send(msg: PartialTransportMessage): SendResult;
171
+ _handleStateExit(): void;
172
+ _handleClose(): void;
173
+ }
174
+ interface IdentifiedSessionWithGracePeriodListeners {
175
+ onSessionGracePeriodElapsed: () => void;
176
+ }
177
+ interface IdentifiedSessionWithGracePeriodProps extends IdentifiedSessionProps {
178
+ graceExpiryTime: number;
179
+ listeners: IdentifiedSessionWithGracePeriodListeners;
180
+ }
181
+ declare abstract class IdentifiedSessionWithGracePeriod extends IdentifiedSession {
182
+ graceExpiryTime: number;
183
+ protected gracePeriodTimeout?: ReturnType<typeof setTimeout>;
184
+ listeners: IdentifiedSessionWithGracePeriodListeners;
185
+ constructor(props: IdentifiedSessionWithGracePeriodProps);
186
+ _handleStateExit(): void;
187
+ _handleClose(): void;
188
+ }
189
+
190
+ type ConstructHandshake<T extends TSchema> = () => Static<T> | Promise<Static<T>>;
191
+ type ValidateHandshake<T extends TSchema, ParsedMetadata> = (metadata: Static<T>, previousParsedMetadata?: ParsedMetadata) => Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata | Promise<Static<typeof HandshakeErrorCustomHandlerFatalResponseCodes> | ParsedMetadata>;
192
+ interface ClientHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
193
+ /**
194
+ * Schema for the metadata that the client sends to the server
195
+ * during the handshake.
196
+ */
197
+ schema: MetadataSchema;
198
+ /**
199
+ * Gets the {@link HandshakeRequestMetadata} to send to the server.
200
+ */
201
+ construct: ConstructHandshake<MetadataSchema>;
202
+ }
203
+ interface ServerHandshakeOptions<MetadataSchema extends TSchema = TSchema, ParsedMetadata extends object = object> {
204
+ /**
205
+ * Schema for the metadata that the server receives from the client
206
+ * during the handshake.
207
+ */
208
+ schema: MetadataSchema;
209
+ /**
210
+ * Parses the {@link HandshakeRequestMetadata} sent by the client, transforming
211
+ * it into {@link ParsedHandshakeMetadata}.
212
+ *
213
+ * May return `false` if the client should be rejected.
214
+ *
215
+ * @param metadata - The metadata sent by the client.
216
+ * @param session - The session that the client would be associated with.
217
+ * @param isReconnect - Whether the client is reconnecting to the session,
218
+ * or if this is a new session.
219
+ */
220
+ validate: ValidateHandshake<MetadataSchema, ParsedMetadata>;
221
+ }
222
+ declare function createClientHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, construct: ConstructHandshake<MetadataSchema>): ClientHandshakeOptions;
223
+ declare function createServerHandshakeOptions<MetadataSchema extends TSchema = TSchema, ParsedMetadata extends object = object>(schema: MetadataSchema, validate: ValidateHandshake<MetadataSchema, ParsedMetadata>): ServerHandshakeOptions<MetadataSchema, ParsedMetadata>;
224
+
225
+ /**
226
+ * Options to control the backoff and retry behavior of the client transport's connection behaviour.
227
+ *
228
+ * River implements exponential backoff with jitter to prevent flooding the server
229
+ * when there's an issue with connection establishment.
230
+ *
231
+ * The backoff is calculated via the following:
232
+ * backOff = min(jitter + {@link baseIntervalMs} * 2 ^ budget_consumed, {@link maxBackoffMs})
233
+ *
234
+ * We use a leaky bucket rate limit with a budget of {@link attemptBudgetCapacity} reconnection attempts.
235
+ * Budget only starts to restore after a successful handshake at a rate of one budget per {@link budgetRestoreIntervalMs}.
236
+ */
237
+ interface ConnectionRetryOptions {
238
+ /**
239
+ * The base interval to wait before retrying a connection.
240
+ */
241
+ baseIntervalMs: number;
242
+ /**
243
+ * The maximum random jitter to add to the total backoff time.
244
+ */
245
+ maxJitterMs: number;
246
+ /**
247
+ * The maximum amount of time to wait before retrying a connection.
248
+ * This does not include the jitter.
249
+ */
250
+ maxBackoffMs: number;
251
+ /**
252
+ * The max number of times to attempt a connection before a successful handshake.
253
+ * This persists across connections but starts restoring budget after a successful handshake.
254
+ * The restoration interval depends on {@link budgetRestoreIntervalMs}
255
+ */
256
+ attemptBudgetCapacity: number;
257
+ /**
258
+ * After a successful connection attempt, how long to wait before we restore a single budget.
259
+ */
260
+ budgetRestoreIntervalMs: number;
261
+ }
262
+ declare class LeakyBucketRateLimit {
263
+ private budgetConsumed;
264
+ private intervalHandle?;
265
+ private readonly options;
266
+ constructor(options: ConnectionRetryOptions);
267
+ getBackoffMs(): number;
268
+ get totalBudgetRestoreTime(): number;
269
+ consumeBudget(): void;
270
+ getBudgetConsumed(): number;
271
+ hasBudget(): boolean;
272
+ startRestoringBudget(): void;
273
+ private stopLeak;
274
+ close(): void;
275
+ }
276
+
277
+ type TransportOptions = SessionOptions;
278
+ type ProvidedTransportOptions = Partial<TransportOptions>;
279
+ type ClientTransportOptions = TransportOptions & ConnectionRetryOptions;
280
+ type ProvidedClientTransportOptions = Partial<ClientTransportOptions>;
281
+ type ServerTransportOptions = TransportOptions;
282
+ type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;
283
+
284
+ interface SessionConnectingListeners extends IdentifiedSessionWithGracePeriodListeners {
285
+ onConnectionEstablished: (conn: Connection) => void;
286
+ onConnectionFailed: (err: unknown) => void;
287
+ onConnectionTimeout: () => void;
288
+ }
289
+ interface SessionConnectingProps<ConnType extends Connection> extends IdentifiedSessionWithGracePeriodProps {
290
+ connPromise: Promise<ConnType>;
291
+ listeners: SessionConnectingListeners;
292
+ }
293
+ declare class SessionConnecting<ConnType extends Connection> extends IdentifiedSessionWithGracePeriod {
294
+ readonly state: SessionState.Connecting;
295
+ connPromise: Promise<ConnType>;
296
+ listeners: SessionConnectingListeners;
297
+ connectionTimeout?: ReturnType<typeof setTimeout>;
298
+ constructor(props: SessionConnectingProps<ConnType>);
299
+ bestEffortClose(): void;
300
+ _handleStateExit(): void;
301
+ _handleClose(): void;
302
+ }
303
+
304
+ interface SessionHandshakingListeners extends IdentifiedSessionWithGracePeriodListeners {
305
+ onConnectionErrored: (err: unknown) => void;
306
+ onConnectionClosed: () => void;
307
+ onHandshake: (msg: OpaqueTransportMessage) => void;
308
+ onInvalidHandshake: (reason: string, code: Static<typeof HandshakeErrorResponseCodes>) => void;
309
+ onHandshakeTimeout: () => void;
310
+ }
311
+ interface SessionHandshakingProps<ConnType extends Connection> extends IdentifiedSessionWithGracePeriodProps {
312
+ conn: ConnType;
313
+ listeners: SessionHandshakingListeners;
314
+ }
315
+ declare class SessionHandshaking<ConnType extends Connection> extends IdentifiedSessionWithGracePeriod {
316
+ readonly state: SessionState.Handshaking;
317
+ conn: ConnType;
318
+ listeners: SessionHandshakingListeners;
319
+ handshakeTimeout?: ReturnType<typeof setTimeout>;
320
+ constructor(props: SessionHandshakingProps<ConnType>);
321
+ get loggingMetadata(): {
322
+ protocolVersion?: ProtocolVersion | undefined;
323
+ clientId?: string | undefined;
324
+ connectedTo?: string | undefined;
325
+ sessionId?: string | undefined;
326
+ connId?: string | undefined;
327
+ transportMessage?: Partial<OpaqueTransportMessage> | undefined;
328
+ validationErrors?: {
329
+ path: string;
330
+ message: string;
331
+ }[] | undefined;
332
+ tags?: Tags[] | undefined;
333
+ telemetry?: {
334
+ traceId: string;
335
+ spanId: string;
336
+ } | undefined;
337
+ extras?: Record<string, unknown> | undefined;
338
+ };
339
+ onHandshakeData: (msg: Uint8Array) => void;
340
+ sendHandshake(msg: TransportMessage): SendResult;
341
+ _handleStateExit(): void;
342
+ _handleClose(): void;
343
+ }
344
+
345
+ interface SessionConnectedListeners {
346
+ onConnectionErrored: (err: unknown) => void;
347
+ onConnectionClosed: () => void;
348
+ onMessage: (msg: OpaqueTransportMessage) => void;
349
+ onMessageSendFailure: (msg: PartialTransportMessage, reason: string) => void;
350
+ onInvalidMessage: (reason: string) => void;
351
+ }
352
+ interface SessionConnectedProps<ConnType extends Connection> extends IdentifiedSessionProps {
353
+ conn: ConnType;
354
+ listeners: SessionConnectedListeners;
355
+ }
356
+ declare class SessionConnected<ConnType extends Connection> extends IdentifiedSession {
357
+ readonly state: SessionState.Connected;
358
+ conn: ConnType;
359
+ listeners: SessionConnectedListeners;
360
+ private heartbeatHandle?;
361
+ private heartbeatMissTimeout?;
362
+ private isActivelyHeartbeating;
363
+ updateBookkeeping(ack: number, seq: number): void;
364
+ private assertSendOrdering;
365
+ send(msg: PartialTransportMessage): SendResult;
366
+ constructor(props: SessionConnectedProps<ConnType>);
367
+ sendBufferedMessages(): SendBufferResult;
368
+ get loggingMetadata(): {
369
+ protocolVersion?: ProtocolVersion | undefined;
370
+ clientId?: string | undefined;
371
+ connectedTo?: string | undefined;
372
+ sessionId?: string | undefined;
373
+ connId?: string | undefined;
374
+ transportMessage?: Partial<OpaqueTransportMessage> | undefined;
375
+ validationErrors?: {
376
+ path: string;
377
+ message: string;
378
+ }[] | undefined;
379
+ tags?: Tags[] | undefined;
380
+ telemetry?: {
381
+ traceId: string;
382
+ spanId: string;
383
+ } | undefined;
384
+ extras?: Record<string, unknown> | undefined;
385
+ };
386
+ startMissingHeartbeatTimeout(): void;
387
+ startActiveHeartbeat(): void;
388
+ private sendHeartbeat;
389
+ onMessageData: (msg: Uint8Array) => void;
390
+ _handleStateExit(): void;
391
+ _handleClose(): void;
392
+ }
393
+
394
+ declare class SessionNoConnection extends IdentifiedSessionWithGracePeriod {
395
+ readonly state: SessionState.NoConnection;
396
+ _handleClose(): void;
397
+ _handleStateExit(): void;
398
+ }
399
+
400
+ interface SessionBackingOffListeners extends IdentifiedSessionWithGracePeriodListeners {
401
+ onBackoffFinished: () => void;
402
+ }
403
+ interface SessionBackingOffProps extends IdentifiedSessionWithGracePeriodProps {
404
+ backoffMs: number;
405
+ listeners: SessionBackingOffListeners;
406
+ }
407
+ declare class SessionBackingOff extends IdentifiedSessionWithGracePeriod {
408
+ readonly state: SessionState.BackingOff;
409
+ listeners: SessionBackingOffListeners;
410
+ backoffTimeout?: ReturnType<typeof setTimeout>;
411
+ constructor(props: SessionBackingOffProps);
412
+ _handleClose(): void;
413
+ _handleStateExit(): void;
414
+ }
415
+
416
+ type ClientSession<ConnType extends Connection> = SessionNoConnection | SessionBackingOff | SessionConnecting<ConnType> | SessionHandshaking<ConnType> | SessionConnected<ConnType>;
417
+ type ServerSession<ConnType extends Connection> = SessionConnected<ConnType> | SessionNoConnection;
418
+ type Session<ConnType extends Connection> = ClientSession<ConnType> | ServerSession<ConnType>;
419
+
420
+ declare const ProtocolError: {
421
+ readonly RetriesExceeded: "conn_retry_exceeded";
422
+ readonly HandshakeFailed: "handshake_failed";
423
+ readonly MessageOrderingViolated: "message_ordering_violated";
424
+ readonly InvalidMessage: "invalid_message";
425
+ readonly MessageSendFailure: "message_send_failure";
426
+ };
427
+ type ProtocolErrorType = (typeof ProtocolError)[keyof typeof ProtocolError];
428
+ interface EventMap {
429
+ message: OpaqueTransportMessage;
430
+ sessionStatus: {
431
+ status: 'created' | 'closing';
432
+ session: Session<Connection>;
433
+ } | {
434
+ status: 'closed';
435
+ session: Pick<Session<Connection>, 'id' | 'to'>;
436
+ };
437
+ sessionTransition: {
438
+ state: SessionState.Connected;
439
+ id: SessionId;
440
+ } | {
441
+ state: SessionState.Handshaking;
442
+ id: SessionId;
443
+ } | {
444
+ state: SessionState.Connecting;
445
+ id: SessionId;
446
+ } | {
447
+ state: SessionState.BackingOff;
448
+ id: SessionId;
449
+ } | {
450
+ state: SessionState.NoConnection;
451
+ id: SessionId;
452
+ };
453
+ protocolError: {
454
+ type: (typeof ProtocolError)['HandshakeFailed'];
455
+ code: Static<typeof HandshakeErrorResponseCodes>;
456
+ message: string;
457
+ } | {
458
+ type: Omit<ProtocolErrorType, (typeof ProtocolError)['HandshakeFailed']>;
459
+ message: string;
460
+ };
461
+ transportStatus: {
462
+ status: TransportStatus;
463
+ };
464
+ }
465
+ type EventTypes = keyof EventMap;
466
+ type EventHandler<K extends EventTypes> = (event: EventMap[K]) => unknown;
467
+ declare class EventDispatcher<T extends EventTypes> {
468
+ private eventListeners;
469
+ removeAllListeners(): void;
470
+ numberOfListeners<K extends T>(eventType: K): number;
471
+ addEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
472
+ removeEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
473
+ dispatchEvent<K extends T>(eventType: K, event: EventMap[K]): void;
474
+ }
475
+
476
+ /**
477
+ * Represents the possible states of a transport.
478
+ * @property {'open'} open - The transport is open and operational (note that this doesn't mean it is actively connected)
479
+ * @property {'closed'} closed - The transport is permanently closed and cannot be reopened.
480
+ */
481
+ type TransportStatus = 'open' | 'closed';
482
+ interface DeleteSessionOptions {
483
+ unhealthy: boolean;
484
+ }
485
+ type SessionBoundSendFn = (msg: PartialTransportMessage) => string;
486
+ /**
487
+ * Transports manage the lifecycle (creation/deletion) of sessions
488
+ *
489
+ * ```plaintext
490
+ * ▲
491
+ * incoming │
492
+ * messages │
493
+ * ▼
494
+ * ┌─────────────┐ 1:N ┌───────────┐ 1:1* ┌────────────┐
495
+ * │ Transport │ ◄─────► │ Session │ ◄─────► │ Connection │
496
+ * └─────────────┘ └───────────┘ └────────────┘
497
+ * ▲ * (may or may not be initialized yet)
498
+ * │
499
+ * ▼
500
+ * ┌───────────┐
501
+ * │ Message │
502
+ * │ Listeners │
503
+ * └───────────┘
504
+ * ```
505
+ * @abstract
506
+ */
507
+ declare abstract class Transport<ConnType extends Connection> {
508
+ /**
509
+ * The status of the transport.
510
+ */
511
+ private status;
512
+ /**
513
+ * The client ID of this transport.
514
+ */
515
+ clientId: TransportClientId;
516
+ /**
517
+ * The event dispatcher for handling events of type EventTypes.
518
+ */
519
+ eventDispatcher: EventDispatcher<EventTypes>;
520
+ /**
521
+ * The options for this transport.
522
+ */
523
+ protected options: TransportOptions;
524
+ log?: Logger;
525
+ tracer: Tracer;
526
+ sessions: Map<TransportClientId, Session<ConnType>>;
527
+ /**
528
+ * Creates a new Transport instance.
529
+ * @param codec The codec used to encode and decode messages.
530
+ * @param clientId The client ID of this transport.
531
+ */
532
+ constructor(clientId: TransportClientId, providedOptions?: ProvidedTransportOptions);
533
+ bindLogger(fn: LogFn | Logger, level?: LoggingLevel): void;
534
+ /**
535
+ * Called when a message is received by this transport.
536
+ * You generally shouldn't need to override this in downstream transport implementations.
537
+ * @param message The received message.
538
+ */
539
+ protected handleMsg(message: OpaqueTransportMessage): void;
540
+ /**
541
+ * Adds a listener to this transport.
542
+ * @param the type of event to listen for
543
+ * @param handler The message handler to add.
544
+ */
545
+ addEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
546
+ /**
547
+ * Removes a listener from this transport.
548
+ * @param the type of event to un-listen on
549
+ * @param handler The message handler to remove.
550
+ */
551
+ removeEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
552
+ protected protocolError(message: EventMap['protocolError']): void;
553
+ /**
554
+ * Default close implementation for transports. You should override this in the downstream
555
+ * implementation if you need to do any additional cleanup and call super.close() at the end.
556
+ * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
557
+ */
558
+ close(): void;
559
+ getStatus(): TransportStatus;
560
+ protected createSession<S extends Session<ConnType>>(session: S): void;
561
+ protected updateSession<S extends Session<ConnType>>(session: S): void;
562
+ protected deleteSession(session: Session<ConnType>, options?: DeleteSessionOptions): void;
563
+ protected onSessionGracePeriodElapsed(session: Session<ConnType>): void;
564
+ protected onConnectingFailed(session: SessionConnecting<ConnType>): SessionNoConnection;
565
+ protected onConnClosed(session: SessionHandshaking<ConnType> | SessionConnected<ConnType>): SessionNoConnection;
566
+ /**
567
+ * Gets a send closure scoped to a specific session. Sending using the returned
568
+ * closure after the session has transitioned to a different state will be a noop.
569
+ *
570
+ * Session objects themselves can become stale as they transition between
571
+ * states. As stale sessions cannot be used again (and will throw), holding
572
+ * onto a session object is not recommended.
573
+ */
574
+ getSessionBoundSendFn(to: TransportClientId, sessionId: SessionId): SessionBoundSendFn;
575
+ }
576
+
577
+ export { Connection as C, type DeleteSessionOptions as D, type EventMap as E, LeakyBucketRateLimit as L, type ProvidedTransportOptions as P, type Session as S, Transport as T, type TransportStatus as a, type ProvidedClientTransportOptions as b, type ProvidedServerTransportOptions as c, SessionState as d, SessionNoConnection as e, SessionConnecting as f, SessionHandshaking as g, SessionConnected as h, type EventTypes as i, type EventHandler as j, ProtocolError as k, type ProtocolErrorType as l, type ClientTransportOptions as m, type ClientHandshakeOptions as n, type ClientSession as o, SessionBackingOff as p, type ServerHandshakeOptions as q, createClientHandshakeOptions as r, createServerHandshakeOptions as s, CommonSession as t, type CommonSessionProps as u, type ServerTransportOptions as v, type ServerSession as w, type SessionOptions as x, type SessionBoundSendFn as y, type SessionId as z };