react-websocket 4.22.0 → 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 (47) hide show
  1. package/README.md +1 -1
  2. package/dist/ag-ui.cjs +7 -7
  3. package/dist/ag-ui.cjs.map +1 -1
  4. package/dist/ag-ui.d.cts +3 -2
  5. package/dist/ag-ui.js +7 -7
  6. package/dist/ag-ui.js.map +1 -1
  7. package/dist/chaos.cjs +59 -11
  8. package/dist/chaos.cjs.map +1 -1
  9. package/dist/chaos.d.cts +1 -0
  10. package/dist/chaos.d.ts +1 -0
  11. package/dist/chaos.js +59 -11
  12. package/dist/chaos.js.map +1 -1
  13. package/dist/core.cjs +82 -43
  14. package/dist/core.cjs.map +1 -1
  15. package/dist/core.d.cts +4 -3
  16. package/dist/core.d.ts +4 -3
  17. package/dist/core.js +82 -43
  18. package/dist/core.js.map +1 -1
  19. package/dist/index.d.cts +4 -3
  20. package/dist/index.d.ts +3 -2
  21. package/dist/outbox.cjs +14 -8
  22. package/dist/outbox.cjs.map +1 -1
  23. package/dist/outbox.d.cts +1 -1
  24. package/dist/outbox.js +14 -8
  25. package/dist/outbox.js.map +1 -1
  26. package/dist/replay.cjs +12 -7
  27. package/dist/replay.cjs.map +1 -1
  28. package/dist/replay.d.cts +8 -2
  29. package/dist/replay.d.ts +8 -2
  30. package/dist/replay.js +12 -7
  31. package/dist/replay.js.map +1 -1
  32. package/dist/tabs.cjs +11 -14
  33. package/dist/tabs.cjs.map +1 -1
  34. package/dist/tabs.js +11 -14
  35. package/dist/tabs.js.map +1 -1
  36. package/dist/timeline.cjs +3 -1
  37. package/dist/timeline.cjs.map +1 -1
  38. package/dist/timeline.d.cts +3 -3
  39. package/dist/timeline.d.ts +2 -2
  40. package/dist/timeline.js +3 -1
  41. package/dist/timeline.js.map +1 -1
  42. package/dist/{types-paLT8yQF.d.cts → types-Bb3sBG8L.d.cts} +4 -3
  43. package/dist/webtransport.cjs +12 -10
  44. package/dist/webtransport.cjs.map +1 -1
  45. package/dist/webtransport.js +12 -10
  46. package/dist/webtransport.js.map +1 -1
  47. package/package.json +9 -9
