@replit/river 0.200.0-rc.2 → 0.200.0-rc.4

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 (84) hide show
  1. package/README.md +21 -20
  2. package/dist/chunk-2BF4VMUZ.js +50 -0
  3. package/dist/chunk-2BF4VMUZ.js.map +1 -0
  4. package/dist/chunk-BZQQXMVF.js +401 -0
  5. package/dist/chunk-BZQQXMVF.js.map +1 -0
  6. package/dist/{chunk-4VNY34QG.js → chunk-F7Z2QQRL.js} +24 -18
  7. package/dist/chunk-F7Z2QQRL.js.map +1 -0
  8. package/dist/chunk-IMFMNIEO.js +384 -0
  9. package/dist/chunk-IMFMNIEO.js.map +1 -0
  10. package/dist/chunk-RDGHFHXN.js +658 -0
  11. package/dist/chunk-RDGHFHXN.js.map +1 -0
  12. package/dist/chunk-SI4YHBTI.js +277 -0
  13. package/dist/chunk-SI4YHBTI.js.map +1 -0
  14. package/dist/{chunk-7CKIN3JT.js → chunk-SIRRYRLQ.js} +73 -490
  15. package/dist/chunk-SIRRYRLQ.js.map +1 -0
  16. package/dist/{chunk-S5RL45KH.js → chunk-V57VWV5S.js} +80 -44
  17. package/dist/chunk-V57VWV5S.js.map +1 -0
  18. package/dist/{chunk-QMM35C3H.js → chunk-VXYHC666.js} +1 -1
  19. package/dist/chunk-VXYHC666.js.map +1 -0
  20. package/dist/client-f56a6da3.d.ts +49 -0
  21. package/dist/{connection-f900e390.d.ts → connection-11991b13.d.ts} +1 -5
  22. package/dist/connection-6031a354.d.ts +11 -0
  23. package/dist/context-73df8978.d.ts +528 -0
  24. package/dist/logging/index.cjs.map +1 -1
  25. package/dist/logging/index.d.cts +1 -1
  26. package/dist/logging/index.d.ts +1 -1
  27. package/dist/logging/index.js +1 -1
  28. package/dist/{index-10ebd26a.d.ts → message-fd349b27.d.ts} +31 -31
  29. package/dist/router/index.cjs +125 -502
  30. package/dist/router/index.cjs.map +1 -1
  31. package/dist/router/index.d.cts +11 -46
  32. package/dist/router/index.d.ts +11 -46
  33. package/dist/router/index.js +2 -4
  34. package/dist/server-9f31d98f.d.ts +42 -0
  35. package/dist/{services-970f97bb.d.ts → services-c67758fc.d.ts} +5 -602
  36. package/dist/transport/impls/uds/client.cjs +1247 -1238
  37. package/dist/transport/impls/uds/client.cjs.map +1 -1
  38. package/dist/transport/impls/uds/client.d.cts +4 -3
  39. package/dist/transport/impls/uds/client.d.ts +4 -3
  40. package/dist/transport/impls/uds/client.js +7 -13
  41. package/dist/transport/impls/uds/client.js.map +1 -1
  42. package/dist/transport/impls/uds/server.cjs +1311 -1170
  43. package/dist/transport/impls/uds/server.cjs.map +1 -1
  44. package/dist/transport/impls/uds/server.d.cts +4 -4
  45. package/dist/transport/impls/uds/server.d.ts +4 -4
  46. package/dist/transport/impls/uds/server.js +6 -6
  47. package/dist/transport/impls/ws/client.cjs +988 -987
  48. package/dist/transport/impls/ws/client.cjs.map +1 -1
  49. package/dist/transport/impls/ws/client.d.cts +6 -5
  50. package/dist/transport/impls/ws/client.d.ts +6 -5
  51. package/dist/transport/impls/ws/client.js +6 -7
  52. package/dist/transport/impls/ws/client.js.map +1 -1
  53. package/dist/transport/impls/ws/server.cjs +1192 -1066
  54. package/dist/transport/impls/ws/server.cjs.map +1 -1
  55. package/dist/transport/impls/ws/server.d.cts +4 -4
  56. package/dist/transport/impls/ws/server.d.ts +4 -4
  57. package/dist/transport/impls/ws/server.js +6 -6
  58. package/dist/transport/index.cjs +1446 -1380
  59. package/dist/transport/index.cjs.map +1 -1
  60. package/dist/transport/index.d.cts +4 -26
  61. package/dist/transport/index.d.ts +4 -26
  62. package/dist/transport/index.js +9 -9
  63. package/dist/util/testHelpers.cjs +746 -303
  64. package/dist/util/testHelpers.cjs.map +1 -1
  65. package/dist/util/testHelpers.d.cts +9 -4
  66. package/dist/util/testHelpers.d.ts +9 -4
  67. package/dist/util/testHelpers.js +36 -10
  68. package/dist/util/testHelpers.js.map +1 -1
  69. package/package.json +1 -1
  70. package/dist/chunk-47TFNAY2.js +0 -476
  71. package/dist/chunk-47TFNAY2.js.map +0 -1
  72. package/dist/chunk-4VNY34QG.js.map +0 -1
  73. package/dist/chunk-7CKIN3JT.js.map +0 -1
  74. package/dist/chunk-CZP4LK3F.js +0 -335
  75. package/dist/chunk-CZP4LK3F.js.map +0 -1
  76. package/dist/chunk-DJCW3SKT.js +0 -59
  77. package/dist/chunk-DJCW3SKT.js.map +0 -1
  78. package/dist/chunk-NQWDT6GS.js +0 -347
  79. package/dist/chunk-NQWDT6GS.js.map +0 -1
  80. package/dist/chunk-ONUXWVRC.js +0 -492
  81. package/dist/chunk-ONUXWVRC.js.map +0 -1
  82. package/dist/chunk-QMM35C3H.js.map +0 -1
  83. package/dist/chunk-S5RL45KH.js.map +0 -1
  84. package/dist/connection-3f117047.d.ts +0 -17
