react-websocket 4.22.1 → 4.22.2

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 (46) hide show
  1. package/dist/ag-ui.cjs +7 -7
  2. package/dist/ag-ui.cjs.map +1 -1
  3. package/dist/ag-ui.d.cts +3 -2
  4. package/dist/ag-ui.js +7 -7
  5. package/dist/ag-ui.js.map +1 -1
  6. package/dist/chaos.cjs +59 -11
  7. package/dist/chaos.cjs.map +1 -1
  8. package/dist/chaos.d.cts +1 -0
  9. package/dist/chaos.d.ts +1 -0
  10. package/dist/chaos.js +59 -11
  11. package/dist/chaos.js.map +1 -1
  12. package/dist/core.cjs +82 -43
  13. package/dist/core.cjs.map +1 -1
  14. package/dist/core.d.cts +4 -3
  15. package/dist/core.d.ts +4 -3
  16. package/dist/core.js +82 -43
  17. package/dist/core.js.map +1 -1
  18. package/dist/index.d.cts +4 -3
  19. package/dist/index.d.ts +3 -2
  20. package/dist/outbox.cjs +14 -8
  21. package/dist/outbox.cjs.map +1 -1
  22. package/dist/outbox.d.cts +1 -1
  23. package/dist/outbox.js +14 -8
  24. package/dist/outbox.js.map +1 -1
  25. package/dist/replay.cjs +12 -7
  26. package/dist/replay.cjs.map +1 -1
  27. package/dist/replay.d.cts +8 -2
  28. package/dist/replay.d.ts +8 -2
  29. package/dist/replay.js +12 -7
  30. package/dist/replay.js.map +1 -1
  31. package/dist/tabs.cjs +11 -14
  32. package/dist/tabs.cjs.map +1 -1
  33. package/dist/tabs.js +11 -14
  34. package/dist/tabs.js.map +1 -1
  35. package/dist/timeline.cjs +3 -1
  36. package/dist/timeline.cjs.map +1 -1
  37. package/dist/timeline.d.cts +3 -3
  38. package/dist/timeline.d.ts +2 -2
  39. package/dist/timeline.js +3 -1
  40. package/dist/timeline.js.map +1 -1
  41. package/dist/{types-paLT8yQF.d.cts → types-Bb3sBG8L.d.cts} +4 -3
  42. package/dist/webtransport.cjs +12 -10
  43. package/dist/webtransport.cjs.map +1 -1
  44. package/dist/webtransport.js +12 -10
  45. package/dist/webtransport.js.map +1 -1
  46. package/package.json +6 -6
