@replit/river 0.10.13 → 0.12.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 (83) hide show
  1. package/README.md +28 -8
  2. package/dist/{builder-1f26296b.d.ts → builder-c593de11.d.ts} +14 -13
  3. package/dist/{chunk-3JGVFWKQ.js → chunk-24O3BKZA.js} +205 -180
  4. package/dist/chunk-4HOR4NUO.js +40 -0
  5. package/dist/chunk-ANGOKBE5.js +708 -0
  6. package/dist/{chunk-R6H2BIMC.js → chunk-GZ7HCLLM.js} +31 -7
  7. package/dist/{chunk-T7M7OKPE.js → chunk-H4BYJELI.js} +5 -1
  8. package/dist/chunk-IIBVKYDB.js +62 -0
  9. package/dist/chunk-IUDKWAOK.js +47 -0
  10. package/dist/chunk-WTOIOXB7.js +125 -0
  11. package/dist/chunk-XOTIAXAH.js +44 -0
  12. package/dist/codec/index.cjs +13 -7
  13. package/dist/codec/index.js +2 -4
  14. package/dist/connection-2956a1c5.d.ts +17 -0
  15. package/dist/connection-aaea7c88.d.ts +15 -0
  16. package/dist/connection-cd963ed5.d.ts +18 -0
  17. package/dist/index-d91775d9.d.ts +442 -0
  18. package/dist/logging/index.cjs +8 -3
  19. package/dist/logging/index.d.cts +6 -1
  20. package/dist/logging/index.d.ts +6 -1
  21. package/dist/logging/index.js +5 -3
  22. package/dist/messageFraming-b200ef25.d.ts +20 -0
  23. package/dist/router/index.cjs +249 -211
  24. package/dist/router/index.d.cts +6 -7
  25. package/dist/router/index.d.ts +6 -7
  26. package/dist/router/index.js +3 -3
  27. package/dist/transport/impls/stdio/client.cjs +891 -0
  28. package/dist/transport/impls/stdio/client.d.cts +27 -0
  29. package/dist/transport/impls/stdio/client.d.ts +27 -0
  30. package/dist/transport/impls/stdio/client.js +42 -0
  31. package/dist/transport/impls/stdio/server.cjs +861 -0
  32. package/dist/transport/impls/stdio/server.d.cts +25 -0
  33. package/dist/transport/impls/stdio/server.d.ts +25 -0
  34. package/dist/transport/impls/stdio/server.js +33 -0
  35. package/dist/transport/impls/uds/client.cjs +893 -0
  36. package/dist/transport/impls/uds/client.d.cts +16 -0
  37. package/dist/transport/impls/uds/client.d.ts +16 -0
  38. package/dist/transport/impls/uds/client.js +44 -0
  39. package/dist/transport/impls/uds/server.cjs +863 -0
  40. package/dist/transport/impls/uds/server.d.cts +16 -0
  41. package/dist/transport/impls/uds/server.d.ts +16 -0
  42. package/dist/transport/impls/uds/server.js +39 -0
  43. package/dist/transport/impls/ws/client.cjs +587 -248
  44. package/dist/transport/impls/ws/client.d.cts +6 -21
  45. package/dist/transport/impls/ws/client.d.ts +6 -21
  46. package/dist/transport/impls/ws/client.js +77 -7
  47. package/dist/transport/impls/ws/server.cjs +541 -194
  48. package/dist/transport/impls/ws/server.d.cts +6 -10
  49. package/dist/transport/impls/ws/server.d.ts +6 -10
  50. package/dist/transport/impls/ws/server.js +31 -8
  51. package/dist/transport/index.cjs +652 -129
  52. package/dist/transport/index.d.cts +3 -276
  53. package/dist/transport/index.d.ts +3 -276
  54. package/dist/transport/index.js +13 -10
  55. package/dist/util/testHelpers.cjs +40 -602
  56. package/dist/util/testHelpers.d.cts +18 -37
  57. package/dist/util/testHelpers.d.ts +18 -37
  58. package/dist/util/testHelpers.js +27 -47
  59. package/package.json +29 -14
  60. package/dist/chunk-3MQETIGZ.js +0 -80
  61. package/dist/chunk-5IC5XMWK.js +0 -140
  62. package/dist/chunk-L7D75G4K.js +0 -29
  63. package/dist/chunk-LQXPKF3A.js +0 -282
  64. package/dist/chunk-PJ2EUO7O.js +0 -63
  65. package/dist/chunk-WVT5QXMZ.js +0 -20
  66. package/dist/chunk-ZE4MX7DF.js +0 -75
  67. package/dist/connection-2529fc14.d.ts +0 -10
  68. package/dist/connection-316d6e3a.d.ts +0 -10
  69. package/dist/connection-8e19874c.d.ts +0 -11
  70. package/dist/connection-f7688cc1.d.ts +0 -11
  71. package/dist/transport/impls/stdio/stdio.cjs +0 -508
  72. package/dist/transport/impls/stdio/stdio.d.cts +0 -26
  73. package/dist/transport/impls/stdio/stdio.d.ts +0 -26
  74. package/dist/transport/impls/stdio/stdio.js +0 -70
  75. package/dist/transport/impls/unixsocket/client.cjs +0 -506
  76. package/dist/transport/impls/unixsocket/client.d.cts +0 -16
  77. package/dist/transport/impls/unixsocket/client.d.ts +0 -16
  78. package/dist/transport/impls/unixsocket/client.js +0 -67
  79. package/dist/transport/impls/unixsocket/server.cjs +0 -510
  80. package/dist/transport/impls/unixsocket/server.d.cts +0 -18
  81. package/dist/transport/impls/unixsocket/server.d.ts +0 -18
  82. package/dist/transport/impls/unixsocket/server.js +0 -73
  83. /package/dist/{chunk-ORAG7IAU.js → chunk-5IZ2UHWV.js} +0 -0