@@ -1,605 +1,8 @@
1
1
  import * as _sinclair_typebox from '@sinclair/typebox';
2
- import { Static, TSchema, TObject, TUnion, TString, TLiteral, TNever } from '@sinclair/typebox';
3
- import { a as TelemetryInfo, M as MessageMetadata, T as TransportClientId, b as PropagationContext, L as Logger, P as PartialTransportMessage, c as TransportMessage, O as OpaqueTransportMessage, d as LogFn, e as LoggingLevel } from './index-10ebd26a.js';
4
- import { C as Codec } from './types-3e5768ec.js';
5
-
6
- /**
7
- * A connection is the actual raw underlying transport connection.
8
- * It’s responsible for dispatching to/from the actual connection itself
9
- * This should be instantiated as soon as the client/server has a connection
10
- * It’s tied to the lifecycle of the underlying transport connection (i.e. if the WS drops, this connection should be deleted)
11
- */
12
- declare abstract class Connection {
13
- id: string;
14
- telemetry?: TelemetryInfo;
15
- constructor();
16
- get loggingMetadata(): MessageMetadata;
17
- /**
18
- * Handle adding a callback for when a message is received.
19
- * @param msg The message that was received.
20
- */
21
- abstract addDataListener(cb: (msg: Uint8Array) => void): void;
22
- abstract removeDataListener(cb: (msg: Uint8Array) => void): void;
23
- /**
24
- * Handle adding a callback for when the connection is closed.
25
- * This should also be called if an error happens.
26
- * @param cb The callback to call when the connection is closed.
27
- */
28
- abstract addCloseListener(cb: () => void): void;
29
- /**
30
- * Handle adding a callback for when an error is received.
31
- * This should only be used for this.logging errors, all cleanup
32
- * should be delegated to addCloseListener.
33
- *
34
- * The implementer should take care such that the implemented
35
- * connection will call both the close and error callbacks
36
- * on an error.
37
- *
38
- * @param cb The callback to call when an error is received.
39
- */
40
- abstract addErrorListener(cb: (err: Error) => void): void;
41
- /**
42
- * Sends a message over the connection.
43
- * @param msg The message to send.
44
- * @returns true if the message was sent, false otherwise.
45
- */
46
- abstract send(msg: Uint8Array): boolean;
47
- /**
48
- * Closes the connection.
49
- */
50
- abstract close(): void;
51
- }
52
- interface SessionOptions {
53
- /**
54
- * Frequency at which to send heartbeat acknowledgements
55
- */
56
- heartbeatIntervalMs: number;
57
- /**
58
- * Number of elapsed heartbeats without a response message before we consider
59
- * the connection dead.
60
- */
61
- heartbeatsUntilDead: number;
62
- /**
63
- * Duration to wait between connection disconnect and actual session disconnect
64
- */
65
- sessionDisconnectGraceMs: number;
66
- /**
67
- * The codec to use for encoding/decoding messages over the wire
68
- */
69
- codec: Codec;
70
- }
71
- /**
72
- * A session is a higher-level abstraction that operates over the span of potentially multiple transport-level connections
73
- * - It’s responsible for tracking any metadata for a particular client that might need to be persisted across connections (i.e. the sendBuffer, ack, seq)
74
- * - This will only be considered disconnected if
75
- * - the server tells the client that we’ve reconnected but it doesn’t recognize us anymore (server definitely died) or
76
- * - we hit a grace period after a connection disconnect
77
- */
78
- declare class Session<ConnType extends Connection> {
79
- private codec;
80
- private options;
81
- readonly telemetry: TelemetryInfo;
82
- /**
83
- * The buffer of messages that have been sent but not yet acknowledged.
84
- */
85
- private sendBuffer;
86
- /**
87
- * The active connection associated with this session
88
- */
89
- connection?: ConnType;
90
- /**
91
- * A connection that is currently undergoing handshaking. Used to distinguish between the active
92
- * connection, but still be able to close it if needed.
93
- */
94
- private handshakingConnection?;
95
- readonly from: TransportClientId;
96
- readonly to: TransportClientId;
97
- /**
98
- * The unique ID of this session.
99
- */
100
- readonly id: string;
101
- /**
102
- * What the other side advertised as their session ID
103
- * for this session.
104
- */
105
- advertisedSessionId?: string;
106
- /**
107
- * Number of messages we've sent along this session (excluding handshake and acks)
108
- */
109
- private seq;
110
- /**
111
- * Number of unique messages we've received this session (excluding handshake and acks)
112
- */
113
- private ack;
114
- /**
115
- * The grace period between when the inner connection is disconnected
116
- * and when we should consider the entire session disconnected.
117
- */
118
- private disconnectionGrace?;
119
- /**
120
- * Number of heartbeats we've sent without a response.
121
- */
122
- private heartbeatMisses;
123
- /**
124
- * The interval for sending heartbeats.
125
- */
126
- private heartbeat;
127
- private log?;
128
- constructor(conn: ConnType | undefined, from: TransportClientId, to: TransportClientId, options: SessionOptions, propagationCtx?: PropagationContext);
129
- bindLogger(log: Logger): void;
130
- get loggingMetadata(): MessageMetadata;
131
- /**
132
- * Sends a message over the session's connection.
133
- * If the connection is not ready or the message fails to send, the message can be buffered for retry unless skipped.
134
- *
135
- * @param msg The partial message to be sent, which will be constructed into a full message.
136
- * @param addToSendBuff Whether to add the message to the send buffer for retry.
137
- * @returns The full transport ID of the message that was attempted to be sent.
138
- */
139
- send(msg: PartialTransportMessage): string;
140
- sendHeartbeat(): void;
141
- resetBufferedMessages(): void;
142
- sendBufferedMessages(conn: ConnType): void;
143
- updateBookkeeping(ack: number, seq: number): void;
144
- private closeStaleConnection;
145
- replaceWithNewConnection(newConn: ConnType, isTransparentReconnect: boolean): void;
146
- replaceWithNewHandshakingConnection(newConn: ConnType): void;
147
- beginGrace(cb: () => void): void;
148
- cancelGrace(): void;
149
- /**
150
- * Used to close the handshaking connection, if set.
151
- */
152
- closeHandshakingConnection(expectedHandshakingConn?: ConnType): void;
153
- close(): void;
154
- get connected(): boolean;
155
- get nextExpectedAck(): number;
156
- get nextExpectedSeq(): number;
157
- /**
158
- * Check that the peer's next expected seq number matches something that is in our send buffer
159
- * _or_ matches our actual next seq.
160
- */
161
- nextExpectedSeqInRange(nextExpectedSeq: number): boolean;
162
- advanceAckForTesting(by: number): void;
163
- constructMsg<Payload>(partialMsg: PartialTransportMessage<Payload>): TransportMessage<Payload>;
164
- inspectSendBuffer(): ReadonlyArray<OpaqueTransportMessage>;
165
- }
166
-
167
- type ConnectionStatus = 'connect' | 'disconnect';
168
- declare const ProtocolError: {
169
- readonly RetriesExceeded: "conn_retry_exceeded";
170
- readonly HandshakeFailed: "handshake_failed";
171
- readonly MessageOrderingViolated: "message_ordering_violated";
172
- };
173
- type ProtocolErrorType = (typeof ProtocolError)[keyof typeof ProtocolError];
174
- interface EventMap {
175
- message: OpaqueTransportMessage;
176
- connectionStatus: {
177
- status: ConnectionStatus;
178
- conn: Connection;
179
- };
180
- sessionStatus: {
181
- status: ConnectionStatus;
182
- session: Session<Connection>;
183
- };
184
- protocolError: {
185
- type: ProtocolErrorType;
186
- message: string;
187
- };
188
- transportStatus: {
189
- status: TransportStatus;
190
- };
191
- }
192
- type EventTypes = keyof EventMap;
193
- type EventHandler<K extends EventTypes> = (event: EventMap[K]) => unknown;
194
- declare class EventDispatcher<T extends EventTypes> {
195
- private eventListeners;
196
- removeAllListeners(): void;
197
- numberOfListeners<K extends T>(eventType: K): number;
198
- addEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
199
- removeEventListener<K extends T>(eventType: K, handler: EventHandler<K>): void;
200
- dispatchEvent<K extends T>(eventType: K, event: EventMap[K]): void;
201
- }
202
-
203
- /**
204
- * Options to control the backoff and retry behavior of the client transport's connection behaviour.
205
- *
206
- * River implements exponential backoff with jitter to prevent flooding the server
207
- * when there's an issue with connection establishment.
208
- *
209
- * The backoff is calculated via the following:
210
- * backOff = min(jitter + {@link baseIntervalMs} * 2 ^ budget_consumed, {@link maxBackoffMs})
211
- *
212
- * We use a leaky bucket rate limit with a budget of {@link attemptBudgetCapacity} reconnection attempts.
213
- * Budget only starts to restore after a successful handshake at a rate of one budget per {@link budgetRestoreIntervalMs}.
214
- */
215
- interface ConnectionRetryOptions {
216
- /**
217
- * The base interval to wait before retrying a connection.
218
- */
219
- baseIntervalMs: number;
220
- /**
221
- * The maximum random jitter to add to the total backoff time.
222
- */
223
- maxJitterMs: number;
224
- /**
225
- * The maximum amount of time to wait before retrying a connection.
226
- * This does not include the jitter.
227
- */
228
- maxBackoffMs: number;
229
- /**
230
- * The max number of times to attempt a connection before a successful handshake.
231
- * This persists across connections but starts restoring budget after a successful handshake.
232
- * The restoration interval depends on {@link budgetRestoreIntervalMs}
233
- */
234
- attemptBudgetCapacity: number;
235
- /**
236
- * After a successful connection attempt, how long to wait before we restore a single budget.
237
- */
238
- budgetRestoreIntervalMs: number;
239
- }
240
- declare class LeakyBucketRateLimit {
241
- private budgetConsumed;
242
- private intervalHandles;
243
- private readonly options;
244
- constructor(options: ConnectionRetryOptions);
245
- getBackoffMs(user: TransportClientId): number;
246
- get totalBudgetRestoreTime(): number;
247
- consumeBudget(user: TransportClientId): void;
248
- getBudgetConsumed(user: TransportClientId): number;
249
- hasBudget(user: TransportClientId): boolean;
250
- startRestoringBudget(user: TransportClientId): void;
251
- private stopLeak;
252
- close(): void;
253
- }
254
-
255
- type TransportOptions = SessionOptions;
256
- type ProvidedTransportOptions = Partial<TransportOptions>;
257
- type ClientTransportOptions = TransportOptions & ConnectionRetryOptions;
258
- type ProvidedClientTransportOptions = Partial<ClientTransportOptions>;
259
- type ServerTransportOptions = TransportOptions;
260
- type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;
261
-
262
- /**
263
- * Represents the possible states of a transport.
264
- * @property {'open'} open - The transport is open and operational (note that this doesn't mean it is actively connected)
265
- * @property {'closed'} closed - The transport is permanently closed and cannot be reopened.
266
- */
267
- type TransportStatus = 'open' | 'closed';
268
- /**
269
- * Transports manage the lifecycle (creation/deletion) of sessions and connections. Its responsibilities include:
270
- *
271
- * 1) Constructing a new {@link Session} and {@link Connection} on {@link TransportMessage}s from new clients.
272
- * After constructing the {@link Connection}, {@link onConnect} is called which adds it to the connection map.
273
- * 2) Delegating message listening of the connection to the newly created {@link Connection}.
274
- * From this point on, the {@link Connection} is responsible for *reading* and *writing*
275
- * messages from the connection.
276
- * 3) When a connection is closed, the {@link Transport} calls {@link onDisconnect} which closes the
277
- * connection via {@link Connection.close} and removes it from the {@link connections} map.
278
-
279
- *
280
- * ```plaintext
281
- * ▲
282
- * incoming │
283
- * messages │
284
- * ▼
285
- * ┌─────────────┐ 1:N ┌───────────┐ 1:1* ┌────────────┐
286
- * │ Transport │ ◄─────► │ Session │ ◄─────► │ Connection │
287
- * └─────────────┘ └───────────┘ └────────────┘
288
- * ▲ * (may or may not be initialized yet)
289
- * │
290
- * ▼
291
- * ┌───────────┐
292
- * │ Message │
293
- * │ Listeners │
294
- * └───────────┘
295
- * ```
296
- * @abstract
297
- */
298
- declare abstract class Transport<ConnType extends Connection> {
299
- /**
300
- * The status of the transport.
301
- */
302
- private status;
303
- /**
304
- * The {@link Codec} used to encode and decode messages.
305
- */
306
- codec: Codec;
307
- /**
308
- * The client ID of this transport.
309
- */
310
- clientId: TransportClientId;
311
- /**
312
- * The map of {@link Session}s managed by this transport.
313
- */
314
- sessions: Map<TransportClientId, Session<ConnType>>;
315
- /**
316
- * The map of {@link Connection}s managed by this transport.
317
- */
318
- get connections(): Map<string, ConnType>;
319
- /**
320
- * The event dispatcher for handling events of type EventTypes.
321
- */
322
- eventDispatcher: EventDispatcher<EventTypes>;
323
- /**
324
- * The options for this transport.
325
- */
326
- protected options: TransportOptions;
327
- log?: Logger;
328
- /**
329
- * Creates a new Transport instance.
330
- * This should also set up {@link onConnect}, and {@link onDisconnect} listeners.
331
- * @param codec The codec used to encode and decode messages.
332
- * @param clientId The client ID of this transport.
333
- */
334
- constructor(clientId: TransportClientId, providedOptions?: ProvidedTransportOptions);
335
- bindLogger(fn: LogFn | Logger, level?: LoggingLevel): void;
336
- /**
337
- * This is called immediately after a new connection is established and we
338
- * may or may not know the identity of the connected client.
339
- * It should attach all the necessary listeners to the connection for lifecycle
340
- * events (i.e. data, close, error)
341
- *
342
- * This method is implemented by {@link ClientTransport} and {@link ServerTransport}.
343
- */
344
- protected abstract handleConnection(conn: ConnType, to: TransportClientId): void;
345
- /**
346
- * Called when a new connection is established
347
- * and we know the identity of the connected client.
348
- * @param conn The connection object.
349
- */
350
- protected onConnect(conn: ConnType, session: Session<ConnType>, isTransparentReconnect: boolean): void;
351
- protected createSession(to: TransportClientId, conn?: ConnType, propagationCtx?: PropagationContext): Session<ConnType>;
352
- protected createNewSession({ to, conn, sessionId, propagationCtx, }: {
353
- to: TransportClientId;
354
- conn: ConnType;
355
- sessionId: string;
356
- propagationCtx?: PropagationContext;
357
- }): Session<ConnType>;
358
- protected getExistingSession({ to, sessionId, nextExpectedSeq, }: {
359
- to: TransportClientId;
360
- sessionId: string;
361
- nextExpectedSeq: number;
362
- }): false | Session<ConnType>;
363
- protected getOrCreateSession({ to, conn, handshakingConn, sessionId, propagationCtx, }: {
364
- to: TransportClientId;
365
- conn?: ConnType;
366
- handshakingConn?: ConnType;
367
- sessionId?: string;
368
- propagationCtx?: PropagationContext;
369
- }): {
370
- session: Session<ConnType>;
371
- isReconnect: boolean;
372
- isTransparentReconnect: boolean;
373
- };
374
- protected deleteSession({ session, closeHandshakingConnection, handshakingConn, }: {
375
- session: Session<ConnType>;
376
- closeHandshakingConnection: boolean;
377
- handshakingConn?: ConnType;
378
- }): void;
379
- /**
380
- * The downstream implementation needs to call this when a connection is closed.
381
- * @param conn The connection object.
382
- * @param connectedTo The peer we are connected to.
383
- */
384
- protected onDisconnect(conn: ConnType, session: Session<ConnType>): void;
385
- /**
386
- * Parses a message from a Uint8Array into a {@link OpaqueTransportMessage}.
387
- * @param msg The message to parse.
388
- * @returns The parsed message, or null if the message is malformed or invalid.
389
- */
390
- protected parseMsg(msg: Uint8Array, conn: ConnType): OpaqueTransportMessage | null;
391
- /**
392
- * Called when a message is received by this transport.
393
- * You generally shouldn't need to override this in downstream transport implementations.
394
- * @param msg The received message.
395
- */
396
- protected handleMsg(msg: OpaqueTransportMessage, conn: ConnType): void;
397
- /**
398
- * Adds a listener to this transport.
399
- * @param the type of event to listen for
400
- * @param handler The message handler to add.
401
- */
402
- addEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
403
- /**
404
- * Removes a listener from this transport.
405
- * @param the type of event to un-listen on
406
- * @param handler The message handler to remove.
407
- */
408
- removeEventListener<K extends EventTypes, T extends EventHandler<K>>(type: K, handler: T): void;
409
- /**
410
- * Sends a message over this transport, delegating to the appropriate connection to actually
411
- * send the message.
412
- * @param msg The message to send.
413
- * @returns The ID of the sent message or undefined if it wasn't sent
414
- */
415
- send(to: TransportClientId, msg: PartialTransportMessage): string;
416
- sendCloseControl(to: TransportClientId, streamId: string): string;
417
- sendRequestCloseControl(to: TransportClientId, streamId: string): string;
418
- sendAbort(to: TransportClientId, streamId: string, payload: ErrResult<Static<typeof OutputReaderErrorSchema | typeof InputReaderErrorSchema>>): string;
419
- protected protocolError(type: ProtocolErrorType, message: string): void;
420
- /**
421
- * Default close implementation for transports. You should override this in the downstream
422
- * implementation if you need to do any additional cleanup and call super.close() at the end.
423
- * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
424
- */
425
- close(): void;
426
- getStatus(): TransportStatus;
427
- }
428
-
429
- type ConstructHandshake<T extends TSchema> = () => Static<T> | Promise<Static<T>>;
430
- type ValidateHandshake<T extends TSchema> = (metadata: Static<T>, previousParsedMetadata?: ParsedMetadata) => false | ParsedMetadata | Promise<false | ParsedMetadata>;
431
- interface ClientHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
432
- /**
433
- * Schema for the metadata that the client sends to the server
434
- * during the handshake.
435
- */
436
- schema: MetadataSchema;
437
- /**
438
- * Gets the {@link HandshakeRequestMetadata} to send to the server.
439
- */
440
- construct: ConstructHandshake<MetadataSchema>;
441
- }
442
- interface ServerHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
443
- /**
444
- * Schema for the metadata that the server receives from the client
445
- * during the handshake.
446
- */
447
- schema: MetadataSchema;
448
- /**
449
- * Parses the {@link HandshakeRequestMetadata} sent by the client, transforming
450
- * it into {@link ParsedHandshakeMetadata}.
451
- *
452
- * May return `false` if the client should be rejected.
453
- *
454
- * @param metadata - The metadata sent by the client.
455
- * @param session - The session that the client would be associated with.
456
- * @param isReconnect - Whether the client is reconnecting to the session,
457
- * or if this is a new session.
458
- */
459
- validate: ValidateHandshake<MetadataSchema>;
460
- }
461
- declare function createClientHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, construct: ConstructHandshake<MetadataSchema>): ClientHandshakeOptions;
462
- declare function createServerHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, validate: ValidateHandshake<MetadataSchema>): ServerHandshakeOptions;
463
-
464
- declare abstract class ClientTransport<ConnType extends Connection> extends Transport<ConnType> {
465
- /**
466
- * The options for this transport.
467
- */
468
- protected options: ClientTransportOptions;
469
- /**
470
- * The map of reconnect promises for each client ID.
471
- */
472
- inflightConnectionPromises: Map<TransportClientId, Promise<ConnType>>;
473
- retryBudget: LeakyBucketRateLimit;
474
- /**
475
- * A flag indicating whether the transport should automatically reconnect
476
- * when a connection is dropped.
477
- * Realistically, this should always be true for clients unless you are writing
478
- * tests or a special case where you don't want to reconnect.
479
- */
480
- reconnectOnConnectionDrop: boolean;
481
- /**
482
- * Optional handshake options for this client.
483
- */
484
- handshakeExtensions?: ClientHandshakeOptions;
485
- constructor(clientId: TransportClientId, providedOptions?: ProvidedClientTransportOptions);
486
- extendHandshake(options: ClientHandshakeOptions): void;
487
- protected handleConnection(conn: ConnType, to: TransportClientId): void;
488
- receiveHandshakeResponseMessage(data: Uint8Array, conn: ConnType): Session<ConnType> | false;
489
- /**
490
- * Abstract method that creates a new {@link Connection} object.
491
- * This should call {@link handleConnection} when the connection is created.
492
- * The downstream client implementation needs to implement this.
493
- *
494
- * @param to The client ID of the node to connect to.
495
- * @returns The new connection object.
496
- */
497
- protected abstract createNewOutgoingConnection(to: TransportClientId): Promise<ConnType>;
498
- /**
499
- * Manually attempts to connect to a client.
500
- * @param to The client ID of the node to connect to.
501
- */
502
- connect(to: TransportClientId): Promise<void>;
503
- protected deleteSession({ session, closeHandshakingConnection, handshakingConn, }: {
504
- session: Session<ConnType>;
505
- closeHandshakingConnection: boolean;
506
- handshakingConn?: ConnType;
507
- }): void;
508
- protected sendHandshake(to: TransportClientId, conn: ConnType): Promise<boolean>;
509
- close(): void;
510
- }
511
-
512
- /**
513
- * ServiceContext exist for the purpose of declaration merging
514
- * to extend the context with additional properties.
515
- *
516
- * For example:
517
- *
518
- * ```ts
519
- * declare module '@replit/river' {
520
- * interface ServiceContext {
521
- * db: Database;
522
- * }
523
- * }
524
- *
525
- * createServer(someTransport, myServices, { extendedContext: { db: myDb } });
526
- * ```
527
- *
528
- * Once you do this, your {@link ProcedureHandlerContext} will have `db` property on it.
529
- */
530
- interface ServiceContext {
531
- }
532
- /**
533
- * The parsed metadata schema for a service. This is the
534
- * return value of the {@link ServerHandshakeOptions.validate}
535
- * if the handshake extension is used.
536
- *
537
- * You should use declaration merging to extend this interface
538
- * with the sanitized metadata.
539
- *
540
- * ```ts
541
- * declare module '@replit/river' {
542
- * interface ParsedMetadata {
543
- * userId: number;
544
- * }
545
- * }
546
- * ```
547
- */
548
- interface ParsedMetadata {
549
- }
550
- /**
551
- * This is passed to every procedure handler and contains various context-level
552
- * information and utilities. This may be extended, see {@link ServiceContext}
553
- */
554
- type ProcedureHandlerContext<State> = ServiceContext & {
555
- /**
556
- * State for this service as defined by the service definition.
557
- */
558
- state: State;
559
- /**
560
- * Metadata parsed on the server. See {@link ParsedMetadata}
561
- */
562
- metadata: ParsedMetadata;
563
- /**
564
- * The ID of the client that sent this request.
565
- */
566
- from: TransportClientId;
567
- /**
568
- * An AbortController for this stream. This is used to abort the stream from the
569
- * handler and notify the client that the stream was aborted.
570
- *
571
- * Important to note that this controller is owned by the handler, if you
572
- * want to listen to aborts coming from the client, you should use the
573
- * {@link clientAbortSignal}.
574
- *
575
- * Aborts are not the same as closing streams gracefully, please refer to
576
- * the river documentation to understand the difference between the two concepts.
577
- */
578
- abortController: AbortController;
579
- /**
580
- * You can listen to clientAbortSignal this to check if the client aborted the request,
581
- * or if the request was aborted due to an unexpected disconnect from the calling
582
- * session.
583
- *
584
- * If the procedure has a read stream (e.g. upload or stream), the procedure will
585
- * notified of aborts as part of the stream, but you may still want to use
586
- * this signal as it is triggered immediately after an abort comes in,
587
- * in readStreams some data may be buffered before the abort result shows up.
588
- *
589
- * Important to note that this signal is owned by the client, you have a separate
590
- * signal inside {@link abortController} for aborts triggered within the handler.
591
- *
592
- * Aborts are not the same as closing streams gracefully, please refer to
593
- * the river documentation to understand the difference between the two concepts.
594
- */
595
- clientAbortSignal: AbortSignal;
596
- /**
597
- * Lets you add a function that will run when the request is done, this can be
598
- * due to an abort (from either side), error, or success. If the callback is
599
- * added after the stream ended, it will run immediately.
600
- */
601
- onRequestFinished: (callback: () => void) => void;
602
- };
2
+ import { Static, TObject, TUnion, TString, TSchema, TLiteral, TNever } from '@sinclair/typebox';
3
+ import { C as Connection, p as ClientHandshakeOptions, s as ProcedureHandlerContext, n as ServiceContext } from './context-73df8978.js';
4
+ import { c as TransportClientId } from './message-fd349b27.js';
5
+ import { C as ClientTransport } from './client-f56a6da3.js';
603
6
 
