@aglyn/tenant-feature-instance 1.15.1 → 1.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-feature-instance",
3
- "version": "1.15.1",
3
+ "version": "1.15.2",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.15.1",
29
- "@aglyn/shared-data-enums": "1.15.1",
30
- "@aglyn/shared-ui-jsx": "1.15.1",
31
- "@aglyn/shared-util-email": "1.15.1",
32
- "@aglyn/shared-util-http": "1.15.1",
33
- "@aglyn/shared-util-timestamp": "1.15.1",
28
+ "@aglyn/aglyn": "1.15.2",
29
+ "@aglyn/shared-data-enums": "1.15.2",
30
+ "@aglyn/shared-ui-jsx": "1.15.2",
31
+ "@aglyn/shared-util-email": "1.15.2",
32
+ "@aglyn/shared-util-http": "1.15.2",
33
+ "@aglyn/shared-util-timestamp": "1.15.2",
34
34
  "@swc/helpers": "0.5.23",
35
35
  "lodash-es": "^4.18.1",
36
36
  "mobx": "^7.0.5"
@@ -365,9 +365,10 @@ export declare function createWedgeEscalation(deps: WedgeEscalationDeps): () =>
365
365
  * server and nothing typed into it has been read back. And it is waiting on the
366
366
  * same lock either way: its persistence cannot start while another tab's
367
367
  * transaction holds every store (the booting tab had no `clientMetadata` row
368
- * 17 s in). So once, about {@link BOOT_WEDGE_CHECK_DELAY_MS} after the client
368
+ * 17 s in). So from about {@link BOOT_WEDGE_CHECK_DELAY_MS} after the client
369
369
  * is created, a visible online tab whose client has not heard from the server
370
- * reads the lease, and a store that stays locked for
370
+ * reads the lease every {@link BOOT_WEDGE_RECHECK_MS} for up to
371
+ * {@link BOOT_WEDGE_WINDOW_MS}, and a store that stays locked for
371
372
  * {@link BOOT_WEDGE_LOCK_MS} moves it to the memory cache straight away,
372
373
  * sharing the lock with the tabs that open next (AGL-4090).
373
374
  *
@@ -380,7 +381,9 @@ export declare function createWedgeEscalation(deps: WedgeEscalationDeps): () =>
380
381
  * - **Only when someone is looking.** A tab opened in the background runs the
381
382
  * check when it is first shown, which is when its spinner starts costing
382
383
  * anyone anything.
383
- * - **Once per tab.** Never on a tab already on the fallback.
384
+ * - **Until answered, then never again.** The reads stop at the first server
385
+ * answer or at the end of the window, and never run on a tab already on the
386
+ * fallback.
384
387
  *
385
388
  * A false verdict costs a reload of a page with nothing on it, onto the memory
386
389
  * cache, which every lock verdict already costs today, 30 s later.
@@ -392,6 +395,20 @@ export declare const BOOT_WEDGE_CHECK_DELAY_MS = 2000;
392
395
  * 1-5 ms on the same production cache once the lock had lifted.
393
396
  */
394
397
  export declare const BOOT_WEDGE_LOCK_MS = 3000;
398
+ /**
399
+ * How often a booting tab reads the lease again while the server has not
400
+ * answered it (AGL-4201). The lock is not there from the start: measured in
401
+ * production on v1.15.1, a booting tab's first read at 2 s found the store
402
+ * free, another tab locked it a few seconds later, and the tab sat 35 s on the
403
+ * old path. One read was a coin toss; reading until the tab is answered is not.
404
+ */
405
+ export declare const BOOT_WEDGE_RECHECK_MS = 2000;
406
+ /**
407
+ * How long, from when the tab is first seen, a booting tab keeps reading. Past
408
+ * it, a tab still unanswered is left to the stall watch, which has budgets of
409
+ * its own for a page that is in use.
410
+ */
411
+ export declare const BOOT_WEDGE_WINDOW_MS = 30000;
395
412
  /** What the boot check did (AGL-4201). */
396
413
  export type BootWedgeOutcome =
397
414
  /** The store was locked: this tab is moving to the memory cache. */
@@ -421,6 +438,9 @@ export interface BootWedgeCheckDeps {
421
438
  whenVisible?: () => Promise<void>;
422
439
  wait?: (ms: number) => Promise<void>;
423
440
  delayMs?: number;
441
+ recheckMs?: number;
442
+ windowMs?: number;
443
+ now?: () => number;
424
444
  }
425
445
  /** The boot check, with its browser parts injected. Never rejects. */
426
446
  export declare function runBootWedgeCheck(deps: BootWedgeCheckDeps): Promise<BootWedgeOutcome>;
@@ -491,9 +491,10 @@ const documentVisible = ()=>typeof document === 'undefined' || document.visibili
491
491
  * server and nothing typed into it has been read back. And it is waiting on the
492
492
  * same lock either way: its persistence cannot start while another tab's
493
493
  * transaction holds every store (the booting tab had no `clientMetadata` row
494
- * 17 s in). So once, about {@link BOOT_WEDGE_CHECK_DELAY_MS} after the client
494
+ * 17 s in). So from about {@link BOOT_WEDGE_CHECK_DELAY_MS} after the client
495
495
  * is created, a visible online tab whose client has not heard from the server
496
- * reads the lease, and a store that stays locked for
496
+ * reads the lease every {@link BOOT_WEDGE_RECHECK_MS} for up to
497
+ * {@link BOOT_WEDGE_WINDOW_MS}, and a store that stays locked for
497
498
  * {@link BOOT_WEDGE_LOCK_MS} moves it to the memory cache straight away,
498
499
  * sharing the lock with the tabs that open next (AGL-4090).
499
500
  *
@@ -506,7 +507,9 @@ const documentVisible = ()=>typeof document === 'undefined' || document.visibili
506
507
  * - **Only when someone is looking.** A tab opened in the background runs the
507
508
  * check when it is first shown, which is when its spinner starts costing
508
509
  * anyone anything.
509
- * - **Once per tab.** Never on a tab already on the fallback.
510
+ * - **Until answered, then never again.** The reads stop at the first server
511
+ * answer or at the end of the window, and never run on a tab already on the
512
+ * fallback.
510
513
  *
511
514
  * A false verdict costs a reload of a page with nothing on it, onto the memory
512
515
  * cache, which every lock verdict already costs today, 30 s later.
@@ -516,6 +519,18 @@ const documentVisible = ()=>typeof document === 'undefined' || document.visibili
516
519
  * locked. The SDK's own transactions take milliseconds; the read answered in
517
520
  * 1-5 ms on the same production cache once the lock had lifted.
518
521
  */ export const BOOT_WEDGE_LOCK_MS = 3000;