@@ -0,0 +1,861 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // transport/impls/stdio/server.ts
21
+ var server_exports = {};
22
+ __export(server_exports, {
23
+ StdioServerTransport: () => StdioServerTransport
24
+ });
25
+ module.exports = __toCommonJS(server_exports);
26
+
27
+ // transport/transport.ts
28
+ var import_value = require("@sinclair/typebox/value");
29
+
30
+ // transport/message.ts
31
+ var import_typebox = require("@sinclair/typebox");
32
+ var import_nanoid = require("nanoid");
33
+ var TransportMessageSchema = (t) => import_typebox.Type.Object({
34
+ id: import_typebox.Type.String(),
35
+ from: import_typebox.Type.String(),
36
+ to: import_typebox.Type.String(),
37
+ seq: import_typebox.Type.Integer(),
38
+ ack: import_typebox.Type.Integer(),
39
+ serviceName: import_typebox.Type.Optional(import_typebox.Type.Union([import_typebox.Type.String(), import_typebox.Type.Null()])),
40
+ procedureName: import_typebox.Type.Optional(import_typebox.Type.Union([import_typebox.Type.String(), import_typebox.Type.Null()])),
41
+ streamId: import_typebox.Type.String(),
42
+ controlFlags: import_typebox.Type.Integer(),
43
+ payload: t
44
+ });
45
+ var ControlMessageAckSchema = import_typebox.Type.Object({
46
+ type: import_typebox.Type.Literal("ACK")
47
+ });
48
+ var ControlMessageCloseSchema = import_typebox.Type.Object({
49
+ type: import_typebox.Type.Literal("CLOSE")
50
+ });
51
+ var PROTOCOL_VERSION = "v1";
52
+ var ControlMessageHandshakeRequestSchema = import_typebox.Type.Object({
53
+ type: import_typebox.Type.Literal("HANDSHAKE_REQ"),
54
+ protocolVersion: import_typebox.Type.Literal(PROTOCOL_VERSION)
55
+ });
56
+ var ControlMessageHandshakeResponseSchema = import_typebox.Type.Object({
57
+ type: import_typebox.Type.Literal("HANDSHAKE_RESP"),
58
+ status: import_typebox.Type.Union([
59
+ import_typebox.Type.Object({
60
+ ok: import_typebox.Type.Literal(true),
61
+ instanceId: import_typebox.Type.String()
62
+ }),
63
+ import_typebox.Type.Object({
64
+ ok: import_typebox.Type.Literal(false),
65
+ reason: import_typebox.Type.Union([import_typebox.Type.Literal("VERSION_MISMATCH")])
66
+ })
67
+ ])
68
+ });
69
+ var ControlMessagePayloadSchema = import_typebox.Type.Union([
70
+ ControlMessageCloseSchema,
71
+ ControlMessageAckSchema,
72
+ ControlMessageHandshakeRequestSchema,
73
+ ControlMessageHandshakeResponseSchema
74
+ ]);
75
+ var OpaqueTransportMessageSchema = TransportMessageSchema(
76
+ import_typebox.Type.Unknown()
77
+ );
78
+ function bootResponseMessage(from, instanceId, to, ok) {
79
+ return {
80
+ id: (0, import_nanoid.nanoid)(),
81
+ from,
82
+ to,
83
+ seq: 0,
84
+ ack: 0,
85
+ streamId: (0, import_nanoid.nanoid)(),
86
+ controlFlags: 0,
87
+ payload: ok ? {
88
+ type: "HANDSHAKE_RESP",
89
+ status: {
90
+ ok: true,
91
+ instanceId
92
+ }
93
+ } : {
94
+ type: "HANDSHAKE_RESP",
95
+ status: {
96
+ ok: false,
97
+ reason: "VERSION_MISMATCH"
98
+ }
99
+ }
100
+ };
101
+ }
102
+ function isAck(controlFlag) {
103
+ return (controlFlag & 1 /* AckBit */) === 1 /* AckBit */;
104
+ }
105
+
106
+ // logging/index.ts
107
+ var log;
108
+
109
+ // transport/events.ts
110
+ var EventDispatcher = class {
111
+ eventListeners = {};
112
+ numberOfListeners(eventType) {
113
+ return this.eventListeners[eventType]?.size ?? 0;
114
+ }
115
+ addEventListener(eventType, handler) {
116
+ if (!this.eventListeners[eventType]) {
117
+ this.eventListeners[eventType] = /* @__PURE__ */ new Set();
118
+ }
119
+ this.eventListeners[eventType]?.add(handler);
120
+ }
121
+ removeEventListener(eventType, handler) {
122
+ const handlers = this.eventListeners[eventType];
123
+ if (handlers) {
124
+ this.eventListeners[eventType]?.delete(handler);
125
+ }
126
+ }
127
+ dispatchEvent(eventType, event) {
128
+ const handlers = this.eventListeners[eventType];
129
+ if (handlers) {
130
+ for (const handler of handlers) {
131
+ handler(event);
132
+ }
133
+ }
134
+ }
135
+ };
136
+
137
+ // transport/session.ts
138
+ var import_nanoid2 = require("nanoid");
139
+ var nanoid2 = (0, import_nanoid2.customAlphabet)("1234567890abcdefghijklmnopqrstuvxyz", 6);
140
+ var unsafeId = () => nanoid2();
141
+ var Connection = class {
142
+ debugId;
143
+ constructor() {
144
+ this.debugId = `conn-${unsafeId()}`;
145
+ }
146
+ };
147
+ var HEARTBEAT_INTERVAL_MS = 250;
148
+ var HEARTBEATS_TILL_DEAD = 4;
149
+ var SESSION_DISCONNECT_GRACE_MS = 3e3;
150
+ var Session = class {
151
+ codec;
152
+ /**
153
+ * The buffer of messages that have been sent but not yet acknowledged.
154
+ */
155
+ sendBuffer = [];
156
+ /**
157
+ * The active connection associated with this session
158
+ */
159
+ connection;
160
+ from;
161
+ to;
162
+ /**
163
+ * The unique ID of this session.
164
+ */
165
+ debugId;
166
+ /**
167
+ * Number of messages we've sent along this session (excluding handshake)
168
+ */
169
+ seq = 0;
170
+ /**
171
+ * Number of unique messages we've received this session (excluding handshake)
172
+ */
173
+ ack = 0;
174
+ /**
175
+ * The grace period between when the inner connection is disconnected
176
+ * and when we should consider the entire session disconnected.
177
+ */
178
+ disconnectionGrace;
179
+ /**
180
+ * Number of heartbeats we've sent without a response.
181
+ */
182
+ heartbeatMisses;
183
+ /**
184
+ * The interval for sending heartbeats.
185
+ */
186
+ heartbeat;
187
+ constructor(codec, from, connectedTo, conn) {
188
+ this.debugId = `sess-${unsafeId()}`;
189
+ this.from = from;
190
+ this.to = connectedTo;
191
+ this.connection = conn;
192
+ this.codec = codec;
193
+ this.heartbeatMisses = 0;
194
+ this.heartbeat = setInterval(
195
+ () => this.sendHeartbeat(),
196
+ HEARTBEAT_INTERVAL_MS
197
+ );
198
+ }
199
+ /**
200
+ * Sends a message over the session's connection.
201
+ * If the connection is not ready or the message fails to send, the message can be buffered for retry unless skipped.
202
+ *
203
+ * @param msg The partial message to be sent, which will be constructed into a full message.
204
+ * @param skipRetry Optional. If true, the message will not be buffered for retry on failure. This should only be used for
205
+ * ack hearbeats, which contain information that can already be found in the other buffered messages.
206
+ * @returns The full transport ID of the message that was attempted to be sent.
207
+ */
208
+ send(msg, skipRetry) {
209
+ const fullMsg = this.constructMsg(msg);
210
+ log?.debug(`${this.from} -- sending ${JSON.stringify(fullMsg)}`);
211
+ if (this.connection) {
212
+ const ok = this.connection.send(this.codec.toBuffer(fullMsg));
213
+ if (ok)
214
+ return fullMsg.id;
215
+ log?.info(
216
+ `${this.from} -- failed to send ${fullMsg.id} to ${fullMsg.to}, connection (id: ${this.connection.debugId}) is probably dead`
217
+ );
218
+ } else {
219
+ log?.info(
220
+ `${this.from} -- failed to send ${fullMsg.id} to ${fullMsg.to}, connection not ready yet`
221
+ );
222
+ }
223
+ if (skipRetry)
224
+ return fullMsg.id;
225
+ this.addToSendBuff(fullMsg);
226
+ log?.info(
227
+ `${this.from} -- buffering msg ${fullMsg.id} until connection is healthy again`
228
+ );
229
+ return fullMsg.id;
230
+ }
231
+ sendHeartbeat() {
232
+ if (this.heartbeatMisses >= HEARTBEATS_TILL_DEAD && this.connection) {
233
+ log?.info(
234
+ `${this.from} -- closing connection (id: ${this.connection.debugId}) to ${this.to} due to inactivity`
235
+ );
236
+ this.halfCloseConnection();
237
+ return;
238
+ }
239
+ this.send(
240
+ {
241
+ streamId: "heartbeat",
242
+ controlFlags: 1 /* AckBit */,
243
+ payload: {
244
+ type: "ACK"
245
+ }
246
+ },
247
+ true
248
+ );
249
+ this.heartbeatMisses++;
250
+ }
251
+ resetBufferedMessages() {
252
+ this.sendBuffer = [];
253
+ this.seq = 0;
254
+ this.ack = 0;
255
+ }
256
+ sendBufferedMessages() {
257
+ if (!this.connection) {
258
+ const msg = `${this.from} -- tried sending buffered messages without a connection (if you hit this code path something is seriously wrong)`;
259
+ log?.error(msg);
260
+ throw new Error(msg);
261
+ }
262
+ for (const msg of this.sendBuffer) {
263
+ log?.debug(`${this.from} -- resending ${JSON.stringify(msg)}`);
264
+ const ok = this.connection.send(this.codec.toBuffer(msg));
265
+ if (!ok) {
266
+ const msg2 = `${this.from} -- failed to send buffered message to ${this.to} in session (id: ${this.debugId}) (if you hit this code path something is seriously wrong)`;
267
+ log?.error(msg2);
268
+ throw new Error(msg2);
269
+ }
270
+ }
271
+ }
272
+ updateBookkeeping(ack, seq) {
273
+ this.heartbeatMisses = 0;
274
+ this.sendBuffer = this.sendBuffer.filter((unacked) => unacked.seq > ack);
275
+ this.ack = seq + 1;
276
+ }
277
+ addToSendBuff(msg) {
278
+ this.sendBuffer.push(msg);
279
+ log?.debug(
280
+ `${this.from} -- send buff to ${this.to} now tracking ${this.sendBuffer.length} messages`
281
+ );
282
+ }
283
+ closeStaleConnection(conn) {
284
+ if (!this.connection || this.connection !== conn)
285
+ return;
286
+ log?.info(
287
+ `${this.from} -- closing old inner connection (id: ${this.connection.debugId}) from session (id: ${this.debugId}) to ${this.to}`
288
+ );
289
+ this.connection.close();
290
+ this.connection = void 0;
291
+ }
292
+ replaceWithNewConnection(newConn) {
293
+ this.closeStaleConnection(this.connection);
294
+ this.cancelGrace();
295
+ this.connection = newConn;
296
+ }
297
+ beginGrace(cb) {
298
+ this.disconnectionGrace = setTimeout(() => {
299
+ this.resetBufferedMessages();
300
+ clearInterval(this.heartbeat);
301
+ cb();
302
+ }, SESSION_DISCONNECT_GRACE_MS);
303
+ }
304
+ cancelGrace() {
305
+ clearTimeout(this.disconnectionGrace);
306
+ }
307
+ get connected() {
308
+ return this.connection !== void 0;
309
+ }
310
+ get nextExpectedSeq() {
311
+ return this.ack;
312
+ }
313
+ constructMsg(partialMsg) {
314
+ const msg = {
315
+ ...partialMsg,
316
+ id: unsafeId(),
317
+ to: this.to,
318
+ from: this.from,
319
+ seq: this.seq,
320
+ ack: this.ack
321
+ };
322
+ this.seq++;
323
+ return msg;
324
+ }
325
+ /**
326
+ * Closes the out-going connection but doesn't remove the listeners
327
+ * for incoming messages. The connection will eventually call onClose
328
+ * when it is ready to be cleaned up and only then will {@link connection} be set back
329
+ * to undefined
330
+ */
331
+ halfCloseConnection() {
332
+ this.connection?.close();
333
+ }
334
+ inspectSendBuffer() {
335
+ return this.sendBuffer;
336
+ }
337
+ };
338
+
339
+ // codec/json.ts
340
+ var encoder = new TextEncoder();
341
+ var decoder = new TextDecoder();
342
+ function uint8ArrayToBase64(uint8Array) {
343
+ let binary = "";
344
+ uint8Array.forEach((byte) => {
345
+ binary += String.fromCharCode(byte);
346
+ });
347
+ return btoa(binary);
348
+ }
349
+ function base64ToUint8Array(base64) {
350
+ const binaryString = atob(base64);
351
+ const uint8Array = new Uint8Array(binaryString.length);
352
+ for (let i = 0; i < binaryString.length; i++) {
353
+ uint8Array[i] = binaryString.charCodeAt(i);
354
+ }
355
+ return uint8Array;
356
+ }
357
+ var NaiveJsonCodec = {
358
+ toBuffer: (obj) => {
359
+ return encoder.encode(
360
+ JSON.stringify(obj, function replacer(key) {
361
+ const val = this[key];
362
+ if (val instanceof Uint8Array) {
363
+ return { $t: uint8ArrayToBase64(val) };
364
+ } else {
365
+ return val;
366
+ }
367
+ })
368
+ );
369
+ },
370
+ fromBuffer: (buff) => {
371
+ try {
372
+ const parsed = JSON.parse(
373
+ decoder.decode(buff),
374
+ function reviver(_key, val) {
375
+ if (val?.$t) {
376
+ return base64ToUint8Array(val.$t);
377
+ } else {
378
+ return val;
379
+ }
380
+ }
381
+ );
382
+ if (typeof parsed === "object")
383
+ return parsed;
384
+ return null;
385
+ } catch {
386
+ return null;
387
+ }
388
+ }
389
+ };
390
+
391
+ // transport/transport.ts
392
+ var import_nanoid3 = require("nanoid");
393
+
394
+ // util/stringify.ts
395
+ function coerceErrorString(err) {
396
+ if (err instanceof Error) {
397
+ return err.message;
398
+ }
399
+ return `[coerced to error] ${String(err)}`;
400
+ }
401
+
402
+ // transport/transport.ts
403
+ var DEFAULT_RECONNECT_JITTER_MAX_MS = 500;
404
+ var DEFAULT_RECONNECT_INTERVAL_MS = 250;
405
+ var defaultTransportOptions = {
406
+ retryIntervalMs: DEFAULT_RECONNECT_INTERVAL_MS,
407
+ retryJitterMs: DEFAULT_RECONNECT_JITTER_MAX_MS,
408
+ retryAttemptsMax: 5,
409
+ codec: NaiveJsonCodec
410
+ };
411
+ var Transport = class {
412
+ /**
413
+ * A flag indicating whether the transport has been destroyed.
414
+ * A destroyed transport will not attempt to reconnect and cannot be used again.
415
+ */
416
+ state;
417
+ /**
418
+ * The {@link Codec} used to encode and decode messages.
419
+ */
420
+ codec;
421
+ /**
422
+ * The client ID of this transport.
423
+ */
424
+ clientId;
425
+ /**
426
+ * The map of {@link Session}s managed by this transport.
427
+ */
428
+ sessions;
429
+ /**
430
+ * The map of {@link Connection}s managed by this transport.
431
+ */
432
+ get connections() {
433
+ return new Map(
434
+ [...this.sessions].map(([client, session]) => [client, session.connection]).filter((entry) => entry[1] !== void 0)
435
+ );
436
+ }
437
+ /**
438
+ * The event dispatcher for handling events of type EventTypes.
439
+ */
440
+ eventDispatcher;
441
+ /**
442
+ * The options for this transport.
443
+ */
444
+ options;
445
+ /**
446
+ * Creates a new Transport instance.
447
+ * This should also set up {@link onConnect}, and {@link onDisconnect} listeners.
448
+ * @param codec The codec used to encode and decode messages.
449
+ * @param clientId The client ID of this transport.
450
+ */
451
+ constructor(clientId, providedOptions) {
452
+ this.options = { ...defaultTransportOptions, ...providedOptions };
453
+ this.eventDispatcher = new EventDispatcher();
454
+ this.sessions = /* @__PURE__ */ new Map();
455
+ this.codec = this.options.codec;
456
+ this.clientId = clientId;
457
+ this.state = "open";
458
+ }
459
+ sessionByClientId(clientId) {
460
+ const session = this.sessions.get(clientId);
461
+ if (!session) {
462
+ const err = `${this.clientId} -- (invariant violation) no existing session for ${clientId}`;
463
+ log?.error(err);
464
+ throw new Error(err);
465
+ }
466
+ return session;
467
+ }
468
+ /**
469
+ * Called when a new connection is established
470
+ * and we know the identity of the connected client.
471
+ * @param conn The connection object.
472
+ */
473
+ onConnect(conn, connectedTo) {
474
+ this.eventDispatcher.dispatchEvent("connectionStatus", {
475
+ status: "connect",
476
+ conn
477
+ });
478
+ const session = this.sessions.get(connectedTo);
479
+ if (session === void 0) {
480
+ const newSession = this.createSession(connectedTo, conn);
481
+ log?.info(
482
+ `${this.clientId} -- new connection (id: ${conn.debugId}) for new session (id: ${newSession.debugId}) to ${connectedTo}`
483
+ );
484
+ return newSession;
485
+ }
486
+ log?.info(
487
+ `${this.clientId} -- new connection (id: ${conn.debugId}) for existing session (id: ${session.debugId}) to ${connectedTo}`
488
+ );
489
+ session.replaceWithNewConnection(conn);
490
+ session.sendBufferedMessages();
491
+ return session;
492
+ }
493
+ createSession(connectedTo, conn) {
494
+ const session = new Session(
495
+ this.codec,
496
+ this.clientId,
497
+ connectedTo,
498
+ conn
499
+ );
500
+ this.sessions.set(session.to, session);
501
+ this.eventDispatcher.dispatchEvent("sessionStatus", {
502
+ status: "connect",
503
+ session
504
+ });
505
+ return session;
506
+ }
507
+ deleteSession(session) {
508
+ this.sessions.delete(session.to);
509
+ this.eventDispatcher.dispatchEvent("sessionStatus", {
510
+ status: "disconnect",
511
+ session
512
+ });
513
+ log?.info(
514
+ `${this.clientId} -- session ${session.debugId} disconnect from ${session.to}`
515
+ );
516
+ }
517
+ /**
518
+ * The downstream implementation needs to call this when a connection is closed.
519
+ * @param conn The connection object.
520
+ */
521
+ onDisconnect(conn, connectedTo) {
522
+ this.eventDispatcher.dispatchEvent("connectionStatus", {
523
+ status: "disconnect",
524
+ conn
525
+ });
526
+ if (!connectedTo)
527
+ return;
528
+ const session = this.sessionByClientId(connectedTo);
529
+ log?.info(
530
+ `${this.clientId} -- connection (id: ${conn.debugId}) disconnect from ${connectedTo}, ${SESSION_DISCONNECT_GRACE_MS}ms until session (id: ${session.debugId}) disconnect`
531
+ );
532
+ session.closeStaleConnection(conn);
533
+ session.beginGrace(() => this.deleteSession(session));
534
+ }
535
+ /**
536
+ * Parses a message from a Uint8Array into a {@link OpaqueTransportMessage}.
537
+ * @param msg The message to parse.
538
+ * @returns The parsed message, or null if the message is malformed or invalid.
539
+ */
540
+ parseMsg(msg) {
541
+ const parsedMsg = this.codec.fromBuffer(msg);
542
+ if (parsedMsg === null) {
543
+ const decodedBuffer = new TextDecoder().decode(msg);
544
+ log?.warn(`${this.clientId} -- received malformed msg: ${decodedBuffer}`);
545
+ return null;
546
+ }
547
+ if (!import_value.Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {
548
+ log?.warn(
549
+ `${this.clientId} -- received invalid msg: ${JSON.stringify(
550
+ parsedMsg
551
+ )}`
552
+ );
553
+ return null;
554
+ }
555
+ return {
556
+ ...parsedMsg,
557
+ serviceName: parsedMsg.serviceName === null ? void 0 : parsedMsg.serviceName,
558
+ procedureName: parsedMsg.procedureName === null ? void 0 : parsedMsg.procedureName
559
+ };
560
+ }
561
+ /**
562
+ * Called when a message is received by this transport.
563
+ * You generally shouldn't need to override this in downstream transport implementations.
564
+ * @param msg The received message.
565
+ */
566
+ handleMsg(msg) {
567
+ if (!msg) {
568
+ return;
569
+ }
570
+ const session = this.sessionByClientId(msg.from);
571
+ session.cancelGrace();
572
+ log?.debug(`${this.clientId} -- received msg: ${JSON.stringify(msg)}`);
573
+ if (msg.seq !== session.nextExpectedSeq) {
574
+ log?.warn(
575
+ `${this.clientId} -- received out-of-order msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), discarding: ${JSON.stringify(
576
+ msg
577
+ )}`
578
+ );
579
+ return;
580
+ }
581
+ if (!isAck(msg.controlFlags)) {
582
+ this.eventDispatcher.dispatchEvent("message", msg);
583
+ }
584
+ session.updateBookkeeping(msg.ack, msg.seq);
585
+ }
586
+ /**
587
+ * Adds a listener to this transport.
588
+ * @param the type of event to listen for
589
+ * @param handler The message handler to add.
590
+ */
591
+ addEventListener(type, handler) {
592
+ this.eventDispatcher.addEventListener(type, handler);
593
+ }
594
+ /**
595
+ * Removes a listener from this transport.
596
+ * @param the type of event to unlisten on
597
+ * @param handler The message handler to remove.
598
+ */
599
+ removeEventListener(type, handler) {
600
+ this.eventDispatcher.removeEventListener(type, handler);
601
+ }
602
+ /**
603
+ * Sends a message over this transport, delegating to the appropriate connection to actually
604
+ * send the message.
605
+ * @param msg The message to send.
606
+ * @returns The ID of the sent message or undefined if it wasn't sent
607
+ */
608
+ send(to, msg) {
609
+ if (this.state === "destroyed") {
610
+ const err = "transport is destroyed, cant send";
611
+ log?.error(`${this.clientId} -- ` + err + `: ${JSON.stringify(msg)}`);
612
+ throw new Error(err);
613
+ } else if (this.state === "closed") {
614
+ log?.info(
615
+ `${this.clientId} -- transport closed when sending, discarding : ${JSON.stringify(
616
+ msg
617
+ )}`
618
+ );
619
+ return void 0;
620
+ }
621
+ let session = this.sessions.get(to);
622
+ if (!session) {
623
+ session = this.createSession(to, void 0);
624
+ log?.info(
625
+ `${this.clientId} -- no session for ${to}, created a new one (id: ${session.debugId})`
626
+ );
627
+ }
628
+ return session.send(msg);
629
+ }
630
+ // control helpers
631
+ sendCloseStream(to, streamId) {
632
+ return this.send(to, {
633
+ streamId,
634
+ controlFlags: 4 /* StreamClosedBit */,
635
+ payload: {
636
+ type: "CLOSE"
637
+ }
638
+ });
639
+ }
640
+ /**
641
+ * Default close implementation for transports. You should override this in the downstream
642
+ * implementation if you need to do any additional cleanup and call super.close() at the end.
643
+ * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
644
+ */
645
+ close() {
646
+ for (const session of this.sessions.values()) {
647
+ session.halfCloseConnection();
648
+ }
649
+ this.state = "closed";
650
+ log?.info(`${this.clientId} -- manually closed transport`);
651
+ }
652
+ /**
653
+ * Default destroy implementation for transports. You should override this in the downstream
654
+ * implementation if you need to do any additional cleanup and call super.destroy() at the end.
655
+ * Destroys the transport. Any messages sent while the transport is destroyed will throw an error.
656
+ */
657
+ destroy() {
658
+ for (const session of this.sessions.values()) {
659
+ session.closeStaleConnection(session.connection);
660
+ }
661
+ this.state = "destroyed";
662
+ log?.info(`${this.clientId} -- manually destroyed transport`);
663
+ }
664
+ };
665
+ var ServerTransport = class extends Transport {
666
+ /**
667
+ * Unique per instance of server transport.
668
+ * This allows us to distinguish reconnects to different
669
+ * server transports at the same reachable address and signal
670
+ * the appropriate session disconnect back to the client at the
671
+ * boot stage.
672
+ */
673
+ instanceId = (0, import_nanoid3.nanoid)();
674
+ constructor(clientId, providedOptions) {
675
+ super(clientId, providedOptions);
676
+ log?.info(
677
+ `${this.clientId} -- initiated server transport (instance id: ${this.instanceId}, protocol: ${PROTOCOL_VERSION})`
678
+ );
679
+ }
680
+ handleConnection(conn) {
681
+ let session = void 0;
682
+ const client = () => session?.to ?? "unknown";
683
+ const bootHandler = this.receiveWithBootSequence(
684
+ conn,
685
+ (establishedSession) => {
686
+ session = establishedSession;
687
+ conn.removeDataListener(bootHandler);
688
+ conn.addDataListener((data) => this.handleMsg(this.parseMsg(data)));
689
+ }
690
+ );
691
+ conn.addDataListener(bootHandler);
692
+ conn.addCloseListener(() => {
693
+ if (!session)
694
+ return;
695
+ log?.info(
696
+ `${this.clientId} -- connection (id: ${conn.debugId}) to ${client()} disconnected`
697
+ );
698
+ this.onDisconnect(conn, session.to);
699
+ });
700
+ conn.addErrorListener((err) => {
701
+ if (!session)
702
+ return;
703
+ log?.warn(
704
+ `${this.clientId} -- connection (id: ${conn.debugId}) to ${client()} got an error: ${coerceErrorString(err)}`
705
+ );
706
+ });
707
+ }
708
+ receiveWithBootSequence(conn, sessionCb) {
709
+ const bootHandler = (data) => {
710
+ const parsed = this.parseMsg(data);
711
+ if (!parsed)
712
+ return;
713
+ if (!import_value.Value.Check(ControlMessageHandshakeRequestSchema, parsed.payload)) {
714
+ const responseMsg2 = bootResponseMessage(
715
+ this.clientId,
716
+ this.instanceId,
717
+ parsed.from,
718
+ false
719
+ );
720
+ conn.send(this.codec.toBuffer(responseMsg2));
721
+ log?.warn(
722
+ `${this.clientId} -- received invalid handshake msg: ${JSON.stringify(
723
+ parsed
724
+ )}`
725
+ );
726
+ return;
727
+ }
728
+ log?.debug(
729
+ `${this.clientId} -- handshake from ${parsed.from} ok, responding with handshake success`
730
+ );
731
+ const responseMsg = bootResponseMessage(
732
+ this.clientId,
733
+ this.instanceId,
734
+ parsed.from,
735
+ true
736
+ );
737
+ conn.send(this.codec.toBuffer(responseMsg));
738
+ sessionCb(this.onConnect(conn, parsed.from));
739
+ };
740
+ return bootHandler;
741
+ }
742
+ };
743
+
744
+ // transport/transforms/messageFraming.ts
745
+ var import_node_stream = require("stream");
746
+ var Uint32LengthPrefixFraming = class extends import_node_stream.Transform {
747
+ receivedBuffer;
748
+ maxBufferSizeBytes;
749
+ constructor({ maxBufferSizeBytes, ...options }) {
750
+ super(options);
751
+ this.maxBufferSizeBytes = maxBufferSizeBytes;
752
+ this.receivedBuffer = Buffer.alloc(0);
753
+ }
754
+ _transform(chunk, _encoding, cb) {
755
+ if (this.receivedBuffer.byteLength + chunk.byteLength > this.maxBufferSizeBytes) {
756
+ const err = new Error(
757
+ `buffer overflow: ${this.receivedBuffer.byteLength}B > ${this.maxBufferSizeBytes}B`
758
+ );
759
+ this.emit("error", err);
760
+ cb(err);
761
+ return;
762
+ }
763
+ this.receivedBuffer = Buffer.concat([this.receivedBuffer, chunk]);
764
+ while (this.receivedBuffer.length > 4) {
765
+ const claimedMessageLength = this.receivedBuffer.readUInt32BE(0) + 4;
766
+ if (this.receivedBuffer.length >= claimedMessageLength) {
767
+ const message = this.receivedBuffer.subarray(4, claimedMessageLength);
768
+ this.push(message);
769
+ this.receivedBuffer = this.receivedBuffer.subarray(claimedMessageLength);
770
+ } else {
771
+ break;
772
+ }
773
+ }
774
+ cb();
775
+ }
776
+ _flush(cb) {
777
+ if (this.receivedBuffer.length) {
778
+ this.emit("error", new Error("got incomplete message while flushing"));
779
+ }
780
+ this.receivedBuffer = Buffer.alloc(0);
781
+ cb();
782
+ }
783
+ _destroy(error, callback) {
784
+ this.receivedBuffer = Buffer.alloc(0);
785
+ super._destroy(error, callback);
786
+ }
787
+ };
788
+ function createLengthEncodedStream(options) {
789
+ return new Uint32LengthPrefixFraming({
790
+ maxBufferSizeBytes: options?.maxBufferSizeBytes ?? 16 * 1024 * 1024
791
+ // 16MB
792
+ });
793
+ }
794
+ var MessageFramer = {
795
+ createFramedStream: createLengthEncodedStream,
796
+ write: (buf) => {
797
+ const lengthPrefix = Buffer.alloc(4);
798
+ lengthPrefix.writeUInt32BE(buf.length, 0);
799
+ return Buffer.concat([lengthPrefix, buf]);
800
+ }
801
+ };
802
+
803
+ // transport/impls/stdio/connection.ts
804
+ var StreamConnection = class extends Connection {
805
+ input;
806
+ output;
807
+ framer;
808
+ constructor(input, output) {
809
+ super();
810
+ this.framer = MessageFramer.createFramedStream();
811
+ this.input = input.pipe(this.framer);
812
+ this.output = output;
813
+ }
814
+ addDataListener(cb) {
815
+ this.input.on("data", cb);
816
+ }
817
+ removeDataListener(cb) {
818
+ this.input.off("data", cb);
819
+ }
820
+ addCloseListener(cb) {
821
+ this.input.on("close", cb);
822
+ this.output.on("close", cb);
823
+ }
824
+ addErrorListener(cb) {
825
+ this.input.on("error", cb);
826
+ this.output.on("error", cb);
827
+ }
828
+ send(payload) {
829
+ if (!this.output.writable)
830
+ return false;
831
+ return this.output.write(MessageFramer.write(payload));
832
+ }
833
+ close() {
834
+ this.output.end();
835
+ this.input.unpipe(this.framer);
836
+ this.framer.destroy();
837
+ }
838
+ };
839
+
840
+ // transport/impls/stdio/server.ts
841
+ var StdioServerTransport = class extends ServerTransport {
842
+ input = process.stdin;
843
+ output = process.stdout;
844
+ /**
845
+ * Constructs a new StdioServerTransport instance.
846
+ * @param clientId - The ID of the client associated with this transport.
847
+ * @param input - The readable stream to use as input. Defaults to process.stdin.
848
+ * @param output - The writable stream to use as output. Defaults to process.stdout.
849
+ */
850
+ constructor(clientId, input = process.stdin, output = process.stdout, providedOptions) {
851
+ super(clientId, providedOptions);
852
+ this.input = input;
853
+ this.output = output;
854
+ const conn = new StreamConnection(this.input, this.output);
855
+ this.handleConnection(conn);
856
+ }
857
+ };
858
+ // Annotate the CommonJS export names for ESM import in node:
859
+ 0 && (module.exports = {
860
+ StdioServerTransport
861
+ });