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