@tallyui/database 1.0.0 → 3.0.0-next.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.
@@ -0,0 +1,149 @@
1
+ import type { RxCollection } from 'rxdb';
2
+ import { BehaviorSubject, type Observable } from 'rxjs';
3
+
4
+ import type { CatalogueReconcileEntry, FingerprintReconcileAdapter, SyncContext } from '@tallyui/core';
5
+
6
+ import { startCatalogueRunner, type CatalogueReconcileSummary } from './catalogue-reconcile';
7
+
8
+ export interface StartFingerprintReconcileOptions<Doc> {
9
+ /** The replicated collection. Read only. */
10
+ collection: RxCollection<Doc>;
11
+ adapter: FingerprintReconcileAdapter<Doc>;
12
+ context: SyncContext;
13
+ /** The app's `() => replication.reSync()`. */
14
+ reSync: () => void;
15
+ /** Delay before the first gate check; `null` (default) skips it and checks hourly. */
16
+ startDelayMs?: number | null;
17
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
18
+ intervalMs?: number;
19
+ /** @deprecated Ignored: the request budget bounds a pass, so a large catalogue never truncates (#248). */
20
+ maxPages?: number;
21
+ /** Injection for tests; default Date.now. Stamps `lastResultAt`/`lastErrorAt`. */
22
+ now?: () => number;
23
+ /**
24
+ * The local document holding this runner's gate (default 'fingerprint-reconcile').
25
+ * Two fingerprint runners on one collection (prices and calculated prices) each need their own.
26
+ */
27
+ stateId?: string;
28
+ }
29
+
30
+ export interface FingerprintReconcileResult {
31
+ pages: number;
32
+ compared: number;
33
+ queued: number;
34
+ /** Always false now that no page cap applies. */
35
+ truncated: boolean;
36
+ /**
37
+ * Local products the remote side did not report in a complete pass (they are skipped); 0 on a failed or resumed
38
+ * pass, and 0 when the adapter yielded no pages at all (e.g. base-only mode, no pricing context) -- that is not
39
+ * the same as everything being unsellable. A channel that lists nothing still reads one empty page, so it
40
+ * correctly reports everything as unreported.
41
+ * For `calculatedPrices`, the products the sales channel does not list, which are not sellable here. A channel
42
+ * misconfiguration shows up as a large number, not a silent empty till.
43
+ */
44
+ unreported: number;
45
+ }
46
+
47
+ /**
48
+ * The runner's state; entirely in memory. The result is current only when
49
+ * `lastResultAt > (lastErrorAt ?? 0)`; show `unreported` from a stale result
50
+ * as stale. See `isFingerprintResultCurrent`.
51
+ */
52
+ export interface FingerprintReconcileState {
53
+ running: boolean;
54
+ lastResult?: FingerprintReconcileResult;
55
+ lastResultAt?: number;
56
+ lastError?: unknown;
57
+ lastErrorAt?: number;
58
+ }
59
+
60
+ /** True when `state.lastResult` is current, i.e. newer than the last failure, if any. */
61
+ export function isFingerprintResultCurrent(state: FingerprintReconcileState): boolean {
62
+ return state.lastResultAt !== undefined && state.lastResultAt > (state.lastErrorAt ?? 0);
63
+ }
64
+
65
+ /**
66
+ * The id wrapper's deletion proof: a pass-through that confirms every candidate. The wrapper hands
67
+ * each to the reconcile feed as a plain `{ id, local }` entry, not a tombstone, and the feed's by-id
68
+ * re-read (`fetchByIds`) tombstones only what does not come back: that refetch is the proof.
69
+ */
70
+ export function confirmAll<Doc>(collection: RxCollection<Doc>) {
71
+ const primary = collection.schema.primaryPath as string;
72
+ return async (locals: Doc[]) => locals.map((doc) => (doc as Record<string, unknown>)[primary] as string);
73
+ }
74
+
75
+ /**
76
+ * An old adapter's pages as catalogue pages. The cursor is the count of pages read. Old adapters
77
+ * cannot start mid-way, so a resumed pass re-reads the pages before its cursor; each comes back
78
+ * empty, so the runner takes a budget slot for its request but compares nothing, and counts it as a page.
79
+ */
80
+ export async function* skipPages<Page>(
81
+ pages: AsyncIterable<Page>, entries: (page: Page) => CatalogueReconcileEntry[], from = 0,
82
+ ): AsyncIterable<{ entries: CatalogueReconcileEntry[]; cursor: number }> {
83
+ let read = 0;
84
+ for await (const page of pages) {
85
+ read++;
86
+ yield { entries: read <= from ? [] : entries(page), cursor: Math.max(read, from) };
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Compares a remote fingerprint per product against the local `collection`
92
+ * and queues disagreeing products for the collection's pull (ADR-060), as a
93
+ * wrapper over the catalogue runner (#248). Never deletes: every entry is
94
+ * `refreshOnly`, and a product the remote side doesn't report is only counted
95
+ * as `unreported`. Passes follow the persisted daily gate within a request
96
+ * budget; the app may still call `reconcile()` on demand. A call during a pass
97
+ * queues one follow-up pass (later calls share it).
98
+ */
99
+ export function startFingerprintReconcile<Doc>({
100
+ adapter, reSync, startDelayMs = null, maxPages: _ignored, stateId = 'fingerprint-reconcile', ...options
101
+ }: StartFingerprintReconcileOptions<Doc>): {
102
+ reconcile(): Promise<FingerprintReconcileResult>;
103
+ stop(): void;
104
+ state$: Observable<FingerprintReconcileState>;
105
+ } {
106
+ let queued = 0;
107
+ let pending = false;
108
+ const { request, stop, state$: catalogue$ } = startCatalogueRunner<Doc, number>({
109
+ ...options, startDelayMs, stateId, keepCandidates: true,
110
+ // Only touch reSync when something reached the pull.
111
+ reSync: () => { if (pending) { pending = false; reSync(); } },
112
+ log: (event) => { if (event.type === 'pass-started') queued = 0; },
113
+ adapter: {
114
+ fetchPages: (context, from) => skipPages(adapter.fetchPages(context),
115
+ (page) => [...page].map(([key, fingerprint]) => ({ key, fingerprint })), from),
116
+ fingerprint: (doc) => adapter.fingerprint(doc),
117
+ // The feed's request size, so the runner budgets a page's refetch by its requests (#307).
118
+ refetchBatchSize: adapter.refetchBatchSize,
119
+ // It never deletes: keepCandidates only counts the products the listing did not name (`unreported`), before the
120
+ // brake and confirmGone, so this is never called; a call is a runner bug, and it fails the pass loudly.
121
+ confirmGone: async () => { throw new Error('The fingerprint reconcile never deletes; confirmGone must not be called.'); },
122
+ // refreshOnly: a missing re-fetch is skipped, never tombstoned (ADR-060). A product the till lacks is left to the pull.
123
+ enqueue: (entries) => {
124
+ const known = entries.flatMap(({ key, local }) => (local ? [{ id: key, local, refreshOnly: true as const }] : []));
125
+ if (!known.length) return;
126
+ queued += known.length;
127
+ pending = true;
128
+ adapter.enqueue(known);
129
+ },
130
+ },
131
+ });
132
+ const toResult = ({ pages, compared, unlisted }: CatalogueReconcileSummary): FingerprintReconcileResult =>
133
+ ({ pages, compared, queued, truncated: false, unreported: pages > 0 ? unlisted : 0 });
134
+
135
+ // Mapped as each pass ends, while `queued` is still that pass's count.
136
+ const state = new BehaviorSubject<FingerprintReconcileState>({ running: false });
137
+ let summary: CatalogueReconcileSummary | undefined;
138
+ let result: FingerprintReconcileResult | undefined;
139
+ catalogue$.subscribe({
140
+ next: ({ lastResult, ...rest }) => {
141
+ if (lastResult !== summary) { summary = lastResult; result = lastResult && toResult(lastResult); }
142
+ state.next(result ? { ...rest, lastResult: result } : rest);
143
+ },
144
+ complete: () => state.complete(),
145
+ });
146
+ // `.then` is attached at call time, so it reads this pass's counts before a follow-up starts.
147
+ const reconcile = () => request().then(toResult);
148
+ return { reconcile, stop, state$: state.asObservable() };
149
+ }
@@ -0,0 +1,80 @@
1
+ import type { RxCollection } from 'rxdb';
2
+ import type { IdReconcileAdapter, SyncContext } from '@tallyui/core';
3
+
4
+ import { startCatalogueRunner } from './catalogue-reconcile';
5
+ import { confirmAll, skipPages } from './fingerprint-reconcile';
6
+
7
+ export interface StartIdReconcileOptions<Doc> {
8
+ /** The replicated products collection. Read only. */
9
+ collection: RxCollection<Doc>;
10
+ adapter: IdReconcileAdapter<Doc>;
11
+ context: SyncContext;
12
+ /** The app's `() => replication.reSync()`. */
13
+ reSync: () => void;
14
+ /** Delay before the first gate check (default 5000); `null` skips it and checks hourly. */
15
+ startDelayMs?: number | null;
16
+ /** Time from the last completed pass to the next (default 86400000, 24 hours). */
17
+ intervalMs?: number;
18
+ /** @deprecated Ignored: the request budget bounds a pass, so a large catalogue never truncates (#248). */
19
+ maxPages?: number;
20
+ /**
21
+ * The brake applies once tombstones exceed this share of local
22
+ * products (default 0.2), unless `allowMassDelete` is set.
23
+ */
24
+ maxDeleteShare?: number;
25
+ /** Explicit override for a genuine purge; disables the mass-delete brake. */
26
+ allowMassDelete?: boolean;
27
+ /** The local document holding this runner's gate (default 'id-reconcile'). */
28
+ stateId?: string;
29
+ }
30
+
31
+ /** `truncated` is always false now that no page cap applies. */
32
+ export interface IdReconcileResult { pages: number; queued: number; truncated: boolean; braked: boolean }
33
+
34
+ /**
35
+ * Compares live product/variant ids against the local `products` collection
36
+ * and queues disagreeing documents for the collection's pull (ADR-060), as a
37
+ * wrapper over the catalogue runner (#248): a product whose variant ids differ
38
+ * is refetched page by page; a product missing remotely is queued for deletion
39
+ * only after an uninterrupted pass and under the mass-delete brake. Passes
40
+ * follow the persisted daily gate within a request budget. A call during a
41
+ * pass queues one follow-up pass (later calls share it).
42
+ */
43
+ export function startIdReconcile<Doc>({
44
+ adapter, reSync, startDelayMs = 5_000, maxPages: _ignored, stateId = 'id-reconcile', ...options
45
+ }: StartIdReconcileOptions<Doc>): { reconcileIds(): Promise<IdReconcileResult>; stop(): void } {
46
+ const fingerprint = (ids: string[]) => [...ids].sort().join('\n');
47
+ let queued = 0;
48
+ let braked = false;
49
+ let pending = false;
50
+ const { request, stop } = startCatalogueRunner<Doc, number>({
51
+ ...options, startDelayMs, stateId,
52
+ // Only touch reSync when something reached the pull.
53
+ reSync: () => { if (pending) { pending = false; reSync(); } },
54
+ log: (event) => {
55
+ if (event.type === 'pass-started') { queued = 0; braked = false; }
56
+ if (event.type === 'kept' && event.reason === 'brake') braked = true;
57
+ },
58
+ adapter: {
59
+ fetchPages: (context, from) => skipPages(adapter.fetchPages(context),
60
+ (rows) => rows.map((row) => ({ key: row.id, fingerprint: fingerprint(row.variantIds) })), from),
61
+ fingerprint: (doc) => fingerprint(adapter.variantIds(doc)),
62
+ // The feed's request size, so the runner budgets a page's refetch by its requests (#307).
63
+ refetchBatchSize: adapter.refetchBatchSize,
64
+ // The proof is the feed's by-id re-read: every candidate is confirmed here and reaches the feed below as a
65
+ // plain entry, never `tombstone: true`, so the feed tombstones it only when fetchByIds does not return it.
66
+ confirmGone: confirmAll(options.collection),
67
+ // The old entry shape. A product the till lacks is left to the pull, as before.
68
+ enqueue: (entries) => {
69
+ const known = entries.flatMap(({ key, local }) => (local ? [{ id: key, local }] : []));
70
+ if (!known.length) return;
71
+ queued += known.length;
72
+ pending = true;
73
+ adapter.enqueue(known);
74
+ },
75
+ },
76
+ });
77
+ // `.then` is attached at call time, so it reads this pass's counts before a follow-up starts.
78
+ const reconcileIds = () => request().then(({ pages }) => ({ pages, queued, truncated: false, braked }));
79
+ return { reconcileIds, stop };
80
+ }
package/src/index.ts CHANGED
@@ -1,7 +1,28 @@
1
- export { createTallyDatabase } from './create-db';
1
+ export { createTallyDatabase, getStorageHealth } from './create-db';
2
2
  export type { TallyDatabase, CreateDatabaseOptions } from './create-db';
3
+ export { connectorCollection } from './connector-collection';
3
4
 
4
5
  export { getStorage } from './storage';
5
6
 
7
+ export { WEB_STORAGE_ENGINE, REQUIRED_MULTI_INSTANCE_BY_ENGINE } from './engine';
8
+ export { STORAGE_WRITE_STALL_MS, STORAGE_READ_WATCHDOG_MS, isStorageWorkerFailure, withStorageWatchdog } from './storage-watchdog';
9
+ export type { StorageHealth, StorageWatchdogOptions } from './storage-watchdog';
10
+
6
11
  export { startReplication } from './replication';
7
- export type { StartReplicationOptions } from './replication';
12
+ export type { StartReplicationOptions, TallyReplicationState } from './replication';
13
+
14
+ export { startLiveTab } from './live-tab';
15
+ export type { LiveTabState, LiveTabOptions, LiveTabHandle } from './live-tab';
16
+
17
+ export { startStockReconcile } from './reconcile';
18
+ export type { StartStockReconcileOptions, StockReconcileResult, StockReconcileState } from './reconcile';
19
+ export { startCatalogueReconcile, shouldReconcileAfterGap, CATALOGUE_OFFLINE_GAP_MS } from './catalogue-reconcile';
20
+ export type {
21
+ StartCatalogueReconcileOptions, CatalogueReconcileEvent, CatalogueReconcileState, CatalogueReconcileSummary,
22
+ } from './catalogue-reconcile';
23
+ export { startIdReconcile } from './id-reconcile';
24
+ export type { StartIdReconcileOptions, IdReconcileResult } from './id-reconcile';
25
+ export { startFingerprintReconcile, isFingerprintResultCurrent } from './fingerprint-reconcile';
26
+ export type { StartFingerprintReconcileOptions, FingerprintReconcileResult, FingerprintReconcileState } from './fingerprint-reconcile';
27
+ export { STOCK_LEVELS_COLLECTION, STOCK_LEVELS_LAST_PASS, stockLevelsCollection, stockLevelsSchema } from './stock-levels';
28
+ export type { StockLevelRow } from './stock-levels';
@@ -0,0 +1,280 @@
1
+ import { BehaviorSubject, type Observable } from 'rxjs';
2
+
3
+ /**
4
+ * ADR-061: exactly one live tab per store, and a second tab never opens
5
+ * storage. `acquiring` while a hand-over is in flight, `live` while this tab
6
+ * holds the lock, `parked` after handing over, `blocked` when the live tab
7
+ * never answered and the user must close it.
8
+ */
9
+ export type LiveTabState = 'acquiring' | 'live' | 'parked' | 'blocked';
10
+
11
+ type LiveTabChannel = Pick<BroadcastChannel, 'postMessage' | 'close'> & {
12
+ onmessage: ((event: { data: unknown }) => void) | null;
13
+ };
14
+
15
+ interface HandoverMessage {
16
+ type: 'handover-request' | 'handover-ack';
17
+ id: string;
18
+ }
19
+
20
+ function isHandoverMessage(data: unknown): data is HandoverMessage {
21
+ const msg = data as Partial<HandoverMessage> | null;
22
+ return (
23
+ typeof msg === 'object' &&
24
+ msg !== null &&
25
+ (msg.type === 'handover-request' || msg.type === 'handover-ack') &&
26
+ typeof msg.id === 'string'
27
+ );
28
+ }
29
+
30
+ export interface LiveTabOptions {
31
+ /** Store scope; the lock and channel are named `tally-live-tab:<scope>`. */
32
+ scope: string;
33
+ /** Called on the live tab before it hands over: close the database, stop workers. Awaited. */
34
+ onPark: () => void | Promise<void>;
35
+ /** True while a sale, payment or storage write is in flight; the hand-over waits for false. */
36
+ isBusy?: () => boolean;
37
+ /** Longest the live tab defers a hand-over while busy (default 10_000 ms). */
38
+ maxDeferMs?: number;
39
+ /** How long a new tab waits for the live tab to acknowledge (default 3_000 ms). */
40
+ ackTimeoutMs?: number;
41
+ /** Injection for tests and non-browser hosts; default globalThis.navigator?.locks and globalThis.BroadcastChannel. */
42
+ locks?: Pick<LockManager, 'request'>;
43
+ createChannel?: (name: string) => LiveTabChannel;
44
+ /** Injection for tests; default globalThis. Source of `pagehide`/`pageshow`. */
45
+ events?: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>;
46
+ /** Injection for tests; default Date.now. Wall clock for the busy-defer cap below. */
47
+ now?: () => number;
48
+ }
49
+
50
+ export interface LiveTabHandle {
51
+ state$: Observable<LiveTabState>;
52
+ /** Ask the live tab to hand over, and take the lock. Used on start and by the parked screen's "Use here" button. */
53
+ takeOver(): Promise<LiveTabState>;
54
+ /** Release the lock and close the channel (sign-out, unmount). */
55
+ stop(): void;
56
+ }
57
+
58
+ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
59
+
60
+ /**
61
+ * Coordinates one live tab per store (ADR-061) over a Web Lock and a
62
+ * BroadcastChannel, both named `tally-live-tab:<scope>`.
63
+ *
64
+ * On platforms without Web Locks (React Native, Node, tests: `locks` is
65
+ * undefined) a tab is simply live at once, since native and Electron have
66
+ * one window per store.
67
+ */
68
+ export function startLiveTab(options: LiveTabOptions): LiveTabHandle {
69
+ const {
70
+ scope,
71
+ onPark,
72
+ isBusy,
73
+ maxDeferMs = 10_000,
74
+ ackTimeoutMs = 3_000,
75
+ locks = globalThis.navigator?.locks,
76
+ createChannel = (name) => new BroadcastChannel(name) as unknown as LiveTabChannel,
77
+ events = globalThis,
78
+ now = Date.now,
79
+ } = options;
80
+ const state = new BehaviorSubject<LiveTabState>('acquiring');
81
+
82
+ if (!locks) {
83
+ state.next('live');
84
+ return { state$: state.asObservable(), takeOver: () => Promise.resolve('live'), stop: () => state.complete() };
85
+ }
86
+
87
+ const name = `tally-live-tab:${scope}`;
88
+ let channel = createChannel(name);
89
+ let releaseLock: (() => void) | undefined;
90
+ let parking = false;
91
+ let requestCounter = 0;
92
+ let stopped = false;
93
+ let deferBlockedTimer: ReturnType<typeof setTimeout> | undefined;
94
+ // Aborts every locks.request() in flight; resume() swaps in a fresh one for the next round.
95
+ let abortController = new AbortController();
96
+ // Unique per coordinator instance, so two tabs requesting at once never mint the same id
97
+ // (a shared id would let one ack satisfy both waiters).
98
+ const tabToken = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
99
+ const ackWaiters = new Map<string, () => void>();
100
+
101
+ /** Holds the lock (if granted) until `releaseLock()` resolves the held promise. */
102
+ // `controller` defaults to the one current when called, so a late grant for a round before a resume is told apart from the current round.
103
+ const requestLock = (lockOptions: Omit<LockOptions, 'signal'>, controller = abortController): Promise<boolean> =>
104
+ new Promise<boolean>((resolve, reject) => {
105
+ // Browsers reject `signal` with `ifAvailable` (NotSupportedError), so the probe carries none; a late probe grant is still caught below by `stopped`/the stale-controller check.
106
+ locks
107
+ .request(name, lockOptions.ifAvailable ? lockOptions : { ...lockOptions, signal: controller.signal }, (lock) => {
108
+ // Stopped, or a stale grant from before a suspend/resume: hand the lock straight back (a non-promise return releases it at once) and never go live.
109
+ if (!lock || stopped || controller !== abortController) {
110
+ resolve(false);
111
+ return undefined;
112
+ }
113
+ resolve(true);
114
+ return new Promise<void>((release) => {
115
+ releaseLock = release;
116
+ });
117
+ })
118
+ .catch((error: unknown) => {
119
+ if (controller.signal.aborted) resolve(false);
120
+ else reject(error);
121
+ });
122
+ });
123
+
124
+ const waitForAck = (id: string): Promise<boolean> =>
125
+ new Promise<boolean>((resolve) => {
126
+ const timer = setTimeout(() => {
127
+ ackWaiters.delete(id);
128
+ resolve(false);
129
+ }, ackTimeoutMs);
130
+ ackWaiters.set(id, () => {
131
+ clearTimeout(timer);
132
+ ackWaiters.delete(id);
133
+ resolve(true);
134
+ });
135
+ });
136
+
137
+ const handleHandoverRequest = async (id: string) => {
138
+ if (state.value !== 'live' || parking) return;
139
+ parking = true;
140
+ channel.postMessage({ type: 'handover-ack', id });
141
+ try {
142
+ // Wall clock, not a count of sleeps: this tab is in the background right now, and
143
+ // browsers throttle background timers to ~1 s or more, so each sleep(100) can take
144
+ // far longer than requested and a sleep count would blow well past maxDeferMs.
145
+ const start = now();
146
+ while (isBusy?.() && now() - start < maxDeferMs) await sleep(100);
147
+ try {
148
+ await onPark();
149
+ } catch (error) {
150
+ // Reload is the recovery, so a broken onPark still parks and frees the lock.
151
+ console.warn(`live-tab: onPark failed for scope "${scope}"; parking anyway.`, error);
152
+ }
153
+ } finally {
154
+ releaseLock?.();
155
+ releaseLock = undefined;
156
+ parking = false;
157
+ state.next('parked');
158
+ }
159
+ };
160
+
161
+ const handleChannelMessage = (event: { data: unknown }) => {
162
+ if (!isHandoverMessage(event.data)) return;
163
+ if (event.data.type === 'handover-ack') ackWaiters.get(event.data.id)?.();
164
+ else void handleHandoverRequest(event.data.id);
165
+ };
166
+ channel.onmessage = handleChannelMessage;
167
+
168
+ // Shared by overlapping takeOver() calls, so a double tap doesn't race two
169
+ // hand-over requests against each other (like runners sharing a relay pass).
170
+ let inFlightTakeOver: Promise<LiveTabState> | undefined;
171
+
172
+ const performTakeOver = async (): Promise<LiveTabState> => {
173
+ state.next('acquiring');
174
+ if (await requestLock({ ifAvailable: true })) {
175
+ state.next('live');
176
+ return 'live';
177
+ }
178
+ if (stopped) return state.value;
179
+
180
+ const id = `${tabToken}-${++requestCounter}`;
181
+ // Register the waiter before posting: an ack can arrive synchronously.
182
+ const acked = waitForAck(id);
183
+ channel.postMessage({ type: 'handover-request', id });
184
+ // Queue for the lock at once, racing the ack: the live tab may already be closing
185
+ // (StrictMode's stop-then-restart, a closing page), so a lock that frees within
186
+ // milliseconds is taken straight away instead of waiting out ackTimeoutMs.
187
+ // No deadline on the request itself: only stop() gives up waiting.
188
+ const gotLockPromise = requestLock({});
189
+ const lockFirst = await Promise.race([gotLockPromise.then(() => true), acked.then(() => false)]);
190
+
191
+ if (lockFirst) {
192
+ ackWaiters.delete(id);
193
+ } else if (await acked) {
194
+ // Acked: shown as blocked once the old defer+ack deadline passes, but keeps waiting.
195
+ deferBlockedTimer = setTimeout(() => state.next('blocked'), maxDeferMs + ackTimeoutMs);
196
+ } else {
197
+ state.next('blocked');
198
+ }
199
+ if (stopped) return state.value;
200
+
201
+ const gotLock = await gotLockPromise;
202
+ clearTimeout(deferBlockedTimer);
203
+ deferBlockedTimer = undefined;
204
+ if (stopped) return state.value;
205
+ state.next(gotLock ? 'live' : 'blocked');
206
+ return gotLock ? 'live' : 'blocked';
207
+ };
208
+
209
+ const takeOver = (): Promise<LiveTabState> => {
210
+ // Stopped: nothing left to ask for or hold.
211
+ if (stopped) return Promise.resolve(state.value);
212
+ // Already holding the lock: nothing to ask for, and trying again would
213
+ // fail ifAvailable against our own held lock and post a request nobody answers.
214
+ if (state.value === 'live') return Promise.resolve('live');
215
+ if (!inFlightTakeOver) {
216
+ inFlightTakeOver = performTakeOver().finally(() => {
217
+ inFlightTakeOver = undefined;
218
+ });
219
+ }
220
+ return inFlightTakeOver;
221
+ };
222
+
223
+ // pagehide: release the lock and park, but never complete state$ or touch the listeners.
224
+ const suspend = () => {
225
+ stopped = true;
226
+ abortController.abort();
227
+ releaseLock?.();
228
+ releaseLock = undefined;
229
+ ackWaiters.clear();
230
+ clearTimeout(deferBlockedTimer);
231
+ deferBlockedTimer = undefined;
232
+ channel.onmessage = null;
233
+ channel.close();
234
+ state.next('parked');
235
+ };
236
+
237
+ // bfcache restore: fresh controller and channel for a clean round, then re-acquire.
238
+ const resume = () => {
239
+ abortController = new AbortController();
240
+ channel = createChannel(name);
241
+ channel.onmessage = handleChannelMessage;
242
+ stopped = false;
243
+ void takeOver().catch((error) => {
244
+ console.warn(`live-tab: takeOver failed for scope "${scope}".`, error);
245
+ state.next('blocked');
246
+ });
247
+ };
248
+
249
+ const handlePageShow = (event: Event) => {
250
+ if ((event as PageTransitionEvent).persisted && stopped) resume();
251
+ };
252
+
253
+ const handlePageHide = () => {
254
+ suspend();
255
+ // Best-effort, not awaited (pagehide can't wait): frees the OPFS handles for another
256
+ // tab while this page sits in the bfcache; reload is still the recovery if it fails.
257
+ void Promise.resolve().then(onPark).catch((error: unknown) => {
258
+ console.warn(`live-tab: onPark failed for scope "${scope}" on pagehide.`, error);
259
+ });
260
+ };
261
+
262
+ const stop = () => {
263
+ suspend();
264
+ events.removeEventListener?.('pagehide', handlePageHide);
265
+ events.removeEventListener?.('pageshow', handlePageShow);
266
+ state.complete();
267
+ };
268
+
269
+ // A reload or a closing page never sends an ack; pageshow recovers after a bfcache restore.
270
+ events.addEventListener?.('pagehide', handlePageHide);
271
+ events.addEventListener?.('pageshow', handlePageShow);
272
+
273
+ // Start. A rejection here (a real locks.request() error, not an abort) still resolves a state.
274
+ void takeOver().catch((error) => {
275
+ console.warn(`live-tab: takeOver failed for scope "${scope}".`, error);
276
+ state.next('blocked');
277
+ });
278
+
279
+ return { state$: state.asObservable(), takeOver, stop };
280
+ }
@@ -0,0 +1,19 @@
1
+ /** Runs `run` for each trigger: idle starts a pass; during a pass, one follow-up is queued (later triggers share it). */
2
+ export function createPassQueue<T>(run: () => Promise<T>): () => Promise<T> {
3
+ let current: Promise<T> | undefined;
4
+ let queued: Promise<T> | undefined;
5
+
6
+ const trigger = (): Promise<T> => {
7
+ if (!current) return (current = run().finally(() => { current = undefined; }));
8
+ if (!queued) {
9
+ // Wait for the in-flight pass to settle, ignoring its rejection here: the
10
+ // caller that started it handles that rejection on its own promise. By the
11
+ // time this fires, `current`'s finally above has already cleared it, so
12
+ // clearing `queued` first and re-triggering starts a fresh pass, not a reuse.
13
+ queued = current.catch(() => {}).then(() => { queued = undefined; return trigger(); });
14
+ }
15
+ return queued;
16
+ };
17
+
18
+ return trigger;
19
+ }