react-websocket 4.20.0 → 4.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ag-ui.cjs +8 -1
- package/dist/ag-ui.cjs.map +1 -1
- package/dist/ag-ui.d.cts +25 -5
- package/dist/ag-ui.d.ts +7 -0
- package/dist/ag-ui.js +8 -1
- package/dist/ag-ui.js.map +1 -1
- package/dist/core.cjs +34 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +23 -5
- package/dist/core.d.ts +23 -5
- package/dist/core.js +34 -1
- package/dist/core.js.map +1 -1
- package/dist/index.d.cts +30 -5
- package/dist/index.d.ts +24 -5
- package/dist/outbox.cjs +27 -13
- package/dist/outbox.cjs.map +1 -1
- package/dist/outbox.d.cts +1 -1
- package/dist/outbox.js +27 -13
- package/dist/outbox.js.map +1 -1
- package/dist/replay.d.cts +1 -0
- package/dist/replay.d.ts +1 -0
- package/dist/tabs.cjs +1 -1
- package/dist/tabs.cjs.map +1 -1
- package/dist/tabs.d.cts +7 -0
- package/dist/tabs.d.ts +7 -0
- package/dist/tabs.js +1 -1
- package/dist/tabs.js.map +1 -1
- package/dist/timeline.d.cts +2 -1
- package/dist/{types-BEecFqIB.d.cts → types-paLT8yQF.d.cts} +11 -6
- package/package.json +11 -11
package/dist/index.d.cts
CHANGED
|
@@ -30,7 +30,10 @@ type Status = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed';
|
|
|
30
30
|
interface Snapshot<In> {
|
|
31
31
|
/** Connection state. */
|
|
32
32
|
readonly status: Status;
|
|
33
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* Most recent message (after `parse`/`json` and `schema`), kept across reconnects and
|
|
35
|
+
* cleared by `close()`.
|
|
36
|
+
*/
|
|
34
37
|
readonly lastMessage: In | undefined;
|
|
35
38
|
/**
|
|
36
39
|
* Consecutive failed attempts since the last stable connection. A connection that closes
|
|
@@ -434,9 +437,10 @@ interface WebSocketClient<In = unknown, Out = unknown> {
|
|
|
434
437
|
*/
|
|
435
438
|
connect(): void;
|
|
436
439
|
/**
|
|
437
|
-
* Close the connection and stop reconnecting. The status becomes `closed
|
|
438
|
-
*
|
|
439
|
-
* to start again. Closed while no hook
|
|
440
|
+
* Close the connection and stop reconnecting. The status becomes `closed`, and the send
|
|
441
|
+
* queue, a `migrate()` target and `lastMessage` are cleared, so call it on logout. Mounted
|
|
442
|
+
* hooks stay mounted; call `connect()` or `reconnect()` to start again. Closed while no hook
|
|
443
|
+
* holds it, the next hook to mount starts it again.
|
|
440
444
|
*
|
|
441
445
|
* Like `WebSocket.close()`, it throws for a code or reason the socket rejects (browsers take
|
|
442
446
|
* `1000` or `3000`–`4999`, and a reason up to 123 bytes), and then nothing has changed.
|
|
@@ -445,7 +449,8 @@ interface WebSocketClient<In = unknown, Out = unknown> {
|
|
|
445
449
|
close(code?: number, reason?: string): void;
|
|
446
450
|
/**
|
|
447
451
|
* Drop the current socket (if any) and connect again immediately, resetting the
|
|
448
|
-
* backoff. Also restarts a `closed` client.
|
|
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.
|
|
449
454
|
*/
|
|
450
455
|
reconnect(): void;
|
|
451
456
|
/**
|
|
@@ -624,6 +629,12 @@ interface WebSocketFeeds<In> extends WebSocketTopics {
|
|
|
624
629
|
on(type: 'message', listener: (message: In, event: MessageEvent) => void): () => void;
|
|
625
630
|
/** The sequence number of the last message delivered on `topic`, while it's held. */
|
|
626
631
|
position(topic: string): number | undefined;
|
|
632
|
+
/**
|
|
633
|
+
* Forget the position of `topic`, or of every topic, e.g. on logout or when another user
|
|
634
|
+
* signs in: the next subscription sends `after: undefined`, so the server sends that user's
|
|
635
|
+
* messages from the start, and none is dropped as a duplicate of the previous user's.
|
|
636
|
+
*/
|
|
637
|
+
reset(topic?: string): void;
|
|
627
638
|
}
|
|
628
639
|
/**
|
|
629
640
|
* Subscribe to topics whose messages carry a sequence number, and get each message once, in
|
|
@@ -1152,6 +1163,13 @@ interface WebSocketRuns<Req, T> {
|
|
|
1152
1163
|
subscribe(listener: () => void): () => void;
|
|
1153
1164
|
/** Forget a run, aborting it first if it's streaming. */
|
|
1154
1165
|
delete(runId: string): void;
|
|
1166
|
+
/**
|
|
1167
|
+
* Forget every run, e.g. on logout or when another user signs in: their values, unsent start
|
|
1168
|
+
* requests and pending cancels, here and in `storage`. Sends nothing, so nothing of the
|
|
1169
|
+
* previous user's goes out on a later connection; `abort()` runs that should stop on the
|
|
1170
|
+
* server first, while connected.
|
|
1171
|
+
*/
|
|
1172
|
+
clear(): void;
|
|
1155
1173
|
/** Stop following runs, and release the connection. Remembered runs stay remembered. */
|
|
1156
1174
|
dispose(): void;
|
|
1157
1175
|
}
|
|
@@ -1422,6 +1440,13 @@ interface AgUiAgent<S> {
|
|
|
1422
1440
|
}): string;
|
|
1423
1441
|
/** Stop the run that's streaming, if any. */
|
|
1424
1442
|
abort(): void;
|
|
1443
|
+
/**
|
|
1444
|
+
* Forget the thread, e.g. on logout or when another user signs in: its runs (with
|
|
1445
|
+
* `runs.clear()`, which sends nothing), messages and state. The next run starts over from
|
|
1446
|
+
* `state`, with a new thread id unless `threadId` was given. `abort()` a streaming run first
|
|
1447
|
+
* to stop it on the server.
|
|
1448
|
+
*/
|
|
1449
|
+
reset(): void;
|
|
1425
1450
|
/** The thread as of the latest run. The same object until it changes. */
|
|
1426
1451
|
getSnapshot(): AgUiThread<S>;
|
|
1427
1452
|
/** Get notified when the thread changes. Compatible with `useSyncExternalStore`. */
|
package/dist/index.d.ts
CHANGED
|
@@ -80,6 +80,13 @@ interface AgUiAgent<S> {
|
|
|
80
80
|
}): string;
|
|
81
81
|
/** Stop the run that's streaming, if any. */
|
|
82
82
|
abort(): void;
|
|
83
|
+
/**
|
|
84
|
+
* Forget the thread, e.g. on logout or when another user signs in: its runs (with
|
|
85
|
+
* `runs.clear()`, which sends nothing), messages and state. The next run starts over from
|
|
86
|
+
* `state`, with a new thread id unless `threadId` was given. `abort()` a streaming run first
|
|
87
|
+
* to stop it on the server.
|
|
88
|
+
*/
|
|
89
|
+
reset(): void;
|
|
83
90
|
/** The thread as of the latest run. The same object until it changes. */
|
|
84
91
|
getSnapshot(): AgUiThread<S>;
|
|
85
92
|
/** Get notified when the thread changes. Compatible with `useSyncExternalStore`. */
|
|
@@ -118,7 +125,10 @@ type Status = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed';
|
|
|
118
125
|
interface Snapshot<In> {
|
|
119
126
|
/** Connection state. */
|
|
120
127
|
readonly status: Status;
|
|
121
|
-
/**
|
|
128
|
+
/**
|
|
129
|
+
* Most recent message (after `parse`/`json` and `schema`), kept across reconnects and
|
|
130
|
+
* cleared by `close()`.
|
|
131
|
+
*/
|
|
122
132
|
readonly lastMessage: In | undefined;
|
|
123
133
|
/**
|
|
124
134
|
* Consecutive failed attempts since the last stable connection. A connection that closes
|
|
@@ -522,9 +532,10 @@ interface WebSocketClient$1<In = unknown, Out = unknown> {
|
|
|
522
532
|
*/
|
|
523
533
|
connect(): void;
|
|
524
534
|
/**
|
|
525
|
-
* Close the connection and stop reconnecting. The status becomes `closed
|
|
526
|
-
*
|
|
527
|
-
* to start again. Closed while no hook
|
|
535
|
+
* Close the connection and stop reconnecting. The status becomes `closed`, and the send
|
|
536
|
+
* queue, a `migrate()` target and `lastMessage` are cleared, so call it on logout. Mounted
|
|
537
|
+
* hooks stay mounted; call `connect()` or `reconnect()` to start again. Closed while no hook
|
|
538
|
+
* holds it, the next hook to mount starts it again.
|
|
528
539
|
*
|
|
529
540
|
* Like `WebSocket.close()`, it throws for a code or reason the socket rejects (browsers take
|
|
530
541
|
* `1000` or `3000`–`4999`, and a reason up to 123 bytes), and then nothing has changed.
|
|
@@ -533,7 +544,8 @@ interface WebSocketClient$1<In = unknown, Out = unknown> {
|
|
|
533
544
|
close(code?: number, reason?: string): void;
|
|
534
545
|
/**
|
|
535
546
|
* Drop the current socket (if any) and connect again immediately, resetting the
|
|
536
|
-
* backoff. Also restarts a `closed` client.
|
|
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.
|
|
537
549
|
*/
|
|
538
550
|
reconnect(): void;
|
|
539
551
|
/**
|
|
@@ -832,6 +844,13 @@ interface WebSocketRuns$1<Req, T> {
|
|
|
832
844
|
subscribe(listener: () => void): () => void;
|
|
833
845
|
/** Forget a run, aborting it first if it's streaming. */
|
|
834
846
|
delete(runId: string): void;
|
|
847
|
+
/**
|
|
848
|
+
* Forget every run, e.g. on logout or when another user signs in: their values, unsent start
|
|
849
|
+
* requests and pending cancels, here and in `storage`. Sends nothing, so nothing of the
|
|
850
|
+
* previous user's goes out on a later connection; `abort()` runs that should stop on the
|
|
851
|
+
* server first, while connected.
|
|
852
|
+
*/
|
|
853
|
+
clear(): void;
|
|
835
854
|
/** Stop following runs, and release the connection. Remembered runs stay remembered. */
|
|
836
855
|
dispose(): void;
|
|
837
856
|
}
|
package/dist/outbox.cjs
CHANGED
|
@@ -78,7 +78,8 @@ function createWebSocketOutbox(client, options) {
|
|
|
78
78
|
const listeners = /* @__PURE__ */ new Set();
|
|
79
79
|
let loaded = false;
|
|
80
80
|
const removed = /* @__PURE__ */ new Set();
|
|
81
|
-
let
|
|
81
|
+
let clearedBeforeLoad = false;
|
|
82
|
+
let addedSinceClear;
|
|
82
83
|
const channel = typeof window !== "undefined" && typeof BroadcastChannel === "function" ? new BroadcastChannel(`react-websocket-outbox:${options.name}`) : void 0;
|
|
83
84
|
let disposed = false;
|
|
84
85
|
let release;
|
|
@@ -96,11 +97,17 @@ function createWebSocketOutbox(client, options) {
|
|
|
96
97
|
if (!loaded) removed.add(id);
|
|
97
98
|
if (entries.delete(id)) changed();
|
|
98
99
|
}
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Drop every entry held now, and its stored copy. Not by `createdAt`: that comes from the clock
|
|
102
|
+
* of whichever page added it, which can be ahead of this one's.
|
|
103
|
+
*/
|
|
104
|
+
function dropAll() {
|
|
105
|
+
if (!loaded) clearedBeforeLoad = true;
|
|
106
|
+
const held = [...entries.keys()];
|
|
107
|
+
if (!held.length) return;
|
|
108
|
+
entries = /* @__PURE__ */ new Map();
|
|
109
|
+
changed();
|
|
110
|
+
for (const id of held) storage.delete(id).catch(noop);
|
|
104
111
|
}
|
|
105
112
|
function forget(id) {
|
|
106
113
|
drop(id);
|
|
@@ -131,7 +138,8 @@ function createWebSocketOutbox(client, options) {
|
|
|
131
138
|
}
|
|
132
139
|
const ready = storage.load().then((records) => {
|
|
133
140
|
if (disposed) return;
|
|
134
|
-
|
|
141
|
+
for (const record of records) lastCreated = Math.max(lastCreated, record.createdAt);
|
|
142
|
+
entries = new Map([...records.filter((record) => !clearedBeforeLoad && !entries.has(record.id) && !removed.has(record.id)), ...entries.values()].sort((a, b) => a.createdAt - b.createdAt).map((record) => [record.id, {
|
|
135
143
|
...record,
|
|
136
144
|
sent: false
|
|
137
145
|
}]));
|
|
@@ -155,8 +163,10 @@ function createWebSocketOutbox(client, options) {
|
|
|
155
163
|
if (changes) changed();
|
|
156
164
|
}
|
|
157
165
|
if (channel) channel.onmessage = ({ data }) => {
|
|
158
|
-
if (data?.before)
|
|
159
|
-
|
|
166
|
+
if (data?.before) {
|
|
167
|
+
lastCreated = Math.max(lastCreated, data.before);
|
|
168
|
+
dropAll();
|
|
169
|
+
} else if (data?.id) drop(data.id);
|
|
160
170
|
};
|
|
161
171
|
const offs = [
|
|
162
172
|
() => channel?.close(),
|
|
@@ -187,6 +197,7 @@ function createWebSocketOutbox(client, options) {
|
|
|
187
197
|
...record,
|
|
188
198
|
sent: false
|
|
189
199
|
});
|
|
200
|
+
addedSinceClear?.add(id);
|
|
190
201
|
changed();
|
|
191
202
|
flush();
|
|
192
203
|
if (!entries.has(id)) return Promise.resolve(id);
|
|
@@ -194,10 +205,13 @@ function createWebSocketOutbox(client, options) {
|
|
|
194
205
|
},
|
|
195
206
|
remove: forget,
|
|
196
207
|
clear() {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
208
|
+
lastCreated = Math.max(Date.now(), lastCreated + 1);
|
|
209
|
+
const kept = addedSinceClear = /* @__PURE__ */ new Set();
|
|
210
|
+
dropAll();
|
|
211
|
+
channel?.postMessage({ before: lastCreated });
|
|
212
|
+
return storage.load().then((records) => Promise.all(records.filter((record) => !kept.has(record.id)).map((record) => storage.delete(record.id)))).then(() => {
|
|
213
|
+
if (addedSinceClear === kept) addedSinceClear = void 0;
|
|
214
|
+
});
|
|
201
215
|
},
|
|
202
216
|
getSnapshot: () => snapshot,
|
|
203
217
|
subscribe(listener) {
|
package/dist/outbox.cjs.map
CHANGED
|
@@ -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 // Entries created before this were cleared, here or in another tab: don't restore them.\n let clearedBefore = 0;\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 function dropBefore(before: number) {\n clearedBefore = Math.max(clearedBefore, before);\n let changes = false;\n for (const entry of entries.values()) {\n if (entry.createdAt < before) changes = entries.delete(entry.id);\n }\n if (changes) changed();\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 meanwhile are newer than the stored ones, unless one has the same id.\n entries = new Map(\n [\n ...records.filter(\n record =>\n record.createdAt >= clearedBefore &&\n !entries.has(record.id) &&\n !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 if (data?.before) dropBefore(data.before);\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 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 // At once, like `remove()`: waiting for the stored entries would send them first.\n const before = (lastCreated = Math.max(Date.now(), lastCreated + 1));\n dropBefore(before);\n channel?.postMessage({ before });\n // Including what other tabs stored, but not what's added from now on.\n return storage\n .load()\n .then(records =>\n Promise.all(\n records\n .filter(record => record.createdAt < before)\n .map(record => storage.delete(record.id))\n )\n )\n .then(noop);\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,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AAU,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.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,OA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ACJ,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
package/dist/outbox.js
CHANGED
|
@@ -77,7 +77,8 @@ function createWebSocketOutbox(client, options) {
|
|
|
77
77
|
const listeners = /* @__PURE__ */ new Set();
|
|
78
78
|
let loaded = false;
|
|
79
79
|
const removed = /* @__PURE__ */ new Set();
|
|
80
|
-
let
|
|
80
|
+
let clearedBeforeLoad = false;
|
|
81
|
+
let addedSinceClear;
|
|
81
82
|
const channel = typeof window !== "undefined" && typeof BroadcastChannel === "function" ? new BroadcastChannel(`react-websocket-outbox:${options.name}`) : void 0;
|
|
82
83
|
let disposed = false;
|
|
83
84
|
let release;
|
|
@@ -95,11 +96,17 @@ function createWebSocketOutbox(client, options) {
|
|
|
95
96
|
if (!loaded) removed.add(id);
|
|
96
97
|
if (entries.delete(id)) changed();
|
|
97
98
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
99
|
+
/**
|
|
100
|
+
* Drop every entry held now, and its stored copy. Not by `createdAt`: that comes from the clock
|
|
101
|
+
* of whichever page added it, which can be ahead of this one's.
|
|
102
|
+
*/
|
|
103
|
+
function dropAll() {
|
|
104
|
+
if (!loaded) clearedBeforeLoad = true;
|
|
105
|
+
const held = [...entries.keys()];
|
|
106
|
+
if (!held.length) return;
|
|
107
|
+
entries = /* @__PURE__ */ new Map();
|
|
108
|
+
changed();
|
|
109
|
+
for (const id of held) storage.delete(id).catch(noop);
|
|
103
110
|
}
|
|
104
111
|
function forget(id) {
|
|
105
112
|
drop(id);
|
|
@@ -130,7 +137,8 @@ function createWebSocketOutbox(client, options) {
|
|
|
130
137
|
}
|
|
131
138
|
const ready = storage.load().then((records) => {
|
|
132
139
|
if (disposed) return;
|
|
133
|
-
|
|
140
|
+
for (const record of records) lastCreated = Math.max(lastCreated, record.createdAt);
|
|
141
|
+
entries = new Map([...records.filter((record) => !clearedBeforeLoad && !entries.has(record.id) && !removed.has(record.id)), ...entries.values()].sort((a, b) => a.createdAt - b.createdAt).map((record) => [record.id, {
|
|
134
142
|
...record,
|
|
135
143
|
sent: false
|
|
136
144
|
}]));
|
|
@@ -154,8 +162,10 @@ function createWebSocketOutbox(client, options) {
|
|
|
154
162
|
if (changes) changed();
|
|
155
163
|
}
|
|
156
164
|
if (channel) channel.onmessage = ({ data }) => {
|
|
157
|
-
if (data?.before)
|
|
158
|
-
|
|
165
|
+
if (data?.before) {
|
|
166
|
+
lastCreated = Math.max(lastCreated, data.before);
|
|
167
|
+
dropAll();
|
|
168
|
+
} else if (data?.id) drop(data.id);
|
|
159
169
|
};
|
|
160
170
|
const offs = [
|
|
161
171
|
() => channel?.close(),
|
|
@@ -186,6 +196,7 @@ function createWebSocketOutbox(client, options) {
|
|
|
186
196
|
...record,
|
|
187
197
|
sent: false
|
|
188
198
|
});
|
|
199
|
+
addedSinceClear?.add(id);
|
|
189
200
|
changed();
|
|
190
201
|
flush();
|
|
191
202
|
if (!entries.has(id)) return Promise.resolve(id);
|
|
@@ -193,10 +204,13 @@ function createWebSocketOutbox(client, options) {
|
|
|
193
204
|
},
|
|
194
205
|
remove: forget,
|
|
195
206
|
clear() {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
207
|
+
lastCreated = Math.max(Date.now(), lastCreated + 1);
|
|
208
|
+
const kept = addedSinceClear = /* @__PURE__ */ new Set();
|
|
209
|
+
dropAll();
|
|
210
|
+
channel?.postMessage({ before: lastCreated });
|
|
211
|
+
return storage.load().then((records) => Promise.all(records.filter((record) => !kept.has(record.id)).map((record) => storage.delete(record.id)))).then(() => {
|
|
212
|
+
if (addedSinceClear === kept) addedSinceClear = void 0;
|
|
213
|
+
});
|
|
200
214
|
},
|
|
201
215
|
getSnapshot: () => snapshot,
|
|
202
216
|
subscribe(listener) {
|
package/dist/outbox.js.map
CHANGED
|
@@ -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 // Entries created before this were cleared, here or in another tab: don't restore them.\n let clearedBefore = 0;\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 function dropBefore(before: number) {\n clearedBefore = Math.max(clearedBefore, before);\n let changes = false;\n for (const entry of entries.values()) {\n if (entry.createdAt < before) changes = entries.delete(entry.id);\n }\n if (changes) changed();\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 meanwhile are newer than the stored ones, unless one has the same id.\n entries = new Map(\n [\n ...records.filter(\n record =>\n record.createdAt >= clearedBefore &&\n !entries.has(record.id) &&\n !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 if (data?.before) dropBefore(data.before);\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 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 // At once, like `remove()`: waiting for the stored entries would send them first.\n const before = (lastCreated = Math.max(Date.now(), lastCreated + 1));\n dropBefore(before);\n channel?.postMessage({ before });\n // Including what other tabs stored, but not what's added from now on.\n return storage\n .load()\n .then(records =>\n Promise.all(\n records\n .filter(record => record.createdAt < before)\n .map(record => storage.delete(record.id))\n )\n )\n .then(noop);\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;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|
|
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,O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I,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/replay.d.cts
CHANGED
|
@@ -121,4 +121,5 @@ export declare function createRecordingWebSocket(options?: {
|
|
|
121
121
|
*/
|
|
122
122
|
export declare function createReplayWebSocket(recording: WebSocketRecording, options?: ReplayOptions): ReplayWebSocket;
|
|
123
123
|
//#endregion
|
|
124
|
+
export {};
|
|
124
125
|
//# sourceMappingURL=replay.d.cts.map
|
package/dist/replay.d.ts
CHANGED
|
@@ -121,4 +121,5 @@ export declare function createRecordingWebSocket(options?: {
|
|
|
121
121
|
*/
|
|
122
122
|
export declare function createReplayWebSocket(recording: WebSocketRecording, options?: ReplayOptions): ReplayWebSocket;
|
|
123
123
|
//#endregion
|
|
124
|
+
export {};
|
|
124
125
|
//# sourceMappingURL=replay.d.ts.map
|
package/dist/tabs.cjs
CHANGED
|
@@ -247,7 +247,7 @@ function createTabsWebSocket(options = {}) {
|
|
|
247
247
|
inner.onclose = (event) => this.#end(event.code, event.reason, event.wasClean);
|
|
248
248
|
return;
|
|
249
249
|
}
|
|
250
|
-
const key = `react-websocket-tabs:${this.url}\u0000${JSON.stringify(protocols ?? null)}`;
|
|
250
|
+
const key = `react-websocket-tabs:${options.session ? `session=${encodeURIComponent(options.session() ?? "")}:` : ""}${this.url}\u0000${JSON.stringify(protocols ?? null)}`;
|
|
251
251
|
agent(key, this.url, protocols);
|
|
252
252
|
const channel = this.#channel = new BroadcastChannel(key);
|
|
253
253
|
channel.onmessage = (event) => this.#signal(event.data);
|