@replit/river 0.12.6 → 0.13.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 (51) hide show
  1. package/README.md +4 -1
  2. package/dist/{builder-c593de11.d.ts → builder-169fbf7f.d.ts} +16 -7
  3. package/dist/{chunk-AFLZ6INU.js → chunk-CBRQM65K.js} +29 -10
  4. package/dist/{chunk-IIBVKYDB.js → chunk-CDH7QSB4.js} +39 -1
  5. package/dist/{chunk-XFFS4UOD.js → chunk-MGGIUH5O.js} +7 -7
  6. package/dist/{chunk-VLBVQX5H.js → chunk-NPXAAD7M.js} +1 -1
  7. package/dist/{chunk-4SDJ5VN4.js → chunk-R2IMXRVU.js} +150 -116
  8. package/dist/{connection-ba37d174.d.ts → connection-ab681c08.d.ts} +1 -1
  9. package/dist/{messageFraming-b200ef25.d.ts → connection-dd789651.d.ts} +17 -2
  10. package/dist/{index-54e0f99c.d.ts → index-21c1b21d.d.ts} +29 -13
  11. package/dist/router/index.cjs +31 -13
  12. package/dist/router/index.d.cts +5 -5
  13. package/dist/router/index.d.ts +5 -5
  14. package/dist/router/index.js +2 -2
  15. package/dist/transport/impls/uds/client.cjs +143 -121
  16. package/dist/transport/impls/uds/client.d.cts +2 -3
  17. package/dist/transport/impls/uds/client.d.ts +2 -3
  18. package/dist/transport/impls/uds/client.js +5 -6
  19. package/dist/transport/impls/uds/server.cjs +151 -127
  20. package/dist/transport/impls/uds/server.d.cts +2 -3
  21. package/dist/transport/impls/uds/server.d.ts +2 -3
  22. package/dist/transport/impls/uds/server.js +4 -5
  23. package/dist/transport/impls/ws/client.cjs +147 -123
  24. package/dist/transport/impls/ws/client.d.cts +4 -4
  25. package/dist/transport/impls/ws/client.d.ts +4 -4
  26. package/dist/transport/impls/ws/client.js +7 -7
  27. package/dist/transport/impls/ws/server.cjs +151 -127
  28. package/dist/transport/impls/ws/server.d.cts +2 -2
  29. package/dist/transport/impls/ws/server.d.ts +2 -2
  30. package/dist/transport/impls/ws/server.js +4 -4
  31. package/dist/transport/index.cjs +202 -167
  32. package/dist/transport/index.d.cts +1 -1
  33. package/dist/transport/index.d.ts +1 -1
  34. package/dist/transport/index.js +3 -3
  35. package/dist/util/testHelpers.cjs +294 -16
  36. package/dist/util/testHelpers.d.cts +2 -2
  37. package/dist/util/testHelpers.d.ts +2 -2
  38. package/dist/util/testHelpers.js +30 -8
  39. package/package.json +1 -9
  40. package/dist/chunk-PBPXYLI6.js +0 -44
  41. package/dist/chunk-Q7GL34DZ.js +0 -47
  42. package/dist/connection-1f9971d8.d.ts +0 -17
  43. package/dist/connection-24d878ac.d.ts +0 -18
  44. package/dist/transport/impls/stdio/client.cjs +0 -904
  45. package/dist/transport/impls/stdio/client.d.cts +0 -27
  46. package/dist/transport/impls/stdio/client.d.ts +0 -27
  47. package/dist/transport/impls/stdio/client.js +0 -42
  48. package/dist/transport/impls/stdio/server.cjs +0 -879
  49. package/dist/transport/impls/stdio/server.d.cts +0 -25
  50. package/dist/transport/impls/stdio/server.d.ts +0 -25
  51. package/dist/transport/impls/stdio/server.js +0 -33
