@replit/river 0.12.5 → 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-6OAKPO5R.js → chunk-NPXAAD7M.js} +1 -1
  7. package/dist/{chunk-2PKONGC3.js → chunk-R2IMXRVU.js} +160 -135
  8. package/dist/{connection-4a839b9a.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-1afc5580.d.ts → index-21c1b21d.d.ts} +32 -18
  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 +153 -140
  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 +161 -146
  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 +157 -142
  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 +161 -146
  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 +212 -186
  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-7J66WOIC.js +0 -44
  41. package/dist/chunk-H4QR2K3T.js +0 -47
  42. package/dist/connection-64b9e0ff.d.ts +0 -17
  43. package/dist/connection-a6cc48e8.d.ts +0 -18
  44. package/dist/transport/impls/stdio/client.cjs +0 -913
  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 -888
  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-1afc5580.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-1afc5580.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`
@@ -260,13 +320,11 @@ var Session = class {
260
320
  this.cancelGrace();
261
321
  this.connection = newConn;
262
322
  }
263
- graceCb;
264
323
  beginGrace(cb) {
265
- this.graceCb = cb;
266
324
  this.disconnectionGrace = setTimeout(() => {
267
325
  this.close();
268
326
  cb();
269
- }, SESSION_DISCONNECT_GRACE_MS);
327
+ }, this.options.sessionDisconnectGraceMs);
270
328
  }
271
329
  // called on reconnect of the underlying session
272
330
  cancelGrace() {
@@ -278,8 +336,8 @@ var Session = class {
278
336
  close() {
279
337
  this.closeStaleConnection(this.connection);
280
338
  this.cancelGrace();
281
- clearInterval(this.heartbeat);
282
339
  this.resetBufferedMessages();
340
+ clearInterval(this.heartbeat);
283
341
  }
284
342
  get connected() {
285
343
  return this.connection !== void 0;
@@ -428,58 +486,6 @@ var EventDispatcher = class {
428
486
  }
429
487
  };
430
488
 
431
- // codec/json.ts
432
- var encoder = new TextEncoder();
433
- var decoder = new TextDecoder();
434
- function uint8ArrayToBase64(uint8Array) {
435
- let binary = "";
436
- uint8Array.forEach((byte) => {
437
- binary += String.fromCharCode(byte);
438
- });
439
- return btoa(binary);
440
- }
441
- function base64ToUint8Array(base64) {
442
- const binaryString = atob(base64);
443
- const uint8Array = new Uint8Array(binaryString.length);
444
- for (let i = 0; i < binaryString.length; i++) {
445
- uint8Array[i] = binaryString.charCodeAt(i);
446
- }
447
- return uint8Array;
448
- }
449
- var NaiveJsonCodec = {
450
- toBuffer: (obj) => {
451
- return encoder.encode(
452
- JSON.stringify(obj, function replacer(key) {
453
- const val = this[key];
454
- if (val instanceof Uint8Array) {
455
- return { $t: uint8ArrayToBase64(val) };
456
- } else {
457
- return val;
458
- }
459
- })
460
- );
461
- },
462
- fromBuffer: (buff) => {
463
- try {
464
- const parsed = JSON.parse(
465
- decoder.decode(buff),
466
- function reviver(_key, val) {
467
- if (val?.$t) {
468
- return base64ToUint8Array(val.$t);
469
- } else {
470
- return val;
471
- }
472
- }
473
- );
474
- if (typeof parsed === "object")
475
- return parsed;
476
- return null;
477
- } catch {
478
- return null;
479
- }
480
- }
481
- };
482
-
483
489
  // transport/transport.ts
484
490
  var import_nanoid3 = require("nanoid");
485
491
 
@@ -492,13 +498,13 @@ function coerceErrorString(err) {
492
498
  }
493
499
 
494
500
  // transport/transport.ts
495
- var DEFAULT_RECONNECT_JITTER_MAX_MS = 500;
496
- var DEFAULT_RECONNECT_INTERVAL_MS = 250;
501
+ var RECONNECT_JITTER_MAX_MS = 500;
502
+ var RECONNECT_INTERVAL_MS = 250;
497
503
  var defaultTransportOptions = {
498
- retryIntervalMs: DEFAULT_RECONNECT_INTERVAL_MS,
499
- retryJitterMs: DEFAULT_RECONNECT_JITTER_MAX_MS,
504
+ retryIntervalMs: RECONNECT_INTERVAL_MS,
505
+ retryJitterMs: RECONNECT_JITTER_MAX_MS,
500
506
  retryAttemptsMax: 5,
501
- codec: NaiveJsonCodec
507
+ ...defaultSessionOptions
502
508
  };
503
509
  var Transport = class {
504
510
  /**
@@ -555,15 +561,6 @@ var Transport = class {
555
561
  this.clientId = clientId;
556
562
  this.state = "open";
557
563
  }
558
- sessionByClientId(clientId) {
559
- const session = this.sessions.get(clientId);
560
- if (!session) {
561
- const err = `${this.clientId} -- (invariant violation) no existing session for ${clientId}`;
562
- log?.error(err);
563
- throw new Error(err);
564
- }
565
- return session;
566
- }
567
564
  /**
568
565
  * Called when a new connection is established
569
566
  * and we know the identity of the connected client.
@@ -578,7 +575,7 @@ var Transport = class {
578
575
  const lastInstanceId = this.connectedInstanceIds.get(connectedTo);
579
576
  if (oldSession && lastInstanceId !== void 0 && lastInstanceId !== instanceId) {
580
577
  log?.warn(
581
- `${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`
582
579
  );
583
580
  oldSession.close();
584
581
  this.deleteSession(oldSession);
@@ -601,10 +598,10 @@ var Transport = class {
601
598
  }
602
599
  createSession(connectedTo, conn) {
603
600
  const session = new Session(
604
- this.codec,
605
601
  this.clientId,
606
602
  connectedTo,
607
- conn
603
+ conn,
604
+ this.options
608
605
  );
609
606
  this.sessions.set(session.to, session);
610
607
  this.eventDispatcher.dispatchEvent("sessionStatus", {
@@ -633,13 +630,10 @@ var Transport = class {
633
630
  status: "disconnect",
634
631
  conn
635
632
  });
636
- if (this.state !== "open")
633
+ const session = this.sessions.get(connectedTo);
634
+ if (!session)
637
635
  return;
638
- const session = this.sessionByClientId(connectedTo);
639
- log?.info(
640
- `${this.clientId} -- connection (id: ${conn.debugId}) disconnect from ${connectedTo}, ${SESSION_DISCONNECT_GRACE_MS}ms until session (id: ${session.debugId}) disconnect`
641
- );
642
- session.closeStaleConnection(conn);
636
+ session.connection = void 0;
643
637
  session.beginGrace(() => this.deleteSession(session));
644
638
  }
645
639
  /**
@@ -650,7 +644,7 @@ var Transport = class {
650
644
  parseMsg(msg) {
651
645
  const parsedMsg = this.codec.fromBuffer(msg);
652
646
  if (parsedMsg === null) {
653
- const decodedBuffer = new TextDecoder().decode(msg);
647
+ const decodedBuffer = new TextDecoder().decode(Buffer.from(msg));
654
648
  log?.error(
655
649
  `${this.clientId} -- received malformed msg, killing conn: ${decodedBuffer}`
656
650
  );
@@ -664,11 +658,7 @@ var Transport = class {
664
658
  );
665
659
  return null;
666
660
  }
667
- return {
668
- ...parsedMsg,
669
- serviceName: parsedMsg.serviceName === null ? void 0 : parsedMsg.serviceName,
670
- procedureName: parsedMsg.procedureName === null ? void 0 : parsedMsg.procedureName
671
- };
661
+ return parsedMsg;
672
662
  }
673
663
  /**
674
664
  * Called when a message is received by this transport.
@@ -678,15 +668,27 @@ var Transport = class {
678
668
  handleMsg(msg) {
679
669
  if (this.state !== "open")
680
670
  return;
681
- const session = this.sessionByClientId(msg.from);
671
+ const session = this.sessions.get(msg.from);
672
+ if (!session) {
673
+ const err = `${this.clientId} -- (invariant violation) no existing session for ${msg.from}`;
674
+ log?.error(err);
675
+ return;
676
+ }
682
677
  session.cancelGrace();
683
678
  log?.debug(`${this.clientId} -- received msg: ${JSON.stringify(msg)}`);
684
679
  if (msg.seq !== session.nextExpectedSeq) {
685
- log?.warn(
686
- `${this.clientId} -- received out-of-order msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), discarding: ${JSON.stringify(
687
- msg
688
- )}`
689
- );
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
+ }
690
692
  return;
691
693
  }
692
694
  if (!isAck(msg.controlFlags)) {
@@ -704,7 +706,7 @@ var Transport = class {
704
706
  }
705
707
  /**
706
708
  * Removes a listener from this transport.
707
- * @param the type of event to unlisten on
709
+ * @param the type of event to un-listen on
708
710
  * @param handler The message handler to remove.
709
711
  */
710
712
  removeEventListener(type, handler) {
@@ -781,23 +783,31 @@ var ClientTransport = class extends Transport {
781
783
  */
782
784
  inflightConnectionPromises;
783
785
  tryReconnecting = true;
784
- constructor(clientId, providedOptions) {
786
+ connectedTo;
787
+ constructor(clientId, connectedTo, providedOptions) {
785
788
  super(clientId, providedOptions);
789
+ this.connectedTo = connectedTo;
786
790
  this.inflightConnectionPromises = /* @__PURE__ */ new Map();
787
791
  }
788
792
  handleConnection(conn, to) {
789
- const bootHandler = this.receiveWithBootSequence(conn, () => {
790
- conn.removeDataListener(bootHandler);
791
- conn.addDataListener((data) => {
792
- 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);
793
803
  if (!parsed) {
794
804
  conn.close();
795
805
  return;
796
806
  }
797
807
  this.handleMsg(parsed);
798
808
  });
799
- });
800
- conn.addDataListener(bootHandler);
809
+ };
810
+ conn.addDataListener(handshakeHandler);
801
811
  conn.addCloseListener(() => {
802
812
  this.onDisconnect(conn, to);
803
813
  void this.connect(to);
@@ -808,6 +818,32 @@ var ClientTransport = class extends Transport {
808
818
  );
809
819
  });
810
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
+ }
811
847
  /**
812
848
  * Manually attempts to connect to a client.
813
849
  * @param to The client ID of the node to connect to.
@@ -826,10 +862,7 @@ var ClientTransport = class extends Transport {
826
862
  }
827
863
  try {
828
864
  const conn = await reconnectPromise;
829
- this.state = "open";
830
- const requestMsg = bootRequestMessage(this.clientId, to, this.instanceId);
831
- log?.debug(`${this.clientId} -- sending boot handshake to ${to}`);
832
- conn.send(this.codec.toBuffer(requestMsg));
865
+ this.sendHandshake(to, conn);
833
866
  } catch (error) {
834
867
  const errStr = coerceErrorString(error);
835
868
  this.inflightConnectionPromises.delete(to);
@@ -847,34 +880,14 @@ var ClientTransport = class extends Transport {
847
880
  }
848
881
  }
849
882
  }
850
- receiveWithBootSequence(conn, sessionCb) {
851
- const bootHandler = (data) => {
852
- const parsed = this.parseMsg(data);
853
- if (!parsed) {
854
- conn.close();
855
- return;
856
- }
857
- if (!import_value.Value.Check(ControlMessageHandshakeResponseSchema, parsed.payload)) {
858
- log?.warn(
859
- `${this.clientId} -- received invalid handshake resp: ${JSON.stringify(parsed)}`
860
- );
861
- return;
862
- }
863
- if (!parsed.payload.status.ok) {
864
- log?.warn(
865
- `${this.clientId} -- received failed handshake resp: ${JSON.stringify(
866
- parsed
867
- )}`
868
- );
869
- return;
870
- }
871
- const serverInstanceId = parsed.payload.status.instanceId;
872
- log?.debug(
873
- `${this.clientId} -- handshake from ${parsed.from} ok (server instance: ${serverInstanceId})`
874
- );
875
- sessionCb(this.onConnect(conn, parsed.from, serverInstanceId));
876
- };
877
- 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));
878
891
  }
879
892
  onDisconnect(conn, connectedTo) {
880
893
  this.inflightConnectionPromises.delete(connectedTo);
@@ -887,7 +900,7 @@ var UnixDomainSocketClientTransport = class extends ClientTransport {
887
900
  path;
888
901
  serverId;
889
902
  constructor(socketPath, clientId, serverId, providedOptions) {
890
- super(clientId, providedOptions);
903
+ super(clientId, serverId, providedOptions);
891
904
  this.path = socketPath;
892
905
  this.serverId = serverId;
893
906
  void this.connect(serverId);
@@ -1,9 +1,8 @@
1
- import { a as ClientTransport, b as TransportClientId, c as TransportOptions } from '../../../index-1afc5580.js';
2
- import { U as UdsConnection } from '../../../connection-a6cc48e8.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> {