604
7
  declare const StreamDrainedError: {
605
8
  readonly code: "STREAM_DRAINED";
@@ -1369,4 +772,4 @@ declare class ServiceScaffold<State extends object> {
1369
772
  }>;
1370
773
  }
1371
774
 
1372
- export { createClientHandshakeOptions as $, AnyServiceSchemaMap as A, BaseErrorSchemaType as B, Connection as C, StreamProcedure as D, ErrResult as E, UNCAUGHT_ERROR_CODE as F, UNEXPECTED_DISCONNECT_CODE as G, INVALID_REQUEST_CODE as H, InstantiatedServiceSchemaMap as I, InputReaderErrorSchema as J, createClient as K, Client as L, ParsedMetadata as M, ProcedureHandlerContext as N, OkResult as O, PayloadType as P, Ok as Q, ReadStream as R, SessionOptions as S, Transport as T, UploadProcedure as U, ValidProcType as V, WriteStream as W, Err as X, ResultUnwrapOk as Y, ResultUnwrapErr as Z, Output as _, Session as a, createServerHandshakeOptions as a0, ServerTransportOptions as a1, TransportStatus as a2, ProvidedTransportOptions as a3, EventMap as a4, EventTypes as a5, EventHandler as a6, ProtocolError as a7, ProtocolErrorType as a8, ProcedureErrorSchemaType as b, Procedure as c, ServiceContext as d, Result as e, OutputReaderErrorSchema as f, ClientTransport as g, ProvidedClientTransportOptions as h, ProvidedServerTransportOptions as i, SerializedServerSchema as j, ServerHandshakeOptions as k, Service as l, ServiceConfiguration as m, ProcHandler as n, ProcInit as o, ProcInput as p, ProcOutput as q, ProcErrors as r, ProcType as s, ServiceSchema as t, serializeSchema as u, SerializedServiceSchema as v, SerializedProcedureSchema as w, ProcedureMap as x, RpcProcedure as y, SubscriptionProcedure as z };
775
+ export { AnyServiceSchemaMap as A, BaseErrorSchemaType as B, Client as C, Err as D, ErrResult as E, ResultUnwrapOk as F, ResultUnwrapErr as G, Output as H, InstantiatedServiceSchemaMap as I, OkResult as O, PayloadType as P, ReadStream as R, Service as S, UploadProcedure as U, ValidProcType as V, WriteStream as W, ProcedureErrorSchemaType as a, Procedure as b, Result as c, OutputReaderErrorSchema as d, ServiceConfiguration as e, ProcHandler as f, ProcInit as g, ProcInput as h, ProcOutput as i, ProcErrors as j, ProcType as k, ServiceSchema as l, SerializedServerSchema as m, SerializedServiceSchema as n, SerializedProcedureSchema as o, ProcedureMap as p, RpcProcedure as q, SubscriptionProcedure as r, serializeSchema as s, StreamProcedure as t, UNCAUGHT_ERROR_CODE as u, UNEXPECTED_DISCONNECT_CODE as v, INVALID_REQUEST_CODE as w, InputReaderErrorSchema as x, createClient as y, Ok as z };