package/dist/core.d.cts CHANGED
@@ -447,8 +447,9 @@ interface WebSocketClient<In = unknown, Out = unknown> {
447
447
  close(code?: number, reason?: string): void;
448
448
  /**
449
449
  * Drop the current socket (if any) and connect again immediately, resetting the
450
- * backoff. Also restarts a `closed` client. The send queue and a `migrate()` target are
451
- * kept: when another user signs in, call `close()` and then `connect()` instead.
450
+ * backoff. Also restarts a `closed` client: one that `connect()` had started stays connected
451
+ * again until `close()`, even with no hook holding it. The send queue and a `migrate()` target
452
+ * are kept: when another user signs in, call `close()` and then `connect()` instead.
452
453
  */
453
454
  reconnect(): void;
454
455
  /**
@@ -856,7 +857,7 @@ interface WebSocketRequestsOptions<Req, In, Out> {
856
857
  cancel?: (id: number) => Out;
857
858
  /**
858
859
  * Default time to wait for a reply, in ms. For a stream, the time to wait for each reply,
859
- * including the first. `Infinity` waits forever.
860
+ * including the first. `Infinity`, or anything over about 24.8 days, waits forever.
860
861
  * @default 10000
861
862
  */
862
863
  timeout?: number;
package/dist/core.d.ts CHANGED
@@ -447,8 +447,9 @@ interface WebSocketClient<In = unknown, Out = unknown> {
447
447
  close(code?: number, reason?: string): void;
448
448
  /**
449
449
  * Drop the current socket (if any) and connect again immediately, resetting the
450
- * backoff. Also restarts a `closed` client. The send queue and a `migrate()` target are
451
- * kept: when another user signs in, call `close()` and then `connect()` instead.
450
+ * backoff. Also restarts a `closed` client: one that `connect()` had started stays connected
451
+ * again until `close()`, even with no hook holding it. The send queue and a `migrate()` target
452
+ * are kept: when another user signs in, call `close()` and then `connect()` instead.
452
453
  */
453
454
  reconnect(): void;
454
455
  /**
@@ -856,7 +857,7 @@ interface WebSocketRequestsOptions<Req, In, Out> {
856
857
  cancel?: (id: number) => Out;
857
858
  /**
858
859
  * Default time to wait for a reply, in ms. For a stream, the time to wait for each reply,
859
- * including the first. `Infinity` waits forever.
860
+ * including the first. `Infinity`, or anything over about 24.8 days, waits forever.
860
861
  * @default 10000
861
862
  */
862
863
  timeout?: number;
package/dist/core.js CHANGED
@@ -34,7 +34,7 @@ const RECONNECT_DEFAULTS = {
34
34
  minUptime: 5e3
35
35
  };
36
36
  const QUEUE_LIMIT = 100;
37
- const MAX_TIMEOUT = 2 ** 31 - 1;
37
+ const MAX_TIMEOUT$2 = 2 ** 31 - 1;
38
38
  /**
39
39
  * The default `reconnect.shouldReconnect`: retry every close except `1002` (protocol error),
40
40
  * `1003` (unsupported data) and `1008` (policy violation, often a rejected login), which
@@ -113,8 +113,11 @@ function isThenable(value) {
113
113
  const ON_TEARDOWN = Symbol.for("react-websocket.onTeardown");
114
114
  /** @internal Method key on a socket that sends `volatile` messages as datagrams (WebTransport). */
115
115
  const DATAGRAM = Symbol.for("react-websocket.datagram");
116
- /** @internal Method key for what `react-websocket/devtools` shows that the snapshot doesn't. */
117
- const INSPECT = Symbol.for("react-websocket.inspect");
116
+ /**
117
+ * @internal Method key for what `react-websocket/devtools` shows that the snapshot doesn't. Requests
118
+ * read its queue length too, to tell a dropped message from a queued one.
119
+ */
120
+ const INSPECT$1 = Symbol.for("react-websocket.inspect");
118
121
  function createClient(url, options = {}) {
119
122
  const onTeardown = options[ON_TEARDOWN];
120
123
  const log = options.logger ?? (() => {});
@@ -144,6 +147,7 @@ function createClient(url, options = {}) {
144
147
  let wanted = false;
145
148
  let refs = 0;
146
149
  let pinned = false;
150
+ let unpinned = false;
147
151
  let unheldStop = false;
148
152
  let pending = [];
149
153
  let ready = null;
@@ -386,7 +390,7 @@ function createClient(url, options = {}) {
386
390
  const attempt = ++failures;
387
391
  const asked = (retry.retryAfter ?? retryAfter)(info);
388
392
  const named = asked >= 0;
389
- const delay = Math.min(MAX_TIMEOUT, named ? asked + backoff(attempt, false) : backoff(attempt, info.code === 1013));
393
+ const delay = Math.min(MAX_TIMEOUT$2, named ? asked + backoff(attempt, false) : backoff(attempt, info.code === 1013));
390
394
  serverWait = named || info.code === 1013;
391
395
  set({
392
396
  status: "reconnecting",
@@ -411,12 +415,13 @@ function createClient(url, options = {}) {
411
415
  if (!wanted) return;
412
416
  if (to !== void 0) moved = to;
413
417
  if (snapshot.status === "open") open(true);
414
- }, Math.min(MAX_TIMEOUT, Math.random() * (within ?? 0)));
418
+ }, Math.min(MAX_TIMEOUT$2, Math.random() * (within ?? 0)));
415
419
  }
416
420
  function fail(reason) {
417
421
  wanted = false;
418
422
  opened = false;
419
423
  unheldStop = refs === 0;
424
+ clearTimeout(teardownTimer);
420
425
  unbindWindow();
421
426
  stopMigrating();
422
427
  pending = [];
@@ -531,6 +536,7 @@ function createClient(url, options = {}) {
531
536
  function begin() {
532
537
  wanted = true;
533
538
  unheldStop = false;
539
+ unpinned = false;
534
540
  if (snapshot.status === "idle" || snapshot.status === "closed") {
535
541
  opened = false;
536
542
  if (ready?.settled) ready = null;
@@ -569,9 +575,11 @@ function createClient(url, options = {}) {
569
575
  }
570
576
  function close(code = 1e3, reason) {
571
577
  stop(code, reason);
578
+ unpinned ||= pinned;
572
579
  pinned = false;
573
580
  opened = false;
574
581
  unheldStop = refs === 0;
582
+ clearTimeout(teardownTimer);
575
583
  set({
576
584
  status: "closed",
577
585
  attempt: 0,
@@ -581,6 +589,7 @@ function createClient(url, options = {}) {
581
589
  }
582
590
  function reconnect() {
583
591
  if (!getImpl()) return;
592
+ if (unpinned) pinned = true;
584
593
  clearTimeout(retryTimer);
585
594
  retryTimer = void 0;
586
595
  stopSocketTimers();
@@ -662,7 +671,7 @@ function createClient(url, options = {}) {
662
671
  reconnect,
663
672
  migrate,
664
673
  acquire,
665
- [INSPECT]: () => ({ queued: pending.length })
674
+ [INSPECT$1]: () => ({ queued: pending.length })
666
675
  };
667
676
  }
668
677
  /**
@@ -736,8 +745,6 @@ function createWebSocketTopics(client, options) {
736
745
  if (options.unsubscribe) client.send(options.unsubscribe(topic));
737
746
  }
738
747
  const off = client.on("open", () => {
739
- sentOn = client.socket;
740
- sent = /* @__PURE__ */ new Set();
741
748
  for (const topic of counts.keys()) subscribe(topic);
742
749
  });
743
750
  return {
@@ -920,6 +927,7 @@ function createWebSocketLatency(client, options) {
920
927
  stop();
921
928
  inFlight.clear();
922
929
  samples = [];
930
+ if (client.getSnapshot().status !== "open") return;
923
931
  ping();
924
932
  timer = setInterval(ping, interval);
925
933
  }
@@ -1002,6 +1010,7 @@ const VOLATILE$1 = { volatile: true };
1002
1010
  */
1003
1011
  function createWebSocketPresence(client, options) {
1004
1012
  const timeout = options.timeout ?? 3e4;
1013
+ const refresh = options.refresh ?? timeout / 3;
1005
1014
  const interval = 1e3 / (options.maxRate ?? 20);
1006
1015
  const peers = /* @__PURE__ */ new Map();
1007
1016
  const listeners = /* @__PURE__ */ new Set();
@@ -1011,16 +1020,21 @@ function createWebSocketPresence(client, options) {
1011
1020
  let sendTimer;
1012
1021
  let refreshTimer;
1013
1022
  let expiryTimer;
1023
+ let disposed = false;
1014
1024
  function changed() {
1015
1025
  snapshot = [...peers.values()];
1016
1026
  for (const listener of [...listeners]) listener();
1017
1027
  }
1018
- function sendNow() {
1028
+ function stopSending() {
1019
1029
  clearTimeout(sendTimer);
1020
- sendTimer = void 0;
1030
+ clearTimeout(refreshTimer);
1031
+ sendTimer = refreshTimer = void 0;
1032
+ }
1033
+ function sendNow() {
1034
+ stopSending();
1021
1035
  if (!own) return;
1022
1036
  lastSent = Date.now();
1023
- client.send(options.send(own.state), VOLATILE$1);
1037
+ if (client.send(options.send(own.state), VOLATILE$1)) refreshTimer = setTimeout(sendNow, refresh);
1024
1038
  }
1025
1039
  function expire() {
1026
1040
  expiryTimer = void 0;
@@ -1035,26 +1049,36 @@ function createWebSocketPresence(client, options) {
1035
1049
  if (next < Infinity) expiryTimer = setTimeout(expire, next - now);
1036
1050
  if (removed) changed();
1037
1051
  }
1038
- const offs = [client.on("open", sendNow), client.on("message", (message) => {
1039
- const update = options.receive(message);
1040
- if (!update) return;
1041
- if (update.state === null) {
1042
- if (!peers.delete(update.peer)) return;
1043
- } else {
1044
- peers.set(update.peer, {
1045
- peer: update.peer,
1046
- state: update.state,
1047
- updatedAt: Date.now()
1048
- });
1049
- expiryTimer ??= setTimeout(expire, timeout);
1050
- }
1051
- changed();
1052
- })];
1052
+ const offs = [
1053
+ client.on("open", sendNow),
1054
+ client.on("message", (message) => {
1055
+ const update = options.receive(message);
1056
+ if (!update) return;
1057
+ if (update.state === null) {
1058
+ if (!peers.delete(update.peer)) return;
1059
+ } else {
1060
+ peers.set(update.peer, {
1061
+ peer: update.peer,
1062
+ state: update.state,
1063
+ updatedAt: Date.now()
1064
+ });
1065
+ expiryTimer ??= setTimeout(expire, timeout);
1066
+ }
1067
+ changed();
1068
+ }),
1069
+ client.subscribe(() => {
1070
+ if (client.getSnapshot().status !== "closed" || !peers.size) return;
1071
+ peers.clear();
1072
+ clearTimeout(expiryTimer);
1073
+ expiryTimer = void 0;
1074
+ changed();
1075
+ })
1076
+ ];
1053
1077
  return {
1054
1078
  client,
1055
1079
  set(state) {
1080
+ if (disposed) return;
1056
1081
  own = { state };
1057
- refreshTimer ??= setInterval(sendNow, options.refresh ?? timeout / 3);
1058
1082
  if (sendTimer !== void 0) return;
1059
1083
  const wait = lastSent + interval - Date.now();
1060
1084
  if (wait <= 0) sendNow();
@@ -1062,10 +1086,7 @@ function createWebSocketPresence(client, options) {
1062
1086
  },
1063
1087
  leave() {
1064
1088
  own = void 0;
1065
- clearTimeout(sendTimer);
1066
- sendTimer = void 0;
1067
- clearInterval(refreshTimer);
1068
- refreshTimer = void 0;
1089
+ stopSending();
1069
1090
  if (options.leave) client.send(options.leave(), VOLATILE$1);
1070
1091
  },
1071
1092
  getSnapshot: () => snapshot,
@@ -1076,9 +1097,8 @@ function createWebSocketPresence(client, options) {
1076
1097
  };
1077
1098
  },
1078
1099
  dispose() {
1079
- own = void 0;
1080
- clearTimeout(sendTimer);
1081
- clearInterval(refreshTimer);
1100
+ disposed = true;
1101
+ stopSending();
1082
1102
  clearTimeout(expiryTimer);
1083
1103
  for (const off of offs) off();
1084
1104
  }
@@ -1087,6 +1107,11 @@ function createWebSocketPresence(client, options) {
1087
1107
  //#endregion
1088
1108
  //#region src/requests.ts
1089
1109
  const lastIds = /* @__PURE__ */ new WeakMap();
1110
+ /** @internal Method key on the client for what the devtools show, such as its queue length. */
1111
+ const INSPECT = Symbol.for("react-websocket.inspect");
1112
+ /** How many messages `client` holds in its send queue, if it tells. */
1113
+ const queued = (client) => client[INSPECT]?.().queued;
1114
+ const MAX_TIMEOUT$1 = 2 ** 31 - 1;
1090
1115
  const noop = () => {};
1091
1116
  /**
1092
1117
  * Send requests and await their replies, matched by an id the library generates.
@@ -1108,6 +1133,7 @@ const noop = () => {};
1108
1133
  */
1109
1134
  function createWebSocketRequests(client, options) {
1110
1135
  const waiting = /* @__PURE__ */ new Map();
1136
+ let disposed = false;
1111
1137
  function endWhere(test, reason, cancel) {
1112
1138
  for (const entry of [...waiting.values()]) if (test(entry)) entry.end(true, reason(), cancel);
1113
1139
  }
@@ -1140,6 +1166,10 @@ function createWebSocketRequests(client, options) {
1140
1166
  done(true, signal.reason);
1141
1167
  return noop;
1142
1168
  }
1169
+ if (disposed) {
1170
+ done(true, /* @__PURE__ */ new Error("Requests were disposed"));
1171
+ return noop;
1172
+ }
1143
1173
  if (client.getSnapshot().status === "closed") {
1144
1174
  done(true, /* @__PURE__ */ new Error("WebSocket is closed: request not sent"));
1145
1175
  return noop;
@@ -1153,7 +1183,7 @@ function createWebSocketRequests(client, options) {
1153
1183
  const onAbort = () => entry.end(true, signal.reason, true);
1154
1184
  function arm() {
1155
1185
  clearTimeout(timer);
1156
- if (timeout > 0 && timeout < Infinity) timer = setTimeout(() => entry.end(true, new DOMException(`Request ${id} timed out after ${timeout}ms`, "TimeoutError"), true), timeout);
1186
+ if (timeout > 0 && timeout <= MAX_TIMEOUT$1) timer = setTimeout(() => entry.end(true, new DOMException(`Request ${id} timed out after ${timeout}ms`, "TimeoutError"), true), timeout);
1157
1187
  }
1158
1188
  const entry = {
1159
1189
  socket: null,
@@ -1180,7 +1210,8 @@ function createWebSocketRequests(client, options) {
1180
1210
  waiting.set(key, entry);
1181
1211
  signal?.addEventListener("abort", onAbort, { once: true });
1182
1212
  arm();
1183
- if (client.getSnapshot().status === "idle") entry.end(true, /* @__PURE__ */ new Error("WebSocket is idle: request not sent"));
1213
+ const { status } = client.getSnapshot();
1214
+ if (status === "idle" || status === "closed") entry.end(true, /* @__PURE__ */ new Error(`WebSocket is ${status}: request not sent`));
1184
1215
  else try {
1185
1216
  if (client.send(options.send(message, id), {
1186
1217
  ...requestOptions,
@@ -1190,7 +1221,7 @@ function createWebSocketRequests(client, options) {
1190
1221
  }
1191
1222
  })) entry.socket = client.socket;
1192
1223
  else if (client.socket?.readyState === 1) entry.end(true, /* @__PURE__ */ new Error("WebSocket send buffer is full: request dropped"));
1193
- else if (requestOptions.volatile) entry.end(true, /* @__PURE__ */ new Error("WebSocket is not open: request dropped"));
1224
+ else if (requestOptions.volatile || queued(client) === 0) entry.end(true, /* @__PURE__ */ new Error("WebSocket is not open: request dropped"));
1194
1225
  } catch (error) {
1195
1226
  entry.end(true, error);
1196
1227
  }
@@ -1244,6 +1275,7 @@ function createWebSocketRequests(client, options) {
1244
1275
  },
1245
1276
  pending: () => waiting.size,
1246
1277
  dispose() {
1278
+ disposed = true;
1247
1279
  offs.forEach((off) => off());
1248
1280
  endWhere(() => true, () => /* @__PURE__ */ new Error("Requests were disposed"), true);
1249
1281
  }
@@ -1252,6 +1284,7 @@ function createWebSocketRequests(client, options) {
1252
1284
  //#endregion
1253
1285
  //#region src/responder.ts
1254
1286
  const abortError = (message) => new DOMException(message, "AbortError");
1287
+ const MAX_TIMEOUT = 2 ** 31 - 1;
1255
1288
  /**
1256
1289
  * Answer requests the server sends: run a handler for tools that only exist in the browser
1257
1290
  * (selection, clipboard, geolocation), or let a person answer, e.g. to approve an agent's action.
@@ -1310,6 +1343,7 @@ function createWebSocketResponder(client, options) {
1310
1343
  reply(id, () => options.error(id, error));
1311
1344
  return;
1312
1345
  }
1346
+ const socket = client.socket;
1313
1347
  const controller = new AbortController();
1314
1348
  let timer;
1315
1349
  let done = false;
@@ -1321,7 +1355,7 @@ function createWebSocketResponder(client, options) {
1321
1355
  clearTimeout(timer);
1322
1356
  if (waiting.includes(request)) setWaiting(waiting.filter((entry) => entry !== request));
1323
1357
  if (reason !== void 0) controller.abort(reason);
1324
- return build ? reply(id, build) : false;
1358
+ return build && socket === client.socket ? reply(id, build) : false;
1325
1359
  }
1326
1360
  const answeredElsewhere = () => running ? abortError(`Request ${id} was answered elsewhere`) : void 0;
1327
1361
  const request = {
@@ -1336,14 +1370,14 @@ function createWebSocketResponder(client, options) {
1336
1370
  settle(() => options.error(id, error), error);
1337
1371
  };
1338
1372
  entries.set(key, {
1339
- socket: client.socket,
1373
+ socket,
1340
1374
  drop: (reason) => {
1341
1375
  settle(null, reason);
1342
1376
  },
1343
1377
  fail
1344
1378
  });
1345
1379
  const timeout = incoming.timeout ?? options.timeout ?? Infinity;
1346
- if (timeout > 0 && timeout < Infinity) timer = setTimeout(() => fail(new DOMException(`Request ${id} was not answered within ${timeout}ms`, "TimeoutError")), timeout);
1380
+ if (timeout > 0 && timeout <= MAX_TIMEOUT) timer = setTimeout(() => fail(new DOMException(`Request ${id} was not answered within ${timeout}ms`, "TimeoutError")), timeout);
1347
1381
  const { handler } = registration;
1348
1382
  if (!handler) {
1349
1383
  setWaiting([...waiting, request]);
@@ -1358,7 +1392,10 @@ function createWebSocketResponder(client, options) {
1358
1392
  request.reject(error);
1359
1393
  });
1360
1394
  }
1361
- const offs = [client.on("message", (message) => {
1395
+ const gone = /* @__PURE__ */ new WeakSet();
1396
+ let current = client.socket;
1397
+ const offs = [client.on("message", (message, event) => {
1398
+ if (gone.has(event.target)) return;
1362
1399
  const incoming = options.request(message);
1363
1400
  if (incoming != null) {
1364
1401
  receive(incoming);
@@ -1367,6 +1404,8 @@ function createWebSocketResponder(client, options) {
1367
1404
  const id = options.cancel?.(message);
1368
1405
  if (id != null) entries.get(String(id))?.drop(abortError(`Request ${id} was cancelled`));
1369
1406
  }), client.subscribe(() => {
1407
+ if (current && current !== client.socket) gone.add(current);
1408
+ current = client.socket;
1370
1409
  for (const entry of [...entries.values()]) if (entry.socket !== client.socket) entry.drop(abortError("WebSocket connection was lost before the request was answered"));
1371
1410
  })];
1372
1411
  return {
@@ -1503,8 +1542,8 @@ function createWebSocketRuns(client, options) {
1503
1542
  function follow(runId, policy, value = options.initial) {
1504
1543
  policies.set(runId, policy);
1505
1544
  remember(runId, policy);
1506
- set(runId, { value });
1507
1545
  releases.set(runId, feeds.acquire(runId));
1546
+ set(runId, { value });
1508
1547
  }
1509
1548
  function cancel(runId) {
1510
1549
  const message = options.cancel;
@@ -1552,7 +1591,7 @@ function createWebSocketRuns(client, options) {
1552
1591
  const previous = status;
1553
1592
  status = client.getSnapshot().status;
1554
1593
  if (previous !== "open" || status === "open") return;
1555
- for (const [runId, policy] of policies) if (policy === "cancel") abort(runId);
1594
+ for (const [runId, policy] of [...policies]) if (policy === "cancel") abort(runId);
1556
1595
  }),
1557
1596
  feeds.dispose
1558
1597
  ];