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