522
+ /**
523
+ * How often a booting tab reads the lease again while the server has not
524
+ * answered it (AGL-4201). The lock is not there from the start: measured in
525
+ * production on v1.15.1, a booting tab's first read at 2 s found the store
526
+ * free, another tab locked it a few seconds later, and the tab sat 35 s on the
527
+ * old path. One read was a coin toss; reading until the tab is answered is not.
528
+ */ export const BOOT_WEDGE_RECHECK_MS = 2000;
529
+ /**
530
+ * How long, from when the tab is first seen, a booting tab keeps reading. Past
531
+ * it, a tab still unanswered is left to the stall watch, which has budgets of
532
+ * its own for a page that is in use.
533
+ */ export const BOOT_WEDGE_WINDOW_MS = 30000;
519
534
  const whenDocumentVisible = ()=>new Promise((resolve)=>{
520
535
  if (typeof document === 'undefined' || document.visibilityState !== 'hidden') {
521
536
  resolve();
@@ -529,23 +544,33 @@ const whenDocumentVisible = ()=>new Promise((resolve)=>{
529
544
  document.addEventListener('visibilitychange', onChange);
530
545
  });
531
546
  /** The boot check, with its browser parts injected. Never rejects. */ export async function runBootWedgeCheck(deps) {
532
- const { probe, fallBack, hasServerAnswered, isFallbackActive = ()=>memoryCacheFallbackActive(), isOnline = browserOnline, whenVisible = whenDocumentVisible, wait = (ms)=>new Promise((resolve)=>setTimeout(resolve, ms)), delayMs = BOOT_WEDGE_CHECK_DELAY_MS } = deps;
547
+ const { probe, fallBack, hasServerAnswered, isFallbackActive = ()=>memoryCacheFallbackActive(), isOnline = browserOnline, whenVisible = whenDocumentVisible, wait = (ms)=>new Promise((resolve)=>setTimeout(resolve, ms)), delayMs = BOOT_WEDGE_CHECK_DELAY_MS, recheckMs = BOOT_WEDGE_RECHECK_MS, windowMs = BOOT_WEDGE_WINDOW_MS, now = Date.now } = deps;
533
548
  try {
534
549
  if (isFallbackActive()) return 'fallback-active';
535
550
  await wait(delayMs);
536
551
  await whenVisible();
537
- if (hasServerAnswered()) return 'answered';
538
- if (!isOnline()) return 'offline';
539
- const read = await probe();
540
- if (read.state !== 'locked') return 'clear';
541
- // The read took up to its whole budget; the client may have come through.
542
- if (hasServerAnswered()) return 'answered';
543
- if (!isOnline()) return 'offline';
544
- if (isFallbackActive()) return 'fallback-active';
545
- fallBack({
546
- reason: 'lease-locked'
547
- });
548
- return 'fell-back';
552
+ const until = now() + windowMs;
553
+ for(;;){
554
+ if (hasServerAnswered()) return 'answered';
555
+ if (!isOnline()) return 'offline';
556
+ if (isFallbackActive()) return 'fallback-active';
557
+ const read = await probe();
558
+ if (read.state === 'locked') {
559
+ // The read took up to its whole budget; the client may have come through.
560
+ if (hasServerAnswered()) return 'answered';
561
+ if (!isOnline()) return 'offline';
562
+ if (isFallbackActive()) return 'fallback-active';
563
+ fallBack({
564
+ reason: 'lease-locked'
565
+ });
566
+ return 'fell-back';
567
+ }
568
+ // Free now is not free for good: another tab can take the store a
569
+ // moment later, and this tab is still waiting on the server.
570
+ if (now() >= until) return 'clear';
571
+ await wait(recheckMs);
572
+ await whenVisible();
573
+ }
549
574
  } catch (unused) {
550
575
  return 'error';
551
576
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-multitab-wedge.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type Firestore } from 'firebase/firestore'\n\nimport { PRIMARY_LEASE_MAX_AGE_MS } from './firestore-tab-handoff'\n\n/**\n * A MULTI-TAB CACHE THAT ANOTHER TAB HAS LOCKED, AND THE WAY OUT (AGL-3428).\n *\n * ## The wedge the network cycle cannot clear\n *\n * `firestore-stall-recovery.ts` recovers a lapsed primary lease by cycling the\n * network, which runs the lease election at once (AGL-3373). That needs the\n * election's IndexedDB transaction to run. Measured against\n * `@firebase/firestore` 4.17.2: `IndexedDbPersistence.runTransaction` opens\n * EVERY transaction over EVERY object store (`getObjectStores(schemaVersion)`),\n * so one tab that stops partway through a readwrite transaction — frozen or\n * discarded by the browser while it runs — holds every store for every tab on\n * the origin. Behind it, in every other tab:\n *\n * - the lease election waits, so the lease row is never renewed by anyone;\n * - cache reads wait, so pages sit on their spinners;\n * - the mutation-queue write waits, so a save never reaches the network;\n * - a freshly opened tab's persistence `start()` waits, so a new tab hangs too;\n * - `disableNetwork`, `enableNetwork` and `terminate` are queued on the same\n * AsyncQueue behind the stuck operation, so none of them ever runs.\n *\n * On 2026-09-30 production (beta.218) did exactly this three times in two\n * hours: every console tab stopped, and the `owner` row named a background\n * tab that had stopped renewing it.\n *\n * ## How it is told apart from a slow read\n *\n * Only after the network cycle, and only from a visible tab on a browser that\n * reports a network. Such a tab wins a lapsed lease within one 4-second\n * election tick, and the cycle has just forced one. So, after a short settle,\n * the tab reads the `owner` row itself:\n *\n * - **the read cannot complete in time** — the store is locked by another\n * tab's open transaction. \"In time\" is {@link WEDGE_LOCK_MS}, longer than a\n * starved but living tab holds it (AGL-4135); or\n * - **the lease is older than {@link STALE_PRIMARY_LEASE_MS}** — no tab,\n * including this one, is completing an election.\n *\n * Either is the wedge. A fresh lease — this tab's or another's — is a healthy\n * cache and a merely slow server, and nothing more happens.\n *\n * ## The way out\n *\n * The tab records a {@link MemoryCacheFallback} in `sessionStorage` and\n * reloads. `firestoreCacheClassFor` reads it at startup and gives this tab the\n * memory cache, which shares nothing with other tabs, so the locked database\n * cannot reach it. `sessionStorage` is per tab: tabs already running keep the\n * durable cache, and the fallback leaves when this tab closes or after\n * {@link MEMORY_CACHE_FALLBACK_TTL_MS}.\n *\n * A reload, not an in-place swap, because nothing in place can work: the\n * wedged instance's `terminate()` is queued behind the stuck operation, a\n * second instance for the same app throws until the first is gone, and\n * hundreds of readers hold the instance from context and from closures.\n * Nothing that could be saved is lost — the wedge had already stopped every\n * write in the tab from leaving it.\n *\n * ## The tabs that open next (AGL-4090)\n *\n * Every tab used to find the lock on its own, so each NEW tab spent the whole\n * path above — the 8 s stall, the cycle's two 5 s steps, the settle, the 4 s\n * read, the reload — on an empty page: about half a minute, per tab. So a tab\n * whose read found the store LOCKED also leaves a {@link SharedCacheLock} in\n * `localStorage`, and `firestoreCacheClassFor` starts every tab that opens\n * while it is fresh on the memory cache at once: no stall, no reload.\n *\n * - **Only a lock is shared.** A locked store hangs every tab that opens the\n * database, a new one included. A stale lease does not: no transaction\n * holds the store, and a freshly started tab wins a lapsed lease at its\n * first election (AGL-3373). That fallback stays per tab.\n * - **Each tab that starts from it reads the lease again**, read-only, once\n * ({@link confirmSharedCacheLock}). Still locked, it re-stamps the record;\n * anything else clears it, so the first tab after the lock lifts is the\n * last one moved. The record lasts as long as the lock while tabs keep\n * opening, and {@link SHARED_CACHE_LOCK_TTL_MS} past the last tab that saw it.\n * - **Nothing here writes to IndexedDB or touches the lease.** A tab on the\n * memory cache takes no part in the multi-tab protocol, so it can never be\n * a second primary over the shared cache (AGL-3788).\n *\n * The cost is the memory cache's, and it is why the fallback was per tab: a\n * write made offline in such a tab is lost if the tab closes first, and the\n * tab shares no cache with the others. But while the store is locked, the\n * durable cache in a new tab can do none of that either: its persistence\n * never starts, so it reads nothing and no write leaves it. The cost is real\n * only for a record that has outlived its lock, and the re-read clears that\n * at the first tab that starts from it.\n *\n * Not chosen: a lease read at boot in every tab, in place of the record. The\n * cache is fixed when `initializeFirestore` runs, synchronously in the\n * provider's first render, and IndexedDB answers asynchronously, so a boot\n * read can shorten the wait to the read plus a reload but never skip it. It\n * would also add a read to every healthy tab's boot, and at boot the store can\n * be held for seconds for healthy reasons (the primary's LRU collection, a\n * schema upgrade) that the stall and the cycle rule out today, so it would\n * reload healthy tabs.\n */\n\n/** `sessionStorage` key of this tab's memory-cache fallback. */\nexport const MEMORY_CACHE_FALLBACK_KEY = 'aglyn:firestore-memory-cache-fallback'\n\n/**\n * How long a tab keeps the memory cache after falling back. The SDK's own\n * inactivity horizon (`MAX_CLIENT_AGE_MS`), after which a tab that is still\n * stuck no longer counts as a client; past it, a reload tries the durable\n * cache again, and falls back again if it has to.\n */\nexport const MEMORY_CACHE_FALLBACK_TTL_MS = 30 * 60 * 1000\n\n/** `localStorage` key of the lock a tab saw, for the tabs that open next (AGL-4090). */\nexport const SHARED_CACHE_LOCK_KEY = 'aglyn:firestore-shared-cache-locked'\n\n/**\n * How long a lock one tab saw starts new tabs on the memory cache, unless a\n * tab that starts from it sees the lock again. Long enough for the tabs a\n * person opens together (a page, then its preview); short, because a record\n * that outlives its lock moves every new tab, not one.\n */\nexport const SHARED_CACHE_LOCK_TTL_MS = 5 * 60 * 1000\n\n/**\n * A lease older than this, read from a visible online tab right after a\n * forced election, means no election is completing. The SDK treats a lease as\n * lapsed at 5 s (`MAX_PRIMARY_ELIGIBLE_AGE_MS`) and runs the election every\n * 4 s; this is three times the first, so an election that is merely late is\n * never mistaken for one that cannot run.\n */\nexport const STALE_PRIMARY_LEASE_MS = 15_000\n\n/**\n * How long the lease read may take before the store is judged locked. The\n * SDK's own transactions take milliseconds.\n *\n * Measured in time this tab was RUNNING, not on the wall clock (AGL-4120). While\n * the main thread is frozen, the read's answer sits unhandled in the same task\n * queue as the timeout, so a four-second freeze used to read as a locked store:\n * an `owner` read measured 3,945 ms in a freeze and 0 ms after it. On that false\n * verdict a healthy tab was reloaded, losing whatever was typed into it, and\n * every tab opened for the next five minutes started on the memory cache.\n */\nexport const LEASE_PROBE_TIMEOUT_MS = 4_000\n\n/**\n * How long the wedge check's lease read may wait before the store counts as\n * locked (AGL-4135). Five times {@link LEASE_PROBE_TIMEOUT_MS}, because a store\n * held by a tab that is slow is not a store held by a tab that is frozen.\n *\n * A starved tab (busy, slow, throttled) keeps each IndexedDB transaction open\n * until its event loop comes back between requests, and the SDK's lease\n * renewal makes several requests. Measured in production (v1.5.0, a tab busy\n * in 3 s slices): the store held every read for about 15 s, then answered with\n * a fresh lease. At 4 s that read as the wedge, and the healthy tab was reloaded\n * onto the memory cache, losing what had been typed into it. A frozen tab never\n * lets go, so the wedge still reads as locked, only later.\n */\nexport const WEDGE_LOCK_MS = 20_000\n\n/**\n * The probe's clock. A browser coalesces the ticks a frozen thread missed, so\n * counting ticks counts only the time the tab could have heard the answer.\n */\nexport const LEASE_PROBE_TICK_MS = 250\n\n/**\n * How long after the network cycle the lease is read, so the election the\n * cycle queued has run.\n */\nexport const LEASE_SETTLE_MS = 3_000\n\n/** The SDK's lease store and its single row's key (`DbPrimaryClientStore`, `DbPrimaryClientKey`). */\nconst OWNER_STORE = 'owner'\nconst OWNER_KEY = 'owner'\n\n/** What reading the lease found. */\nexport type PrimaryLeaseProbe =\n /** The read did not complete in time: another tab's transaction holds the store. */\n | { state: 'locked' }\n /** The lease row: who holds it and how long ago it was renewed. */\n | { state: 'leased'; ownerId: string; ageMs: number }\n /** There is no lease row. */\n | { state: 'vacant' }\n /** The lease could not be read: no IndexedDB, no database, no store, an error. */\n | { state: 'unknown' }\n\n/** Why a tab concluded the multi-tab cache is wedged. */\nexport type WedgeEvidence =\n | { reason: 'lease-locked' }\n | { reason: 'lease-stale'; ownerId: string; ageMs: number }\n /** The SDK's AsyncQueue has failed for good (AGL-4156). */\n | { reason: 'queue-failed' }\n\n/** The fallback this tab recorded, and why. */\nexport type MemoryCacheFallback = WedgeEvidence & { at: number }\n\n/** A lock one tab saw, recorded for the tabs that open next (AGL-4090). */\nexport interface SharedCacheLock {\n reason: 'lease-locked'\n /** The database whose store was locked: `<persistence prefix>main`. */\n databaseName: string\n /** When a tab last saw it locked. */\n at: number\n}\n\n/** What a tab that started from a {@link SharedCacheLock} found when it read the lease again. */\nexport type SharedCacheLockCheck =\n /** There was no fresh record for this database: nothing was read. */\n | 'absent'\n /** The store is still locked; the record was re-stamped. */\n | 'still-locked'\n /** The store answered; the record is gone, so the next tab gets the durable cache. */\n | 'cleared'\n /** Storage could not be read or written; the record is left to expire. */\n | 'failed'\n\n/**\n * Reads the SDK's `owner` row from `databaseName`.\n *\n * Opens only a database that already exists, at whatever version it has (the\n * same rule as `readHeartbeatClientIds`): `open(name)` on a missing database\n * would create it at version 1 under the SDK. The connection serves one\n * read-only request and is closed — also on `versionchange`, so it never\n * holds up the SDK's own upgrade, and also when the read lands after the\n * timeout.\n */\nexport async function probePrimaryLease(\n factory: IDBFactory | undefined,\n databaseName: string,\n {\n timeoutMs = LEASE_PROBE_TIMEOUT_MS,\n now = Date.now,\n }: { timeoutMs?: number; now?: () => number } = {},\n): Promise<PrimaryLeaseProbe> {\n if (!factory || typeof factory.databases !== 'function') return { state: 'unknown' }\n try {\n const databases = await factory.databases()\n if (!databases.some((database) => database.name === databaseName)) {\n return { state: 'unknown' }\n }\n } catch {\n return { state: 'unknown' }\n }\n\n return new Promise((resolve) => {\n let settled = false\n let database: IDBDatabase | undefined\n const settle = (probe: PrimaryLeaseProbe) => {\n if (settled) return\n settled = true\n clearInterval(clock)\n resolve(probe)\n }\n const close = () => {\n try {\n database?.close()\n } catch {\n // Already closed.\n }\n }\n // Only a lock can hold a read-only request this long; the connection is\n // closed when the request finally lands.\n const tickMs = Math.min(LEASE_PROBE_TICK_MS, timeoutMs)\n let ticks = Math.ceil(timeoutMs / tickMs)\n const clock = setInterval(() => {\n ticks -= 1\n if (ticks <= 0) settle({ state: 'locked' })\n }, tickMs)\n\n let request: IDBOpenDBRequest\n try {\n request = factory.open(databaseName)\n } catch {\n settle({ state: 'unknown' })\n return\n }\n // The database was deleted between `databases()` and `open()`: abort the\n // creation rather than leave the SDK an empty version-1 database.\n request.onupgradeneeded = () => request.transaction?.abort()\n request.onerror = () => settle({ state: 'unknown' })\n request.onsuccess = () => {\n database = request.result\n database.onversionchange = close\n if (settled || !database.objectStoreNames.contains(OWNER_STORE)) {\n close()\n settle({ state: 'unknown' })\n return\n }\n try {\n const read = database\n .transaction(OWNER_STORE, 'readonly')\n .objectStore(OWNER_STORE)\n .get(OWNER_KEY)\n read.onsuccess = () => {\n close()\n const row = read.result as\n | { ownerId?: unknown; leaseTimestampMs?: unknown }\n | undefined\n if (\n !row ||\n typeof row.ownerId !== 'string' ||\n typeof row.leaseTimestampMs !== 'number'\n ) {\n settle({ state: 'vacant' })\n return\n }\n settle({\n state: 'leased',\n ownerId: row.ownerId,\n ageMs: now() - row.leaseTimestampMs,\n })\n }\n read.onerror = () => {\n close()\n settle({ state: 'unknown' })\n }\n } catch {\n close()\n settle({ state: 'unknown' })\n }\n }\n })\n}\n\n/**\n * How long the lease read may take before a quiet client counts as WAITING on\n * the store (AGL-4135). Shorter than {@link LEASE_PROBE_TIMEOUT_MS}, which\n * decides a wedge: this asks only whether something holds the store now. The\n * SDK's own transactions take milliseconds, so a read that waits a second has\n * waited on one, from another tab or from this client's own backlog.\n */\nexport const LEASE_PROMPT_READ_MS = 1_000\n\n/** What the shared cache says about a client that has gone quiet (AGL-4135). */\nexport type LeaseCheck =\n /**\n * The store did not answer promptly. A transaction holds it, and every call\n * this client makes is queued behind that transaction.\n */\n | { state: 'waiting' }\n /** Another tab holds a live lease and serves this client through it. */\n | { state: 'served'; ownerId: string }\n /**\n * Nothing here explains the quiet. This tab holds the lease, or the lease has\n * lapsed or is vacant, or the lease could not be read or attributed.\n */\n | { state: 'silent' }\n\n/**\n * Reads a prompt lease probe for a quiet client whose own id is `selfId`.\n * Pure. A lease is live while younger than the SDK's 5 s\n * (`MAX_PRIMARY_ELIGIBLE_AGE_MS`). Without `selfId` a live lease cannot be told\n * apart from this tab's own, so it reads as `silent`, which is what every stall\n * was read as before.\n */\nexport function leaseCheckFrom(\n probe: PrimaryLeaseProbe,\n selfId: string | undefined,\n): LeaseCheck {\n if (probe.state === 'locked') return { state: 'waiting' }\n if (\n probe.state === 'leased' &&\n selfId !== undefined &&\n probe.ownerId !== selfId &&\n probe.ageMs < PRIMARY_LEASE_MAX_AGE_MS\n ) {\n return { state: 'served', ownerId: probe.ownerId }\n }\n return { state: 'silent' }\n}\n\n/**\n * This tab's id in the multi-tab protocol: the id its `clientMetadata` row is\n * written under, and any lease it holds. Read from the SDK's client\n * (`Firestore._firestoreClient.clientId`, which is internal and set once the\n * client has started). `undefined` when it is not there. Read in production\n * (4.17.2) against the `clientMetadata` row the same tab wrote.\n */\nexport function firestoreClientId(firestore: Firestore): string | undefined {\n try {\n const client = (firestore as unknown as {\n _firestoreClient?: { clientId?: unknown }\n })._firestoreClient\n const id = client?.clientId\n return typeof id === 'string' && id.length > 0 ? id : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether a lease read taken right after a forced election, from a visible\n * online tab, shows the wedge. Anything that could be a healthy cache —\n * a fresh lease, no lease row, an unreadable one — is not evidence.\n */\nexport function wedgeEvidenceFrom(\n probe: PrimaryLeaseProbe,\n staleMs = STALE_PRIMARY_LEASE_MS,\n): WedgeEvidence | undefined {\n if (probe.state === 'locked') return { reason: 'lease-locked' }\n if (probe.state === 'leased' && probe.ageMs >= staleMs) {\n return { reason: 'lease-stale', ownerId: probe.ownerId, ageMs: probe.ageMs }\n }\n return undefined\n}\n\n/**\n * The object stored under `key`, when it parses and its `at` is within\n * `ttlMs` of `now` and not ahead of it.\n */\nfunction readStampedRecord(\n storage: Pick<Storage, 'getItem'> | undefined,\n key: string,\n now: number,\n ttlMs: number,\n): ({ at: number } & Record<string, unknown>) | undefined {\n let raw: string | null\n try {\n raw = storage?.getItem(key) ?? null\n } catch {\n return undefined\n }\n if (raw === null) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return undefined\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined\n const record = parsed as { at?: unknown } & Record<string, unknown>\n if (typeof record.at !== 'number' || !Number.isFinite(record.at)) return undefined\n if (now - record.at >= ttlMs || record.at > now) return undefined\n return record as { at: number } & Record<string, unknown>\n}\n\n/**\n * This tab's fallback, or `undefined` when there is none, it has expired, or\n * it does not parse.\n */\nexport function readMemoryCacheFallback(\n storage: Pick<Storage, 'getItem'> | undefined,\n now: number,\n ttlMs = MEMORY_CACHE_FALLBACK_TTL_MS,\n): MemoryCacheFallback | undefined {\n return readStampedRecord(storage, MEMORY_CACHE_FALLBACK_KEY, now, ttlMs) as\n | MemoryCacheFallback\n | undefined\n}\n\n/**\n * The lock a tab saw on `databaseName`, or `undefined` when there is none, it\n * names another database, it has expired, or it does not parse.\n */\nexport function readSharedCacheLock(\n storage: Pick<Storage, 'getItem'> | undefined,\n databaseName: string | undefined,\n now: number,\n ttlMs = SHARED_CACHE_LOCK_TTL_MS,\n): SharedCacheLock | undefined {\n if (databaseName === undefined) return undefined\n const record = readStampedRecord(storage, SHARED_CACHE_LOCK_KEY, now, ttlMs)\n if (record?.reason !== 'lease-locked' || record.databaseName !== databaseName) {\n return undefined\n }\n return record as unknown as SharedCacheLock\n}\n\nconst browserSessionStorage = (): Storage | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.sessionStorage\n } catch {\n // Site data blocked: reading `window.sessionStorage` throws.\n return undefined\n }\n}\n\nconst browserLocalStorage = (): Storage | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.localStorage\n } catch {\n // Site data blocked: reading `window.localStorage` throws.\n return undefined\n }\n}\n\nconst browserIndexedDb = (): IDBFactory | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.indexedDB\n } catch {\n return undefined\n }\n}\n\n/** Whether this browser tab is running on its memory-cache fallback. */\nexport function memoryCacheFallbackActive(now = Date.now()): boolean {\n return readMemoryCacheFallback(browserSessionStorage(), now) !== undefined\n}\n\n/**\n * Whether another tab has just seen the store of `databaseName` locked, so\n * this tab should start on the memory cache rather than wait to find out.\n */\nexport function sharedCacheLockActive(\n databaseName: string | undefined,\n now = Date.now(),\n): boolean {\n return readSharedCacheLock(browserLocalStorage(), databaseName, now) !== undefined\n}\n\n/**\n * Records, for the tabs that open next, that the store of `databaseName` is\n * locked now. Never throws: without the record, the next tab finds the lock\n * itself, as it always has.\n */\nexport function recordSharedCacheLock(\n databaseName: string,\n {\n storage = browserLocalStorage(),\n now = Date.now,\n }: { storage?: Pick<Storage, 'setItem'>; now?: () => number } = {},\n): void {\n const record: SharedCacheLock = { reason: 'lease-locked', databaseName, at: now() }\n try {\n storage?.setItem(SHARED_CACHE_LOCK_KEY, JSON.stringify(record))\n } catch {\n // Full or blocked.\n }\n}\n\n/**\n * Run once by a tab that started on the memory cache: reads the lease of\n * `databaseName` again and keeps another tab's lock record only while the\n * store is still locked. Never creates a record and never rejects.\n */\nexport async function confirmSharedCacheLock(\n databaseName: string,\n {\n probe = () => probePrimaryLease(browserIndexedDb(), databaseName),\n storage = browserLocalStorage(),\n now = Date.now,\n }: {\n probe?: () => Promise<PrimaryLeaseProbe>\n storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>\n now?: () => number\n } = {},\n): Promise<SharedCacheLockCheck> {\n if (!storage) return 'absent'\n const seen = readSharedCacheLock(storage, databaseName, now())\n if (!seen) return 'absent'\n try {\n if ((await probe()).state === 'locked') {\n recordSharedCacheLock(databaseName, { storage, now })\n return 'still-locked'\n }\n const current = readSharedCacheLock(storage, databaseName, now())\n // Another tab saw the lock again while this read ran; its record is\n // newer than this read, so it stands.\n if (current && current.at !== seen.at) return 'still-locked'\n if (current) storage.removeItem(SHARED_CACHE_LOCK_KEY)\n return 'cleared'\n } catch {\n return 'failed'\n }\n}\n\nexport interface WedgeEscalationDeps {\n /** Reads the lease. */\n probe: () => Promise<PrimaryLeaseProbe>\n /** Moves this tab off the shared cache. */\n fallBack: (evidence: WedgeEvidence) => void\n /** Whether this tab is already on the fallback — it then never escalates. */\n isFallbackActive?: () => boolean\n isOnline?: () => boolean\n isVisible?: () => boolean\n /** Waits `ms`; the settle before the lease read. */\n wait?: (ms: number) => Promise<void>\n settleMs?: number\n}\n\nconst browserOnline = () =>\n typeof navigator === 'undefined' || navigator.onLine !== false\n\nconst documentVisible = () =>\n typeof document === 'undefined' || document.visibilityState !== 'hidden'\n\n/**\n * The step `createStallRecovery` runs after its network cycle for a\n * multi-tab client. Resolves `true` when it has moved the tab to the fallback.\n * Never rejects.\n */\nexport function createWedgeEscalation(\n deps: WedgeEscalationDeps,\n): () => Promise<boolean> {\n const {\n probe,\n fallBack,\n isFallbackActive = () => memoryCacheFallbackActive(),\n isOnline = browserOnline,\n isVisible = documentVisible,\n wait = (ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n settleMs = LEASE_SETTLE_MS,\n } = deps\n return async () => {\n try {\n if (isFallbackActive()) return false\n await wait(settleMs)\n // Both guards again: the reader may have gone, or the network with it.\n if (!isOnline() || !isVisible()) return false\n const evidence = wedgeEvidenceFrom(await probe())\n if (!evidence) return false\n fallBack(evidence)\n return true\n } catch {\n return false\n }\n }\n}\n\n/**\n * A TAB THAT IS STILL BOOTING DOES NOT WAIT 37 SECONDS TO FIND THE LOCK\n * (AGL-4201).\n *\n * The rescue above is tuned for a tab that already has a page on it. It runs\n * only once a reader has stalled (`FIRESTORE_STALL_MS`, 8 s), reads the lease\n * promptly (1 s), settles (3 s) and then gives the lock {@link WEDGE_LOCK_MS}\n * (20 s) before it believes it, because a tab that is merely busy holds the\n * store for about 15 s and reloading one loses what was typed into it\n * (AGL-4135). Plus the reload, that is about 37 s, and it is exactly what a\n * tab opened while another tab held the store sat through on the site gate's\n * spinner: measured in production on 2026-11-06, two reloads in three.\n *\n * A tab that is still booting has none of what that budget protects. Its\n * client has had no answer from the server, so nothing it shows came from the\n * server and nothing typed into it has been read back. And it is waiting on the\n * same lock either way: its persistence cannot start while another tab's\n * transaction holds every store (the booting tab had no `clientMetadata` row\n * 17 s in). So once, about {@link BOOT_WEDGE_CHECK_DELAY_MS} after the client\n * is created, a visible online tab whose client has not heard from the server\n * reads the lease, and a store that stays locked for\n * {@link BOOT_WEDGE_LOCK_MS} moves it to the memory cache straight away,\n * sharing the lock with the tabs that open next (AGL-4090).\n *\n * - **Only a lock.** A lapsed or stale lease at boot is the normal state after\n * the last tab went quiet, and a freshly started tab wins it at its first\n * election (AGL-3373). Only a store nobody can read is evidence here.\n * - **Only before the first server answer**, checked before the read and again\n * after it. A tab the server has answered is working and is left to the\n * stall watch, whose budget is the one that protects a page in use.\n * - **Only when someone is looking.** A tab opened in the background runs the\n * check when it is first shown, which is when its spinner starts costing\n * anyone anything.\n * - **Once per tab.** Never on a tab already on the fallback.\n *\n * A false verdict costs a reload of a page with nothing on it, onto the memory\n * cache, which every lock verdict already costs today, 30 s later.\n */\nexport const BOOT_WEDGE_CHECK_DELAY_MS = 2_000\n\n/**\n * How long the boot check's lease read may wait before the store counts as\n * locked. The SDK's own transactions take milliseconds; the read answered in\n * 1-5 ms on the same production cache once the lock had lifted.\n */\nexport const BOOT_WEDGE_LOCK_MS = 3_000\n\n/** What the boot check did (AGL-4201). */\nexport type BootWedgeOutcome =\n /** The store was locked: this tab is moving to the memory cache. */\n | 'fell-back'\n /** The server answered this client first: it is booting fine. */\n | 'answered'\n /** The store answered: nothing holds it. */\n | 'clear'\n /** The browser reports no network. */\n | 'offline'\n /** This tab is already on the fallback. */\n | 'fallback-active'\n /** The client does not run the durable multi-tab cache. */\n | 'not-multi-tab'\n /** Something unexpected; the stall watch stays in charge. */\n | 'error'\n\nexport interface BootWedgeCheckDeps {\n /** Reads the lease, bounded by {@link BOOT_WEDGE_LOCK_MS}. */\n probe: () => Promise<PrimaryLeaseProbe>\n /** Moves this tab off the shared cache. */\n fallBack: (evidence: WedgeEvidence) => void\n /** Whether the server has confirmed anything for this client yet. */\n hasServerAnswered: () => boolean\n isFallbackActive?: () => boolean\n isOnline?: () => boolean\n /** Resolves once the document is visible, at once when it already is. */\n whenVisible?: () => Promise<void>\n wait?: (ms: number) => Promise<void>\n delayMs?: number\n}\n\nconst whenDocumentVisible = (): Promise<void> =>\n new Promise((resolve) => {\n if (typeof document === 'undefined' || document.visibilityState !== 'hidden') {\n resolve()\n return\n }\n const onChange = () => {\n if (document.visibilityState === 'hidden') return\n document.removeEventListener('visibilitychange', onChange)\n resolve()\n }\n document.addEventListener('visibilitychange', onChange)\n })\n\n/** The boot check, with its browser parts injected. Never rejects. */\nexport async function runBootWedgeCheck(\n deps: BootWedgeCheckDeps,\n): Promise<BootWedgeOutcome> {\n const {\n probe,\n fallBack,\n hasServerAnswered,\n isFallbackActive = () => memoryCacheFallbackActive(),\n isOnline = browserOnline,\n whenVisible = whenDocumentVisible,\n wait = (ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n delayMs = BOOT_WEDGE_CHECK_DELAY_MS,\n } = deps\n try {\n if (isFallbackActive()) return 'fallback-active'\n await wait(delayMs)\n await whenVisible()\n if (hasServerAnswered()) return 'answered'\n if (!isOnline()) return 'offline'\n const read = await probe()\n if (read.state !== 'locked') return 'clear'\n // The read took up to its whole budget; the client may have come through.\n if (hasServerAnswered()) return 'answered'\n if (!isOnline()) return 'offline'\n if (isFallbackActive()) return 'fallback-active'\n fallBack({ reason: 'lease-locked' })\n return 'fell-back'\n } catch {\n return 'error'\n }\n}\n\n/**\n * Records the fallback for this tab and reloads it onto the memory cache.\n * When the record cannot be written it does not reload: without it, the\n * reloaded tab would open the same locked database and hang again.\n *\n * A lock is also recorded for the tabs that open next (AGL-4090), first and\n * whatever happens to this tab's own record: they would hang on it too.\n */\nexport function fallBackToMemoryCache(\n evidence: WedgeEvidence,\n {\n storage = browserSessionStorage(),\n sharedStorage = browserLocalStorage(),\n databaseName,\n reload = () => window.location.reload(),\n now = Date.now,\n }: {\n storage?: Pick<Storage, 'setItem'>\n /** Where the tabs that open next look for a lock this tab saw. */\n sharedStorage?: Pick<Storage, 'setItem'>\n /** The locked database. Without it, nothing is shared. */\n databaseName?: string\n reload?: () => void\n now?: () => number\n } = {},\n): void {\n if (evidence.reason === 'lease-locked' && databaseName !== undefined) {\n recordSharedCacheLock(databaseName, { storage: sharedStorage, now })\n }\n if (!storage) return\n const record: MemoryCacheFallback = { ...evidence, at: now() }\n try {\n storage.setItem(MEMORY_CACHE_FALLBACK_KEY, JSON.stringify(record))\n } catch {\n return\n }\n console.warn(\n evidence.reason === 'queue-failed'\n ? '[firestore] The multi-tab cache failed this tab\\'s Firestore client; reloading this tab on the memory cache (AGL-4156).'\n : '[firestore] The multi-tab cache is locked by another tab; reloading this tab on the memory cache (AGL-3428).',\n record,\n )\n reload()\n}\n\n/**\n * A FIRESTORE CLIENT WHOSE QUEUE HAS FAILED, AND THE WAY OUT (AGL-4156).\n *\n * The SDK runs every operation on one AsyncQueue. When an operation rejects\n * with an error the queue does not retry, it keeps that error and refuses\n * every later operation with the assertion `Unexpected state (ID: b815)`,\n * whose `CONTEXT` names the first error. Nothing restarts it: the\n * client is dead until the page reloads, so every read and listener in the tab\n * fails, and pages stop loading.\n *\n * The durable cache is what kills it in production. On 2026-11-04 (v1.9.0,\n * `@firebase/firestore` 4.18.0) a new Firefox sign-up's console lost its client\n * on three page loads in 25 minutes. Each time, an IndexedDB request in the\n * SDK's transaction threw \"Attempt to get a record from database without an\n * in-progress transaction\". The SDK retries a failed transaction three times,\n * then hands the raw `DOMException` to the queue, which counts it as fatal\n * rather than as an `IndexedDbTransactionError` to back off from. The earlier\n * cases ended the same way: a full `localStorage` (AGL-2845) and a null target\n * from the IndexedDB target cache (`isCorePipeline`, 2026-10-14, Chrome).\n *\n * So the first b815 of a durable multi-tab client moves the tab onto the\n * memory cache, which does not use IndexedDB, through the same per-tab\n * {@link fallBackToMemoryCache} as the wedge. Nothing that could be saved is\n * lost: the dead queue had already stopped every write in the tab. A tab already\n * on the fallback runs the memory cache, which is never watched, so a b815 there\n * cannot loop. No lock is shared, because another tab's client is not dead.\n */\nconst QUEUE_FAILURE = /INTERNAL ASSERTION FAILED: Unexpected state \\(ID: b815\\)/\n\n/** Whether `thrown` (an error, an event's message, a rejection reason) is the SDK's failed-queue assertion. */\nexport function isFirestoreQueueFailure(thrown: unknown): boolean {\n try {\n const message =\n typeof thrown === 'string'\n ? thrown\n : thrown && typeof thrown === 'object' && 'message' in thrown\n ? String((thrown as { message: unknown }).message)\n : ''\n return QUEUE_FAILURE.test(message)\n } catch {\n return false\n }\n}\n\n/**\n * Watches `target` for the failed-queue assertion, as an uncaught error or an\n * unhandled rejection, and calls `fallBack` once, the first time it appears.\n * Returns the function that stops watching.\n */\nexport function watchFirestoreQueueFailure(\n fallBack: (evidence: WedgeEvidence) => void,\n {\n target = typeof window === 'undefined' ? undefined : window,\n isFallbackActive = () => memoryCacheFallbackActive(),\n }: {\n target?: Pick<Window, 'addEventListener' | 'removeEventListener'>\n isFallbackActive?: () => boolean\n } = {},\n): () => void {\n if (!target) return () => undefined\n let fired = false\n const onError = (event: Event) => {\n const { error, message } = event as ErrorEvent\n check(isFirestoreQueueFailure(error) || isFirestoreQueueFailure(message))\n }\n const onRejection = (event: Event) => {\n check(isFirestoreQueueFailure((event as PromiseRejectionEvent).reason))\n }\n const stop = () => {\n target.removeEventListener('error', onError)\n target.removeEventListener('unhandledrejection', onRejection)\n }\n const check = (failed: boolean) => {\n if (!failed || fired) return\n fired = true\n stop()\n try {\n if (isFallbackActive()) return\n fallBack({ reason: 'queue-failed' })\n } catch {\n // Watching never breaks the page.\n }\n }\n target.addEventListener('error', onError)\n target.addEventListener('unhandledrejection', onRejection)\n return stop\n}\n\n/** The IndexedDB database of each client running the durable multi-tab cache. */\nconst multiTabDatabases = new WeakMap<Firestore, string>()\n\n/**\n * Registers `firestore` as running the durable multi-tab cache under\n * `databaseName` (`<persistence prefix>main`). Only a registered client ever\n * escalates past the network cycle, and only its page is watched for a failed\n * queue ({@link watchFirestoreQueueFailure}).\n */\nexport function markMultiTabFirestore(firestore: Firestore, databaseName: string): void {\n if (firestore && typeof firestore === 'object') {\n if (!multiTabDatabases.has(firestore)) {\n watchFirestoreQueueFailure((evidence) =>\n fallBackToMemoryCache(evidence, { databaseName }),\n )\n }\n multiTabDatabases.set(firestore, databaseName)\n }\n}\n\n/**\n * The browser escalation for `firestore`, or `undefined` when it does not run\n * the durable multi-tab cache (the emulator configuration, an ephemeral\n * origin, a tab already on the fallback).\n */\nexport function browserWedgeEscalationFor(\n firestore: Firestore,\n): (() => Promise<boolean>) | undefined {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return undefined\n return createWedgeEscalation({\n probe: () =>\n probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: WEDGE_LOCK_MS,\n }),\n fallBack: (evidence) => fallBackToMemoryCache(evidence, { databaseName }),\n })\n}\n\n/**\n * The lease check `createStallRecovery` runs before a network cycle, or\n * `undefined` when `firestore` does not run the durable multi-tab cache: a\n * client with a cache of its own has no other tab to wait on. Never rejects.\n */\nexport function browserLeaseCheckFor(\n firestore: Firestore,\n): (() => Promise<LeaseCheck>) | undefined {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return undefined\n return async () => {\n try {\n const probe = await probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: LEASE_PROMPT_READ_MS,\n })\n return leaseCheckFrom(probe, firestoreClientId(firestore))\n } catch {\n return { state: 'silent' }\n }\n }\n}\n\n/**\n * Runs the boot check (AGL-4201) for `firestore`, which\n * {@link markMultiTabFirestore} has registered. Call it right after\n * registering. `hasServerAnswered` is the stall watch's record of server\n * answers (`firestoreHasServerAnswered`), passed in so this module does not\n * import the one that imports it. Fire and forget: it never rejects.\n */\nexport function startBootWedgeCheck(\n firestore: Firestore,\n hasServerAnswered: () => boolean,\n): Promise<BootWedgeOutcome> {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return Promise.resolve('not-multi-tab')\n return runBootWedgeCheck({\n probe: () =>\n probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: BOOT_WEDGE_LOCK_MS,\n }),\n fallBack: (evidence) => fallBackToMemoryCache(evidence, { databaseName }),\n hasServerAnswered,\n })\n}\n"],"names":["PRIMARY_LEASE_MAX_AGE_MS","MEMORY_CACHE_FALLBACK_KEY","MEMORY_CACHE_FALLBACK_TTL_MS","SHARED_CACHE_LOCK_KEY","SHARED_CACHE_LOCK_TTL_MS","STALE_PRIMARY_LEASE_MS","LEASE_PROBE_TIMEOUT_MS","WEDGE_LOCK_MS","LEASE_PROBE_TICK_MS","LEASE_SETTLE_MS","OWNER_STORE","OWNER_KEY","probePrimaryLease","factory","databaseName","timeoutMs","now","Date","databases","state","some","database","name","Promise","resolve","settled","settle","probe","clearInterval","clock","close","tickMs","Math","min","ticks","ceil","setInterval","request","open","onupgradeneeded","transaction","abort","onerror","onsuccess","result","onversionchange","objectStoreNames","contains","read","objectStore","get","row","ownerId","leaseTimestampMs","ageMs","LEASE_PROMPT_READ_MS","leaseCheckFrom","selfId","undefined","firestoreClientId","firestore","client","_firestoreClient","id","clientId","length","wedgeEvidenceFrom","staleMs","reason","readStampedRecord","storage","key","ttlMs","raw","getItem","parsed","JSON","parse","record","at","Number","isFinite","readMemoryCacheFallback","readSharedCacheLock","browserSessionStorage","window","sessionStorage","browserLocalStorage","localStorage","browserIndexedDb","indexedDB","memoryCacheFallbackActive","sharedCacheLockActive","recordSharedCacheLock","setItem","stringify","confirmSharedCacheLock","seen","current","removeItem","browserOnline","navigator","onLine","documentVisible","document","visibilityState","createWedgeEscalation","deps","fallBack","isFallbackActive","isOnline","isVisible","wait","ms","setTimeout","settleMs","evidence","BOOT_WEDGE_CHECK_DELAY_MS","BOOT_WEDGE_LOCK_MS","whenDocumentVisible","onChange","removeEventListener","addEventListener","runBootWedgeCheck","hasServerAnswered","whenVisible","delayMs","fallBackToMemoryCache","sharedStorage","reload","location","console","warn","QUEUE_FAILURE","isFirestoreQueueFailure","thrown","message","String","test","watchFirestoreQueueFailure","target","fired","onError","event","error","check","onRejection","stop","failed","multiTabDatabases","WeakMap","markMultiTabFirestore","has","set","browserWedgeEscalationFor","browserLeaseCheckFor","startBootWedgeCheck"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,SAASA,wBAAwB,QAAQ,6BAAyB;AAElE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+FC,GAED,8DAA8D,GAC9D,OAAO,MAAMC,4BAA4B,wCAAuC;AAEhF;;;;;CAKC,GACD,OAAO,MAAMC,+BAA+B,KAAK,KAAK,KAAI;AAE1D,sFAAsF,GACtF,OAAO,MAAMC,wBA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kBAAkBG,GAAG,CAAC5F,YAAY;YACrC+E,2BAA2B,CAACvB,WAC1BW,sBAAsBX,UAAU;oBAAEtG;gBAAa;QAEnD;QACAuI,kBAAkBI,GAAG,CAAC7F,WAAW9C;IACnC;AACF;AAEA;;;;CAIC,GACD,OAAO,SAAS4I,0BACd9F,SAAoB;IAEpB,MAAM9C,eAAeuI,kBAAkBnG,GAAG,CAACU;IAC3C,IAAI9C,iBAAiB4C,WAAW,OAAOA;IACvC,OAAOgD,sBAAsB;QAC3B/E,OAAO,IACLf,kBAAkB6E,oBAAoB3E,cAAc;gBAClDC,WAAWR;YACb;QACFqG,UAAU,CAACQ,WAAaW,sBAAsBX,UAAU;gBAAEtG;YAAa;IACzE;AACF;AAEA;;;;CAIC,GACD,OAAO,SAAS6I,qBACd/F,SAAoB;IAEpB,MAAM9C,eAAeuI,kBAAkBnG,GAAG,CAACU;IAC3C,IAAI9C,iBAAiB4C,WAAW,OAAOA;IACvC,OAAO;QACL,IAAI;YACF,MAAM/B,QAAQ,MAAMf,kBAAkB6E,oBAAoB3E,cAAc;gBACtEC,WAAWwC;YACb;YACA,OAAOC,eAAe7B,OAAOgC,kBAAkBC;QACjD,EAAE,eAAM;YACN,OAAO;gBAAEzC,OAAO;YAAS;QAC3B;IACF;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASyI,oBACdhG,SAAoB,EACpBgE,iBAAgC;IAEhC,MAAM9G,eAAeuI,kBAAkBnG,GAAG,CAACU;IAC3C,IAAI9C,iBAAiB4C,WAAW,OAAOnC,QAAQC,OAAO,CAAC;IACvD,OAAOmG,kBAAkB;QACvBhG,OAAO,IACLf,kBAAkB6E,oBAAoB3E,cAAc;gBAClDC,WAAWuG;YACb;QACFV,UAAU,CAACQ,WAAaW,sBAAsBX,UAAU;gBAAEtG;YAAa;QACvE8G;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-multitab-wedge.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type Firestore } from 'firebase/firestore'\n\nimport { PRIMARY_LEASE_MAX_AGE_MS } from './firestore-tab-handoff'\n\n/**\n * A MULTI-TAB CACHE THAT ANOTHER TAB HAS LOCKED, AND THE WAY OUT (AGL-3428).\n *\n * ## The wedge the network cycle cannot clear\n *\n * `firestore-stall-recovery.ts` recovers a lapsed primary lease by cycling the\n * network, which runs the lease election at once (AGL-3373). That needs the\n * election's IndexedDB transaction to run. Measured against\n * `@firebase/firestore` 4.17.2: `IndexedDbPersistence.runTransaction` opens\n * EVERY transaction over EVERY object store (`getObjectStores(schemaVersion)`),\n * so one tab that stops partway through a readwrite transaction — frozen or\n * discarded by the browser while it runs — holds every store for every tab on\n * the origin. Behind it, in every other tab:\n *\n * - the lease election waits, so the lease row is never renewed by anyone;\n * - cache reads wait, so pages sit on their spinners;\n * - the mutation-queue write waits, so a save never reaches the network;\n * - a freshly opened tab's persistence `start()` waits, so a new tab hangs too;\n * - `disableNetwork`, `enableNetwork` and `terminate` are queued on the same\n * AsyncQueue behind the stuck operation, so none of them ever runs.\n *\n * On 2026-09-30 production (beta.218) did exactly this three times in two\n * hours: every console tab stopped, and the `owner` row named a background\n * tab that had stopped renewing it.\n *\n * ## How it is told apart from a slow read\n *\n * Only after the network cycle, and only from a visible tab on a browser that\n * reports a network. Such a tab wins a lapsed lease within one 4-second\n * election tick, and the cycle has just forced one. So, after a short settle,\n * the tab reads the `owner` row itself:\n *\n * - **the read cannot complete in time** — the store is locked by another\n * tab's open transaction. \"In time\" is {@link WEDGE_LOCK_MS}, longer than a\n * starved but living tab holds it (AGL-4135); or\n * - **the lease is older than {@link STALE_PRIMARY_LEASE_MS}** — no tab,\n * including this one, is completing an election.\n *\n * Either is the wedge. A fresh lease — this tab's or another's — is a healthy\n * cache and a merely slow server, and nothing more happens.\n *\n * ## The way out\n *\n * The tab records a {@link MemoryCacheFallback} in `sessionStorage` and\n * reloads. `firestoreCacheClassFor` reads it at startup and gives this tab the\n * memory cache, which shares nothing with other tabs, so the locked database\n * cannot reach it. `sessionStorage` is per tab: tabs already running keep the\n * durable cache, and the fallback leaves when this tab closes or after\n * {@link MEMORY_CACHE_FALLBACK_TTL_MS}.\n *\n * A reload, not an in-place swap, because nothing in place can work: the\n * wedged instance's `terminate()` is queued behind the stuck operation, a\n * second instance for the same app throws until the first is gone, and\n * hundreds of readers hold the instance from context and from closures.\n * Nothing that could be saved is lost — the wedge had already stopped every\n * write in the tab from leaving it.\n *\n * ## The tabs that open next (AGL-4090)\n *\n * Every tab used to find the lock on its own, so each NEW tab spent the whole\n * path above — the 8 s stall, the cycle's two 5 s steps, the settle, the 4 s\n * read, the reload — on an empty page: about half a minute, per tab. So a tab\n * whose read found the store LOCKED also leaves a {@link SharedCacheLock} in\n * `localStorage`, and `firestoreCacheClassFor` starts every tab that opens\n * while it is fresh on the memory cache at once: no stall, no reload.\n *\n * - **Only a lock is shared.** A locked store hangs every tab that opens the\n * database, a new one included. A stale lease does not: no transaction\n * holds the store, and a freshly started tab wins a lapsed lease at its\n * first election (AGL-3373). That fallback stays per tab.\n * - **Each tab that starts from it reads the lease again**, read-only, once\n * ({@link confirmSharedCacheLock}). Still locked, it re-stamps the record;\n * anything else clears it, so the first tab after the lock lifts is the\n * last one moved. The record lasts as long as the lock while tabs keep\n * opening, and {@link SHARED_CACHE_LOCK_TTL_MS} past the last tab that saw it.\n * - **Nothing here writes to IndexedDB or touches the lease.** A tab on the\n * memory cache takes no part in the multi-tab protocol, so it can never be\n * a second primary over the shared cache (AGL-3788).\n *\n * The cost is the memory cache's, and it is why the fallback was per tab: a\n * write made offline in such a tab is lost if the tab closes first, and the\n * tab shares no cache with the others. But while the store is locked, the\n * durable cache in a new tab can do none of that either: its persistence\n * never starts, so it reads nothing and no write leaves it. The cost is real\n * only for a record that has outlived its lock, and the re-read clears that\n * at the first tab that starts from it.\n *\n * Not chosen: a lease read at boot in every tab, in place of the record. The\n * cache is fixed when `initializeFirestore` runs, synchronously in the\n * provider's first render, and IndexedDB answers asynchronously, so a boot\n * read can shorten the wait to the read plus a reload but never skip it. It\n * would also add a read to every healthy tab's boot, and at boot the store can\n * be held for seconds for healthy reasons (the primary's LRU collection, a\n * schema upgrade) that the stall and the cycle rule out today, so it would\n * reload healthy tabs.\n */\n\n/** `sessionStorage` key of this tab's memory-cache fallback. */\nexport const MEMORY_CACHE_FALLBACK_KEY = 'aglyn:firestore-memory-cache-fallback'\n\n/**\n * How long a tab keeps the memory cache after falling back. The SDK's own\n * inactivity horizon (`MAX_CLIENT_AGE_MS`), after which a tab that is still\n * stuck no longer counts as a client; past it, a reload tries the durable\n * cache again, and falls back again if it has to.\n */\nexport const MEMORY_CACHE_FALLBACK_TTL_MS = 30 * 60 * 1000\n\n/** `localStorage` key of the lock a tab saw, for the tabs that open next (AGL-4090). */\nexport const SHARED_CACHE_LOCK_KEY = 'aglyn:firestore-shared-cache-locked'\n\n/**\n * How long a lock one tab saw starts new tabs on the memory cache, unless a\n * tab that starts from it sees the lock again. Long enough for the tabs a\n * person opens together (a page, then its preview); short, because a record\n * that outlives its lock moves every new tab, not one.\n */\nexport const SHARED_CACHE_LOCK_TTL_MS = 5 * 60 * 1000\n\n/**\n * A lease older than this, read from a visible online tab right after a\n * forced election, means no election is completing. The SDK treats a lease as\n * lapsed at 5 s (`MAX_PRIMARY_ELIGIBLE_AGE_MS`) and runs the election every\n * 4 s; this is three times the first, so an election that is merely late is\n * never mistaken for one that cannot run.\n */\nexport const STALE_PRIMARY_LEASE_MS = 15_000\n\n/**\n * How long the lease read may take before the store is judged locked. The\n * SDK's own transactions take milliseconds.\n *\n * Measured in time this tab was RUNNING, not on the wall clock (AGL-4120). While\n * the main thread is frozen, the read's answer sits unhandled in the same task\n * queue as the timeout, so a four-second freeze used to read as a locked store:\n * an `owner` read measured 3,945 ms in a freeze and 0 ms after it. On that false\n * verdict a healthy tab was reloaded, losing whatever was typed into it, and\n * every tab opened for the next five minutes started on the memory cache.\n */\nexport const LEASE_PROBE_TIMEOUT_MS = 4_000\n\n/**\n * How long the wedge check's lease read may wait before the store counts as\n * locked (AGL-4135). Five times {@link LEASE_PROBE_TIMEOUT_MS}, because a store\n * held by a tab that is slow is not a store held by a tab that is frozen.\n *\n * A starved tab (busy, slow, throttled) keeps each IndexedDB transaction open\n * until its event loop comes back between requests, and the SDK's lease\n * renewal makes several requests. Measured in production (v1.5.0, a tab busy\n * in 3 s slices): the store held every read for about 15 s, then answered with\n * a fresh lease. At 4 s that read as the wedge, and the healthy tab was reloaded\n * onto the memory cache, losing what had been typed into it. A frozen tab never\n * lets go, so the wedge still reads as locked, only later.\n */\nexport const WEDGE_LOCK_MS = 20_000\n\n/**\n * The probe's clock. A browser coalesces the ticks a frozen thread missed, so\n * counting ticks counts only the time the tab could have heard the answer.\n */\nexport const LEASE_PROBE_TICK_MS = 250\n\n/**\n * How long after the network cycle the lease is read, so the election the\n * cycle queued has run.\n */\nexport const LEASE_SETTLE_MS = 3_000\n\n/** The SDK's lease store and its single row's key (`DbPrimaryClientStore`, `DbPrimaryClientKey`). */\nconst OWNER_STORE = 'owner'\nconst OWNER_KEY = 'owner'\n\n/** What reading the lease found. */\nexport type PrimaryLeaseProbe =\n /** The read did not complete in time: another tab's transaction holds the store. */\n | { state: 'locked' }\n /** The lease row: who holds it and how long ago it was renewed. */\n | { state: 'leased'; ownerId: string; ageMs: number }\n /** There is no lease row. */\n | { state: 'vacant' }\n /** The lease could not be read: no IndexedDB, no database, no store, an error. */\n | { state: 'unknown' }\n\n/** Why a tab concluded the multi-tab cache is wedged. */\nexport type WedgeEvidence =\n | { reason: 'lease-locked' }\n | { reason: 'lease-stale'; ownerId: string; ageMs: number }\n /** The SDK's AsyncQueue has failed for good (AGL-4156). */\n | { reason: 'queue-failed' }\n\n/** The fallback this tab recorded, and why. */\nexport type MemoryCacheFallback = WedgeEvidence & { at: number }\n\n/** A lock one tab saw, recorded for the tabs that open next (AGL-4090). */\nexport interface SharedCacheLock {\n reason: 'lease-locked'\n /** The database whose store was locked: `<persistence prefix>main`. */\n databaseName: string\n /** When a tab last saw it locked. */\n at: number\n}\n\n/** What a tab that started from a {@link SharedCacheLock} found when it read the lease again. */\nexport type SharedCacheLockCheck =\n /** There was no fresh record for this database: nothing was read. */\n | 'absent'\n /** The store is still locked; the record was re-stamped. */\n | 'still-locked'\n /** The store answered; the record is gone, so the next tab gets the durable cache. */\n | 'cleared'\n /** Storage could not be read or written; the record is left to expire. */\n | 'failed'\n\n/**\n * Reads the SDK's `owner` row from `databaseName`.\n *\n * Opens only a database that already exists, at whatever version it has (the\n * same rule as `readHeartbeatClientIds`): `open(name)` on a missing database\n * would create it at version 1 under the SDK. The connection serves one\n * read-only request and is closed — also on `versionchange`, so it never\n * holds up the SDK's own upgrade, and also when the read lands after the\n * timeout.\n */\nexport async function probePrimaryLease(\n factory: IDBFactory | undefined,\n databaseName: string,\n {\n timeoutMs = LEASE_PROBE_TIMEOUT_MS,\n now = Date.now,\n }: { timeoutMs?: number; now?: () => number } = {},\n): Promise<PrimaryLeaseProbe> {\n if (!factory || typeof factory.databases !== 'function') return { state: 'unknown' }\n try {\n const databases = await factory.databases()\n if (!databases.some((database) => database.name === databaseName)) {\n return { state: 'unknown' }\n }\n } catch {\n return { state: 'unknown' }\n }\n\n return new Promise((resolve) => {\n let settled = false\n let database: IDBDatabase | undefined\n const settle = (probe: PrimaryLeaseProbe) => {\n if (settled) return\n settled = true\n clearInterval(clock)\n resolve(probe)\n }\n const close = () => {\n try {\n database?.close()\n } catch {\n // Already closed.\n }\n }\n // Only a lock can hold a read-only request this long; the connection is\n // closed when the request finally lands.\n const tickMs = Math.min(LEASE_PROBE_TICK_MS, timeoutMs)\n let ticks = Math.ceil(timeoutMs / tickMs)\n const clock = setInterval(() => {\n ticks -= 1\n if (ticks <= 0) settle({ state: 'locked' })\n }, tickMs)\n\n let request: IDBOpenDBRequest\n try {\n request = factory.open(databaseName)\n } catch {\n settle({ state: 'unknown' })\n return\n }\n // The database was deleted between `databases()` and `open()`: abort the\n // creation rather than leave the SDK an empty version-1 database.\n request.onupgradeneeded = () => request.transaction?.abort()\n request.onerror = () => settle({ state: 'unknown' })\n request.onsuccess = () => {\n database = request.result\n database.onversionchange = close\n if (settled || !database.objectStoreNames.contains(OWNER_STORE)) {\n close()\n settle({ state: 'unknown' })\n return\n }\n try {\n const read = database\n .transaction(OWNER_STORE, 'readonly')\n .objectStore(OWNER_STORE)\n .get(OWNER_KEY)\n read.onsuccess = () => {\n close()\n const row = read.result as\n | { ownerId?: unknown; leaseTimestampMs?: unknown }\n | undefined\n if (\n !row ||\n typeof row.ownerId !== 'string' ||\n typeof row.leaseTimestampMs !== 'number'\n ) {\n settle({ state: 'vacant' })\n return\n }\n settle({\n state: 'leased',\n ownerId: row.ownerId,\n ageMs: now() - row.leaseTimestampMs,\n })\n }\n read.onerror = () => {\n close()\n settle({ state: 'unknown' })\n }\n } catch {\n close()\n settle({ state: 'unknown' })\n }\n }\n })\n}\n\n/**\n * How long the lease read may take before a quiet client counts as WAITING on\n * the store (AGL-4135). Shorter than {@link LEASE_PROBE_TIMEOUT_MS}, which\n * decides a wedge: this asks only whether something holds the store now. The\n * SDK's own transactions take milliseconds, so a read that waits a second has\n * waited on one, from another tab or from this client's own backlog.\n */\nexport const LEASE_PROMPT_READ_MS = 1_000\n\n/** What the shared cache says about a client that has gone quiet (AGL-4135). */\nexport type LeaseCheck =\n /**\n * The store did not answer promptly. A transaction holds it, and every call\n * this client makes is queued behind that transaction.\n */\n | { state: 'waiting' }\n /** Another tab holds a live lease and serves this client through it. */\n | { state: 'served'; ownerId: string }\n /**\n * Nothing here explains the quiet. This tab holds the lease, or the lease has\n * lapsed or is vacant, or the lease could not be read or attributed.\n */\n | { state: 'silent' }\n\n/**\n * Reads a prompt lease probe for a quiet client whose own id is `selfId`.\n * Pure. A lease is live while younger than the SDK's 5 s\n * (`MAX_PRIMARY_ELIGIBLE_AGE_MS`). Without `selfId` a live lease cannot be told\n * apart from this tab's own, so it reads as `silent`, which is what every stall\n * was read as before.\n */\nexport function leaseCheckFrom(\n probe: PrimaryLeaseProbe,\n selfId: string | undefined,\n): LeaseCheck {\n if (probe.state === 'locked') return { state: 'waiting' }\n if (\n probe.state === 'leased' &&\n selfId !== undefined &&\n probe.ownerId !== selfId &&\n probe.ageMs < PRIMARY_LEASE_MAX_AGE_MS\n ) {\n return { state: 'served', ownerId: probe.ownerId }\n }\n return { state: 'silent' }\n}\n\n/**\n * This tab's id in the multi-tab protocol: the id its `clientMetadata` row is\n * written under, and any lease it holds. Read from the SDK's client\n * (`Firestore._firestoreClient.clientId`, which is internal and set once the\n * client has started). `undefined` when it is not there. Read in production\n * (4.17.2) against the `clientMetadata` row the same tab wrote.\n */\nexport function firestoreClientId(firestore: Firestore): string | undefined {\n try {\n const client = (firestore as unknown as {\n _firestoreClient?: { clientId?: unknown }\n })._firestoreClient\n const id = client?.clientId\n return typeof id === 'string' && id.length > 0 ? id : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether a lease read taken right after a forced election, from a visible\n * online tab, shows the wedge. Anything that could be a healthy cache —\n * a fresh lease, no lease row, an unreadable one — is not evidence.\n */\nexport function wedgeEvidenceFrom(\n probe: PrimaryLeaseProbe,\n staleMs = STALE_PRIMARY_LEASE_MS,\n): WedgeEvidence | undefined {\n if (probe.state === 'locked') return { reason: 'lease-locked' }\n if (probe.state === 'leased' && probe.ageMs >= staleMs) {\n return { reason: 'lease-stale', ownerId: probe.ownerId, ageMs: probe.ageMs }\n }\n return undefined\n}\n\n/**\n * The object stored under `key`, when it parses and its `at` is within\n * `ttlMs` of `now` and not ahead of it.\n */\nfunction readStampedRecord(\n storage: Pick<Storage, 'getItem'> | undefined,\n key: string,\n now: number,\n ttlMs: number,\n): ({ at: number } & Record<string, unknown>) | undefined {\n let raw: string | null\n try {\n raw = storage?.getItem(key) ?? null\n } catch {\n return undefined\n }\n if (raw === null) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return undefined\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined\n const record = parsed as { at?: unknown } & Record<string, unknown>\n if (typeof record.at !== 'number' || !Number.isFinite(record.at)) return undefined\n if (now - record.at >= ttlMs || record.at > now) return undefined\n return record as { at: number } & Record<string, unknown>\n}\n\n/**\n * This tab's fallback, or `undefined` when there is none, it has expired, or\n * it does not parse.\n */\nexport function readMemoryCacheFallback(\n storage: Pick<Storage, 'getItem'> | undefined,\n now: number,\n ttlMs = MEMORY_CACHE_FALLBACK_TTL_MS,\n): MemoryCacheFallback | undefined {\n return readStampedRecord(storage, MEMORY_CACHE_FALLBACK_KEY, now, ttlMs) as\n | MemoryCacheFallback\n | undefined\n}\n\n/**\n * The lock a tab saw on `databaseName`, or `undefined` when there is none, it\n * names another database, it has expired, or it does not parse.\n */\nexport function readSharedCacheLock(\n storage: Pick<Storage, 'getItem'> | undefined,\n databaseName: string | undefined,\n now: number,\n ttlMs = SHARED_CACHE_LOCK_TTL_MS,\n): SharedCacheLock | undefined {\n if (databaseName === undefined) return undefined\n const record = readStampedRecord(storage, SHARED_CACHE_LOCK_KEY, now, ttlMs)\n if (record?.reason !== 'lease-locked' || record.databaseName !== databaseName) {\n return undefined\n }\n return record as unknown as SharedCacheLock\n}\n\nconst browserSessionStorage = (): Storage | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.sessionStorage\n } catch {\n // Site data blocked: reading `window.sessionStorage` throws.\n return undefined\n }\n}\n\nconst browserLocalStorage = (): Storage | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.localStorage\n } catch {\n // Site data blocked: reading `window.localStorage` throws.\n return undefined\n }\n}\n\nconst browserIndexedDb = (): IDBFactory | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.indexedDB\n } catch {\n return undefined\n }\n}\n\n/** Whether this browser tab is running on its memory-cache fallback. */\nexport function memoryCacheFallbackActive(now = Date.now()): boolean {\n return readMemoryCacheFallback(browserSessionStorage(), now) !== undefined\n}\n\n/**\n * Whether another tab has just seen the store of `databaseName` locked, so\n * this tab should start on the memory cache rather than wait to find out.\n */\nexport function sharedCacheLockActive(\n databaseName: string | undefined,\n now = Date.now(),\n): boolean {\n return readSharedCacheLock(browserLocalStorage(), databaseName, now) !== undefined\n}\n\n/**\n * Records, for the tabs that open next, that the store of `databaseName` is\n * locked now. Never throws: without the record, the next tab finds the lock\n * itself, as it always has.\n */\nexport function recordSharedCacheLock(\n databaseName: string,\n {\n storage = browserLocalStorage(),\n now = Date.now,\n }: { storage?: Pick<Storage, 'setItem'>; now?: () => number } = {},\n): void {\n const record: SharedCacheLock = { reason: 'lease-locked', databaseName, at: now() }\n try {\n storage?.setItem(SHARED_CACHE_LOCK_KEY, JSON.stringify(record))\n } catch {\n // Full or blocked.\n }\n}\n\n/**\n * Run once by a tab that started on the memory cache: reads the lease of\n * `databaseName` again and keeps another tab's lock record only while the\n * store is still locked. Never creates a record and never rejects.\n */\nexport async function confirmSharedCacheLock(\n databaseName: string,\n {\n probe = () => probePrimaryLease(browserIndexedDb(), databaseName),\n storage = browserLocalStorage(),\n now = Date.now,\n }: {\n probe?: () => Promise<PrimaryLeaseProbe>\n storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>\n now?: () => number\n } = {},\n): Promise<SharedCacheLockCheck> {\n if (!storage) return 'absent'\n const seen = readSharedCacheLock(storage, databaseName, now())\n if (!seen) return 'absent'\n try {\n if ((await probe()).state === 'locked') {\n recordSharedCacheLock(databaseName, { storage, now })\n return 'still-locked'\n }\n const current = readSharedCacheLock(storage, databaseName, now())\n // Another tab saw the lock again while this read ran; its record is\n // newer than this read, so it stands.\n if (current && current.at !== seen.at) return 'still-locked'\n if (current) storage.removeItem(SHARED_CACHE_LOCK_KEY)\n return 'cleared'\n } catch {\n return 'failed'\n }\n}\n\nexport interface WedgeEscalationDeps {\n /** Reads the lease. */\n probe: () => Promise<PrimaryLeaseProbe>\n /** Moves this tab off the shared cache. */\n fallBack: (evidence: WedgeEvidence) => void\n /** Whether this tab is already on the fallback — it then never escalates. */\n isFallbackActive?: () => boolean\n isOnline?: () => boolean\n isVisible?: () => boolean\n /** Waits `ms`; the settle before the lease read. */\n wait?: (ms: number) => Promise<void>\n settleMs?: number\n}\n\nconst browserOnline = () =>\n typeof navigator === 'undefined' || navigator.onLine !== false\n\nconst documentVisible = () =>\n typeof document === 'undefined' || document.visibilityState !== 'hidden'\n\n/**\n * The step `createStallRecovery` runs after its network cycle for a\n * multi-tab client. Resolves `true` when it has moved the tab to the fallback.\n * Never rejects.\n */\nexport function createWedgeEscalation(\n deps: WedgeEscalationDeps,\n): () => Promise<boolean> {\n const {\n probe,\n fallBack,\n isFallbackActive = () => memoryCacheFallbackActive(),\n isOnline = browserOnline,\n isVisible = documentVisible,\n wait = (ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n settleMs = LEASE_SETTLE_MS,\n } = deps\n return async () => {\n try {\n if (isFallbackActive()) return false\n await wait(settleMs)\n // Both guards again: the reader may have gone, or the network with it.\n if (!isOnline() || !isVisible()) return false\n const evidence = wedgeEvidenceFrom(await probe())\n if (!evidence) return false\n fallBack(evidence)\n return true\n } catch {\n return false\n }\n }\n}\n\n/**\n * A TAB THAT IS STILL BOOTING DOES NOT WAIT 37 SECONDS TO FIND THE LOCK\n * (AGL-4201).\n *\n * The rescue above is tuned for a tab that already has a page on it. It runs\n * only once a reader has stalled (`FIRESTORE_STALL_MS`, 8 s), reads the lease\n * promptly (1 s), settles (3 s) and then gives the lock {@link WEDGE_LOCK_MS}\n * (20 s) before it believes it, because a tab that is merely busy holds the\n * store for about 15 s and reloading one loses what was typed into it\n * (AGL-4135). Plus the reload, that is about 37 s, and it is exactly what a\n * tab opened while another tab held the store sat through on the site gate's\n * spinner: measured in production on 2026-11-06, two reloads in three.\n *\n * A tab that is still booting has none of what that budget protects. Its\n * client has had no answer from the server, so nothing it shows came from the\n * server and nothing typed into it has been read back. And it is waiting on the\n * same lock either way: its persistence cannot start while another tab's\n * transaction holds every store (the booting tab had no `clientMetadata` row\n * 17 s in). So from about {@link BOOT_WEDGE_CHECK_DELAY_MS} after the client\n * is created, a visible online tab whose client has not heard from the server\n * reads the lease every {@link BOOT_WEDGE_RECHECK_MS} for up to\n * {@link BOOT_WEDGE_WINDOW_MS}, and a store that stays locked for\n * {@link BOOT_WEDGE_LOCK_MS} moves it to the memory cache straight away,\n * sharing the lock with the tabs that open next (AGL-4090).\n *\n * - **Only a lock.** A lapsed or stale lease at boot is the normal state after\n * the last tab went quiet, and a freshly started tab wins it at its first\n * election (AGL-3373). Only a store nobody can read is evidence here.\n * - **Only before the first server answer**, checked before the read and again\n * after it. A tab the server has answered is working and is left to the\n * stall watch, whose budget is the one that protects a page in use.\n * - **Only when someone is looking.** A tab opened in the background runs the\n * check when it is first shown, which is when its spinner starts costing\n * anyone anything.\n * - **Until answered, then never again.** The reads stop at the first server\n * answer or at the end of the window, and never run on a tab already on the\n * fallback.\n *\n * A false verdict costs a reload of a page with nothing on it, onto the memory\n * cache, which every lock verdict already costs today, 30 s later.\n */\nexport const BOOT_WEDGE_CHECK_DELAY_MS = 2_000\n\n/**\n * How long the boot check's lease read may wait before the store counts as\n * locked. The SDK's own transactions take milliseconds; the read answered in\n * 1-5 ms on the same production cache once the lock had lifted.\n */\nexport const BOOT_WEDGE_LOCK_MS = 3_000\n\n/**\n * How often a booting tab reads the lease again while the server has not\n * answered it (AGL-4201). The lock is not there from the start: measured in\n * production on v1.15.1, a booting tab's first read at 2 s found the store\n * free, another tab locked it a few seconds later, and the tab sat 35 s on the\n * old path. One read was a coin toss; reading until the tab is answered is not.\n */\nexport const BOOT_WEDGE_RECHECK_MS = 2_000\n\n/**\n * How long, from when the tab is first seen, a booting tab keeps reading. Past\n * it, a tab still unanswered is left to the stall watch, which has budgets of\n * its own for a page that is in use.\n */\nexport const BOOT_WEDGE_WINDOW_MS = 30_000\n\n/** What the boot check did (AGL-4201). */\nexport type BootWedgeOutcome =\n /** The store was locked: this tab is moving to the memory cache. */\n | 'fell-back'\n /** The server answered this client first: it is booting fine. */\n | 'answered'\n /** The store answered: nothing holds it. */\n | 'clear'\n /** The browser reports no network. */\n | 'offline'\n /** This tab is already on the fallback. */\n | 'fallback-active'\n /** The client does not run the durable multi-tab cache. */\n | 'not-multi-tab'\n /** Something unexpected; the stall watch stays in charge. */\n | 'error'\n\nexport interface BootWedgeCheckDeps {\n /** Reads the lease, bounded by {@link BOOT_WEDGE_LOCK_MS}. */\n probe: () => Promise<PrimaryLeaseProbe>\n /** Moves this tab off the shared cache. */\n fallBack: (evidence: WedgeEvidence) => void\n /** Whether the server has confirmed anything for this client yet. */\n hasServerAnswered: () => boolean\n isFallbackActive?: () => boolean\n isOnline?: () => boolean\n /** Resolves once the document is visible, at once when it already is. */\n whenVisible?: () => Promise<void>\n wait?: (ms: number) => Promise<void>\n delayMs?: number\n recheckMs?: number\n windowMs?: number\n now?: () => number\n}\n\nconst whenDocumentVisible = (): Promise<void> =>\n new Promise((resolve) => {\n if (typeof document === 'undefined' || document.visibilityState !== 'hidden') {\n resolve()\n return\n }\n const onChange = () => {\n if (document.visibilityState === 'hidden') return\n document.removeEventListener('visibilitychange', onChange)\n resolve()\n }\n document.addEventListener('visibilitychange', onChange)\n })\n\n/** The boot check, with its browser parts injected. Never rejects. */\nexport async function runBootWedgeCheck(\n deps: BootWedgeCheckDeps,\n): Promise<BootWedgeOutcome> {\n const {\n probe,\n fallBack,\n hasServerAnswered,\n isFallbackActive = () => memoryCacheFallbackActive(),\n isOnline = browserOnline,\n whenVisible = whenDocumentVisible,\n wait = (ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n delayMs = BOOT_WEDGE_CHECK_DELAY_MS,\n recheckMs = BOOT_WEDGE_RECHECK_MS,\n windowMs = BOOT_WEDGE_WINDOW_MS,\n now = Date.now,\n } = deps\n try {\n if (isFallbackActive()) return 'fallback-active'\n await wait(delayMs)\n await whenVisible()\n const until = now() + windowMs\n for (;;) {\n if (hasServerAnswered()) return 'answered'\n if (!isOnline()) return 'offline'\n if (isFallbackActive()) return 'fallback-active'\n const read = await probe()\n if (read.state === 'locked') {\n // The read took up to its whole budget; the client may have come through.\n if (hasServerAnswered()) return 'answered'\n if (!isOnline()) return 'offline'\n if (isFallbackActive()) return 'fallback-active'\n fallBack({ reason: 'lease-locked' })\n return 'fell-back'\n }\n // Free now is not free for good: another tab can take the store a\n // moment later, and this tab is still waiting on the server.\n if (now() >= until) return 'clear'\n await wait(recheckMs)\n await whenVisible()\n }\n } catch {\n return 'error'\n }\n}\n\n/**\n * Records the fallback for this tab and reloads it onto the memory cache.\n * When the record cannot be written it does not reload: without it, the\n * reloaded tab would open the same locked database and hang again.\n *\n * A lock is also recorded for the tabs that open next (AGL-4090), first and\n * whatever happens to this tab's own record: they would hang on it too.\n */\nexport function fallBackToMemoryCache(\n evidence: WedgeEvidence,\n {\n storage = browserSessionStorage(),\n sharedStorage = browserLocalStorage(),\n databaseName,\n reload = () => window.location.reload(),\n now = Date.now,\n }: {\n storage?: Pick<Storage, 'setItem'>\n /** Where the tabs that open next look for a lock this tab saw. */\n sharedStorage?: Pick<Storage, 'setItem'>\n /** The locked database. Without it, nothing is shared. */\n databaseName?: string\n reload?: () => void\n now?: () => number\n } = {},\n): void {\n if (evidence.reason === 'lease-locked' && databaseName !== undefined) {\n recordSharedCacheLock(databaseName, { storage: sharedStorage, now })\n }\n if (!storage) return\n const record: MemoryCacheFallback = { ...evidence, at: now() }\n try {\n storage.setItem(MEMORY_CACHE_FALLBACK_KEY, JSON.stringify(record))\n } catch {\n return\n }\n console.warn(\n evidence.reason === 'queue-failed'\n ? '[firestore] The multi-tab cache failed this tab\\'s Firestore client; reloading this tab on the memory cache (AGL-4156).'\n : '[firestore] The multi-tab cache is locked by another tab; reloading this tab on the memory cache (AGL-3428).',\n record,\n )\n reload()\n}\n\n/**\n * A FIRESTORE CLIENT WHOSE QUEUE HAS FAILED, AND THE WAY OUT (AGL-4156).\n *\n * The SDK runs every operation on one AsyncQueue. When an operation rejects\n * with an error the queue does not retry, it keeps that error and refuses\n * every later operation with the assertion `Unexpected state (ID: b815)`,\n * whose `CONTEXT` names the first error. Nothing restarts it: the\n * client is dead until the page reloads, so every read and listener in the tab\n * fails, and pages stop loading.\n *\n * The durable cache is what kills it in production. On 2026-11-04 (v1.9.0,\n * `@firebase/firestore` 4.18.0) a new Firefox sign-up's console lost its client\n * on three page loads in 25 minutes. Each time, an IndexedDB request in the\n * SDK's transaction threw \"Attempt to get a record from database without an\n * in-progress transaction\". The SDK retries a failed transaction three times,\n * then hands the raw `DOMException` to the queue, which counts it as fatal\n * rather than as an `IndexedDbTransactionError` to back off from. The earlier\n * cases ended the same way: a full `localStorage` (AGL-2845) and a null target\n * from the IndexedDB target cache (`isCorePipeline`, 2026-10-14, Chrome).\n *\n * So the first b815 of a durable multi-tab client moves the tab onto the\n * memory cache, which does not use IndexedDB, through the same per-tab\n * {@link fallBackToMemoryCache} as the wedge. Nothing that could be saved is\n * lost: the dead queue had already stopped every write in the tab. A tab already\n * on the fallback runs the memory cache, which is never watched, so a b815 there\n * cannot loop. No lock is shared, because another tab's client is not dead.\n */\nconst QUEUE_FAILURE = /INTERNAL ASSERTION FAILED: Unexpected state \\(ID: b815\\)/\n\n/** Whether `thrown` (an error, an event's message, a rejection reason) is the SDK's failed-queue assertion. */\nexport function isFirestoreQueueFailure(thrown: unknown): boolean {\n try {\n const message =\n typeof thrown === 'string'\n ? thrown\n : thrown && typeof thrown === 'object' && 'message' in thrown\n ? String((thrown as { message: unknown }).message)\n : ''\n return QUEUE_FAILURE.test(message)\n } catch {\n return false\n }\n}\n\n/**\n * Watches `target` for the failed-queue assertion, as an uncaught error or an\n * unhandled rejection, and calls `fallBack` once, the first time it appears.\n * Returns the function that stops watching.\n */\nexport function watchFirestoreQueueFailure(\n fallBack: (evidence: WedgeEvidence) => void,\n {\n target = typeof window === 'undefined' ? undefined : window,\n isFallbackActive = () => memoryCacheFallbackActive(),\n }: {\n target?: Pick<Window, 'addEventListener' | 'removeEventListener'>\n isFallbackActive?: () => boolean\n } = {},\n): () => void {\n if (!target) return () => undefined\n let fired = false\n const onError = (event: Event) => {\n const { error, message } = event as ErrorEvent\n check(isFirestoreQueueFailure(error) || isFirestoreQueueFailure(message))\n }\n const onRejection = (event: Event) => {\n check(isFirestoreQueueFailure((event as PromiseRejectionEvent).reason))\n }\n const stop = () => {\n target.removeEventListener('error', onError)\n target.removeEventListener('unhandledrejection', onRejection)\n }\n const check = (failed: boolean) => {\n if (!failed || fired) return\n fired = true\n stop()\n try {\n if (isFallbackActive()) return\n fallBack({ reason: 'queue-failed' })\n } catch {\n // Watching never breaks the page.\n }\n }\n target.addEventListener('error', onError)\n target.addEventListener('unhandledrejection', onRejection)\n return stop\n}\n\n/** The IndexedDB database of each client running the durable multi-tab cache. */\nconst multiTabDatabases = new WeakMap<Firestore, string>()\n\n/**\n * Registers `firestore` as running the durable multi-tab cache under\n * `databaseName` (`<persistence prefix>main`). Only a registered client ever\n * escalates past the network cycle, and only its page is watched for a failed\n * queue ({@link watchFirestoreQueueFailure}).\n */\nexport function markMultiTabFirestore(firestore: Firestore, databaseName: string): void {\n if (firestore && typeof firestore === 'object') {\n if (!multiTabDatabases.has(firestore)) {\n watchFirestoreQueueFailure((evidence) =>\n fallBackToMemoryCache(evidence, { databaseName }),\n )\n }\n multiTabDatabases.set(firestore, databaseName)\n }\n}\n\n/**\n * The browser escalation for `firestore`, or `undefined` when it does not run\n * the durable multi-tab cache (the emulator configuration, an ephemeral\n * origin, a tab already on the fallback).\n */\nexport function browserWedgeEscalationFor(\n firestore: Firestore,\n): (() => Promise<boolean>) | undefined {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return undefined\n return createWedgeEscalation({\n probe: () =>\n probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: WEDGE_LOCK_MS,\n }),\n fallBack: (evidence) => fallBackToMemoryCache(evidence, { databaseName }),\n })\n}\n\n/**\n * The lease check `createStallRecovery` runs before a network cycle, or\n * `undefined` when `firestore` does not run the durable multi-tab cache: a\n * client with a cache of its own has no other tab to wait on. Never rejects.\n */\nexport function browserLeaseCheckFor(\n firestore: Firestore,\n): (() => Promise<LeaseCheck>) | undefined {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return undefined\n return async () => {\n try {\n const probe = await probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: LEASE_PROMPT_READ_MS,\n })\n return leaseCheckFrom(probe, firestoreClientId(firestore))\n } catch {\n return { state: 'silent' }\n }\n }\n}\n\n/**\n * Runs the boot check (AGL-4201) for `firestore`, which\n * {@link markMultiTabFirestore} has registered. Call it right after\n * registering. `hasServerAnswered` is the stall watch's record of server\n * answers (`firestoreHasServerAnswered`), passed in so this module does not\n * import the one that imports it. Fire and forget: it never rejects.\n */\nexport function startBootWedgeCheck(\n firestore: Firestore,\n hasServerAnswered: () => boolean,\n): Promise<BootWedgeOutcome> {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return Promise.resolve('not-multi-tab')\n return runBootWedgeCheck({\n probe: () =>\n probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: BOOT_WEDGE_LOCK_MS,\n }),\n fallBack: (evidence) => fallBackToMemoryCache(evidence, { databaseName }),\n hasServerAnswered,\n })\n}\n"],"names":["PRIMARY_LEASE_MAX_AGE_MS","MEMORY_CACHE_FALLBACK_KEY","MEMORY_CACHE_FALLBACK_TTL_MS","SHARED_CACHE_LOCK_KEY","SHARED_CACHE_LOCK_TTL_MS","STALE_PRIMARY_LEASE_MS","LEASE_PROBE_TIMEOUT_MS","WEDGE_LOCK_MS","LEASE_PROBE_TICK_MS","LEASE_SETTLE_MS","OWNER_STORE","OWNER_KEY","probePrimaryLease","factory","databaseName","timeoutMs","now","Date","databases","state","some","database","name","Promise","resolve","settled","settle","probe","clearInterval","clock","close","tickMs","Math","min","ticks","ceil","setInterval","request","open","onupgradeneeded","transaction","abort","onerror","onsuccess","result","onversionchange","objectStoreNames","contains","read","objectStore","get","row","ownerId","leaseTimestampMs","ageMs","LEASE_PROMPT_READ_MS","leaseCheckFrom","selfId","undefined","firestoreClientId","firestore","client","_firestoreClient","id","clientId","length","wedgeEvidenceFrom","staleMs","reason","readStampedRecord","storage","key","ttlMs","raw","getItem","parsed","JSON","parse","record","at","Number","isFinite","readMemoryCacheFallback","readSharedCacheLock","browserSessionStorage","window","sessionStorage","browserLocalStorage","localStorage","browserIndexedDb","indexedDB","memoryCacheFallbackActive","sharedCacheLockActive","recordSharedCacheLock","setItem","stringify","confirmSharedCacheLock","seen","current","removeItem","browserOnline","navigator","onLine","documentVisible","document","visibilityState","createWedgeEscalation","deps","fallBack","isFallbackActive","isOnline","isVisible","wait","ms","setTimeout","settleMs","evidence","BOOT_WEDGE_CHECK_DELAY_MS","BOOT_WEDGE_LOCK_MS","BOOT_WEDGE_RECHECK_MS","BOOT_WEDGE_WINDOW_MS","whenDocumentVisible","onChange","removeEventListener","addEventListener","runBootWedgeCheck","hasServerAnswered","whenVisible","delayMs","recheckMs","windowMs","until","fallBackToMemoryCache","sharedStorage","reload","location","console","warn","QUEUE_FAILURE","isFirestoreQueueFailure","thrown","message","String","test","watchFirestoreQueueFailure","target","fired","onError","event","error","check","onRejection","stop","failed","multiTabDatabases","WeakMap","markMultiTabFirestore","has","set","browserWedgeEscalationFor","browserLeaseCheckFor","startBootWedgeCheck"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,SAASA,wBAAwB,QAAQ,6BAAyB;AAElE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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