package/dist/index.d.cts CHANGED
@@ -449,8 +449,9 @@ interface WebSocketClient<In = unknown, Out = unknown> {
449
449
  close(code?: number, reason?: string): void;
450
450
  /**
451
451
  * Drop the current socket (if any) and connect again immediately, resetting the
452
- * backoff. Also restarts a `closed` client. The send queue and a `migrate()` target are
453
- * kept: when another user signs in, call `close()` and then `connect()` instead.
452
+ * backoff. Also restarts a `closed` client: one that `connect()` had started stays connected
453
+ * again until `close()`, even with no hook holding it. The send queue and a `migrate()` target
454
+ * are kept: when another user signs in, call `close()` and then `connect()` instead.
454
455
  */
455
456
  reconnect(): void;
456
457
  /**
@@ -858,7 +859,7 @@ interface WebSocketRequestsOptions<Req, In, Out> {
858
859
  cancel?: (id: number) => Out;
859
860
  /**
860
861
  * Default time to wait for a reply, in ms. For a stream, the time to wait for each reply,
861
- * including the first. `Infinity` waits forever.
862
+ * including the first. `Infinity`, or anything over about 24.8 days, waits forever.
862
863
  * @default 10000
863
864
  */
864
865
  timeout?: number;
package/dist/index.d.ts CHANGED
@@ -544,8 +544,9 @@ interface WebSocketClient$1<In = unknown, Out = unknown> {
544
544
  close(code?: number, reason?: string): void;
545
545
  /**
546
546
  * Drop the current socket (if any) and connect again immediately, resetting the
547
- * backoff. Also restarts a `closed` client. The send queue and a `migrate()` target are
548
- * kept: when another user signs in, call `close()` and then `connect()` instead.
547
+ * backoff. Also restarts a `closed` client: one that `connect()` had started stays connected
548
+ * again until `close()`, even with no hook holding it. The send queue and a `migrate()` target
549
+ * are kept: when another user signs in, call `close()` and then `connect()` instead.
549
550
  */
550
551
  reconnect(): void;
551
552
  /**
package/dist/outbox.cjs CHANGED
@@ -80,9 +80,10 @@ function createWebSocketOutbox(client, options) {
80
80
  const removed = /* @__PURE__ */ new Set();
81
81
  let clearedBeforeLoad = false;
82
82
  let addedSinceClear;
83
- const channel = typeof window !== "undefined" && typeof BroadcastChannel === "function" ? new BroadcastChannel(`react-websocket-outbox:${options.name}`) : void 0;
83
+ let channel = typeof window !== "undefined" && typeof BroadcastChannel === "function" ? new BroadcastChannel(`react-websocket-outbox:${options.name}`) : void 0;
84
84
  let disposed = false;
85
85
  let release;
86
+ let sentOn = null;
86
87
  let lastCreated = 0;
87
88
  function changed() {
88
89
  snapshot = [...entries.values()];
@@ -115,11 +116,16 @@ function createWebSocketOutbox(client, options) {
115
116
  return storage.delete(id);
116
117
  }
117
118
  function flush() {
118
- if (!loaded || disposed || client.socket?.readyState !== 1) return;
119
+ const socket = client.socket;
120
+ if (!loaded || disposed || socket?.readyState !== 1) return;
121
+ if (socket !== sentOn) {
122
+ unsend();
123
+ sentOn = socket;
124
+ }
119
125
  const now = Date.now();
120
126
  let sent = false;
121
127
  for (const entry of [...entries.values()]) {
122
- if (entry.sent) continue;
128
+ if (entry.sent || entries.get(entry.id) !== entry) continue;
123
129
  if (now - entry.createdAt > maxAge) {
124
130
  forget(entry.id).catch(noop);
125
131
  options.onExpire?.(entry);
@@ -169,11 +175,11 @@ function createWebSocketOutbox(client, options) {
169
175
  } else if (data?.id) drop(data.id);
170
176
  };
171
177
  const offs = [
172
- () => channel?.close(),
173
- client.on("open", () => {
174
- unsend();
175
- flush();
176
- }),
178
+ () => {
179
+ channel?.close();
180
+ channel = void 0;
181
+ },
182
+ client.on("open", flush),
177
183
  client.subscribe(() => {
178
184
  if (client.getSnapshot().status !== "open") unsend();
179
185
  }),
@@ -1 +1 @@
1
- {"version":3,"file":"outbox.cjs","names":[],"sources":["../src/outbox.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient } from './core';\n\n/** What an outbox stores for each message. */\nexport interface OutboxRecord<M = unknown> {\n /** The message's idempotency key, sent with it every time. */\n readonly id: string;\n /** The message, as passed to `add()`. */\n readonly message: M;\n /** When it was added, from `Date.now()`. Entries are sent in this order. */\n readonly createdAt: number;\n}\n\n/** A message waiting in the outbox. */\nexport interface OutboxEntry<M = unknown> extends OutboxRecord<M> {\n /** Sent on the current connection, and waiting for the server's ack. */\n readonly sent: boolean;\n}\n\n/**\n * Where an outbox keeps its messages. The default, {@link indexedDBStorage}, keeps them across\n * reloads. Pass your own to store them elsewhere, or {@link memoryStorage} in tests.\n */\nexport interface OutboxStorage {\n /** Every stored record, in any order. */\n load(): Promise<OutboxRecord[]>;\n put(record: OutboxRecord): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\n/** Options for {@link createWebSocketOutbox}. */\nexport interface WebSocketOutboxOptions<M, In, Out> {\n /**\n * Names the outbox's IndexedDB database, `react-websocket-outbox:<name>`. Give each outbox\n * its own. Unused with `storage`.\n */\n name: string;\n /**\n * Build the message to send for an entry, with its `id` as the idempotency key: the server\n * should do nothing for an id it has already handled, except acknowledge it again. Annotate\n * `message`: that's what `outbox.add()` accepts.\n */\n send: (message: M, id: string) => Out;\n /**\n * Recognize the server's acknowledgement and return the id it confirms, or `undefined` (or\n * `null`) for any other message. An entry stays until it's acknowledged, and is sent again\n * on every new connection until then. Without `ack`, an entry is removed once it has been\n * sent, so one sent just before the connection dropped can be lost.\n */\n ack?: (message: In) => string | null | undefined;\n /**\n * Drop an entry instead of sending it once it's older than this many ms. Checked when it\n * would be sent: on a new connection, and when stored entries are loaded.\n * @default Infinity\n */\n maxAge?: number;\n /** Called with each entry dropped by `maxAge`. */\n onExpire?: (entry: OutboxEntry<M>) => void;\n /**\n * Where to keep entries.\n * @default indexedDBStorage(name), or memoryStorage() where IndexedDB doesn't exist\n */\n storage?: OutboxStorage;\n}\n\n/** A persistent outbox on one client. Create with {@link createWebSocketOutbox}. */\nexport interface WebSocketOutbox<M> {\n /** The client the entries are sent on. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Resolves once the entries stored by an earlier page load are back in the outbox, and\n * rejects if they couldn't be loaded. Nothing is sent before.\n */\n readonly ready: Promise<void>;\n /**\n * Add a message and send it as soon as the socket is open. Resolves with its id once it's\n * stored, and rejects if storing failed; the entry is still sent from memory then, but won't\n * survive a reload. Without `ack`, one sent right away isn't stored, and resolves at once.\n * @param id - The idempotency key, e.g. an order number. A new random one by default.\n */\n add(message: M, id?: string): Promise<string>;\n /**\n * Remove an entry without sending it again, e.g. when the user cancels it. Other tabs using\n * the same `name` drop it too.\n */\n remove(id: string): Promise<void>;\n /**\n * Remove every entry at once, including ones other tabs stored, e.g. on logout. Other tabs\n * using the same `name` drop theirs too. Resolves once they're deleted from storage.\n */\n clear(): Promise<void>;\n /** The waiting entries, oldest first. A new array on every change. */\n getSnapshot(): readonly OutboxEntry<M>[];\n /** Get notified when the entries change. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop sending and listening, and release the connection. Stored entries stay stored. */\n dispose(): void;\n}\n\n/** Keep outbox entries in IndexedDB, in the database `react-websocket-outbox:<name>`. */\nexport function indexedDBStorage(name: string): OutboxStorage {\n let db: Promise<IDBDatabase> | undefined;\n // Settles once the transaction has committed, not when its request succeeds: a write isn't\n // durable before, and could still be lost if the page closed.\n const run = async <T>(\n mode: IDBTransactionMode,\n ask: (store: IDBObjectStore) => IDBRequest<T>\n ): Promise<T> => {\n db ??= new Promise((resolve, reject) => {\n const open = indexedDB.open(`react-websocket-outbox:${name}`, 1);\n open.onupgradeneeded = () => open.result.createObjectStore('entries', { keyPath: 'id' });\n open.onsuccess = () => {\n const connection = open.result;\n // Let another page delete or upgrade the database: the next write opens it again.\n connection.onversionchange = () => {\n connection.close();\n db = undefined;\n };\n resolve(connection);\n };\n open.onerror = () => reject(open.error);\n });\n const transaction = (await db).transaction('entries', mode);\n const req = ask(transaction.objectStore('entries'));\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve(req.result);\n transaction.onerror = transaction.onabort = () => reject(transaction.error ?? req.error);\n });\n };\n return {\n load: () => run('readonly', store => store.getAll()),\n put: record => run('readwrite', store => store.put(record)).then(noop),\n delete: id => run('readwrite', store => store.delete(id))\n };\n}\n\n/** Keep outbox entries in memory only: they don't survive a reload. For tests and servers. */\nexport function memoryStorage(): OutboxStorage {\n const records = new Map<string, OutboxRecord>();\n return {\n load: async () => [...records.values()],\n put: async record => void records.set(record.id, record),\n delete: async id => void records.delete(id)\n };\n}\n\nconst noop = () => {};\n\nfunction randomId() {\n // `randomUUID` needs a secure context; plain-HTTP pages fall back to a timestamp and random digits.\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\n/**\n * Keep messages until the server acknowledges them, across reconnects and page reloads, for\n * apps that must not lose a message on flaky Wi-Fi: point of sale, field service, warehouses.\n *\n * - `add(message)` stores the message (in IndexedDB by default) and sends it, tagged with an\n * idempotency key, as soon as the socket is open.\n * - It stays until the server acknowledges that key (`ack`). Every new connection sends the\n * unacknowledged entries again, in order, so the server must ignore a key it has already\n * handled and acknowledge it again.\n * - After a reload, the stored entries are loaded and sent before new ones.\n * - While entries are waiting, the outbox holds the client's connection open.\n *\n * Its entries don't go through the client's send queue, so `queue` options don't apply to them.\n *\n * @example\n * ```ts\n * import { createWebSocketOutbox } from 'react-websocket/outbox';\n *\n * export const orders = createWebSocketOutbox(pos, {\n * name: 'orders',\n * send: (order: Order, id) => ({ type: 'order', id, order }),\n * ack: message => (message.type === 'ack' ? message.id : undefined)\n * });\n *\n * await orders.add({ table: 4, items });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only; `M` comes from how `send`\n// annotates its parameter.\nexport function createWebSocketOutbox<M, In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketOutboxOptions<M, NoInfer<In>, NoInfer<Out>>\n): WebSocketOutbox<M> {\n const storage =\n options.storage ??\n (typeof indexedDB === 'undefined' ? memoryStorage() : indexedDBStorage(options.name));\n const maxAge = options.maxAge ?? Infinity;\n // Insertion order is `createdAt` order: entries loaded from storage are sorted in.\n let entries = new Map<string, OutboxEntry<M>>();\n let snapshot: readonly OutboxEntry<M>[] = [];\n const listeners = new Set<() => void>();\n let loaded = false;\n // Removed (or acknowledged) before the stored entries were loaded: don't restore them.\n const removed = new Set<string>();\n // Cleared, here or in another tab, before the stored entries were loaded: restore none.\n let clearedBeforeLoad = false;\n // Ids added since the latest `clear()` here began: the only stored entries it keeps.\n let addedSinceClear: Set<string> | undefined;\n // Other tabs using the same outbox, which loaded the same entries: tell them what's gone. Not\n // on a server, where an open channel would keep the process alive.\n const channel =\n typeof window !== 'undefined' && typeof BroadcastChannel === 'function'\n ? new BroadcastChannel(`react-websocket-outbox:${options.name}`)\n : undefined;\n let disposed = false;\n let release: (() => void) | undefined;\n // A strictly increasing `createdAt`, so entries added in the same ms keep their order.\n let lastCreated = 0;\n\n function changed() {\n snapshot = [...entries.values()];\n // Hold the connection while anything is waiting, so it gets delivered.\n if (snapshot.length && !release && !disposed) release = client.acquire();\n else if (!snapshot.length && release) {\n release();\n release = undefined;\n }\n for (const listener of [...listeners]) listener();\n }\n\n function drop(id: string) {\n if (!loaded) removed.add(id);\n if (entries.delete(id)) changed();\n }\n\n /**\n * Drop every entry held now, and its stored copy. Not by `createdAt`: that comes from the clock\n * of whichever page added it, which can be ahead of this one's.\n */\n function dropAll() {\n if (!loaded) clearedBeforeLoad = true;\n const held = [...entries.keys()];\n if (!held.length) return;\n entries = new Map();\n changed();\n for (const id of held) storage.delete(id).catch(noop);\n }\n\n // Also deletes a stored entry that isn't loaded yet, so it doesn't come back.\n function forget(id: string) {\n drop(id);\n channel?.postMessage({ id });\n return storage.delete(id);\n }\n\n function flush() {\n // The socket, not the status, which reads `open` while the server closes it. Not `volatile`\n // either, which can be a datagram that never arrives.\n if (!loaded || disposed || client.socket?.readyState !== 1) return;\n const now = Date.now();\n let sent = false;\n for (const entry of [...entries.values()]) {\n if (entry.sent) continue;\n if (now - entry.createdAt > maxAge) {\n forget(entry.id).catch(noop);\n options.onExpire?.(entry);\n } else if (client.send(options.send(entry.message, entry.id))) {\n if (!options.ack) forget(entry.id).catch(noop);\n else {\n entries.set(entry.id, { ...entry, sent: true });\n sent = true;\n }\n }\n }\n if (sent) changed();\n }\n\n const ready = storage\n .load()\n .then(records => {\n if (disposed) return;\n // Entries added from now on sort after the stored ones, whichever clock stored them.\n for (const record of records) lastCreated = Math.max(lastCreated, record.createdAt);\n // Entries added meanwhile are newer than the stored ones, unless one has the same id.\n entries = new Map(\n [\n ...records.filter(\n record => !clearedBeforeLoad && !entries.has(record.id) && !removed.has(record.id)\n ),\n ...entries.values()\n ]\n .sort((a, b) => a.createdAt - b.createdAt)\n .map(record => [record.id, { ...record, sent: false } as OutboxEntry<M>])\n );\n changed();\n })\n // Even without its stored entries, the outbox works from memory.\n .finally(() => {\n loaded = true;\n removed.clear();\n flush();\n });\n // Nobody may be awaiting `ready`; don't surface that as an unhandled rejection.\n ready.catch(noop);\n\n /** What was sent on the last connection may not have arrived: send it again on the next. */\n function unsend() {\n let changes = false;\n for (const entry of entries.values()) {\n if (entry.sent) {\n entries.set(entry.id, { ...entry, sent: false });\n changes = true;\n }\n }\n if (changes) changed();\n }\n\n if (channel) {\n channel.onmessage = ({ data }: MessageEvent<{ id?: string; before?: number } | null>) => {\n // Another tab cleared: drop everything held now, whenever it was added.\n if (data?.before) {\n lastCreated = Math.max(lastCreated, data.before);\n dropAll();\n } else if (data?.id) drop(data.id);\n };\n }\n\n const offs = [\n () => channel?.close(),\n // Also after `migrate()`, where the status stays `open`.\n client.on('open', () => {\n unsend();\n flush();\n }),\n client.subscribe(() => {\n if (client.getSnapshot().status !== 'open') unsend();\n }),\n client.on('message', message => {\n const id = options.ack?.(message);\n if (id != null) forget(String(id)).catch(noop);\n })\n ];\n\n return {\n client,\n ready,\n add(message, id = randomId()) {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const record: OutboxRecord<M> = { id, message, createdAt: lastCreated };\n // Re-adding an id moves it to the end, as a new message.\n entries.delete(id);\n entries.set(id, { ...record, sent: false });\n addedSinceClear?.add(id);\n changed();\n flush();\n // Sent, with no ack to wait for: there's nothing to keep. Storing it now would outlive its\n // delete, and send it again after a reload.\n if (!entries.has(id)) return Promise.resolve(id);\n return storage.put(record).then(() => id);\n },\n remove: forget,\n clear() {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const kept = (addedSinceClear = new Set<string>());\n // At once, like `remove()`: waiting for the stored entries would send them first.\n dropAll();\n channel?.postMessage({ before: lastCreated });\n // Everything stored, by other tabs and earlier page loads too, but not what's added from\n // now on.\n return storage\n .load()\n .then(records =>\n Promise.all(\n records.filter(record => !kept.has(record.id)).map(record => storage.delete(record.id))\n )\n )\n .then(() => {\n if (addedSinceClear === kept) addedSinceClear = undefined;\n });\n },\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n disposed = true;\n for (const off of offs) off();\n release?.();\n release = undefined;\n }\n };\n}\n"],"mappings":";;;AAoGA,SAAgB,iBAAiB,MAA6B;CAC5D,IAAI;CAGJ,MAAM,MAAM,OACV,MACA,QACe;EACf,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,OAAO,UAAU,KAAK,0BAA0B,QAAQ,CAAC;GAC/D,KAAK,wBAAwB,KAAK,OAAO,kBAAkB,WAAW,EAAE,SAAS,KAAK,CAAC;GACvF,KAAK,kBAAkB;IACrB,MAAM,aAAa,KAAK;IAExB,WAAW,wBAAwB;KACjC,WAAW,MAAM;KACjB,KAAK,KAAA;IACP;IACA,QAAQ,UAAU;GACpB;GACA,KAAK,gBAAgB,OAAO,KAAK,KAAK;EACxC,CAAC;EACD,MAAM,eAAe,MAAM,GAAA,CAAI,YAAY,WAAW,IAAI;EAC1D,MAAM,MAAM,IAAI,YAAY,YAAY,SAAS,CAAC;EAClD,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,YAAY,mBAAmB,QAAQ,IAAI,MAAM;GACjD,YAAY,UAAU,YAAY,gBAAgB,OAAO,YAAY,SAAS,IAAI,KAAK;EACzF,CAAC;CACH;CACA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sources":["../src/outbox.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient } from './core';\n\n/** What an outbox stores for each message. */\nexport interface OutboxRecord<M = unknown> {\n /** The message's idempotency key, sent with it every time. */\n readonly id: string;\n /** The message, as passed to `add()`. */\n readonly message: M;\n /** When it was added, from `Date.now()`. Entries are sent in this order. */\n readonly createdAt: number;\n}\n\n/** A message waiting in the outbox. */\nexport interface OutboxEntry<M = unknown> extends OutboxRecord<M> {\n /** Sent on the current connection, and waiting for the server's ack. */\n readonly sent: boolean;\n}\n\n/**\n * Where an outbox keeps its messages. The default, {@link indexedDBStorage}, keeps them across\n * reloads. Pass your own to store them elsewhere, or {@link memoryStorage} in tests.\n */\nexport interface OutboxStorage {\n /** Every stored record, in any order. */\n load(): Promise<OutboxRecord[]>;\n put(record: OutboxRecord): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\n/** Options for {@link createWebSocketOutbox}. */\nexport interface WebSocketOutboxOptions<M, In, Out> {\n /**\n * Names the outbox's IndexedDB database, `react-websocket-outbox:<name>`. Give each outbox\n * its own. Unused with `storage`.\n */\n name: string;\n /**\n * Build the message to send for an entry, with its `id` as the idempotency key: the server\n * should do nothing for an id it has already handled, except acknowledge it again. Annotate\n * `message`: that's what `outbox.add()` accepts.\n */\n send: (message: M, id: string) => Out;\n /**\n * Recognize the server's acknowledgement and return the id it confirms, or `undefined` (or\n * `null`) for any other message. An entry stays until it's acknowledged, and is sent again\n * on every new connection until then. Without `ack`, an entry is removed once it has been\n * sent, so one sent just before the connection dropped can be lost.\n */\n ack?: (message: In) => string | null | undefined;\n /**\n * Drop an entry instead of sending it once it's older than this many ms. Checked when it\n * would be sent: on a new connection, and when stored entries are loaded.\n * @default Infinity\n */\n maxAge?: number;\n /** Called with each entry dropped by `maxAge`. */\n onExpire?: (entry: OutboxEntry<M>) => void;\n /**\n * Where to keep entries.\n * @default indexedDBStorage(name), or memoryStorage() where IndexedDB doesn't exist\n */\n storage?: OutboxStorage;\n}\n\n/** A persistent outbox on one client. Create with {@link createWebSocketOutbox}. */\nexport interface WebSocketOutbox<M> {\n /** The client the entries are sent on. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Resolves once the entries stored by an earlier page load are back in the outbox, and\n * rejects if they couldn't be loaded. Nothing is sent before.\n */\n readonly ready: Promise<void>;\n /**\n * Add a message and send it as soon as the socket is open. Resolves with its id once it's\n * stored, and rejects if storing failed; the entry is still sent from memory then, but won't\n * survive a reload. Without `ack`, one sent right away isn't stored, and resolves at once.\n * @param id - The idempotency key, e.g. an order number. A new random one by default.\n */\n add(message: M, id?: string): Promise<string>;\n /**\n * Remove an entry without sending it again, e.g. when the user cancels it. Other tabs using\n * the same `name` drop it too.\n */\n remove(id: string): Promise<void>;\n /**\n * Remove every entry at once, including ones other tabs stored, e.g. on logout. Other tabs\n * using the same `name` drop theirs too. Resolves once they're deleted from storage.\n */\n clear(): Promise<void>;\n /** The waiting entries, oldest first. A new array on every change. */\n getSnapshot(): readonly OutboxEntry<M>[];\n /** Get notified when the entries change. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop sending and listening, and release the connection. Stored entries stay stored. */\n dispose(): void;\n}\n\n/** Keep outbox entries in IndexedDB, in the database `react-websocket-outbox:<name>`. */\nexport function indexedDBStorage(name: string): OutboxStorage {\n let db: Promise<IDBDatabase> | undefined;\n // Settles once the transaction has committed, not when its request succeeds: a write isn't\n // durable before, and could still be lost if the page closed.\n const run = async <T>(\n mode: IDBTransactionMode,\n ask: (store: IDBObjectStore) => IDBRequest<T>\n ): Promise<T> => {\n db ??= new Promise((resolve, reject) => {\n const open = indexedDB.open(`react-websocket-outbox:${name}`, 1);\n open.onupgradeneeded = () => open.result.createObjectStore('entries', { keyPath: 'id' });\n open.onsuccess = () => {\n const connection = open.result;\n // Let another page delete or upgrade the database: the next write opens it again.\n connection.onversionchange = () => {\n connection.close();\n db = undefined;\n };\n resolve(connection);\n };\n open.onerror = () => reject(open.error);\n });\n const transaction = (await db).transaction('entries', mode);\n const req = ask(transaction.objectStore('entries'));\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve(req.result);\n transaction.onerror = transaction.onabort = () => reject(transaction.error ?? req.error);\n });\n };\n return {\n load: () => run('readonly', store => store.getAll()),\n put: record => run('readwrite', store => store.put(record)).then(noop),\n delete: id => run('readwrite', store => store.delete(id))\n };\n}\n\n/** Keep outbox entries in memory only: they don't survive a reload. For tests and servers. */\nexport function memoryStorage(): OutboxStorage {\n const records = new Map<string, OutboxRecord>();\n return {\n load: async () => [...records.values()],\n put: async record => void records.set(record.id, record),\n delete: async id => void records.delete(id)\n };\n}\n\nconst noop = () => {};\n\nfunction randomId() {\n // `randomUUID` needs a secure context; plain-HTTP pages fall back to a timestamp and random digits.\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\n/**\n * Keep messages until the server acknowledges them, across reconnects and page reloads, for\n * apps that must not lose a message on flaky Wi-Fi: point of sale, field service, warehouses.\n *\n * - `add(message)` stores the message (in IndexedDB by default) and sends it, tagged with an\n * idempotency key, as soon as the socket is open.\n * - It stays until the server acknowledges that key (`ack`). Every new connection sends the\n * unacknowledged entries again, in order, so the server must ignore a key it has already\n * handled and acknowledge it again.\n * - After a reload, the stored entries are loaded and sent before new ones.\n * - While entries are waiting, the outbox holds the client's connection open.\n *\n * Its entries don't go through the client's send queue, so `queue` options don't apply to them.\n *\n * @example\n * ```ts\n * import { createWebSocketOutbox } from 'react-websocket/outbox';\n *\n * export const orders = createWebSocketOutbox(pos, {\n * name: 'orders',\n * send: (order: Order, id) => ({ type: 'order', id, order }),\n * ack: message => (message.type === 'ack' ? message.id : undefined)\n * });\n *\n * await orders.add({ table: 4, items });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only; `M` comes from how `send`\n// annotates its parameter.\nexport function createWebSocketOutbox<M, In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketOutboxOptions<M, NoInfer<In>, NoInfer<Out>>\n): WebSocketOutbox<M> {\n const storage =\n options.storage ??\n (typeof indexedDB === 'undefined' ? memoryStorage() : indexedDBStorage(options.name));\n const maxAge = options.maxAge ?? Infinity;\n // Insertion order is `createdAt` order: entries loaded from storage are sorted in.\n let entries = new Map<string, OutboxEntry<M>>();\n let snapshot: readonly OutboxEntry<M>[] = [];\n const listeners = new Set<() => void>();\n let loaded = false;\n // Removed (or acknowledged) before the stored entries were loaded: don't restore them.\n const removed = new Set<string>();\n // Cleared, here or in another tab, before the stored entries were loaded: restore none.\n let clearedBeforeLoad = false;\n // Ids added since the latest `clear()` here began: the only stored entries it keeps.\n let addedSinceClear: Set<string> | undefined;\n // Other tabs using the same outbox, which loaded the same entries: tell them what's gone. Not\n // on a server, where an open channel would keep the process alive.\n let channel =\n typeof window !== 'undefined' && typeof BroadcastChannel === 'function'\n ? new BroadcastChannel(`react-websocket-outbox:${options.name}`)\n : undefined;\n let disposed = false;\n let release: (() => void) | undefined;\n // The socket that entries marked `sent` went out on. On any other, they go out again.\n let sentOn: WebSocket | null = null;\n // A strictly increasing `createdAt`, so entries added in the same ms keep their order.\n let lastCreated = 0;\n\n function changed() {\n snapshot = [...entries.values()];\n // Hold the connection while anything is waiting, so it gets delivered.\n if (snapshot.length && !release && !disposed) release = client.acquire();\n else if (!snapshot.length && release) {\n release();\n release = undefined;\n }\n for (const listener of [...listeners]) listener();\n }\n\n function drop(id: string) {\n if (!loaded) removed.add(id);\n if (entries.delete(id)) changed();\n }\n\n /**\n * Drop every entry held now, and its stored copy. Not by `createdAt`: that comes from the clock\n * of whichever page added it, which can be ahead of this one's.\n */\n function dropAll() {\n if (!loaded) clearedBeforeLoad = true;\n const held = [...entries.keys()];\n if (!held.length) return;\n entries = new Map();\n changed();\n for (const id of held) storage.delete(id).catch(noop);\n }\n\n // Also deletes a stored entry that isn't loaded yet, so it doesn't come back.\n function forget(id: string) {\n drop(id);\n channel?.postMessage({ id });\n return storage.delete(id);\n }\n\n function flush() {\n const socket = client.socket;\n // The socket, not the status, which reads `open` while the server closes it. Not `volatile`\n // either, which can be a datagram that never arrives.\n if (!loaded || disposed || socket?.readyState !== 1) return;\n // A new connection, including after `migrate()`, where the status stays `open`.\n if (socket !== sentOn) {\n unsend();\n sentOn = socket;\n }\n const now = Date.now();\n let sent = false;\n for (const entry of [...entries.values()]) {\n // Sent, removed or replaced meanwhile, by `onExpire` or a listener.\n if (entry.sent || entries.get(entry.id) !== entry) continue;\n if (now - entry.createdAt > maxAge) {\n forget(entry.id).catch(noop);\n options.onExpire?.(entry);\n } else if (client.send(options.send(entry.message, entry.id))) {\n if (!options.ack) forget(entry.id).catch(noop);\n else {\n entries.set(entry.id, { ...entry, sent: true });\n sent = true;\n }\n }\n }\n if (sent) changed();\n }\n\n const ready = storage\n .load()\n .then(records => {\n if (disposed) return;\n // Entries added from now on sort after the stored ones, whichever clock stored them.\n for (const record of records) lastCreated = Math.max(lastCreated, record.createdAt);\n // Entries added meanwhile are newer than the stored ones, unless one has the same id.\n entries = new Map(\n [\n ...records.filter(\n record => !clearedBeforeLoad && !entries.has(record.id) && !removed.has(record.id)\n ),\n ...entries.values()\n ]\n .sort((a, b) => a.createdAt - b.createdAt)\n .map(record => [record.id, { ...record, sent: false } as OutboxEntry<M>])\n );\n changed();\n })\n // Even without its stored entries, the outbox works from memory.\n .finally(() => {\n loaded = true;\n removed.clear();\n flush();\n });\n // Nobody may be awaiting `ready`; don't surface that as an unhandled rejection.\n ready.catch(noop);\n\n /** What was sent on the last connection may not have arrived: send it again on the next. */\n function unsend() {\n let changes = false;\n for (const entry of entries.values()) {\n if (entry.sent) {\n entries.set(entry.id, { ...entry, sent: false });\n changes = true;\n }\n }\n if (changes) changed();\n }\n\n if (channel) {\n channel.onmessage = ({ data }: MessageEvent<{ id?: string; before?: number } | null>) => {\n // Another tab cleared: drop everything held now, whenever it was added.\n if (data?.before) {\n lastCreated = Math.max(lastCreated, data.before);\n dropAll();\n } else if (data?.id) drop(data.id);\n };\n }\n\n const offs = [\n () => {\n // A closed channel throws on `postMessage`, which `remove()` and `clear()` still call.\n channel?.close();\n channel = undefined;\n },\n client.on('open', flush),\n client.subscribe(() => {\n if (client.getSnapshot().status !== 'open') unsend();\n }),\n client.on('message', message => {\n const id = options.ack?.(message);\n if (id != null) forget(String(id)).catch(noop);\n })\n ];\n\n return {\n client,\n ready,\n add(message, id = randomId()) {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const record: OutboxRecord<M> = { id, message, createdAt: lastCreated };\n // Re-adding an id moves it to the end, as a new message.\n entries.delete(id);\n entries.set(id, { ...record, sent: false });\n addedSinceClear?.add(id);\n changed();\n flush();\n // Sent, with no ack to wait for: there's nothing to keep. Storing it now would outlive its\n // delete, and send it again after a reload.\n if (!entries.has(id)) return Promise.resolve(id);\n return storage.put(record).then(() => id);\n },\n remove: forget,\n clear() {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const kept = (addedSinceClear = new Set<string>());\n // At once, like `remove()`: waiting for the stored entries would send them first.\n dropAll();\n channel?.postMessage({ before: lastCreated });\n // Everything stored, by other tabs and earlier page loads too, but not what's added from\n // now on.\n return storage\n .load()\n .then(records =>\n Promise.all(\n records.filter(record => !kept.has(record.id)).map(record => storage.delete(record.id))\n )\n )\n .then(() => {\n if (addedSinceClear === kept) addedSinceClear = undefined;\n });\n },\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n disposed = true;\n for (const off of offs) off();\n release?.();\n release = undefined;\n }\n };\n}\n"],"mappings":";;;AAoGA,SAAgB,iBAAiB,MAA6B;CAC5D,IAAI;CAGJ,MAAM,MAAM,OACV,MACA,QACe;EACf,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,OAAO,UAAU,KAAK,0BAA0B,QAAQ,CAAC;GAC/D,KAAK,wBAAwB,KAAK,OAAO,kBAAkB,WAAW,EAAE,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D,MAAM,OAAQ,kCAAkB,IAAI,IAAY;GAEhD,QAAQ;GACR,SAAS,YAAY,EAAE,QAAQ,YAAY,CAAC;GAG5C,OAAO,QACJ,KAAK,CAAC,CACN,MAAK,YACJ,QAAQ,IACN,QAAQ,QAAO,WAAU,CAAC,KAAK,IAAI,OAAO,EAAE,CAAC,CAAC,CAAC,KAAI,WAAU,QAAQ,OAAO,OAAO,EAAE,CAAC,CACxF,CACF,CAAC,CACA,WAAW;IACV,IAAI,oBAAoB,MAAM,kBAAkB,KAAA;GAClD,CAAC;EACL;EACA,mBAAmB;EACnB,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,UAAU;GACR,WAAW;GACX,KAAK,MAAM,OAAO,MAAM,IAAI;GAC5B,UAAU;GACV,UAAU,KAAA;EACZ;CACF;AACF"}
package/dist/outbox.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as WebSocketClient } from "./types-paLT8yQF.cjs";
1
+ import { t as WebSocketClient } from "./types-Bb3sBG8L.cjs";
2
2
  //#region src/outbox.d.ts
3
3
  /** What an outbox stores for each message. */
4
4
  export interface OutboxRecord<M = unknown> {
package/dist/outbox.js CHANGED
@@ -79,9 +79,10 @@ function createWebSocketOutbox(client, options) {
79
79
  const removed = /* @__PURE__ */ new Set();
80
80
  let clearedBeforeLoad = false;
81
81
  let addedSinceClear;
82
- const channel = typeof window !== "undefined" && typeof BroadcastChannel === "function" ? new BroadcastChannel(`react-websocket-outbox:${options.name}`) : void 0;
82
+ let channel = typeof window !== "undefined" && typeof BroadcastChannel === "function" ? new BroadcastChannel(`react-websocket-outbox:${options.name}`) : void 0;
83
83
  let disposed = false;
84
84
  let release;
85
+ let sentOn = null;
85
86
  let lastCreated = 0;
86
87
  function changed() {
87
88
  snapshot = [...entries.values()];
@@ -114,11 +115,16 @@ function createWebSocketOutbox(client, options) {
114
115
  return storage.delete(id);
115
116
  }
116
117
  function flush() {
117
- if (!loaded || disposed || client.socket?.readyState !== 1) return;
118
+ const socket = client.socket;
119
+ if (!loaded || disposed || socket?.readyState !== 1) return;
120
+ if (socket !== sentOn) {
121
+ unsend();
122
+ sentOn = socket;
123
+ }
118
124
  const now = Date.now();
119
125
  let sent = false;
120
126
  for (const entry of [...entries.values()]) {
121
- if (entry.sent) continue;
127
+ if (entry.sent || entries.get(entry.id) !== entry) continue;
122
128
  if (now - entry.createdAt > maxAge) {
123
129
  forget(entry.id).catch(noop);
124
130
  options.onExpire?.(entry);
@@ -168,11 +174,11 @@ function createWebSocketOutbox(client, options) {
168
174
  } else if (data?.id) drop(data.id);
169
175
  };
170
176
  const offs = [
171
- () => channel?.close(),
172
- client.on("open", () => {
173
- unsend();
174
- flush();
175
- }),
177
+ () => {
178
+ channel?.close();
179
+ channel = void 0;
180
+ },
181
+ client.on("open", flush),
176
182
  client.subscribe(() => {
177
183
  if (client.getSnapshot().status !== "open") unsend();
178
184
  }),
@@ -1 +1 @@
1
- {"version":3,"file":"outbox.js","names":[],"sources":["../src/outbox.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient } from './core';\n\n/** What an outbox stores for each message. */\nexport interface OutboxRecord<M = unknown> {\n /** The message's idempotency key, sent with it every time. */\n readonly id: string;\n /** The message, as passed to `add()`. */\n readonly message: M;\n /** When it was added, from `Date.now()`. Entries are sent in this order. */\n readonly createdAt: number;\n}\n\n/** A message waiting in the outbox. */\nexport interface OutboxEntry<M = unknown> extends OutboxRecord<M> {\n /** Sent on the current connection, and waiting for the server's ack. */\n readonly sent: boolean;\n}\n\n/**\n * Where an outbox keeps its messages. The default, {@link indexedDBStorage}, keeps them across\n * reloads. Pass your own to store them elsewhere, or {@link memoryStorage} in tests.\n */\nexport interface OutboxStorage {\n /** Every stored record, in any order. */\n load(): Promise<OutboxRecord[]>;\n put(record: OutboxRecord): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\n/** Options for {@link createWebSocketOutbox}. */\nexport interface WebSocketOutboxOptions<M, In, Out> {\n /**\n * Names the outbox's IndexedDB database, `react-websocket-outbox:<name>`. Give each outbox\n * its own. Unused with `storage`.\n */\n name: string;\n /**\n * Build the message to send for an entry, with its `id` as the idempotency key: the server\n * should do nothing for an id it has already handled, except acknowledge it again. Annotate\n * `message`: that's what `outbox.add()` accepts.\n */\n send: (message: M, id: string) => Out;\n /**\n * Recognize the server's acknowledgement and return the id it confirms, or `undefined` (or\n * `null`) for any other message. An entry stays until it's acknowledged, and is sent again\n * on every new connection until then. Without `ack`, an entry is removed once it has been\n * sent, so one sent just before the connection dropped can be lost.\n */\n ack?: (message: In) => string | null | undefined;\n /**\n * Drop an entry instead of sending it once it's older than this many ms. Checked when it\n * would be sent: on a new connection, and when stored entries are loaded.\n * @default Infinity\n */\n maxAge?: number;\n /** Called with each entry dropped by `maxAge`. */\n onExpire?: (entry: OutboxEntry<M>) => void;\n /**\n * Where to keep entries.\n * @default indexedDBStorage(name), or memoryStorage() where IndexedDB doesn't exist\n */\n storage?: OutboxStorage;\n}\n\n/** A persistent outbox on one client. Create with {@link createWebSocketOutbox}. */\nexport interface WebSocketOutbox<M> {\n /** The client the entries are sent on. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Resolves once the entries stored by an earlier page load are back in the outbox, and\n * rejects if they couldn't be loaded. Nothing is sent before.\n */\n readonly ready: Promise<void>;\n /**\n * Add a message and send it as soon as the socket is open. Resolves with its id once it's\n * stored, and rejects if storing failed; the entry is still sent from memory then, but won't\n * survive a reload. Without `ack`, one sent right away isn't stored, and resolves at once.\n * @param id - The idempotency key, e.g. an order number. A new random one by default.\n */\n add(message: M, id?: string): Promise<string>;\n /**\n * Remove an entry without sending it again, e.g. when the user cancels it. Other tabs using\n * the same `name` drop it too.\n */\n remove(id: string): Promise<void>;\n /**\n * Remove every entry at once, including ones other tabs stored, e.g. on logout. Other tabs\n * using the same `name` drop theirs too. Resolves once they're deleted from storage.\n */\n clear(): Promise<void>;\n /** The waiting entries, oldest first. A new array on every change. */\n getSnapshot(): readonly OutboxEntry<M>[];\n /** Get notified when the entries change. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop sending and listening, and release the connection. Stored entries stay stored. */\n dispose(): void;\n}\n\n/** Keep outbox entries in IndexedDB, in the database `react-websocket-outbox:<name>`. */\nexport function indexedDBStorage(name: string): OutboxStorage {\n let db: Promise<IDBDatabase> | undefined;\n // Settles once the transaction has committed, not when its request succeeds: a write isn't\n // durable before, and could still be lost if the page closed.\n const run = async <T>(\n mode: IDBTransactionMode,\n ask: (store: IDBObjectStore) => IDBRequest<T>\n ): Promise<T> => {\n db ??= new Promise((resolve, reject) => {\n const open = indexedDB.open(`react-websocket-outbox:${name}`, 1);\n open.onupgradeneeded = () => open.result.createObjectStore('entries', { keyPath: 'id' });\n open.onsuccess = () => {\n const connection = open.result;\n // Let another page delete or upgrade the database: the next write opens it again.\n connection.onversionchange = () => {\n connection.close();\n db = undefined;\n };\n resolve(connection);\n };\n open.onerror = () => reject(open.error);\n });\n const transaction = (await db).transaction('entries', mode);\n const req = ask(transaction.objectStore('entries'));\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve(req.result);\n transaction.onerror = transaction.onabort = () => reject(transaction.error ?? req.error);\n });\n };\n return {\n load: () => run('readonly', store => store.getAll()),\n put: record => run('readwrite', store => store.put(record)).then(noop),\n delete: id => run('readwrite', store => store.delete(id))\n };\n}\n\n/** Keep outbox entries in memory only: they don't survive a reload. For tests and servers. */\nexport function memoryStorage(): OutboxStorage {\n const records = new Map<string, OutboxRecord>();\n return {\n load: async () => [...records.values()],\n put: async record => void records.set(record.id, record),\n delete: async id => void records.delete(id)\n };\n}\n\nconst noop = () => {};\n\nfunction randomId() {\n // `randomUUID` needs a secure context; plain-HTTP pages fall back to a timestamp and random digits.\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\n/**\n * Keep messages until the server acknowledges them, across reconnects and page reloads, for\n * apps that must not lose a message on flaky Wi-Fi: point of sale, field service, warehouses.\n *\n * - `add(message)` stores the message (in IndexedDB by default) and sends it, tagged with an\n * idempotency key, as soon as the socket is open.\n * - It stays until the server acknowledges that key (`ack`). Every new connection sends the\n * unacknowledged entries again, in order, so the server must ignore a key it has already\n * handled and acknowledge it again.\n * - After a reload, the stored entries are loaded and sent before new ones.\n * - While entries are waiting, the outbox holds the client's connection open.\n *\n * Its entries don't go through the client's send queue, so `queue` options don't apply to them.\n *\n * @example\n * ```ts\n * import { createWebSocketOutbox } from 'react-websocket/outbox';\n *\n * export const orders = createWebSocketOutbox(pos, {\n * name: 'orders',\n * send: (order: Order, id) => ({ type: 'order', id, order }),\n * ack: message => (message.type === 'ack' ? message.id : undefined)\n * });\n *\n * await orders.add({ table: 4, items });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only; `M` comes from how `send`\n// annotates its parameter.\nexport function createWebSocketOutbox<M, In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketOutboxOptions<M, NoInfer<In>, NoInfer<Out>>\n): WebSocketOutbox<M> {\n const storage =\n options.storage ??\n (typeof indexedDB === 'undefined' ? memoryStorage() : indexedDBStorage(options.name));\n const maxAge = options.maxAge ?? Infinity;\n // Insertion order is `createdAt` order: entries loaded from storage are sorted in.\n let entries = new Map<string, OutboxEntry<M>>();\n let snapshot: readonly OutboxEntry<M>[] = [];\n const listeners = new Set<() => void>();\n let loaded = false;\n // Removed (or acknowledged) before the stored entries were loaded: don't restore them.\n const removed = new Set<string>();\n // Cleared, here or in another tab, before the stored entries were loaded: restore none.\n let clearedBeforeLoad = false;\n // Ids added since the latest `clear()` here began: the only stored entries it keeps.\n let addedSinceClear: Set<string> | undefined;\n // Other tabs using the same outbox, which loaded the same entries: tell them what's gone. Not\n // on a server, where an open channel would keep the process alive.\n const channel =\n typeof window !== 'undefined' && typeof BroadcastChannel === 'function'\n ? new BroadcastChannel(`react-websocket-outbox:${options.name}`)\n : undefined;\n let disposed = false;\n let release: (() => void) | undefined;\n // A strictly increasing `createdAt`, so entries added in the same ms keep their order.\n let lastCreated = 0;\n\n function changed() {\n snapshot = [...entries.values()];\n // Hold the connection while anything is waiting, so it gets delivered.\n if (snapshot.length && !release && !disposed) release = client.acquire();\n else if (!snapshot.length && release) {\n release();\n release = undefined;\n }\n for (const listener of [...listeners]) listener();\n }\n\n function drop(id: string) {\n if (!loaded) removed.add(id);\n if (entries.delete(id)) changed();\n }\n\n /**\n * Drop every entry held now, and its stored copy. Not by `createdAt`: that comes from the clock\n * of whichever page added it, which can be ahead of this one's.\n */\n function dropAll() {\n if (!loaded) clearedBeforeLoad = true;\n const held = [...entries.keys()];\n if (!held.length) return;\n entries = new Map();\n changed();\n for (const id of held) storage.delete(id).catch(noop);\n }\n\n // Also deletes a stored entry that isn't loaded yet, so it doesn't come back.\n function forget(id: string) {\n drop(id);\n channel?.postMessage({ id });\n return storage.delete(id);\n }\n\n function flush() {\n // The socket, not the status, which reads `open` while the server closes it. Not `volatile`\n // either, which can be a datagram that never arrives.\n if (!loaded || disposed || client.socket?.readyState !== 1) return;\n const now = Date.now();\n let sent = false;\n for (const entry of [...entries.values()]) {\n if (entry.sent) continue;\n if (now - entry.createdAt > maxAge) {\n forget(entry.id).catch(noop);\n options.onExpire?.(entry);\n } else if (client.send(options.send(entry.message, entry.id))) {\n if (!options.ack) forget(entry.id).catch(noop);\n else {\n entries.set(entry.id, { ...entry, sent: true });\n sent = true;\n }\n }\n }\n if (sent) changed();\n }\n\n const ready = storage\n .load()\n .then(records => {\n if (disposed) return;\n // Entries added from now on sort after the stored ones, whichever clock stored them.\n for (const record of records) lastCreated = Math.max(lastCreated, record.createdAt);\n // Entries added meanwhile are newer than the stored ones, unless one has the same id.\n entries = new Map(\n [\n ...records.filter(\n record => !clearedBeforeLoad && !entries.has(record.id) && !removed.has(record.id)\n ),\n ...entries.values()\n ]\n .sort((a, b) => a.createdAt - b.createdAt)\n .map(record => [record.id, { ...record, sent: false } as OutboxEntry<M>])\n );\n changed();\n })\n // Even without its stored entries, the outbox works from memory.\n .finally(() => {\n loaded = true;\n removed.clear();\n flush();\n });\n // Nobody may be awaiting `ready`; don't surface that as an unhandled rejection.\n ready.catch(noop);\n\n /** What was sent on the last connection may not have arrived: send it again on the next. */\n function unsend() {\n let changes = false;\n for (const entry of entries.values()) {\n if (entry.sent) {\n entries.set(entry.id, { ...entry, sent: false });\n changes = true;\n }\n }\n if (changes) changed();\n }\n\n if (channel) {\n channel.onmessage = ({ data }: MessageEvent<{ id?: string; before?: number } | null>) => {\n // Another tab cleared: drop everything held now, whenever it was added.\n if (data?.before) {\n lastCreated = Math.max(lastCreated, data.before);\n dropAll();\n } else if (data?.id) drop(data.id);\n };\n }\n\n const offs = [\n () => channel?.close(),\n // Also after `migrate()`, where the status stays `open`.\n client.on('open', () => {\n unsend();\n flush();\n }),\n client.subscribe(() => {\n if (client.getSnapshot().status !== 'open') unsend();\n }),\n client.on('message', message => {\n const id = options.ack?.(message);\n if (id != null) forget(String(id)).catch(noop);\n })\n ];\n\n return {\n client,\n ready,\n add(message, id = randomId()) {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const record: OutboxRecord<M> = { id, message, createdAt: lastCreated };\n // Re-adding an id moves it to the end, as a new message.\n entries.delete(id);\n entries.set(id, { ...record, sent: false });\n addedSinceClear?.add(id);\n changed();\n flush();\n // Sent, with no ack to wait for: there's nothing to keep. Storing it now would outlive its\n // delete, and send it again after a reload.\n if (!entries.has(id)) return Promise.resolve(id);\n return storage.put(record).then(() => id);\n },\n remove: forget,\n clear() {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const kept = (addedSinceClear = new Set<string>());\n // At once, like `remove()`: waiting for the stored entries would send them first.\n dropAll();\n channel?.postMessage({ before: lastCreated });\n // Everything stored, by other tabs and earlier page loads too, but not what's added from\n // now on.\n return storage\n .load()\n .then(records =>\n Promise.all(\n records.filter(record => !kept.has(record.id)).map(record => storage.delete(record.id))\n )\n )\n .then(() => {\n if (addedSinceClear === kept) addedSinceClear = undefined;\n });\n },\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n disposed = true;\n for (const off of offs) off();\n release?.();\n release = undefined;\n }\n };\n}\n"],"mappings":";;AAoGA,SAAgB,iBAAiB,MAA6B;CAC5D,IAAI;CAGJ,MAAM,MAAM,OACV,MACA,QACe;EACf,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,OAAO,UAAU,KAAK,0BAA0B,QAAQ,CAAC;GAC/D,KAAK,wBAAwB,KAAK,OAAO,kBAAkB,WAAW,EAAE,SAAS,KAAK,CAAC;GACvF,KAAK,kBAAkB;IACrB,MAAM,aAAa,KAAK;IAExB,WAAW,wBAAwB;KACjC,WAAW,MAAM;KACjB,KAAK,KAAA;IACP;IACA,QAAQ,UAAU;GACpB;GACA,KAAK,gBAAgB,OAAO,KAAK,KAAK;EACxC,CAAC;EACD,MAAM,eAAe,MAAM,GAAA,CAAI,YAAY,WAAW,IAAI;EAC1D,MAAM,MAAM,IAAI,YAAY,YAAY,SAAS,CAAC;EAClD,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,YAAY,mBAAmB,QAAQ,IAAI,MAAM;GACjD,YAAY,UAAU,YAAY,gBAAgB,OAAO,YAAY,SAAS,IAAI,KAAK;EACzF,CAAC;CACH;CACA,OAAO;EACL,YAAY,IAAI,aAAY,UAAS,MAAM,OAAO,CAAC;EACnD,MAAK,WAAU,IAAI,cAAa,UAAS,MAAM,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI;EACrE,SAAQ,OAAM,IAAI,cAAa,UAAS,MAAM,OAAO,EAAE,CAAC;CAC1D;AACF;;AAGA,SAAgB,gBAA+B;CAC7C,MAAM,0BAAU,IAAI,IAA0B;CAC9C,OAAO;EACL,MAAM,YAAY,CAAC,GAAG,QAAQ,OAAO,CAAC;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AI,IAAI;IAAE,GAAG;IAAQ,MAAM;GAAM,CAAC;GAC1C,iBAAiB,IAAI,EAAE;GACvB,QAAQ;GACR,MAAM;GAGN,IAAI,CAAC,QAAQ,IAAI,EAAE,GAAG,OAAO,QAAQ,QAAQ,EAAE;GAC/C,OAAO,QAAQ,IAAI,MAAM,CAAC,CAAC,WAAW,EAAE;EAC1C;EACA,QAAQ;EACR,QAAQ;GACN,cAAc,KAAK,IAAI,KAAK,IAAI,GAAG,cAAc,CAAC;GAClD,MAAM,OAAQ,kCAAkB,IAAI,IAAY;GAEhD,QAAQ;GACR,SAAS,YAAY,EAAE,QAAQ,YAAY,CAAC;GAG5C,OAAO,QACJ,KAAK,CAAC,CACN,MAAK,YACJ,QAAQ,IACN,QAAQ,QAAO,WAAU,CAAC,KAAK,IAAI,OAAO,EAAE,CAAC,CAAC,CAAC,KAAI,WAAU,QAAQ,OAAO,OAAO,EAAE,CAAC,CACxF,CACF,CAAC,CACA,WAAW;IACV,IAAI,oBAAoB,MAAM,kBAAkB,KAAA;GAClD,CAAC;EACL;EACA,mBAAmB;EACnB,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,UAAU;GACR,WAAW;GACX,KAAK,MAAM,OAAO,MAAM,IAAI;GAC5B,UAAU;GACV,UAAU,KAAA;EACZ;CACF;AACF"}
1
+ {"version":3,"file":"outbox.js","names":[],"sources":["../src/outbox.ts"],"sourcesContent":["// Types only: the built entry has no imports, and its declarations point at `core`'s.\nimport type { WebSocketClient } from './core';\n\n/** What an outbox stores for each message. */\nexport interface OutboxRecord<M = unknown> {\n /** The message's idempotency key, sent with it every time. */\n readonly id: string;\n /** The message, as passed to `add()`. */\n readonly message: M;\n /** When it was added, from `Date.now()`. Entries are sent in this order. */\n readonly createdAt: number;\n}\n\n/** A message waiting in the outbox. */\nexport interface OutboxEntry<M = unknown> extends OutboxRecord<M> {\n /** Sent on the current connection, and waiting for the server's ack. */\n readonly sent: boolean;\n}\n\n/**\n * Where an outbox keeps its messages. The default, {@link indexedDBStorage}, keeps them across\n * reloads. Pass your own to store them elsewhere, or {@link memoryStorage} in tests.\n */\nexport interface OutboxStorage {\n /** Every stored record, in any order. */\n load(): Promise<OutboxRecord[]>;\n put(record: OutboxRecord): Promise<void>;\n delete(id: string): Promise<void>;\n}\n\n/** Options for {@link createWebSocketOutbox}. */\nexport interface WebSocketOutboxOptions<M, In, Out> {\n /**\n * Names the outbox's IndexedDB database, `react-websocket-outbox:<name>`. Give each outbox\n * its own. Unused with `storage`.\n */\n name: string;\n /**\n * Build the message to send for an entry, with its `id` as the idempotency key: the server\n * should do nothing for an id it has already handled, except acknowledge it again. Annotate\n * `message`: that's what `outbox.add()` accepts.\n */\n send: (message: M, id: string) => Out;\n /**\n * Recognize the server's acknowledgement and return the id it confirms, or `undefined` (or\n * `null`) for any other message. An entry stays until it's acknowledged, and is sent again\n * on every new connection until then. Without `ack`, an entry is removed once it has been\n * sent, so one sent just before the connection dropped can be lost.\n */\n ack?: (message: In) => string | null | undefined;\n /**\n * Drop an entry instead of sending it once it's older than this many ms. Checked when it\n * would be sent: on a new connection, and when stored entries are loaded.\n * @default Infinity\n */\n maxAge?: number;\n /** Called with each entry dropped by `maxAge`. */\n onExpire?: (entry: OutboxEntry<M>) => void;\n /**\n * Where to keep entries.\n * @default indexedDBStorage(name), or memoryStorage() where IndexedDB doesn't exist\n */\n storage?: OutboxStorage;\n}\n\n/** A persistent outbox on one client. Create with {@link createWebSocketOutbox}. */\nexport interface WebSocketOutbox<M> {\n /** The client the entries are sent on. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Resolves once the entries stored by an earlier page load are back in the outbox, and\n * rejects if they couldn't be loaded. Nothing is sent before.\n */\n readonly ready: Promise<void>;\n /**\n * Add a message and send it as soon as the socket is open. Resolves with its id once it's\n * stored, and rejects if storing failed; the entry is still sent from memory then, but won't\n * survive a reload. Without `ack`, one sent right away isn't stored, and resolves at once.\n * @param id - The idempotency key, e.g. an order number. A new random one by default.\n */\n add(message: M, id?: string): Promise<string>;\n /**\n * Remove an entry without sending it again, e.g. when the user cancels it. Other tabs using\n * the same `name` drop it too.\n */\n remove(id: string): Promise<void>;\n /**\n * Remove every entry at once, including ones other tabs stored, e.g. on logout. Other tabs\n * using the same `name` drop theirs too. Resolves once they're deleted from storage.\n */\n clear(): Promise<void>;\n /** The waiting entries, oldest first. A new array on every change. */\n getSnapshot(): readonly OutboxEntry<M>[];\n /** Get notified when the entries change. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop sending and listening, and release the connection. Stored entries stay stored. */\n dispose(): void;\n}\n\n/** Keep outbox entries in IndexedDB, in the database `react-websocket-outbox:<name>`. */\nexport function indexedDBStorage(name: string): OutboxStorage {\n let db: Promise<IDBDatabase> | undefined;\n // Settles once the transaction has committed, not when its request succeeds: a write isn't\n // durable before, and could still be lost if the page closed.\n const run = async <T>(\n mode: IDBTransactionMode,\n ask: (store: IDBObjectStore) => IDBRequest<T>\n ): Promise<T> => {\n db ??= new Promise((resolve, reject) => {\n const open = indexedDB.open(`react-websocket-outbox:${name}`, 1);\n open.onupgradeneeded = () => open.result.createObjectStore('entries', { keyPath: 'id' });\n open.onsuccess = () => {\n const connection = open.result;\n // Let another page delete or upgrade the database: the next write opens it again.\n connection.onversionchange = () => {\n connection.close();\n db = undefined;\n };\n resolve(connection);\n };\n open.onerror = () => reject(open.error);\n });\n const transaction = (await db).transaction('entries', mode);\n const req = ask(transaction.objectStore('entries'));\n return new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve(req.result);\n transaction.onerror = transaction.onabort = () => reject(transaction.error ?? req.error);\n });\n };\n return {\n load: () => run('readonly', store => store.getAll()),\n put: record => run('readwrite', store => store.put(record)).then(noop),\n delete: id => run('readwrite', store => store.delete(id))\n };\n}\n\n/** Keep outbox entries in memory only: they don't survive a reload. For tests and servers. */\nexport function memoryStorage(): OutboxStorage {\n const records = new Map<string, OutboxRecord>();\n return {\n load: async () => [...records.values()],\n put: async record => void records.set(record.id, record),\n delete: async id => void records.delete(id)\n };\n}\n\nconst noop = () => {};\n\nfunction randomId() {\n // `randomUUID` needs a secure context; plain-HTTP pages fall back to a timestamp and random digits.\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\n/**\n * Keep messages until the server acknowledges them, across reconnects and page reloads, for\n * apps that must not lose a message on flaky Wi-Fi: point of sale, field service, warehouses.\n *\n * - `add(message)` stores the message (in IndexedDB by default) and sends it, tagged with an\n * idempotency key, as soon as the socket is open.\n * - It stays until the server acknowledges that key (`ack`). Every new connection sends the\n * unacknowledged entries again, in order, so the server must ignore a key it has already\n * handled and acknowledge it again.\n * - After a reload, the stored entries are loaded and sent before new ones.\n * - While entries are waiting, the outbox holds the client's connection open.\n *\n * Its entries don't go through the client's send queue, so `queue` options don't apply to them.\n *\n * @example\n * ```ts\n * import { createWebSocketOutbox } from 'react-websocket/outbox';\n *\n * export const orders = createWebSocketOutbox(pos, {\n * name: 'orders',\n * send: (order: Order, id) => ({ type: 'order', id, order }),\n * ack: message => (message.type === 'ack' ? message.id : undefined)\n * });\n *\n * await orders.add({ table: 4, items });\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only; `M` comes from how `send`\n// annotates its parameter.\nexport function createWebSocketOutbox<M, In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketOutboxOptions<M, NoInfer<In>, NoInfer<Out>>\n): WebSocketOutbox<M> {\n const storage =\n options.storage ??\n (typeof indexedDB === 'undefined' ? memoryStorage() : indexedDBStorage(options.name));\n const maxAge = options.maxAge ?? Infinity;\n // Insertion order is `createdAt` order: entries loaded from storage are sorted in.\n let entries = new Map<string, OutboxEntry<M>>();\n let snapshot: readonly OutboxEntry<M>[] = [];\n const listeners = new Set<() => void>();\n let loaded = false;\n // Removed (or acknowledged) before the stored entries were loaded: don't restore them.\n const removed = new Set<string>();\n // Cleared, here or in another tab, before the stored entries were loaded: restore none.\n let clearedBeforeLoad = false;\n // Ids added since the latest `clear()` here began: the only stored entries it keeps.\n let addedSinceClear: Set<string> | undefined;\n // Other tabs using the same outbox, which loaded the same entries: tell them what's gone. Not\n // on a server, where an open channel would keep the process alive.\n let channel =\n typeof window !== 'undefined' && typeof BroadcastChannel === 'function'\n ? new BroadcastChannel(`react-websocket-outbox:${options.name}`)\n : undefined;\n let disposed = false;\n let release: (() => void) | undefined;\n // The socket that entries marked `sent` went out on. On any other, they go out again.\n let sentOn: WebSocket | null = null;\n // A strictly increasing `createdAt`, so entries added in the same ms keep their order.\n let lastCreated = 0;\n\n function changed() {\n snapshot = [...entries.values()];\n // Hold the connection while anything is waiting, so it gets delivered.\n if (snapshot.length && !release && !disposed) release = client.acquire();\n else if (!snapshot.length && release) {\n release();\n release = undefined;\n }\n for (const listener of [...listeners]) listener();\n }\n\n function drop(id: string) {\n if (!loaded) removed.add(id);\n if (entries.delete(id)) changed();\n }\n\n /**\n * Drop every entry held now, and its stored copy. Not by `createdAt`: that comes from the clock\n * of whichever page added it, which can be ahead of this one's.\n */\n function dropAll() {\n if (!loaded) clearedBeforeLoad = true;\n const held = [...entries.keys()];\n if (!held.length) return;\n entries = new Map();\n changed();\n for (const id of held) storage.delete(id).catch(noop);\n }\n\n // Also deletes a stored entry that isn't loaded yet, so it doesn't come back.\n function forget(id: string) {\n drop(id);\n channel?.postMessage({ id });\n return storage.delete(id);\n }\n\n function flush() {\n const socket = client.socket;\n // The socket, not the status, which reads `open` while the server closes it. Not `volatile`\n // either, which can be a datagram that never arrives.\n if (!loaded || disposed || socket?.readyState !== 1) return;\n // A new connection, including after `migrate()`, where the status stays `open`.\n if (socket !== sentOn) {\n unsend();\n sentOn = socket;\n }\n const now = Date.now();\n let sent = false;\n for (const entry of [...entries.values()]) {\n // Sent, removed or replaced meanwhile, by `onExpire` or a listener.\n if (entry.sent || entries.get(entry.id) !== entry) continue;\n if (now - entry.createdAt > maxAge) {\n forget(entry.id).catch(noop);\n options.onExpire?.(entry);\n } else if (client.send(options.send(entry.message, entry.id))) {\n if (!options.ack) forget(entry.id).catch(noop);\n else {\n entries.set(entry.id, { ...entry, sent: true });\n sent = true;\n }\n }\n }\n if (sent) changed();\n }\n\n const ready = storage\n .load()\n .then(records => {\n if (disposed) return;\n // Entries added from now on sort after the stored ones, whichever clock stored them.\n for (const record of records) lastCreated = Math.max(lastCreated, record.createdAt);\n // Entries added meanwhile are newer than the stored ones, unless one has the same id.\n entries = new Map(\n [\n ...records.filter(\n record => !clearedBeforeLoad && !entries.has(record.id) && !removed.has(record.id)\n ),\n ...entries.values()\n ]\n .sort((a, b) => a.createdAt - b.createdAt)\n .map(record => [record.id, { ...record, sent: false } as OutboxEntry<M>])\n );\n changed();\n })\n // Even without its stored entries, the outbox works from memory.\n .finally(() => {\n loaded = true;\n removed.clear();\n flush();\n });\n // Nobody may be awaiting `ready`; don't surface that as an unhandled rejection.\n ready.catch(noop);\n\n /** What was sent on the last connection may not have arrived: send it again on the next. */\n function unsend() {\n let changes = false;\n for (const entry of entries.values()) {\n if (entry.sent) {\n entries.set(entry.id, { ...entry, sent: false });\n changes = true;\n }\n }\n if (changes) changed();\n }\n\n if (channel) {\n channel.onmessage = ({ data }: MessageEvent<{ id?: string; before?: number } | null>) => {\n // Another tab cleared: drop everything held now, whenever it was added.\n if (data?.before) {\n lastCreated = Math.max(lastCreated, data.before);\n dropAll();\n } else if (data?.id) drop(data.id);\n };\n }\n\n const offs = [\n () => {\n // A closed channel throws on `postMessage`, which `remove()` and `clear()` still call.\n channel?.close();\n channel = undefined;\n },\n client.on('open', flush),\n client.subscribe(() => {\n if (client.getSnapshot().status !== 'open') unsend();\n }),\n client.on('message', message => {\n const id = options.ack?.(message);\n if (id != null) forget(String(id)).catch(noop);\n })\n ];\n\n return {\n client,\n ready,\n add(message, id = randomId()) {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const record: OutboxRecord<M> = { id, message, createdAt: lastCreated };\n // Re-adding an id moves it to the end, as a new message.\n entries.delete(id);\n entries.set(id, { ...record, sent: false });\n addedSinceClear?.add(id);\n changed();\n flush();\n // Sent, with no ack to wait for: there's nothing to keep. Storing it now would outlive its\n // delete, and send it again after a reload.\n if (!entries.has(id)) return Promise.resolve(id);\n return storage.put(record).then(() => id);\n },\n remove: forget,\n clear() {\n lastCreated = Math.max(Date.now(), lastCreated + 1);\n const kept = (addedSinceClear = new Set<string>());\n // At once, like `remove()`: waiting for the stored entries would send them first.\n dropAll();\n channel?.postMessage({ before: lastCreated });\n // Everything stored, by other tabs and earlier page loads too, but not what's added from\n // now on.\n return storage\n .load()\n .then(records =>\n Promise.all(\n records.filter(record => !kept.has(record.id)).map(record => storage.delete(record.id))\n )\n )\n .then(() => {\n if (addedSinceClear === kept) addedSinceClear = undefined;\n });\n },\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n disposed = true;\n for (const off of offs) off();\n release?.();\n release = undefined;\n }\n };\n}\n"],"mappings":";;AAoGA,SAAgB,iBAAiB,MAA6B;CAC5D,IAAI;CAGJ,MAAM,MAAM,OACV,MACA,QACe;EACf,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,OAAO,UAAU,KAAK,0BAA0B,QAAQ,CAAC;GAC/D,KAAK,wBAAwB,KAAK,OAAO,kBAAkB,WAAW,EAAE,SAAS,KAAK,CAAC;GACvF,KAAK,kBAAkB;IACrB,MAAM,aAAa,KAAK;IAExB,WAAW,wBAAwB;KACjC,WAAW,MAAM;KACjB,KAAK,KAAA;IACP;IACA,QAAQ,UAAU;GACpB;GACA,KAAK,gBAAgB,OAAO,KAAK,KAAK;EACxC,CAAC;EACD,MAAM,eAAe,MAAM,GAAA,CAAI,YAAY,WAAW,IAAI;EAC1D,MAAM,MAAM,IAAI,YAAY,YAAY,SAAS,CAAC;EAClD,OAAO,IAAI,SAAS,SAAS,WAA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ClD,CAAC;EACL;EACA,mBAAmB;EACnB,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,UAAU;GACR,WAAW;GACX,KAAK,MAAM,OAAO,MAAM,IAAI;GAC5B,UAAU;GACV,UAAU,KAAA;EACZ;CACF;AACF"}
package/dist/replay.cjs CHANGED
@@ -186,8 +186,8 @@ function createRecordingWebSocket(options = {}) {
186
186
  }
187
187
  close(code, reason) {
188
188
  if (this.state >= CLOSING) return;
189
- this.state = CLOSING;
190
189
  this.#inner.close(code, reason);
190
+ this.state = CLOSING;
191
191
  }
192
192
  }
193
193
  return RecordingSocket;
@@ -238,7 +238,10 @@ function createReplayWebSocket(recording, options = {}) {
238
238
  return done;
239
239
  }
240
240
  static reset() {
241
- for (const socket of live) socket.#stop();
241
+ for (const socket of live) {
242
+ socket.#stop();
243
+ socket.#finished();
244
+ }
242
245
  next = 0;
243
246
  sent = [];
244
247
  done = new Promise((resolve) => finish = resolve);
@@ -273,7 +276,7 @@ function createReplayWebSocket(recording, options = {}) {
273
276
  if (this.state >= CLOSING) return;
274
277
  this.state = CLOSING;
275
278
  this.#stop();
276
- setTimeout(() => this.ended(code, reason, true), 0);
279
+ setTimeout(() => this.#end(code, reason, true), 0);
277
280
  }
278
281
  #schedule() {
279
282
  clearTimeout(this.#timer);
@@ -299,15 +302,17 @@ function createReplayWebSocket(recording, options = {}) {
299
302
  if (event.type === "open") this.opened(event.protocol);
300
303
  else if (event.type === "message") this.received(decode(event.data, this.binaryType));
301
304
  else if (event.type === "error") this.dispatchEvent(new Event("error"));
302
- else if (event.type === "close") {
303
- this.#stop();
304
- return this.ended(event.code, event.reason, event.wasClean);
305
- }
305
+ else if (event.type === "close") return this.#end(event.code, event.reason, event.wasClean);
306
306
  this.#schedule();
307
307
  }
308
308
  #stop() {
309
309
  clearTimeout(this.#timer);
310
310
  this.#index = this.#events.length;
311
+ }
312
+ /** Finished once the close event is out, so `done` comes after it. */
313
+ #end(code, reason, wasClean) {
314
+ this.#stop();
315
+ this.ended(code, reason, wasClean);
311
316
  this.#finished();
312
317
  }
313
318
  #finished() {
@@ -1 +1 @@
1
- {"version":3,"file":"replay.cjs","names":[],"sources":["../src/replay.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Data in a recording: text as it was, binary as base64. */\nexport type RecordedData = string | { readonly binary: string };\n\n/** One event of a recorded connection, `t` ms after it was created. */\nexport type RecordedEvent =\n | { readonly t: number; readonly type: 'open'; readonly protocol: string }\n | { readonly t: number; readonly type: 'send' | 'message'; readonly data: RecordedData }\n | { readonly t: number; readonly type: 'error' }\n | {\n readonly t: number;\n readonly type: 'close';\n readonly code: number;\n readonly reason: string;\n readonly wasClean: boolean;\n };\n\n/** A recorded event before its time is known. */\ntype Untimed = RecordedEvent extends infer E\n ? E extends RecordedEvent\n ? Omit<E, 't'>\n : never\n : never;\n\n/** A recorded session: every connection, in the order they were opened. Plain JSON. */\nexport interface WebSocketRecording {\n readonly format: 'react-websocket-recording';\n readonly version: 1;\n readonly connections: readonly {\n readonly url: string;\n /** When it was created, from `Date.now()`. */\n readonly at: number;\n readonly events: readonly RecordedEvent[];\n }[];\n}\n\n/** The class from {@link createRecordingWebSocket}: a `WebSocket` that records what it does. */\nexport interface RecordingWebSocket extends Statics {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n /** Everything recorded so far, as a new plain object. */\n recording(): WebSocketRecording;\n /** Download the recording as a JSON file, e.g. from a \"Report a problem\" button. */\n save(filename?: string): void;\n /** Forget everything recorded so far. */\n clear(): void;\n}\n\n/** Options for {@link createReplayWebSocket}. */\nexport interface ReplayOptions {\n /**\n * How fast to replay: `1` is the recorded timing, `4` four times faster, `Infinity` as fast as\n * possible, each event in a task of its own.\n * @default 1\n */\n speed?: number;\n /**\n * Wait for the app to send before replaying what came after a send in the recording, so the\n * replay follows the app instead of the clock: a server's answer comes after the question,\n * however long the app takes to ask. `false` follows the recorded timing alone.\n * @default true\n */\n waitForSends?: boolean;\n}\n\n/** The class from {@link createReplayWebSocket}: a `WebSocket` that plays a recording back. */\nexport interface ReplayWebSocket extends Statics {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n /** What the app sent during the replay, by connection, as recorded data. */\n readonly sent: readonly RecordedData[][];\n /** Resolves once every recorded connection has been played to its end. */\n readonly done: Promise<void>;\n /** Start again from the first recorded connection. */\n reset(): void;\n}\n\ninterface Statics {\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nfunction encode(bytes: ArrayBuffer | ArrayBufferView): RecordedData {\n const view =\n bytes instanceof ArrayBuffer\n ? new Uint8Array(bytes)\n : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n let text = '';\n for (const byte of view) text += String.fromCharCode(byte);\n return { binary: btoa(text) };\n}\n\nfunction decode(data: RecordedData, binaryType: BinaryType): unknown {\n if (typeof data === 'string') return data;\n const buffer = Uint8Array.from(atob(data.binary), char => char.charCodeAt(0)).buffer;\n return binaryType === 'blob' ? new Blob([buffer]) : buffer;\n}\n\n/** Shared by both classes: the `WebSocket` surface over a state and some events. */\nclass Base extends EventTarget {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n protocol = '';\n state: WebSocket['readyState'] = CONNECTING;\n\n constructor(url: string | URL) {\n super();\n this.url = String(url);\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n }\n\n get readyState() {\n return this.state;\n }\n\n opened(protocol: string) {\n this.state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n received(data: unknown) {\n if (this.state === OPEN) this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n ended(code: number, reason: string, wasClean: boolean) {\n if (this.state === CLOSED) return;\n this.state = CLOSED;\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n}\n\n/**\n * A `WebSocket` class that records what its connections do: when each one opened, every message\n * sent and received, errors and closes. Pass it as the `WebSocket` option, and get the session\n * back with `recording()`, or download it with `save()`, to attach to a bug report or replay\n * with {@link createReplayWebSocket}.\n *\n * Recordings hold every message, so they can hold tokens and personal data: record in\n * development, or ask before saving one from a user's session.\n *\n * @example\n * ```ts\n * import { createRecordingWebSocket } from 'react-websocket/replay';\n *\n * export const Recorder = createRecordingWebSocket();\n * export const live = createWebSocket(url, { WebSocket: Recorder });\n *\n * reportButton.onclick = () => Recorder.save('session.json');\n * ```\n */\nexport function createRecordingWebSocket(\n options: { WebSocket?: typeof WebSocket } = {}\n): RecordingWebSocket {\n let connections: { url: string; at: number; events: RecordedEvent[] }[] = [];\n\n class RecordingSocket extends Base implements WebSocket {\n #inner: WebSocket;\n #binaryType: BinaryType = 'blob';\n\n static recording(): WebSocketRecording {\n return JSON.parse(\n JSON.stringify({ format: 'react-websocket-recording', version: 1, connections })\n );\n }\n\n static save(filename = 'websocket-recording.json') {\n const url = URL.createObjectURL(\n new Blob([JSON.stringify(RecordingSocket.recording(), null, 2)], {\n type: 'application/json'\n })\n );\n const link = Object.assign(document.createElement('a'), { href: url, download: filename });\n link.click();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n }\n\n static clear() {\n connections = [];\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url);\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n const inner = (this.#inner = new Impl(url, protocols));\n // Binary data arrives as an ArrayBuffer, to record it without waiting on a Blob.\n inner.binaryType = 'arraybuffer';\n const start = performance.now();\n const events: RecordedEvent[] = [];\n connections.push({ url: this.url, at: Date.now(), events });\n const record = (event: Untimed) =>\n events.push({ t: Math.round(performance.now() - start), ...event } as RecordedEvent);\n this.#record = record;\n inner.onopen = () => {\n record({ type: 'open', protocol: inner.protocol ?? '' });\n this.opened(inner.protocol);\n };\n inner.onmessage = event => {\n const data = event.data as string | ArrayBuffer;\n record({ type: 'message', data: typeof data === 'string' ? data : encode(data) });\n this.received(\n typeof data === 'string' || this.#binaryType !== 'blob' ? data : new Blob([data])\n );\n };\n inner.onerror = () => {\n record({ type: 'error' });\n this.dispatchEvent(new Event('error'));\n };\n inner.onclose = event => {\n record({ type: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n this.ended(event.code, event.reason, event.wasClean);\n };\n }\n\n #record: (event: Untimed) => void;\n\n get binaryType() {\n return this.#binaryType;\n }\n\n set binaryType(value) {\n this.#binaryType = value;\n }\n\n get bufferedAmount() {\n return this.#inner.bufferedAmount;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n this.#inner.send(data);\n if (typeof data === 'string') this.#record({ type: 'send', data });\n else if (data instanceof Blob) {\n // Recorded where it was sent; its bytes are filled in once read.\n const event = { type: 'send', data: { binary: '' } } as const;\n this.#record(event);\n void data.arrayBuffer().then(buffer => Object.assign(event.data, encode(buffer)));\n } else this.#record({ type: 'send', data: encode(data) });\n }\n\n close(code?: number, reason?: string) {\n if (this.state >= CLOSING) return;\n this.state = CLOSING;\n this.#inner.close(code, reason);\n }\n }\n\n return RecordingSocket as unknown as RecordingWebSocket;\n}\n\n/**\n * A `WebSocket` class that plays a recording back, without a server: each connection the client\n * opens replays the next recorded one, with its open, messages, errors and close, at the recorded\n * timing or faster. For reproducing a bug report, offline demos, and UI tests that don't call a\n * live backend, such as an AI model, on every run.\n *\n * By default, what came after a send in the recording waits until the app sends too, so the\n * replay follows the app. Wrap it with `createChaosWebSocket({ WebSocket: Replay })` to add\n * faults.\n *\n * @example\n * ```ts\n * import { createReplayWebSocket } from 'react-websocket/replay';\n * import recording from './fixtures/chat.json';\n *\n * const Replay = createReplayWebSocket(recording, { speed: Infinity });\n * render(<Chat client={createWebSocket(url, { WebSocket: Replay })} />);\n * await Replay.done;\n * ```\n */\nexport function createReplayWebSocket(\n recording: WebSocketRecording,\n options: ReplayOptions = {}\n): ReplayWebSocket {\n const speed = options.speed ?? 1;\n const waitForSends = options.waitForSends ?? true;\n let next = 0;\n let sent: RecordedData[][] = [];\n let finish: () => void;\n let done = new Promise<void>(resolve => (finish = resolve));\n const live = new Set<ReplaySocket>();\n\n class ReplaySocket extends Base implements WebSocket {\n binaryType: BinaryType = 'blob';\n readonly bufferedAmount = 0;\n #events: readonly RecordedEvent[];\n #index = 0;\n #sent: RecordedData[] = [];\n // The recorded time the timeline is at, and the real time it was there.\n #recordedAt = 0;\n #realAt = performance.now();\n #timer: ReturnType<typeof setTimeout> | undefined;\n // Recorded sends passed so far, and whether the timeline waits for the app to send.\n #sends = 0;\n #paused = false;\n\n static get sent() {\n return sent;\n }\n\n static get done() {\n return done;\n }\n\n static reset() {\n for (const socket of live) socket.#stop();\n next = 0;\n sent = [];\n done = new Promise<void>(resolve => (finish = resolve));\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url);\n void protocols;\n const connection = recording.connections[next++];\n sent.push(this.#sent);\n // More connections than were recorded: refused, like a server that's gone.\n this.#events = connection?.events ?? [\n { t: 0, type: 'error' },\n { t: 0, type: 'close', code: 1006, reason: '', wasClean: false }\n ];\n live.add(this);\n this.#schedule();\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.state !== OPEN) return;\n this.#sent.push(\n typeof data === 'string' ? data : data instanceof Blob ? { binary: '' } : encode(data)\n );\n if (this.#paused) {\n this.#paused = false;\n this.#schedule();\n }\n }\n\n close(code = 1000, reason = '') {\n if (this.state >= CLOSING) return;\n this.state = CLOSING;\n this.#stop();\n setTimeout(() => this.ended(code, reason, true), 0);\n }\n\n #schedule(): void {\n clearTimeout(this.#timer);\n const event = this.#events[this.#index];\n if (!event || this.state === CLOSED) return this.#finished();\n if (event.type === 'send') {\n if (waitForSends) {\n // Wait until the app has sent as many messages, then go on from that moment.\n if (this.#sent.length <= this.#sends) return void (this.#paused = true);\n this.#recordedAt = event.t;\n this.#realAt = performance.now();\n }\n this.#index++;\n this.#sends++;\n return this.#schedule();\n }\n const wait = (event.t - this.#recordedAt) / speed - (performance.now() - this.#realAt);\n this.#timer = setTimeout(\n () => this.#play(event),\n Math.max(0, Number.isFinite(wait) ? wait : 0)\n );\n }\n\n #play(event: RecordedEvent) {\n this.#index++;\n this.#recordedAt = event.t;\n this.#realAt = performance.now();\n if (event.type === 'open') this.opened(event.protocol);\n else if (event.type === 'message') this.received(decode(event.data, this.binaryType));\n else if (event.type === 'error') this.dispatchEvent(new Event('error'));\n else if (event.type === 'close') {\n this.#stop();\n return this.ended(event.code, event.reason, event.wasClean);\n }\n this.#schedule();\n }\n\n #stop() {\n clearTimeout(this.#timer);\n this.#index = this.#events.length;\n this.#finished();\n }\n\n #finished() {\n live.delete(this);\n if (next >= recording.connections.length && !live.size) finish();\n }\n }\n\n return ReplaySocket as unknown as ReplayWebSocket;\n}\n"],"mappings":";;AAqFA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AAEf,SAAS,WAAW,MAAc,QAAgB,UAA0B;CAC1E,MAAM,OAAO;EAAE;EAAM;EAAQ;CAAS;CAEtC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Q,MAAM,QAAQ;GAC5D;GACA,KAAK,UAAU;EACjB;EAEA,QAAQ;GACN,aAAa,KAAK,MAAM;GACxB,KAAK,SAAS,KAAK,QAAQ;GAC3B,KAAK,UAAU;EACjB;EAEA,YAAY;GACV,KAAK,OAAO,IAAI;GAChB,IAAI,QAAQ,UAAU,YAAY,UAAU,CAAC,KAAK,MAAM,OAAO;EACjE;CACF;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"replay.cjs","names":[],"sources":["../src/replay.ts"],"sourcesContent":["// An entry with no imports: it only implements the `WebSocket` interface.\n\n/** Data in a recording: text as it was, binary as base64. */\nexport type RecordedData = string | { readonly binary: string };\n\n/** One event of a recorded connection, `t` ms after it was created. */\nexport type RecordedEvent =\n | { readonly t: number; readonly type: 'open'; readonly protocol: string }\n | { readonly t: number; readonly type: 'send' | 'message'; readonly data: RecordedData }\n | { readonly t: number; readonly type: 'error' }\n | {\n readonly t: number;\n readonly type: 'close';\n readonly code: number;\n readonly reason: string;\n readonly wasClean: boolean;\n };\n\n/** A recorded event before its time is known. */\ntype Untimed = RecordedEvent extends infer E\n ? E extends RecordedEvent\n ? Omit<E, 't'>\n : never\n : never;\n\n/** A recorded session: every connection, in the order they were opened. Plain JSON. */\nexport interface WebSocketRecording {\n readonly format: 'react-websocket-recording';\n readonly version: 1;\n readonly connections: readonly {\n readonly url: string;\n /** When it was created, from `Date.now()`. */\n readonly at: number;\n readonly events: readonly RecordedEvent[];\n }[];\n}\n\n/** The class from {@link createRecordingWebSocket}: a `WebSocket` that records what it does. */\nexport interface RecordingWebSocket extends Statics {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n /** Everything recorded so far, as a new plain object. */\n recording(): WebSocketRecording;\n /** Download the recording as a JSON file, e.g. from a \"Report a problem\" button. */\n save(filename?: string): void;\n /** Forget everything recorded so far. */\n clear(): void;\n}\n\n/** Options for {@link createReplayWebSocket}. */\nexport interface ReplayOptions {\n /**\n * How fast to replay: `1` is the recorded timing, `4` four times faster, `Infinity` as fast as\n * possible, each event in a task of its own.\n * @default 1\n */\n speed?: number;\n /**\n * Wait for the app to send before replaying what came after a send in the recording, so the\n * replay follows the app instead of the clock: a server's answer comes after the question,\n * however long the app takes to ask. `false` follows the recorded timing alone.\n * @default true\n */\n waitForSends?: boolean;\n}\n\n/** The class from {@link createReplayWebSocket}: a `WebSocket` that plays a recording back. */\nexport interface ReplayWebSocket extends Statics {\n new (url: string | URL, protocols?: string | string[]): WebSocket;\n readonly prototype: WebSocket;\n /** What the app sent during the replay, by connection, as recorded data. */\n readonly sent: readonly RecordedData[][];\n /**\n * Resolves once every recorded connection has been played to its end, after its last `close`\n * event.\n */\n readonly done: Promise<void>;\n /**\n * Start again from the first recorded connection. Connections still playing stop where they are,\n * without a `close` event.\n */\n reset(): void;\n}\n\ninterface Statics {\n readonly CONNECTING: 0;\n readonly OPEN: 1;\n readonly CLOSING: 2;\n readonly CLOSED: 3;\n}\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\nfunction closeEvent(code: number, reason: string, wasClean: boolean): Event {\n const init = { code, reason, wasClean };\n // Node 22 has no CloseEvent.\n return typeof CloseEvent === 'function'\n ? new CloseEvent('close', init)\n : Object.assign(new Event('close'), init);\n}\n\nfunction encode(bytes: ArrayBuffer | ArrayBufferView): RecordedData {\n const view =\n bytes instanceof ArrayBuffer\n ? new Uint8Array(bytes)\n : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n let text = '';\n for (const byte of view) text += String.fromCharCode(byte);\n return { binary: btoa(text) };\n}\n\nfunction decode(data: RecordedData, binaryType: BinaryType): unknown {\n if (typeof data === 'string') return data;\n const buffer = Uint8Array.from(atob(data.binary), char => char.charCodeAt(0)).buffer;\n return binaryType === 'blob' ? new Blob([buffer]) : buffer;\n}\n\n/** Shared by both classes: the `WebSocket` surface over a state and some events. */\nclass Base extends EventTarget {\n static readonly CONNECTING = CONNECTING;\n static readonly OPEN = OPEN;\n static readonly CLOSING = CLOSING;\n static readonly CLOSED = CLOSED;\n readonly CONNECTING = CONNECTING;\n readonly OPEN = OPEN;\n readonly CLOSING = CLOSING;\n readonly CLOSED = CLOSED;\n readonly url: string;\n readonly extensions = '';\n onopen: WebSocket['onopen'] = null;\n onmessage: WebSocket['onmessage'] = null;\n onerror: WebSocket['onerror'] = null;\n onclose: WebSocket['onclose'] = null;\n protocol = '';\n state: WebSocket['readyState'] = CONNECTING;\n\n constructor(url: string | URL) {\n super();\n this.url = String(url);\n for (const type of ['open', 'message', 'error', 'close'] as const) {\n this.addEventListener(type, event =>\n (this[`on${type}`] as ((event: Event) => void) | null)?.call(this, event)\n );\n }\n }\n\n get readyState() {\n return this.state;\n }\n\n opened(protocol: string) {\n this.state = OPEN;\n this.protocol = protocol;\n this.dispatchEvent(new Event('open'));\n }\n\n received(data: unknown) {\n if (this.state === OPEN) this.dispatchEvent(new MessageEvent('message', { data }));\n }\n\n ended(code: number, reason: string, wasClean: boolean) {\n if (this.state === CLOSED) return;\n this.state = CLOSED;\n this.dispatchEvent(closeEvent(code, reason, wasClean));\n }\n}\n\n/**\n * A `WebSocket` class that records what its connections do: when each one opened, every message\n * sent and received, errors and closes. Pass it as the `WebSocket` option, and get the session\n * back with `recording()`, or download it with `save()`, to attach to a bug report or replay\n * with {@link createReplayWebSocket}.\n *\n * Recordings hold every message, so they can hold tokens and personal data: record in\n * development, or ask before saving one from a user's session.\n *\n * @example\n * ```ts\n * import { createRecordingWebSocket } from 'react-websocket/replay';\n *\n * export const Recorder = createRecordingWebSocket();\n * export const live = createWebSocket(url, { WebSocket: Recorder });\n *\n * reportButton.onclick = () => Recorder.save('session.json');\n * ```\n */\nexport function createRecordingWebSocket(\n options: { WebSocket?: typeof WebSocket } = {}\n): RecordingWebSocket {\n let connections: { url: string; at: number; events: RecordedEvent[] }[] = [];\n\n class RecordingSocket extends Base implements WebSocket {\n #inner: WebSocket;\n #binaryType: BinaryType = 'blob';\n\n static recording(): WebSocketRecording {\n return JSON.parse(\n JSON.stringify({ format: 'react-websocket-recording', version: 1, connections })\n );\n }\n\n static save(filename = 'websocket-recording.json') {\n const url = URL.createObjectURL(\n new Blob([JSON.stringify(RecordingSocket.recording(), null, 2)], {\n type: 'application/json'\n })\n );\n const link = Object.assign(document.createElement('a'), { href: url, download: filename });\n link.click();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n }\n\n static clear() {\n connections = [];\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url);\n const Impl = options.WebSocket ?? globalThis.WebSocket;\n const inner = (this.#inner = new Impl(url, protocols));\n // Binary data arrives as an ArrayBuffer, to record it without waiting on a Blob.\n inner.binaryType = 'arraybuffer';\n const start = performance.now();\n const events: RecordedEvent[] = [];\n connections.push({ url: this.url, at: Date.now(), events });\n const record = (event: Untimed) =>\n events.push({ t: Math.round(performance.now() - start), ...event } as RecordedEvent);\n this.#record = record;\n inner.onopen = () => {\n record({ type: 'open', protocol: inner.protocol ?? '' });\n this.opened(inner.protocol);\n };\n inner.onmessage = event => {\n const data = event.data as string | ArrayBuffer;\n record({ type: 'message', data: typeof data === 'string' ? data : encode(data) });\n this.received(\n typeof data === 'string' || this.#binaryType !== 'blob' ? data : new Blob([data])\n );\n };\n inner.onerror = () => {\n record({ type: 'error' });\n this.dispatchEvent(new Event('error'));\n };\n inner.onclose = event => {\n record({ type: 'close', code: event.code, reason: event.reason, wasClean: event.wasClean });\n this.ended(event.code, event.reason, event.wasClean);\n };\n }\n\n #record: (event: Untimed) => void;\n\n get binaryType() {\n return this.#binaryType;\n }\n\n set binaryType(value) {\n this.#binaryType = value;\n }\n\n get bufferedAmount() {\n return this.#inner.bufferedAmount;\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n this.#inner.send(data);\n if (typeof data === 'string') this.#record({ type: 'send', data });\n else if (data instanceof Blob) {\n // Recorded where it was sent; its bytes are filled in once read.\n const event = { type: 'send', data: { binary: '' } } as const;\n this.#record(event);\n void data.arrayBuffer().then(buffer => Object.assign(event.data, encode(buffer)));\n } else this.#record({ type: 'send', data: encode(data) });\n }\n\n close(code?: number, reason?: string) {\n if (this.state >= CLOSING) return;\n // First, so that a code the socket rejects throws before anything has changed.\n this.#inner.close(code, reason);\n this.state = CLOSING;\n }\n }\n\n return RecordingSocket as unknown as RecordingWebSocket;\n}\n\n/**\n * A `WebSocket` class that plays a recording back, without a server: each connection the client\n * opens replays the next recorded one, with its open, messages, errors and close, at the recorded\n * timing or faster. For reproducing a bug report, offline demos, and UI tests that don't call a\n * live backend, such as an AI model, on every run.\n *\n * By default, what came after a send in the recording waits until the app sends too, so the\n * replay follows the app. Wrap it with `createChaosWebSocket({ WebSocket: Replay })` to add\n * faults.\n *\n * @example\n * ```ts\n * import { createReplayWebSocket } from 'react-websocket/replay';\n * import recording from './fixtures/chat.json';\n *\n * const Replay = createReplayWebSocket(recording, { speed: Infinity });\n * render(<Chat client={createWebSocket(url, { WebSocket: Replay })} />);\n * await Replay.done;\n * ```\n */\nexport function createReplayWebSocket(\n recording: WebSocketRecording,\n options: ReplayOptions = {}\n): ReplayWebSocket {\n const speed = options.speed ?? 1;\n const waitForSends = options.waitForSends ?? true;\n let next = 0;\n let sent: RecordedData[][] = [];\n let finish: () => void;\n let done = new Promise<void>(resolve => (finish = resolve));\n const live = new Set<ReplaySocket>();\n\n class ReplaySocket extends Base implements WebSocket {\n binaryType: BinaryType = 'blob';\n readonly bufferedAmount = 0;\n #events: readonly RecordedEvent[];\n #index = 0;\n #sent: RecordedData[] = [];\n // The recorded time the timeline is at, and the real time it was there.\n #recordedAt = 0;\n #realAt = performance.now();\n #timer: ReturnType<typeof setTimeout> | undefined;\n // Recorded sends passed so far, and whether the timeline waits for the app to send.\n #sends = 0;\n #paused = false;\n\n static get sent() {\n return sent;\n }\n\n static get done() {\n return done;\n }\n\n static reset() {\n for (const socket of live) {\n socket.#stop();\n socket.#finished();\n }\n next = 0;\n sent = [];\n done = new Promise<void>(resolve => (finish = resolve));\n }\n\n constructor(url: string | URL, protocols?: string | string[]) {\n super(url);\n void protocols;\n const connection = recording.connections[next++];\n sent.push(this.#sent);\n // More connections than were recorded: refused, like a server that's gone.\n this.#events = connection?.events ?? [\n { t: 0, type: 'error' },\n { t: 0, type: 'close', code: 1006, reason: '', wasClean: false }\n ];\n live.add(this);\n this.#schedule();\n }\n\n send(data: Parameters<WebSocket['send']>[0]) {\n if (this.state === CONNECTING) {\n throw new DOMException('WebSocket is still in CONNECTING state', 'InvalidStateError');\n }\n if (this.state !== OPEN) return;\n this.#sent.push(\n typeof data === 'string' ? data : data instanceof Blob ? { binary: '' } : encode(data)\n );\n if (this.#paused) {\n this.#paused = false;\n this.#schedule();\n }\n }\n\n close(code = 1000, reason = '') {\n if (this.state >= CLOSING) return;\n this.state = CLOSING;\n this.#stop();\n setTimeout(() => this.#end(code, reason, true), 0);\n }\n\n #schedule(): void {\n clearTimeout(this.#timer);\n const event = this.#events[this.#index];\n if (!event || this.state === CLOSED) return this.#finished();\n if (event.type === 'send') {\n if (waitForSends) {\n // Wait until the app has sent as many messages, then go on from that moment.\n if (this.#sent.length <= this.#sends) return void (this.#paused = true);\n this.#recordedAt = event.t;\n this.#realAt = performance.now();\n }\n this.#index++;\n this.#sends++;\n return this.#schedule();\n }\n const wait = (event.t - this.#recordedAt) / speed - (performance.now() - this.#realAt);\n this.#timer = setTimeout(\n () => this.#play(event),\n Math.max(0, Number.isFinite(wait) ? wait : 0)\n );\n }\n\n #play(event: RecordedEvent) {\n this.#index++;\n this.#recordedAt = event.t;\n this.#realAt = performance.now();\n if (event.type === 'open') this.opened(event.protocol);\n else if (event.type === 'message') this.received(decode(event.data, this.binaryType));\n else if (event.type === 'error') this.dispatchEvent(new Event('error'));\n else if (event.type === 'close') return this.#end(event.code, event.reason, event.wasClean);\n this.#schedule();\n }\n\n #stop() {\n clearTimeout(this.#timer);\n this.#index = this.#events.length;\n }\n\n /** Finished once the close event is out, so `done` comes after it. */\n #end(code: number, reason: string, wasClean: boolean) {\n this.#stop();\n this.ended(code, reason, wasClean);\n this.#finished();\n }\n\n #finished() {\n live.delete(this);\n if (next >= recording.connections.length && !live.size) finish();\n }\n }\n\n return ReplaySocket as unknown as ReplayWebSocket;\n}\n"],"mappings":";;AA2FA,MAAM,aAAa;AACnB,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AAEf,SAAS,WAAW,MAAc,QAAgB,UAA0B;CAC1E,MAAM,OAAO;EAAE;EAAM;EAAQ;CAAS;CAEtC,OAAO,OAAO,eAAe,aACzB,IAAI,WAAW,SAAS,IAAI,IAC5B,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG,IAAI;AAC5C;AAEA,SAAS,OAAO,OAAoD;CAClE,MAAM,OACJ,iBAAiB,cACb,IAAI,WAAW,KAAK,IACpB,IAAI,WAAW,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU;CACrE,IAAI,OAAO;CACX,KAAK,MAAM,QAAQ,MAAM,QAAQ,OAAO,aAAa,IAAI;CACzD,OAAO,EAAE,QAAQ,KAAK,IAAI,EAAE;AAC9B;AAEA,SAAS,OAAO,MAAoB,YAAiC;CACnE,IAAI,OAAO,SAAS,UAAU,OAAO;CACrC,MAAM,SAAS,WAAW,KAAK,KAAK,KAAK,MAAM,IAAG,SAAQ,KAAK,WAAW,CAAC,CAAC,CAAC,CAAC;CAC9E,OAAO,eAAe,SAAS,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI;AACtD;;AAGA,IAAM,OAAN,cAAmB,YAAY;CAC7B,OAAgB,aAAa;CAC7B,OAAgB,OAAO;CACvB,OAAgB,UAAU;CAC1B,OAAgB,SAAS;CACzB,aAAsB;CACtB,OAAgB;CAChB,UAAmB;CACnB,SAAkB;CAClB;CACA,aAAsB;CACtB,SAA8B;CAC9B,YAAoC;CACpC,UAAgC;CAChC,UAAgC;CAChC,WAAW;CACX,QAAiC;CAEjC,YAAY,KAAmB;EAC7B,MAAM;EACN,KAAK,MAAM,OAAO,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ACL,KAAK,cAAc,MAAM;GACzB,KAAK,UAAU,YAAY,IAAI;GAC/B,IAAI,MAAM,SAAS,QAAQ,KAAK,OAAO,MAAM,QAAQ;QAChD,IAAI,MAAM,SAAS,WAAW,KAAK,SAAS,OAAO,MAAM,MAAM,KAAK,UAAU,CAAC;QAC/E,IAAI,MAAM,SAAS,SAAS,KAAK,cAAc,IAAI,MAAM,OAAO,CAAC;QACjE,IAAI,MAAM,SAAS,SAAS,OAAO,KAAK,KAAK,MAAM,MAAM,MAAM,QAAQ,MAAM,QAAQ;GAC1F,KAAK,UAAU;EACjB;EAEA,QAAQ;GACN,aAAa,KAAK,MAAM;GACxB,KAAK,SAAS,KAAK,QAAQ;EAC7B;;EAGA,KAAK,MAAc,QAAgB,UAAmB;GACpD,KAAK,MAAM;GACX,KAAK,MAAM,MAAM,QAAQ,QAAQ;GACjC,KAAK,UAAU;EACjB;EAEA,YAAY;GACV,KAAK,OAAO,IAAI;GAChB,IAAI,QAAQ,UAAU,YAAY,UAAU,CAAC,KAAK,MAAM,OAAO;EACjE;CACF;CAEA,OAAO;AACT"}
package/dist/replay.d.cts CHANGED
@@ -66,9 +66,15 @@ export interface ReplayWebSocket extends Statics {
66
66
  readonly prototype: WebSocket;
67
67
  /** What the app sent during the replay, by connection, as recorded data. */
68
68
  readonly sent: readonly RecordedData[][];
69
- /** Resolves once every recorded connection has been played to its end. */
69
+ /**
70
+ * Resolves once every recorded connection has been played to its end, after its last `close`
71
+ * event.
72
+ */
70
73
  readonly done: Promise<void>;
71
- /** Start again from the first recorded connection. */
74
+ /**
75
+ * Start again from the first recorded connection. Connections still playing stop where they are,
76
+ * without a `close` event.
77
+ */
72
78
  reset(): void;
73
79
  }
74
80
  interface Statics {
package/dist/replay.d.ts CHANGED
@@ -66,9 +66,15 @@ export interface ReplayWebSocket extends Statics {
66
66
  readonly prototype: WebSocket;
67
67
  /** What the app sent during the replay, by connection, as recorded data. */
68
68
  readonly sent: readonly RecordedData[][];
69
- /** Resolves once every recorded connection has been played to its end. */
69
+ /**
70
+ * Resolves once every recorded connection has been played to its end, after its last `close`
71
+ * event.
72
+ */
70
73
  readonly done: Promise<void>;
71
- /** Start again from the first recorded connection. */
74
+ /**
75
+ * Start again from the first recorded connection. Connections still playing stop where they are,
76
+ * without a `close` event.
77
+ */
72
78
  reset(): void;
73
79
  }
74
80
  interface Statics {
package/dist/replay.js CHANGED
@@ -185,8 +185,8 @@ function createRecordingWebSocket(options = {}) {
185
185
  }
186
186
  close(code, reason) {
187
187
  if (this.state >= CLOSING) return;
188
- this.state = CLOSING;
189
188
  this.#inner.close(code, reason);
189
+ this.state = CLOSING;
190
190
  }
191
191
  }
192
192
  return RecordingSocket;
@@ -237,7 +237,10 @@ function createReplayWebSocket(recording, options = {}) {
237
237
  return done;
238
238
  }
239
239
  static reset() {
240
- for (const socket of live) socket.#stop();
240
+ for (const socket of live) {
241
+ socket.#stop();
242
+ socket.#finished();
243
+ }
241
244
  next = 0;
242
245
  sent = [];
243
246
  done = new Promise((resolve) => finish = resolve);
@@ -272,7 +275,7 @@ function createReplayWebSocket(recording, options = {}) {
272
275
  if (this.state >= CLOSING) return;
273
276
  this.state = CLOSING;
274
277
  this.#stop();
275
- setTimeout(() => this.ended(code, reason, true), 0);
278
+ setTimeout(() => this.#end(code, reason, true), 0);
276
279
  }
277
280
  #schedule() {
278
281
  clearTimeout(this.#timer);
@@ -298,15 +301,17 @@ function createReplayWebSocket(recording, options = {}) {
298
301
  if (event.type === "open") this.opened(event.protocol);
299
302
  else if (event.type === "message") this.received(decode(event.data, this.binaryType));
300
303
  else if (event.type === "error") this.dispatchEvent(new Event("error"));
301
- else if (event.type === "close") {
302
- this.#stop();
303
- return this.ended(event.code, event.reason, event.wasClean);
304
- }
304
+ else if (event.type === "close") return this.#end(event.code, event.reason, event.wasClean);
305
305
  this.#schedule();
306
306
  }
307
307
  #stop() {
308
308
  clearTimeout(this.#timer);
309
309
  this.#index = this.#events.length;
310
+ }
311
+ /** Finished once the close event is out, so `done` comes after it. */
312
+ #end(code, reason, wasClean) {
313
+ this.#stop();
314
+ this.ended(code, reason, wasClean);
310
315
  this.#finished();
311
316
  }
312
317
  #finished() {