@replit/river 0.216.1 → 0.217.1

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