@@ -412,8 +412,8 @@ var TransportMessageSchema = (t) => import_typebox2.Type.Object({
412
412
  to: import_typebox2.Type.String(),
413
413
  seq: import_typebox2.Type.Integer(),
414
414
  ack: import_typebox2.Type.Integer(),
415
- serviceName: import_typebox2.Type.Optional(import_typebox2.Type.Union([import_typebox2.Type.String(), import_typebox2.Type.Null()])),
416
- procedureName: import_typebox2.Type.Optional(import_typebox2.Type.Union([import_typebox2.Type.String(), import_typebox2.Type.Null()])),
415
+ serviceName: import_typebox2.Type.Optional(import_typebox2.Type.String()),
416
+ procedureName: import_typebox2.Type.Optional(import_typebox2.Type.String()),
417
417
  streamId: import_typebox2.Type.String(),
418
418
  controlFlags: import_typebox2.Type.Integer(),
419
419
  payload: t
@@ -424,10 +424,9 @@ var ControlMessageAckSchema = import_typebox2.Type.Object({
424
424
  var ControlMessageCloseSchema = import_typebox2.Type.Object({
425
425
  type: import_typebox2.Type.Literal("CLOSE")
426
426
  });
427
- var PROTOCOL_VERSION = "v1";
428
427
  var ControlMessageHandshakeRequestSchema = import_typebox2.Type.Object({
429
428
  type: import_typebox2.Type.Literal("HANDSHAKE_REQ"),
430
- protocolVersion: import_typebox2.Type.Literal(PROTOCOL_VERSION),
429
+ protocolVersion: import_typebox2.Type.String(),
431
430
  instanceId: import_typebox2.Type.String()
432
431
  });
433
432
  var ControlMessageHandshakeResponseSchema = import_typebox2.Type.Object({
@@ -513,7 +512,8 @@ function _createRecursiveProxy(callback, path) {
513
512
  });
514
513
  return proxy;
515
514
  }
516
- var createClient = (transport, serverId = "SERVER") => _createRecursiveProxy(async (opts) => {
515
+ var createClient = (transport) => _createRecursiveProxy(async (opts) => {
516
+ const serverId = transport.connectedTo;
517
517
  const [serviceName, procName, procType] = [...opts.path];
518
518
  if (!(serviceName && procName && procType)) {
519
519
  throw new Error(
@@ -878,7 +878,13 @@ var RiverServer = class {
878
878
  );
879
879
  return;
880
880
  }
881
- if (!message.serviceName || !(message.serviceName in this.services)) {
881
+ if (!message.procedureName || !message.serviceName) {
882
+ log?.warn(
883
+ `${this.transport.clientId} -- missing procedure or service name in stream open message`
884
+ );
885
+ return;
886
+ }
887
+ if (!(message.serviceName in this.services)) {
882
888
  log?.warn(
883
889
  `${this.transport.clientId} -- couldn't find service ${message.serviceName}`
884
890
  );
@@ -886,7 +892,7 @@ var RiverServer = class {
886
892
  }
887
893
  const service = this.services[message.serviceName];
888
894
  const serviceContext = this.getContext(service);
889
- if (!message.procedureName || !(message.procedureName in service.procedures)) {
895
+ if (!(message.procedureName in service.procedures)) {
890
896
  log?.warn(
891
897
  `${this.transport.clientId} -- couldn't find a matching procedure for ${message.serviceName}.${message.procedureName}`
892
898
  );
@@ -932,6 +938,13 @@ var RiverServer = class {
932
938
  };
933
939
  let inputHandler;
934
940
  const procHasInitMessage = "init" in procedure;
941
+ const serviceContextWithTransportInfo = {
942
+ ...serviceContext,
943
+ to: message.to,
944
+ from: message.from,
945
+ streamId: message.streamId,
946
+ session
947
+ };
935
948
  switch (procedure.type) {
936
949
  case "rpc":
937
950
  inputHandler = (async () => {
@@ -941,7 +954,7 @@ var RiverServer = class {
941
954
  }
942
955
  try {
943
956
  const outputMessage = await procedure.handler(
944
- serviceContext,
957
+ serviceContextWithTransportInfo,
945
958
  inputMessage.value
946
959
  );
947
960
  outgoing.push(outputMessage);
@@ -957,10 +970,15 @@ var RiverServer = class {
957
970
  if (initMessage.done) {
958
971
  return;
959
972
  }
960
- return procedure.handler(serviceContext, initMessage.value, incoming, outgoing).catch(errorHandler);
973
+ return procedure.handler(
974
+ serviceContextWithTransportInfo,
975
+ initMessage.value,
976
+ incoming,
977
+ outgoing
978
+ ).catch(errorHandler);
961
979
  })();
962
980
  } else {
963
- inputHandler = procedure.handler(serviceContext, incoming, outgoing).catch(errorHandler);
981
+ inputHandler = procedure.handler(serviceContextWithTransportInfo, incoming, outgoing).catch(errorHandler);
964
982
  }
965
983
  break;
966
984
  case "subscription":
@@ -971,7 +989,7 @@ var RiverServer = class {
971
989
  }
972
990
  try {
973
991
  await procedure.handler(
974
- serviceContext,
992
+ serviceContextWithTransportInfo,
975
993
  inputMessage.value,
976
994
  outgoing
977
995
  );
@@ -989,7 +1007,7 @@ var RiverServer = class {
989
1007
  }
990
1008
  try {
991
1009
  const outputMessage = await procedure.handler(
992
- serviceContext,
1010
+ serviceContextWithTransportInfo,
993
1011
  initMessage.value,
994
1012
  incoming
995
1013
  );
@@ -1004,7 +1022,7 @@ var RiverServer = class {
1004
1022
  inputHandler = (async () => {
1005
1023
  try {
1006
1024
  const outputMessage = await procedure.handler(
1007
- serviceContext,
1025
+ serviceContextWithTransportInfo,
1008
1026
  incoming
1009
1027
  );
1010
1028
  if (!this.disconnectedSessions.has(message.from)) {
@@ -1,6 +1,6 @@
1
- import { A as AnyService, P as PayloadType, b as Result, R as RiverError, S as ServiceContext, d as ProcType, e as ProcInput, f as ProcOutput, g as ProcErrors, h as ProcHasInit, i as ProcInit } from '../builder-c593de11.js';
2
- export { E as Err, O as Ok, m as ProcHandler, k as ProcListing, a as Procedure, o as RiverErrorSchema, c as RiverUncaughtSchema, l as Service, j as ServiceBuilder, n as ServiceContextWithState, U as UNCAUGHT_ERROR, V as ValidProcType, s as serializeService } from '../builder-c593de11.js';
3
- import { T as Transport, C as Connection, b as TransportClientId } from '../index-54e0f99c.js';
1
+ import { A as AnyService, P as PayloadType, b as Result, R as RiverError, S as ServiceContext, d as ProcType, e as ProcInput, f as ProcOutput, g as ProcErrors, h as ProcHasInit, i as ProcInit } from '../builder-169fbf7f.js';
2
+ export { E as Err, O as Ok, m as ProcHandler, k as ProcListing, a as Procedure, p as RiverErrorSchema, c as RiverUncaughtSchema, l as Service, j as ServiceBuilder, n as ServiceContextWithState, o as ServiceContextWithTransportInfo, U as UNCAUGHT_ERROR, V as ValidProcType, s as serializeService } from '../builder-169fbf7f.js';
3
+ import { S as ServerTransport, C as Connection, a as ClientTransport } from '../index-21c1b21d.js';
4
4
  import { Pushable } from 'it-pushable';
5
5
  import { Static } from '@sinclair/typebox';
6
6
  import '../types-3e5768ec.js';
@@ -50,7 +50,7 @@ interface ProcStream {
50
50
  * @param extendedContext - An optional object containing additional context to be passed to all services.
51
51
  * @returns A promise that resolves to a server instance with the registered services.
52
52
  */
53
- declare function createServer<Services extends ServiceDefs>(transport: Transport<Connection>, services: Services, extendedContext?: Omit<ServiceContext, 'state'>): Server<Services>;
53
+ declare function createServer<Services extends ServiceDefs>(transport: ServerTransport<Connection>, services: Services, extendedContext?: Omit<ServiceContext, 'state'>): Server<Services>;
54
54
 
55
55
  type AsyncIter<T> = AsyncGenerator<T, T>;
56
56
  /**
@@ -110,6 +110,6 @@ type ServerClient<Srv extends Server<ServiceDefs>> = {
110
110
  * @param {Transport} transport - The transport to use for communication.
111
111
  * @returns The client for the server.
112
112
  */
113
- declare const createClient: <Srv extends Server<ServiceDefs>>(transport: Transport<Connection>, serverId?: TransportClientId) => ServerClient<Srv>;
113
+ declare const createClient: <Srv extends Server<ServiceDefs>>(transport: ClientTransport<Connection>) => ServerClient<Srv>;
114
114
 
115
115
  export { PayloadType, ProcInput, ProcOutput, ProcType, Result, RiverError, Server, ServerClient, ServiceContext, ServiceDefs, buildServiceDefs, createClient, createServer };
@@ -1,6 +1,6 @@
1
- import { A as AnyService, P as PayloadType, b as Result, R as RiverError, S as ServiceContext, d as ProcType, e as ProcInput, f as ProcOutput, g as ProcErrors, h as ProcHasInit, i as ProcInit } from '../builder-c593de11.js';
2
- export { E as Err, O as Ok, m as ProcHandler, k as ProcListing, a as Procedure, o as RiverErrorSchema, c as RiverUncaughtSchema, l as Service, j as ServiceBuilder, n as ServiceContextWithState, U as UNCAUGHT_ERROR, V as ValidProcType, s as serializeService } from '../builder-c593de11.js';
3
- import { T as Transport, C as Connection, b as TransportClientId } from '../index-54e0f99c.js';
1
+ import { A as AnyService, P as PayloadType, b as Result, R as RiverError, S as ServiceContext, d as ProcType, e as ProcInput, f as ProcOutput, g as ProcErrors, h as ProcHasInit, i as ProcInit } from '../builder-169fbf7f.js';
2
+ export { E as Err, O as Ok, m as ProcHandler, k as ProcListing, a as Procedure, p as RiverErrorSchema, c as RiverUncaughtSchema, l as Service, j as ServiceBuilder, n as ServiceContextWithState, o as ServiceContextWithTransportInfo, U as UNCAUGHT_ERROR, V as ValidProcType, s as serializeService } from '../builder-169fbf7f.js';
3
+ import { S as ServerTransport, C as Connection, a as ClientTransport } from '../index-21c1b21d.js';
4
4
  import { Pushable } from 'it-pushable';
5
5
  import { Static } from '@sinclair/typebox';
6
6
  import '../types-3e5768ec.js';
@@ -50,7 +50,7 @@ interface ProcStream {
50
50
  * @param extendedContext - An optional object containing additional context to be passed to all services.
51
51
  * @returns A promise that resolves to a server instance with the registered services.
52
52
  */
53
- declare function createServer<Services extends ServiceDefs>(transport: Transport<Connection>, services: Services, extendedContext?: Omit<ServiceContext, 'state'>): Server<Services>;
53
+ declare function createServer<Services extends ServiceDefs>(transport: ServerTransport<Connection>, services: Services, extendedContext?: Omit<ServiceContext, 'state'>): Server<Services>;
54
54
 
55
55
  type AsyncIter<T> = AsyncGenerator<T, T>;
56
56
  /**
@@ -110,6 +110,6 @@ type ServerClient<Srv extends Server<ServiceDefs>> = {
110
110
  * @param {Transport} transport - The transport to use for communication.
111
111
  * @returns The client for the server.
112
112
  */
113
- declare const createClient: <Srv extends Server<ServiceDefs>>(transport: Transport<Connection>, serverId?: TransportClientId) => ServerClient<Srv>;
113
+ declare const createClient: <Srv extends Server<ServiceDefs>>(transport: ClientTransport<Connection>) => ServerClient<Srv>;
114
114
 
115
115
  export { PayloadType, ProcInput, ProcOutput, ProcType, Result, RiverError, Server, ServerClient, ServiceContext, ServiceDefs, buildServiceDefs, createClient, createServer };
@@ -8,8 +8,8 @@ import {
8
8
  createClient,
9
9
  createServer,
10
10
  serializeService
11
- } from "../chunk-AFLZ6INU.js";
12
- import "../chunk-XFFS4UOD.js";
11
+ } from "../chunk-CBRQM65K.js";
12
+ import "../chunk-MGGIUH5O.js";
13
13
  import "../chunk-H4BYJELI.js";
14
14
  export {
15
15
  Err,
@@ -40,8 +40,8 @@ var TransportMessageSchema = (t) => import_typebox.Type.Object({
40
40
  to: import_typebox.Type.String(),
41
41
  seq: import_typebox.Type.Integer(),
42
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()])),
43
+ serviceName: import_typebox.Type.Optional(import_typebox.Type.String()),
44
+ procedureName: import_typebox.Type.Optional(import_typebox.Type.String()),
45
45
  streamId: import_typebox.Type.String(),
46
46
  controlFlags: import_typebox.Type.Integer(),
47
47
  payload: t
@@ -55,7 +55,7 @@ var ControlMessageCloseSchema = import_typebox.Type.Object({
55
55
  var PROTOCOL_VERSION = "v1";
56
56
  var ControlMessageHandshakeRequestSchema = import_typebox.Type.Object({
57
57
  type: import_typebox.Type.Literal("HANDSHAKE_REQ"),
58
- protocolVersion: import_typebox.Type.Literal(PROTOCOL_VERSION),
58
+ protocolVersion: import_typebox.Type.String(),
59
59
  instanceId: import_typebox.Type.String()
60
60
  });
61
61
  var ControlMessageHandshakeResponseSchema = import_typebox.Type.Object({
@@ -80,7 +80,7 @@ var ControlMessagePayloadSchema = import_typebox.Type.Union([
80
80
  var OpaqueTransportMessageSchema = TransportMessageSchema(
81
81
  import_typebox.Type.Unknown()
82
82
  );
83
- function bootRequestMessage(from, to, instanceId) {
83
+ function handshakeRequestMessage(from, to, instanceId) {
84
84
  return {
85
85
  id: (0, import_nanoid.nanoid)(),
86
86
  from,
@@ -100,6 +100,58 @@ function isAck(controlFlag) {
100
100
  return (controlFlag & 1 /* AckBit */) === 1 /* AckBit */;
101
101
  }
102
102
 
103
+ // codec/json.ts
104
+ var encoder = new TextEncoder();
105
+ var decoder = new TextDecoder();
106
+ function uint8ArrayToBase64(uint8Array) {
107
+ let binary = "";
108
+ uint8Array.forEach((byte) => {
109
+ binary += String.fromCharCode(byte);
110
+ });
111
+ return btoa(binary);
112
+ }
113
+ function base64ToUint8Array(base64) {
114
+ const binaryString = atob(base64);
115
+ const uint8Array = new Uint8Array(binaryString.length);
116
+ for (let i = 0; i < binaryString.length; i++) {
117
+ uint8Array[i] = binaryString.charCodeAt(i);
118
+ }
119
+ return uint8Array;
120
+ }
121
+ var NaiveJsonCodec = {
122
+ toBuffer: (obj) => {
123
+ return encoder.encode(
124
+ JSON.stringify(obj, function replacer(key) {
125
+ const val = this[key];
126
+ if (val instanceof Uint8Array) {
127
+ return { $t: uint8ArrayToBase64(val) };
128
+ } else {
129
+ return val;
130
+ }
131
+ })
132
+ );
133
+ },
134
+ fromBuffer: (buff) => {
135
+ try {
136
+ const parsed = JSON.parse(
137
+ decoder.decode(buff),
138
+ function reviver(_key, val) {
139
+ if (val?.$t) {
140
+ return base64ToUint8Array(val.$t);
141
+ } else {
142
+ return val;
143
+ }
144
+ }
145
+ );
146
+ if (typeof parsed === "object")
147
+ return parsed;
148
+ return null;
149
+ } catch {
150
+ return null;
151
+ }
152
+ }
153
+ };
154
+
103
155
  // transport/session.ts
104
156
  var nanoid2 = (0, import_nanoid2.customAlphabet)("1234567890abcdefghijklmnopqrstuvxyz", 6);
105
157
  var unsafeId = () => nanoid2();
@@ -112,8 +164,15 @@ var Connection = class {
112
164
  var HEARTBEAT_INTERVAL_MS = 1e3;
113
165
  var HEARTBEATS_TILL_DEAD = 2;
114
166
  var SESSION_DISCONNECT_GRACE_MS = 5e3;
167
+ var defaultSessionOptions = {
168
+ heartbeatIntervalMs: HEARTBEAT_INTERVAL_MS,
169
+ heartbeatsUntilDead: HEARTBEATS_TILL_DEAD,
170
+ sessionDisconnectGraceMs: SESSION_DISCONNECT_GRACE_MS,
171
+ codec: NaiveJsonCodec
172
+ };
115
173
  var Session = class {
116
174
  codec;
175
+ options;
117
176
  /**
118
177
  * The buffer of messages that have been sent but not yet acknowledged.
119
178
  */
@@ -149,16 +208,17 @@ var Session = class {
149
208
  * The interval for sending heartbeats.
150
209
  */
151
210
  heartbeat;
152
- constructor(codec, from, connectedTo, conn) {
211
+ constructor(from, connectedTo, conn, options) {
212
+ this.options = options;
153
213
  this.debugId = `sess-${unsafeId()}`;
154
214
  this.from = from;
155
215
  this.to = connectedTo;
156
216
  this.connection = conn;
157
- this.codec = codec;
217
+ this.codec = options.codec;
158
218
  this.heartbeatMisses = 0;
159
219
  this.heartbeat = setInterval(
160
220
  () => this.sendHeartbeat(),
161
- HEARTBEAT_INTERVAL_MS
221
+ options.heartbeatIntervalMs
162
222
  );
163
223
  }
164
224
  /**
@@ -194,7 +254,7 @@ var Session = class {
194
254
  return fullMsg.id;
195
255
  }
196
256
  sendHeartbeat() {
197
- if (this.heartbeatMisses >= HEARTBEATS_TILL_DEAD) {
257
+ if (this.heartbeatMisses >= this.options.heartbeatsUntilDead) {
198
258
  if (this.connection) {
199
259
  log?.info(
200
260
  `${this.from} -- closing connection (id: ${this.connection.debugId}) to ${this.to} due to inactivity`
@@ -264,7 +324,7 @@ var Session = class {
264
324
  this.disconnectionGrace = setTimeout(() => {
265
325
  this.close();
266
326
  cb();
267
- }, SESSION_DISCONNECT_GRACE_MS);
327
+ }, this.options.sessionDisconnectGraceMs);
268
328
  }
269
329
  // called on reconnect of the underlying session
270
330
  cancelGrace() {
@@ -426,58 +486,6 @@ var EventDispatcher = class {
426
486
  }
427
487
  };
428
488
 
429
- // codec/json.ts
430
- var encoder = new TextEncoder();
431
- var decoder = new TextDecoder();
432
- function uint8ArrayToBase64(uint8Array) {
433
- let binary = "";
434
- uint8Array.forEach((byte) => {
435
- binary += String.fromCharCode(byte);
436
- });
437
- return btoa(binary);
438
- }
439
- function base64ToUint8Array(base64) {
440
- const binaryString = atob(base64);
441
- const uint8Array = new Uint8Array(binaryString.length);
442
- for (let i = 0; i < binaryString.length; i++) {
443
- uint8Array[i] = binaryString.charCodeAt(i);
444
- }
445
- return uint8Array;
446
- }
447
- var NaiveJsonCodec = {
448
- toBuffer: (obj) => {
449
- return encoder.encode(
450
- JSON.stringify(obj, function replacer(key) {
451
- const val = this[key];
452
- if (val instanceof Uint8Array) {
453
- return { $t: uint8ArrayToBase64(val) };
454
- } else {
455
- return val;
456
- }
457
- })
458
- );
459
- },
460
- fromBuffer: (buff) => {
461
- try {
462
- const parsed = JSON.parse(
463
- decoder.decode(buff),
464
- function reviver(_key, val) {
465
- if (val?.$t) {
466
- return base64ToUint8Array(val.$t);
467
- } else {
468
- return val;
469
- }
470
- }
471
- );
472
- if (typeof parsed === "object")
473
- return parsed;
474
- return null;
475
- } catch {
476
- return null;
477
- }
478
- }
479
- };
480
-
481
489
  // transport/transport.ts
482
490
  var import_nanoid3 = require("nanoid");
483
491
 
@@ -490,13 +498,13 @@ function coerceErrorString(err) {
490
498
  }
491
499
 
492
500
  // transport/transport.ts
493
- var DEFAULT_RECONNECT_JITTER_MAX_MS = 500;
494
- var DEFAULT_RECONNECT_INTERVAL_MS = 250;
501
+ var RECONNECT_JITTER_MAX_MS = 500;
502
+ var RECONNECT_INTERVAL_MS = 250;
495
503
  var defaultTransportOptions = {
496
- retryIntervalMs: DEFAULT_RECONNECT_INTERVAL_MS,
497
- retryJitterMs: DEFAULT_RECONNECT_JITTER_MAX_MS,
504
+ retryIntervalMs: RECONNECT_INTERVAL_MS,
505
+ retryJitterMs: RECONNECT_JITTER_MAX_MS,
498
506
  retryAttemptsMax: 5,
499
- codec: NaiveJsonCodec
507
+ ...defaultSessionOptions
500
508
  };
501
509
  var Transport = class {
502
510
  /**
@@ -567,7 +575,7 @@ var Transport = class {
567
575
  const lastInstanceId = this.connectedInstanceIds.get(connectedTo);
568
576
  if (oldSession && lastInstanceId !== void 0 && lastInstanceId !== instanceId) {
569
577
  log?.warn(
570
- `${this.clientId} -- handshake from ${connectedTo} is a different instance (got: ${instanceId}, last connected to: ${lastInstanceId}), starting a new session`
578
+ `${this.clientId} -- connection from ${connectedTo} is a different instance (got: ${instanceId}, last connected to: ${lastInstanceId}), starting a new session`
571
579
  );
572
580
  oldSession.close();
573
581
  this.deleteSession(oldSession);
@@ -590,10 +598,10 @@ var Transport = class {
590
598
  }
591
599
  createSession(connectedTo, conn) {
592
600
  const session = new Session(
593
- this.codec,
594
601
  this.clientId,
595
602
  connectedTo,
596
- conn
603
+ conn,
604
+ this.options
597
605
  );
598
606
  this.sessions.set(session.to, session);
599
607
  this.eventDispatcher.dispatchEvent("sessionStatus", {
@@ -636,7 +644,7 @@ var Transport = class {
636
644
  parseMsg(msg) {
637
645
  const parsedMsg = this.codec.fromBuffer(msg);
638
646
  if (parsedMsg === null) {
639
- const decodedBuffer = new TextDecoder().decode(msg);
647
+ const decodedBuffer = new TextDecoder().decode(Buffer.from(msg));
640
648
  log?.error(
641
649
  `${this.clientId} -- received malformed msg, killing conn: ${decodedBuffer}`
642
650
  );
@@ -650,11 +658,7 @@ var Transport = class {
650
658
  );
651
659
  return null;
652
660
  }
653
- return {
654
- ...parsedMsg,
655
- serviceName: parsedMsg.serviceName === null ? void 0 : parsedMsg.serviceName,
656
- procedureName: parsedMsg.procedureName === null ? void 0 : parsedMsg.procedureName
657
- };
661
+ return parsedMsg;
658
662
  }
659
663
  /**
660
664
  * Called when a message is received by this transport.
@@ -673,11 +677,18 @@ var Transport = class {
673
677
  session.cancelGrace();
674
678
  log?.debug(`${this.clientId} -- received msg: ${JSON.stringify(msg)}`);
675
679
  if (msg.seq !== session.nextExpectedSeq) {
676
- log?.warn(
677
- `${this.clientId} -- received out-of-order msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), discarding: ${JSON.stringify(
678
- msg
679
- )}`
680
- );
680
+ if (msg.seq < session.nextExpectedSeq) {
681
+ log?.debug(
682
+ `${this.clientId} -- received duplicate msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), discarding: ${JSON.stringify(
683
+ msg
684
+ )}`
685
+ );
686
+ } else {
687
+ log?.error(
688
+ `${this.clientId} -- received out-of-order msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), marking connection as dead: ${JSON.stringify(msg)}`
689
+ );
690
+ session.closeStaleConnection(session.connection);
691
+ }
681
692
  return;
682
693
  }
683
694
  if (!isAck(msg.controlFlags)) {
@@ -695,7 +706,7 @@ var Transport = class {
695
706
  }
696
707
  /**
697
708
  * Removes a listener from this transport.
698
- * @param the type of event to unlisten on
709
+ * @param the type of event to un-listen on
699
710
  * @param handler The message handler to remove.
700
711
  */
701
712
  removeEventListener(type, handler) {
@@ -772,23 +783,31 @@ var ClientTransport = class extends Transport {
772
783
  */
773
784
  inflightConnectionPromises;
774
785
  tryReconnecting = true;
775
- constructor(clientId, providedOptions) {
786
+ connectedTo;
787
+ constructor(clientId, connectedTo, providedOptions) {
776
788
  super(clientId, providedOptions);
789
+ this.connectedTo = connectedTo;
777
790
  this.inflightConnectionPromises = /* @__PURE__ */ new Map();
778
791
  }
779
792
  handleConnection(conn, to) {
780
- const bootHandler = this.receiveWithBootSequence(conn, () => {
781
- conn.removeDataListener(bootHandler);
782
- conn.addDataListener((data) => {
783
- const parsed = this.parseMsg(data);
793
+ const handshakeHandler = (data) => {
794
+ const handshake = this.receiveHandshakeResponseMessage(data);
795
+ if (!handshake) {
796
+ conn.close();
797
+ return;
798
+ }
799
+ this.onConnect(conn, handshake.from, handshake.instanceId);
800
+ conn.removeDataListener(handshakeHandler);
801
+ conn.addDataListener((data2) => {
802
+ const parsed = this.parseMsg(data2);
784
803
  if (!parsed) {
785
804
  conn.close();
786
805
  return;
787
806
  }
788
807
  this.handleMsg(parsed);
789
808
  });
790
- });
791
- conn.addDataListener(bootHandler);
809
+ };
810
+ conn.addDataListener(handshakeHandler);
792
811
  conn.addCloseListener(() => {
793
812
  this.onDisconnect(conn, to);
794
813
  void this.connect(to);
@@ -799,6 +818,32 @@ var ClientTransport = class extends Transport {
799
818
  );
800
819
  });
801
820
  }
821
+ receiveHandshakeResponseMessage(data) {
822
+ const parsed = this.parseMsg(data);
823
+ if (!parsed)
824
+ return false;
825
+ if (!import_value.Value.Check(ControlMessageHandshakeResponseSchema, parsed.payload)) {
826
+ log?.warn(
827
+ `${this.clientId} -- received invalid handshake resp: ${JSON.stringify(
828
+ parsed
829
+ )}`
830
+ );
831
+ return false;
832
+ }
833
+ if (!parsed.payload.status.ok) {
834
+ log?.warn(
835
+ `${this.clientId} -- received failed handshake resp: ${JSON.stringify(
836
+ parsed
837
+ )}`
838
+ );
839
+ return false;
840
+ }
841
+ const instanceId = parsed.payload.status.instanceId;
842
+ log?.debug(
843
+ `${this.clientId} -- handshake from ${parsed.from} ok (instance: ${instanceId})`
844
+ );
845
+ return { instanceId, from: parsed.from };
846
+ }
802
847
  /**
803
848
  * Manually attempts to connect to a client.
804
849
  * @param to The client ID of the node to connect to.
@@ -817,10 +862,7 @@ var ClientTransport = class extends Transport {
817
862
  }
818
863
  try {
819
864
  const conn = await reconnectPromise;
820
- this.state = "open";
821
- const requestMsg = bootRequestMessage(this.clientId, to, this.instanceId);
822
- log?.debug(`${this.clientId} -- sending boot handshake to ${to}`);
823
- conn.send(this.codec.toBuffer(requestMsg));
865
+ this.sendHandshake(to, conn);
824
866
  } catch (error) {
825
867
  const errStr = coerceErrorString(error);
826
868
  this.inflightConnectionPromises.delete(to);
@@ -838,34 +880,14 @@ var ClientTransport = class extends Transport {
838
880
  }
839
881
  }
840
882
  }
841
- receiveWithBootSequence(conn, sessionCb) {
842
- const bootHandler = (data) => {
843
- const parsed = this.parseMsg(data);
844
- if (!parsed) {
845
- conn.close();
846
- return;
847
- }
848
- if (!import_value.Value.Check(ControlMessageHandshakeResponseSchema, parsed.payload)) {
849
- log?.warn(
850
- `${this.clientId} -- received invalid handshake resp: ${JSON.stringify(parsed)}`
851
- );
852
- return;
853
- }
854
- if (!parsed.payload.status.ok) {
855
- log?.warn(
856
- `${this.clientId} -- received failed handshake resp: ${JSON.stringify(
857
- parsed
858
- )}`
859
- );
860
- return;
861
- }
862
- const serverInstanceId = parsed.payload.status.instanceId;
863
- log?.debug(
864
- `${this.clientId} -- handshake from ${parsed.from} ok (server instance: ${serverInstanceId})`
865
- );
866
- sessionCb(this.onConnect(conn, parsed.from, serverInstanceId));
867
- };
868
- return bootHandler;
883
+ sendHandshake(to, conn) {
884
+ const requestMsg = handshakeRequestMessage(
885
+ this.clientId,
886
+ to,
887
+ this.instanceId
888
+ );
889
+ log?.debug(`${this.clientId} -- sending handshake request to ${to}`);
890
+ conn.send(this.codec.toBuffer(requestMsg));
869
891
  }
870
892
  onDisconnect(conn, connectedTo) {
871
893
  this.inflightConnectionPromises.delete(connectedTo);
@@ -878,7 +900,7 @@ var UnixDomainSocketClientTransport = class extends ClientTransport {
878
900
  path;
879
901
  serverId;
880
902
  constructor(socketPath, clientId, serverId, providedOptions) {
881
- super(clientId, providedOptions);
903
+ super(clientId, serverId, providedOptions);
882
904
  this.path = socketPath;
883
905
  this.serverId = serverId;
884
906
  void this.connect(serverId);
@@ -1,9 +1,8 @@
1
- import { a as ClientTransport, b as TransportClientId, c as TransportOptions } from '../../../index-54e0f99c.js';
2
- import { U as UdsConnection } from '../../../connection-24d878ac.js';
1
+ import { a as ClientTransport, b as TransportClientId, c as TransportOptions } from '../../../index-21c1b21d.js';
2
+ import { U as UdsConnection } from '../../../connection-dd789651.js';
3
3
  import '../../../types-3e5768ec.js';
4
4
  import '@sinclair/typebox';
5
5
  import 'node:net';
6
- import '../../../messageFraming-b200ef25.js';
7
6
  import 'node:stream';
8
7
 
9
8
  declare class UnixDomainSocketClientTransport extends ClientTransport<UdsConnection> {
@@ -1,9 +1,8 @@
1
- import { a as ClientTransport, b as TransportClientId, c as TransportOptions } from '../../../index-54e0f99c.js';
2
- import { U as UdsConnection } from '../../../connection-24d878ac.js';
1
+ import { a as ClientTransport, b as TransportClientId, c as TransportOptions } from '../../../index-21c1b21d.js';
2
+ import { U as UdsConnection } from '../../../connection-dd789651.js';
3
3
  import '../../../types-3e5768ec.js';
4
4
  import '@sinclair/typebox';
5
5
  import 'node:net';
6
- import '../../../messageFraming-b200ef25.js';
7
6
  import 'node:stream';
8
7
 
9
8
  declare class UnixDomainSocketClientTransport extends ClientTransport<UdsConnection> {
@@ -1,15 +1,14 @@
1
1
  import {
2
2
  UdsConnection
3
- } from "../../../chunk-PBPXYLI6.js";
4
- import "../../../chunk-IIBVKYDB.js";
3
+ } from "../../../chunk-CDH7QSB4.js";
5
4
  import {
6
5
  ClientTransport
7
- } from "../../../chunk-4SDJ5VN4.js";
8
- import "../../../chunk-GZ7HCLLM.js";
9
- import "../../../chunk-XFFS4UOD.js";
6
+ } from "../../../chunk-R2IMXRVU.js";
7
+ import "../../../chunk-MGGIUH5O.js";
10
8
  import {
11
9
  log
12
10
  } from "../../../chunk-H4BYJELI.js";
11
+ import "../../../chunk-GZ7HCLLM.js";
13
12
 
14
13
  // transport/impls/uds/client.ts
15
14
  import { Socket } from "node:net";
@@ -17,7 +16,7 @@ var UnixDomainSocketClientTransport = class extends ClientTransport {
17
16
  path;
18
17
  serverId;
19
18
  constructor(socketPath, clientId, serverId, providedOptions) {
20
- super(clientId, providedOptions);
19
+ super(clientId, serverId, providedOptions);
21
20
  this.path = socketPath;
22
21
  this.serverId = serverId;
23
22
  void this.connect(serverId);